2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{AddModToCommunity, AddModToCommunityResponse},
6 utils::{get_local_user_view_from_jwt, is_mod_or_admin},
7 websocket::UserOperation,
11 community::{Community, CommunityModerator, CommunityModeratorForm},
12 moderator::{ModAddCommunity, ModAddCommunityForm},
14 traits::{Crud, Joinable},
16 use lemmy_db_views_actor::structs::CommunityModeratorView;
17 use lemmy_utils::{error::LemmyError, ConnectionId};
19 #[async_trait::async_trait(?Send)]
20 impl Perform for AddModToCommunity {
21 type Response = AddModToCommunityResponse;
23 #[tracing::instrument(skip(context, websocket_id))]
26 context: &Data<LemmyContext>,
27 websocket_id: Option<ConnectionId>,
28 ) -> Result<AddModToCommunityResponse, LemmyError> {
29 let data: &AddModToCommunity = self;
31 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
33 let community_id = data.community_id;
35 // Verify that only mods or admins can add mod
36 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
37 let community = Community::read(context.pool(), community_id).await?;
38 if local_user_view.person.admin && !community.local {
39 return Err(LemmyError::from_message("not_a_moderator"));
42 // Update in local database
43 let community_moderator_form = CommunityModeratorForm {
44 community_id: data.community_id,
45 person_id: data.person_id,
48 CommunityModerator::join(context.pool(), &community_moderator_form)
50 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
52 CommunityModerator::leave(context.pool(), &community_moderator_form)
54 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
58 let form = ModAddCommunityForm {
59 mod_person_id: local_user_view.person.id,
60 other_person_id: data.person_id,
61 community_id: data.community_id,
62 removed: Some(!data.added),
65 ModAddCommunity::create(context.pool(), &form).await?;
67 // Note: in case a remote mod is added, this returns the old moderators list, it will only get
68 // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
69 let community_id = data.community_id;
70 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
72 let res = AddModToCommunityResponse { moderators };
73 context.send_mod_ws_message(
74 &UserOperation::AddModToCommunity,