]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/instance.rs
72d133441bfe3e67e7864d0fe0928c9059fc96b3
[lemmy.git] / crates / apub / src / objects / instance.rs
1 use crate::{
2   check_apub_id_valid_with_strictness,
3   fetch_local_site_data,
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(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(data.pool(), site_id).await?;
88     let language = LanguageTag::new_multiple(langs, 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     let local_site_data = fetch_local_site_data(data.pool()).await?;
117
118     check_apub_id_valid_with_strictness(apub.id.inner(), true, &local_site_data, data.settings())?;
119     verify_domains_match(expected_domain, apub.id.inner())?;
120
121     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
122
123     check_slurs(&apub.name, slur_regex)?;
124     check_slurs_opt(&apub.summary, slur_regex)?;
125     Ok(())
126   }
127
128   #[tracing::instrument(skip_all)]
129   async fn from_json(apub: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, LemmyError> {
130     let domain = apub.id.inner().domain().expect("group id has domain");
131     let instance = DbInstance::read_or_create(data.pool(), domain.to_string()).await?;
132
133     let site_form = SiteInsertForm {
134       name: apub.name.clone(),
135       sidebar: read_from_string_or_source_opt(&apub.content, &None, &apub.source),
136       updated: apub.updated.map(|u| u.clone().naive_local()),
137       icon: apub.icon.clone().map(|i| i.url.into()),
138       banner: apub.image.clone().map(|i| i.url.into()),
139       description: apub.summary.clone(),
140       actor_id: Some(apub.id.clone().into()),
141       last_refreshed_at: Some(naive_now()),
142       inbox_url: Some(apub.inbox.clone().into()),
143       public_key: Some(apub.public_key.public_key_pem.clone()),
144       private_key: None,
145       instance_id: instance.id,
146     };
147     let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?;
148
149     let site = Site::create(data.pool(), &site_form).await?;
150     SiteLanguage::update(data.pool(), languages, &site).await?;
151     Ok(site.into())
152   }
153 }
154
155 impl Actor for ApubSite {
156   fn id(&self) -> Url {
157     self.actor_id.inner().clone()
158   }
159
160   fn public_key_pem(&self) -> &str {
161     &self.public_key
162   }
163
164   fn private_key_pem(&self) -> Option<String> {
165     self.private_key.clone()
166   }
167
168   fn inbox(&self) -> Url {
169     self.inbox_url.clone().into()
170   }
171 }
172
173 /// Try to fetch the instance actor (to make things like instance rules available).
174 pub(in crate::objects) async fn fetch_instance_actor_for_object<T: Into<Url> + Clone>(
175   object_id: &T,
176   context: &Data<LemmyContext>,
177 ) -> Result<InstanceId, LemmyError> {
178   let object_id: Url = object_id.clone().into();
179   let instance_id = Site::instance_actor_id_from_url(object_id);
180   let site = ObjectId::<ApubSite>::from(instance_id.clone())
181     .dereference(context)
182     .await;
183   match site {
184     Ok(s) => Ok(s.instance_id),
185     Err(e) => {
186       // Failed to fetch instance actor, its probably not a lemmy instance
187       debug!("Failed to dereference site for {}: {}", &instance_id, e);
188       let domain = instance_id.domain().expect("has domain");
189       Ok(
190         DbInstance::read_or_create(context.pool(), domain.to_string())
191           .await?
192           .id,
193       )
194     }
195   }
196 }
197
198 pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result<Vec<Url>, LemmyError> {
199   Ok(
200     Site::read_remote_sites(pool)
201       .await?
202       .into_iter()
203       .map(|s| ApubSite::from(s).shared_inbox_or_inbox())
204       .collect(),
205   )
206 }
207
208 #[cfg(test)]
209 pub(crate) mod tests {
210   use super::*;
211   use crate::{objects::tests::init_context, protocol::tests::file_to_json_object};
212   use lemmy_db_schema::traits::Crud;
213   use serial_test::serial;
214
215   pub(crate) async fn parse_lemmy_instance(context: &Data<LemmyContext>) -> ApubSite {
216     let json: Instance = file_to_json_object("assets/lemmy/objects/instance.json").unwrap();
217     let id = Url::parse("https://enterprise.lemmy.ml/").unwrap();
218     ApubSite::verify(&json, &id, context).await.unwrap();
219     let site = ApubSite::from_json(json, context).await.unwrap();
220     assert_eq!(context.request_count(), 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 }