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;
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(context.pool(), local_user_view.person.id, community_id).await?;
34 let community = Community::read(context.pool(), community_id).await?;
35 if local_user_view.person.admin && !community.local {
36 return Err(LemmyError::from_message("not_a_moderator"));
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(context.pool(), &community_moderator_form)
47 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
49 CommunityModerator::leave(context.pool(), &community_moderator_form)
51 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
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(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;
67 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
69 Ok(AddModToCommunityResponse { moderators })