3 deletion::{send_apub_delete_in_community, DeletableObjects},
4 voting::send_like_activity,
6 objects::{community::ApubCommunity, person::ApubPerson},
7 protocol::activities::{
8 create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
13 use activitypub_federation::{
14 activity_queue::send_activity,
16 fetch::object_id::ObjectId,
18 protocol::context::WithContext,
19 traits::{ActivityHandler, Actor},
22 use lemmy_api_common::{
23 context::LemmyContext,
24 send_activity::{ActivityChannel, SendActivityData},
26 use lemmy_db_schema::{
27 newtypes::CommunityId,
29 activity::{SentActivity, SentActivityForm},
34 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
36 error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
38 SYNCHRONOUS_FEDERATION,
40 use moka::future::Cache;
41 use once_cell::sync::Lazy;
43 use std::{ops::Deref, sync::Arc, time::Duration};
45 use url::{ParseError, Url};
50 pub mod create_or_update;
56 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
57 /// so there is no harm in caching it for a longer time.
58 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
60 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
61 /// doesn't have a site ban.
62 #[tracing::instrument(skip_all)]
63 async fn verify_person(
64 person_id: &ObjectId<ApubPerson>,
65 context: &Data<LemmyContext>,
66 ) -> Result<(), LemmyError> {
67 let person = person_id.dereference(context).await?;
69 return Err(anyhow!("Person {} is banned", person_id))
70 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
75 /// Fetches the person and community to verify their type, then checks if person is banned from site
77 #[tracing::instrument(skip_all)]
78 pub(crate) async fn verify_person_in_community(
79 person_id: &ObjectId<ApubPerson>,
80 community: &ApubCommunity,
81 context: &Data<LemmyContext>,
82 ) -> Result<(), LemmyError> {
83 let person = person_id.dereference(context).await?;
85 return Err(LemmyErrorType::PersonIsBannedFromSite)?;
87 let person_id = person.id;
88 let community_id = community.id;
89 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
93 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
99 /// Verify that mod action in community was performed by a moderator.
101 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
102 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
103 /// * `community` - The community inside which moderation is happening
104 #[tracing::instrument(skip_all)]
105 pub(crate) async fn verify_mod_action(
106 mod_id: &ObjectId<ApubPerson>,
108 community_id: CommunityId,
109 context: &Data<LemmyContext>,
110 ) -> Result<(), LemmyError> {
111 let mod_ = mod_id.dereference(context).await?;
113 let is_mod_or_admin =
114 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
119 // mod action comes from the same instance as the moderated object, so it was presumably done
120 // by an instance admin.
121 // TODO: federate instance admin status and check it here
122 if mod_id.inner().domain() == object_id.domain() {
126 Err(LemmyErrorType::NotAModerator)?
129 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
130 if ![to, cc].iter().any(|set| set.contains(&public())) {
131 return Err(LemmyErrorType::ObjectIsNotPublic)?;
136 pub(crate) fn verify_community_matches<T>(
137 a: &ObjectId<ApubCommunity>,
139 ) -> Result<(), LemmyError>
141 T: Into<ObjectId<ApubCommunity>>,
143 let b: ObjectId<ApubCommunity> = b.into();
145 return Err(LemmyErrorType::InvalidCommunity)?;
150 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
151 if community.deleted || community.removed {
152 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
158 /// Generate a unique ID for an activity, in the format:
159 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
160 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
165 "{}/activities/{}/{}",
166 protocol_and_hostname,
167 kind.to_string().to_lowercase(),
173 #[tracing::instrument(skip_all)]
174 async fn send_lemmy_activity<Activity, ActorT>(
175 data: &Data<LemmyContext>,
180 ) -> Result<(), LemmyError>
182 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
184 Activity: ActivityHandler<Error = LemmyError>,
186 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
189 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
192 let dead_instances = CACHE
193 .try_get_with((), async {
194 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
199 let domain = i.domain().expect("has domain").to_string();
200 !dead_instances.contains(&domain)
202 info!("Sending activity {}", activity.id().to_string());
203 let activity = WithContext::new(activity, CONTEXT.deref().clone());
205 let form = SentActivityForm {
206 ap_id: activity.id().clone().into(),
207 data: serde_json::to_value(activity.clone())?,
210 SentActivity::create(&mut data.pool(), form).await?;
211 send_activity(activity, actor, inbox, data).await?;
216 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
217 while let Some(data) = ActivityChannel::retrieve_activity().await {
218 match_outgoing_activities(data, &context.reset_request_count()).await?
223 pub async fn match_outgoing_activities(
224 data: SendActivityData,
225 context: &Data<LemmyContext>,
226 ) -> LemmyResult<()> {
227 let context = context.reset_request_count();
228 let fed_task = async {
229 use SendActivityData::*;
231 CreatePost(post) | UpdatePost(post) => {
232 let creator_id = post.creator_id;
233 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
235 CreateComment(comment) | UpdateComment(comment) => {
236 let creator_id = comment.creator_id;
237 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
239 DeleteComment(comment, actor, community) => {
240 let is_deleted = comment.deleted;
241 let deletable = DeletableObjects::Comment(comment.into());
242 send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
244 RemoveComment(comment, actor, community, reason) => {
245 let is_removed = comment.removed;
246 let deletable = DeletableObjects::Comment(comment.into());
247 send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
250 LikePostOrComment(object_id, person, community, score) => {
251 send_like_activity(object_id, person, community, score, context).await
255 if *SYNCHRONOUS_FEDERATION {
258 spawn_try_task(fed_task);