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