1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::{
    fs,
    io::{Error, ErrorKind},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use lol_html::{element, html_content::ContentType, HtmlRewriter, Settings};

pub struct InlineResult {
    pub html: String,
    pub files: Vec<PathBuf>,
}

pub fn inline<P>(file: P) -> anyhow::Result<InlineResult>
where
    P: AsRef<Path>,
{
    let html = fs::read_to_string(&file)?;
    let root = file.as_ref().parent().unwrap_or(Path::new(""));

    let mut output = vec![];
    let deps = Arc::new(Mutex::new(vec![]));
    let mut rewriter = HtmlRewriter::new(
        Settings {
            element_content_handlers: vec![
                element!("img", |el| {
                    let src = el.get_attribute("src");
                    if src.is_none() {
                        return Ok(());
                    }
                    let src = src.unwrap();
                    if src.starts_with("http") || src.starts_with("data:") {
                        return Ok(());
                    }

                    let path = root.clone().join(&src);
                    if !path.exists() {
                        return Err(Box::new(Error::new(
                            ErrorKind::NotFound,
                            format!("Can't inline image {}: file does not exist", src),
                        )));
                    }
                    let img_contents = fs::read(&path)?;
                    let mut deps = deps.lock().unwrap();
                    deps.push(path);
                    let new_src = base64::encode(img_contents);
                    let new_src = format!("data:image/png;base64,{}", new_src);

                    el.set_attribute("src", &new_src)?;
                    Ok(())
                }),
                element!("link", |el| {
                    let rel = el.get_attribute("rel");
                    let typ = el.get_attribute("type");

                    if let Some(rel) = rel {
                        if rel != "stylesheet" {
                            return Ok(());
                        }
                    }

                    if let Some(typ) = typ {
                        if typ != "text/css" {
                            return Ok(());
                        }
                    }

                    let href = el.get_attribute("href");
                    if href.is_none() {
                        return Ok(());
                    }
                    let href = href.unwrap();

                    if !href.ends_with(".css")
                        || href.starts_with("http")
                        || href.starts_with("data:")
                    {
                        return Ok(());
                    }

                    let path = root.clone().join(&href);
                    if !path.exists() {
                        return Err(Box::new(Error::new(
                            ErrorKind::NotFound,
                            format!("Can't inline styles from {}: file does not exist", href),
                        )));
                    }
                    let mut css = fs::read_to_string(&path)?;
                    let mut deps = deps.lock().unwrap();
                    deps.push(path);

                    if let Some(media) = el.get_attribute("media") {
                        css = format!("@media {} {{ {} }}", media, css);
                    }

                    el.replace(
                        &format!(r#"<style type="text/css">{}</style>"#, css),
                        ContentType::Html,
                    );

                    Ok(())
                }),
                element!("script", |el| {
                    let typ = el.get_attribute("type");
                    if let Some(typ) = typ {
                        if typ != "text/javascript" {
                            return Ok(());
                        }
                    }

                    let src = el.get_attribute("src");
                    if src.is_none() {
                        return Ok(());
                    }
                    let src = src.unwrap();

                    if src.starts_with("http") || src.starts_with("data:") {
                        return Ok(());
                    }

                    let path = root.clone().join(&src);
                    if !path.exists() {
                        return Err(Box::new(Error::new(
                            ErrorKind::NotFound,
                            format!("Can't inline script from {}: file does not exist", src),
                        )));
                    }
                    let js = fs::read_to_string(&path)?;
                    let mut deps = deps.lock().unwrap();
                    deps.push(path);

                    el.replace(
                        &format!("<script type=\"text/javascript\">{}</script>", js),
                        ContentType::Html,
                    );

                    Ok(())
                }),
            ],
            ..Settings::default()
        },
        |c: &[u8]| output.extend_from_slice(c),
    );

    rewriter.write(html.as_bytes())?;
    rewriter.end()?;

    let html = String::from_utf8(output)?;
    let files = Arc::try_unwrap(deps).unwrap();
    let files = files.into_inner().unwrap();
    Ok(InlineResult { html, files })
}