]> Untitled Git - lemmy.git/blob - crates/api/src/community/follow.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api / src / community / follow.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{CommunityResponse, FollowCommunity},
5   context::LemmyContext,
6   utils::{check_community_ban, check_community_deleted_or_removed, local_user_view_from_jwt},
7 };
8 use lemmy_db_schema::{
9   source::{
10     actor_language::CommunityLanguage,
11     community::{Community, CommunityFollower, CommunityFollowerForm},
12   },
13   traits::{Crud, 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 FollowCommunity {
20   type Response = CommunityResponse;
21
22   #[tracing::instrument(skip(context))]
23   async fn perform(&self, context: &Data<LemmyContext>) -> Result<CommunityResponse, LemmyError> {
24     let data: &FollowCommunity = self;
25     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
26
27     let community_id = data.community_id;
28     let community = Community::read(&mut context.pool(), community_id).await?;
29     let mut community_follower_form = CommunityFollowerForm {
30       community_id: data.community_id,
31       person_id: local_user_view.person.id,
32       pending: false,
33     };
34
35     if data.follow {
36       if community.local {
37         check_community_ban(local_user_view.person.id, community_id, &mut context.pool()).await?;
38         check_community_deleted_or_removed(community_id, &mut context.pool()).await?;
39
40         CommunityFollower::follow(&mut context.pool(), &community_follower_form)
41           .await
42           .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
43       } else {
44         // Mark as pending, the actual federation activity is sent via `SendActivity` handler
45         community_follower_form.pending = true;
46         CommunityFollower::follow(&mut context.pool(), &community_follower_form)
47           .await
48           .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
49       }
50     }
51     if !data.follow {
52       CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
53         .await
54         .with_lemmy_type(LemmyErrorType::CommunityFollowerAlreadyExists)?;
55     }
56
57     let community_id = data.community_id;
58     let person_id = local_user_view.person.id;
59     let community_view =
60       CommunityView::read(&mut context.pool(), community_id, Some(person_id), None).await?;
61     let discussion_languages = CommunityLanguage::read(&mut context.pool(), community_id).await?;
62
63     Ok(Self::Response {
64       community_view,
65       discussion_languages,
66     })
67   }
68 }