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