]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/search.rs
Consolidate reqwest clients, use reqwest-middleware for tracing
[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 chrono::NaiveDateTime;
8 use lemmy_apub_lib::{object_id::ObjectId, traits::ApubObject};
9 use lemmy_utils::LemmyError;
10 use lemmy_websocket::LemmyContext;
11 use serde::Deserialize;
12 use url::Url;
13
14 /// Attempt to parse the query as URL, and fetch an ActivityPub object from it.
15 ///
16 /// Some working examples for use with the `docker/federation/` setup:
17 /// http://lemmy_alpha:8541/c/main, or !main@lemmy_alpha:8541
18 /// http://lemmy_beta:8551/u/lemmy_alpha, or @lemmy_beta@lemmy_beta:8551
19 /// http://lemmy_gamma:8561/post/3
20 /// http://lemmy_delta:8571/comment/2
21 #[tracing::instrument(skip_all)]
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, context.client(), 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, context.client(), 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, context.client(), request_counter)
61               .await?,
62           ))
63         }
64         _ => Err(LemmyError::from_message("invalid query")),
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   #[tracing::instrument(skip_all)]
109   async fn read_from_apub_id(
110     object_id: Url,
111     context: &LemmyContext,
112   ) -> Result<Option<Self>, LemmyError> {
113     let c = ApubCommunity::read_from_apub_id(object_id.clone(), context).await?;
114     if let Some(c) = c {
115       return Ok(Some(SearchableObjects::Community(c)));
116     }
117     let p = ApubPerson::read_from_apub_id(object_id.clone(), context).await?;
118     if let Some(p) = p {
119       return Ok(Some(SearchableObjects::Person(p)));
120     }
121     let p = ApubPost::read_from_apub_id(object_id.clone(), context).await?;
122     if let Some(p) = p {
123       return Ok(Some(SearchableObjects::Post(p)));
124     }
125     let c = ApubComment::read_from_apub_id(object_id, context).await?;
126     if let Some(c) = c {
127       return Ok(Some(SearchableObjects::Comment(c)));
128     }
129     Ok(None)
130   }
131
132   #[tracing::instrument(skip_all)]
133   async fn delete(self, data: &Self::DataType) -> Result<(), LemmyError> {
134     match self {
135       SearchableObjects::Person(p) => p.delete(data).await,
136       SearchableObjects::Community(c) => c.delete(data).await,
137       SearchableObjects::Post(p) => p.delete(data).await,
138       SearchableObjects::Comment(c) => c.delete(data).await,
139     }
140   }
141
142   async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
143     unimplemented!()
144   }
145
146   fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
147     unimplemented!()
148   }
149
150   #[tracing::instrument(skip_all)]
151   async fn verify(
152     apub: &Self::ApubType,
153     expected_domain: &Url,
154     data: &Self::DataType,
155     request_counter: &mut i32,
156   ) -> Result<(), LemmyError> {
157     match apub {
158       SearchableApubTypes::Group(a) => {
159         ApubCommunity::verify(a, expected_domain, data, request_counter).await
160       }
161       SearchableApubTypes::Person(a) => {
162         ApubPerson::verify(a, expected_domain, data, request_counter).await
163       }
164       SearchableApubTypes::Page(a) => {
165         ApubPost::verify(a, expected_domain, data, request_counter).await
166       }
167       SearchableApubTypes::Note(a) => {
168         ApubComment::verify(a, expected_domain, data, request_counter).await
169       }
170     }
171   }
172
173   #[tracing::instrument(skip_all)]
174   async fn from_apub(
175     apub: Self::ApubType,
176     context: &LemmyContext,
177     rc: &mut i32,
178   ) -> Result<Self, LemmyError> {
179     use SearchableApubTypes as SAT;
180     use SearchableObjects as SO;
181     Ok(match apub {
182       SAT::Group(g) => SO::Community(ApubCommunity::from_apub(g, context, rc).await?),
183       SAT::Person(p) => SO::Person(ApubPerson::from_apub(p, context, rc).await?),
184       SAT::Page(p) => SO::Post(ApubPost::from_apub(p, context, rc).await?),
185       SAT::Note(n) => SO::Comment(ApubComment::from_apub(n, context, rc).await?),
186     })
187   }
188 }