2 objects::{community::ApubCommunity, person::ApubPerson},
5 use activitypub_federation::{
6 activity_queue::send_activity,
8 fetch::object_id::ObjectId,
10 protocol::context::WithContext,
11 traits::{ActivityHandler, Actor},
14 use lemmy_api_common::context::LemmyContext;
15 use lemmy_db_schema::{
16 newtypes::CommunityId,
18 activity::{SentActivity, SentActivityForm},
23 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
24 use lemmy_utils::error::{LemmyError, LemmyErrorExt, LemmyErrorType};
25 use moka::future::Cache;
26 use once_cell::sync::Lazy;
28 use std::{ops::Deref, sync::Arc, time::Duration};
30 use url::{ParseError, Url};
35 pub mod create_or_update;
41 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
42 /// so there is no harm in caching it for a longer time.
43 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
45 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
46 /// doesn't have a site ban.
47 #[tracing::instrument(skip_all)]
48 async fn verify_person(
49 person_id: &ObjectId<ApubPerson>,
50 context: &Data<LemmyContext>,
51 ) -> Result<(), LemmyError> {
52 let person = person_id.dereference(context).await?;
54 return Err(anyhow!("Person {} is banned", person_id))
55 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
60 /// Fetches the person and community to verify their type, then checks if person is banned from site
62 #[tracing::instrument(skip_all)]
63 pub(crate) async fn verify_person_in_community(
64 person_id: &ObjectId<ApubPerson>,
65 community: &ApubCommunity,
66 context: &Data<LemmyContext>,
67 ) -> Result<(), LemmyError> {
68 let person = person_id.dereference(context).await?;
70 return Err(LemmyErrorType::PersonIsBannedFromSite)?;
72 let person_id = person.id;
73 let community_id = community.id;
74 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
78 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
84 /// Verify that mod action in community was performed by a moderator.
86 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
87 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
88 /// * `community` - The community inside which moderation is happening
89 #[tracing::instrument(skip_all)]
90 pub(crate) async fn verify_mod_action(
91 mod_id: &ObjectId<ApubPerson>,
93 community_id: CommunityId,
94 context: &Data<LemmyContext>,
95 ) -> Result<(), LemmyError> {
96 let mod_ = mod_id.dereference(context).await?;
99 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
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() {
111 Err(LemmyErrorType::NotAModerator)?
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(LemmyErrorType::ObjectIsNotPublic)?;
121 pub(crate) fn verify_community_matches<T>(
122 a: &ObjectId<ApubCommunity>,
124 ) -> Result<(), LemmyError>
126 T: Into<ObjectId<ApubCommunity>>,
128 let b: ObjectId<ApubCommunity> = b.into();
130 return Err(LemmyErrorType::InvalidCommunity)?;
135 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
136 if community.deleted || community.removed {
137 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
143 /// Generate a unique ID for an activity, in the format:
144 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
145 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
150 "{}/activities/{}/{}",
151 protocol_and_hostname,
152 kind.to_string().to_lowercase(),
158 #[tracing::instrument(skip_all)]
159 async fn send_lemmy_activity<Activity, ActorT>(
160 data: &Data<LemmyContext>,
165 ) -> Result<(), LemmyError>
167 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
169 Activity: ActivityHandler<Error = LemmyError>,
171 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
174 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
177 let dead_instances = CACHE
178 .try_get_with((), async {
179 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
184 let domain = i.domain().expect("has domain").to_string();
185 !dead_instances.contains(&domain)
187 info!("Sending activity {}", activity.id().to_string());
188 let activity = WithContext::new(activity, CONTEXT.deref().clone());
190 let form = SentActivityForm {
191 ap_id: activity.id().clone().into(),
192 data: serde_json::to_value(activity.clone())?,
195 SentActivity::create(&mut data.pool(), form).await?;
196 send_activity(activity, actor, inbox, data).await?;