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},
7 websocket::{messages::SendCommunityRoomMessage, UserOperation},
13 CommunityFollowerForm,
15 CommunityPersonBanForm,
17 moderator::{ModBanFromCommunity, ModBanFromCommunityForm},
19 traits::{Bannable, Crud, Followable},
21 use lemmy_db_views_actor::structs::PersonViewSafe;
22 use lemmy_utils::{error::LemmyError, utils::naive_from_unix, ConnectionId};
24 #[async_trait::async_trait(?Send)]
25 impl Perform for BanFromCommunity {
26 type Response = BanFromCommunityResponse;
28 #[tracing::instrument(skip(context, websocket_id))]
31 context: &Data<LemmyContext>,
32 websocket_id: Option<ConnectionId>,
33 ) -> Result<BanFromCommunityResponse, LemmyError> {
34 let data: &BanFromCommunity = self;
36 get_local_user_view_from_jwt(&data.auth, context.pool(), context.secret()).await?;
38 let community_id = data.community_id;
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
44 is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?;
46 let community_user_ban_form = CommunityPersonBanForm {
47 community_id: data.community_id,
48 person_id: data.person_id,
49 expires: Some(expires),
53 CommunityPersonBan::ban(context.pool(), &community_user_ban_form)
55 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
57 // Also unsubscribe them from the community, if they are subscribed
58 let community_follower_form = CommunityFollowerForm {
59 community_id: data.community_id,
60 person_id: banned_person_id,
64 CommunityFollower::unfollow(context.pool(), &community_follower_form)
68 CommunityPersonBan::unban(context.pool(), &community_user_ban_form)
70 .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?;
73 // Remove/Restore their data if that's desired
75 remove_user_data_in_community(community_id, banned_person_id, context.pool()).await?;
79 let form = ModBanFromCommunityForm {
80 mod_person_id: local_user_view.person.id,
81 other_person_id: data.person_id,
82 community_id: data.community_id,
83 reason: data.reason.clone(),
84 banned: Some(data.ban),
88 ModBanFromCommunity::create(context.pool(), &form).await?;
90 let person_id = data.person_id;
91 let person_view = PersonViewSafe::read(context.pool(), person_id).await?;
93 let res = BanFromCommunityResponse {
98 context.chat_server().do_send(SendCommunityRoomMessage {
99 op: UserOperation::BanFromCommunity,
100 response: res.clone(),