1 use activitypub_federation::config::Data;
2 use actix_web::web::Json;
3 use lemmy_api_common::{
4 community::{BanFromCommunity, BanFromCommunityResponse},
6 send_activity::{ActivityChannel, SendActivityData},
9 local_user_view_from_jwt,
10 remove_user_data_in_community,
14 use lemmy_db_schema::{
18 CommunityFollowerForm,
20 CommunityPersonBanForm,
22 moderator::{ModBanFromCommunity, ModBanFromCommunityForm},
24 traits::{Bannable, Crud, Followable},
26 use lemmy_db_views_actor::structs::PersonView;
28 error::{LemmyError, LemmyErrorExt, LemmyErrorType},
29 utils::{time::naive_from_unix, validation::is_valid_body_field},
32 #[tracing::instrument(skip(context))]
33 pub async fn ban_from_community(
34 data: Json<BanFromCommunity>,
35 context: Data<LemmyContext>,
36 ) -> Result<Json<BanFromCommunityResponse>, LemmyError> {
37 let local_user_view = local_user_view_from_jwt(&data.auth, &context).await?;
39 let banned_person_id = data.person_id;
40 let remove_data = data.remove_data.unwrap_or(false);
41 let expires = data.expires.map(naive_from_unix);
43 // Verify that only mods or admins can ban
46 local_user_view.person.id,
50 is_valid_body_field(&data.reason, false)?;
52 let community_user_ban_form = CommunityPersonBanForm {
53 community_id: data.community_id,
54 person_id: data.person_id,
55 expires: Some(expires),
59 CommunityPersonBan::ban(&mut context.pool(), &community_user_ban_form)
61 .with_lemmy_type(LemmyErrorType::CommunityUserAlreadyBanned)?;
63 // Also unsubscribe them from the community, if they are subscribed
64 let community_follower_form = CommunityFollowerForm {
65 community_id: data.community_id,
66 person_id: banned_person_id,
70 CommunityFollower::unfollow(&mut context.pool(), &community_follower_form)
74 CommunityPersonBan::unban(&mut context.pool(), &community_user_ban_form)
76 .with_lemmy_type(LemmyErrorType::CommunityUserAlreadyBanned)?;
79 // Remove/Restore their data if that's desired
81 remove_user_data_in_community(data.community_id, banned_person_id, &mut context.pool()).await?;
85 let form = ModBanFromCommunityForm {
86 mod_person_id: local_user_view.person.id,
87 other_person_id: data.person_id,
88 community_id: data.community_id,
89 reason: sanitize_html_opt(&data.reason),
90 banned: Some(data.ban),
94 ModBanFromCommunity::create(&mut context.pool(), &form).await?;
96 let person_view = PersonView::read(&mut context.pool(), data.person_id).await?;
98 ActivityChannel::submit_activity(
99 SendActivityData::BanFromCommunity(
100 local_user_view.person,
102 person_view.person.clone(),
109 Ok(Json(BanFromCommunityResponse {