2 activities::{verify_is_public, verify_person_in_community},
3 context::lemmy_context,
4 fetcher::object_id::ObjectId,
5 objects::{create_tombstone, person::ApubPerson, post::ApubPost, Source},
10 chrono::NaiveDateTime,
11 object::{kind::NoteType, Tombstone},
12 primitives::OneOrMany,
17 use chrono::{DateTime, FixedOffset};
18 use html2md::parse_html;
19 use lemmy_api_common::blocking;
21 traits::{ApubObject, FromApub, ToApub},
22 values::{MediaTypeHtml, MediaTypeMarkdown},
23 verify::verify_domains_match,
25 use lemmy_db_schema::{
28 comment::{Comment, CommentForm},
37 utils::{convert_datetime, remove_slurs},
40 use lemmy_websocket::LemmyContext;
41 use serde::{Deserialize, Serialize};
42 use serde_with::skip_serializing_none;
46 #[skip_serializing_none]
47 #[derive(Clone, Debug, Deserialize, Serialize)]
48 #[serde(rename_all = "camelCase")]
50 #[serde(rename = "@context")]
51 context: OneOrMany<AnyBase>,
54 pub(crate) attributed_to: ObjectId<ApubPerson>,
55 /// Indicates that the object is publicly readable. Unlike [`Post.to`], this one doesn't contain
56 /// the community ID, as it would be incompatible with Pleroma (and we can get the community from
57 /// the post in [`in_reply_to`]).
60 media_type: Option<MediaTypeHtml>,
62 in_reply_to: ObjectId<PostOrComment>,
63 published: Option<DateTime<FixedOffset>>,
64 updated: Option<DateTime<FixedOffset>>,
69 /// Pleroma puts a raw string in the source, so we have to handle it here for deserialization to work
70 #[derive(Clone, Debug, Deserialize, Serialize)]
71 #[serde(rename_all = "camelCase")]
79 pub(crate) fn id_unchecked(&self) -> &Url {
82 pub(crate) fn id(&self, expected_domain: &Url) -> Result<&Url, LemmyError> {
83 verify_domains_match(&self.id, expected_domain)?;
87 pub(crate) async fn get_parents(
89 context: &LemmyContext,
90 request_counter: &mut i32,
91 ) -> Result<(ApubPost, Option<CommentId>), LemmyError> {
92 // Fetch parent comment chain in a box, otherwise it can cause a stack overflow.
93 let parent = Box::pin(
96 .dereference(context, request_counter)
99 match parent.deref() {
100 PostOrComment::Post(p) => {
101 // Workaround because I cant figure out how to get the post out of the box (and we dont
102 // want to stackoverflow in a deep comment hierarchy).
104 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
105 Ok((post.into(), None))
107 PostOrComment::Comment(c) => {
108 let post_id = c.post_id;
109 let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
110 Ok((post.into(), Some(c.id)))
115 pub(crate) async fn verify(
117 context: &LemmyContext,
118 request_counter: &mut i32,
119 ) -> Result<(), LemmyError> {
120 let (post, _parent_comment_id) = self.get_parents(context, request_counter).await?;
121 let community_id = post.community_id;
122 let community = blocking(context.pool(), move |conn| {
123 Community::read(conn, community_id)
128 return Err(anyhow!("Post is locked").into());
130 verify_domains_match(self.attributed_to.inner(), &self.id)?;
131 verify_person_in_community(
133 &ObjectId::new(community.actor_id),
138 verify_is_public(&self.to)?;
143 #[derive(Clone, Debug)]
144 pub struct ApubComment(Comment);
146 impl Deref for ApubComment {
147 type Target = Comment;
148 fn deref(&self) -> &Self::Target {
153 impl From<Comment> for ApubComment {
154 fn from(c: Comment) -> Self {
159 #[async_trait::async_trait(?Send)]
160 impl ApubObject for ApubComment {
161 type DataType = LemmyContext;
163 fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
167 async fn read_from_apub_id(
169 context: &LemmyContext,
170 ) -> Result<Option<Self>, LemmyError> {
172 blocking(context.pool(), move |conn| {
173 Comment::read_from_apub_id(conn, object_id)
180 async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
181 blocking(context.pool(), move |conn| {
182 Comment::update_deleted(conn, self.id, true)
189 #[async_trait::async_trait(?Send)]
190 impl ToApub for ApubComment {
191 type ApubType = Note;
192 type TombstoneType = Tombstone;
193 type DataType = DbPool;
195 async fn to_apub(&self, pool: &DbPool) -> Result<Note, LemmyError> {
196 let creator_id = self.creator_id;
197 let creator = blocking(pool, move |conn| Person::read(conn, creator_id)).await??;
199 let post_id = self.post_id;
200 let post = blocking(pool, move |conn| Post::read(conn, post_id)).await??;
202 let in_reply_to = if let Some(comment_id) = self.parent_id {
203 let parent_comment = blocking(pool, move |conn| Comment::read(conn, comment_id)).await??;
204 ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
206 ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
210 context: lemmy_context(),
211 r#type: NoteType::Note,
212 id: self.ap_id.to_owned().into_inner(),
213 attributed_to: ObjectId::new(creator.actor_id),
215 content: self.content.clone(),
216 media_type: Some(MediaTypeHtml::Html),
217 source: SourceCompat::Lemmy(Source {
218 content: self.content.clone(),
219 media_type: MediaTypeMarkdown::Markdown,
222 published: Some(convert_datetime(self.published)),
223 updated: self.updated.map(convert_datetime),
224 unparsed: Default::default(),
230 fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
233 self.ap_id.to_owned().into(),
240 #[async_trait::async_trait(?Send)]
241 impl FromApub for ApubComment {
242 type ApubType = Note;
243 type DataType = LemmyContext;
245 /// Converts a `Note` to `Comment`.
247 /// If the parent community, post and comment(s) are not known locally, these are also fetched.
250 context: &LemmyContext,
251 expected_domain: &Url,
252 request_counter: &mut i32,
253 ) -> Result<ApubComment, LemmyError> {
254 let ap_id = Some(note.id(expected_domain)?.clone().into());
257 .dereference(context, request_counter)
259 let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
261 return Err(anyhow!("Post is locked").into());
264 let content = if let SourceCompat::Lemmy(source) = ¬e.source {
265 source.content.clone()
267 parse_html(¬e.content)
269 let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
271 let form = CommentForm {
272 creator_id: creator.id,
274 parent_id: parent_comment_id,
275 content: content_slurs_removed,
278 published: note.published.map(|u| u.to_owned().naive_local()),
279 updated: note.updated.map(|u| u.to_owned().naive_local()),
284 let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
292 use crate::objects::{
293 community::ApubCommunity,
294 tests::{file_to_json_object, init_context},
296 use assert_json_diff::assert_json_include;
297 use serial_test::serial;
299 async fn prepare_comment_test(
301 context: &LemmyContext,
302 ) -> (ApubPerson, ApubCommunity, ApubPost) {
303 let person_json = file_to_json_object("assets/lemmy-person.json");
304 let person = ApubPerson::from_apub(&person_json, context, url, &mut 0)
307 let community_json = file_to_json_object("assets/lemmy-community.json");
308 let community = ApubCommunity::from_apub(&community_json, context, url, &mut 0)
311 let post_json = file_to_json_object("assets/lemmy-post.json");
312 let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
315 (person, community, post)
318 fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
319 Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
320 Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
321 Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
326 async fn test_parse_lemmy_comment() {
327 let context = init_context();
328 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
329 let data = prepare_comment_test(&url, &context).await;
331 let json = file_to_json_object("assets/lemmy-comment.json");
332 let mut request_counter = 0;
333 let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
337 assert_eq!(comment.ap_id.clone().into_inner(), url);
338 assert_eq!(comment.content.len(), 14);
339 assert!(!comment.local);
340 assert_eq!(request_counter, 0);
342 let to_apub = comment.to_apub(context.pool()).await.unwrap();
343 assert_json_include!(actual: json, expected: to_apub);
345 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
346 cleanup(data, &context);
351 async fn test_parse_pleroma_comment() {
352 let context = init_context();
353 let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
354 let data = prepare_comment_test(&url, &context).await;
357 Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
359 let person_json = file_to_json_object("assets/pleroma-person.json");
360 ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
363 let json = file_to_json_object("assets/pleroma-comment.json");
364 let mut request_counter = 0;
365 let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
369 assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
370 assert_eq!(comment.content.len(), 64);
371 assert!(!comment.local);
372 assert_eq!(request_counter, 0);
374 Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
375 cleanup(data, &context);
380 async fn test_html_to_markdown_sanitize() {
381 let parsed = parse_html("<script></script><b>hello</b>");
382 assert_eq!(parsed, "**hello**");