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