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