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