diff --git a/src/jobs/cache_media.rs b/src/jobs/cache_media.rs new file mode 100644 index 0000000..d8e7001 --- /dev/null +++ b/src/jobs/cache_media.rs @@ -0,0 +1,44 @@ +use crate::jobs::JobState; +use anyhow::Error; +use background_jobs::ActixJob; +use std::{future::Future, pin::Pin}; +use uuid::Uuid; + +#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] +pub struct CacheMedia { + uuid: Uuid, +} + +impl CacheMedia { + pub fn new(uuid: Uuid) -> Self { + CacheMedia { uuid } + } + + async fn perform(self, state: JobState) -> Result<(), Error> { + if state.media.get_bytes(self.uuid).await.is_some() { + return Ok(()); + } + + if let Some(url) = state.media.get_url(self.uuid).await? { + let (content_type, bytes) = state.requests.fetch_bytes(url.as_str()).await?; + + state + .media + .store_bytes(self.uuid, content_type, bytes) + .await; + } + + Ok(()) + } +} + +impl ActixJob for CacheMedia { + type State = JobState; + type Future = Pin>>>; + + const NAME: &'static str = "relay::jobs::CacheMedia"; + + fn run(self, state: Self::State) -> Self::Future { + Box::pin(self.perform(state)) + } +} diff --git a/src/jobs/instance.rs b/src/jobs/instance.rs index 4de7713..27e6f68 100644 --- a/src/jobs/instance.rs +++ b/src/jobs/instance.rs @@ -1,4 +1,7 @@ -use crate::{config::UrlKind, jobs::JobState}; +use crate::{ + config::UrlKind, + jobs::{cache_media::CacheMedia, JobState}, +}; use activitystreams_new::primitives::XsdAnyUri; use anyhow::Error; use background_jobs::ActixJob; @@ -44,12 +47,16 @@ impl QueryInstance { }; if let Some(mut contact) = instance.contact { - if let Some(uuid) = state.media.get_uuid(&contact.avatar).await? { + let uuid = if let Some(uuid) = state.media.get_uuid(&contact.avatar).await? { contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).parse()?; + uuid } else { let uuid = state.media.store_url(&contact.avatar).await?; contact.avatar = state.config.generate_url(UrlKind::Media(uuid)).parse()?; - } + uuid + }; + + state.job_server.queue(CacheMedia::new(uuid))?; state .node_cache diff --git a/src/jobs/mod.rs b/src/jobs/mod.rs index 29df26c..08f12bb 100644 --- a/src/jobs/mod.rs +++ b/src/jobs/mod.rs @@ -1,4 +1,5 @@ pub mod apub; +mod cache_media; mod deliver; mod deliver_many; mod instance; @@ -7,7 +8,8 @@ mod process_listeners; mod storage; pub use self::{ - deliver::Deliver, deliver_many::DeliverMany, instance::QueryInstance, nodeinfo::QueryNodeinfo, + cache_media::CacheMedia, deliver::Deliver, deliver_many::DeliverMany, instance::QueryInstance, + nodeinfo::QueryNodeinfo, }; use crate::{ @@ -54,6 +56,7 @@ pub fn create_workers( .register::() .register::() .register::() + .register::() .register::() .register::() .register::()