]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Moving settings to Database. (#2492)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_apub_id_valid_with_strictness,
4   fetch_local_site_data,
5   local_instance,
6   objects::{read_from_string_or_source_opt, verify_is_remote_object},
7   protocol::{
8     objects::{
9       page::{Attachment, AttributedTo, Page, PageType},
10       LanguageTag,
11     },
12     ImageObject,
13     Source,
14   },
15 };
16 use activitypub_federation::{
17   core::object_id::ObjectId,
18   deser::values::MediaTypeMarkdownOrHtml,
19   traits::ApubObject,
20   utils::verify_domains_match,
21 };
22 use activitystreams_kinds::public;
23 use chrono::NaiveDateTime;
24 use lemmy_api_common::{
25   request::fetch_site_data,
26   utils::{blocking, local_site_opt_to_slur_regex},
27 };
28 use lemmy_db_schema::{
29   self,
30   source::{
31     community::Community,
32     local_site::LocalSite,
33     moderator::{ModLockPost, ModLockPostForm, ModStickyPost, ModStickyPostForm},
34     person::Person,
35     post::{Post, PostInsertForm, PostUpdateForm},
36   },
37   traits::Crud,
38 };
39 use lemmy_utils::{
40   error::LemmyError,
41   utils::{check_slurs, convert_datetime, markdown_to_html, remove_slurs},
42 };
43 use lemmy_websocket::LemmyContext;
44 use std::ops::Deref;
45 use url::Url;
46
47 #[derive(Clone, Debug)]
48 pub struct ApubPost(Post);
49
50 impl Deref for ApubPost {
51   type Target = Post;
52   fn deref(&self) -> &Self::Target {
53     &self.0
54   }
55 }
56
57 impl From<Post> for ApubPost {
58   fn from(p: Post) -> Self {
59     ApubPost(p)
60   }
61 }
62
63 #[async_trait::async_trait(?Send)]
64 impl ApubObject for ApubPost {
65   type DataType = LemmyContext;
66   type ApubType = Page;
67   type DbType = Post;
68   type Error = LemmyError;
69
70   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
71     None
72   }
73
74   #[tracing::instrument(skip_all)]
75   async fn read_from_apub_id(
76     object_id: Url,
77     context: &LemmyContext,
78   ) -> Result<Option<Self>, LemmyError> {
79     Ok(
80       blocking(context.pool(), move |conn| {
81         Post::read_from_apub_id(conn, object_id)
82       })
83       .await??
84       .map(Into::into),
85     )
86   }
87
88   #[tracing::instrument(skip_all)]
89   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
90     if !self.deleted {
91       blocking(context.pool(), move |conn| {
92         let form = PostUpdateForm::builder().deleted(Some(true)).build();
93         Post::update(conn, self.id, &form)
94       })
95       .await??;
96     }
97     Ok(())
98   }
99
100   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
101   #[tracing::instrument(skip_all)]
102   async fn into_apub(self, context: &LemmyContext) -> Result<Page, LemmyError> {
103     let creator_id = self.creator_id;
104     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
105     let community_id = self.community_id;
106     let community = blocking(context.pool(), move |conn| {
107       Community::read(conn, community_id)
108     })
109     .await??;
110     let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
111
112     let page = Page {
113       kind: PageType::Page,
114       id: ObjectId::new(self.ap_id.clone()),
115       attributed_to: AttributedTo::Lemmy(ObjectId::new(creator.actor_id)),
116       to: vec![community.actor_id.into(), public()],
117       cc: vec![],
118       name: self.name.clone(),
119       content: self.body.as_ref().map(|b| markdown_to_html(b)),
120       media_type: Some(MediaTypeMarkdownOrHtml::Html),
121       source: self.body.clone().map(Source::new),
122       url: self.url.clone().map(|u| u.into()),
123       attachment: self.url.clone().map(Attachment::new).into_iter().collect(),
124       image: self.thumbnail_url.clone().map(ImageObject::new),
125       comments_enabled: Some(!self.locked),
126       sensitive: Some(self.nsfw),
127       stickied: Some(self.stickied),
128       language,
129       published: Some(convert_datetime(self.published)),
130       updated: self.updated.map(convert_datetime),
131     };
132     Ok(page)
133   }
134
135   #[tracing::instrument(skip_all)]
136   async fn verify(
137     page: &Page,
138     expected_domain: &Url,
139     context: &LemmyContext,
140     request_counter: &mut i32,
141   ) -> Result<(), LemmyError> {
142     // We can't verify the domain in case of mod action, because the mod may be on a different
143     // instance from the post author.
144     if !page.is_mod_action(context).await? {
145       verify_domains_match(page.id.inner(), expected_domain)?;
146       verify_is_remote_object(page.id.inner(), context.settings())?;
147     };
148
149     let local_site_data = blocking(context.pool(), fetch_local_site_data).await??;
150
151     let community = page.extract_community(context, request_counter).await?;
152     check_apub_id_valid_with_strictness(
153       page.id.inner(),
154       community.local,
155       &local_site_data,
156       context.settings(),
157     )?;
158     verify_person_in_community(&page.creator()?, &community, context, request_counter).await?;
159
160     let slur_regex = &local_site_opt_to_slur_regex(&local_site_data.local_site);
161     check_slurs(&page.name, slur_regex)?;
162
163     verify_domains_match(page.creator()?.inner(), page.id.inner())?;
164     verify_is_public(&page.to, &page.cc)?;
165     Ok(())
166   }
167
168   #[tracing::instrument(skip_all)]
169   async fn from_apub(
170     page: Page,
171     context: &LemmyContext,
172     request_counter: &mut i32,
173   ) -> Result<ApubPost, LemmyError> {
174     let creator = page
175       .creator()?
176       .dereference(context, local_instance(context), request_counter)
177       .await?;
178     let community = page.extract_community(context, request_counter).await?;
179
180     let form = if !page.is_mod_action(context).await? {
181       let url = if let Some(attachment) = page.attachment.first() {
182         Some(match attachment {
183           // url as sent by Lemmy (new)
184           Attachment::Link(link) => link.href.clone(),
185           Attachment::Image(image) => image.url.clone(),
186         })
187       } else if page.kind == PageType::Video {
188         // we cant display videos directly, so insert a link to external video page
189         Some(page.id.inner().clone())
190       } else {
191         // url sent by lemmy (old)
192         page.url
193       };
194       let (metadata_res, thumbnail_url) = if let Some(url) = &url {
195         fetch_site_data(context.client(), context.settings(), Some(url)).await
196       } else {
197         (None, page.image.map(|i| i.url.into()))
198       };
199       let (embed_title, embed_description, embed_video_url) = metadata_res
200         .map(|u| (u.title, u.description, u.embed_video_url))
201         .unwrap_or_default();
202       let local_site = blocking(context.pool(), LocalSite::read).await?.ok();
203       let slur_regex = &local_site_opt_to_slur_regex(&local_site);
204
205       let body_slurs_removed =
206         read_from_string_or_source_opt(&page.content, &page.media_type, &page.source)
207           .map(|s| remove_slurs(&s, slur_regex));
208       let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?;
209
210       PostInsertForm {
211         name: page.name.clone(),
212         url: url.map(Into::into),
213         body: body_slurs_removed,
214         creator_id: creator.id,
215         community_id: community.id,
216         removed: None,
217         locked: page.comments_enabled.map(|e| !e),
218         published: page.published.map(|u| u.naive_local()),
219         updated: page.updated.map(|u| u.naive_local()),
220         deleted: None,
221         nsfw: page.sensitive,
222         stickied: page.stickied,
223         embed_title,
224         embed_description,
225         embed_video_url,
226         thumbnail_url,
227         ap_id: Some(page.id.clone().into()),
228         local: Some(false),
229         language_id,
230       }
231     } else {
232       // if is mod action, only update locked/stickied fields, nothing else
233       PostInsertForm::builder()
234         .name(page.name.clone())
235         .creator_id(creator.id)
236         .community_id(community.id)
237         .ap_id(Some(page.id.clone().into()))
238         .locked(page.comments_enabled.map(|e| !e))
239         .stickied(page.stickied)
240         .updated(page.updated.map(|u| u.naive_local()))
241         .build()
242     };
243
244     // read existing, local post if any (for generating mod log)
245     let old_post = ObjectId::<ApubPost>::new(page.id.clone())
246       .dereference_local(context)
247       .await;
248
249     let post = blocking(context.pool(), move |conn| Post::create(conn, &form)).await??;
250
251     // write mod log entries for sticky/lock
252     if Page::is_stickied_changed(&old_post, &page.stickied) {
253       let form = ModStickyPostForm {
254         mod_person_id: creator.id,
255         post_id: post.id,
256         stickied: Some(post.stickied),
257       };
258       blocking(context.pool(), move |conn| {
259         ModStickyPost::create(conn, &form)
260       })
261       .await??;
262     }
263     if Page::is_locked_changed(&old_post, &page.comments_enabled) {
264       let form = ModLockPostForm {
265         mod_person_id: creator.id,
266         post_id: post.id,
267         locked: Some(post.locked),
268       };
269       blocking(context.pool(), move |conn| ModLockPost::create(conn, &form)).await??;
270     }
271
272     Ok(post.into())
273   }
274 }
275
276 #[cfg(test)]
277 mod tests {
278   use super::*;
279   use crate::{
280     objects::{
281       community::tests::parse_lemmy_community,
282       person::tests::parse_lemmy_person,
283       post::ApubPost,
284       tests::init_context,
285     },
286     protocol::tests::file_to_json_object,
287   };
288   use lemmy_db_schema::source::site::Site;
289   use serial_test::serial;
290
291   #[actix_rt::test]
292   #[serial]
293   async fn test_parse_lemmy_post() {
294     let context = init_context();
295     let conn = &mut context.pool().get().unwrap();
296     let (person, site) = parse_lemmy_person(&context).await;
297     let community = parse_lemmy_community(&context).await;
298
299     let json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
300     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
301     let mut request_counter = 0;
302     ApubPost::verify(&json, &url, &context, &mut request_counter)
303       .await
304       .unwrap();
305     let post = ApubPost::from_apub(json, &context, &mut request_counter)
306       .await
307       .unwrap();
308
309     assert_eq!(post.ap_id, url.into());
310     assert_eq!(post.name, "Post title");
311     assert!(post.body.is_some());
312     assert_eq!(post.body.as_ref().unwrap().len(), 45);
313     assert!(!post.locked);
314     assert!(post.stickied);
315     assert_eq!(request_counter, 0);
316
317     Post::delete(conn, post.id).unwrap();
318     Person::delete(conn, person.id).unwrap();
319     Community::delete(conn, community.id).unwrap();
320     Site::delete(conn, site.id).unwrap();
321   }
322 }