]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Check if post or comment are deleted first. Fixes #1864 (#1867)
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use std::ops::Deref;
2
3 use activitystreams::{object::kind::NoteType, public};
4 use anyhow::anyhow;
5 use chrono::NaiveDateTime;
6 use html2md::parse_html;
7 use url::Url;
8
9 use lemmy_api_common::blocking;
10 use lemmy_apub_lib::{
11   traits::ApubObject,
12   values::{MediaTypeHtml, MediaTypeMarkdown},
13 };
14 use lemmy_db_schema::{
15   source::{
16     comment::{Comment, CommentForm},
17     community::Community,
18     person::Person,
19     post::Post,
20   },
21   traits::Crud,
22 };
23 use lemmy_utils::{
24   utils::{convert_datetime, remove_slurs},
25   LemmyError,
26 };
27 use lemmy_websocket::LemmyContext;
28
29 use crate::{
30   activities::verify_person_in_community,
31   check_is_apub_id_valid,
32   fetcher::object_id::ObjectId,
33   protocol::{
34     objects::{
35       note::{Note, SourceCompat},
36       tombstone::Tombstone,
37     },
38     Source,
39   },
40   PostOrComment,
41 };
42 use lemmy_utils::utils::markdown_to_html;
43
44 #[derive(Clone, Debug)]
45 pub struct ApubComment(Comment);
46
47 impl Deref for ApubComment {
48   type Target = Comment;
49   fn deref(&self) -> &Self::Target {
50     &self.0
51   }
52 }
53
54 impl From<Comment> for ApubComment {
55   fn from(c: Comment) -> Self {
56     ApubComment { 0: c }
57   }
58 }
59
60 #[async_trait::async_trait(?Send)]
61 impl ApubObject for ApubComment {
62   type DataType = LemmyContext;
63   type ApubType = Note;
64   type TombstoneType = Tombstone;
65
66   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
67     None
68   }
69
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         Comment::read_from_apub_id(conn, object_id)
77       })
78       .await??
79       .map(Into::into),
80     )
81   }
82
83   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
84     if !self.deleted {
85       blocking(context.pool(), move |conn| {
86         Comment::update_deleted(conn, self.id, true)
87       })
88       .await??;
89     }
90     Ok(())
91   }
92
93   async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
94     let creator_id = self.creator_id;
95     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
96
97     let post_id = self.post_id;
98     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
99
100     let in_reply_to = if let Some(comment_id) = self.parent_id {
101       let parent_comment =
102         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
103       ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
104     } else {
105       ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
106     };
107
108     let note = Note {
109       r#type: NoteType::Note,
110       id: self.ap_id.to_owned().into_inner(),
111       attributed_to: ObjectId::new(creator.actor_id),
112       to: vec![public()],
113       content: markdown_to_html(&self.content),
114       media_type: Some(MediaTypeHtml::Html),
115       source: SourceCompat::Lemmy(Source {
116         content: self.content.clone(),
117         media_type: MediaTypeMarkdown::Markdown,
118       }),
119       in_reply_to,
120       published: Some(convert_datetime(self.published)),
121       updated: self.updated.map(convert_datetime),
122       unparsed: Default::default(),
123     };
124
125     Ok(note)
126   }
127
128   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
129     Ok(Tombstone::new(
130       NoteType::Note,
131       self.updated.unwrap_or(self.published),
132     ))
133   }
134
135   /// Converts a `Note` to `Comment`.
136   ///
137   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
138   async fn from_apub(
139     note: &Note,
140     context: &LemmyContext,
141     expected_domain: &Url,
142     request_counter: &mut i32,
143   ) -> Result<ApubComment, LemmyError> {
144     let ap_id = Some(note.id(expected_domain)?.clone().into());
145     let creator = note
146       .attributed_to
147       .dereference(context, request_counter)
148       .await?;
149     let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
150     let community_id = post.community_id;
151     let community = blocking(context.pool(), move |conn| {
152       Community::read(conn, community_id)
153     })
154     .await??;
155     check_is_apub_id_valid(&note.id, community.local, &context.settings())?;
156     verify_person_in_community(
157       &note.attributed_to,
158       &community.into(),
159       context,
160       request_counter,
161     )
162     .await?;
163     if post.locked {
164       return Err(anyhow!("Post is locked").into());
165     }
166
167     let content = if let SourceCompat::Lemmy(source) = &note.source {
168       source.content.clone()
169     } else {
170       parse_html(&note.content)
171     };
172     let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
173
174     let form = CommentForm {
175       creator_id: creator.id,
176       post_id: post.id,
177       parent_id: parent_comment_id,
178       content: content_slurs_removed,
179       removed: None,
180       read: None,
181       published: note.published.map(|u| u.to_owned().naive_local()),
182       updated: note.updated.map(|u| u.to_owned().naive_local()),
183       deleted: None,
184       ap_id,
185       local: Some(false),
186     };
187     let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
188     Ok(comment.into())
189   }
190 }
191
192 #[cfg(test)]
193 pub(crate) mod tests {
194   use super::*;
195   use crate::objects::{
196     community::{tests::parse_lemmy_community, ApubCommunity},
197     person::{tests::parse_lemmy_person, ApubPerson},
198     post::ApubPost,
199     tests::{file_to_json_object, init_context},
200   };
201   use assert_json_diff::assert_json_include;
202   use serial_test::serial;
203
204   async fn prepare_comment_test(
205     url: &Url,
206     context: &LemmyContext,
207   ) -> (ApubPerson, ApubCommunity, ApubPost) {
208     let person = parse_lemmy_person(context).await;
209     let community = parse_lemmy_community(context).await;
210     let post_json = file_to_json_object("assets/lemmy/objects/page.json");
211     let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
212       .await
213       .unwrap();
214     (person, community, post)
215   }
216
217   fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
218     Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
219     Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
220     Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
221   }
222
223   #[actix_rt::test]
224   #[serial]
225   pub(crate) async fn test_parse_lemmy_comment() {
226     let context = init_context();
227     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
228     let data = prepare_comment_test(&url, &context).await;
229
230     let json = file_to_json_object("assets/lemmy/objects/note.json");
231     let mut request_counter = 0;
232     let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
233       .await
234       .unwrap();
235
236     assert_eq!(comment.ap_id.clone().into_inner(), url);
237     assert_eq!(comment.content.len(), 14);
238     assert!(!comment.local);
239     assert_eq!(request_counter, 0);
240
241     let to_apub = comment.to_apub(&context).await.unwrap();
242     assert_json_include!(actual: json, expected: to_apub);
243
244     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
245     cleanup(data, &context);
246   }
247
248   #[actix_rt::test]
249   #[serial]
250   async fn test_parse_pleroma_comment() {
251     let context = init_context();
252     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
253     let data = prepare_comment_test(&url, &context).await;
254
255     let pleroma_url =
256       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
257         .unwrap();
258     let person_json = file_to_json_object("assets/pleroma/objects/person.json");
259     ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
260       .await
261       .unwrap();
262     let json = file_to_json_object("assets/pleroma/objects/note.json");
263     let mut request_counter = 0;
264     let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
265       .await
266       .unwrap();
267
268     assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
269     assert_eq!(comment.content.len(), 64);
270     assert!(!comment.local);
271     assert_eq!(request_counter, 0);
272
273     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
274     cleanup(data, &context);
275   }
276
277   #[actix_rt::test]
278   #[serial]
279   async fn test_html_to_markdown_sanitize() {
280     let parsed = parse_html("<script></script><b>hello</b>");
281     assert_eq!(parsed, "**hello**");
282   }
283 }