]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Remove federation backwards compatibility with 0.16.x (#2183)
[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::{check_slurs, check_slurs_opt, convert_datetime, markdown_to_html},
34 };
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       Site::read_from_apub_id(data.pool(), object_id)
73         .await?
74         .map(Into::into),
75     )
76   }
77
78   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
79     unimplemented!()
80   }
81
82   #[tracing::instrument(skip_all)]
83   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
84     let site_id = self.id;
85     let langs = SiteLanguage::read(data.pool(), site_id).await?;
86     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
87
88     let instance = Instance {
89       kind: ApplicationType::Application,
90       id: ObjectId::new(self.actor_id()),
91       name: self.name.clone(),
92       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
93       source: self.sidebar.clone().map(Source::new),
94       summary: self.description.clone(),
95       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
96       icon: self.icon.clone().map(ImageObject::new),
97       image: self.banner.clone().map(ImageObject::new),
98       inbox: self.inbox_url.clone().into(),
99       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
100       public_key: self.get_public_key(),
101       language,
102       published: convert_datetime(self.published),
103       updated: self.updated.map(convert_datetime),
104     };
105     Ok(instance)
106   }
107
108   #[tracing::instrument(skip_all)]
109   async fn verify(
110     apub: &Self::ApubType,
111     expected_domain: &Url,
112     data: &Self::DataType,
113     _request_counter: &mut i32,
114   ) -> Result<(), LemmyError> {
115     let local_site_data = fetch_local_site_data(data.pool()).await?;
116
117     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
118     verify_domains_match(expected_domain, apub.id.inner())?;
119
120     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
121
122     check_slurs(&apub.name, slur_regex)?;
123     check_slurs_opt(&apub.summary, slur_regex)?;
124     Ok(())
125   }
126
127   #[tracing::instrument(skip_all)]
128   async fn from_apub(
129     apub: Self::ApubType,
130     data: &Self::DataType,
131     _request_counter: &mut i32,
132   ) -> Result<Self, LemmyError> {
133     let apub_id = apub.id.inner().clone();
134     let instance = DbInstance::create_from_actor_id(data.pool(), &apub_id).await?;
135
136     let site_form = SiteInsertForm {
137       name: apub.name.clone(),
138       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
139       updated: apub.updated.map(|u| u.clone().naive_local()),
140       icon: apub.icon.clone().map(|i| i.url.into()),
141       banner: apub.image.clone().map(|i| i.url.into()),
142       description: 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       private_key: None,
148       instance_id: instance.id,
149     };
150     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
151
152     let site = Site::create(data.pool(), &site_form).await?;
153     SiteLanguage::update(data.pool(), languages, &site).await?;
154     Ok(site.into())
155   }
156 }
157
158 impl ActorType for ApubSite {
159   fn actor_id(&self) -> Url {
160     self.actor_id.clone().into()
161   }
162   fn private_key(&self) -> Option<String> {
163     self.private_key.clone()
164   }
165 }
166
167 impl Actor for ApubSite {
168   fn public_key(&self) -> &str {
169     &self.public_key
170   }
171
172   fn inbox(&self) -> Url {
173     self.inbox_url.clone().into()
174   }
175 }
176
177 /// try to fetch the instance actor (to make things like instance rules available)
178 pub(in crate::objects) async fn fetch_instance_actor_for_object(
179   object_id: Url,
180   context: &LemmyContext,
181   request_counter: &mut i32,
182 ) {
183   // try to fetch the instance actor (to make things like instance rules available)
184   let instance_id = Site::instance_actor_id_from_url(object_id);
185   let site = ObjectId::<ApubSite>::new(instance_id.clone())
186     .dereference(context, local_instance(context).await, request_counter)
187     .await;
188   if let Err(e) = site {
189     debug!("Failed to dereference site for {}: {}", instance_id, e);
190   }
191 }
192
193 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
194   Ok(
195     Site::read_remote_sites(pool)
196       .await?
197       .into_iter()
198       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
199       .collect(),
200   )
201 }
202
203 #[cfg(test)]
204 pub(crate) mod tests {
205   use super::*;
206   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
207   use lemmy_db_schema::traits::Crud;
208   use serial_test::serial;
209
210   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
211     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
212     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
213     let mut request_counter = 0;
214     ApubSite::verify(&json, &id, context, &mut request_counter)
215       .await
216       .unwrap();
217     let site = ApubSite::from_apub(json, context, &mut request_counter)
218       .await
219       .unwrap();
220     assert_eq!(request_counter, 0);
221     site
222   }
223
224   #[actix_rt::test]
225   #[serial]
226   async fn test_parse_lemmy_instance() {
227     let context = init_context().await;
228     let site = parse_lemmy_instance(&context).await;
229
230     assert_eq!(site.name, "Enterprise");
231     assert_eq!(site.description.as_ref().unwrap().len(), 15);
232
233     Site::delete(context.pool(), site.id).await.unwrap();
234   }
235 }