]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
Dont upsert Instance row every apub fetch (#2771)
[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   newtypes::InstanceId,
24   source::{
25     actor_language::SiteLanguage,
26     instance::Instance as DbInstance,
27     site::{Site, SiteInsertForm},
28   },
29   traits::Crud,
30   utils::{naive_now, DbPool},
31 };
32 use lemmy_utils::{
33   error::LemmyError,
34   utils::{
35     markdown::markdown_to_html,
36     slurs::{check_slurs, check_slurs_opt},
37     time::convert_datetime,
38   },
39 };
40 use std::ops::Deref;
41 use tracing::debug;
42 use url::Url;
43
44 #[derive(Clone, Debug)]
45 pub struct ApubSite(Site);
46
47 impl Deref for ApubSite {
48   type Target = Site;
49   fn deref(&self) -> &Self::Target {
50     &self.0
51   }
52 }
53
54 impl From<Site> for ApubSite {
55   fn from(s: Site) -> Self {
56     ApubSite(s)
57   }
58 }
59
60 #[async_trait::async_trait(?Send)]
61 impl ApubObject for ApubSite {
62   type DataType = LemmyContext;
63   type ApubType = Instance;
64   type DbType = Site;
65   type Error = LemmyError;
66
67   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
68     Some(self.last_refreshed_at)
69   }
70
71   #[tracing::instrument(skip_all)]
72   async fn read_from_apub_id(
73     object_id: Url,
74     data: &Self::DataType,
75   ) -> Result<Option<Self>, LemmyError> {
76     Ok(
77       Site::read_from_apub_id(data.pool(), object_id)
78         .await?
79         .map(Into::into),
80     )
81   }
82
83   async fn delete(self, _data: &Self::DataType) -> Result<(), LemmyError> {
84     unimplemented!()
85   }
86
87   #[tracing::instrument(skip_all)]
88   async fn into_apub(self, data: &Self::DataType) -> Result<Self::ApubType, LemmyError> {
89     let site_id = self.id;
90     let langs = SiteLanguage::read(data.pool(), site_id).await?;
91     let language = LanguageTag::new_multiple(langs, data.pool()).await?;
92
93     let instance = Instance {
94       kind: ApplicationType::Application,
95       id: ObjectId::new(self.actor_id()),
96       name: self.name.clone(),
97       content: self.sidebar.as_ref().map(|d| markdown_to_html(d)),
98       source: self.sidebar.clone().map(Source::new),
99       summary: self.description.clone(),
100       media_type: self.sidebar.as_ref().map(|_| MediaTypeHtml::Html),
101       icon: self.icon.clone().map(ImageObject::new),
102       image: self.banner.clone().map(ImageObject::new),
103       inbox: self.inbox_url.clone().into(),
104       outbox: Url::parse(&format!("{}/site_outbox", self.actor_id))?,
105       public_key: self.get_public_key(),
106       language,
107       published: convert_datetime(self.published),
108       updated: self.updated.map(convert_datetime),
109     };
110     Ok(instance)
111   }
112
113   #[tracing::instrument(skip_all)]
114   async fn verify(
115     apub: &Self::ApubType,
116     expected_domain: &Url,
117     data: &Self::DataType,
118     _request_counter: &mut i32,
119   ) -> Result<(), LemmyError> {
120     let local_site_data = fetch_local_site_data(data.pool()).await?;
121
122     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
123     verify_domains_match(expected_domain, apub.id.inner())?;
124
125     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
126
127     check_slurs(&apub.name, slur_regex)?;
128     check_slurs_opt(&apub.summary, slur_regex)?;
129     Ok(())
130   }
131
132   #[tracing::instrument(skip_all)]
133   async fn from_apub(
134     apub: Self::ApubType,
135     data: &Self::DataType,
136     _request_counter: &mut i32,
137   ) -> Result<Self, LemmyError> {
138     let domain = apub.id.inner().domain().expect("group id has domain");
139     let instance = DbInstance::read_or_create(data.pool(), domain.to_string()).await?;
140
141     let site_form = SiteInsertForm {
142       name: apub.name.clone(),
143       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
144       updated: apub.updated.map(|u| u.clone().naive_local()),
145       icon: apub.icon.clone().map(|i| i.url.into()),
146       banner: apub.image.clone().map(|i| i.url.into()),
147       description: apub.summary.clone(),
148       actor_id: Some(apub.id.clone().into()),
149       last_refreshed_at: Some(naive_now()),
150       inbox_url: Some(apub.inbox.clone().into()),
151       public_key: Some(apub.public_key.public_key_pem.clone()),
152       private_key: None,
153       instance_id: instance.id,
154     };
155     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
156
157     let site = Site::create(data.pool(), &site_form).await?;
158     SiteLanguage::update(data.pool(), languages, &site).await?;
159     Ok(site.into())
160   }
161 }
162
163 impl ActorType for ApubSite {
164   fn actor_id(&self) -> Url {
165     self.actor_id.clone().into()
166   }
167   fn private_key(&self) -> Option<String> {
168     self.private_key.clone()
169   }
170 }
171
172 impl Actor for ApubSite {
173   fn public_key(&self) -> &str {
174     &self.public_key
175   }
176
177   fn inbox(&self) -> Url {
178     self.inbox_url.clone().into()
179   }
180 }
181
182 /// Try to fetch the instance actor (to make things like instance rules available).
183 pub(in crate::objects) async fn fetch_instance_actor_for_object<T: Into<Url> + Clone>(
184   object_id: &T,
185   context: &LemmyContext,
186   request_counter: &mut i32,
187 ) -> Result<InstanceId, LemmyError> {
188   let object_id: Url = object_id.clone().into();
189   let instance_id = Site::instance_actor_id_from_url(object_id);
190   let site = ObjectId::<ApubSite>::new(instance_id.clone())
191     .dereference(context, local_instance(context).await, request_counter)
192     .await;
193   match site {
194     Ok(s) => Ok(s.instance_id),
195     Err(e) => {
196       // Failed to fetch instance actor, its probably not a lemmy instance
197       debug!("Failed to dereference site for {}: {}", &instance_id, e);
198       let domain = instance_id.domain().expect("has domain");
199       Ok(
200         DbInstance::read_or_create(context.pool(), domain.to_string())
201           .await?
202           .id,
203       )
204     }
205   }
206 }
207
208 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
209   Ok(
210     Site::read_remote_sites(pool)
211       .await?
212       .into_iter()
213       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
214       .collect(),
215   )
216 }
217
218 #[cfg(test)]
219 pub(crate) mod tests {
220   use super::*;
221   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
222   use lemmy_db_schema::traits::Crud;
223   use serial_test::serial;
224
225   pub(crate) async fn parse_lemmy_instance(context: &LemmyContext) -> ApubSite {
226     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
227     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
228     let mut request_counter = 0;
229     ApubSite::verify(&json, &id, context, &mut request_counter)
230       .await
231       .unwrap();
232     let site = ApubSite::from_apub(json, context, &mut request_counter)
233       .await
234       .unwrap();
235     assert_eq!(request_counter, 0);
236     site
237   }
238
239   #[actix_rt::test]
240   #[serial]
241   async fn test_parse_lemmy_instance() {
242     let context = init_context().await;
243     let site = parse_lemmy_instance(&context).await;
244
245     assert_eq!(site.name, "Enterprise");
246     assert_eq!(site.description.as_ref().unwrap().len(), 15);
247
248     Site::delete(context.pool(), site.id).await.unwrap();
249   }
250 }