1 use self::following::send_follow_community;
4 block::{send_ban_from_community, send_ban_from_site},
6 collection_add::{send_add_mod_to_community, send_feature_post},
7 lock_page::send_lock_post,
8 update::send_update_community,
10 create_or_update::private_message::send_create_or_update_pm,
12 delete_user::delete_user,
13 send_apub_delete_in_community,
14 send_apub_delete_in_community_new,
15 send_apub_delete_private_message,
18 voting::send_like_activity,
20 objects::{community::ApubCommunity, person::ApubPerson},
21 protocol::activities::{
22 community::report::Report,
23 create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
28 use activitypub_federation::{
29 activity_queue::send_activity,
31 fetch::object_id::ObjectId,
33 protocol::context::WithContext,
34 traits::{ActivityHandler, Actor},
37 use lemmy_api_common::{
38 context::LemmyContext,
39 send_activity::{ActivityChannel, SendActivityData},
41 use lemmy_db_schema::{
42 newtypes::CommunityId,
44 activity::{SentActivity, SentActivityForm},
49 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
51 error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
53 SYNCHRONOUS_FEDERATION,
55 use moka::future::Cache;
56 use once_cell::sync::Lazy;
58 use std::{ops::Deref, sync::Arc, time::Duration};
60 use url::{ParseError, Url};
65 pub mod create_or_update;
71 /// Amount of time that the list of dead instances is cached. This is only updated once a day,
72 /// so there is no harm in caching it for a longer time.
73 pub static DEAD_INSTANCE_LIST_CACHE_DURATION: Duration = Duration::from_secs(30 * 60);
75 /// Checks that the specified Url actually identifies a Person (by fetching it), and that the person
76 /// doesn't have a site ban.
77 #[tracing::instrument(skip_all)]
78 async fn verify_person(
79 person_id: &ObjectId<ApubPerson>,
80 context: &Data<LemmyContext>,
81 ) -> Result<(), LemmyError> {
82 let person = person_id.dereference(context).await?;
84 return Err(anyhow!("Person {} is banned", person_id))
85 .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
90 /// Fetches the person and community to verify their type, then checks if person is banned from site
92 #[tracing::instrument(skip_all)]
93 pub(crate) async fn verify_person_in_community(
94 person_id: &ObjectId<ApubPerson>,
95 community: &ApubCommunity,
96 context: &Data<LemmyContext>,
97 ) -> Result<(), LemmyError> {
98 let person = person_id.dereference(context).await?;
100 return Err(LemmyErrorType::PersonIsBannedFromSite(
101 person.actor_id.to_string(),
104 let person_id = person.id;
105 let community_id = community.id;
106 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
110 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
116 /// Verify that mod action in community was performed by a moderator.
118 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
119 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
120 /// * `community` - The community inside which moderation is happening
121 #[tracing::instrument(skip_all)]
122 pub(crate) async fn verify_mod_action(
123 mod_id: &ObjectId<ApubPerson>,
125 community_id: CommunityId,
126 context: &Data<LemmyContext>,
127 ) -> Result<(), LemmyError> {
128 let mod_ = mod_id.dereference(context).await?;
130 let is_mod_or_admin =
131 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
136 // mod action comes from the same instance as the moderated object, so it was presumably done
137 // by an instance admin.
138 // TODO: federate instance admin status and check it here
139 if mod_id.inner().domain() == object_id.domain() {
143 Err(LemmyErrorType::NotAModerator)?
146 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
147 if ![to, cc].iter().any(|set| set.contains(&public())) {
148 Err(LemmyErrorType::ObjectIsNotPublic)?;
153 pub(crate) fn verify_community_matches<T>(
154 a: &ObjectId<ApubCommunity>,
156 ) -> Result<(), LemmyError>
158 T: Into<ObjectId<ApubCommunity>>,
160 let b: ObjectId<ApubCommunity> = b.into();
162 Err(LemmyErrorType::InvalidCommunity)?;
167 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
168 if community.deleted || community.removed {
169 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
175 /// Generate a unique ID for an activity, in the format:
176 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
177 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
182 "{}/activities/{}/{}",
183 protocol_and_hostname,
184 kind.to_string().to_lowercase(),
190 #[tracing::instrument(skip_all)]
191 async fn send_lemmy_activity<Activity, ActorT>(
192 data: &Data<LemmyContext>,
197 ) -> Result<(), LemmyError>
199 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
201 Activity: ActivityHandler<Error = LemmyError>,
203 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
206 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
209 let dead_instances = CACHE
210 .try_get_with((), async {
211 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
216 let domain = i.domain().expect("has domain").to_string();
217 !dead_instances.contains(&domain)
219 info!("Sending activity {}", activity.id().to_string());
220 let activity = WithContext::new(activity, CONTEXT.deref().clone());
222 let form = SentActivityForm {
223 ap_id: activity.id().clone().into(),
224 data: serde_json::to_value(activity.clone())?,
227 SentActivity::create(&mut data.pool(), form).await?;
228 send_activity(activity, actor, inbox, data).await?;
233 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
234 while let Some(data) = ActivityChannel::retrieve_activity().await {
235 match_outgoing_activities(data, &context.reset_request_count()).await?
240 pub async fn match_outgoing_activities(
241 data: SendActivityData,
242 context: &Data<LemmyContext>,
243 ) -> LemmyResult<()> {
244 let context = context.reset_request_count();
245 let fed_task = async {
246 use SendActivityData::*;
248 CreatePost(post) => {
249 let creator_id = post.creator_id;
250 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
252 UpdatePost(post) => {
253 let creator_id = post.creator_id;
254 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Update, context).await
256 DeletePost(post, person, data) => {
257 send_apub_delete_in_community_new(
260 DeletableObjects::Post(post.into()),
267 RemovePost(post, person, data) => {
268 send_apub_delete_in_community_new(
271 DeletableObjects::Post(post.into()),
272 data.reason.or_else(|| Some(String::new())),
278 LockPost(post, actor, locked) => send_lock_post(post, actor, locked, context).await,
279 FeaturePost(post, actor, featured) => send_feature_post(post, actor, featured, context).await,
280 CreateComment(comment) => {
281 let creator_id = comment.creator_id;
282 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
284 UpdateComment(comment) => {
285 let creator_id = comment.creator_id;
286 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Update, context).await
288 DeleteComment(comment, actor, community) => {
289 let is_deleted = comment.deleted;
290 let deletable = DeletableObjects::Comment(comment.into());
291 send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
293 RemoveComment(comment, actor, community, reason) => {
294 let is_removed = comment.removed;
295 let deletable = DeletableObjects::Comment(comment.into());
296 send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
299 LikePostOrComment(object_id, person, community, score) => {
300 send_like_activity(object_id, person, community, score, context).await
302 FollowCommunity(community, person, follow) => {
303 send_follow_community(community, person, follow, &context).await
305 UpdateCommunity(actor, community) => send_update_community(community, actor, context).await,
306 DeleteCommunity(actor, community, removed) => {
307 let deletable = DeletableObjects::Community(community.clone().into());
308 send_apub_delete_in_community(actor, community, deletable, None, removed, &context).await
310 RemoveCommunity(actor, community, reason, removed) => {
311 let deletable = DeletableObjects::Community(community.clone().into());
312 send_apub_delete_in_community(
316 reason.clone().or_else(|| Some(String::new())),
322 AddModToCommunity(actor, community_id, updated_mod_id, added) => {
323 send_add_mod_to_community(actor, community_id, updated_mod_id, added, context).await
325 BanFromCommunity(mod_, community_id, target, data) => {
326 send_ban_from_community(mod_, community_id, target, data, context).await
328 BanFromSite(mod_, target, data) => send_ban_from_site(mod_, target, data, context).await,
329 CreatePrivateMessage(pm) => {
330 send_create_or_update_pm(pm, CreateOrUpdateType::Create, context).await
332 UpdatePrivateMessage(pm) => {
333 send_create_or_update_pm(pm, CreateOrUpdateType::Update, context).await
335 DeletePrivateMessage(person, pm, deleted) => {
336 send_apub_delete_private_message(&person.into(), pm, deleted, context).await
338 DeleteUser(person) => delete_user(person, context).await,
339 CreateReport(url, actor, community, reason) => {
340 Report::send(ObjectId::from(url), actor, community, reason, context).await
344 if *SYNCHRONOUS_FEDERATION {
347 spawn_try_task(fed_task);