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