]> Untitled Git - lemmy.git/blobdiff - crates/apub/src/objects/comment.rs
First pass at adding comment trees. (#2362)
[lemmy.git] / crates / apub / src / objects / comment.rs
index b5f72ca38b7f04a2c69dc57665264c8a1ef08cbf..88b08746c15ea6507ccbd7067f38118900364328 100644 (file)
@@ -1,16 +1,21 @@
-use std::ops::Deref;
-
-use activitystreams::{object::kind::NoteType, public};
-use anyhow::anyhow;
-use chrono::NaiveDateTime;
-use html2md::parse_html;
-use url::Url;
-
-use lemmy_api_common::blocking;
-use lemmy_apub_lib::{
+use crate::{
+  activities::{verify_is_public, verify_person_in_community},
+  check_apub_id_valid_with_strictness,
+  local_instance,
+  mentions::collect_non_local_mentions,
+  objects::{read_from_string_or_source, verify_is_remote_object},
+  protocol::{objects::note::Note, Source},
+  PostOrComment,
+};
+use activitypub_federation::{
+  core::object_id::ObjectId,
+  deser::values::MediaTypeMarkdownOrHtml,
   traits::ApubObject,
-  values::{MediaTypeHtml, MediaTypeMarkdown},
+  utils::verify_domains_match,
 };
+use activitystreams_kinds::{object::NoteType, public};
+use chrono::NaiveDateTime;
+use lemmy_api_common::utils::blocking;
 use lemmy_db_schema::{
   source::{
     comment::{Comment, CommentForm},
@@ -21,23 +26,12 @@ use lemmy_db_schema::{
   traits::Crud,
 };
 use lemmy_utils::{
-  utils::{convert_datetime, remove_slurs},
-  LemmyError,
+  error::LemmyError,
+  utils::{convert_datetime, markdown_to_html, remove_slurs},
 };
 use lemmy_websocket::LemmyContext;
-
-use crate::{
-  activities::verify_person_in_community,
-  fetcher::object_id::ObjectId,
-  protocol::{
-    objects::{
-      note::{Note, SourceCompat},
-      tombstone::Tombstone,
-    },
-    Source,
-  },
-  PostOrComment,
-};
+use std::ops::Deref;
+use url::Url;
 
 #[derive(Clone, Debug)]
 pub struct ApubComment(Comment);
@@ -51,7 +45,7 @@ impl Deref for ApubComment {
 
 impl From<Comment> for ApubComment {
   fn from(c: Comment) -> Self {
-    ApubComment { 0: c }
+    ApubComment(c)
   }
 }
 
@@ -59,12 +53,14 @@ impl From<Comment> for ApubComment {
 impl ApubObject for ApubComment {
   type DataType = LemmyContext;
   type ApubType = Note;
-  type TombstoneType = Tombstone;
+  type DbType = Comment;
+  type Error = LemmyError;
 
   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
     None
   }
 
+  #[tracing::instrument(skip_all)]
   async fn read_from_apub_id(
     object_id: Url,
     context: &LemmyContext,
@@ -78,76 +74,76 @@ impl ApubObject for ApubComment {
     )
   }
 
+  #[tracing::instrument(skip_all)]
   async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
-    blocking(context.pool(), move |conn| {
-      Comment::update_deleted(conn, self.id, true)
-    })
-    .await??;
+    if !self.deleted {
+      blocking(context.pool(), move |conn| {
+        Comment::update_deleted(conn, self.id, true)
+      })
+      .await??;
+    }
     Ok(())
   }
 
-  async fn to_apub(&self, context: &LemmyContext) -> Result<Note, LemmyError> {
+  #[tracing::instrument(skip_all)]
+  async fn into_apub(self, context: &LemmyContext) -> Result<Note, LemmyError> {
     let creator_id = self.creator_id;
     let creator = blocking(context.pool(), move |conn| Person::read(conn, creator_id)).await??;
 
     let post_id = self.post_id;
     let post = blocking(context.pool(), move |conn| Post::read(conn, post_id)).await??;
+    let community_id = post.community_id;
+    let community = blocking(context.pool(), move |conn| {
+      Community::read(conn, community_id)
+    })
+    .await??;
 
-    let in_reply_to = if let Some(comment_id) = self.parent_id {
+    let in_reply_to = if let Some(comment_id) = self.parent_comment_id() {
       let parent_comment =
         blocking(context.pool(), move |conn| Comment::read(conn, comment_id)).await??;
-      ObjectId::<PostOrComment>::new(parent_comment.ap_id.into_inner())
+      ObjectId::<PostOrComment>::new(parent_comment.ap_id)
     } else {
-      ObjectId::<PostOrComment>::new(post.ap_id.into_inner())
+      ObjectId::<PostOrComment>::new(post.ap_id)
     };
+    let maa =
+      collect_non_local_mentions(&self, ObjectId::new(community.actor_id), context, &mut 0).await?;
 
     let note = Note {
       r#type: NoteType::Note,
-      id: self.ap_id.to_owned().into_inner(),
+      id: ObjectId::new(self.ap_id.clone()),
       attributed_to: ObjectId::new(creator.actor_id),
       to: vec![public()],
-      content: self.content.clone(),
-      media_type: Some(MediaTypeHtml::Html),
-      source: SourceCompat::Lemmy(Source {
-        content: self.content.clone(),
-        media_type: MediaTypeMarkdown::Markdown,
-      }),
+      cc: maa.ccs,
+      content: markdown_to_html(&self.content),
+      media_type: Some(MediaTypeMarkdownOrHtml::Html),
+      source: Some(Source::new(self.content.clone())),
       in_reply_to,
       published: Some(convert_datetime(self.published)),
       updated: self.updated.map(convert_datetime),
-      unparsed: Default::default(),
+      tag: maa.tags,
     };
 
     Ok(note)
   }
 
-  fn to_tombstone(&self) -> Result<Tombstone, LemmyError> {
-    Ok(Tombstone::new(
-      NoteType::Note,
-      self.updated.unwrap_or(self.published),
-    ))
-  }
-
-  /// Converts a `Note` to `Comment`.
-  ///
-  /// If the parent community, post and comment(s) are not known locally, these are also fetched.
-  async fn from_apub(
+  #[tracing::instrument(skip_all)]
+  async fn verify(
     note: &Note,
-    context: &LemmyContext,
     expected_domain: &Url,
+    context: &LemmyContext,
     request_counter: &mut i32,
-  ) -> Result<ApubComment, LemmyError> {
-    let ap_id = Some(note.id(expected_domain)?.clone().into());
-    let creator = note
-      .attributed_to
-      .dereference(context, request_counter)
-      .await?;
-    let (post, parent_comment_id) = note.get_parents(context, request_counter).await?;
+  ) -> Result<(), LemmyError> {
+    verify_domains_match(note.id.inner(), expected_domain)?;
+    verify_domains_match(note.attributed_to.inner(), note.id.inner())?;
+    verify_is_public(&note.to, &note.cc)?;
+    let (post, _) = note.get_parents(context, request_counter).await?;
     let community_id = post.community_id;
     let community = blocking(context.pool(), move |conn| {
       Community::read(conn, community_id)
     })
     .await??;
+    check_apub_id_valid_with_strictness(note.id.inner(), community.local, context.settings())?;
+    verify_is_remote_object(note.id.inner(), context.settings())?;
     verify_person_in_community(
       &note.attributed_to,
       &community.into(),
@@ -156,30 +152,45 @@ impl ApubObject for ApubComment {
     )
     .await?;
     if post.locked {
-      return Err(anyhow!("Post is locked").into());
+      return Err(LemmyError::from_message("Post is locked"));
     }
+    Ok(())
+  }
 
-    let content = if let SourceCompat::Lemmy(source) = &note.source {
-      source.content.clone()
-    } else {
-      parse_html(&note.content)
-    };
+  /// Converts a `Note` to `Comment`.
+  ///
+  /// If the parent community, post and comment(s) are not known locally, these are also fetched.
+  #[tracing::instrument(skip_all)]
+  async fn from_apub(
+    note: Note,
+    context: &LemmyContext,
+    request_counter: &mut i32,
+  ) -> Result<ApubComment, LemmyError> {
+    let creator = note
+      .attributed_to
+      .dereference(context, local_instance(context), request_counter)
+      .await?;
+    let (post, parent_comment) = note.get_parents(context, request_counter).await?;
+
+    let content = read_from_string_or_source(&note.content, &note.media_type, &note.source);
     let content_slurs_removed = remove_slurs(&content, &context.settings().slur_regex());
 
     let form = CommentForm {
       creator_id: creator.id,
       post_id: post.id,
-      parent_id: parent_comment_id,
       content: content_slurs_removed,
       removed: None,
-      read: None,
-      published: note.published.map(|u| u.to_owned().naive_local()),
-      updated: note.updated.map(|u| u.to_owned().naive_local()),
+      published: note.published.map(|u| u.naive_local()),
+      updated: note.updated.map(|u| u.naive_local()),
       deleted: None,
-      ap_id,
+      ap_id: Some(note.id.into()),
       local: Some(false),
     };
-    let comment = blocking(context.pool(), move |conn| Comment::upsert(conn, &form)).await??;
+    let parent_comment_path = parent_comment.map(|t| t.0.path);
+    let comment = blocking(context.pool(), move |conn| {
+      Comment::create(conn, &form, parent_comment_path.as_ref())
+    })
+    .await??;
     Ok(comment.into())
   }
 }
@@ -187,32 +198,42 @@ impl ApubObject for ApubComment {
 #[cfg(test)]
 pub(crate) mod tests {
   use super::*;
-  use crate::objects::{
-    community::{tests::parse_lemmy_community, ApubCommunity},
-    person::{tests::parse_lemmy_person, ApubPerson},
-    post::ApubPost,
-    tests::{file_to_json_object, init_context},
+  use crate::{
+    objects::{
+      community::{tests::parse_lemmy_community, ApubCommunity},
+      instance::ApubSite,
+      person::{tests::parse_lemmy_person, ApubPerson},
+      post::ApubPost,
+      tests::init_context,
+    },
+    protocol::tests::file_to_json_object,
   };
   use assert_json_diff::assert_json_include;
+  use html2md::parse_html;
+  use lemmy_db_schema::source::site::Site;
   use serial_test::serial;
 
   async fn prepare_comment_test(
     url: &Url,
     context: &LemmyContext,
-  ) -> (ApubPerson, ApubCommunity, ApubPost) {
-    let person = parse_lemmy_person(context).await;
+  ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
+    let (person, site) = parse_lemmy_person(context).await;
     let community = parse_lemmy_community(context).await;
-    let post_json = file_to_json_object("assets/lemmy/objects/page.json");
-    let post = ApubPost::from_apub(&post_json, context, url, &mut 0)
+    let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
+    ApubPost::verify(&post_json, url, context, &mut 0)
       .await
       .unwrap();
-    (person, community, post)
+    let post = ApubPost::from_apub(post_json, context, &mut 0)
+      .await
+      .unwrap();
+    (person, community, post, site)
   }
 
-  fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost), context: &LemmyContext) {
+  fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
     Post::delete(&*context.pool().get().unwrap(), data.2.id).unwrap();
     Community::delete(&*context.pool().get().unwrap(), data.1.id).unwrap();
     Person::delete(&*context.pool().get().unwrap(), data.0.id).unwrap();
+    Site::delete(&*context.pool().get().unwrap(), data.3.id).unwrap();
   }
 
   #[actix_rt::test]
@@ -222,21 +243,25 @@ pub(crate) mod tests {
     let url = Url::parse("https://enterprise.lemmy.ml/comment/38741").unwrap();
     let data = prepare_comment_test(&url, &context).await;
 
-    let json = file_to_json_object("assets/lemmy/objects/note.json");
+    let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
     let mut request_counter = 0;
-    let comment = ApubComment::from_apub(&json, &context, &url, &mut request_counter)
+    ApubComment::verify(&json, &url, &context, &mut request_counter)
+      .await
+      .unwrap();
+    let comment = ApubComment::from_apub(json.clone(), &context, &mut request_counter)
       .await
       .unwrap();
 
-    assert_eq!(comment.ap_id.clone().into_inner(), url);
+    assert_eq!(comment.ap_id, url.into());
     assert_eq!(comment.content.len(), 14);
     assert!(!comment.local);
     assert_eq!(request_counter, 0);
 
-    let to_apub = comment.to_apub(&context).await.unwrap();
+    let comment_id = comment.id;
+    let to_apub = comment.into_apub(&context).await.unwrap();
     assert_json_include!(actual: json, expected: to_apub);
 
-    Comment::delete(&*context.pool().get().unwrap(), comment.id).unwrap();
+    Comment::delete(&*context.pool().get().unwrap(), comment_id).unwrap();
     cleanup(data, &context);
   }
 
@@ -250,17 +275,23 @@ pub(crate) mod tests {
     let pleroma_url =
       Url::parse("https://queer.hacktivis.me/objects/8d4973f4-53de-49cd-8c27-df160e16a9c2")
         .unwrap();
-    let person_json = file_to_json_object("assets/pleroma/objects/person.json");
-    ApubPerson::from_apub(&person_json, &context, &pleroma_url, &mut 0)
+    let person_json = file_to_json_object("assets/pleroma/objects/person.json").unwrap();
+    ApubPerson::verify(&person_json, &pleroma_url, &context, &mut 0)
       .await
       .unwrap();
-    let json = file_to_json_object("assets/pleroma/objects/note.json");
+    ApubPerson::from_apub(person_json, &context, &mut 0)
+      .await
+      .unwrap();
+    let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
     let mut request_counter = 0;
-    let comment = ApubComment::from_apub(&json, &context, &pleroma_url, &mut request_counter)
+    ApubComment::verify(&json, &pleroma_url, &context, &mut request_counter)
+      .await
+      .unwrap();
+    let comment = ApubComment::from_apub(json, &context, &mut request_counter)
       .await
       .unwrap();
 
-    assert_eq!(comment.ap_id.clone().into_inner(), pleroma_url);
+    assert_eq!(comment.ap_id, pleroma_url.into());
     assert_eq!(comment.content.len(), 64);
     assert!(!comment.local);
     assert_eq!(request_counter, 0);