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