]> Untitled Git - lemmy.git/blob - crates/api/src/community/hide.rs
Moving settings to Database. (#2492)
[lemmy.git] / crates / api / src / community / hide.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{CommunityResponse, HideCommunity},
5   utils::{blocking, get_local_user_view_from_jwt, is_admin},
6 };
7 use lemmy_apub::protocol::activities::community::update::UpdateCommunity;
8 use lemmy_db_schema::{
9   source::{
10     community::{Community, CommunityUpdateForm},
11     moderator::{ModHideCommunity, ModHideCommunityForm},
12   },
13   traits::Crud,
14 };
15 use lemmy_utils::{error::LemmyError, ConnectionId};
16 use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
17
18 #[async_trait::async_trait(?Send)]
19 impl Perform for HideCommunity {
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: &HideCommunity = self;
29
30     // Verify its a admin (only admin can hide or unhide it)
31     let local_user_view =
32       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
33     is_admin(&local_user_view)?;
34
35     let community_form = CommunityUpdateForm::builder()
36       .hidden(Some(data.hidden))
37       .build();
38
39     let mod_hide_community_form = ModHideCommunityForm {
40       community_id: data.community_id,
41       mod_person_id: local_user_view.person.id,
42       reason: data.reason.clone(),
43       hidden: Some(data.hidden),
44     };
45
46     let community_id = data.community_id;
47     let updated_community = blocking(context.pool(), move |conn| {
48       Community::update(conn, community_id, &community_form)
49     })
50     .await?
51     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?;
52
53     blocking(context.pool(), move |conn| {
54       ModHideCommunity::create(conn, &mod_hide_community_form)
55     })
56     .await??;
57
58     UpdateCommunity::send(
59       updated_community.into(),
60       &local_user_view.person.into(),
61       context,
62     )
63     .await?;
64
65     let op = UserOperationCrud::EditCommunity;
66     send_community_ws_message(data.community_id, op, websocket_id, None, context).await
67   }
68 }