]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
bc8379f111b9b070420d6f951f74592cf883265c
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use self::following::send_follow_community;
2 use crate::{
3   activities::{
4     block::{send_ban_from_community, send_ban_from_site},
5     community::{
6       collection_add::{send_add_mod_to_community, send_feature_post},
7       lock_page::send_lock_post,
8       update::send_update_community,
9     },
10     create_or_update::private_message::send_create_or_update_pm,
11     deletion::{
12       delete_user::delete_user,
13       send_apub_delete_in_community,
14       send_apub_delete_in_community_new,
15       send_apub_delete_private_message,
16       DeletableObjects,
17     },
18     voting::send_like_activity,
19   },
20   objects::{community::ApubCommunity, person::ApubPerson},
21   protocol::activities::{
22     community::report::Report,
23     create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
24     CreateOrUpdateType,
25   },
26   CONTEXT,
27 };
28 use activitypub_federation::{
29   activity_queue::send_activity,
30   config::Data,
31   fetch::object_id::ObjectId,
32   kinds::public,
33   protocol::context::WithContext,
34   traits::{ActivityHandler, Actor},
35 };
36 use anyhow::anyhow;
37 use lemmy_api_common::{
38   context::LemmyContext,
39   send_activity::{ActivityChannel, SendActivityData},
40 };
41 use lemmy_db_schema::{
42   newtypes::CommunityId,
43   source::{
44     activity::{SentActivity, SentActivityForm},
45     community::Community,
46     instance::Instance,
47   },
48 };
49 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
50 use lemmy_utils::{
51   error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
52   spawn_try_task,
53   SYNCHRONOUS_FEDERATION,
54 };
55 use moka::future::Cache;
56 use once_cell::sync::Lazy;
57 use serde::Serialize;
58 use std::{ops::Deref, sync::Arc, time::Duration};
59 use tracing::info;
60 use url::{ParseError, Url};
61 use uuid::Uuid;
62
63 pub mod block;
64 pub mod community;
65 pub mod create_or_update;
66 pub mod deletion;
67 pub mod following;
68 pub mod unfederated;
69 pub mod voting;
70
71 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
72 /// so there is no harm in caching it for a longer time.
73 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
74
75 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
76 /// doesn't have a site ban.
77 #[tracing::instrument(skip_all)]
78 async fn verify_person(
79   person_id: &ObjectId<ApubPerson>,
80   context: &Data<LemmyContext>,
81 ) -> Result<(), LemmyError> {
82   let person = person_id.dereference(context).await?;
83   if person.banned {
84     return Err(anyhow!("Person {} is banned", person_id))
85       .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
86   }
87   Ok(())
88 }
89
90 /// Fetches the person and community to verify their type, then checks if person is banned from site
91 /// or community.
92 #[tracing::instrument(skip_all)]
93 pub(crate) async fn verify_person_in_community(
94   person_id: &ObjectId<ApubPerson>,
95   community: &ApubCommunity,
96   context: &Data<LemmyContext>,
97 ) -> Result<(), LemmyError> {
98   let person = person_id.dereference(context).await?;
99   if person.banned {
100     return Err(LemmyErrorType::PersonIsBannedFromSite)?;
101   }
102   let person_id = person.id;
103   let community_id = community.id;
104   let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
105     .await
106     .is_ok();
107   if is_banned {
108     return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
109   }
110
111   Ok(())
112 }
113
114 /// Verify that mod action in community was performed by a moderator.
115 ///
116 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
117 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
118 /// * `community` - The community inside which moderation is happening
119 #[tracing::instrument(skip_all)]
120 pub(crate) async fn verify_mod_action(
121   mod_id: &ObjectId<ApubPerson>,
122   object_id: &Url,
123   community_id: CommunityId,
124   context: &Data<LemmyContext>,
125 ) -> Result<(), LemmyError> {
126   let mod_ = mod_id.dereference(context).await?;
127
128   let is_mod_or_admin =
129     CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
130   if is_mod_or_admin {
131     return Ok(());
132   }
133
134   // mod action comes from the same instance as the moderated object, so it was presumably done
135   // by an instance admin.
136   // TODO: federate instance admin status and check it here
137   if mod_id.inner().domain() == object_id.domain() {
138     return Ok(());
139   }
140
141   Err(LemmyErrorType::NotAModerator)?
142 }
143
144 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
145   if ![to, cc].iter().any(|set| set.contains(&public())) {
146     Err(LemmyErrorType::ObjectIsNotPublic)?;
147   }
148   Ok(())
149 }
150
151 pub(crate) fn verify_community_matches<T>(
152   a: &ObjectId<ApubCommunity>,
153   b: T,
154 ) -> Result<(), LemmyError>
155 where
156   T: Into<ObjectId<ApubCommunity>>,
157 {
158   let b: ObjectId<ApubCommunity> = b.into();
159   if a != &b {
160     Err(LemmyErrorType::InvalidCommunity)?;
161   }
162   Ok(())
163 }
164
165 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
166   if community.deleted || community.removed {
167     Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
168   } else {
169     Ok(())
170   }
171 }
172
173 /// Generate a unique ID for an activity, in the format:
174 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
175 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
176 where
177   T: ToString,
178 {
179   let id = format!(
180     "{}/activities/{}/{}",
181     protocol_and_hostname,
182     kind.to_string().to_lowercase(),
183     Uuid::new_v4()
184   );
185   Url::parse(&id)
186 }
187
188 #[tracing::instrument(skip_all)]
189 async fn send_lemmy_activity<Activity, ActorT>(
190   data: &Data<LemmyContext>,
191   activity: Activity,
192   actor: &ActorT,
193   mut inbox: Vec<Url>,
194   sensitive: bool,
195 ) -> Result<(), LemmyError>
196 where
197   Activity: ActivityHandler + Serialize + Send + Sync + Clone,
198   ActorT: Actor,
199   Activity: ActivityHandler<Error = LemmyError>,
200 {
201   static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
202     Cache::builder()
203       .max_capacity(1)
204       .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
205       .build()
206   });
207   let dead_instances = CACHE
208     .try_get_with((), async {
209       Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
210     })
211     .await?;
212
213   inbox.retain(|i| {
214     let domain = i.domain().expect("has domain").to_string();
215     !dead_instances.contains(&domain)
216   });
217   info!("Sending activity {}", activity.id().to_string());
218   let activity = WithContext::new(activity, CONTEXT.deref().clone());
219
220   let form = SentActivityForm {
221     ap_id: activity.id().clone().into(),
222     data: serde_json::to_value(activity.clone())?,
223     sensitive,
224   };
225   SentActivity::create(&mut data.pool(), form).await?;
226   send_activity(activity, actor, inbox, data).await?;
227
228   Ok(())
229 }
230
231 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
232   while let Some(data) = ActivityChannel::retrieve_activity().await {
233     match_outgoing_activities(data, &context.reset_request_count()).await?
234   }
235   Ok(())
236 }
237
238 pub async fn match_outgoing_activities(
239   data: SendActivityData,
240   context: &Data<LemmyContext>,
241 ) -> LemmyResult<()> {
242   let context = context.reset_request_count();
243   let fed_task = async {
244     use SendActivityData::*;
245     match data {
246       CreatePost(post) => {
247         let creator_id = post.creator_id;
248         CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
249       }
250       UpdatePost(post) => {
251         let creator_id = post.creator_id;
252         CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Update, context).await
253       }
254       DeletePost(post, person, data) => {
255         send_apub_delete_in_community_new(
256           person,
257           post.community_id,
258           DeletableObjects::Post(post.into()),
259           None,
260           data.deleted,
261           context,
262         )
263         .await
264       }
265       RemovePost(post, person, data) => {
266         send_apub_delete_in_community_new(
267           person,
268           post.community_id,
269           DeletableObjects::Post(post.into()),
270           data.reason.or_else(|| Some(String::new())),
271           data.removed,
272           context,
273         )
274         .await
275       }
276       LockPost(post, actor, locked) => send_lock_post(post, actor, locked, context).await,
277       FeaturePost(post, actor, featured) => send_feature_post(post, actor, featured, context).await,
278       CreateComment(comment) => {
279         let creator_id = comment.creator_id;
280         CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
281       }
282       UpdateComment(comment) => {
283         let creator_id = comment.creator_id;
284         CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Update, context).await
285       }
286       DeleteComment(comment, actor, community) => {
287         let is_deleted = comment.deleted;
288         let deletable = DeletableObjects::Comment(comment.into());
289         send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
290       }
291       RemoveComment(comment, actor, community, reason) => {
292         let is_removed = comment.removed;
293         let deletable = DeletableObjects::Comment(comment.into());
294         send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
295           .await
296       }
297       LikePostOrComment(object_id, person, community, score) => {
298         send_like_activity(object_id, person, community, score, context).await
299       }
300       FollowCommunity(community, person, follow) => {
301         send_follow_community(community, person, follow, &context).await
302       }
303       UpdateCommunity(actor, community) => send_update_community(community, actor, context).await,
304       DeleteCommunity(actor, community, removed) => {
305         let deletable = DeletableObjects::Community(community.clone().into());
306         send_apub_delete_in_community(actor, community, deletable, None, removed, &context).await
307       }
308       RemoveCommunity(actor, community, reason, removed) => {
309         let deletable = DeletableObjects::Community(community.clone().into());
310         send_apub_delete_in_community(
311           actor,
312           community,
313           deletable,
314           reason.clone().or_else(|| Some(String::new())),
315           removed,
316           &context,
317         )
318         .await
319       }
320       AddModToCommunity(actor, community_id, updated_mod_id, added) => {
321         send_add_mod_to_community(actor, community_id, updated_mod_id, added, context).await
322       }
323       BanFromCommunity(mod_, community_id, target, data) => {
324         send_ban_from_community(mod_, community_id, target, data, context).await
325       }
326       BanFromSite(mod_, target, data) => send_ban_from_site(mod_, target, data, context).await,
327       CreatePrivateMessage(pm) => {
328         send_create_or_update_pm(pm, CreateOrUpdateType::Create, context).await
329       }
330       UpdatePrivateMessage(pm) => {
331         send_create_or_update_pm(pm, CreateOrUpdateType::Update, context).await
332       }
333       DeletePrivateMessage(person, pm, deleted) => {
334         send_apub_delete_private_message(&person.into(), pm, deleted, context).await
335       }
336       DeleteUser(person) => delete_user(person, context).await,
337       CreateReport(url, actor, community, reason) => {
338         Report::send(ObjectId::from(url), actor, community, reason, context).await
339       }
340     }
341   };
342   if *SYNCHRONOUS_FEDERATION {
343     fed_task.await?;
344   } else {
345     spawn_try_task(fed_task);
346   }
347   Ok(())
348 }