]> Untitled Git - lemmy.git/blobdiff - crates/apub/src/objects/comment.rs
Cache & Optimize Woodpecker CI (#3450)
[lemmy.git] / crates / apub / src / objects / comment.rs
index a4c6ef737f018bf3828e35bc8a394b504101b7b2..2954de0968cab4af742a911b161cfabfdb889c00 100644 (file)
@@ -1,8 +1,6 @@
 use crate::{
   activities::{verify_is_public, verify_person_in_community},
   check_apub_id_valid_with_strictness,
-  fetch_local_site_data,
-  local_instance,
   mentions::collect_non_local_mentions,
   objects::{read_from_string_or_source, verify_is_remote_object},
   protocol::{
@@ -10,17 +8,15 @@ use crate::{
     InCommunity,
     Source,
   },
-  PostOrComment,
 };
 use activitypub_federation::{
-  core::object_id::ObjectId,
-  deser::values::MediaTypeMarkdownOrHtml,
-  traits::ApubObject,
-  utils::verify_domains_match,
+  config::Data,
+  kinds::{object::NoteType, public},
+  protocol::{values::MediaTypeMarkdownOrHtml, verification::verify_domains_match},
+  traits::Object,
 };
-use activitystreams_kinds::{object::NoteType, public};
 use chrono::NaiveDateTime;
-use lemmy_api_common::{utils::local_site_opt_to_slur_regex, LemmyContext};
+use lemmy_api_common::{context::LemmyContext, utils::local_site_opt_to_slur_regex};
 use lemmy_db_schema::{
   source::{
     comment::{Comment, CommentInsertForm, CommentUpdateForm},
@@ -32,14 +28,14 @@ use lemmy_db_schema::{
   traits::Crud,
 };
 use lemmy_utils::{
-  error::LemmyError,
-  utils::{convert_datetime, markdown_to_html, remove_slurs},
+  error::{LemmyError, LemmyErrorType},
+  utils::{markdown::markdown_to_html, slurs::remove_slurs, time::convert_datetime},
 };
 use std::ops::Deref;
 use url::Url;
 
 #[derive(Clone, Debug)]
-pub struct ApubComment(Comment);
+pub struct ApubComment(pub(crate) Comment);
 
 impl Deref for ApubComment {
   type Target = Comment;
@@ -54,11 +50,10 @@ impl From<Comment> for ApubComment {
   }
 }
 
-#[async_trait::async_trait(?Send)]
-impl ApubObject for ApubComment {
+#[async_trait::async_trait]
+impl Object for ApubComment {
   type DataType = LemmyContext;
-  type ApubType = Note;
-  type DbType = Comment;
+  type Kind = Note;
   type Error = LemmyError;
 
   fn last_refreshed_at(&self) -> Option<NaiveDateTime> {
@@ -66,55 +61,49 @@ impl ApubObject for ApubComment {
   }
 
   #[tracing::instrument(skip_all)]
-  async fn read_from_apub_id(
+  async fn read_from_id(
     object_id: Url,
-    context: &LemmyContext,
+    context: &Data<Self::DataType>,
   ) -> Result<Option<Self>, LemmyError> {
     Ok(
-      Comment::read_from_apub_id(context.pool(), object_id)
+      Comment::read_from_apub_id(&mut context.pool(), object_id)
         .await?
         .map(Into::into),
     )
   }
 
   #[tracing::instrument(skip_all)]
-  async fn delete(self, context: &LemmyContext) -> Result<(), LemmyError> {
+  async fn delete(self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
     if !self.deleted {
       let form = CommentUpdateForm::builder().deleted(Some(true)).build();
-      Comment::update(context.pool(), self.id, &form).await?;
+      Comment::update(&mut context.pool(), self.id, &form).await?;
     }
     Ok(())
   }
 
   #[tracing::instrument(skip_all)]
-  async fn into_apub(self, context: &LemmyContext) -> Result<Note, LemmyError> {
+  async fn into_json(self, context: &Data<Self::DataType>) -> Result<Note, LemmyError> {
     let creator_id = self.creator_id;
-    let creator = Person::read(context.pool(), creator_id).await?;
+    let creator = Person::read(&mut context.pool(), creator_id).await?;
 
     let post_id = self.post_id;
-    let post = Post::read(context.pool(), post_id).await?;
+    let post = Post::read(&mut context.pool(), post_id).await?;
     let community_id = post.community_id;
-    let community = Community::read(context.pool(), community_id).await?;
+    let community = Community::read(&mut context.pool(), community_id).await?;
 
     let in_reply_to = if let Some(comment_id) = self.parent_comment_id() {
-      let parent_comment = Comment::read(context.pool(), comment_id).await?;
-      ObjectId::<PostOrComment>::new(parent_comment.ap_id)
+      let parent_comment = Comment::read(&mut context.pool(), comment_id).await?;
+      parent_comment.ap_id.into()
     } else {
-      ObjectId::<PostOrComment>::new(post.ap_id)
+      post.ap_id.into()
     };
-    let language = LanguageTag::new_single(self.language_id, context.pool()).await?;
-    let maa = collect_non_local_mentions(
-      &self,
-      ObjectId::new(community.actor_id.clone()),
-      context,
-      &mut 0,
-    )
-    .await?;
+    let language = LanguageTag::new_single(self.language_id, &mut context.pool()).await?;
+    let maa = collect_non_local_mentions(&self, community.actor_id.clone().into(), context).await?;
 
     let note = Note {
       r#type: NoteType::Note,
-      id: ObjectId::new(self.ap_id.clone()),
-      attributed_to: ObjectId::new(creator.actor_id),
+      id: self.ap_id.clone().into(),
+      attributed_to: creator.actor_id.into(),
       to: vec![public()],
       cc: maa.ccs,
       content: markdown_to_html(&self.content),
@@ -126,7 +115,7 @@ impl ApubObject for ApubComment {
       tag: maa.tags,
       distinguished: Some(self.distinguished),
       language,
-      audience: Some(ObjectId::new(community.actor_id)),
+      audience: Some(community.actor_id.into()),
     };
 
     Ok(note)
@@ -136,26 +125,19 @@ impl ApubObject for ApubComment {
   async fn verify(
     note: &Note,
     expected_domain: &Url,
-    context: &LemmyContext,
-    request_counter: &mut i32,
+    context: &Data<LemmyContext>,
   ) -> 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 community = note.community(context, request_counter).await?;
-    let local_site_data = fetch_local_site_data(context.pool()).await?;
-
-    check_apub_id_valid_with_strictness(
-      note.id.inner(),
-      community.local,
-      &local_site_data,
-      context.settings(),
-    )?;
+    let community = note.community(context).await?;
+
+    check_apub_id_valid_with_strictness(note.id.inner(), community.local, context).await?;
     verify_is_remote_object(note.id.inner(), context.settings())?;
-    verify_person_in_community(&note.attributed_to, &community, context, request_counter).await?;
-    let (post, _) = note.get_parents(context, request_counter).await?;
+    verify_person_in_community(&note.attributed_to, &community, context).await?;
+    let (post, _) = note.get_parents(context).await?;
     if post.locked {
-      return Err(LemmyError::from_message("Post is locked"));
+      return Err(LemmyErrorType::PostIsLocked)?;
     }
     Ok(())
   }
@@ -164,23 +146,17 @@ impl ApubObject for ApubComment {
   ///
   /// 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).await, request_counter)
-      .await?;
-    let (post, parent_comment) = note.get_parents(context, request_counter).await?;
+  async fn from_json(note: Note, context: &Data<LemmyContext>) -> Result<ApubComment, LemmyError> {
+    let creator = note.attributed_to.dereference(context).await?;
+    let (post, parent_comment) = note.get_parents(context).await?;
 
     let content = read_from_string_or_source(&note.content, &note.media_type, &note.source);
 
-    let local_site = LocalSite::read(context.pool()).await.ok();
+    let local_site = LocalSite::read(&mut context.pool()).await.ok();
     let slur_regex = &local_site_opt_to_slur_regex(&local_site);
     let content_slurs_removed = remove_slurs(&content, slur_regex);
-    let language_id = LanguageTag::to_language_id_single(note.language, context.pool()).await?;
+    let language_id =
+      LanguageTag::to_language_id_single(note.language, &mut context.pool()).await?;
 
     let form = CommentInsertForm {
       creator_id: creator.id,
@@ -196,13 +172,16 @@ impl ApubObject for ApubComment {
       language_id,
     };
     let parent_comment_path = parent_comment.map(|t| t.0.path);
-    let comment = Comment::create(context.pool(), &form, parent_comment_path.as_ref()).await?;
+    let comment = Comment::create(&mut context.pool(), &form, parent_comment_path.as_ref()).await?;
     Ok(comment.into())
   }
 }
 
 #[cfg(test)]
 pub(crate) mod tests {
+  #![allow(clippy::unwrap_used)]
+  #![allow(clippy::indexing_slicing)]
+
   use super::*;
   use crate::{
     objects::{
@@ -221,29 +200,31 @@ pub(crate) mod tests {
 
   async fn prepare_comment_test(
     url: &Url,
-    context: &LemmyContext,
+    context: &Data<LemmyContext>,
   ) -> (ApubPerson, ApubCommunity, ApubPost, ApubSite) {
-    let (person, site) = parse_lemmy_person(context).await;
-    let community = parse_lemmy_community(context).await;
+    // use separate counter so this doesnt affect tests
+    let context2 = context.reset_request_count();
+    let (person, site) = parse_lemmy_person(&context2).await;
+    let community = parse_lemmy_community(&context2).await;
     let post_json = file_to_json_object("assets/lemmy/objects/page.json").unwrap();
-    ApubPost::verify(&post_json, url, context, &mut 0)
-      .await
-      .unwrap();
-    let post = ApubPost::from_apub(post_json, context, &mut 0)
-      .await
-      .unwrap();
+    ApubPost::verify(&post_json, url, &context2).await.unwrap();
+    let post = ApubPost::from_json(post_json, &context2).await.unwrap();
     (person, community, post, site)
   }
 
   async fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) {
-    Post::delete(context.pool(), data.2.id).await.unwrap();
-    Community::delete(context.pool(), data.1.id).await.unwrap();
-    Person::delete(context.pool(), data.0.id).await.unwrap();
-    Site::delete(context.pool(), data.3.id).await.unwrap();
-    LocalSite::delete(context.pool()).await.unwrap();
+    Post::delete(&mut context.pool(), data.2.id).await.unwrap();
+    Community::delete(&mut context.pool(), data.1.id)
+      .await
+      .unwrap();
+    Person::delete(&mut context.pool(), data.0.id)
+      .await
+      .unwrap();
+    Site::delete(&mut context.pool(), data.3.id).await.unwrap();
+    LocalSite::delete(&mut context.pool()).await.unwrap();
   }
 
-  #[actix_rt::test]
+  #[tokio::test]
   #[serial]
   pub(crate) async fn test_parse_lemmy_comment() {
     let context = init_context().await;
@@ -251,28 +232,27 @@ pub(crate) mod tests {
     let data = prepare_comment_test(&url, &context).await;
 
     let json: Note = file_to_json_object("assets/lemmy/objects/note.json").unwrap();
-    let mut request_counter = 0;
-    ApubComment::verify(&json, &url, &context, &mut request_counter)
-      .await
-      .unwrap();
-    let comment = ApubComment::from_apub(json.clone(), &context, &mut request_counter)
+    ApubComment::verify(&json, &url, &context).await.unwrap();
+    let comment = ApubComment::from_json(json.clone(), &context)
       .await
       .unwrap();
 
     assert_eq!(comment.ap_id, url.into());
     assert_eq!(comment.content.len(), 14);
     assert!(!comment.local);
-    assert_eq!(request_counter, 0);
+    assert_eq!(context.request_count(), 0);
 
     let comment_id = comment.id;
-    let to_apub = comment.into_apub(&context).await.unwrap();
+    let to_apub = comment.into_json(&context).await.unwrap();
     assert_json_include!(actual: json, expected: to_apub);
 
-    Comment::delete(context.pool(), comment_id).await.unwrap();
+    Comment::delete(&mut context.pool(), comment_id)
+      .await
+      .unwrap();
     cleanup(data, &context).await;
   }
 
-  #[actix_rt::test]
+  #[tokio::test]
   #[serial]
   async fn test_parse_pleroma_comment() {
     let context = init_context().await;
@@ -283,31 +263,28 @@ pub(crate) mod tests {
       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").unwrap();
-    ApubPerson::verify(&person_json, &pleroma_url, &context, &mut 0)
-      .await
-      .unwrap();
-    ApubPerson::from_apub(person_json, &context, &mut 0)
+    ApubPerson::verify(&person_json, &pleroma_url, &context)
       .await
       .unwrap();
+    ApubPerson::from_json(person_json, &context).await.unwrap();
     let json = file_to_json_object("assets/pleroma/objects/note.json").unwrap();
-    let mut request_counter = 0;
-    ApubComment::verify(&json, &pleroma_url, &context, &mut request_counter)
-      .await
-      .unwrap();
-    let comment = ApubComment::from_apub(json, &context, &mut request_counter)
+    ApubComment::verify(&json, &pleroma_url, &context)
       .await
       .unwrap();
+    let comment = ApubComment::from_json(json, &context).await.unwrap();
 
     assert_eq!(comment.ap_id, pleroma_url.into());
     assert_eq!(comment.content.len(), 64);
     assert!(!comment.local);
-    assert_eq!(request_counter, 0);
+    assert_eq!(context.request_count(), 1);
 
-    Comment::delete(context.pool(), comment.id).await.unwrap();
+    Comment::delete(&mut context.pool(), comment.id)
+      .await
+      .unwrap();
     cleanup(data, &context).await;
   }
 
-  #[actix_rt::test]
+  #[tokio::test]
   #[serial]
   async fn test_html_to_markdown_sanitize() {
     let parsed = parse_html("<script></script><b>hello</b>");