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