]> Untitled Git - lemmy.git/blob - crates/api/src/community/block.rs
Make functions work with both connection and pool (#3420)
[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   context::LemmyContext,
6   utils::local_user_view_from_jwt,
7 };
8 use lemmy_db_schema::{
9   source::{
10     community::{CommunityFollower, CommunityFollowerForm},
11     community_block::{CommunityBlock, CommunityBlockForm},
12   },
13   traits::{Blockable, Followable},
14 };
15 use lemmy_db_views_actor::structs::CommunityView;
16 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
17
18 #[async_trait::async_trait(?Send)]
19 impl Perform for BlockCommunity {
20   type Response = BlockCommunityResponse;
21
22   #[tracing::instrument(skip(context))]
23   async fn perform(
24     &self,
25     context: &Data<LemmyContext>,
26   ) -> Result<BlockCommunityResponse, LemmyError> {
27     let data: &BlockCommunity = self;
28     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
29
30     let community_id = data.community_id;
31     let person_id = local_user_view.person.id;
32     let community_block_form = CommunityBlockForm {
33       person_id,
34       community_id,
35     };
36
37     if data.block {
38       CommunityBlock::block(&mut context.pool(), &community_block_form)
39         .await
40         .with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
41
42       // Also, unfollow the community, and send a federated unfollow
43       let community_follower_form = CommunityFollowerForm {
44         community_id: data.community_id,
45         person_id,
46         pending: false,
47       };
48
49       CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
50         .await
51         .ok();
52     } else {
53       CommunityBlock::unblock(&mut context.pool(), &community_block_form)
54         .await
55         .with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
56     }
57
58     let community_view =
59       CommunityView::read(&mut context.pool(), community_id, Some(person_id), None).await?;
60
61     Ok(BlockCommunityResponse {
62       blocked: data.block,
63       community_view,
64     })
65   }
66 }