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