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