laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
//! Where the picture behind a card comes from.

use std::path::{Path, PathBuf};

use async_trait::async_trait;
use laravel::http::client;
use laravel::time::ToSpan;
use sha1::{Digest, Sha1};

use crate::config::LaracardsConfig;
use crate::contracts::Background;
use crate::exceptions::RenderFailed;

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// A background already on disk.
///
/// This is the driver for images generated elsewhere, including anything you produced with an image
/// model and dropped into the repository: save the file, point at it, done. The template does not change.
pub struct LocalBackground {
    path: PathBuf,
}

impl LocalBackground {
    /// A background at `path`.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    fn existing(&self) -> Option<&Path> {
        self.path.is_file().then_some(self.path.as_path())
    }
}

#[async_trait]
impl Background for LocalBackground {
    async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
        match self.existing() {
            Some(path) => Ok(Some(path.to_path_buf())),
            None => Err(RenderFailed::new(format!(
                "Laracards: the background '{}' does not exist.",
                self.path.display()
            ))
            .into()),
        }
    }

    fn fingerprint(&self) -> String {
        match self.existing().and_then(|path| std::fs::read(path).ok()) {
            Some(contents) => format!("local:{}", &hex(&Sha1::digest(contents))[..16]),
            None => "local:missing".to_owned(),
        }
    }
}

/// No background layer: the template paints its own.
#[derive(Debug, Clone, Copy, Default)]
pub struct NullBackground;

#[async_trait]
impl Background for NullBackground {
    async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
        Ok(None)
    }

    fn fingerprint(&self) -> String {
        "none".to_owned()
    }
}

/// Downloads a photo from Unsplash once and caches it on disk.
///
/// The cache key is the query plus the orientation, so re-running the generate command does not hit the
/// API again, and the same query always yields the same card. Deleting the cached file is how you ask
/// for a different photo.
///
/// The access key and the cache directory come from `backgrounds.unsplash` in the configuration, read
/// when the photo is fetched, unless they are set here.
pub struct UnsplashBackground {
    query: String,
    orientation: String,
    width: u32,
    cache_path: Option<PathBuf>,
    access_key: Option<String>,
}

impl UnsplashBackground {
    /// A landscape photo for `query`.
    pub fn new(query: impl Into<String>) -> Self {
        Self {
            query: query.into(),
            orientation: "landscape".to_owned(),
            width: 1600,
            cache_path: None,
            access_key: None,
        }
    }

    /// `landscape`, `portrait` or `squarish`.
    #[must_use]
    pub fn orientation(mut self, orientation: impl Into<String>) -> Self {
        self.orientation = orientation.into();

        self
    }

    /// The width of the downloaded photo.
    #[must_use]
    pub fn width(mut self, width: u32) -> Self {
        self.width = width;

        self
    }

    /// Where photos are cached, instead of `backgrounds.unsplash.cache`.
    #[must_use]
    pub fn cache_path(mut self, cache_path: impl Into<PathBuf>) -> Self {
        self.cache_path = Some(cache_path.into());

        self
    }

    /// The access key, instead of `backgrounds.unsplash.access_key`.
    #[must_use]
    pub fn access_key(mut self, access_key: impl Into<String>) -> Self {
        self.access_key = Some(access_key.into());

        self
    }

    fn cache_key(&self) -> String {
        let digest = Sha1::digest(format!("{}|{}|{}", self.query, self.orientation, self.width));

        hex(&digest)[..20].to_owned()
    }
}

#[async_trait]
impl Background for UnsplashBackground {
    async fn resolve(&self) -> laravel::Result<Option<PathBuf>> {
        let config = LaracardsConfig::current();
        let cache = self
            .cache_path
            .clone()
            .unwrap_or_else(|| LaracardsConfig::resolve(&LaracardsConfig::base(), &config.backgrounds.unsplash.cache));
        let cached = cache.join(format!("{}.jpg", self.cache_key()));

        if cached.is_file() {
            return Ok(Some(cached));
        }

        let Some(access_key) = self.access_key.clone().or(config.backgrounds.unsplash.access_key) else {
            tracing::warn!(query = %self.query, "Laracards: no Unsplash access key configured, skipping background.");

            return Ok(None);
        };

        std::fs::create_dir_all(&cache)?;

        let search = client::get("https://api.unsplash.com/search/photos")
            .header("Authorization", format!("Client-ID {access_key}"))
            .header("Accept-Version", "v1")
            .query([
                ("query", self.query.as_str()),
                ("orientation", self.orientation.as_str()),
                ("per_page", "1"),
            ])
            .timeout(20.seconds())
            .await?;

        if !search.successful() {
            tracing::warn!(query = %self.query, status = search.status().as_u16(), "Laracards: Unsplash search failed.");

            return Ok(None);
        }

        let found: serde_json::Value = search.json()?;

        let Some(url) = found["results"][0]["urls"]["raw"].as_str() else {
            tracing::warn!(query = %self.query, "Laracards: Unsplash returned no results.");

            return Ok(None);
        };

        let photo = client::get(format!("{url}&w={}&q=80&fm=jpg&fit=max", self.width))
            .timeout(60.seconds())
            .await?;

        if !photo.successful() {
            return Ok(None);
        }

        std::fs::write(&cached, photo.bytes())?;

        Ok(Some(cached))
    }

    fn fingerprint(&self) -> String {
        format!("unsplash:{}", self.cache_key())
    }
}