]> Untitled Git - lemmy.git/blob - crates/apub/src/fetcher/search.rs
add enable_federated_downvotes site option
[lemmy.git] / crates / apub / src / fetcher / search.rs
1 use crate::{
2   objects::{comment::ApubComment, community::ApubCommunity, person::ApubPerson, post::ApubPost},
3   protocol::objects::{group::Group, note::Note, page::Page, person::Person},
4 };
5 use activitypub_federation::{
6   config::Data,
7   fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
8   traits::Object,
9 };
10 use chrono::NaiveDateTime;
11 use lemmy_api_common::context::LemmyContext;
12 use lemmy_utils::error::{LemmyError, LemmyErrorType};
13 use serde::Deserialize;
14 use url::Url;
15
16 /// Converts search query to object id. The query can either be an URL, which will be treated as
17 /// ObjectId directly, or a webfinger identifier (@user@example.com or !community@example.com)
18 /// which gets resolved to an URL.
19 #[tracing::instrument(skip_all)]
20 pub(crate) async fn search_query_to_object_id(
21   query: &str,
22   context: &Data<LemmyContext>,
23 ) -> Result<SearchableObjects, LemmyError> {
24   Ok(match Url::parse(query) {
25     Ok(url) => {
26       // its already an url, just go with it
27       ObjectId::from(url).dereference(context).await?
28     }
29     Err(_) => {
30       // not an url, try to resolve via webfinger
31       let mut chars = query.chars();
32       let kind = chars.next();
33       let identifier = chars.as_str();
34       match kind {
35         Some('@') => SearchableObjects::Person(
36           webfinger_resolve_actor::<LemmyContext, ApubPerson>(identifier, context).await?,
37         ),
38         Some('!') => SearchableObjects::Community(
39           webfinger_resolve_actor::<LemmyContext, ApubCommunity>(identifier, context).await?,
40         ),
41         _ => return Err(LemmyErrorType::InvalidQuery)?,
42       }
43     }
44   })
45 }
46
47 /// Converts a search query to an object id.  The query MUST bbe a URL which will bbe treated
48 /// as the ObjectId directly.  If the query is a webfinger identifier (@user@example.com or
49 /// !community@example.com) this method will return an error.
50 #[tracing::instrument(skip_all)]
51 pub(crate) async fn search_query_to_object_id_local(
52   query: &str,
53   context: &Data<LemmyContext>,
54 ) -> Result<SearchableObjects, LemmyError> {
55   let url = Url::parse(query)?;
56   ObjectId::from(url).dereference_local(context).await
57 }
58
59 /// The types of ActivityPub objects that can be fetched directly by searching for their ID.
60 #[derive(Debug)]
61 pub(crate) enum SearchableObjects {
62   Person(ApubPerson),
63   Community(ApubCommunity),
64   Post(ApubPost),
65   Comment(ApubComment),
66 }
67
68 #[derive(Deserialize)]
69 #[serde(untagged)]
70 pub(crate) enum SearchableKinds {
71   Group(Group),
72   Person(Person),
73   Page(Page),
74   Note(Note),
75 }
76
77 #[async_trait::async_trait]
78 impl Object for SearchableObjects {
79   type DataType = LemmyContext;
80   type Kind = SearchableKinds;
81   type Error = LemmyError;
82
83   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
84     match self {
85       SearchableObjects::Person(p) => p.last_refreshed_at(),
86       SearchableObjects::Community(c) => c.last_refreshed_at(),
87       SearchableObjects::Post(p) => p.last_refreshed_at(),
88       SearchableObjects::Comment(c) => c.last_refreshed_at(),
89     }
90   }
91
92   // TODO: this is inefficient, because if the object is not in local db, it will run 4 db queries
93   //       before finally returning an error. it would be nice if we could check all 4 tables in
94   //       a single query.
95   //       we could skip this and always return an error, but then it would always fetch objects
96   //       over http, and not be able to mark objects as deleted that were deleted by remote server.
97   #[tracing::instrument(skip_all)]
98   async fn read_from_id(
99     object_id: Url,
100     context: &Data<Self::DataType>,
101   ) -> Result<Option<Self>, LemmyError> {
102     let c = ApubCommunity::read_from_id(object_id.clone(), context).await?;
103     if let Some(c) = c {
104       return Ok(Some(SearchableObjects::Community(c)));
105     }
106     let p = ApubPerson::read_from_id(object_id.clone(), context).await?;
107     if let Some(p) = p {
108       return Ok(Some(SearchableObjects::Person(p)));
109     }
110     let p = ApubPost::read_from_id(object_id.clone(), context).await?;
111     if let Some(p) = p {
112       return Ok(Some(SearchableObjects::Post(p)));
113     }
114     let c = ApubComment::read_from_id(object_id, context).await?;
115     if let Some(c) = c {
116       return Ok(Some(SearchableObjects::Comment(c)));
117     }
118     Ok(None)
119   }
120
121   #[tracing::instrument(skip_all)]
122   async fn delete(self, data: &Data<Self::DataType>) -> Result<(), LemmyError> {
123     match self {
124       SearchableObjects::Person(p) => p.delete(data).await,
125       SearchableObjects::Community(c) => c.delete(data).await,
126       SearchableObjects::Post(p) => p.delete(data).await,
127       SearchableObjects::Comment(c) => c.delete(data).await,
128     }
129   }
130
131   async fn into_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, LemmyError> {
132     unimplemented!()
133   }
134
135   #[tracing::instrument(skip_all)]
136   async fn verify(
137     apub: &Self::Kind,
138     expected_domain: &Url,
139     data: &Data<Self::DataType>,
140   ) -> Result<(), LemmyError> {
141     match apub {
142       SearchableKinds::Group(a) => ApubCommunity::verify(a, expected_domain, data).await,
143       SearchableKinds::Person(a) => ApubPerson::verify(a, expected_domain, data).await,
144       SearchableKinds::Page(a) => ApubPost::verify(a, expected_domain, data).await,
145       SearchableKinds::Note(a) => ApubComment::verify(a, expected_domain, data).await,
146     }
147   }
148
149   #[tracing::instrument(skip_all)]
150   async fn from_json(apub: Self::Kind, context: &Data<LemmyContext>) -> Result<Self, LemmyError> {
151     use SearchableKinds as SAT;
152     use SearchableObjects as SO;
153     Ok(match apub {
154       SAT::Group(g) => SO::Community(ApubCommunity::from_json(g, context).await?),
155       SAT::Person(p) => SO::Person(ApubPerson::from_json(p, context).await?),
156       SAT::Page(p) => SO::Post(ApubPost::from_json(p, context).await?),
157       SAT::Note(n) => SO::Comment(ApubComment::from_json(n, context).await?),
158     })
159   }
160 }