laravel-template-engine 0.2.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! What the application gives templates: filters, pictures (`<img src="logo">`), fonts for
//! PDFs, and layouts.

use std::ops::Range;
use std::sync::Arc;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;

use crate::sandbox::Filter;

/// A picture templates can show with `<img src="name">`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
    /// The name templates use.
    pub name: String,
    /// `image/png`, `image/jpeg` or `image/gif`.
    pub content_type: &'static str,
    /// The file.
    pub bytes: Arc<Vec<u8>>,
}

impl Image {
    /// A picture called `name`.
    ///
    /// # Panics
    ///
    /// When the name has characters other than letters, digits, `.`, `-` and `_`, or the bytes
    /// aren't a PNG, JPEG or GIF: both are mistakes in the application's code.
    #[must_use]
    pub fn new(name: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        let name = name.into();
        assert!(
            !name.is_empty()
                && name
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')),
            "laravel-template-engine: the image name `{name}` may only have letters, digits, `.`, `-` and `_`"
        );
        let bytes = bytes.into();
        let content_type = sniff(&bytes)
            .unwrap_or_else(|| panic!("laravel-template-engine: the image `{name}` isn't a PNG, JPEG or GIF"));
        Self {
            name,
            content_type,
            bytes: Arc::new(bytes),
        }
    }

    /// The picture as a `data:` URI.
    #[must_use]
    pub fn data_uri(&self) -> String {
        format!(
            "data:{};base64,{}",
            self.content_type,
            STANDARD.encode(self.bytes.as_slice())
        )
    }

    pub(crate) fn file_name(&self) -> String {
        let extension = match self.content_type {
            "image/png" => "png",
            "image/jpeg" => "jpg",
            _ => "gif",
        };
        format!("{}.{extension}", self.name)
    }
}

fn sniff(bytes: &[u8]) -> Option<&'static str> {
    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
        Some("image/png")
    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
        Some("image/jpeg")
    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
        Some("image/gif")
    } else {
        None
    }
}

/// A font PDF documents can use with `font-family: name`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Font {
    /// The family name CSS uses.
    pub family: String,
    /// The TrueType or OpenType file.
    pub bytes: Arc<Vec<u8>>,
}

/// A layout: shared HTML, such as a header, a footer and styles, that a template's text goes
/// into at `{{ content }}`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout {
    /// The name templates choose it by.
    pub name: String,
    /// The layout's template. It sees `content` (the template's HTML), `subject` (for emails)
    /// and `locale`.
    pub source: String,
}

impl Layout {
    /// A layout called `name`.
    ///
    /// # Panics
    ///
    /// When `source` isn't a valid template or doesn't use `content`: both are mistakes in the
    /// application's code.
    #[must_use]
    pub fn new(name: impl Into<String>, source: impl Into<String>) -> Self {
        let name = name.into();
        let source = source.into();
        if let Err(error) = minijinja::machinery::parse(&source, &name, minijinja::syntax::SyntaxConfig::default()) {
            panic!("laravel-template-engine: the layout `{name}` isn't a valid template: {error}");
        }
        assert!(
            source.contains("content"),
            "laravel-template-engine: the layout `{name}` doesn't show `{{{{ content }}}}`"
        );
        Self { name, source }
    }
}

/// What the application registered on the provider: filters, pictures, fonts and layouts.
#[derive(Clone, Default)]
pub(crate) struct Assets {
    pub filters: Arc<Vec<Filter>>,
    pub images: Arc<Vec<Image>>,
    pub fonts: Arc<Vec<Font>>,
    pub layouts: Arc<Vec<Layout>>,
}

impl Assets {
    pub(crate) fn layout(&self, name: Option<&str>) -> Option<&Layout> {
        let name = name?;
        self.layouts.iter().find(|layout| layout.name == name)
    }

    pub(crate) fn layout_names(&self) -> Vec<String> {
        self.layouts.iter().map(|layout| layout.name.clone()).collect()
    }

    pub(crate) fn image(&self, name: &str) -> Option<&Image> {
        self.images.iter().find(|image| image.name == name)
    }

    pub(crate) fn image_names(&self) -> Vec<String> {
        self.images.iter().map(|image| image.name.clone()).collect()
    }
}

pub(crate) async fn assets() -> laravel::Result<Assets> {
    Ok(laravel::resolve::<Assets>()
        .await
        .map(|a| (*a).clone())
        .unwrap_or_default())
}

