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