]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
Implement separate mod activities for feature, lock post (#2716)
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use crate::{
2   insert_activity,
3   local_instance,
4   objects::{community::ApubCommunity, person::ApubPerson},
5   ActorType,
6   CONTEXT,
7 };
8 use activitypub_federation::{
9   core::{activity_queue::send_activity, object_id::ObjectId},
10   deser::context::WithContext,
11   traits::{ActivityHandler, Actor},
12 };
13 use activitystreams_kinds::public;
14 use anyhow::anyhow;
15 use lemmy_api_common::context::LemmyContext;
16 use lemmy_db_schema::{
17   newtypes::CommunityId,
18   source::{community::Community, local_site::LocalSite},
19 };
20 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
21 use lemmy_utils::error::LemmyError;
22 use serde::Serialize;
23 use std::ops::Deref;
24 use tracing::info;
25 use url::{ParseError, Url};
26 use uuid::Uuid;
27
28 pub mod block;
29 pub mod community;
30 pub mod create_or_update;
31 pub mod deletion;
32 pub mod following;
33 pub mod unfederated;
34 pub mod voting;
35
36 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
37 /// doesn't have a site ban.
38 #[tracing::instrument(skip_all)]
39 async fn verify_person(
40   person_id: &ObjectId<ApubPerson>,
41   context: &LemmyContext,
42   request_counter: &mut i32,
43 ) -> Result<(), LemmyError> {
44   let person = person_id
45     .dereference(context, local_instance(context).await, request_counter)
46     .await?;
47   if person.banned {
48     let err = anyhow!("Person {} is banned", person_id);
49     return Err(LemmyError::from_error_message(err, "banned"));
50   }
51   Ok(())
52 }
53
54 /// Fetches the person and community to verify their type, then checks if person is banned from site
55 /// or community.
56 #[tracing::instrument(skip_all)]
57 pub(crate) async fn verify_person_in_community(
58   person_id: &ObjectId<ApubPerson>,
59   community: &ApubCommunity,
60   context: &LemmyContext,
61   request_counter: &mut i32,
62 ) -> Result<(), LemmyError> {
63   let person = person_id
64     .dereference(context, local_instance(context).await, request_counter)
65     .await?;
66   if person.banned {
67     return Err(LemmyError::from_message("Person is banned from site"));
68   }
69   let person_id = person.id;
70   let community_id = community.id;
71   let is_banned = CommunityPersonBanView::get(context.pool(), person_id, community_id)
72     .await
73     .is_ok();
74   if is_banned {
75     return Err(LemmyError::from_message("Person is banned from community"));
76   }
77
78   Ok(())
79 }
80
81 /// Verify that mod action in community was performed by a moderator.
82 ///
83 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
84 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
85 /// * `community` - The community inside which moderation is happening
86 #[tracing::instrument(skip_all)]
87 pub(crate) async fn verify_mod_action(
88   mod_id: &ObjectId<ApubPerson>,
89   object_id: &Url,
90   community_id: CommunityId,
91   context: &LemmyContext,
92   request_counter: &mut i32,
93 ) -> Result<(), LemmyError> {
94   let mod_ = mod_id
95     .dereference(context, local_instance(context).await, request_counter)
96     .await?;
97
98   let is_mod_or_admin =
99     CommunityView::is_mod_or_admin(context.pool(), mod_.id, community_id).await?;
100   if is_mod_or_admin {
101     return Ok(());
102   }
103
104   // mod action comes from the same instance as the moderated object, so it was presumably done
105   // by an instance admin.
106   // TODO: federate instance admin status and check it here
107   if mod_id.inner().domain() == object_id.domain() {
108     return Ok(());
109   }
110
111   Err(LemmyError::from_message("Not a mod"))
112 }
113
114 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
115   if ![to, cc].iter().any(|set| set.contains(&public())) {
116     return Err(LemmyError::from_message("Object is not public"));
117   }
118   Ok(())
119 }
120
121 pub(crate) fn verify_community_matches<T>(
122   a: &ObjectId<ApubCommunity>,
123   b: T,
124 ) -> Result<(), LemmyError>
125 where
126   T: Into<ObjectId<ApubCommunity>>,
127 {
128   let b: ObjectId<ApubCommunity> = b.into();
129   if a != &b {
130     return Err(LemmyError::from_message("Invalid community"));
131   }
132   Ok(())
133 }
134
135 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
136   if community.deleted || community.removed {
137     Err(LemmyError::from_message(
138       "New post or comment cannot be created in deleted or removed community",
139     ))
140   } else {
141     Ok(())
142   }
143 }
144
145 /// Generate a unique ID for an activity, in the format:
146 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
147 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
148 where
149   T: ToString,
150 {
151   let id = format!(
152     "{}/activities/{}/{}",
153     protocol_and_hostname,
154     kind.to_string().to_lowercase(),
155     Uuid::new_v4()
156   );
157   Url::parse(&id)
158 }
159
160 #[tracing::instrument(skip_all)]
161 async fn send_lemmy_activity<Activity, ActorT>(
162   context: &LemmyContext,
163   activity: Activity,
164   actor: &ActorT,
165   inbox: Vec<Url>,
166   sensitive: bool,
167 ) -> Result<(), LemmyError>
168 where
169   Activity: ActivityHandler + Serialize,
170   ActorT: Actor + ActorType,
171   Activity: ActivityHandler<Error = LemmyError>,
172 {
173   let federation_enabled = LocalSite::read(context.pool())
174     .await
175     .map(|l| l.federation_enabled)
176     .unwrap_or(false);
177   if !federation_enabled {
178     return Ok(());
179   }
180
181   info!("Sending activity {}", activity.id().to_string());
182   let activity = WithContext::new(activity, CONTEXT.deref().clone());
183
184   let object_value = serde_json::to_value(&activity)?;
185   insert_activity(activity.id(), object_value, true, sensitive, context.pool()).await?;
186
187   send_activity(
188     activity,
189     actor.get_public_key(),
190     actor.private_key().expect("actor has private key"),
191     inbox,
192     local_instance(context).await,
193   )
194   .await?;
195
196   Ok(())
197 }