]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/remove.rs
Merge websocket crate into api_common
[lemmy.git] / crates / api_crud / src / community / remove.rs
1 use crate::PerformCrud;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{CommunityResponse, RemoveCommunity},
5   utils::{get_local_user_view_from_jwt, is_admin},
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::{
12     community::{Community, CommunityUpdateForm},
13     moderator::{ModRemoveCommunity, ModRemoveCommunityForm},
14   },
15   traits::Crud,
16 };
17 use lemmy_utils::{error::LemmyError, utils::naive_from_unix, ConnectionId};
18
19 #[async_trait::async_trait(?Send)]
20 impl PerformCrud for RemoveCommunity {
21   type Response = CommunityResponse;
22
23   #[tracing::instrument(skip(context, websocket_id))]
24   async fn perform(
25     &self,
26     context: &Data<LemmyContext>,
27     websocket_id: Option<ConnectionId>,
28   ) -> Result<CommunityResponse, LemmyError> {
29     let data: &RemoveCommunity = self;
30     let local_user_view =
31       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
32
33     // Verify its an admin (only an admin can remove a community)
34     is_admin(&local_user_view)?;
35
36     // Do the remove
37     let community_id = data.community_id;
38     let removed = data.removed;
39     let updated_community = Community::update(
40       context.pool(),
41       community_id,
42       &CommunityUpdateForm::builder()
43         .removed(Some(removed))
44         .build(),
45     )
46     .await
47     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
48
49     // Mod tables
50     let expires = data.expires.map(naive_from_unix);
51     let form = ModRemoveCommunityForm {
52       mod_person_id: local_user_view.person.id,
53       community_id: data.community_id,
54       removed: Some(removed),
55       reason: data.reason.clone(),
56       expires,
57     };
58     ModRemoveCommunity::create(context.pool(), &form).await?;
59
60     let res = send_community_ws_message(
61       data.community_id,
62       UserOperationCrud::RemoveCommunity,
63       websocket_id,
64       Some(local_user_view.person.id),
65       context,
66     )
67     .await?;
68
69     // Apub messages
70     let deletable = DeletableObjects::Community(Box::new(updated_community.clone().into()));
71     send_apub_delete_in_community(
72       local_user_view.person,
73       updated_community,
74       deletable,
75       data.reason.clone().or_else(|| Some(String::new())),
76       removed,
77       context,
78     )
79     .await?;
80     Ok(res)
81   }
82 }