]> Untitled Git - lemmy.git/blob - crates/apub_receive/src/activities/community/block_user.rs
Apub inbox rewrite (#1652)
[lemmy.git] / crates / apub_receive / src / activities / community / block_user.rs
1 use crate::activities::{verify_activity, verify_mod_action, verify_person_in_community};
2 use activitystreams::activity::kind::BlockType;
3 use lemmy_api_common::blocking;
4 use lemmy_apub::fetcher::{
5   community::get_or_fetch_and_upsert_community,
6   person::get_or_fetch_and_upsert_person,
7 };
8 use lemmy_apub_lib::{ActivityCommonFields, ActivityHandler, PublicUrl};
9 use lemmy_db_queries::{Bannable, Followable};
10 use lemmy_db_schema::source::community::{
11   CommunityFollower,
12   CommunityFollowerForm,
13   CommunityPersonBan,
14   CommunityPersonBanForm,
15 };
16 use lemmy_utils::LemmyError;
17 use lemmy_websocket::LemmyContext;
18 use url::Url;
19
20 #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
21 #[serde(rename_all = "camelCase")]
22 pub struct BlockUserFromCommunity {
23   to: PublicUrl,
24   pub(in crate::activities::community) object: Url,
25   cc: [Url; 1],
26   #[serde(rename = "type")]
27   kind: BlockType,
28   #[serde(flatten)]
29   common: ActivityCommonFields,
30 }
31
32 #[async_trait::async_trait(?Send)]
33 impl ActivityHandler for BlockUserFromCommunity {
34   async fn verify(
35     &self,
36     context: &LemmyContext,
37     request_counter: &mut i32,
38   ) -> Result<(), LemmyError> {
39     verify_activity(self.common())?;
40     verify_person_in_community(&self.common.actor, &self.cc, context, request_counter).await?;
41     verify_mod_action(&self.common.actor, self.cc[0].clone(), context).await?;
42     Ok(())
43   }
44
45   async fn receive(
46     &self,
47     context: &LemmyContext,
48     request_counter: &mut i32,
49   ) -> Result<(), LemmyError> {
50     let community =
51       get_or_fetch_and_upsert_community(&self.cc[0], context, request_counter).await?;
52     let blocked_user =
53       get_or_fetch_and_upsert_person(&self.object, context, request_counter).await?;
54
55     let community_user_ban_form = CommunityPersonBanForm {
56       community_id: community.id,
57       person_id: blocked_user.id,
58     };
59
60     blocking(context.pool(), move |conn: &'_ _| {
61       CommunityPersonBan::ban(conn, &community_user_ban_form)
62     })
63     .await??;
64
65     // Also unsubscribe them from the community, if they are subscribed
66     let community_follower_form = CommunityFollowerForm {
67       community_id: community.id,
68       person_id: blocked_user.id,
69       pending: false,
70     };
71     blocking(context.pool(), move |conn: &'_ _| {
72       CommunityFollower::unfollow(conn, &community_follower_form)
73     })
74     .await?
75     .ok();
76
77     Ok(())
78   }
79
80   fn common(&self) -> &ActivityCommonFields {
81     &self.common
82   }
83 }