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