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