]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/block/block_user.rs
Extract Activitypub logic into separate library (#2288)
[lemmy.git] / crates / apub / src / activities / block / block_user.rs
1 use crate::{
2   activities::{
3     block::{generate_cc, generate_instance_inboxes, SiteOrCommunity},
4     community::{announce::GetCommunity, send_activity_in_community},
5     generate_activity_id,
6     send_lemmy_activity,
7     verify_is_public,
8     verify_mod_action,
9     verify_person_in_community,
10   },
11   activity_lists::AnnouncableActivities,
12   local_instance,
13   objects::{community::ApubCommunity, person::ApubPerson},
14   protocol::activities::block::block_user::BlockUser,
15   ActorType,
16 };
17 use activitypub_federation::{
18   core::object_id::ObjectId,
19   data::Data,
20   traits::ActivityHandler,
21   utils::verify_domains_match,
22 };
23 use activitystreams_kinds::{activity::BlockType, public};
24 use anyhow::anyhow;
25 use chrono::NaiveDateTime;
26 use lemmy_api_common::utils::{blocking, remove_user_data, remove_user_data_in_community};
27 use lemmy_db_schema::{
28   source::{
29     community::{
30       CommunityFollower,
31       CommunityFollowerForm,
32       CommunityPersonBan,
33       CommunityPersonBanForm,
34     },
35     moderator::{ModBan, ModBanForm, ModBanFromCommunity, ModBanFromCommunityForm},
36     person::Person,
37   },
38   traits::{Bannable, Crud, Followable},
39 };
40 use lemmy_utils::{error::LemmyError, settings::structs::Settings, utils::convert_datetime};
41 use lemmy_websocket::LemmyContext;
42 use url::Url;
43
44 impl BlockUser {
45   pub(in crate::activities::block) async fn new(
46     target: &SiteOrCommunity,
47     user: &ApubPerson,
48     mod_: &ApubPerson,
49     remove_data: Option<bool>,
50     reason: Option<String>,
51     expires: Option<NaiveDateTime>,
52     context: &LemmyContext,
53   ) -> Result<BlockUser, LemmyError> {
54     Ok(BlockUser {
55       actor: ObjectId::new(mod_.actor_id()),
56       to: vec![public()],
57       object: ObjectId::new(user.actor_id()),
58       cc: generate_cc(target, context.pool()).await?,
59       target: target.id(),
60       kind: BlockType::Block,
61       remove_data,
62       summary: reason,
63       id: generate_activity_id(
64         BlockType::Block,
65         &context.settings().get_protocol_and_hostname(),
66       )?,
67       expires: expires.map(convert_datetime),
68       unparsed: Default::default(),
69     })
70   }
71
72   #[tracing::instrument(skip_all)]
73   pub async fn send(
74     target: &SiteOrCommunity,
75     user: &ApubPerson,
76     mod_: &ApubPerson,
77     remove_data: bool,
78     reason: Option<String>,
79     expires: Option<NaiveDateTime>,
80     context: &LemmyContext,
81   ) -> Result<(), LemmyError> {
82     let block = BlockUser::new(
83       target,
84       user,
85       mod_,
86       Some(remove_data),
87       reason,
88       expires,
89       context,
90     )
91     .await?;
92     let block_id = block.id.clone();
93
94     match target {
95       SiteOrCommunity::Site(_) => {
96         let inboxes = generate_instance_inboxes(user, context.pool()).await?;
97         send_lemmy_activity(context, &block, &block_id, mod_, inboxes, false).await
98       }
99       SiteOrCommunity::Community(c) => {
100         let activity = AnnouncableActivities::BlockUser(block);
101         let inboxes = vec![user.shared_inbox_or_inbox_url()];
102         send_activity_in_community(activity, &block_id, mod_, c, inboxes, context).await
103       }
104     }
105   }
106 }
107
108 #[async_trait::async_trait(?Send)]
109 impl ActivityHandler for BlockUser {
110   type DataType = LemmyContext;
111   type Error = LemmyError;
112
113   fn id(&self) -> &Url {
114     &self.id
115   }
116
117   fn actor(&self) -> &Url {
118     self.actor.inner()
119   }
120
121   #[tracing::instrument(skip_all)]
122   async fn verify(
123     &self,
124     context: &Data<LemmyContext>,
125     request_counter: &mut i32,
126   ) -> Result<(), LemmyError> {
127     verify_is_public(&self.to, &self.cc)?;
128     match self
129       .target
130       .dereference::<LemmyError>(context, local_instance(context), request_counter)
131       .await?
132     {
133       SiteOrCommunity::Site(site) => {
134         let domain = self.object.inner().domain().expect("url needs domain");
135         if Settings::get().hostname == domain {
136           return Err(
137             anyhow!("Site bans from remote instance can't affect user's home instance").into(),
138           );
139         }
140         // site ban can only target a user who is on the same instance as the actor (admin)
141         verify_domains_match(&site.actor_id(), self.actor.inner())?;
142         verify_domains_match(&site.actor_id(), self.object.inner())?;
143       }
144       SiteOrCommunity::Community(community) => {
145         verify_person_in_community(&self.actor, &community, context, request_counter).await?;
146         verify_mod_action(
147           &self.actor,
148           self.object.inner(),
149           &community,
150           context,
151           request_counter,
152         )
153         .await?;
154       }
155     }
156     Ok(())
157   }
158
159   #[tracing::instrument(skip_all)]
160   async fn receive(
161     self,
162     context: &Data<LemmyContext>,
163     request_counter: &mut i32,
164   ) -> Result<(), LemmyError> {
165     let expires = self.expires.map(|u| u.naive_local());
166     let mod_person = self
167       .actor
168       .dereference::<LemmyError>(context, local_instance(context), request_counter)
169       .await?;
170     let blocked_person = self
171       .object
172       .dereference::<LemmyError>(context, local_instance(context), request_counter)
173       .await?;
174     let target = self
175       .target
176       .dereference::<LemmyError>(context, local_instance(context), request_counter)
177       .await?;
178     match target {
179       SiteOrCommunity::Site(_site) => {
180         let blocked_person = blocking(context.pool(), move |conn| {
181           Person::ban_person(conn, blocked_person.id, true, expires)
182         })
183         .await??;
184         if self.remove_data.unwrap_or(false) {
185           remove_user_data(blocked_person.id, context.pool()).await?;
186         }
187
188         // write mod log
189         let form = ModBanForm {
190           mod_person_id: mod_person.id,
191           other_person_id: blocked_person.id,
192           reason: self.summary,
193           banned: Some(true),
194           expires,
195         };
196         blocking(context.pool(), move |conn| ModBan::create(conn, &form)).await??;
197       }
198       SiteOrCommunity::Community(community) => {
199         let community_user_ban_form = CommunityPersonBanForm {
200           community_id: community.id,
201           person_id: blocked_person.id,
202           expires: Some(expires),
203         };
204         blocking(context.pool(), move |conn| {
205           CommunityPersonBan::ban(conn, &community_user_ban_form)
206         })
207         .await??;
208
209         // Also unsubscribe them from the community, if they are subscribed
210         let community_follower_form = CommunityFollowerForm {
211           community_id: community.id,
212           person_id: blocked_person.id,
213           pending: false,
214         };
215         blocking(context.pool(), move |conn: &'_ _| {
216           CommunityFollower::unfollow(conn, &community_follower_form)
217         })
218         .await?
219         .ok();
220
221         if self.remove_data.unwrap_or(false) {
222           remove_user_data_in_community(community.id, blocked_person.id, context.pool()).await?;
223         }
224
225         // write to mod log
226         let form = ModBanFromCommunityForm {
227           mod_person_id: mod_person.id,
228           other_person_id: blocked_person.id,
229           community_id: community.id,
230           reason: self.summary,
231           banned: Some(true),
232           expires,
233         };
234         blocking(context.pool(), move |conn| {
235           ModBanFromCommunity::create(conn, &form)
236         })
237         .await??;
238       }
239     }
240
241     Ok(())
242   }
243 }
244
245 #[async_trait::async_trait(?Send)]
246 impl GetCommunity for BlockUser {
247   #[tracing::instrument(skip_all)]
248   async fn get_community(
249     &self,
250     context: &LemmyContext,
251     request_counter: &mut i32,
252   ) -> Result<ApubCommunity, LemmyError> {
253     let target = self
254       .target
255       .dereference::<LemmyError>(context, local_instance(context), request_counter)
256       .await?;
257     match target {
258       SiteOrCommunity::Community(c) => Ok(c),
259       SiteOrCommunity::Site(_) => Err(anyhow!("Calling get_community() on site activity").into()),
260     }
261   }
262 }