]> Untitled Git - lemmy.git/blob - crates/api/src/community/hide.rs
Add cargo feature for building lemmy_api_common with mininum deps (#2243)
[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, CommunityForm},
11     moderator::{ModHideCommunity, ModHideCommunityForm},
12   },
13   traits::Crud,
14   utils::naive_now,
15 };
16 use lemmy_utils::{ConnectionId, LemmyError};
17 use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
18
19 #[async_trait::async_trait(?Send)]
20 impl Perform for HideCommunity {
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: &HideCommunity = self;
30
31     // Verify its a admin (only admin can hide or unhide it)
32     let local_user_view =
33       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
34     is_admin(&local_user_view)?;
35
36     let community_id = data.community_id;
37     let read_community = blocking(context.pool(), move |conn| {
38       Community::read(conn, community_id)
39     })
40     .await??;
41
42     let community_form = CommunityForm {
43       name: read_community.name,
44       title: read_community.title,
45       description: read_community.description.to_owned(),
46       hidden: Some(data.hidden),
47       updated: Some(naive_now()),
48       ..CommunityForm::default()
49     };
50
51     let mod_hide_community_form = ModHideCommunityForm {
52       community_id: data.community_id,
53       mod_person_id: local_user_view.person.id,
54       reason: data.reason.clone(),
55       hidden: Some(data.hidden),
56     };
57
58     let community_id = data.community_id;
59     let updated_community = blocking(context.pool(), move |conn| {
60       Community::update(conn, community_id, &community_form)
61     })
62     .await?
63     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?;
64
65     blocking(context.pool(), move |conn| {
66       ModHideCommunity::create(conn, &mod_hide_community_form)
67     })
68     .await??;
69
70     UpdateCommunity::send(
71       updated_community.into(),
72       &local_user_view.person.into(),
73       context,
74     )
75     .await?;
76
77     let op = UserOperationCrud::EditCommunity;
78     send_community_ws_message(data.community_id, op, websocket_id, None, context).await
79   }
80 }