]> Untitled Git - lemmy.git/blob - crates/api_crud/src/community/remove.rs
Moving settings to Database. (#2492)
[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::{blocking, get_local_user_view_from_jwt, is_admin},
6 };
7 use lemmy_apub::activities::deletion::{send_apub_delete_in_community, DeletableObjects};
8 use lemmy_db_schema::{
9   source::{
10     community::{Community, CommunityUpdateForm},
11     moderator::{ModRemoveCommunity, ModRemoveCommunityForm},
12   },
13   traits::Crud,
14 };
15 use lemmy_utils::{error::LemmyError, utils::naive_from_unix, ConnectionId};
16 use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
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     let updated_community = blocking(context.pool(), move |conn| {
39       Community::update(
40         conn,
41         community_id,
42         &CommunityUpdateForm::builder()
43           .removed(Some(removed))
44           .build(),
45       )
46     })
47     .await?
48     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?;
49
50     // Mod tables
51     let expires = data.expires.map(naive_from_unix);
52     let form = ModRemoveCommunityForm {
53       mod_person_id: local_user_view.person.id,
54       community_id: data.community_id,
55       removed: Some(removed),
56       reason: data.reason.to_owned(),
57       expires,
58     };
59     blocking(context.pool(), move |conn| {
60       ModRemoveCommunity::create(conn, &form)
61     })
62     .await??;
63
64     let res = send_community_ws_message(
65       data.community_id,
66       UserOperationCrud::RemoveCommunity,
67       websocket_id,
68       Some(local_user_view.person.id),
69       context,
70     )
71     .await?;
72
73     // Apub messages
74     let deletable = DeletableObjects::Community(Box::new(updated_community.clone().into()));
75     send_apub_delete_in_community(
76       local_user_view.person,
77       updated_community,
78       deletable,
79       data.reason.clone().or_else(|| Some("".to_string())),
80       removed,
81       context,
82     )
83     .await?;
84     Ok(res)
85   }
86 }