2 objects::{community::ApubCommunity, person::ApubPerson},
3 protocol::activities::{create_or_update::page::CreateOrUpdatePage, CreateOrUpdateType},
6 use activitypub_federation::{
7 activity_queue::send_activity,
9 fetch::object_id::ObjectId,
11 protocol::context::WithContext,
12 traits::{ActivityHandler, Actor},
15 use lemmy_api_common::{
16 context::LemmyContext,
17 send_activity::{ActivityChannel, SendActivityData},
19 use lemmy_db_schema::{
20 newtypes::CommunityId,
22 activity::{SentActivity, SentActivityForm},
27 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
29 error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
31 SYNCHRONOUS_FEDERATION,
33 use moka::future::Cache;
34 use once_cell::sync::Lazy;
36 use std::{ops::Deref, sync::Arc, time::Duration};
38 use url::{ParseError, Url};
43 pub mod create_or_update;
49 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
50 /// so there is no harm in caching it for a longer time.
51 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
53 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
54 /// doesn't have a site ban.
55 #[tracing::instrument(skip_all)]
56 async fn verify_person(
57 person_id: &ObjectId<ApubPerson>,
58 context: &Data<LemmyContext>,
59 ) -> Result<(), LemmyError> {
60 let person = person_id.dereference(context).await?;
62 return Err(anyhow!("Person {} is banned", person_id))
63 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
68 /// Fetches the person and community to verify their type, then checks if person is banned from site
70 #[tracing::instrument(skip_all)]
71 pub(crate) async fn verify_person_in_community(
72 person_id: &ObjectId<ApubPerson>,
73 community: &ApubCommunity,
74 context: &Data<LemmyContext>,
75 ) -> Result<(), LemmyError> {
76 let person = person_id.dereference(context).await?;
78 return Err(LemmyErrorType::PersonIsBannedFromSite)?;
80 let person_id = person.id;
81 let community_id = community.id;
82 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
86 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
92 /// Verify that mod action in community was performed by a moderator.
94 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
95 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
96 /// * `community` - The community inside which moderation is happening
97 #[tracing::instrument(skip_all)]
98 pub(crate) async fn verify_mod_action(
99 mod_id: &ObjectId<ApubPerson>,
101 community_id: CommunityId,
102 context: &Data<LemmyContext>,
103 ) -> Result<(), LemmyError> {
104 let mod_ = mod_id.dereference(context).await?;
106 let is_mod_or_admin =
107 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
112 // mod action comes from the same instance as the moderated object, so it was presumably done
113 // by an instance admin.
114 // TODO: federate instance admin status and check it here
115 if mod_id.inner().domain() == object_id.domain() {
119 Err(LemmyErrorType::NotAModerator)?
122 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
123 if ![to, cc].iter().any(|set| set.contains(&public())) {
124 return Err(LemmyErrorType::ObjectIsNotPublic)?;
129 pub(crate) fn verify_community_matches<T>(
130 a: &ObjectId<ApubCommunity>,
132 ) -> Result<(), LemmyError>
134 T: Into<ObjectId<ApubCommunity>>,
136 let b: ObjectId<ApubCommunity> = b.into();
138 return Err(LemmyErrorType::InvalidCommunity)?;
143 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
144 if community.deleted || community.removed {
145 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
151 /// Generate a unique ID for an activity, in the format:
152 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
153 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
158 "{}/activities/{}/{}",
159 protocol_and_hostname,
160 kind.to_string().to_lowercase(),
166 #[tracing::instrument(skip_all)]
167 async fn send_lemmy_activity<Activity, ActorT>(
168 data: &Data<LemmyContext>,
173 ) -> Result<(), LemmyError>
175 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
177 Activity: ActivityHandler<Error = LemmyError>,
179 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
182 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
185 let dead_instances = CACHE
186 .try_get_with((), async {
187 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
192 let domain = i.domain().expect("has domain").to_string();
193 !dead_instances.contains(&domain)
195 info!("Sending activity {}", activity.id().to_string());
196 let activity = WithContext::new(activity, CONTEXT.deref().clone());
198 let form = SentActivityForm {
199 ap_id: activity.id().clone().into(),
200 data: serde_json::to_value(activity.clone())?,
203 SentActivity::create(&mut data.pool(), form).await?;
204 send_activity(activity, actor, inbox, data).await?;
209 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
210 while let Some(data) = ActivityChannel::retrieve_activity().await {
211 match_outgoing_activities(data, &context.reset_request_count()).await?
216 pub async fn match_outgoing_activities(
217 data: SendActivityData,
218 context: &Data<LemmyContext>,
219 ) -> LemmyResult<()> {
220 let fed_task = match data {
221 SendActivityData::CreatePost(post) => {
222 let creator_id = post.creator_id;
223 CreateOrUpdatePage::send(
226 CreateOrUpdateType::Create,
227 context.reset_request_count(),
231 if *SYNCHRONOUS_FEDERATION {
234 spawn_try_task(fed_task);