]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/search.rs
6a3cc14f08e7fec21db1fa263e355199b2ccde8f
[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(name, domain, kind, context.client()).await?
49       }
50       // local actor, read from database and return
51       else {
52         return find_local_actor_by_name(name, kind, context.pool()).await;
53       }
54     }
55   };
56
57   let request_counter = &mut 0;
58   ObjectId::new(query_url)
59     .dereference(context, request_counter)
60     .await
61 }
62
63 async fn find_local_actor_by_name(
64   name: &str,
65   kind: WebfingerType,
66   pool: &DbPool,
67 ) -> Result<SearchableObjects, LemmyError> {
68   let name: String = name.into();
69   Ok(match kind {
70     WebfingerType::Group => SearchableObjects::Community(
71       blocking(pool, move |conn| Community::read_from_name(conn, &name)).await??,
72     ),
73     WebfingerType::Person => SearchableObjects::Person(
74       blocking(pool, move |conn| Person::find_by_name(conn, &name)).await??,
75     ),
76   })
77 }
78
79 /// The types of ActivityPub objects that can be fetched directly by searching for their ID.
80 #[derive(Debug)]
81 pub enum SearchableObjects {
82   Person(Person),
83   Community(Community),
84   Post(Post),
85   Comment(Comment),
86 }
87
88 #[derive(Deserialize)]
89 #[serde(untagged)]
90 pub enum SearchableApubTypes {
91   Group(Group),
92   Person(ApubPerson),
93   Page(Page),
94   Note(Note),
95 }
96
97 impl ApubObject for SearchableObjects {
98   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
99     match self {
100       SearchableObjects::Person(p) => p.last_refreshed_at(),
101       SearchableObjects::Community(c) => c.last_refreshed_at(),
102       SearchableObjects::Post(p) => p.last_refreshed_at(),
103       SearchableObjects::Comment(c) => c.last_refreshed_at(),
104     }
105   }
106
107   // TODO: this is inefficient, because if the object is not in local db, it will run 4 db queries
108   //       before finally returning an error. it would be nice if we could check all 4 tables in
109   //       a single query.
110   //       we could skip this and always return an error, but then it would not be able to mark
111   //       objects as deleted that were deleted by remote server.
112   fn read_from_apub_id(conn: &PgConnection, object_id: &DbUrl) -> Result<Self, Error> {
113     let c = Community::read_from_apub_id(conn, object_id);
114     if let Ok(c) = c {
115       return Ok(SearchableObjects::Community(c));
116     }
117     let p = Person::read_from_apub_id(conn, object_id);
118     if let Ok(p) = p {
119       return Ok(SearchableObjects::Person(p));
120     }
121     let p = Post::read_from_apub_id(conn, object_id);
122     if let Ok(p) = p {
123       return Ok(SearchableObjects::Post(p));
124     }
125     let c = Comment::read_from_apub_id(conn, object_id);
126     Ok(SearchableObjects::Comment(c?))
127   }
128 }
129
130 #[async_trait::async_trait(?Send)]
131 impl FromApub for SearchableObjects {
132   type ApubType = SearchableApubTypes;
133
134   async fn from_apub(
135     apub: &Self::ApubType,
136     context: &LemmyContext,
137     ed: &Url,
138     rc: &mut i32,
139   ) -> Result<Self, LemmyError> {
140     use SearchableApubTypes as SAT;
141     use SearchableObjects as SO;
142     Ok(match apub {
143       SAT::Group(g) => SO::Community(Community::from_apub(g, context, ed, rc).await?),
144       SAT::Person(p) => SO::Person(Person::from_apub(p, context, ed, rc).await?),
145       SAT::Page(p) => SO::Post(Post::from_apub(p, context, ed, rc).await?),
146       SAT::Note(n) => SO::Comment(Comment::from_apub(n, context, ed, rc).await?),
147     })
148   }
149 }
150
151 #[async_trait::async_trait(?Send)]
152 impl DeletableApubObject for SearchableObjects {
153   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
154     match self {
155       SearchableObjects::Person(p) => p.delete(context).await,
156       SearchableObjects::Community(c) => c.delete(context).await,
157       SearchableObjects::Post(p) => p.delete(context).await,
158       SearchableObjects::Comment(c) => c.delete(context).await,
159     }
160   }
161 }