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