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},
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;
30 let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
32 let community_id = data.community_id;
34 // Verify that only mods or admins can add mod
35 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
36 let community = Community::read(context.pool(), community_id).await?;
37 if local_user_view.person.admin && !community.local {
38 return Err(LemmyError::from_message("not_a_moderator"));
41 // Update in local database
42 let community_moderator_form = CommunityModeratorForm {
43 community_id: data.community_id,
44 person_id: data.person_id,
47 CommunityModerator::join(context.pool(), &community_moderator_form)
49 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
51 CommunityModerator::leave(context.pool(), &community_moderator_form)
53 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
57 let form = ModAddCommunityForm {
58 mod_person_id: local_user_view.person.id,
59 other_person_id: data.person_id,
60 community_id: data.community_id,
61 removed: Some(!data.added),
64 ModAddCommunity::create(context.pool(), &form).await?;
66 // Note: in case a remote mod is added, this returns the old moderators list, it will only get
67 // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
68 let community_id = data.community_id;
69 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
71 let res = AddModToCommunityResponse { moderators };
72 context.send_mod_ws_message(
73 &UserOperation::AddModToCommunity,