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)?;
102 let person_id = person.id;
103 let community_id = community.id;
104 let is_banned = CommunityPersonBanView::get(&mut context.pool(), person_id, community_id)
108 return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
114 /// Verify that mod action in community was performed by a moderator.
116 /// * `mod_id` - Activitypub ID of the mod or admin who performed the action
117 /// * `object_id` - Activitypub ID of the actor or object that is being moderated
118 /// * `community` - The community inside which moderation is happening
119 #[tracing::instrument(skip_all)]
120 pub(crate) async fn verify_mod_action(
121 mod_id: &ObjectId<ApubPerson>,
123 community_id: CommunityId,
124 context: &Data<LemmyContext>,
125 ) -> Result<(), LemmyError> {
126 let mod_ = mod_id.dereference(context).await?;
128 let is_mod_or_admin =
129 CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
134 // mod action comes from the same instance as the moderated object, so it was presumably done
135 // by an instance admin.
136 // TODO: federate instance admin status and check it here
137 if mod_id.inner().domain() == object_id.domain() {
141 Err(LemmyErrorType::NotAModerator)?
144 pub(crate) fn verify_is_public(to: &[Url], cc: &[Url]) -> Result<(), LemmyError> {
145 if ![to, cc].iter().any(|set| set.contains(&public())) {
146 return Err(LemmyErrorType::ObjectIsNotPublic)?;
151 pub(crate) fn verify_community_matches<T>(
152 a: &ObjectId<ApubCommunity>,
154 ) -> Result<(), LemmyError>
156 T: Into<ObjectId<ApubCommunity>>,
158 let b: ObjectId<ApubCommunity> = b.into();
160 return Err(LemmyErrorType::InvalidCommunity)?;
165 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
166 if community.deleted || community.removed {
167 Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
173 /// Generate a unique ID for an activity, in the format:
174 /// `http(s)://example.com/receive/create/202daf0a-1489-45df-8d2e-c8a3173fed36`
175 fn generate_activity_id<T>(kind: T, protocol_and_hostname: &str) -> Result<Url, ParseError>
180 "{}/activities/{}/{}",
181 protocol_and_hostname,
182 kind.to_string().to_lowercase(),
188 #[tracing::instrument(skip_all)]
189 async fn send_lemmy_activity<Activity, ActorT>(
190 data: &Data<LemmyContext>,
195 ) -> Result<(), LemmyError>
197 Activity: ActivityHandler + Serialize + Send + Sync + Clone,
199 Activity: ActivityHandler<Error = LemmyError>,
201 static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
204 .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
207 let dead_instances = CACHE
208 .try_get_with((), async {
209 Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
214 let domain = i.domain().expect("has domain").to_string();
215 !dead_instances.contains(&domain)
217 info!("Sending activity {}", activity.id().to_string());
218 let activity = WithContext::new(activity, CONTEXT.deref().clone());
220 let form = SentActivityForm {
221 ap_id: activity.id().clone().into(),
222 data: serde_json::to_value(activity.clone())?,
225 SentActivity::create(&mut data.pool(), form).await?;
226 send_activity(activity, actor, inbox, data).await?;
231 pub async fn handle_outgoing_activities(context: Data<LemmyContext>) -> LemmyResult<()> {
232 while let Some(data) = ActivityChannel::retrieve_activity().await {
233 match_outgoing_activities(data, &context.reset_request_count()).await?
238 pub async fn match_outgoing_activities(
239 data: SendActivityData,
240 context: &Data<LemmyContext>,
241 ) -> LemmyResult<()> {
242 let context = context.reset_request_count();
243 let fed_task = async {
244 use SendActivityData::*;
246 CreatePost(post) => {
247 let creator_id = post.creator_id;
248 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
250 UpdatePost(post) => {
251 let creator_id = post.creator_id;
252 CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Update, context).await
254 DeletePost(post, person, data) => {
255 send_apub_delete_in_community_new(
258 DeletableObjects::Post(post.into()),
265 RemovePost(post, person, data) => {
266 send_apub_delete_in_community_new(
269 DeletableObjects::Post(post.into()),
270 data.reason.or_else(|| Some(String::new())),
276 LockPost(post, actor, locked) => send_lock_post(post, actor, locked, context).await,
277 FeaturePost(post, actor, featured) => send_feature_post(post, actor, featured, context).await,
278 CreateComment(comment) => {
279 let creator_id = comment.creator_id;
280 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
282 UpdateComment(comment) => {
283 let creator_id = comment.creator_id;
284 CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Update, context).await
286 DeleteComment(comment, actor, community) => {
287 let is_deleted = comment.deleted;
288 let deletable = DeletableObjects::Comment(comment.into());
289 send_apub_delete_in_community(actor, community, deletable, None, is_deleted, &context).await
291 RemoveComment(comment, actor, community, reason) => {
292 let is_removed = comment.removed;
293 let deletable = DeletableObjects::Comment(comment.into());
294 send_apub_delete_in_community(actor, community, deletable, reason, is_removed, &context)
297 LikePostOrComment(object_id, person, community, score) => {
298 send_like_activity(object_id, person, community, score, context).await
300 FollowCommunity(community, person, follow) => {
301 send_follow_community(community, person, follow, &context).await
303 UpdateCommunity(actor, community) => send_update_community(community, actor, context).await,
304 DeleteCommunity(actor, community, removed) => {
305 let deletable = DeletableObjects::Community(community.clone().into());
306 send_apub_delete_in_community(actor, community, deletable, None, removed, &context).await
308 RemoveCommunity(actor, community, reason, removed) => {
309 let deletable = DeletableObjects::Community(community.clone().into());
310 send_apub_delete_in_community(
314 reason.clone().or_else(|| Some(String::new())),
320 AddModToCommunity(actor, community_id, updated_mod_id, added) => {
321 send_add_mod_to_community(actor, community_id, updated_mod_id, added, context).await
323 BanFromCommunity(mod_, community_id, target, data) => {
324 send_ban_from_community(mod_, community_id, target, data, context).await
326 BanFromSite(mod_, target, data) => send_ban_from_site(mod_, target, data, context).await,
327 CreatePrivateMessage(pm) => {
328 send_create_or_update_pm(pm, CreateOrUpdateType::Create, context).await
330 UpdatePrivateMessage(pm) => {
331 send_create_or_update_pm(pm, CreateOrUpdateType::Update, context).await
333 DeletePrivateMessage(person, pm, deleted) => {
334 send_apub_delete_private_message(&person.into(), pm, deleted, context).await
336 DeleteUser(person) => delete_user(person, context).await,
337 CreateReport(url, actor, community, reason) => {
338 Report::send(ObjectId::from(url), actor, community, reason, context).await
342 if *SYNCHRONOUS_FEDERATION {
345 spawn_try_task(fed_task);