]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Mark objects as not deleted when received via apub (fixes #2507) (#2528)
[lemmy.git] / crates / apub / src / objects / comment.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   mentions::collect_non_local_mentions,
7   objects::{read_from_string_or_source, verify_is_remote_object},
8   protocol::{
9     objects::{note::Note, LanguageTag},
10     Source,
11   },
12   PostOrComment,
13 };
14 use activitypub_federation::{
15   core::object_id::ObjectId,
16   deser::values::MediaTypeMarkdownOrHtml,
17   traits::ApubObject,
18   utils::verify_domains_match,
19 };
20 use activitystreams_kinds::{object::NoteType, public};
21 use chrono::NaiveDateTime;
22 use lemmy_api_common::utils::{blocking, local_site_opt_to_slur_regex};
23 use lemmy_db_schema::{
24   source::{
25     comment::{Comment, CommentInsertForm, CommentUpdateForm},
26     community::Community,
27     local_site::LocalSite,
28     person::Person,
29     post::Post,
30   },
31   traits::Crud,
32 };
33 use lemmy_utils::{
34   error::LemmyError,
35   utils::{convert_datetime, markdown_to_html, remove_slurs},
36 };
37 use lemmy_websocket::LemmyContext;
38 use std::ops::Deref;
39 use url::Url;
40
41 #[derive(Clone, Debug)]
42 pub struct ApubComment(Comment);
43
44 impl Deref for ApubComment {
45   type Target = Comment;
46   fn deref(&self) -> &Self::Target {
47     &self.0
48   }
49 }
50
51 impl From<Comment> for ApubComment {
52   fn from(c: Comment) -> Self {
53     ApubComment(c)
54   }
55 }
56
57 #[async_trait::async_trait(?Send)]
58 impl ApubObject for ApubComment {
59   type DataType = LemmyContext;
60   type ApubType = Note;
61   type DbType = Comment;
62   type Error = LemmyError;
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         Comment::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         let form = CommentUpdateForm::builder().deleted(Some(true)).build();
87         Comment::update(conn, self.id, &form)
88       })
89       .await??;
90     }
91     Ok(())
92   }
93
94   #[tracing::instrument(skip_all)]
95   async fn into_apub(self, context: &LemmyContext) -> Result<Note, LemmyError> {
96     let creator_id = self.creator_id;
97     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
98
99     let post_id = self.post_id;
100     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
101     let community_id = post.community_id;
102     let community = blocking(context.pool(), move |conn| {
103       Community::read(conn, community_id)
104     })
105     .await??;
106
107     let in_reply_to = if let Some(comment_id) = self.parent_comment_id() {
108       let parent_comment =
109         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
110       ObjectId::<PostOrComment>::new(parent_comment.ap_id)
111     } else {
112       ObjectId::<PostOrComment>::new(post.ap_id)
113     };
114     let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
115     let maa =
116       collect_non_local_mentions(&self, ObjectId::new(community.actor_id), context, &mut 0).await?;
117
118     let note = Note {
119       r#type: NoteType::Note,
120       id: ObjectId::new(self.ap_id.clone()),
121       attributed_to: ObjectId::new(creator.actor_id),
122       to: vec![public()],
123       cc: maa.ccs,
124       content: markdown_to_html(&self.content),
125       media_type: Some(MediaTypeMarkdownOrHtml::Html),
126       source: Some(Source::new(self.content.clone())),
127       in_reply_to,
128       published: Some(convert_datetime(self.published)),
129       updated: self.updated.map(convert_datetime),
130       tag: maa.tags,
131       distinguished: Some(self.distinguished),
132       language,
133     };
134
135     Ok(note)
136   }
137
138   #[tracing::instrument(skip_all)]
139   async fn verify(
140     note: &Note,
141     expected_domain: &Url,
142     context: &LemmyContext,
143     request_counter: &mut i32,
144   ) -> Result<(), LemmyError> {
145     verify_domains_match(note.id.inner(), expected_domain)?;
146     verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
147     verify_is_public(&note.to, &note.cc)?;
148     let (post, _) = note.get_parents(context, request_counter).await?;
149     let community_id = post.community_id;
150     let community = blocking(context.pool(), move |conn| {
151       Community::read(conn, community_id)
152     })
153     .await??;
154     let local_site_data = blocking(context.pool(), fetch_local_site_data).await??;
155
156     check_apub_id_valid_with_strictness(
157       note.id.inner(),
158       community.local,
159       &local_site_data,
160       context.settings(),
161     )?;
162     verify_is_remote_object(note.id.inner(), context.settings())?;
163     verify_person_in_community(
164       &note.attributed_to,
165       &community.into(),
166       context,
167       request_counter,
168     )
169     .await?;
170     if post.locked {
171       return Err(LemmyError::from_message("Post is locked"));
172     }
173     Ok(())
174   }
175
176   /// Converts a `Note` to `Comment`.
177   ///
178   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
179   #[tracing::instrument(skip_all)]
180   async fn from_apub(
181     note: Note,
182     context: &LemmyContext,
183     request_counter: &mut i32,
184   ) -> Result<ApubComment, LemmyError> {
185     let creator = note
186       .attributed_to
187       .dereference(context, local_instance(context), request_counter)
188       .await?;
189     let (post, parent_comment) = note.get_parents(context, request_counter).await?;
190
191     let content = read_from_string_or_source(&note.content, &note.media_type, &note.source);
192
193     let local_site = blocking(context.pool(), LocalSite::read).await?.ok();
194     let slur_regex = &local_site_opt_to_slur_regex(&local_site);
195     let content_slurs_removed = remove_slurs(&content, slur_regex);
196     let language_id = LanguageTag::to_language_id_single(note.language, context.pool()).await?;
197
198     let form = CommentInsertForm {
199       creator_id: creator.id,
200       post_id: post.id,
201       content: content_slurs_removed,
202       removed: None,
203       published: note.published.map(|u| u.naive_local()),
204       updated: note.updated.map(|u| u.naive_local()),
205       deleted: Some(false),
206       ap_id: Some(note.id.into()),
207       distinguished: note.distinguished,
208       local: Some(false),
209       language_id,
210     };
211     let parent_comment_path = parent_comment.map(|t| t.0.path);
212     let comment = blocking(context.pool(), move |conn| {
213       Comment::create(conn, &form, parent_comment_path.as_ref())
214     })
215     .await??;
216     Ok(comment.into())
217   }
218 }
219
220 #[cfg(test)]
221 pub(crate) mod tests {
222   use super::*;
223   use crate::{
224     objects::{
225       community::{tests::parse_lemmy_community, ApubCommunity},
226       instance::ApubSite,
227       person::{tests::parse_lemmy_person, ApubPerson},
228       post::ApubPost,
229       tests::init_context,
230     },
231     protocol::tests::file_to_json_object,
232   };
233   use assert_json_diff::assert_json_include;
234   use html2md::parse_html;
235   use lemmy_db_schema::source::site::Site;
236   use serial_test::serial;
237
238   async fn prepare_comment_test(
239     url: &Url,
240     context: &LemmyContext,
241   ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
242     let (person, site) = parse_lemmy_person(context).await;
243     let community = parse_lemmy_community(context).await;
244     let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
245     ApubPost::verify(&post_json, url, context, &mut 0)
246       .await
247       .unwrap();
248     let post = ApubPost::from_apub(post_json, context, &mut 0)
249       .await
250       .unwrap();
251     (person, community, post, site)
252   }
253
254   fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
255     let conn = &mut context.pool().get().unwrap();
256     Post::delete(conn, data.2.id).unwrap();
257     Community::delete(conn, data.1.id).unwrap();
258     Person::delete(conn, data.0.id).unwrap();
259     Site::delete(conn, data.3.id).unwrap();
260     LocalSite::delete(conn).unwrap();
261   }
262
263   #[actix_rt::test]
264   #[serial]
265   pub(crate) async fn test_parse_lemmy_comment() {
266     let context = init_context();
267     let conn = &mut context.pool().get().unwrap();
268     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
269     let data = prepare_comment_test(&url, &context).await;
270
271     let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
272     let mut request_counter = 0;
273     ApubComment::verify(&json, &url, &context, &mut request_counter)
274       .await
275       .unwrap();
276     let comment = ApubComment::from_apub(json.clone(), &context, &mut request_counter)
277       .await
278       .unwrap();
279
280     assert_eq!(comment.ap_id, url.into());
281     assert_eq!(comment.content.len(), 14);
282     assert!(!comment.local);
283     assert_eq!(request_counter, 0);
284
285     let comment_id = comment.id;
286     let to_apub = comment.into_apub(&context).await.unwrap();
287     assert_json_include!(actual: json, expected: to_apub);
288
289     Comment::delete(conn, comment_id).unwrap();
290     cleanup(data, &context);
291   }
292
293   #[actix_rt::test]
294   #[serial]
295   async fn test_parse_pleroma_comment() {
296     let context = init_context();
297     let conn = &mut context.pool().get().unwrap();
298     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
299     let data = prepare_comment_test(&url, &context).await;
300
301     let pleroma_url =
302       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
303         .unwrap();
304     let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
305     ApubPerson::verify(&person_json, &pleroma_url, &context, &mut 0)
306       .await
307       .unwrap();
308     ApubPerson::from_apub(person_json, &context, &mut 0)
309       .await
310       .unwrap();
311     let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
312     let mut request_counter = 0;
313     ApubComment::verify(&json, &pleroma_url, &context, &mut request_counter)
314       .await
315       .unwrap();
316     let comment = ApubComment::from_apub(json, &context, &mut request_counter)
317       .await
318       .unwrap();
319
320     assert_eq!(comment.ap_id, pleroma_url.into());
321     assert_eq!(comment.content.len(), 64);
322     assert!(!comment.local);
323     assert_eq!(request_counter, 0);
324
325     Comment::delete(conn, comment.id).unwrap();
326     cleanup(data, &context);
327   }
328
329   #[actix_rt::test]
330   #[serial]
331   async fn test_html_to_markdown_sanitize() {
332     let parsed = parse_html("<script></script><b>hello</b>");
333     assert_eq!(parsed, "**hello**");
334   }
335 }