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