1 use activitypub_federation::config::Data;
2 use actix_web::web::Json;
3 use lemmy_api_common::{
4 community::{AddModToCommunity, AddModToCommunityResponse},
6 send_activity::{ActivityChannel, SendActivityData},
7 utils::{is_mod_or_admin, local_user_view_from_jwt},
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, LemmyErrorExt, LemmyErrorType};
19 #[tracing::instrument(skip(context))]
20 pub async fn add_mod_to_community(
21 data: Json<AddModToCommunity>,
22 context: Data<LemmyContext>,
23 ) -> Result<Json<AddModToCommunityResponse>, LemmyError> {
24 let local_user_view = local_user_view_from_jwt(&data.auth, &context).await?;
26 let community_id = data.community_id;
28 // Verify that only mods or admins can add mod
29 is_mod_or_admin(&mut context.pool(), local_user_view.person.id, community_id).await?;
30 let community = Community::read(&mut context.pool(), community_id).await?;
31 if local_user_view.person.admin && !community.local {
32 return Err(LemmyErrorType::NotAModerator)?;
35 // Update in local database
36 let community_moderator_form = CommunityModeratorForm {
37 community_id: data.community_id,
38 person_id: data.person_id,
41 CommunityModerator::join(&mut context.pool(), &community_moderator_form)
43 .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
45 CommunityModerator::leave(&mut context.pool(), &community_moderator_form)
47 .with_lemmy_type(LemmyErrorType::CommunityModeratorAlreadyExists)?;
51 let form = ModAddCommunityForm {
52 mod_person_id: local_user_view.person.id,
53 other_person_id: data.person_id,
54 community_id: data.community_id,
55 removed: Some(!data.added),
58 ModAddCommunity::create(&mut context.pool(), &form).await?;
60 // Note: in case a remote mod is added, this returns the old moderators list, it will only get
61 // updated once we receive an activity from the community (like `Announce/Add/Moderator`)
62 let community_id = data.community_id;
63 let moderators = CommunityModeratorView::for_community(&mut context.pool(), community_id).await?;
65 ActivityChannel::submit_activity(
66 SendActivityData::AddModToCommunity(
67 local_user_view.person,
76 Ok(Json(AddModToCommunityResponse { moderators }))