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