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