1 use self::following::send_follow_community;
4 deletion::{send_apub_delete_in_community, DeletableObjects},
5 voting::send_like_activity,
7 objects::{community::ApubCommunity, person::ApubPerson},
8 protocol::activities::{
9 create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
14 use activitypub_federation::{
15 activity_queue::send_activity,
17 fetch::object_id::ObjectId,
19 protocol::context::WithContext,
20 traits::{ActivityHandler, Actor},
23 use lemmy_api_common::{
24 context::LemmyContext,
25 send_activity::{ActivityChannel, SendActivityData},
27 use lemmy_db_schema::{
28 newtypes::CommunityId,
30 activity::{SentActivity, SentActivityForm},
35 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
37 error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
39 SYNCHRONOUS_FEDERATION,
41 use moka::future::Cache;
42 use once_cell::sync::Lazy;
44 use std::{ops::Deref, sync::Arc, time::Duration};
46 use url::{ParseError, Url};
51 pub mod create_or_update;
57 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
58 /// so there is no harm in caching it for a longer time.
59 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
61 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
62 /// doesn't have a site ban.
63 #[tracing::instrument(skip_all)]
64 async fn verify_person(
65 person_id: &ObjectId<ApubPerson>,
66 context: &Data<LemmyContext>,
67 ) -> Result<(), LemmyError> {
68 let person = person_id.dereference(context).await?;
70 return Err(anyhow!("Person {} is banned", person_id))
71 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
76 /// Fetches the person and community to verify their type, then checks if person is banned from site
78 #[tracing::instrument(skip_all)]
79 pub(crate) async fn verify_person_in_community(
80 person_id: &ObjectId<ApubPerson>,
81 community: &ApubCommunity,
82 context: &Data<LemmyContext>,
83 ) -> Result<(), LemmyError> {
84 let person = person_id.dereference(context).await?;
86 return Err(LemmyErrorType::PersonIsBannedFromSite)?;
88 let person_id = person.id;
89 let community_id = community.id;
90 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
94 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
100 /// Verify that mod action in community was performed by a moderator.
102 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
103 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
104 /// * `community` - The community inside which moderation is happening
105 #[tracing::instrument(skip_all)]
106 pub(crate) async fn verify_mod_action(
107 mod_id: &ObjectId<ApubPerson>,
109 community_id: CommunityId,
110 context: &Data<LemmyContext>,
111 ) -> Result<(), LemmyError> {
112 let mod_ = mod_id.dereference(context).await?;
114 let is_mod_or_admin =
115 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
120 // mod action comes from the same instance as the moderated object, so it was presumably done
121 // by an instance admin.
122 // TODO: federate instance admin status and check it here
123 if mod_id.inner().domain() == object_id.domain() {
127 Err(LemmyErrorType::NotAModerator)?
130 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
131 if ![to, cc].iter().any(|set| set.contains(&public())) {
132 return Err(LemmyErrorType::ObjectIsNotPublic)?;
137 pub(crate) fn verify_community_matches<T>(
138 a: &ObjectId<ApubCommunity>,
140 ) -> Result<(), LemmyError>
142 T: Into<ObjectId<ApubCommunity>>,
144 let b: ObjectId<ApubCommunity> = b.into();
146 return Err(LemmyErrorType::InvalidCommunity)?;
151 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
152 if community.deleted || community.removed {
153 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
159 /// Generate a unique ID for an activity, in the format:
160 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
161 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
166 "{}/activities/{}/{}",
167 protocol_and_hostname,
168 kind.to_string().to_lowercase(),
174 #[tracing::instrument(skip_all)]
175 async fn send_lemmy_activity<Activity, ActorT>(
176 data: &Data<LemmyContext>,
181 ) -> Result<(), LemmyError>
183 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
185 Activity: ActivityHandler<Error = LemmyError>,
187 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
190 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
193 let dead_instances = CACHE
194 .try_get_with((), async {
195 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
200 let domain = i.domain().expect("has domain").to_string();
201 !dead_instances.contains(&domain)
203 info!("Sending activity {}", activity.id().to_string());
204 let activity = WithContext::new(activity, CONTEXT.deref().clone());
206 let form = SentActivityForm {
207 ap_id: activity.id().clone().into(),
208 data: serde_json::to_value(activity.clone())?,
211 SentActivity::create(&mut data.pool(), form).await?;
212 send_activity(activity, actor, inbox, data).await?;
217 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
218 while let Some(data) = ActivityChannel::retrieve_activity().await {
219 match_outgoing_activities(data, &context.reset_request_count()).await?
224 pub async fn match_outgoing_activities(
225 data: SendActivityData,
226 context: &Data<LemmyContext>,
227 ) -> LemmyResult<()> {
228 let context = context.reset_request_count();
229 let fed_task = async {
230 use SendActivityData::*;
232 CreatePost(post) | UpdatePost(post) => {
233 let creator_id = post.creator_id;
234 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
236 CreateComment(comment) | UpdateComment(comment) => {
237 let creator_id = comment.creator_id;
238 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
240 DeleteComment(comment, actor, community) => {
241 let is_deleted = comment.deleted;
242 let deletable = DeletableObjects::Comment(comment.into());
243 send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
245 RemoveComment(comment, actor, community, reason) => {
246 let is_removed = comment.removed;
247 let deletable = DeletableObjects::Comment(comment.into());
248 send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
251 LikePostOrComment(object_id, person, community, score) => {
252 send_like_activity(object_id, person, community, score, context).await
254 SendActivityData::FollowCommunity(community, person, follow) => {
255 send_follow_community(community, person, follow, &context).await
259 if *SYNCHRONOUS_FEDERATION {
262 spawn_try_task(fed_task);