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