]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
ef4328ef0582f4856e4333b2159ca39d7912747f
[lemmy.git] / crates / apub / src / objects / instance.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   local_instance,
4   objects::read_from_string_or_source_opt,
5   protocol::{
6     objects::{
7       instance::{Instance, InstanceType},
8       LanguageTag,
9     },
10     ImageObject,
11     Source,
12   },
13   ActorType,
14 };
15 use activitypub_federation::{
16   core::object_id::ObjectId,
17   deser::values::MediaTypeHtml,
18   traits::{Actor, ApubObject},
19   utils::verify_domains_match,
20 };
21 use chrono::NaiveDateTime;
22 use lemmy_api_common::utils::blocking;
23 use lemmy_db_schema::{
24   source::{
25     actor_language::SiteLanguage,
26     site::{Site, SiteForm},
27   },
28   utils::{naive_now, DbPool},
29 };
30 use lemmy_utils::{
31   error::LemmyError,
32   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
33 };
34 use lemmy_websocket::LemmyContext;
35 use std::ops::Deref;
36 use tracing::debug;
37 use url::Url;
38
39 #[derive(Clone, Debug)]
40 pub struct ApubSite(Site);
41
42 impl Deref for ApubSite {
43   type Target = Site;
44   fn deref(&self) -> &Self::Target {
45     &self.0
46   }
47 }
48
49 impl From<Site> for ApubSite {
50   fn from(s: Site) -> Self {
51     ApubSite(s)
52   }
53 }
54
55 #[async_trait::async_trait(?Send)]
56 impl ApubObject for ApubSite {
57   type DataType = LemmyContext;
58   type ApubType = Instance;
59   type DbType = Site;
60   type Error = LemmyError;
61
62   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
63     Some(self.last_refreshed_at)
64   }
65
66   #[tracing::instrument(skip_all)]
67   async fn read_from_apub_id(
68     object_id: Url,
69     data: &Self::DataType,
70   ) -> Result<Option<Self>, LemmyError> {
71     Ok(
72       blocking(data.pool(), move |conn| {
73         Site::read_from_apub_id(conn, object_id)
74       })
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 = blocking(data.pool(), move |conn| SiteLanguage::read(conn, 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     check_apub_id_valid_with_strictness(apub.id.inner(), true, data.settings())?;
118     verify_domains_match(expected_domain, apub.id.inner())?;
119
120     let slur_regex = &data.settings().slur_regex();
121     check_slurs(&apub.name, slur_regex)?;
122     check_slurs_opt(&apub.summary, slur_regex)?;
123     Ok(())
124   }
125
126   #[tracing::instrument(skip_all)]
127   async fn from_apub(
128     apub: Self::ApubType,
129     data: &Self::DataType,
130     _request_counter: &mut i32,
131   ) -> Result<Self, LemmyError> {
132     let site_form = SiteForm {
133       name: apub.name.clone(),
134       sidebar: Some(read_from_string_or_source_opt(
135         &apub.content,
136         &None,
137         &apub.source,
138       )),
139       updated: apub.updated.map(|u| u.clone().naive_local()),
140       icon: Some(apub.icon.clone().map(|i| i.url.into())),
141       banner: Some(apub.image.clone().map(|i| i.url.into())),
142       description: Some(apub.summary.clone()),
143       actor_id: Some(apub.id.clone().into()),
144       last_refreshed_at: Some(naive_now()),
145       inbox_url: Some(apub.inbox.clone().into()),
146       public_key: Some(apub.public_key.public_key_pem.clone()),
147       ..SiteForm::default()
148     };
149     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
150
151     let site = blocking(data.pool(), move |conn| {
152       let site = Site::upsert(conn, &site_form)?;
153       SiteLanguage::update(conn, languages, site.id)?;
154       Ok::<Site, diesel::result::Error>(site)
155     })
156     .await??;
157     Ok(site.into())
158   }
159 }
160
161 impl ActorType for ApubSite {
162   fn actor_id(&self) -> Url {
163     self.actor_id.to_owned().into()
164   }
165   fn private_key(&self) -> Option<String> {
166     self.private_key.to_owned()
167   }
168 }
169
170 impl Actor for ApubSite {
171   fn public_key(&self) -> &str {
172     &self.public_key
173   }
174
175   fn inbox(&self) -> Url {
176     self.inbox_url.clone().into()
177   }
178 }
179
180 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
181 /// parts of the url.
182 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
183   url.set_fragment(None);
184   url.set_path("");
185   url.set_query(None);
186   url
187 }
188
189 /// try to fetch the instance actor (to make things like instance rules available)
190 pub(in crate::objects) async fn fetch_instance_actor_for_object(
191   object_id: Url,
192   context: &LemmyContext,
193   request_counter: &mut i32,
194 ) {
195   // try to fetch the instance actor (to make things like instance rules available)
196   let instance_id = instance_actor_id_from_url(object_id);
197   let site = ObjectId::<ApubSite>::new(instance_id.clone())
198     .dereference(context, local_instance(context), request_counter)
199     .await;
200   if let Err(e) = site {
201     debug!("Failed to dereference site for {}: {}", instance_id, e);
202   }
203 }
204
205 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
206   Ok(
207     blocking(pool, Site::read_remote_sites)
208       .await??
209       .into_iter()
210       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
211       .collect(),
212   )
213 }
214
215 #[cfg(test)]
216 pub(crate) mod tests {
217   use super::*;
218   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
219   use lemmy_db_schema::traits::Crud;
220   use serial_test::serial;
221
222   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
223     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
224     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
225     let mut request_counter = 0;
226     ApubSite::verify(&json, &id, context, &mut request_counter)
227       .await
228       .unwrap();
229     let site = ApubSite::from_apub(json, context, &mut request_counter)
230       .await
231       .unwrap();
232     assert_eq!(request_counter, 0);
233     site
234   }
235
236   #[actix_rt::test]
237   #[serial]
238   async fn test_parse_lemmy_instance() {
239     let context = init_context();
240     let conn = &mut context.pool().get().unwrap();
241     let site = parse_lemmy_instance(&context).await;
242
243     assert_eq!(site.name, "Enterprise");
244     assert_eq!(site.description.as_ref().unwrap().len(), 15);
245
246     Site::delete(conn, site.id).unwrap();
247   }
248 }