]> Untitled Git - lemmy.git/blobdiff - crates/apub/src/activities/deletion/delete.rs
Split activity table into sent and received parts (fixes #3103) (#3583)
[lemmy.git] / crates / apub / src / activities / deletion / delete.rs
index acfc1ba7ef3ad84264eeb37406f4f29a00c6321f..fcdede8d76745460653ea97874f3317633146b61 100644 (file)
@@ -1,36 +1,18 @@
 use crate::{
   activities::{
-    community::{announce::AnnouncableActivities, send_to_community},
-    deletion::{
-      receive_delete_action,
-      verify_delete_activity,
-      DeletableObjects,
-      WebsocketMessages,
-    },
+    deletion::{receive_delete_action, verify_delete_activity, DeletableObjects},
     generate_activity_id,
-    verify_activity,
   },
-  context::lemmy_context,
-  fetcher::object_id::ObjectId,
-  migrations::PublicUrlMigration,
-  objects::{community::ApubCommunity, person::ApubPerson},
-};
-use activitystreams::{
-  activity::kind::DeleteType,
-  base::AnyBase,
-  primitives::OneOrMany,
-  unparsed::Unparsed,
-};
-use anyhow::anyhow;
-use lemmy_api_common::blocking;
-use lemmy_apub_lib::{
-  data::Data,
-  traits::{ActivityFields, ActivityHandler, ActorType},
+  insert_received_activity,
+  objects::person::ApubPerson,
+  protocol::{activities::deletion::delete::Delete, IdOrNestedObject},
 };
+use activitypub_federation::{config::Data, kinds::activity::DeleteType, traits::ActivityHandler};
+use lemmy_api_common::context::LemmyContext;
 use lemmy_db_schema::{
   source::{
-    comment::Comment,
-    community::Community,
+    comment::{Comment, CommentUpdateForm},
+    community::{Community, CommunityUpdateForm},
     moderator::{
       ModRemoveComment,
       ModRemoveCommentForm,
@@ -39,74 +21,35 @@ use lemmy_db_schema::{
       ModRemovePost,
       ModRemovePostForm,
     },
-    post::Post,
+    post::{Post, PostUpdateForm},
   },
   traits::Crud,
 };
-use lemmy_utils::LemmyError;
-use lemmy_websocket::{
-  send::{send_comment_ws_message_simple, send_community_ws_message, send_post_ws_message},
-  LemmyContext,
-  UserOperationCrud,
-};
-use serde::{Deserialize, Serialize};
-use serde_with::skip_serializing_none;
+use lemmy_utils::error::{LemmyError, LemmyErrorType};
 use url::Url;
 
-/// This is very confusing, because there are four distinct cases to handle:
-/// - user deletes their post
-/// - user deletes their comment
-/// - remote community mod deletes local community
-/// - remote community deletes itself (triggered by a mod)
-///
-/// TODO: we should probably change how community deletions work to simplify this. Probably by
-/// wrapping it in an announce just like other activities, instead of having the community send it.
-#[skip_serializing_none]
-#[derive(Clone, Debug, Deserialize, Serialize, ActivityFields)]
-#[serde(rename_all = "camelCase")]
-pub struct Delete {
-  actor: ObjectId<ApubPerson>,
-  to: PublicUrlMigration,
-  pub(in crate::activities::deletion) object: Url,
-  pub(in crate::activities::deletion) cc: [ObjectId<ApubCommunity>; 1],
-  #[serde(rename = "type")]
-  kind: DeleteType,
-  /// If summary is present, this is a mod action (Remove in Lemmy terms). Otherwise, its a user
-  /// deleting their own content.
-  pub(in crate::activities::deletion) summary: Option<String>,
-  id: Url,
-  #[serde(rename = "@context")]
-  context: OneOrMany<AnyBase>,
-  #[serde(flatten)]
-  unparsed: Unparsed,
-}
-
-#[async_trait::async_trait(?Send)]
+#[async_trait::async_trait]
 impl ActivityHandler for Delete {
   type DataType = LemmyContext;
-  async fn verify(
-    &self,
-    context: &Data<LemmyContext>,
-    request_counter: &mut i32,
-  ) -> Result<(), LemmyError> {
-    verify_activity(self, &context.settings())?;
-    verify_delete_activity(
-      &self.object,
-      self,
-      &self.cc[0],
-      self.summary.is_some(),
-      context,
-      request_counter,
-    )
-    .await?;
+  type Error = LemmyError;
+
+  fn id(&self) -> &Url {
+    &self.id
+  }
+
+  fn actor(&self) -> &Url {
+    self.actor.inner()
+  }
+
+  #[tracing::instrument(skip_all)]
+  async fn verify(&self, context: &Data<Self::DataType>) -> Result<(), LemmyError> {
+    insert_received_activity(&self.id, context).await?;
+    verify_delete_activity(self, self.summary.is_some(), context).await?;
     Ok(())
   }
 
-  async fn receive(
-    self,
-    context: &Data<LemmyContext>,
-    request_counter: &mut i32,
-  ) -> Result<(), LemmyError> {
+  #[tracing::instrument(skip_all)]
+  async fn receive(self, context: &Data<LemmyContext>) -> Result<(), LemmyError> {
     if let Some(reason) = self.summary {
       // We set reason to empty string if it doesn't exist, to distinguish between delete and
       // remove. Here we change it back to option, so we don't write it to db.
@@ -115,21 +58,15 @@ impl ActivityHandler for Delete {
       } else {
         Some(reason)
       };
-      receive_remove_action(&self.actor, &self.object, reason, context, request_counter).await
-    } else {
-      receive_delete_action(
-        &self.object,
-        &self.actor,
-        WebsocketMessages {
-          community: UserOperationCrud::DeleteCommunity,
-          post: UserOperationCrud::DeletePost,
-          comment: UserOperationCrud::DeleteComment,
-        },
-        true,
+      receive_remove_action(
+        &self.actor.dereference(context).await?,
+        self.object.id(),
+        reason,
         context,
-        request_counter,
       )
       .await
+    } else {
+      receive_delete_action(self.object.id(), &self.actor, true, context).await
     }
   }
 }
@@ -137,54 +74,41 @@ impl ActivityHandler for Delete {
 impl Delete {
   pub(in crate::activities::deletion) fn new(
     actor: &ApubPerson,
-    community: &ApubCommunity,
-    object_id: Url,
+    object: DeletableObjects,
+    to: Url,
+    community: Option<&Community>,
     summary: Option<String>,
-    context: &LemmyContext,
+    context: &Data<LemmyContext>,
   ) -> Result<Delete, LemmyError> {
+    let id = generate_activity_id(
+      DeleteType::Delete,
+      &context.settings().get_protocol_and_hostname(),
+    )?;
+    let cc: Option<Url> = community.map(|c| c.actor_id.clone().into());
     Ok(Delete {
-      actor: ObjectId::new(actor.actor_id()),
-      to: PublicUrlMigration::create(),
-      object: object_id,
-      cc: [ObjectId::new(community.actor_id())],
+      actor: actor.actor_id.clone().into(),
+      to: vec![to],
+      object: IdOrNestedObject::Id(object.id()),
+      cc: cc.into_iter().collect(),
       kind: DeleteType::Delete,
       summary,
-      id: generate_activity_id(
-        DeleteType::Delete,
-        &context.settings().get_protocol_and_hostname(),
-      )?,
-      context: lemmy_context(),
-      unparsed: Default::default(),
+      id,
+      audience: community.map(|c| c.actor_id.clone().into()),
     })
   }
-  pub(in crate::activities::deletion) async fn send(
-    actor: &ApubPerson,
-    community: &ApubCommunity,
-    object_id: Url,
-    summary: Option<String>,
-    context: &LemmyContext,
-  ) -> Result<(), LemmyError> {
-    let delete = Delete::new(actor, community, object_id, summary, context)?;
-    let delete_id = delete.id.clone();
-
-    let activity = AnnouncableActivities::Delete(delete);
-    send_to_community(activity, &delete_id, actor, community, vec![], context).await
-  }
 }
 
+#[tracing::instrument(skip_all)]
 pub(in crate::activities) async fn receive_remove_action(
-  actor: &ObjectId<ApubPerson>,
+  actor: &ApubPerson,
   object: &Url,
   reason: Option<String>,
-  context: &LemmyContext,
-  request_counter: &mut i32,
+  context: &Data<LemmyContext>,
 ) -> Result<(), LemmyError> {
-  let actor = actor.dereference(context, request_counter).await?;
-  use UserOperationCrud::*;
   match DeletableObjects::read_from_db(object, context).await? {
     DeletableObjects::Community(community) => {
       if community.local {
-        return Err(anyhow!("Only local admin can remove community").into());
+        return Err(LemmyErrorType::OnlyLocalAdminCanRemoveCommunity)?;
       }
       let form = ModRemoveCommunityForm {
         mod_person_id: actor.id,
@@ -193,16 +117,13 @@ pub(in crate::activities) async fn receive_remove_action(
         reason,
         expires: None,
       };
-      blocking(context.pool(), move |conn| {
-        ModRemoveCommunity::create(conn, &form)
-      })
-      .await??;
-      let deleted_community = blocking(context.pool(), move |conn| {
-        Community::update_removed(conn, community.id, true)
-      })
-      .await??;
-
-      send_community_ws_message(deleted_community.id, RemoveCommunity, None, None, context).await?;
+      ModRemoveCommunity::create(&mut context.pool(), &form).await?;
+      Community::update(
+        &mut context.pool(),
+        community.id,
+        &CommunityUpdateForm::builder().removed(Some(true)).build(),
+      )
+      .await?;
     }
     DeletableObjects::Post(post) => {
       let form = ModRemovePostForm {
@@ -211,16 +132,13 @@ pub(in crate::activities) async fn receive_remove_action(
         removed: Some(true),
         reason,
       };
-      blocking(context.pool(), move |conn| {
-        ModRemovePost::create(conn, &form)
-      })
-      .await??;
-      let removed_post = blocking(context.pool(), move |conn| {
-        Post::update_removed(conn, post.id, true)
-      })
-      .await??;
-
-      send_post_ws_message(removed_post.id, RemovePost, None, None, context).await?;
+      ModRemovePost::create(&mut context.pool(), &form).await?;
+      Post::update(
+        &mut context.pool(),
+        post.id,
+        &PostUpdateForm::builder().removed(Some(true)).build(),
+      )
+      .await?;
     }
     DeletableObjects::Comment(comment) => {
       let form = ModRemoveCommentForm {
@@ -229,17 +147,15 @@ pub(in crate::activities) async fn receive_remove_action(
         removed: Some(true),
         reason,
       };
-      blocking(context.pool(), move |conn| {
-        ModRemoveComment::create(conn, &form)
-      })
-      .await??;
-      let removed_comment = blocking(context.pool(), move |conn| {
-        Comment::update_removed(conn, comment.id, true)
-      })
-      .await??;
-
-      send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?;
+      ModRemoveComment::create(&mut context.pool(), &form).await?;
+      Comment::update(
+        &mut context.pool(),
+        comment.id,
+        &CommentUpdateForm::builder().removed(Some(true)).build(),
+      )
+      .await?;
     }
+    DeletableObjects::PrivateMessage(_) => unimplemented!(),
   }
   Ok(())
 }