]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
ee131adf7ed0903cea176b9373c3066a94386994
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   check_is_apub_id_valid,
4   mentions::collect_non_local_mentions,
5   protocol::{
6     objects::{
7       note::{Note, SourceCompat},
8       tombstone::Tombstone,
9     },
10     Source,
11   },
12   PostOrComment,
13 };
14 use activitystreams_kinds::{object::NoteType, public};
15 use chrono::NaiveDateTime;
16 use html2md::parse_html;
17 use lemmy_api_common::blocking;
18 use lemmy_apub_lib::{
19   object_id::ObjectId,
20   traits::ApubObject,
21   values::{MediaTypeHtml, MediaTypeMarkdown},
22   verify::verify_domains_match,
23 };
24 use lemmy_db_schema::{
25   source::{
26     comment::{Comment, CommentForm},
27     community::Community,
28     person::Person,
29     post::Post,
30   },
31   traits::Crud,
32 };
33 use lemmy_utils::{
34   utils::{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 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 { 0: 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 TombstoneType = Tombstone;
62
63   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
64     None
65   }
66
67   #[tracing::instrument(skip_all)]
68   async fn read_from_apub_id(
69     object_id: Url,
70     context: &LemmyContext,
71   ) -> Result<Option<Self>, LemmyError> {
72     Ok(
73       blocking(context.pool(), move |conn| {
74         Comment::read_from_apub_id(conn, object_id)
75       })
76       .await??
77       .map(Into::into),
78     )
79   }
80
81   #[tracing::instrument(skip_all)]
82   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
83     if !self.deleted {
84       blocking(context.pool(), move |conn| {
85         Comment::update_deleted(conn, self.id, true)
86       })
87       .await??;
88     }
89     Ok(())
90   }
91
92   #[tracing::instrument(skip_all)]
93   async fn into_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     let community_id = post.community_id;
100     let community = blocking(context.pool(), move |conn| {
101       Community::read(conn, community_id)
102     })
103     .await??;
104
105     let in_reply_to = if let Some(comment_id) = self.parent_id {
106       let parent_comment =
107         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
108       ObjectId::<PostOrComment>::new(parent_comment.ap_id)
109     } else {
110       ObjectId::<PostOrComment>::new(post.ap_id)
111     };
112     let maa =
113       collect_non_local_mentions(&self, ObjectId::new(community.actor_id), context, &mut 0).await?;
114
115     let note = Note {
116       r#type: NoteType::Note,
117       id: ObjectId::new(self.ap_id.clone()),
118       attributed_to: ObjectId::new(creator.actor_id),
119       to: vec![public()],
120       cc: maa.ccs,
121       content: markdown_to_html(&self.content),
122       media_type: Some(MediaTypeHtml::Html),
123       source: SourceCompat::Lemmy(Source {
124         content: self.content.clone(),
125         media_type: MediaTypeMarkdown::Markdown,
126       }),
127       in_reply_to,
128       published: Some(convert_datetime(self.published)),
129       updated: self.updated.map(convert_datetime),
130       tag: maa.tags,
131       unparsed: Default::default(),
132     };
133
134     Ok(note)
135   }
136
137   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
138     Ok(Tombstone::new(self.ap_id.clone().into()))
139   }
140
141   #[tracing::instrument(skip_all)]
142   async fn verify(
143     note: &Note,
144     expected_domain: &Url,
145     context: &LemmyContext,
146     request_counter: &mut i32,
147   ) -> Result<(), LemmyError> {
148     verify_domains_match(note.id.inner(), expected_domain)?;
149     verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
150     verify_is_public(&note.to, &note.cc)?;
151     let (post, _) = note.get_parents(context, request_counter).await?;
152     let community_id = post.community_id;
153     let community = blocking(context.pool(), move |conn| {
154       Community::read(conn, community_id)
155     })
156     .await??;
157     check_is_apub_id_valid(note.id.inner(), community.local, &context.settings())?;
158     verify_person_in_community(
159       &note.attributed_to,
160       &community.into(),
161       context,
162       request_counter,
163     )
164     .await?;
165     if post.locked {
166       return Err(LemmyError::from_message("Post is locked"));
167     }
168     Ok(())
169   }
170
171   /// Converts a `Note` to `Comment`.
172   ///
173   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
174   #[tracing::instrument(skip_all)]
175   async fn from_apub(
176     note: Note,
177     context: &LemmyContext,
178     request_counter: &mut i32,
179   ) -> Result<ApubComment, LemmyError> {
180     let creator = note
181       .attributed_to
182       .dereference(context, context.client(), request_counter)
183       .await?;
184     let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
185
186     let content = if let SourceCompat::Lemmy(source) = &note.source {
187       source.content.clone()
188     } else {
189       parse_html(&note.content)
190     };
191     let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
192
193     let form = CommentForm {
194       creator_id: creator.id,
195       post_id: post.id,
196       parent_id: parent_comment_id,
197       content: content_slurs_removed,
198       removed: None,
199       read: None,
200       published: note.published.map(|u| u.naive_local()),
201       updated: note.updated.map(|u| u.naive_local()),
202       deleted: None,
203       ap_id: Some(note.id.into()),
204       local: Some(false),
205     };
206     let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
207     Ok(comment.into())
208   }
209 }
210
211 #[cfg(test)]
212 pub(crate) mod tests {
213   use super::*;
214   use crate::objects::{
215     community::{tests::parse_lemmy_community, ApubCommunity},
216     person::{tests::parse_lemmy_person, ApubPerson},
217     post::ApubPost,
218     tests::{file_to_json_object, init_context},
219   };
220   use assert_json_diff::assert_json_include;
221   use lemmy_apub_lib::activity_queue::create_activity_queue;
222   use serial_test::serial;
223
224   async fn prepare_comment_test(
225     url: &Url,
226     context: &LemmyContext,
227   ) -> (ApubPerson, ApubCommunity, ApubPost) {
228     let person = parse_lemmy_person(context).await;
229     let community = parse_lemmy_community(context).await;
230     let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
231     ApubPost::verify(&post_json, url, context, &mut 0)
232       .await
233       .unwrap();
234     let post = ApubPost::from_apub(post_json, context, &mut 0)
235       .await
236       .unwrap();
237     (person, community, post)
238   }
239
240   fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
241     Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
242     Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
243     Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
244   }
245
246   #[actix_rt::test]
247   #[serial]
248   pub(crate) async fn test_parse_lemmy_comment() {
249     let client = reqwest::Client::new().into();
250     let manager = create_activity_queue(client);
251     let context = init_context(manager.queue_handle().clone());
252     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
253     let data = prepare_comment_test(&url, &context).await;
254
255     let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
256     let mut request_counter = 0;
257     ApubComment::verify(&json, &url, &context, &mut request_counter)
258       .await
259       .unwrap();
260     let comment = ApubComment::from_apub(json.clone(), &context, &mut request_counter)
261       .await
262       .unwrap();
263
264     assert_eq!(comment.ap_id, url.into());
265     assert_eq!(comment.content.len(), 14);
266     assert!(!comment.local);
267     assert_eq!(request_counter, 0);
268
269     let comment_id = comment.id;
270     let to_apub = comment.into_apub(&context).await.unwrap();
271     assert_json_include!(actual: json, expected: to_apub);
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_parse_pleroma_comment() {
280     let client = reqwest::Client::new().into();
281     let manager = create_activity_queue(client);
282     let context = init_context(manager.queue_handle().clone());
283     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
284     let data = prepare_comment_test(&url, &context).await;
285
286     let pleroma_url =
287       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
288         .unwrap();
289     let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
290     ApubPerson::verify(&person_json, &pleroma_url, &context, &mut 0)
291       .await
292       .unwrap();
293     ApubPerson::from_apub(person_json, &context, &mut 0)
294       .await
295       .unwrap();
296     let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
297     let mut request_counter = 0;
298     ApubComment::verify(&json, &pleroma_url, &context, &mut request_counter)
299       .await
300       .unwrap();
301     let comment = ApubComment::from_apub(json, &context, &mut request_counter)
302       .await
303       .unwrap();
304
305     assert_eq!(comment.ap_id, pleroma_url.into());
306     assert_eq!(comment.content.len(), 64);
307     assert!(!comment.local);
308     assert_eq!(request_counter, 0);
309
310     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
311     cleanup(data, &context);
312   }
313
314   #[actix_rt::test]
315   #[serial]
316   async fn test_html_to_markdown_sanitize() {
317     let parsed = parse_html("<script></script><b>hello</b>");
318     assert_eq!(parsed, "**hello**");
319   }
320 }