]> Untitled Git - lemmy.git/blob - crates/api/src/community/add_mod.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / api / src / community / add_mod.rs
1 use crate::Perform;
2 use actix_web::web::Data;
3 use lemmy_api_common::{
4   community::{AddModToCommunity, AddModToCommunityResponse},
5   context::LemmyContext,
6   utils::{is_mod_or_admin, local_user_view_from_jwt},
7 };
8 use lemmy_db_schema::{
9   source::{
10     community::{Community, CommunityModerator, CommunityModeratorForm},
11     moderator::{ModAddCommunity, ModAddCommunityForm},
12   },
13   traits::{Crud, Joinable},
14 };
15 use lemmy_db_views_actor::structs::CommunityModeratorView;
16 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
17
18 #[async_trait::async_trait(?Send)]
19 impl Perform for AddModToCommunity {
20   type Response = AddModToCommunityResponse;
21
22   #[tracing::instrument(skip(context))]
23   async fn perform(
24     &self,
25     context: &Data<LemmyContext>,
26   ) -> Result<AddModToCommunityResponse, LemmyError> {
27     let data: &AddModToCommunity = self;
28     let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
29
30     let community_id = data.community_id;
31
32     // Verify that only mods or admins can add mod
33     is_mod_or_admin(&mut context.pool(), local_user_view.person.id, community_id).await?;
34     let community = Community::read(&mut context.pool(), community_id).await?;
35     if local_user_view.person.admin && !community.local {
36       return Err(LemmyErrorType::NotAModerator)?;
37     }
38
39     // Update in local database
40     let community_moderator_form = CommunityModeratorForm {
41       community_id: data.community_id,
42       person_id: data.person_id,
43     };
44     if data.added {
45       CommunityModerator::join(&mut context.pool(), &community_moderator_form)
46         .await
47         .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
48     } else {
49       CommunityModerator::leave(&mut context.pool(), &community_moderator_form)
50         .await
51         .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
52     }
53
54     // Mod tables
55     let form = ModAddCommunityForm {
56       mod_person_id: local_user_view.person.id,
57       other_person_id: data.person_id,
58       community_id: data.community_id,
59       removed: Some(!data.added),
60     };
61
62     ModAddCommunity::create(&mut context.pool(), &form).await?;
63
64     // Note: in case a remote mod is added, this returns the old moderators list, it will only get
65     //       updated once we receive an activity from the community (like `Announce/Add/Moderator`)
66     let community_id = data.community_id;
67     let moderators =
68       CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
69
70     Ok(AddModToCommunityResponse { moderators })
71   }
72 }