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