]> Untitled Git - lemmy.git/blob - crates/apub/src/objects/comment.rs
Move apub test files into tree structure
[lemmy.git] / crates / apub / src / objects / comment.rs
1 use std::ops::Deref;
2
3 use activitystreams::{object::kind::NoteType, public};
4 use anyhow::anyhow;
5 use chrono::NaiveDateTime;
6 use html2md::parse_html;
7 use url::Url;
8
9 use lemmy_api_common::blocking;
10 use lemmy_apub_lib::{
11   traits::ApubObject,
12   values::{MediaTypeHtml, MediaTypeMarkdown},
13 };
14 use lemmy_db_schema::{
15   source::{
16     comment::{Comment, CommentForm},
17     community::Community,
18     person::Person,
19     post::Post,
20   },
21   traits::Crud,
22 };
23 use lemmy_utils::{
24   utils::{convert_datetime, remove_slurs},
25   LemmyError,
26 };
27 use lemmy_websocket::LemmyContext;
28
29 use crate::{
30   activities::verify_person_in_community,
31   fetcher::object_id::ObjectId,
32   protocol::{
33     objects::{
34       note::{Note, SourceCompat},
35       tombstone::Tombstone,
36     },
37     Source,
38   },
39   PostOrComment,
40 };
41
42 #[derive(Clone, Debug)]
43 pub struct ApubComment(Comment);
44
45 impl Deref for ApubComment {
46   type Target = Comment;
47   fn deref(&self) -> &Self::Target {
48     &self.0
49   }
50 }
51
52 impl From<Comment> for ApubComment {
53   fn from(c: Comment) -> Self {
54     ApubComment { 0: c }
55   }
56 }
57
58 #[async_trait::async_trait(?Send)]
59 impl ApubObject for ApubComment {
60   type DataType = LemmyContext;
61   type ApubType = Note;
62   type TombstoneType = Tombstone;
63
64   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
65     None
66   }
67
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   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
82     blocking(context.pool(), move |conn| {
83       Comment::update_deleted(conn, self.id, true)
84     })
85     .await??;
86     Ok(())
87   }
88
89   async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
90     let creator_id = self.creator_id;
91     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
92
93     let post_id = self.post_id;
94     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
95
96     let in_reply_to = if let Some(comment_id) = self.parent_id {
97       let parent_comment =
98         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
99       ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
100     } else {
101       ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
102     };
103
104     let note = Note {
105       r#type: NoteType::Note,
106       id: self.ap_id.to_owned().into_inner(),
107       attributed_to: ObjectId::new(creator.actor_id),
108       to: vec![public()],
109       content: self.content.clone(),
110       media_type: Some(MediaTypeHtml::Html),
111       source: SourceCompat::Lemmy(Source {
112         content: self.content.clone(),
113         media_type: MediaTypeMarkdown::Markdown,
114       }),
115       in_reply_to,
116       published: Some(convert_datetime(self.published)),
117       updated: self.updated.map(convert_datetime),
118       unparsed: Default::default(),
119     };
120
121     Ok(note)
122   }
123
124   fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
125     Ok(Tombstone::new(
126       NoteType::Note,
127       self.updated.unwrap_or(self.published),
128     ))
129   }
130
131   /// Converts a `Note` to `Comment`.
132   ///
133   /// If the parent community, post and comment(s) are not known locally, these are also fetched.
134   async fn from_apub(
135     note: &Note,
136     context: &LemmyContext,
137     expected_domain: &Url,
138     request_counter: &mut i32,
139   ) -> Result<ApubComment, LemmyError> {
140     let ap_id = Some(note.id(expected_domain)?.clone().into());
141     let creator = note
142       .attributed_to
143       .dereference(context, request_counter)
144       .await?;
145     let (post, parent_comment_id) = 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     verify_person_in_community(
152       &note.attributed_to,
153       &community.into(),
154       context,
155       request_counter,
156     )
157     .await?;
158     if post.locked {
159       return Err(anyhow!("Post is locked").into());
160     }
161
162     let content = if let SourceCompat::Lemmy(source) = &note.source {
163       source.content.clone()
164     } else {
165       parse_html(&note.content)
166     };
167     let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
168
169     let form = CommentForm {
170       creator_id: creator.id,
171       post_id: post.id,
172       parent_id: parent_comment_id,
173       content: content_slurs_removed,
174       removed: None,
175       read: None,
176       published: note.published.map(|u| u.to_owned().naive_local()),
177       updated: note.updated.map(|u| u.to_owned().naive_local()),
178       deleted: None,
179       ap_id,
180       local: Some(false),
181     };
182     let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
183     Ok(comment.into())
184   }
185 }
186
187 #[cfg(test)]
188 pub(crate) mod tests {
189   use super::*;
190   use crate::objects::{
191     community::ApubCommunity,
192     person::ApubPerson,
193     post::ApubPost,
194     tests::{file_to_json_object, init_context},
195   };
196   use assert_json_diff::assert_json_include;
197   use serial_test::serial;
198
199   pub(crate) async fn prepare_comment_test(
200     url: &Url,
201     context: &LemmyContext,
202   ) -> (ApubPerson, ApubCommunity, ApubPost) {
203     let person_json = file_to_json_object("assets/lemmy/objects/person.json");
204     let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
205       .await
206       .unwrap();
207     let community_json = file_to_json_object("assets/lemmy/objects/group.json");
208     let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
209       .await
210       .unwrap();
211     let post_json = file_to_json_object("assets/lemmy/objects/page.json");
212     let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
213       .await
214       .unwrap();
215     (person, community, post)
216   }
217
218   fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
219     Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
220     Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
221     Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
222   }
223
224   #[actix_rt::test]
225   #[serial]
226   pub(crate) async fn test_parse_lemmy_comment() {
227     let context = init_context();
228     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
229     let data = prepare_comment_test(&url, &context).await;
230
231     let json = file_to_json_object("assets/lemmy/objects/note.json");
232     let mut request_counter = 0;
233     let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
234       .await
235       .unwrap();
236
237     assert_eq!(comment.ap_id.clone().into_inner(), url);
238     assert_eq!(comment.content.len(), 14);
239     assert!(!comment.local);
240     assert_eq!(request_counter, 0);
241
242     let to_apub = comment.to_apub(&context).await.unwrap();
243     assert_json_include!(actual: json, expected: to_apub);
244
245     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
246     cleanup(data, &context);
247   }
248
249   #[actix_rt::test]
250   #[serial]
251   async fn test_parse_pleroma_comment() {
252     let context = init_context();
253     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
254     let data = prepare_comment_test(&url, &context).await;
255
256     let pleroma_url =
257       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
258         .unwrap();
259     let person_json = file_to_json_object("assets/pleroma/objects/person.json");
260     ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
261       .await
262       .unwrap();
263     let json = file_to_json_object("assets/pleroma/objects/note.json");
264     let mut request_counter = 0;
265     let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
266       .await
267       .unwrap();
268
269     assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
270     assert_eq!(comment.content.len(), 64);
271     assert!(!comment.local);
272     assert_eq!(request_counter, 0);
273
274     Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
275     cleanup(data, &context);
276   }
277
278   #[actix_rt::test]
279   #[serial]
280   async fn test_html_to_markdown_sanitize() {
281     let parsed = parse_html("<script></script><b>hello</b>");
282     assert_eq!(parsed, "**hello**");
283   }
284 }