2 use actix_web::web::Data;
3 use lemmy_api_common::{
4 community::{BanFromCommunity, BanFromCommunityResponse},
6 utils::{get_local_user_view_from_jwt, is_mod_or_admin, 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;
44 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
46 let community_id = data.community_id;
47 let banned_person_id = data.person_id;
48 let remove_data = data.remove_data.unwrap_or(false);
49 let expires = data.expires.map(naive_from_unix);
51 // Verify that only mods or admins can ban
52 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
53 is_valid_body_field(&data.reason)?;
55 let community_user_ban_form = CommunityPersonBanForm {
56 community_id: data.community_id,
57 person_id: data.person_id,
58 expires: Some(expires),
62 CommunityPersonBan::ban(context.pool(), &community_user_ban_form)
64 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
66 // Also unsubscribe them from the community, if they are subscribed
67 let community_follower_form = CommunityFollowerForm {
68 community_id: data.community_id,
69 person_id: banned_person_id,
73 CommunityFollower::unfollow(context.pool(), &community_follower_form)
77 CommunityPersonBan::unban(context.pool(), &community_user_ban_form)
79 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
82 // Remove/Restore their data if that's desired
84 remove_user_data_in_community(community_id, banned_person_id, context.pool()).await?;
88 let form = ModBanFromCommunityForm {
89 mod_person_id: local_user_view.person.id,
90 other_person_id: data.person_id,
91 community_id: data.community_id,
92 reason: data.reason.clone(),
93 banned: Some(data.ban),
97 ModBanFromCommunity::create(context.pool(), &form).await?;
99 let person_id = data.person_id;
100 let person_view = PersonView::read(context.pool(), person_id).await?;
102 let res = BanFromCommunityResponse {
107 // A custom ban message
108 let message = serialize_websocket_message(&UserOperation::BanFromCommunity, &res)?;
109 context.chat_server().do_send(SendCommunityRoomMessage {