]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/deletion/delete.rs
7593c5bf48ac53b61a9e0154c58b903256383767
[lemmy.git] / crates / apub / src / activities / deletion / delete.rs
1 use crate::{
2   activities::{
3     community::{announce::AnnouncableActivities, send_to_community},
4     deletion::{
5       receive_delete_action,
6       verify_delete_activity,
7       DeletableObjects,
8       WebsocketMessages,
9     },
10     generate_activity_id,
11     verify_activity,
12     verify_is_public,
13   },
14   context::lemmy_context,
15   fetcher::object_id::ObjectId,
16   objects::{community::ApubCommunity, person::ApubPerson},
17 };
18 use activitystreams::{
19   activity::kind::DeleteType,
20   base::AnyBase,
21   primitives::OneOrMany,
22   public,
23   unparsed::Unparsed,
24 };
25 use anyhow::anyhow;
26 use lemmy_api_common::blocking;
27 use lemmy_apub_lib::{
28   data::Data,
29   traits::{ActivityFields, ActivityHandler, ActorType},
30 };
31 use lemmy_db_schema::{
32   source::{
33     comment::Comment,
34     community::Community,
35     moderator::{
36       ModRemoveComment,
37       ModRemoveCommentForm,
38       ModRemoveCommunity,
39       ModRemoveCommunityForm,
40       ModRemovePost,
41       ModRemovePostForm,
42     },
43     post::Post,
44   },
45   traits::Crud,
46 };
47 use lemmy_utils::LemmyError;
48 use lemmy_websocket::{
49   send::{send_comment_ws_message_simple, send_community_ws_message, send_post_ws_message},
50   LemmyContext,
51   UserOperationCrud,
52 };
53 use serde::{Deserialize, Serialize};
54 use serde_with::skip_serializing_none;
55 use url::Url;
56
57 /// This is very confusing, because there are four distinct cases to handle:
58 /// - user deletes their post
59 /// - user deletes their comment
60 /// - remote community mod deletes local community
61 /// - remote community deletes itself (triggered by a mod)
62 ///
63 /// TODO: we should probably change how community deletions work to simplify this. Probably by
64 /// wrapping it in an announce just like other activities, instead of having the community send it.
65 #[skip_serializing_none]
66 #[derive(Clone, Debug, Deserialize, Serialize, ActivityFields)]
67 #[serde(rename_all = "camelCase")]
68 pub struct Delete {
69   actor: ObjectId<ApubPerson>,
70   to: Vec<Url>,
71   pub(in crate::activities::deletion) object: Url,
72   pub(in crate::activities::deletion) cc: [ObjectId<ApubCommunity>; 1],
73   #[serde(rename = "type")]
74   kind: DeleteType,
75   /// If summary is present, this is a mod action (Remove in Lemmy terms). Otherwise, its a user
76   /// deleting their own content.
77   pub(in crate::activities::deletion) summary: Option<String>,
78   id: Url,
79   #[serde(rename = "@context")]
80   context: OneOrMany<AnyBase>,
81   #[serde(flatten)]
82   unparsed: Unparsed,
83 }
84
85 #[async_trait::async_trait(?Send)]
86 impl ActivityHandler for Delete {
87   type DataType = LemmyContext;
88   async fn verify(
89     &self,
90     context: &Data<LemmyContext>,
91     request_counter: &mut i32,
92   ) -> Result<(), LemmyError> {
93     verify_is_public(&self.to)?;
94     verify_activity(self, &context.settings())?;
95     verify_delete_activity(
96       &self.object,
97       self,
98       &self.cc[0],
99       self.summary.is_some(),
100       context,
101       request_counter,
102     )
103     .await?;
104     Ok(())
105   }
106
107   async fn receive(
108     self,
109     context: &Data<LemmyContext>,
110     request_counter: &mut i32,
111   ) -> Result<(), LemmyError> {
112     if let Some(reason) = self.summary {
113       // We set reason to empty string if it doesn't exist, to distinguish between delete and
114       // remove. Here we change it back to option, so we don't write it to db.
115       let reason = if reason.is_empty() {
116         None
117       } else {
118         Some(reason)
119       };
120       receive_remove_action(&self.actor, &self.object, reason, context, request_counter).await
121     } else {
122       receive_delete_action(
123         &self.object,
124         &self.actor,
125         WebsocketMessages {
126           community: UserOperationCrud::DeleteCommunity,
127           post: UserOperationCrud::DeletePost,
128           comment: UserOperationCrud::DeleteComment,
129         },
130         true,
131         context,
132         request_counter,
133       )
134       .await
135     }
136   }
137 }
138
139 impl Delete {
140   pub(in crate::activities::deletion) fn new(
141     actor: &ApubPerson,
142     community: &ApubCommunity,
143     object_id: Url,
144     summary: Option<String>,
145     context: &LemmyContext,
146   ) -> Result<Delete, LemmyError> {
147     Ok(Delete {
148       actor: ObjectId::new(actor.actor_id()),
149       to: vec![public()],
150       object: object_id,
151       cc: [ObjectId::new(community.actor_id())],
152       kind: DeleteType::Delete,
153       summary,
154       id: generate_activity_id(
155         DeleteType::Delete,
156         &context.settings().get_protocol_and_hostname(),
157       )?,
158       context: lemmy_context(),
159       unparsed: Default::default(),
160     })
161   }
162   pub(in crate::activities::deletion) async fn send(
163     actor: &ApubPerson,
164     community: &ApubCommunity,
165     object_id: Url,
166     summary: Option<String>,
167     context: &LemmyContext,
168   ) -> Result<(), LemmyError> {
169     let delete = Delete::new(actor, community, object_id, summary, context)?;
170     let delete_id = delete.id.clone();
171
172     let activity = AnnouncableActivities::Delete(delete);
173     send_to_community(activity, &delete_id, actor, community, vec![], context).await
174   }
175 }
176
177 pub(in crate::activities) async fn receive_remove_action(
178   actor: &ObjectId<ApubPerson>,
179   object: &Url,
180   reason: Option<String>,
181   context: &LemmyContext,
182   request_counter: &mut i32,
183 ) -> Result<(), LemmyError> {
184   let actor = actor.dereference(context, request_counter).await?;
185   use UserOperationCrud::*;
186   match DeletableObjects::read_from_db(object, context).await? {
187     DeletableObjects::Community(community) => {
188       if community.local {
189         return Err(anyhow!("Only local admin can remove community").into());
190       }
191       let form = ModRemoveCommunityForm {
192         mod_person_id: actor.id,
193         community_id: community.id,
194         removed: Some(true),
195         reason,
196         expires: None,
197       };
198       blocking(context.pool(), move |conn| {
199         ModRemoveCommunity::create(conn, &form)
200       })
201       .await??;
202       let deleted_community = blocking(context.pool(), move |conn| {
203         Community::update_removed(conn, community.id, true)
204       })
205       .await??;
206
207       send_community_ws_message(deleted_community.id, RemoveCommunity, None, None, context).await?;
208     }
209     DeletableObjects::Post(post) => {
210       let form = ModRemovePostForm {
211         mod_person_id: actor.id,
212         post_id: post.id,
213         removed: Some(true),
214         reason,
215       };
216       blocking(context.pool(), move |conn| {
217         ModRemovePost::create(conn, &form)
218       })
219       .await??;
220       let removed_post = blocking(context.pool(), move |conn| {
221         Post::update_removed(conn, post.id, true)
222       })
223       .await??;
224
225       send_post_ws_message(removed_post.id, RemovePost, None, None, context).await?;
226     }
227     DeletableObjects::Comment(comment) => {
228       let form = ModRemoveCommentForm {
229         mod_person_id: actor.id,
230         comment_id: comment.id,
231         removed: Some(true),
232         reason,
233       };
234       blocking(context.pool(), move |conn| {
235         ModRemoveComment::create(conn, &form)
236       })
237       .await??;
238       let removed_comment = blocking(context.pool(), move |conn| {
239         Comment::update_removed(conn, comment.id, true)
240       })
241       .await??;
242
243       send_comment_ws_message_simple(removed_comment.id, RemoveComment, context).await?;
244     }
245   }
246   Ok(())
247 }