2 check_is_apub_id_valid,
3 extensions::signatures::sign_and_send,
8 base::{BaseExt, Extends, ExtendsExt},
11 use anyhow::{anyhow, Context, Error};
12 use background_jobs::{
14 memory_storage::Storage,
21 use itertools::Itertools;
22 use lemmy_db::{community::Community, user::User_, DbPool};
23 use lemmy_utils::{location_info, settings::Settings, LemmyError};
24 use lemmy_websocket::LemmyContext;
25 use log::{debug, warn};
27 use serde::{export::fmt::Debug, Deserialize, Serialize};
28 use std::{collections::BTreeMap, future::Future, pin::Pin};
31 /// Sends a local activity to a single, remote actor.
33 /// * `activity` the apub activity to be sent
34 /// * `creator` the local actor which created the activity
35 /// * `inbox` the inbox url where the activity should be delivered to
36 pub async fn send_activity_single_dest<T, Kind>(
38 creator: &dyn ActorType,
40 context: &LemmyContext,
41 ) -> Result<(), LemmyError>
43 T: AsObject<Kind> + Extends<Kind> + Debug + BaseExt<Kind>,
45 <T as Extends<Kind>>::Error: From<serde_json::Error> + Send + Sync + 'static,
47 if check_is_apub_id_valid(&inbox).is_ok() {
49 "Sending activity {:?} to {}",
50 &activity.id_unchecked(),
53 send_activity_internal(
54 context.activity_queue(),
68 /// From a local community, send activity to all remote followers.
70 /// * `activity` the apub activity to send
71 /// * `community` the sending community
72 /// * `sender_shared_inbox` in case of an announce, this should be the shared inbox of the inner
73 /// activities creator, as receiving a known activity will cause an error
74 pub async fn send_to_community_followers<T, Kind>(
76 community: &Community,
77 context: &LemmyContext,
78 ) -> Result<(), LemmyError>
80 T: AsObject<Kind> + Extends<Kind> + Debug + BaseExt<Kind>,
82 <T as Extends<Kind>>::Error: From<serde_json::Error> + Send + Sync + 'static,
84 let follower_inboxes: Vec<Url> = community
85 .get_follower_inboxes(context.pool())
89 .filter(|inbox| inbox.host_str() != Some(&Settings::get().hostname))
90 .filter(|inbox| check_is_apub_id_valid(inbox).is_ok())
91 .map(|inbox| inbox.to_owned())
94 "Sending activity {:?} to followers of {}",
95 &activity.id_unchecked(),
99 send_activity_internal(
100 context.activity_queue(),
113 /// Sends an activity from a local user to a remote community.
115 /// * `activity` the activity to send
116 /// * `creator` the creator of the activity
117 /// * `community` the destination community
119 pub async fn send_to_community<T, Kind>(
122 community: &Community,
123 context: &LemmyContext,
124 ) -> Result<(), LemmyError>
126 T: AsObject<Kind> + Extends<Kind> + Debug + BaseExt<Kind>,
128 <T as Extends<Kind>>::Error: From<serde_json::Error> + Send + Sync + 'static,
130 // if this is a local community, we need to do an announce from the community instead
133 .send_announce(activity.into_any_base()?, context)
136 let inbox = community.get_shared_inbox_url()?;
137 check_is_apub_id_valid(&inbox)?;
139 "Sending activity {:?} to community {}",
140 &activity.id_unchecked(),
143 send_activity_internal(
144 context.activity_queue(),
158 /// Sends notification to any users mentioned in a comment
160 /// * `creator` user who created the comment
161 /// * `mentions` list of inboxes of users which are mentioned in the comment
162 /// * `activity` either a `Create/Note` or `Update/Note`
163 pub async fn send_comment_mentions<T, Kind>(
167 context: &LemmyContext,
168 ) -> Result<(), LemmyError>
170 T: AsObject<Kind> + Extends<Kind> + Debug + BaseExt<Kind>,
172 <T as Extends<Kind>>::Error: From<serde_json::Error> + Send + Sync + 'static,
175 "Sending mentions activity {:?} to {:?}",
176 &activity.id_unchecked(),
179 let mentions = mentions
181 .filter(|inbox| check_is_apub_id_valid(inbox).is_ok())
182 .map(|i| i.to_owned())
184 send_activity_internal(
185 context.activity_queue(),
190 false, // Don't create a new DB row
197 /// Create new `SendActivityTasks`, which will deliver the given activity to inboxes, as well as
198 /// handling signing and retrying failed deliveres.
200 /// The caller of this function needs to remove any blocked domains from `to`,
201 /// using `check_is_apub_id_valid()`.
202 async fn send_activity_internal<T, Kind>(
203 activity_sender: &QueueHandle,
205 actor: &dyn ActorType,
208 insert_into_db: bool,
210 ) -> Result<(), LemmyError>
212 T: AsObject<Kind> + Extends<Kind> + Debug,
214 <T as Extends<Kind>>::Error: From<serde_json::Error> + Send + Sync + 'static,
216 if !Settings::get().federation.enabled || inboxes.is_empty() {
220 let activity = activity.into_any_base()?;
221 let serialised_activity = serde_json::to_string(&activity)?;
223 // This is necessary because send_comment and send_comment_mentions
224 // might send the same ap_id
226 let id = activity.id().context(location_info!())?;
227 insert_activity(id, activity.clone(), true, sensitive, pool).await?;
231 let message = SendActivityTask {
232 activity: serialised_activity.to_owned(),
234 actor_id: actor.actor_id()?,
235 private_key: actor.private_key().context(location_info!())?,
237 activity_sender.queue::<SendActivityTask>(message)?;
243 #[derive(Clone, Debug, Deserialize, Serialize)]
244 struct SendActivityTask {
251 /// Signs the activity with the sending actor's key, and delivers to the given inbox. Also retries
252 /// if the delivery failed.
253 impl ActixJob for SendActivityTask {
254 type State = MyState;
255 type Future = Pin<Box<dyn Future<Output = Result<(), Error>>>>;
256 const NAME: &'static str = "SendActivityTask";
258 const MAX_RETRIES: MaxRetries = MaxRetries::Count(10);
259 const BACKOFF: Backoff = Backoff::Exponential(2);
261 fn run(self, state: Self::State) -> Self::Future {
262 Box::pin(async move {
263 let mut headers = BTreeMap::<String, String>::new();
264 headers.insert("Content-Type".into(), "application/json".into());
265 let result = sign_and_send(
269 self.activity.clone(),
271 self.private_key.to_owned(),
275 if let Err(e) = result {
278 "Failed to send activity {} to {}",
288 pub fn create_activity_queue() -> QueueHandle {
289 // Start the application server. This guards access to to the jobs store
290 let queue_handle = create_server(Storage::new());
292 // Configure and start our workers
293 WorkerConfig::new(|| MyState {
294 client: Client::default(),
296 .register::<SendActivityTask>()
297 .start(queue_handle.clone());