]> Untitled Git - lemmy.git/blob - crates/api/src/community/follow.rs
Replace Option<bool> with bool for PostQuery and CommentQuery (#3819) (#3857)
[lemmy.git] / crates / api / src / community / follow.rs
1 use activitypub_federation::config::Data;
2 use actix_web::web::Json;
3 use lemmy_api_common::{
4   community::{CommunityResponse, FollowCommunity},
5   context::LemmyContext,
6   send_activity::{ActivityChannel, SendActivityData},
7   utils::{check_community_ban, check_community_deleted_or_removed, local_user_view_from_jwt},
8 };
9 use lemmy_db_schema::{
10   source::{
11     actor_language::CommunityLanguage,
12     community::{Community, CommunityFollower, CommunityFollowerForm},
13   },
14   traits::{Crud, 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 follow_community(
21   data: Json<FollowCommunity>,
22   context: Data<LemmyContext>,
23 ) -> Result<Json<CommunityResponse>, LemmyError> {
24   let local_user_view = local_user_view_from_jwt(&data.auth, &context).await?;
25
26   let community = Community::read(&mut context.pool(), data.community_id).await?;
27   let mut community_follower_form = CommunityFollowerForm {
28     community_id: community.id,
29     person_id: local_user_view.person.id,
30     pending: false,
31   };
32
33   if data.follow {
34     if community.local {
35       check_community_ban(local_user_view.person.id, community.id, &mut context.pool()).await?;
36       check_community_deleted_or_removed(community.id, &mut context.pool()).await?;
37
38       CommunityFollower::follow(&mut context.pool(), &community_follower_form)
39         .await
40         .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
41     } else {
42       // Mark as pending, the actual federation activity is sent via `SendActivity` handler
43       community_follower_form.pending = true;
44       CommunityFollower::follow(&mut context.pool(), &community_follower_form)
45         .await
46         .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
47     }
48   }
49   if !data.follow {
50     CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
51       .await
52       .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
53   }
54
55   ActivityChannel::submit_activity(
56     SendActivityData::FollowCommunity(community, local_user_view.person.clone(), data.follow),
57     &context,
58   )
59   .await?;
60
61   let community_id = data.community_id;
62   let person_id = local_user_view.person.id;
63   let community_view =
64     CommunityView::read(&mut context.pool(), community_id, Some(person_id), false).await?;
65   let discussion_languages = CommunityLanguage::read(&mut context.pool(), community_id).await?;
66
67   Ok(Json(CommunityResponse {
68     community_view,
69     discussion_languages,
70   }))
71 }