2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{BanFromCommunity, BanFromCommunityResponse},
6 utils::{is_mod_or_admin, local_user_view_from_jwt, remove_user_data_in_community},
8 handlers::messages::SendCommunityRoomMessage,
9 serialize_websocket_message,
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;
28 utils::{time::naive_from_unix, validation::is_valid_body_field},
32 #[async_trait::async_trait(?Send)]
33 impl Perform for BanFromCommunity {
34 type Response = BanFromCommunityResponse;
36 #[tracing::instrument(skip(context, websocket_id))]
39 context: &Data<LemmyContext>,
40 websocket_id: Option<ConnectionId>,
41 ) -> Result<BanFromCommunityResponse, LemmyError> {
42 let data: &BanFromCommunity = self;
43 let local_user_view = local_user_view_from_jwt(&data.auth, context).await?;
45 let community_id = data.community_id;
46 let banned_person_id = data.person_id;
47 let remove_data = data.remove_data.unwrap_or(false);
48 let expires = data.expires.map(naive_from_unix);
50 // Verify that only mods or admins can ban
51 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
52 is_valid_body_field(&data.reason)?;
54 let community_user_ban_form = CommunityPersonBanForm {
55 community_id: data.community_id,
56 person_id: data.person_id,
57 expires: Some(expires),
61 CommunityPersonBan::ban(context.pool(), &community_user_ban_form)
63 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
65 // Also unsubscribe them from the community, if they are subscribed
66 let community_follower_form = CommunityFollowerForm {
67 community_id: data.community_id,
68 person_id: banned_person_id,
72 CommunityFollower::unfollow(context.pool(), &community_follower_form)
76 CommunityPersonBan::unban(context.pool(), &community_user_ban_form)
78 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
81 // Remove/Restore their data if that's desired
83 remove_user_data_in_community(community_id, banned_person_id, context.pool()).await?;
87 let form = ModBanFromCommunityForm {
88 mod_person_id: local_user_view.person.id,
89 other_person_id: data.person_id,
90 community_id: data.community_id,
91 reason: data.reason.clone(),
92 banned: Some(data.ban),
96 ModBanFromCommunity::create(context.pool(), &form).await?;
98 let person_id = data.person_id;
99 let person_view = PersonView::read(context.pool(), person_id).await?;
101 let res = BanFromCommunityResponse {
106 // A custom ban message
107 let message = serialize_websocket_message(&UserOperation::BanFromCommunity, &res)?;
108 context.chat_server().do_send(SendCommunityRoomMessage {