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