]> Untitled Git - lemmy.git/blob - crates/api/src/community/block.rs
Replace Option<bool> with bool for PostQuery and CommentQuery (#3819) (#3857)
[lemmy.git] / crates / api / src / community / block.rs
1 use activitypub_federation::config::Data;
2 use actix_web::web::Json;
3 use lemmy_api_common::{
4   community::{BlockCommunity, BlockCommunityResponse},
5   context::LemmyContext,
6   send_activity::{ActivityChannel, SendActivityData},
7   utils::local_user_view_from_jwt,
8 };
9 use lemmy_db_schema::{
10   source::{
11     community::{CommunityFollower, CommunityFollowerForm},
12     community_block::{CommunityBlock, CommunityBlockForm},
13   },
14   traits::{Blockable, Followable},
15 };
16 use lemmy_db_views_actor::structs::CommunityView;
17 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
18
19 #[tracing::instrument(skip(context))]
20 pub async fn block_community(
21   data: Json<BlockCommunity>,
22   context: Data<LemmyContext>,
23 ) -> Result<Json<BlockCommunityResponse>, LemmyError> {
24   let local_user_view = local_user_view_from_jwt(&data.auth, &context).await?;
25
26   let community_id = data.community_id;
27   let person_id = local_user_view.person.id;
28   let community_block_form = CommunityBlockForm {
29     person_id,
30     community_id,
31   };
32
33   if data.block {
34     CommunityBlock::block(&mut context.pool(), &community_block_form)
35       .await
36       .with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
37
38     // Also, unfollow the community, and send a federated unfollow
39     let community_follower_form = CommunityFollowerForm {
40       community_id: data.community_id,
41       person_id,
42       pending: false,
43     };
44
45     CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
46       .await
47       .ok();
48   } else {
49     CommunityBlock::unblock(&mut context.pool(), &community_block_form)
50       .await
51       .with_lemmy_type(LemmyErrorType::CommunityBlockAlreadyExists)?;
52   }
53
54   let community_view =
55     CommunityView::read(&mut context.pool(), community_id, Some(person_id), false).await?;
56
57   ActivityChannel::submit_activity(
58     SendActivityData::FollowCommunity(
59       community_view.community.clone(),
60       local_user_view.person.clone(),
61       false,
62     ),
63     &context,
64   )
65   .await?;
66
67   Ok(Json(BlockCommunityResponse {
68     blocked: data.block,
69     community_view,
70   }))
71 }