2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{AddModToCommunity, AddModToCommunityResponse},
5 utils::{get_local_user_view_from_jwt, is_mod_or_admin},
6 websocket::{messages::SendCommunityRoomMessage, UserOperation},
10 objects::{community::ApubCommunity, person::ApubPerson},
11 protocol::activities::community::{add_mod::AddMod, remove_mod::RemoveMod},
13 use lemmy_db_schema::{
15 community::{Community, CommunityModerator, CommunityModeratorForm},
16 moderator::{ModAddCommunity, ModAddCommunityForm},
19 traits::{Crud, Joinable},
21 use lemmy_db_views_actor::structs::CommunityModeratorView;
22 use lemmy_utils::{error::LemmyError, ConnectionId};
24 #[async_trait::async_trait(?Send)]
25 impl Perform for AddModToCommunity {
26 type Response = AddModToCommunityResponse;
28 #[tracing::instrument(skip(context, websocket_id))]
31 context: &Data<LemmyContext>,
32 websocket_id: Option<ConnectionId>,
33 ) -> Result<AddModToCommunityResponse, LemmyError> {
34 let data: &AddModToCommunity = self;
36 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
38 let community_id = data.community_id;
40 // Verify that only mods or admins can add mod
41 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
42 let community = Community::read(context.pool(), community_id).await?;
43 if local_user_view.person.admin && !community.local {
44 return Err(LemmyError::from_message("not_a_moderator"));
47 // Update in local database
48 let community_moderator_form = CommunityModeratorForm {
49 community_id: data.community_id,
50 person_id: data.person_id,
53 CommunityModerator::join(context.pool(), &community_moderator_form)
55 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
57 CommunityModerator::leave(context.pool(), &community_moderator_form)
59 .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?;
63 let form = ModAddCommunityForm {
64 mod_person_id: local_user_view.person.id,
65 other_person_id: data.person_id,
66 community_id: data.community_id,
67 removed: Some(!data.added),
70 ModAddCommunity::create(context.pool(), &form).await?;
72 // Send to federated instances
73 let updated_mod_id = data.person_id;
74 let updated_mod: ApubPerson = Person::read(context.pool(), updated_mod_id).await?.into();
75 let community: ApubCommunity = community.into();
80 &local_user_view.person.into(),
88 &local_user_view.person.into(),
94 // Note: in case a remote mod is added, this returns the old moderators list, it will only get
95 // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
96 let community_id = data.community_id;
97 let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?;
99 let res = AddModToCommunityResponse { moderators };
100 context.chat_server().do_send(SendCommunityRoomMessage {
101 op: UserOperation::AddModToCommunity,
102 response: res.clone(),