]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Add cargo feature for building lemmy_api_common with mininum deps (#2243)
[lemmy.git] / crates / apub / src / objects / instance.rs
1 use crate::{
2   check_is_apub_id_valid,
3   objects::{read_from_string_or_source_opt, verify_image_domain_matches},
4   protocol::{
5     objects::instance::{Instance, InstanceType},
6     ImageObject,
7     Source,
8   },
9 };
10 use chrono::NaiveDateTime;
11 use lemmy_api_common::utils::blocking;
12 use lemmy_apub_lib::{
13   object_id::ObjectId,
14   traits::{ActorType, ApubObject},
15   values::MediaTypeHtml,
16   verify::verify_domains_match,
17 };
18 use lemmy_db_schema::{
19   source::site::{Site, SiteForm},
20   utils::naive_now,
21 };
22 use lemmy_utils::{
23   utils::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
24   LemmyError,
25 };
26 use lemmy_websocket::LemmyContext;
27 use std::ops::Deref;
28 use tracing::debug;
29 use url::Url;
30
31 #[derive(Clone, Debug)]
32 pub struct ApubSite(Site);
33
34 impl Deref for ApubSite {
35   type Target = Site;
36   fn deref(&self) -> &Self::Target {
37     &self.0
38   }
39 }
40
41 impl From<Site> for ApubSite {
42   fn from(s: Site) -> Self {
43     ApubSite(s)
44   }
45 }
46
47 #[async_trait::async_trait(?Send)]
48 impl ApubObject for ApubSite {
49   type DataType = LemmyContext;
50   type ApubType = Instance;
51   type DbType = Site;
52   type TombstoneType = ();
53
54   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
55     Some(self.last_refreshed_at)
56   }
57
58   #[tracing::instrument(skip_all)]
59   async fn read_from_apub_id(
60     object_id: Url,
61     data: &Self::DataType,
62   ) -> Result<Option<Self>, LemmyError> {
63     Ok(
64       blocking(data.pool(), move |conn| {
65         Site::read_from_apub_id(conn, object_id)
66       })
67       .await??
68       .map(Into::into),
69     )
70   }
71
72   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
73     unimplemented!()
74   }
75
76   #[tracing::instrument(skip_all)]
77   async fn into_apub(self, _data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
78     let instance = Instance {
79       kind: InstanceType::Service,
80       id: ObjectId::new(self.actor_id()),
81       name: self.name.clone(),
82       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
83       source: self.sidebar.clone().map(Source::new),
84       summary: self.description.clone(),
85       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
86       icon: self.icon.clone().map(ImageObject::new),
87       image: self.banner.clone().map(ImageObject::new),
88       inbox: self.inbox_url.clone().into(),
89       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
90       public_key: self.get_public_key()?,
91       published: convert_datetime(self.published),
92       updated: self.updated.map(convert_datetime),
93     };
94     Ok(instance)
95   }
96
97   fn to_tombstone(&self) -> Result<Self::TombstoneType, LemmyError> {
98     unimplemented!()
99   }
100
101   #[tracing::instrument(skip_all)]
102   async fn verify(
103     apub: &Self::ApubType,
104     expected_domain: &Url,
105     data: &Self::DataType,
106     _request_counter: &mut i32,
107   ) -> Result<(), LemmyError> {
108     check_is_apub_id_valid(apub.id.inner(), true, &data.settings())?;
109     verify_domains_match(expected_domain, apub.id.inner())?;
110     verify_image_domain_matches(expected_domain, &apub.icon)?;
111     verify_image_domain_matches(expected_domain, &apub.image)?;
112
113     let slur_regex = &data.settings().slur_regex();
114     check_slurs(&apub.name, slur_regex)?;
115     check_slurs_opt(&apub.summary, slur_regex)?;
116     Ok(())
117   }
118
119   #[tracing::instrument(skip_all)]
120   async fn from_apub(
121     apub: Self::ApubType,
122     data: &Self::DataType,
123     _request_counter: &mut i32,
124   ) -> Result<Self, LemmyError> {
125     let site_form = SiteForm {
126       name: apub.name.clone(),
127       sidebar: Some(read_from_string_or_source_opt(&apub.content, &apub.source)),
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 }