2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{AddModToCommunity, AddModToCommunityResponse},
6 utils::{is_mod_or_admin, local_user_view_from_jwt},
10 community::{Community, CommunityModerator, CommunityModeratorForm},
11 moderator::{ModAddCommunity, ModAddCommunityForm},
13 traits::{Crud, Joinable},
15 use lemmy_db_views_actor::structs::CommunityModeratorView;
16 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
18 #[async_trait::async_trait(?Send)]
19 impl Perform for AddModToCommunity {
20 type Response = AddModToCommunityResponse;
22 #[tracing::instrument(skip(context))]
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?;
30 let community_id = data.community_id;
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)?;
39 // Update in local database
40 let community_moderator_form = CommunityModeratorForm {
41 community_id: data.community_id,
42 person_id: data.person_id,
45 CommunityModerator::join(&mut context.pool(), &community_moderator_form)
47 .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
49 CommunityModerator::leave(&mut context.pool(), &community_moderator_form)
51 .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
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),
62 ModAddCommunity::create(&mut context.pool(), &form).await?;
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;
68 CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
70 Ok(AddModToCommunityResponse { moderators })