]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/remove.rs
Merge pull request #2593 from LemmyNet/refactor-notifications
[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   context::LemmyContext,
6   utils::{get_local_user_view_from_jwt, is_admin},
7   websocket::{send::send_community_ws_message, UserOperationCrud},
8 };
9 use lemmy_db_schema::{
10   source::{
11     community::{Community, CommunityUpdateForm},
12     moderator::{ModRemoveCommunity, ModRemoveCommunityForm},
13   },
14   traits::Crud,
15 };
16 use lemmy_utils::{error::LemmyError, utils::naive_from_unix, ConnectionId};
17
18 #[async_trait::async_trait(?Send)]
19 impl PerformCrud for RemoveCommunity {
20   type Response = CommunityResponse;
21
22   #[tracing::instrument(skip(context, websocket_id))]
23   async fn perform(
24     &self,
25     context: &Data<LemmyContext>,
26     websocket_id: Option<ConnectionId>,
27   ) -> Result<CommunityResponse, LemmyError> {
28     let data: &RemoveCommunity = self;
29     let local_user_view =
30       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
31
32     // Verify its an admin (only an admin can remove a community)
33     is_admin(&local_user_view)?;
34
35     // Do the remove
36     let community_id = data.community_id;
37     let removed = data.removed;
38     Community::update(
39       context.pool(),
40       community_id,
41       &CommunityUpdateForm::builder()
42         .removed(Some(removed))
43         .build(),
44     )
45     .await
46     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
47
48     // Mod tables
49     let expires = data.expires.map(naive_from_unix);
50     let form = ModRemoveCommunityForm {
51       mod_person_id: local_user_view.person.id,
52       community_id: data.community_id,
53       removed: Some(removed),
54       reason: data.reason.clone(),
55       expires,
56     };
57     ModRemoveCommunity::create(context.pool(), &form).await?;
58
59     let res = send_community_ws_message(
60       data.community_id,
61       UserOperationCrud::RemoveCommunity,
62       websocket_id,
63       Some(local_user_view.person.id),
64       context,
65     )
66     .await?;
67
68     Ok(res)
69   }
70 }