]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/search.rs
f8784a5ee09c798456835923bb278c79ae100534
[lemmy.git] / crates / apub / src / fetcher / search.rs
1 use crate::{
2   fetcher::webfinger::webfinger_resolve,
3   objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson, post::ApubPost},
4   protocol::objects::{group::Group, note::Note, page::Page, person::Person},
5   EndpointType,
6 };
7 use anyhow::anyhow;
8 use chrono::NaiveDateTime;
9 use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject};
10 use lemmy_utils::LemmyError;
11 use lemmy_websocket::LemmyContext;
12 use serde::Deserialize;
13 use url::Url;
14
15 /// Attempt to parse the query as URL, and fetch an ActivityPub object from it.
16 ///
17 /// Some working examples for use with the `docker/federation/` setup:
18 /// http://lemmy_alpha:8541/c/main, or !main@lemmy_alpha:8541
19 /// http://lemmy_beta:8551/u/lemmy_alpha, or @lemmy_beta@lemmy_beta:8551
20 /// http://lemmy_gamma:8561/post/3
21 /// http://lemmy_delta:8571/comment/2
22 pub async fn search_by_apub_id(
23   query: &str,
24   context: &LemmyContext,
25 ) -> Result<SearchableObjects, LemmyError> {
26   let request_counter = &mut 0;
27   match Url::parse(query) {
28     Ok(url) => {
29       ObjectId::new(url)
30         .dereference(context, request_counter)
31         .await
32     }
33     Err(_) => {
34       let (kind, identifier) = query.split_at(1);
35       match kind {
36         "@" => {
37           let id = webfinger_resolve::<ApubPerson>(
38             identifier,
39             EndpointType::Person,
40             context,
41             request_counter,
42           )
43           .await?;
44           Ok(SearchableObjects::Person(
45             ObjectId::new(id)
46               .dereference(context, request_counter)
47               .await?,
48           ))
49         }
50         "!" => {
51           let id = webfinger_resolve::<ApubCommunity>(
52             identifier,
53             EndpointType::Community,
54             context,
55             request_counter,
56           )
57           .await?;
58           Ok(SearchableObjects::Community(
59             ObjectId::new(id)
60               .dereference(context, request_counter)
61               .await?,
62           ))
63         }
64         _ => Err(anyhow!("invalid query").into()),
65       }
66     }
67   }
68 }
69
70 /// The types of ActivityPub objects that can be fetched directly by searching for their ID.
71 #[derive(Debug)]
72 pub enum SearchableObjects {
73   Person(ApubPerson),
74   Community(ApubCommunity),
75   Post(ApubPost),
76   Comment(ApubComment),
77 }
78
79 #[derive(Deserialize)]
80 #[serde(untagged)]
81 pub enum SearchableApubTypes {
82   Group(Group),
83   Person(Person),
84   Page(Page),
85   Note(Note),
86 }
87
88 #[async_trait::async_trait(?Send)]
89 impl ApubObject for SearchableObjects {
90   type DataType = LemmyContext;
91   type ApubType = SearchableApubTypes;
92   type TombstoneType = ();
93
94   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
95     match self {
96       SearchableObjects::Person(p) => p.last_refreshed_at(),
97       SearchableObjects::Community(c) => c.last_refreshed_at(),
98       SearchableObjects::Post(p) => p.last_refreshed_at(),
99       SearchableObjects::Comment(c) => c.last_refreshed_at(),
100     }
101   }
102
103   // TODO: this is inefficient, because if the object is not in local db, it will run 4 db queries
104   //       before finally returning an error. it would be nice if we could check all 4 tables in
105   //       a single query.
106   //       we could skip this and always return an error, but then it would always fetch objects
107   //       over http, and not be able to mark objects as deleted that were deleted by remote server.
108   async fn read_from_apub_id(
109     object_id: Url,
110     context: &LemmyContext,
111   ) -> Result<Option<Self>, LemmyError> {
112     let c = ApubCommunity::read_from_apub_id(object_id.clone(), context).await?;
113     if let Some(c) = c {
114       return Ok(Some(SearchableObjects::Community(c)));
115     }
116     let p = ApubPerson::read_from_apub_id(object_id.clone(), context).await?;
117     if let Some(p) = p {
118       return Ok(Some(SearchableObjects::Person(p)));
119     }
120     let p = ApubPost::read_from_apub_id(object_id.clone(), context).await?;
121     if let Some(p) = p {
122       return Ok(Some(SearchableObjects::Post(p)));
123     }
124     let c = ApubComment::read_from_apub_id(object_id, context).await?;
125     if let Some(c) = c {
126       return Ok(Some(SearchableObjects::Comment(c)));
127     }
128     Ok(None)
129   }
130
131   async fn delete(self, data: &Self::DataType) -> Result<(), LemmyError> {
132     match self {
133       SearchableObjects::Person(p) => p.delete(data).await,
134       SearchableObjects::Community(c) => c.delete(data).await,
135       SearchableObjects::Post(p) => p.delete(data).await,
136       SearchableObjects::Comment(c) => c.delete(data).await,
137     }
138   }
139
140   async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
141     unimplemented!()
142   }
143
144   fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
145     unimplemented!()
146   }
147
148   async fn verify(
149     apub: &Self::ApubType,
150     expected_domain: &Url,
151     data: &Self::DataType,
152     request_counter: &mut i32,
153   ) -> Result<(), LemmyError> {
154     match apub {
155       SearchableApubTypes::Group(a) => {
156         ApubCommunity::verify(a, expected_domain, data, request_counter).await
157       }
158       SearchableApubTypes::Person(a) => {
159         ApubPerson::verify(a, expected_domain, data, request_counter).await
160       }
161       SearchableApubTypes::Page(a) => {
162         ApubPost::verify(a, expected_domain, data, request_counter).await
163       }
164       SearchableApubTypes::Note(a) => {
165         ApubComment::verify(a, expected_domain, data, request_counter).await
166       }
167     }
168   }
169
170   async fn from_apub(
171     apub: Self::ApubType,
172     context: &LemmyContext,
173     rc: &mut i32,
174   ) -> Result<Self, LemmyError> {
175     use SearchableApubTypes as SAT;
176     use SearchableObjects as SO;
177     Ok(match apub {
178       SAT::Group(g) => SO::Community(ApubCommunity::from_apub(g, context, rc).await?),
179       SAT::Person(p) => SO::Person(ApubPerson::from_apub(p, context, rc).await?),
180       SAT::Page(p) => SO::Post(ApubPost::from_apub(p, context, rc).await?),
181       SAT::Note(n) => SO::Comment(ApubComment::from_apub(n, context, rc).await?),
182     })
183   }
184 }