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