]> Untitled Git - lemmy.git/blob - crates/api/src/community/block.rs
6c6efc2131a5d67b91c150c9d641fc3f8ba67e0d
[lemmy.git] / crates / api / src / community / block.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{BlockCommunity, BlockCommunityResponse},
5   utils::get_local_user_view_from_jwt,
6   LemmyContext,
7 };
8 use lemmy_apub::protocol::activities::following::undo_follow::UndoFollow;
9 use lemmy_db_schema::{
10   source::{
11     community::{Community, CommunityFollower, CommunityFollowerForm},
12     community_block::{CommunityBlock, CommunityBlockForm},
13   },
14   traits::{Blockable, Crud, Followable},
15 };
16 use lemmy_db_views_actor::structs::CommunityView;
17 use lemmy_utils::{error::LemmyError, ConnectionId};
18
19 #[async_trait::async_trait(?Send)]
20 impl Perform for BlockCommunity {
21   type Response = BlockCommunityResponse;
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<BlockCommunityResponse, LemmyError> {
29     let data: &BlockCommunity = self;
30     let local_user_view =
31       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
32
33     let community_id = data.community_id;
34     let person_id = local_user_view.person.id;
35     let community_block_form = CommunityBlockForm {
36       person_id,
37       community_id,
38     };
39
40     if data.block {
41       CommunityBlock::block(context.pool(), &community_block_form)
42         .await
43         .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?;
44
45       // Also, unfollow the community, and send a federated unfollow
46       let community_follower_form = CommunityFollowerForm {
47         community_id: data.community_id,
48         person_id,
49         pending: false,
50       };
51
52       CommunityFollower::unfollow(context.pool(), &community_follower_form)
53         .await
54         .ok();
55       let community = Community::read(context.pool(), community_id).await?;
56       UndoFollow::send(&local_user_view.person.into(), &community.into(), context).await?;
57     } else {
58       CommunityBlock::unblock(context.pool(), &community_block_form)
59         .await
60         .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?;
61     }
62
63     let community_view = CommunityView::read(context.pool(), community_id, Some(person_id)).await?;
64
65     Ok(BlockCommunityResponse {
66       blocked: data.block,
67       community_view,
68     })
69   }
70 }