]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/delete.rs
Merge websocket crate into api_common
[lemmy.git] / crates / api_crud / src / community / delete.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{CommunityResponse, DeleteCommunity},
5   utils::get_local_user_view_from_jwt,
6   websocket::{send::send_community_ws_message, UserOperationCrud},
7   LemmyContext,
8 };
9 use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
10 use lemmy_db_schema::{
11   source::community::{Community, CommunityUpdateForm},
12   traits::Crud,
13 };
14 use lemmy_db_views_actor::structs::CommunityModeratorView;
15 use lemmy_utils::{error::LemmyError, ConnectionId};
16
17 #[async_trait::async_trait(?Send)]
18 impl PerformCrud for DeleteCommunity {
19   type Response = CommunityResponse;
20
21   #[tracing::instrument(skip(context, websocket_id))]
22   async fn perform(
23     &self,
24     context: &Data<LemmyContext>,
25     websocket_id: Option<ConnectionId>,
26   ) -> Result<CommunityResponse, LemmyError> {
27     let data: &DeleteCommunity = self;
28     let local_user_view =
29       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
30
31     // Fetch the community mods
32     let community_id = data.community_id;
33     let community_mods =
34       CommunityModeratorView::for_community(context.pool(), community_id).await?;
35
36     // Make sure deleter is the top mod
37     if local_user_view.person.id != community_mods[0].moderator.id {
38       return Err(LemmyError::from_message("no_community_edit_allowed"));
39     }
40
41     // Do the delete
42     let community_id = data.community_id;
43     let deleted = data.deleted;
44     let updated_community = Community::update(
45       context.pool(),
46       community_id,
47       &CommunityUpdateForm::builder()
48         .deleted(Some(deleted))
49         .build(),
50     )
51     .await
52     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
53
54     let res = send_community_ws_message(
55       data.community_id,
56       UserOperationCrud::DeleteCommunity,
57       websocket_id,
58       Some(local_user_view.person.id),
59       context,
60     )
61     .await?;
62
63     // Send apub messages
64     let deletable = DeletableObjects::Community(Box::new(updated_community.clone().into()));
65     send_apub_delete_in_community(
66       local_user_view.person,
67       updated_community,
68       deletable,
69       None,
70       deleted,
71       context,
72     )
73     .await?;
74
75     Ok(res)
76   }
77 }