]> Untitled Git - lemmy.git/blob - crates/apub/src/activities/mod.rs
Remove follow community traits (#3737)
[lemmy.git] / crates / apub / src / activities / mod.rs
1 use self::following::send_follow_community;
2 use crate::{
3   activities::{
4     deletion::{send_apub_delete_in_community, DeletableObjects},
5     voting::send_like_activity,
6   },
7   objects::{community::ApubCommunity, person::ApubPerson},
8   protocol::activities::{
9     create_or_update::{note::CreateOrUpdateNote, page::CreateOrUpdatePage},
10     CreateOrUpdateType,
11   },
12   CONTEXT,
13 };
14 use activitypub_federation::{
15   activity_queue::send_activity,
16   config::Data,
17   fetch::object_id::ObjectId,
18   kinds::public,
19   protocol::context::WithContext,
20   traits::{ActivityHandler, Actor},
21 };
22 use anyhow::anyhow;
23 use lemmy_api_common::{
24   context::LemmyContext,
25   send_activity::{ActivityChannel, SendActivityData},
26 };
27 use lemmy_db_schema::{
28   newtypes::CommunityId,
29   source::{
30     activity::{SentActivity, SentActivityForm},
31     community::Community,
32     instance::Instance,
33   },
34 };
35 use lemmy_db_views_actor::structs::{CommunityPersonBanView, CommunityView};
36 use lemmy_utils::{
37   error::{LemmyError, LemmyErrorExt, LemmyErrorType, LemmyResult},
38   spawn_try_task,
39   SYNCHRONOUS_FEDERATION,
40 };
41 use moka::future::Cache;
42 use once_cell::sync::Lazy;
43 use serde::Serialize;
44 use std::{ops::Deref, sync::Arc, time::Duration};
45 use tracing::info;
46 use url::{ParseError, Url};
47 use uuid::Uuid;
48
49 pub mod block;
50 pub mod community;
51 pub mod create_or_update;
52 pub mod deletion;
53 pub mod following;
54 pub mod unfederated;
55 pub mod voting;
56
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);
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?;
69   if person.banned {
70     return Err(anyhow!("Person {} is banned", person_id))
71       .with_lemmy_type(LemmyErrorType::CouldntUpdateComment);
72   }
73   Ok(())
74 }
75
76 /// Fetches the person and community to verify their type, then checks if person is banned from site
77 /// or community.
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?;
85   if person.banned {
86     return Err(LemmyErrorType::PersonIsBannedFromSite)?;
87   }
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)
91     .await
92     .is_ok();
93   if is_banned {
94     return Err(LemmyErrorType::PersonIsBannedFromCommunity)?;
95   }
96
97   Ok(())
98 }
99
100 /// Verify that mod action in community was performed by a moderator.
101 ///
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>,
108   object_id: &Url,
109   community_id: CommunityId,
110   context: &Data<LemmyContext>,
111 ) -> Result<(), LemmyError> {
112   let mod_ = mod_id.dereference(context).await?;
113
114   let is_mod_or_admin =
115     CommunityView::is_mod_or_admin(&mut context.pool(), mod_.id, community_id).await?;
116   if is_mod_or_admin {
117     return Ok(());
118   }
119
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() {
124     return Ok(());
125   }
126
127   Err(LemmyErrorType::NotAModerator)?
128 }
129
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)?;
133   }
134   Ok(())
135 }
136
137 pub(crate) fn verify_community_matches<T>(
138   a: &ObjectId<ApubCommunity>,
139   b: T,
140 ) -> Result<(), LemmyError>
141 where
142   T: Into<ObjectId<ApubCommunity>>,
143 {
144   let b: ObjectId<ApubCommunity> = b.into();
145   if a != &b {
146     return Err(LemmyErrorType::InvalidCommunity)?;
147   }
148   Ok(())
149 }
150
151 pub(crate) fn check_community_deleted_or_removed(community: &Community) -> Result<(), LemmyError> {
152   if community.deleted || community.removed {
153     Err(LemmyErrorType::CannotCreatePostOrCommentInDeletedOrRemovedCommunity)?
154   } else {
155     Ok(())
156   }
157 }
158
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>
162 where
163   T: ToString,
164 {
165   let id = format!(
166     "{}/activities/{}/{}",
167     protocol_and_hostname,
168     kind.to_string().to_lowercase(),
169     Uuid::new_v4()
170   );
171   Url::parse(&id)
172 }
173
174 #[tracing::instrument(skip_all)]
175 async fn send_lemmy_activity<Activity, ActorT>(
176   data: &Data<LemmyContext>,
177   activity: Activity,
178   actor: &ActorT,
179   mut inbox: Vec<Url>,
180   sensitive: bool,
181 ) -> Result<(), LemmyError>
182 where
183   Activity: ActivityHandler + Serialize + Send + Sync + Clone,
184   ActorT: Actor,
185   Activity: ActivityHandler<Error = LemmyError>,
186 {
187   static CACHE: Lazy<Cache<(), Arc<Vec<String>>>> = Lazy::new(|| {
188     Cache::builder()
189       .max_capacity(1)
190       .time_to_live(DEAD_INSTANCE_LIST_CACHE_DURATION)
191       .build()
192   });
193   let dead_instances = CACHE
194     .try_get_with((), async {
195       Ok::<_, diesel::result::Error>(Arc::new(Instance::dead_instances(&mut data.pool()).await?))
196     })
197     .await?;
198
199   inbox.retain(|i| {
200     let domain = i.domain().expect("has domain").to_string();
201     !dead_instances.contains(&domain)
202   });
203   info!("Sending activity {}", activity.id().to_string());
204   let activity = WithContext::new(activity, CONTEXT.deref().clone());
205
206   let form = SentActivityForm {
207     ap_id: activity.id().clone().into(),
208     data: serde_json::to_value(activity.clone())?,
209     sensitive,
210   };
211   SentActivity::create(&mut data.pool(), form).await?;
212   send_activity(activity, actor, inbox, data).await?;
213
214   Ok(())
215 }
216
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?
220   }
221   Ok(())
222 }
223
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::*;
231     match data {
232       CreatePost(post) | UpdatePost(post) => {
233         let creator_id = post.creator_id;
234         CreateOrUpdatePage::send(post, creator_id, CreateOrUpdateType::Create, context).await
235       }
236       CreateComment(comment) | UpdateComment(comment) => {
237         let creator_id = comment.creator_id;
238         CreateOrUpdateNote::send(comment, creator_id, CreateOrUpdateType::Create, context).await
239       }
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
244       }
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)
249           .await
250       }
251       LikePostOrComment(object_id, person, community, score) => {
252         send_like_activity(object_id, person, community, score, context).await
253       }
254       SendActivityData::FollowCommunity(community, person, follow) => {
255         send_follow_community(community, person, follow, &context).await
256       }
257     }
258   };
259   if *SYNCHRONOUS_FEDERATION {
260     fed_task.await?;
261   } else {
262     spawn_try_task(fed_task);
263   }
264   Ok(())
265 }