]> Untitled Git - lemmy.git/blob - crates/api/src/community/hide.rs
a3910010024b53e130cb341364bd28c367169519
[lemmy.git] / crates / api / src / community / hide.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   blocking,
5   community::{CommunityResponse, HideCommunity},
6   get_local_user_view_from_jwt,
7   is_admin,
8 };
9 use lemmy_apub::protocol::activities::community::update::UpdateCommunity;
10 use lemmy_db_schema::{
11   naive_now,
12   source::{
13     community::{Community, CommunityForm},
14     moderator::{ModHideCommunity, ModHideCommunityForm},
15   },
16   traits::Crud,
17 };
18 use lemmy_utils::{ConnectionId, LemmyError};
19 use lemmy_websocket::{send::send_community_ws_message, LemmyContext, UserOperationCrud};
20
21 #[async_trait::async_trait(?Send)]
22 impl Perform for HideCommunity {
23   type Response = CommunityResponse;
24
25   #[tracing::instrument(skip(context, websocket_id))]
26   async fn perform(
27     &self,
28     context: &Data<LemmyContext>,
29     websocket_id: Option<ConnectionId>,
30   ) -> Result<CommunityResponse, LemmyError> {
31     let data: &HideCommunity = self;
32
33     // Verify its a admin (only admin can hide or unhide it)
34     let local_user_view =
35       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
36     is_admin(&local_user_view)?;
37
38     let community_id = data.community_id;
39     let read_community = blocking(context.pool(), move |conn| {
40       Community::read(conn, community_id)
41     })
42     .await??;
43
44     let community_form = CommunityForm {
45       name: read_community.name,
46       title: read_community.title,
47       description: read_community.description.to_owned(),
48       hidden: Some(data.hidden),
49       updated: Some(naive_now()),
50       ..CommunityForm::default()
51     };
52
53     let mod_hide_community_form = ModHideCommunityForm {
54       community_id: data.community_id,
55       mod_person_id: local_user_view.person.id,
56       reason: data.reason.clone(),
57       hidden: Some(data.hidden),
58     };
59
60     let community_id = data.community_id;
61     let updated_community = blocking(context.pool(), move |conn| {
62       Community::update(conn, community_id, &community_form)
63     })
64     .await?
65     .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?;
66
67     blocking(context.pool(), move |conn| {
68       ModHideCommunity::create(conn, &mod_hide_community_form)
69     })
70     .await??;
71
72     UpdateCommunity::send(
73       updated_community.into(),
74       &local_user_view.person.into(),
75       context,
76     )
77     .await?;
78
79     let op = UserOperationCrud::EditCommunity;
80     send_community_ws_message(data.community_id, op, websocket_id, None, context).await
81   }
82 }