]> Untitled Git - lemmy.git/blob - crates/api/src/community/follow.rs
Merge pull request #2593 from LemmyNet/refactor-notifications
[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, get_local_user_view_from_jwt},
7 };
8 use lemmy_db_schema::{
9   source::community::{Community, CommunityFollower, CommunityFollowerForm},
10   traits::{Crud, Followable},
11 };
12 use lemmy_db_views_actor::structs::CommunityView;
13 use lemmy_utils::{error::LemmyError, ConnectionId};
14
15 #[async_trait::async_trait(?Send)]
16 impl Perform for FollowCommunity {
17   type Response = CommunityResponse;
18
19   #[tracing::instrument(skip(context, _websocket_id))]
20   async fn perform(
21     &self,
22     context: &Data<LemmyContext>,
23     _websocket_id: Option<ConnectionId>,
24   ) -> Result<CommunityResponse, LemmyError> {
25     let data: &FollowCommunity = self;
26     let local_user_view =
27       get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
28
29     let community_id = data.community_id;
30     let community = Community::read(context.pool(), community_id).await?;
31     let community_follower_form = CommunityFollowerForm {
32       community_id: data.community_id,
33       person_id: local_user_view.person.id,
34       pending: false,
35     };
36
37     if community.local && data.follow {
38       check_community_ban(local_user_view.person.id, community_id, context.pool()).await?;
39       check_community_deleted_or_removed(community_id, context.pool()).await?;
40
41       CommunityFollower::follow(context.pool(), &community_follower_form)
42         .await
43         .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
44     }
45     if !data.follow {
46       CommunityFollower::unfollow(context.pool(), &community_follower_form)
47         .await
48         .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?;
49     }
50
51     let community_id = data.community_id;
52     let person_id = local_user_view.person.id;
53     let community_view = CommunityView::read(context.pool(), community_id, Some(person_id)).await?;
54
55     Ok(Self::Response { community_view })
56   }
57 }