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