]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Replace TypedBuilder with Default in update forms (#3814)
[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 {
82         deleted: Some(true),
83         ..Default::default()
84       };
85       Comment::update(&mut context.pool(), self.id, &form).await?;
86     }
87     Ok(())
88   }
89
90   #[tracing::instrument(skip_all)]
91   async fn into_json(self, context: &Data<Self::DataType>) -> Result<Note, LemmyError> {
92     let creator_id = self.creator_id;
93     let creator = Person::read(&mut context.pool(), creator_id).await?;
94
95     let post_id = self.post_id;
96     let post = Post::read(&mut context.pool(), post_id).await?;
97     let community_id = post.community_id;
98     let community = Community::read(&mut 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(&mut context.pool(), comment_id).await?;
102       parent_comment.ap_id.into()
103     } else {
104       post.ap_id.into()
105     };
106     let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
107     let maa = collect_non_local_mentions(&self, community.actor_id.clone().into(), context).await?;
108
109     let note = Note {
110       r#type: NoteType::Note,
111       id: self.ap_id.clone().into(),
112       attributed_to: creator.actor_id.into(),
113       to: vec![public()],
114       cc: maa.ccs,
115       content: markdown_to_html(&self.content),
116       media_type: Some(MediaTypeMarkdownOrHtml::Html),
117       source: Some(Source::new(self.content.clone())),
118       in_reply_to,
119       published: Some(convert_datetime(self.published)),
120       updated: self.updated.map(convert_datetime),
121       tag: maa.tags,
122       distinguished: Some(self.distinguished),
123       language,
124       audience: Some(community.actor_id.into()),
125     };
126
127     Ok(note)
128   }
129
130   #[tracing::instrument(skip_all)]
131   async fn verify(
132     note: &Note,
133     expected_domain: &Url,
134     context: &Data<LemmyContext>,
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 community = note.community(context).await?;
140
141     check_apub_id_valid_with_strictness(note.id.inner(), community.local, context).await?;
142     verify_is_remote_object(note.id.inner(), context.settings())?;
143     verify_person_in_community(&note.attributed_to, &community, context).await?;
144     let (post, _) = note.get_parents(context).await?;
145     if post.locked {
146       return Err(LemmyErrorType::PostIsLocked)?;
147     }
148     Ok(())
149   }
150
151   /// Converts a `Note` to `Comment`.
152   ///
153   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
154   #[tracing::instrument(skip_all)]
155   async fn from_json(note: Note, context: &Data<LemmyContext>) -> Result<ApubComment, LemmyError> {
156     let creator = note.attributed_to.dereference(context).await?;
157     let (post, parent_comment) = note.get_parents(context).await?;
158
159     let content = read_from_string_or_source(&note.content, &note.media_type, &note.source);
160
161     let local_site = LocalSite::read(&mut context.pool()).await.ok();
162     let slur_regex = &local_site_opt_to_slur_regex(&local_site);
163     let content = remove_slurs(&content, slur_regex);
164     let content = sanitize_html(&content);
165     let language_id =
166       LanguageTag::to_language_id_single(note.language, &mut context.pool()).await?;
167
168     let form = CommentInsertForm {
169       creator_id: creator.id,
170       post_id: post.id,
171       content,
172       removed: None,
173       published: note.published.map(|u| u.naive_local()),
174       updated: note.updated.map(|u| u.naive_local()),
175       deleted: Some(false),
176       ap_id: Some(note.id.into()),
177       distinguished: note.distinguished,
178       local: Some(false),
179       language_id,
180     };
181     let parent_comment_path = parent_comment.map(|t| t.0.path);
182     let comment = Comment::create(&mut context.pool(), &form, parent_comment_path.as_ref()).await?;
183     Ok(comment.into())
184   }
185 }
186
187 #[cfg(test)]
188 pub(crate) mod tests {
189   #![allow(clippy::unwrap_used)]
190   #![allow(clippy::indexing_slicing)]
191
192   use super::*;
193   use crate::{
194     objects::{
195       community::{tests::parse_lemmy_community, ApubCommunity},
196       instance::ApubSite,
197       person::{tests::parse_lemmy_person, ApubPerson},
198       post::ApubPost,
199       tests::init_context,
200     },
201     protocol::tests::file_to_json_object,
202   };
203   use assert_json_diff::assert_json_include;
204   use html2md::parse_html;
205   use lemmy_db_schema::source::site::Site;
206   use serial_test::serial;
207
208   async fn prepare_comment_test(
209     url: &Url,
210     context: &Data<LemmyContext>,
211   ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
212     // use separate counter so this doesnt affect tests
213     let context2 = context.reset_request_count();
214     let (person, site) = parse_lemmy_person(&context2).await;
215     let community = parse_lemmy_community(&context2).await;
216     let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
217     ApubPost::verify(&post_json, url, &context2).await.unwrap();
218     let post = ApubPost::from_json(post_json, &context2).await.unwrap();
219     (person, community, post, site)
220   }
221
222   async fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
223     Post::delete(&mut context.pool(), data.2.id).await.unwrap();
224     Community::delete(&mut context.pool(), data.1.id)
225       .await
226       .unwrap();
227     Person::delete(&mut context.pool(), data.0.id)
228       .await
229       .unwrap();
230     Site::delete(&mut context.pool(), data.3.id).await.unwrap();
231     LocalSite::delete(&mut context.pool()).await.unwrap();
232   }
233
234   #[tokio::test]
235   #[serial]
236   pub(crate) async fn test_parse_lemmy_comment() {
237     let context = init_context().await;
238     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
239     let data = prepare_comment_test(&url, &context).await;
240
241     let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
242     ApubComment::verify(&json, &url, &context).await.unwrap();
243     let comment = ApubComment::from_json(json.clone(), &context)
244       .await
245       .unwrap();
246
247     assert_eq!(comment.ap_id, url.into());
248     assert_eq!(comment.content.len(), 14);
249     assert!(!comment.local);
250     assert_eq!(context.request_count(), 0);
251
252     let comment_id = comment.id;
253     let to_apub = comment.into_json(&context).await.unwrap();
254     assert_json_include!(actual: json, expected: to_apub);
255
256     Comment::delete(&mut context.pool(), comment_id)
257       .await
258       .unwrap();
259     cleanup(data, &context).await;
260   }
261
262   #[tokio::test]
263   #[serial]
264   async fn test_parse_pleroma_comment() {
265     let context = init_context().await;
266     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
267     let data = prepare_comment_test(&url, &context).await;
268
269     let pleroma_url =
270       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
271         .unwrap();
272     let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
273     ApubPerson::verify(&person_json, &pleroma_url, &context)
274       .await
275       .unwrap();
276     ApubPerson::from_json(person_json, &context).await.unwrap();
277     let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
278     ApubComment::verify(&json, &pleroma_url, &context)
279       .await
280       .unwrap();
281     let comment = ApubComment::from_json(json, &context).await.unwrap();
282
283     assert_eq!(comment.ap_id, pleroma_url.into());
284     assert_eq!(comment.content.len(), 64);
285     assert!(!comment.local);
286     assert_eq!(context.request_count(), 1);
287
288     Comment::delete(&mut context.pool(), comment.id)
289       .await
290       .unwrap();
291     cleanup(data, &context).await;
292   }
293
294   #[tokio::test]
295   #[serial]
296   async fn test_html_to_markdown_sanitize() {
297     let parsed = parse_html("<script></script><b>hello</b>");
298     assert_eq!(parsed, "**hello**");
299   }
300 }