use std::ops::Range;
use std::sync::Arc;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use crate::sandbox::Filter;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
pub name: String,
pub content_type: &'static str,
pub bytes: Arc<Vec<u8>>,
}
impl Image {
#[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),
}
}
#[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
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Font {
pub family: String,
pub bytes: Arc<Vec<u8>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout {
pub name: String,
pub source: String,
}
impl Layout {
#[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 }
}
}
#[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())
}
pub(crate) fn image_sources(html: &str) -> Vec<Range<usize>> {
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
}
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
}
#[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()
}
pub(crate) fn inline_images(html: &str, assets: &Assets) -> String {
rewrite_sources(html, |src| assets.image(src).map(Image::data_uri))
}
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">"#);
}
}