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