2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{BanFromCommunity, BanFromCommunityResponse},
8 local_user_view_from_jwt,
9 remove_user_data_in_community,
13 use lemmy_db_schema::{
17 CommunityFollowerForm,
19 CommunityPersonBanForm,
21 moderator::{ModBanFromCommunity, ModBanFromCommunityForm},
23 traits::{Bannable, Crud, Followable},
25 use lemmy_db_views_actor::structs::PersonView;
27 error::{LemmyError, LemmyErrorExt, LemmyErrorType},
28 utils::{time::naive_from_unix, validation::is_valid_body_field},
31 #[async_trait::async_trait(?Send)]
32 impl Perform for BanFromCommunity {
33 type Response = BanFromCommunityResponse;
35 #[tracing::instrument(skip(context))]
38 context: &Data<LemmyContext>,
39 ) -> Result<BanFromCommunityResponse, LemmyError> {
40 let data: &BanFromCommunity = self;
41 let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
43 let community_id = data.community_id;
44 let banned_person_id = data.person_id;
45 let remove_data = data.remove_data.unwrap_or(false);
46 let expires = data.expires.map(naive_from_unix);
48 // Verify that only mods or admins can ban
49 is_mod_or_admin(&mut context.pool(), local_user_view.person.id, community_id).await?;
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(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_id = data.person_id;
97 let person_view = PersonView::read(&mut context.pool(), person_id).await?;
99 Ok(BanFromCommunityResponse {