use std::collections::BTreeMap;
use crate::TemplateError;
use crate::assets::{Assets, Layout, inline_images};
use crate::config::{TemplateEngineConfig, config};
use crate::sandbox::{Escape, Limits, Sandbox, to_value};
use crate::template::{Content, DocumentFormat, DocumentSettings, Orientation};
pub(crate) fn sandbox(locale: &str, assets: &Assets, config: &TemplateEngineConfig) -> Sandbox {
Sandbox {
locale: locale.to_owned(),
currency: config.currency.clone(),
custom: assets.filters.clone(),
limits: Limits::from_config(config),
}
}
pub(crate) fn pick_locale<'a>(
content: &'a BTreeMap<String, Content>,
wanted: Option<&str>,
default: &str,
) -> Option<(&'a str, &'a Content)> {
let find = |locale: &str| {
let locale = locale.replace('_', "-").to_ascii_lowercase();
content
.iter()
.find(|(key, _)| key.replace('_', "-").to_ascii_lowercase() == locale)
};
let language = |locale: &str| locale.split(['-', '_']).next().unwrap_or(locale).to_owned();
wanted
.and_then(|w| find(w).or_else(|| find(&language(w))))
.or_else(|| find(default))
.or_else(|| find(&language(default)))
.or_else(|| content.iter().next())
.map(|(key, value)| (key.as_str(), value))
}
pub(crate) fn render_text(
sandbox: &Sandbox,
name: &str,
source: &str,
data: &serde_json::Value,
escape: Escape,
) -> laravel::Result<String> {
sandbox
.render(name, source, &to_value(data), escape)
.map_err(|message| TemplateError::Render(format!("{name}: {message}")).into())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedMail {
pub locale: String,
pub subject: String,
pub html: String,
pub text: String,
}
pub(crate) fn render_mail(
sandbox: &Sandbox,
locale: &str,
content: &Content,
data: &serde_json::Value,
layout: Option<&Layout>,
) -> laravel::Result<RenderedMail> {
let subject = render_text(sandbox, "subject", &content.subject, data, Escape::None)?;
let body = render_text(sandbox, "body", &content.body, data, Escape::Html)?;
let body = apply_layout(sandbox, layout, body, &subject, locale)?;
let html = inline_css(&body)?;
let text = html_to_text(&html);
Ok(RenderedMail {
locale: locale.to_owned(),
subject: subject.trim().replace(['\r', '\n'], " "),
html,
text,
})
}
fn apply_layout(
sandbox: &Sandbox,
layout: Option<&Layout>,
body: String,
subject: &str,
locale: &str,
) -> laravel::Result<String> {
let Some(layout) = layout else { return Ok(body) };
let context = minijinja::context! {
content => minijinja::Value::from_safe_string(body),
subject => subject,
locale => locale,
};
sandbox
.render(
&format!("layout {}", layout.name),
&layout.source,
&context,
Escape::Html,
)
.map_err(|message| TemplateError::Render(format!("layout `{}`: {message}", layout.name)).into())
}
fn base_style(settings: &DocumentSettings) -> String {
let mut rules = Vec::new();
if let Some(family) = settings
.font_family
.as_deref()
.map(safe_font_family)
.filter(|f| !f.is_empty())
{
rules.push(format!("font-family: \"{family}\""));
}
if let Some(size) = settings.font_size {
rules.push(format!("font-size: {size}pt"));
}
if let Some(height) = settings.line_height {
rules.push(format!("line-height: {height}"));
}
if rules.is_empty() {
return String::new();
}
let rules = rules.join("; ");
format!("<style>body, p, td, th, li {{ {rules} }}</style>")
}
pub(crate) fn safe_font_family(family: &str) -> String {
family
.chars()
.filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_'))
.collect::<String>()
.trim()
.to_owned()
}
fn inline_css(html: &str) -> laravel::Result<String> {
css_inline::CSSInliner::options()
.load_remote_stylesheets(false)
.build()
.inline(html)
.map_err(|e| TemplateError::Render(format!("the email's CSS: {e}")).into())
}
fn html_to_text(html: &str) -> String {
html2text::from_read(html.as_bytes(), 78)
.unwrap_or_default()
.trim()
.to_owned()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document {
pub filename: String,
pub content_type: String,
pub bytes: Vec<u8>,
pub html: String,
pub locale: String,
}
impl Document {
pub fn into_download(self) -> laravel::http::Download {
laravel::http::Download::new(self.filename, self.bytes).content_type(self.content_type)
}
#[must_use]
pub fn into_attachment(self) -> laravel::mail::Attachment {
laravel::mail::Attachment::from_bytes(self.bytes, self.filename).content_type(self.content_type)
}
}
pub(crate) fn render_document(
sandbox: &Sandbox,
locale: &str,
content: &Content,
settings: &DocumentSettings,
data: &serde_json::Value,
assets: &Assets,
) -> laravel::Result<Document> {
let body = render_text(sandbox, "body", &content.body, data, Escape::Html)?;
let layout = assets.layout(settings.layout.as_deref());
let rendered = format!(
"{}{}",
base_style(settings),
apply_layout(sandbox, layout, body, "", locale)?
);
let html = inline_images(&rendered, assets);
let name = render_text(sandbox, "filename", &settings.filename, data, Escape::None)?;
let extension = match settings.format {
DocumentFormat::Pdf => "pdf",
DocumentFormat::Html => "html",
};
let filename = file_name(&name, extension);
let (bytes, content_type) = match settings.format {
DocumentFormat::Html => (html.clone().into_bytes(), "text/html; charset=utf-8"),
DocumentFormat::Pdf => (pdf(&rendered, settings, assets)?, "application/pdf"),
};
Ok(Document {
filename,
content_type: content_type.to_owned(),
bytes,
html,
locale: locale.to_owned(),
})
}
fn file_name(name: &str, extension: &str) -> String {
let cleaned: String = name
.trim()
.chars()
.map(|c| {
if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') {
'-'
} else {
c
}
})
.collect();
let cleaned = cleaned.trim_matches(['.', ' ']).to_owned();
let cleaned = if cleaned.is_empty() {
"document".to_owned()
} else {
cleaned
};
if cleaned.to_ascii_lowercase().ends_with(&format!(".{extension}")) {
cleaned
} else {
format!("{cleaned}.{extension}")
}
}
pub(crate) const PAPERS: &[(&str, f32, f32)] = &[
("a0", 841.0, 1189.0),
("a1", 594.0, 841.0),
("a2", 420.0, 594.0),
("a3", 297.0, 420.0),
("a4", 210.0, 297.0),
("a5", 148.0, 210.0),
("a6", 105.0, 148.0),
("letter", 215.9, 279.4),
("legal", 215.9, 355.6),
("tabloid", 279.4, 431.8),
("ledger", 431.8, 279.4),
];
#[cfg(feature = "pdf")]
fn pdf(html: &str, settings: &DocumentSettings, assets: &Assets) -> laravel::Result<Vec<u8>> {
use printpdf::{Base64OrRaw, GeneratePdfOptions, PdfDocument, PdfSaveOptions};
let paper = settings.paper.to_ascii_lowercase();
let (_, width, height) = PAPERS
.iter()
.find(|(name, ..)| *name == paper)
.copied()
.unwrap_or(PAPERS[4]);
let (width, height) = match settings.orientation {
Orientation::Portrait => (width, height),
Orientation::Landscape => (height, width),
};
let options = GeneratePdfOptions {
page_width: Some(width),
page_height: Some(height),
margin_top: Some(settings.margins.top),
margin_right: Some(settings.margins.right),
margin_bottom: Some(settings.margins.bottom),
margin_left: Some(settings.margins.left),
show_page_numbers: None,
header_text: None,
footer_text: None,
skip_first_page: None,
};
let mut images = BTreeMap::new();
let html = crate::assets::rewrite_sources(html, |src| {
if let Some(image) = assets.image(src) {
images.insert(src.to_owned(), Base64OrRaw::Raw(image.bytes.to_vec()));
return None;
}
let bytes = crate::assets::decode_data_uri(src)?;
let key = format!("data-image-{}", images.len());
images.insert(key.clone(), Base64OrRaw::Raw(bytes));
Some(key)
});
let fonts = assets
.fonts
.iter()
.map(|font| (font.family.clone(), Base64OrRaw::Raw(font.bytes.to_vec())))
.collect();
let mut warnings = Vec::new();
let document = PdfDocument::from_html(without_doctype(&html), &images, &fonts, &options, &mut warnings)
.map_err(|e| TemplateError::Render(format!("the PDF: {e}")))?;
Ok(document.save(&PdfSaveOptions::default(), &mut warnings))
}
#[cfg(feature = "pdf")]
fn without_doctype(html: &str) -> &str {
let trimmed = html.trim_start();
if trimmed
.get(..9)
.is_some_and(|start| start.eq_ignore_ascii_case("<!doctype"))
{
return trimmed.split_once('>').map_or("", |(_, rest)| rest);
}
trimmed
}
#[cfg(not(feature = "pdf"))]
fn pdf(_html: &str, _settings: &DocumentSettings, _assets: &Assets) -> laravel::Result<Vec<u8>> {
let _ = Orientation::Portrait;
Err(TemplateError::PdfDisabled.into())
}
pub(crate) fn current_config() -> TemplateEngineConfig {
config()
}