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