]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
335605a6c834eca1157f43585078d607faea0fce
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use crate::{
2   activities::{verify_is_public, verify_person_in_community},
3   context::lemmy_context,
4   fetcher::object_id::ObjectId,
5   objects::{
6     community::ApubCommunity,
7     person::ApubPerson,
8     post::ApubPost,
9     tombstone::Tombstone,
10     Source,
11   },
12   PostOrComment,
13 };
14 use activitystreams::{
15   base::AnyBase,
16   chrono::NaiveDateTime,
17   object::kind::NoteType,
18   primitives::OneOrMany,
19   public,
20   unparsed::Unparsed,
21 };
22 use anyhow::anyhow;
23 use chrono::{DateTime, FixedOffset};
24 use html2md::parse_html;
25 use lemmy_api_common::blocking;
26 use lemmy_apub_lib::{
27   traits::ApubObject,
28   values::{MediaTypeHtml, MediaTypeMarkdown},
29   verify::verify_domains_match,
30 };
31 use lemmy_db_schema::{
32   newtypes::CommentId,
33   source::{
34     comment::{Comment, CommentForm},
35     community::Community,
36     person::Person,
37     post::Post,
38   },
39   traits::Crud,
40 };
41 use lemmy_utils::{
42   utils::{convert_datetime, remove_slurs},
43   LemmyError,
44 };
45 use lemmy_websocket::LemmyContext;
46 use serde::{Deserialize, Serialize};
47 use serde_with::skip_serializing_none;
48 use std::ops::Deref;
49 use url::Url;
50
51 #[skip_serializing_none]
52 #[derive(Clone, Debug, Deserialize, Serialize)]
53 #[serde(rename_all = "camelCase")]
54 pub struct Note {
55   /// Necessary to make this optional to make Pleroma Create/Note work.
56   /// TODO: change this so that context is not defined in the struct itself, but added in activity
57   ///       queue and http handlers
58   #[serde(rename = "@context")]
59   context: Option<OneOrMany<AnyBase>>,
60   r#type: NoteType,
61   id: Url,
62   pub(crate) attributed_to: ObjectId<ApubPerson>,
63   /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
64   /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
65   /// the post in [`in_reply_to`]).
66   to: Vec<Url>,
67   content: String,
68   media_type: Option<MediaTypeHtml>,
69   source: SourceCompat,
70   in_reply_to: ObjectId<PostOrComment>,
71   published: Option<DateTime<FixedOffset>>,
72   updated: Option<DateTime<FixedOffset>>,
73   #[serde(flatten)]
74   unparsed: Unparsed,
75 }
76
77 /// Pleroma puts a raw string in the source, so we have to handle it here for deserialization to work
78 #[derive(Clone, Debug, Deserialize, Serialize)]
79 #[serde(rename_all = "camelCase")]
80 #[serde(untagged)]
81 enum SourceCompat {
82   Lemmy(Source),
83   Pleroma(String),
84 }
85
86 impl Note {
87   pub(crate) fn id_unchecked(&self) -> &Url {
88     &self.id
89   }
90   pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
91     verify_domains_match(&self.id, expected_domain)?;
92     Ok(&self.id)
93   }
94
95   pub(crate) async fn get_parents(
96     &self,
97     context: &LemmyContext,
98     request_counter: &mut i32,
99   ) -> Result<(ApubPost, Option<CommentId>), LemmyError> {
100     // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
101     let parent = Box::pin(
102       self
103         .in_reply_to
104         .dereference(context, request_counter)
105         .await?,
106     );
107     match parent.deref() {
108       PostOrComment::Post(p) => {
109         // Workaround because I cant figure out how to get the post out of the box (and we dont
110         // want to stackoverflow in a deep comment hierarchy).
111         let post_id = p.id;
112         let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
113         Ok((post.into(), None))
114       }
115       PostOrComment::Comment(c) => {
116         let post_id = c.post_id;
117         let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
118         Ok((post.into(), Some(c.id)))
119       }
120     }
121   }
122
123   pub(crate) async fn verify(
124     &self,
125     context: &LemmyContext,
126     request_counter: &mut i32,
127   ) -> Result<(), LemmyError> {
128     let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
129     let community_id = post.community_id;
130     let community: ApubCommunity = blocking(context.pool(), move |conn| {
131       Community::read(conn, community_id)
132     })
133     .await??
134     .into();
135
136     if post.locked {
137       return Err(anyhow!("Post is locked").into());
138     }
139     verify_domains_match(self.attributed_to.inner(), &self.id)?;
140     verify_person_in_community(&self.attributed_to, &community, context, request_counter).await?;
141     verify_is_public(&self.to)?;
142     Ok(())
143   }
144 }
145
146 #[derive(Clone, Debug)]
147 pub struct ApubComment(Comment);
148
149 impl Deref for ApubComment {
150   type Target = Comment;
151   fn deref(&self) -> &Self::Target {
152     &self.0
153   }
154 }
155
156 impl From<Comment> for ApubComment {
157   fn from(c: Comment) -> Self {
158     ApubComment { 0: c }
159   }
160 }
161
162 #[async_trait::async_trait(?Send)]
163 impl ApubObject for ApubComment {
164   type DataType = LemmyContext;
165   type ApubType = Note;
166   type TombstoneType = Tombstone;
167
168   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
169     None
170   }
171
172   async fn read_from_apub_id(
173     object_id: Url,
174     context: &LemmyContext,
175   ) -> Result<Option<Self>, LemmyError> {
176     Ok(
177       blocking(context.pool(), move |conn| {
178         Comment::read_from_apub_id(conn, object_id)
179       })
180       .await??
181       .map(Into::into),
182     )
183   }
184
185   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
186     blocking(context.pool(), move |conn| {
187       Comment::update_deleted(conn, self.id, true)
188     })
189     .await??;
190     Ok(())
191   }
192
193   async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
194     let creator_id = self.creator_id;
195     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
196
197     let post_id = self.post_id;
198     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
199
200     let in_reply_to = if let Some(comment_id) = self.parent_id {
201       let parent_comment =
202         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
203       ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
204     } else {
205       ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
206     };
207
208     let note = Note {
209       context: Some(lemmy_context()),
210       r#type: NoteType::Note,
211       id: self.ap_id.to_owned().into_inner(),
212       attributed_to: ObjectId::new(creator.actor_id),
213       to: vec![public()],
214       content: self.content.clone(),
215       media_type: Some(MediaTypeHtml::Html),
216       source: SourceCompat::Lemmy(Source {
217         content: self.content.clone(),
218         media_type: MediaTypeMarkdown::Markdown,
219       }),
220       in_reply_to,
221       published: Some(convert_datetime(self.published)),
222       updated: self.updated.map(convert_datetime),
223       unparsed: Default::default(),
224     };
225
226     Ok(note)
227   }
228
229   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
230     Ok(Tombstone::new(
231       NoteType::Note,
232       self.updated.unwrap_or(self.published),
233     ))
234   }
235
236   /// Converts a `Note` to `Comment`.
237   ///
238   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
239   async fn from_apub(
240     note: &Note,
241     context: &LemmyContext,
242     expected_domain: &Url,
243     request_counter: &mut i32,
244   ) -> Result<ApubComment, LemmyError> {
245     let ap_id = Some(note.id(expected_domain)?.clone().into());
246     let creator = note
247       .attributed_to
248       .dereference(context, request_counter)
249       .await?;
250     let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
251     let community_id = post.community_id;
252     let community = blocking(context.pool(), move |conn| {
253       Community::read(conn, community_id)
254     })
255     .await??;
256     verify_person_in_community(
257       &note.attributed_to,
258       &community.into(),
259       context,
260       request_counter,
261     )
262     .await?;
263     if post.locked {
264       return Err(anyhow!("Post is locked").into());
265     }
266
267     let content = if let SourceCompat::Lemmy(source) = &note.source {
268       source.content.clone()
269     } else {
270       parse_html(&note.content)
271     };
272     let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
273
274     let form = CommentForm {
275       creator_id: creator.id,
276       post_id: post.id,
277       parent_id: parent_comment_id,
278       content: content_slurs_removed,
279       removed: None,
280       read: None,
281       published: note.published.map(|u| u.to_owned().naive_local()),
282       updated: note.updated.map(|u| u.to_owned().naive_local()),
283       deleted: None,
284       ap_id,
285       local: Some(false),
286     };
287     let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
288     Ok(comment.into())
289   }
290 }
291
292 #[cfg(test)]
293 pub(crate) mod tests {
294   use super::*;
295   use crate::objects::{
296     community::ApubCommunity,
297     tests::{file_to_json_object, init_context},
298   };
299   use assert_json_diff::assert_json_include;
300   use serial_test::serial;
301
302   pub(crate) async fn prepare_comment_test(
303     url: &Url,
304     context: &LemmyContext,
305   ) -> (ApubPerson, ApubCommunity, ApubPost) {
306     let person_json = file_to_json_object("assets/lemmy-person.json");
307     let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
308       .await
309       .unwrap();
310     let community_json = file_to_json_object("assets/lemmy-community.json");
311     let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
312       .await
313       .unwrap();
314     let post_json = file_to_json_object("assets/lemmy-post.json");
315     let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
316       .await
317       .unwrap();
318     (person, community, post)
319   }
320
321   fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
322     Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
323     Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
324     Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
325   }
326
327   #[actix_rt::test]
328   #[serial]
329   pub(crate) async fn test_parse_lemmy_comment() {
330     let context = init_context();
331     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
332     let data = prepare_comment_test(&url, &context).await;
333
334     let json = file_to_json_object("assets/lemmy-comment.json");
335     let mut request_counter = 0;
336     let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
337       .await
338       .unwrap();
339
340     assert_eq!(comment.ap_id.clone().into_inner(), url);
341     assert_eq!(comment.content.len(), 14);
342     assert!(!comment.local);
343     assert_eq!(request_counter, 0);
344
345     let to_apub = comment.to_apub(&context).await.unwrap();
346     assert_json_include!(actual: json, expected: to_apub);
347
348     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
349     cleanup(data, &context);
350   }
351
352   #[actix_rt::test]
353   #[serial]
354   async fn test_parse_pleroma_comment() {
355     let context = init_context();
356     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
357     let data = prepare_comment_test(&url, &context).await;
358
359     let pleroma_url =
360       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
361         .unwrap();
362     let person_json = file_to_json_object("assets/pleroma-person.json");
363     ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
364       .await
365       .unwrap();
366     let json = file_to_json_object("assets/pleroma-comment.json");
367     let mut request_counter = 0;
368     let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
369       .await
370       .unwrap();
371
372     assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
373     assert_eq!(comment.content.len(), 64);
374     assert!(!comment.local);
375     assert_eq!(request_counter, 0);
376
377     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
378     cleanup(data, &context);
379   }
380
381   #[actix_rt::test]
382   #[serial]
383   async fn test_html_to_markdown_sanitize() {
384     let parsed = parse_html("<script></script><b>hello</b>");
385     assert_eq!(parsed, "**hello**");
386   }
387 }