laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde_json::Value;
use sha1::{Digest, Sha1};

use crate::backgrounds::{LocalBackground, NullBackground, UnsplashBackground};
use crate::config::{Format, LaracardsConfig};
use crate::contracts::Background;
use crate::generator::CardGenerator;
use crate::support::Raster;

/// Anything a card accepts as its background: a [`Background`], a path to a local image, or `None` for
/// no background layer.
pub trait IntoBackground {
    /// The driver.
    fn into_background(self) -> Arc<dyn Background>;
}

impl<B: Background + 'static> IntoBackground for B {
    fn into_background(self) -> Arc<dyn Background> {
        Arc::new(self)
    }
}

impl IntoBackground for Arc<dyn Background> {
    fn into_background(self) -> Arc<dyn Background> {
        self
    }
}

impl IntoBackground for &str {
    fn into_background(self) -> Arc<dyn Background> {
        Arc::new(LocalBackground::new(self))
    }
}

impl IntoBackground for String {
    fn into_background(self) -> Arc<dyn Background> {
        Arc::new(LocalBackground::new(self))
    }
}

impl IntoBackground for &Path {
    fn into_background(self) -> Arc<dyn Background> {
        Arc::new(LocalBackground::new(self))
    }
}

impl IntoBackground for PathBuf {
    fn into_background(self) -> Arc<dyn Background> {
        Arc::new(LocalBackground::new(self))
    }
}

impl<T: IntoBackground> IntoBackground for Option<T> {
    fn into_background(self) -> Arc<dyn Background> {
        match self {
            Some(background) => background.into_background(),
            None => Arc::new(NullBackground),
        }
    }
}

/// A card waiting to be generated.
///
/// Everything a card needs is declared here and nothing is resolved until [`generate`](Self::generate)
/// runs, so a [`CardSource`](crate::contracts::CardSource) can hand back thousands of these cheaply and
/// the command decides which ones are actually stale.
#[derive(Clone)]
pub struct Card {
    key: String,
    template: String,
    data: BTreeMap<String, Value>,
    background: Option<Arc<dyn Background>>,
    output: Option<PathBuf>,
}

impl Card {
    /// `key` identifies the card in the manifest, usually the content slug.
    pub fn make(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            template: "post".to_owned(),
            data: BTreeMap::new(),
            background: None,
            output: None,
        }
    }

    /// The template to draw the card with. `post` unless set.
    #[must_use]
    pub fn template(mut self, template: impl Into<String>) -> Self {
        self.template = template.into();

        self
    }

    /// Merges fields into the card's data. Takes a JSON object, so `json!({ "title": "..." })` is the
    /// array of the PHP package, and values can be strings, numbers or null. Anything that is not an
    /// object is ignored.
    #[must_use]
    pub fn data(mut self, data: impl Into<Value>) -> Self {
        if let Value::Object(fields) = data.into() {
            self.data.extend(fields);
        }

        self
    }

    /// A [`Background`], the path of a local image, or `None` for no background layer.
    #[must_use]
    pub fn background(mut self, background: impl IntoBackground) -> Self {
        self.background = Some(background.into_background());

        self
    }

    /// A landscape photo from Unsplash, downloaded once and then cached. For another orientation, pass
    /// an [`UnsplashBackground`] to [`background`](Self::background).
    #[must_use]
    pub fn unsplash(self, query: impl Into<String>) -> Self {
        self.background(UnsplashBackground::new(query))
    }

    /// Where the card is written. The extension decides the format.
    #[must_use]
    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
        self.output = Some(path.into());

        self
    }

    /// The key of the card.
    pub fn key(&self) -> &str {
        &self.key
    }

    /// The name of the template.
    pub fn template_name(&self) -> &str {
        &self.template
    }

    /// The card's data.
    pub fn payload(&self) -> &BTreeMap<String, Value> {
        &self.data
    }

    /// A field of the data as text. PHP casts scalars: `true` is `1`, `false` and null are empty.
    pub fn scalar(&self, field: &str) -> String {
        match self.data.get(field) {
            Some(Value::String(text)) => text.clone(),
            Some(Value::Number(number)) => number.to_string(),
            Some(Value::Bool(true)) => "1".to_owned(),
            _ => String::new(),
        }
    }

    /// The background driver. A card without one has [`NullBackground`].
    pub fn background_driver(&self) -> Arc<dyn Background> {
        self.background.clone().unwrap_or_else(|| Arc::new(NullBackground))
    }

    /// Where the card is written: the explicit path, or `paths.output` with the key and the extension of
    /// the template's format.
    ///
    /// The extension follows the template's format, so a template that produces JPEG does not end up
    /// writing files named `.png`.
    pub fn output_path(&self) -> PathBuf {
        if let Some(output) = &self.output {
            return output.clone();
        }

        let config = LaracardsConfig::current();
        let format = config
            .templates
            .get(&self.template)
            .and_then(|template| template.format)
            .unwrap_or(config.format);

        LaracardsConfig::resolve(&LaracardsConfig::base(), &config.paths.output).join(format!(
            "{}.{}",
            self.key,
            format.extension()
        ))
    }

    /// Everything that, if changed, should produce a different image.
    ///
    /// This is what removes the "remember to delete the PNG by hand when the date changes" step: the date
    /// is part of the payload, so a changed date is a changed fingerprint and the card regenerates on its
    /// own.
    pub fn fingerprint(&self) -> String {
        let parts = serde_json::json!({
            "template": self.template,
            "data": self.data,
            "background": self.background_driver().fingerprint(),
        });
        let digest = Sha1::digest(parts.to_string());

        digest.iter().map(|byte| format!("{byte:02x}")).collect()
    }

    /// Generates the card. Returns where it was written, or `None` when it was already up to date and
    /// `force` is off. PHP's `generate($force = false)`.
    ///
    /// # Errors
    ///
    /// Fails when the template, a font or the background cannot be read, or the card cannot be drawn or
    /// written.
    pub async fn generate(&self, force: bool) -> laravel::Result<Option<PathBuf>> {
        laravel::resolve::<CardGenerator>().await?.generate(self, force).await
    }

    /// The format an explicit output path asks for, if its extension is one.
    pub(crate) fn output_format(&self) -> Option<Format> {
        Raster::normalise(self.output_path().extension().and_then(|extension| extension.to_str()))
    }
}