]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
cdd76c5a959300a54a6f00c451f2258a69cad15c
[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,
4   protocol::{objects::instance::Instance, ImageObject, Source, Unparsed},
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 TombstoneType = ();
49
50   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
51     Some(self.last_refreshed_at)
52   }
53
54   #[tracing::instrument(skip_all)]
55   async fn read_from_apub_id(
56     object_id: Url,
57     data: &Self::DataType,
58   ) -> Result<Option<Self>, LemmyError> {
59     Ok(
60       blocking(data.pool(), move |conn| {
61         Site::read_from_apub_id(conn, object_id)
62       })
63       .await??
64       .map(Into::into),
65     )
66   }
67
68   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
69     unimplemented!()
70   }
71
72   #[tracing::instrument(skip_all)]
73   async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
74     let instance = Instance {
75       kind: ServiceType::Service,
76       id: ObjectId::new(self.actor_id()),
77       name: self.name.clone(),
78       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
79       source: self.sidebar.clone().map(Source::new),
80       summary: self.description.clone(),
81       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
82       icon: self.icon.clone().map(ImageObject::new),
83       image: self.banner.clone().map(ImageObject::new),
84       inbox: self.inbox_url.clone().into(),
85       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
86       public_key: self.get_public_key()?,
87       published: convert_datetime(self.published),
88       updated: self.updated.map(convert_datetime),
89       unparsed: Unparsed::default(),
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
108     let slur_regex = &data.settings().slur_regex();
109     check_slurs(&apub.name, slur_regex)?;
110     check_slurs_opt(&apub.summary, slur_regex)?;
111     Ok(())
112   }
113
114   #[tracing::instrument(skip_all)]
115   async fn from_apub(
116     apub: Self::ApubType,
117     data: &Self::DataType,
118     _request_counter: &mut i32,
119   ) -> Result<Self, LemmyError> {
120     let site_form = SiteForm {
121       name: apub.name.clone(),
122       sidebar: Some(get_summary_from_string_or_source(
123         &apub.content,
124         &apub.source,
125       )),
126       updated: apub.updated.map(|u| u.clone().naive_local()),
127       icon: Some(apub.icon.clone().map(|i| i.url.into())),
128       banner: Some(apub.image.clone().map(|i| i.url.into())),
129       description: Some(apub.summary.clone()),
130       actor_id: Some(apub.id.clone().into()),
131       last_refreshed_at: Some(naive_now()),
132       inbox_url: Some(apub.inbox.clone().into()),
133       public_key: Some(apub.public_key.public_key_pem.clone()),
134       ..SiteForm::default()
135     };
136     let site = blocking(data.pool(), move |conn| Site::upsert(conn, &site_form)).await??;
137     Ok(site.into())
138   }
139 }
140
141 impl ActorType for ApubSite {
142   fn actor_id(&self) -> Url {
143     self.actor_id.to_owned().into()
144   }
145   fn public_key(&self) -> String {
146     self.public_key.to_owned()
147   }
148   fn private_key(&self) -> Option<String> {
149     self.private_key.to_owned()
150   }
151
152   fn inbox_url(&self) -> Url {
153     self.inbox_url.clone().into()
154   }
155
156   fn shared_inbox_url(&self) -> Option<Url> {
157     None
158   }
159 }
160
161 /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary
162 /// parts of the url.
163 pub fn instance_actor_id_from_url(mut url: Url) -> Url {
164   url.set_fragment(None);
165   url.set_path("");
166   url.set_query(None);
167   url
168 }
169
170 /// try to fetch the instance actor (to make things like instance rules available)
171 pub(in crate::objects) async fn fetch_instance_actor_for_object(
172   object_id: Url,
173   context: &LemmyContext,
174   request_counter: &mut i32,
175 ) {
176   // try to fetch the instance actor (to make things like instance rules available)
177   let instance_id = instance_actor_id_from_url(object_id);
178   let site = ObjectId::<ApubSite>::new(instance_id.clone())
179     .dereference(context, context.client(), request_counter)
180     .await;
181   if let Err(e) = site {
182     debug!("Failed to dereference site for {}: {}", instance_id, e);
183   }
184 }
185
186 #[cfg(test)]
187 pub(crate) mod tests {
188   use super::*;
189   use crate::objects::tests::{file_to_json_object, init_context};
190   use lemmy_apub_lib::activity_queue::create_activity_queue;
191   use lemmy_db_schema::traits::Crud;
192   use serial_test::serial;
193
194   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
195     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
196     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
197     let mut request_counter = 0;
198     ApubSite::verify(&json, &id, context, &mut request_counter)
199       .await
200       .unwrap();
201     let site = ApubSite::from_apub(json, context, &mut request_counter)
202       .await
203       .unwrap();
204     assert_eq!(request_counter, 0);
205     site
206   }
207
208   #[actix_rt::test]
209   #[serial]
210   async fn test_parse_lemmy_instance() {
211     let client = reqwest::Client::new().into();
212     let manager = create_activity_queue(client);
213     let context = init_context(manager.queue_handle().clone());
214     let site = parse_lemmy_instance(&context).await;
215
216     assert_eq!(site.name, "Enterprise");
217     assert_eq!(site.description.as_ref().unwrap().len(), 15);
218
219     Site::delete(&*context.pool().get().unwrap(), site.id).unwrap();
220   }
221 }