Skip to main content

laravel_template_engine/
assets.rs

1//! What the application gives templates: filters, pictures (`<img src="logo">`), fonts for
2//! PDFs, and layouts.
3
4use std::ops::Range;
5use std::sync::Arc;
6
7use base64::Engine;
8use base64::engine::general_purpose::STANDARD;
9
10use crate::sandbox::Filter;
11
12/// A picture templates can show with `<img src="name">`.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Image {
15    /// The name templates use.
16    pub name: String,
17    /// `image/png`, `image/jpeg` or `image/gif`.
18    pub content_type: &'static str,
19    /// The file.
20    pub bytes: Arc<Vec<u8>>,
21}
22
23impl Image {
24    /// A picture called `name`.
25    ///
26    /// # Panics
27    ///
28    /// When the name has characters other than letters, digits, `.`, `-` and `_`, or the bytes
29    /// aren't a PNG, JPEG or GIF: both are mistakes in the application's code.
30    #[must_use]
31    pub fn new(name: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
32        let name = name.into();
33        assert!(
34            !name.is_empty()
35                && name
36                    .chars()
37                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')),
38            "laravel-template-engine: the image name `{name}` may only have letters, digits, `.`, `-` and `_`"
39        );
40        let bytes = bytes.into();
41        let content_type = sniff(&bytes)
42            .unwrap_or_else(|| panic!("laravel-template-engine: the image `{name}` isn't a PNG, JPEG or GIF"));
43        Self {
44            name,
45            content_type,
46            bytes: Arc::new(bytes),
47        }
48    }
49
50    /// The picture as a `data:` URI.
51    #[must_use]
52    pub fn data_uri(&self) -> String {
53        format!(
54            "data:{};base64,{}",
55            self.content_type,
56            STANDARD.encode(self.bytes.as_slice())
57        )
58    }
59
60    pub(crate) fn file_name(&self) -> String {
61        let extension = match self.content_type {
62            "image/png" => "png",
63            "image/jpeg" => "jpg",
64            _ => "gif",
65        };
66        format!("{}.{extension}", self.name)
67    }
68}
69
70fn sniff(bytes: &[u8]) -> Option<&'static str> {
71    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
72        Some("image/png")
73    } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
74        Some("image/jpeg")
75    } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
76        Some("image/gif")
77    } else {
78        None
79    }
80}
81
82/// A font PDF documents can use with `font-family: name`.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Font {
85    /// The family name CSS uses.
86    pub family: String,
87    /// The TrueType or OpenType file.
88    pub bytes: Arc<Vec<u8>>,
89}
90
91/// A layout: shared HTML, such as a header, a footer and styles, that a template's text goes
92/// into at `{{ content }}`.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Layout {
95    /// The name templates choose it by.
96    pub name: String,
97    /// The layout's template. It sees `content` (the template's HTML), `subject` (for emails)
98    /// and `locale`.
99    pub source: String,
100}
101
102impl Layout {
103    /// A layout called `name`.
104    ///
105    /// # Panics
106    ///
107    /// When `source` isn't a valid template or doesn't use `content`: both are mistakes in the
108    /// application's code.
109    #[must_use]
110    pub fn new(name: impl Into<String>, source: impl Into<String>) -> Self {
111        let name = name.into();
112        let source = source.into();
113        if let Err(error) = minijinja::machinery::parse(&source, &name, minijinja::syntax::SyntaxConfig::default()) {
114            panic!("laravel-template-engine: the layout `{name}` isn't a valid template: {error}");
115        }
116        assert!(
117            source.contains("content"),
118            "laravel-template-engine: the layout `{name}` doesn't show `{{{{ content }}}}`"
119        );
120        Self { name, source }
121    }
122}
123
124/// What the application registered on the provider: filters, pictures, fonts and layouts.
125#[derive(Clone, Default)]
126pub(crate) struct Assets {
127    pub filters: Arc<Vec<Filter>>,
128    pub images: Arc<Vec<Image>>,
129    pub fonts: Arc<Vec<Font>>,
130    pub layouts: Arc<Vec<Layout>>,
131    pub channels: Arc<Vec<crate::Channel>>,
132}
133
134impl Assets {
135    pub(crate) fn layout(&self, name: Option<&str>) -> Option<&Layout> {
136        let name = name?;
137        self.layouts.iter().find(|layout| layout.name == name)
138    }
139
140    /// Laravel's own channels, then the application's.
141    pub(crate) fn channel_names(&self) -> Vec<String> {
142        crate::notification::builtin_channels()
143            .into_iter()
144            .chain(self.channels.iter().cloned())
145            .map(|channel| channel.name)
146            .collect()
147    }
148
149    pub(crate) fn layout_names(&self) -> Vec<String> {
150        self.layouts.iter().map(|layout| layout.name.clone()).collect()
151    }
152
153    pub(crate) fn image(&self, name: &str) -> Option<&Image> {
154        self.images.iter().find(|image| image.name == name)
155    }
156
157    pub(crate) fn image_names(&self) -> Vec<String> {
158        self.images.iter().map(|image| image.name.clone()).collect()
159    }
160}
161
162pub(crate) async fn assets() -> laravel::Result<Assets> {
163    Ok(laravel::resolve::<Assets>()
164        .await
165        .map(|a| (*a).clone())
166        .unwrap_or_default())
167}
168
169/// The byte ranges of the `src` values of the `<img>` tags in `html`. A value that isn't closed
170/// within `html`, as in a piece of template text cut by `{{ ... }}`, is left out.
171pub(crate) fn image_sources(html: &str) -> Vec<Range<usize>> {
172    // ASCII lowercasing keeps every byte where it is, so offsets match the original.
173    let lower = html.to_ascii_lowercase();
174    let mut sources = Vec::new();
175    let mut from = 0;
176    while let Some(found) = lower[from..].find("<img") {
177        let start = from + found;
178        let end = lower[start..].find('>').map_or(lower.len(), |e| start + e);
179        if let Some(range) = src_in_tag(&lower[start..end]) {
180            sources.push(start + range.start..start + range.end);
181        }
182        from = end.max(start + 4);
183    }
184    sources
185}
186
187fn src_in_tag(tag: &str) -> Option<Range<usize>> {
188    let mut search = 4;
189    while let Some(found) = tag.get(search..)?.find("src") {
190        let at = search + found;
191        search = at + 3;
192        if !tag.as_bytes()[at - 1].is_ascii_whitespace() {
193            continue;
194        }
195        let rest = &tag[at + 3..];
196        let after_name = rest.trim_start();
197        let Some(after_eq) = after_name.strip_prefix('=') else {
198            continue;
199        };
200        let value = after_eq.trim_start();
201        let value_start = tag.len() - value.len();
202        let first = value.chars().next()?;
203        if first == '"' || first == '\'' {
204            let close = value[1..].find(first)?;
205            return Some(value_start + 1..value_start + 1 + close);
206        }
207        let length = value
208            .find(|c: char| c.is_ascii_whitespace() || c == '/')
209            .unwrap_or(value.len());
210        return Some(value_start..value_start + length);
211    }
212    None
213}
214
215/// `html` with each `<img src>` that `replace` gives a value for changed to that value.
216pub(crate) fn rewrite_sources(html: &str, mut replace: impl FnMut(&str) -> Option<String>) -> String {
217    let mut out = String::with_capacity(html.len());
218    let mut copied = 0;
219    for range in image_sources(html) {
220        let Some(new) = replace(html[range.clone()].trim()) else {
221            continue;
222        };
223        out.push_str(&html[copied..range.start]);
224        out.push_str(&new);
225        copied = range.end;
226    }
227    out.push_str(&html[copied..]);
228    out
229}
230
231/// The bytes of a base64 `data:image/...` URI.
232#[cfg_attr(not(feature = "pdf"), allow(dead_code))]
233pub(crate) fn decode_data_uri(src: &str) -> Option<Vec<u8>> {
234    let (meta, payload) = src.strip_prefix("data:image/")?.split_once(',')?;
235    if !meta.ends_with(";base64") {
236        return None;
237    }
238    STANDARD.decode(payload.trim()).ok()
239}
240
241/// Shows registered pictures in a browser: their names become `data:` URIs.
242pub(crate) fn inline_images(html: &str, assets: &Assets) -> String {
243    rewrite_sources(html, |src| assets.image(src).map(Image::data_uri))
244}
245
246/// Points the email's `<img src="logo">` at an attached picture, `cid:logo`, and returns the
247/// pictures to attach. Gmail and Outlook don't show `data:` pictures, so emails attach them.
248pub(crate) fn embed_images(html: &str, assets: &Assets) -> (String, Vec<Image>) {
249    let mut used: Vec<Image> = Vec::new();
250    let html = rewrite_sources(html, |src| {
251        let image = assets.image(src)?;
252        if !used.iter().any(|u| u.name == image.name) {
253            used.push(image.clone());
254        }
255        Some(format!("cid:{}", image.name))
256    });
257    (html, used)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn finds_sources_in_any_quoting() {
266        let html = r#"<p><img src="logo" alt="x"><IMG alt='y' SRC='sig.png'/><img data-src="no" src=bare></p>"#;
267        let found: Vec<&str> = image_sources(html).into_iter().map(|r| &html[r]).collect();
268        assert_eq!(found, vec!["logo", "sig.png", "bare"]);
269    }
270
271    #[test]
272    fn leaves_out_values_a_template_expression_cuts() {
273        assert_eq!(image_sources(r#"<img src="{{ "#).len(), 0);
274        assert_eq!(image_sources(r#"<img src="logo"#).len(), 0);
275    }
276
277    #[test]
278    fn rewrites_only_what_the_callback_knows() {
279        let html = r#"<img src="logo"><img src="https://x/y.png">"#;
280        let out = rewrite_sources(html, |src| (src == "logo").then(|| "cid:logo".to_owned()));
281        assert_eq!(out, r#"<img src="cid:logo"><img src="https://x/y.png">"#);
282    }
283}