]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Add SendActivity trait so that api crates compile in parallel with lemmy_apub
[lemmy.git] / crates / apub / src / objects / instance.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   fetch_local_site_data,
4   local_instance,
5   objects::read_from_string_or_source_opt,
6   protocol::{
7     objects::{
8       instance::{Instance, InstanceType},
9       LanguageTag,
10     },
11     ImageObject,
12     Source,
13   },
14   ActorType,
15 };
16 use activitypub_federation::{
17   core::object_id::ObjectId,
18   deser::values::MediaTypeHtml,
19   traits::{Actor, ApubObject},
20   utils::verify_domains_match,
21 };
22 use chrono::NaiveDateTime;
23 use lemmy_api_common::{context::LemmyContext, utils::local_site_opt_to_slur_regex};
24 use lemmy_db_schema::{
25   source::{
26     actor_language::SiteLanguage,
27     instance::Instance as DbInstance,
28     site::{Site, SiteInsertForm},
29   },
30   traits::Crud,
31   utils::{naive_now, DbPool},
32 };
33 use lemmy_utils::{
34   error::LemmyError,
35   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
36 };
37 use std::ops::Deref;
38 use tracing::debug;
39 use url::Url;
40
41 #[derive(Clone, Debug)]
42 pub struct ApubSite(Site);
43
44 impl Deref for ApubSite {
45   type Target = Site;
46   fn deref(&self) -> &Self::Target {
47     &self.0
48   }
49 }
50
51 impl From<Site> for ApubSite {
52   fn from(s: Site) -> Self {
53     ApubSite(s)
54   }
55 }
56
57 #[async_trait::async_trait(?Send)]
58 impl ApubObject for ApubSite {
59   type DataType = LemmyContext;
60   type ApubType = Instance;
61   type DbType = Site;
62   type Error = LemmyError;
63
64   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
65     Some(self.last_refreshed_at)
66   }
67
68   #[tracing::instrument(skip_all)]
69   async fn read_from_apub_id(
70     object_id: Url,
71     data: &Self::DataType,
72   ) -> Result<Option<Self>, LemmyError> {
73     Ok(
74       Site::read_from_apub_id(data.pool(), object_id)
75         .await?
76         .map(Into::into),
77     )
78   }
79
80   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
81     unimplemented!()
82   }
83
84   #[tracing::instrument(skip_all)]
85   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
86     let site_id = self.id;
87     let langs = SiteLanguage::read(data.pool(), site_id).await?;
88     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
89
90     let instance = Instance {
91       kind: InstanceType::Service,
92       id: ObjectId::new(self.actor_id()),
93       name: self.name.clone(),
94       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
95       source: self.sidebar.clone().map(Source::new),
96       summary: self.description.clone(),
97       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
98       icon: self.icon.clone().map(ImageObject::new),
99       image: self.banner.clone().map(ImageObject::new),
100       inbox: self.inbox_url.clone().into(),
101       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
102       public_key: self.get_public_key(),
103       language,
104       published: convert_datetime(self.published),
105       updated: self.updated.map(convert_datetime),
106     };
107     Ok(instance)
108   }
109
110   #[tracing::instrument(skip_all)]
111   async fn verify(
112     apub: &Self::ApubType,
113     expected_domain: &Url,
114     data: &Self::DataType,
115     _request_counter: &mut i32,
116   ) -> Result<(), LemmyError> {
117     let local_site_data = fetch_local_site_data(data.pool()).await?;
118
119     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
120     verify_domains_match(expected_domain, apub.id.inner())?;
121
122     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
123
124     check_slurs(&apub.name, slur_regex)?;
125     check_slurs_opt(&apub.summary, slur_regex)?;
126     Ok(())
127   }
128
129   #[tracing::instrument(skip_all)]
130   async fn from_apub(
131     apub: Self::ApubType,
132     data: &Self::DataType,
133     _request_counter: &mut i32,
134   ) -> Result<Self, LemmyError> {
135     let apub_id = apub.id.inner().clone();
136     let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
137
138     let site_form = SiteInsertForm {
139       name: apub.name.clone(),
140       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
141       updated: apub.updated.map(|u| u.clone().naive_local()),
142       icon: apub.icon.clone().map(|i| i.url.into()),
143       banner: apub.image.clone().map(|i| i.url.into()),
144       description: apub.summary.clone(),
145       actor_id: Some(apub.id.clone().into()),
146       last_refreshed_at: Some(naive_now()),
147       inbox_url: Some(apub.inbox.clone().into()),
148       public_key: Some(apub.public_key.public_key_pem.clone()),
149       private_key: None,
150       instance_id: instance.id,
151     };
152     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
153
154     let site = Site::create(data.pool(), &site_form).await?;
155     SiteLanguage::update(data.pool(), languages, &site).await?;
156     Ok(site.into())
157   }
158 }
159
160 impl ActorType for ApubSite {
161   fn actor_id(&self) -> Url {
162     self.actor_id.clone().into()
163   }
164   fn private_key(&self) -> Option<String> {
165     self.private_key.clone()
166   }
167 }
168
169 impl Actor for ApubSite {
170   fn public_key(&self) -> &str {
171     &self.public_key
172   }
173
174   fn inbox(&self) -> Url {
175     self.inbox_url.clone().into()
176   }
177 }
178
179 /// try to fetch the instance actor (to make things like instance rules available)
180 pub(in crate::objects) async fn fetch_instance_actor_for_object(
181   object_id: Url,
182   context: &LemmyContext,
183   request_counter: &mut i32,
184 ) {
185   // try to fetch the instance actor (to make things like instance rules available)
186   let instance_id = Site::instance_actor_id_from_url(object_id);
187   let site = ObjectId::<ApubSite>::new(instance_id.clone())
188     .dereference(context, local_instance(context).await, request_counter)
189     .await;
190   if let Err(e) = site {
191     debug!("Failed to dereference site for {}: {}", instance_id, e);
192   }
193 }
194
195 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
196   Ok(
197     Site::read_remote_sites(pool)
198       .await?
199       .into_iter()
200       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
201       .collect(),
202   )
203 }
204
205 #[cfg(test)]
206 pub(crate) mod tests {
207   use super::*;
208   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
209   use lemmy_db_schema::traits::Crud;
210   use serial_test::serial;
211
212   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
213     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
214     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
215     let mut request_counter = 0;
216     ApubSite::verify(&json, &id, context, &mut request_counter)
217       .await
218       .unwrap();
219     let site = ApubSite::from_apub(json, context, &mut request_counter)
220       .await
221       .unwrap();
222     assert_eq!(request_counter, 0);
223     site
224   }
225
226   #[actix_rt::test]
227   #[serial]
228   async fn test_parse_lemmy_instance() {
229     let context = init_context().await;
230     let site = parse_lemmy_instance(&context).await;
231
232     assert_eq!(site.name, "Enterprise");
233     assert_eq!(site.description.as_ref().unwrap().len(), 15);
234
235     Site::delete(context.pool(), site.id).await.unwrap();
236   }
237 }