/// The byte ranges of the `src` values of the `<img>` tags in `html`. A value that isn't closed
/// within `html`, as in a piece of template text cut by `{{ ... }}`, is left out.
pub(crate) fn image_sources(html: &str) -> Vec<Range<usize>> {
    // ASCII lowercasing keeps every byte where it is, so offsets match the original.
    let lower = html.to_ascii_lowercase();
    let mut sources = Vec::new();
    let mut from = 0;
    while let Some(found) = lower[from..].find("<img") {
        let start = from + found;
        let end = lower[start..].find('>').map_or(lower.len(), |e| start + e);
        if let Some(range) = src_in_tag(&lower[start..end]) {
            sources.push(start + range.start..start + range.end);
        }
        from = end.max(start + 4);
    }
    sources
}

fn src_in_tag(tag: &str) -> Option<Range<usize>> {
    let mut search = 4;
    while let Some(found) = tag.get(search..)?.find("src") {
        let at = search + found;
        search = at + 3;
        if !tag.as_bytes()[at - 1].is_ascii_whitespace() {
            continue;
        }
        let rest = &tag[at + 3..];
        let after_name = rest.trim_start();
        let Some(after_eq) = after_name.strip_prefix('=') else {
            continue;
        };
        let value = after_eq.trim_start();
        let value_start = tag.len() - value.len();
        let first = value.chars().next()?;
        if first == '"' || first == '\'' {
            let close = value[1..].find(first)?;
            return Some(value_start + 1..value_start + 1 + close);
        }
        let length = value
            .find(|c: char| c.is_ascii_whitespace() || c == '/')
            .unwrap_or(value.len());
        return Some(value_start..value_start + length);
    }
    None
}

/// `html` with each `<img src>` that `replace` gives a value for changed to that value.
pub(crate) fn rewrite_sources(html: &str, mut replace: impl FnMut(&str) -> Option<String>) -> String {
    let mut out = String::with_capacity(html.len());
    let mut copied = 0;
    for range in image_sources(html) {
        let Some(new) = replace(html[range.clone()].trim()) else {
            continue;
        };
        out.push_str(&html[copied..range.start]);
        out.push_str(&new);
        copied = range.end;
    }
    out.push_str(&html[copied..]);
    out
}

/// The bytes of a base64 `data:image/...` URI.
#[cfg_attr(not(feature = "pdf"), allow(dead_code))]
pub(crate) fn decode_data_uri(src: &str) -> Option<Vec<u8>> {
    let (meta, payload) = src.strip_prefix("data:image/")?.split_once(',')?;
    if !meta.ends_with(";base64") {
        return None;
    }
    STANDARD.decode(payload.trim()).ok()
}

/// Shows registered pictures in a browser: their names become `data:` URIs.
pub(crate) fn inline_images(html: &str, assets: &Assets) -> String {
    rewrite_sources(html, |src| assets.image(src).map(Image::data_uri))
}

/// Points the email's `<img src="logo">` at an attached picture, `cid:logo`, and returns the
/// pictures to attach. Gmail and Outlook don't show `data:` pictures, so emails attach them.
pub(crate) fn embed_images(html: &str, assets: &Assets) -> (String, Vec<Image>) {
    let mut used: Vec<Image> = Vec::new();
    let html = rewrite_sources(html, |src| {
        let image = assets.image(src)?;
        if !used.iter().any(|u| u.name == image.name) {
            used.push(image.clone());
        }
        Some(format!("cid:{}", image.name))
    });
    (html, used)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn finds_sources_in_any_quoting() {
        let html = r#"<p><img src="logo" alt="x"><IMG alt='y' SRC='sig.png'/><img data-src="no" src=bare></p>"#;
        let found: Vec<&str> = image_sources(html).into_iter().map(|r| &html[r]).collect();
        assert_eq!(found, vec!["logo", "sig.png", "bare"]);
    }

    #[test]
    fn leaves_out_values_a_template_expression_cuts() {
        assert_eq!(image_sources(r#"<img src="{{ "#).len(), 0);
        assert_eq!(image_sources(r#"<img src="logo"#).len(), 0);
    }

    #[test]
    fn rewrites_only_what_the_callback_knows() {
        let html = r#"<img src="logo"><img src="https://x/y.png">"#;
        let out = rewrite_sources(html, |src| (src == "logo").then(|| "cid:logo".to_owned()));
        assert_eq!(out, r#"<img src="cid:logo"><img src="https://x/y.png">"#);
    }
}