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