]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/post.rs
Check if post or comment are deleted first. Fixes #1864 (#1867)
[lemmy.git] / crates / apub / src / objects / post.rs
1 use crate::{
2   activities::verify_person_in_community,
3   check_is_apub_id_valid,
4   fetcher::object_id::ObjectId,
5   protocol::{
6     objects::{page::Page, tombstone::Tombstone},
7     ImageObject,
8     Source,
9   },
10 };
11 use activitystreams::{
12   object::kind::{ImageType, PageType},
13   public,
14 };
15 use chrono::NaiveDateTime;
16 use lemmy_api_common::blocking;
17 use lemmy_apub_lib::{
18   traits::ApubObject,
19   values::{MediaTypeHtml, MediaTypeMarkdown},
20 };
21 use lemmy_db_schema::{
22   self,
23   source::{
24     community::Community,
25     person::Person,
26     post::{Post, PostForm},
27   },
28   traits::Crud,
29 };
30 use lemmy_utils::{
31   request::fetch_site_data,
32   utils::{convert_datetime, markdown_to_html, remove_slurs},
33   LemmyError,
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 { 0: 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 TombstoneType = Tombstone;
60
61   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
62     None
63   }
64
65   async fn read_from_apub_id(
66     object_id: Url,
67     context: &LemmyContext,
68   ) -> Result<Option<Self>, LemmyError> {
69     Ok(
70       blocking(context.pool(), move |conn| {
71         Post::read_from_apub_id(conn, object_id)
72       })
73       .await??
74       .map(Into::into),
75     )
76   }
77
78   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
79     if !self.deleted {
80       blocking(context.pool(), move |conn| {
81         Post::update_deleted(conn, self.id, true)
82       })
83       .await??;
84     }
85     Ok(())
86   }
87
88   // Turn a Lemmy post into an ActivityPub page that can be sent out over the network.
89   async fn to_apub(&self, context: &LemmyContext) -> Result<Page, LemmyError> {
90     let creator_id = self.creator_id;
91     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
92     let community_id = self.community_id;
93     let community = blocking(context.pool(), move |conn| {
94       Community::read(conn, community_id)
95     })
96     .await??;
97
98     let source = self.body.clone().map(|body| Source {
99       content: body,
100       media_type: MediaTypeMarkdown::Markdown,
101     });
102     let image = self.thumbnail_url.clone().map(|thumb| ImageObject {
103       kind: ImageType::Image,
104       url: thumb.into(),
105     });
106
107     let page = Page {
108       r#type: PageType::Page,
109       id: self.ap_id.clone().into(),
110       attributed_to: ObjectId::new(creator.actor_id),
111       to: vec![community.actor_id.into(), public()],
112       name: self.name.clone(),
113       content: self.body.as_ref().map(|b| markdown_to_html(b)),
114       media_type: Some(MediaTypeHtml::Html),
115       source,
116       url: self.url.clone().map(|u| u.into()),
117       image,
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       unparsed: Default::default(),
124     };
125     Ok(page)
126   }
127
128   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
129     Ok(Tombstone::new(
130       PageType::Page,
131       self.updated.unwrap_or(self.published),
132     ))
133   }
134
135   async fn from_apub(
136     page: &Page,
137     context: &LemmyContext,
138     expected_domain: &Url,
139     request_counter: &mut i32,
140   ) -> Result<ApubPost, LemmyError> {
141     // We can't verify the domain in case of mod action, because the mod may be on a different
142     // instance from the post author.
143     let ap_id = if page.is_mod_action(context).await? {
144       page.id_unchecked()
145     } else {
146       page.id(expected_domain)?
147     };
148     let ap_id = Some(ap_id.clone().into());
149     let creator = page
150       .attributed_to
151       .dereference(context, request_counter)
152       .await?;
153     let community = page.extract_community(context, request_counter).await?;
154     check_is_apub_id_valid(&page.id, community.local, &context.settings())?;
155     verify_person_in_community(&page.attributed_to, &community, context, request_counter).await?;
156
157     let thumbnail_url: Option<Url> = page.image.clone().map(|i| i.url);
158     let (metadata_res, pictrs_thumbnail) = if let Some(url) = &page.url {
159       fetch_site_data(context.client(), &context.settings(), Some(url)).await
160     } else {
161       (None, thumbnail_url)
162     };
163     let (embed_title, embed_description, embed_html) = metadata_res
164       .map(|u| (u.title, u.description, u.html))
165       .unwrap_or((None, None, None));
166
167     let body_slurs_removed = page
168       .source
169       .as_ref()
170       .map(|s| remove_slurs(&s.content, &context.settings().slur_regex()));
171     let form = PostForm {
172       name: page.name.clone(),
173       url: page.url.clone().map(|u| u.into()),
174       body: body_slurs_removed,
175       creator_id: creator.id,
176       community_id: community.id,
177       removed: None,
178       locked: page.comments_enabled.map(|e| !e),
179       published: page.published.map(|u| u.naive_local()),
180       updated: page.updated.map(|u| u.naive_local()),
181       deleted: None,
182       nsfw: page.sensitive,
183       stickied: page.stickied,
184       embed_title,
185       embed_description,
186       embed_html,
187       thumbnail_url: pictrs_thumbnail.map(|u| u.into()),
188       ap_id,
189       local: Some(false),
190     };
191     let post = blocking(context.pool(), move |conn| Post::upsert(conn, &form)).await??;
192     Ok(post.into())
193   }
194 }
195
196 #[cfg(test)]
197 mod tests {
198   use super::*;
199   use crate::objects::{
200     community::tests::parse_lemmy_community,
201     person::tests::parse_lemmy_person,
202     post::ApubPost,
203     tests::{file_to_json_object, init_context},
204   };
205   use serial_test::serial;
206
207   #[actix_rt::test]
208   #[serial]
209   async fn test_parse_lemmy_post() {
210     let context = init_context();
211     let community = parse_lemmy_community(&context).await;
212     let person = parse_lemmy_person(&context).await;
213
214     let json = file_to_json_object("assets/lemmy/objects/page.json");
215     let url = Url::parse("https://enterprise.lemmy.ml/post/55143").unwrap();
216     let mut request_counter = 0;
217     let post = ApubPost::from_apub(&json, &context, &url, &mut request_counter)
218       .await
219       .unwrap();
220
221     assert_eq!(post.ap_id.clone().into_inner(), url);
222     assert_eq!(post.name, "Post title");
223     assert!(post.body.is_some());
224     assert_eq!(post.body.as_ref().unwrap().len(), 45);
225     assert!(!post.locked);
226     assert!(post.stickied);
227     assert_eq!(request_counter, 0);
228
229     Post::delete(&*context.pool().get().unwrap(), post.id).unwrap();
230     Person::delete(&*context.pool().get().unwrap(), person.id).unwrap();
231     Community::delete(&*context.pool().get().unwrap(), community.id).unwrap();
232   }
233 }