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