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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use css::Css;
use lol_html::{element, html_content::ContentType, HtmlRewriter, Settings};
use std::{
    fs,
    io::{Error, ErrorKind},
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

mod css;
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 css = Css::new(file.as_ref(), root, &deps);

    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.join(&src);
                    if !path.exists() {
                        return Err(Box::new(Error::new(
                            ErrorKind::NotFound,
                            format!(
                                "Can't inline image to {}: file \"{}\" does not exist",
                                file.as_ref().file_name().unwrap().to_str().unwrap(),
                                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| match css.handle(el) {
                    Ok(_) => Ok(()),
                    Err(e) => {
                        let err: Box<Error> = Box::new(e.downcast().unwrap());
                        Err(err)
                    }
                }),
                element!("include", |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.join(&src);
                    if !path.exists() {
                        return Err(Box::new(Error::new(
                            ErrorKind::NotFound,
                            format!(
                                "Can't include to {}: file \"{}\" does not exist",
                                file.as_ref().file_name().unwrap().to_str().unwrap(),
                                src,
                            ),
                        )));
                    }
                    let contents = fs::read_to_string(&path)?;
                    let mut deps = deps.lock().unwrap();
                    deps.push(path);

                    el.replace(&contents, 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 base64 = el.get_attribute("base64");
                    if base64.is_some() {
                        let path = root.join(&src);
                        if !path.exists() {
                            return Err(Box::new(Error::new(
                                ErrorKind::NotFound,
                                format!(
                                    "Can't inline script to {}: file \"{}\" does not exist",
                                    file.as_ref().file_name().unwrap().to_str().unwrap(),
                                    src,
                                ),
                            )));
                        }
                        let js = fs::read(&path)?;
                        let mut deps = deps.lock().unwrap();
                        deps.push(path);
                        let new_src = base64::encode(js);
                        let new_src = format!("data:application/javascript;base64,{}", new_src);

                        el.set_attribute("src", &new_src)?;
                        return Ok(());
                    }

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

                    el.replace(&format!("<script>{}</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 })
}