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