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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
extern crate base64;
extern crate regex;

use std::collections::HashSet;
use std::fs;
use std::io::ErrorKind as IoErrorKind;
use std::path::Path;

use regex::Captures;

/// Augmented std::io::Error so that it shows what line is causing the problem.
#[derive(Debug)]
pub enum FilePathError {
    /// A std::io::ErrorKind::NotFound error with the offending line in the string parameter
    InvalidPath(String),
    /// Any other file read error that is not NotFound
    FileReadError(String, std::io::Error),
    /// A css file is imported twice, or there is a dependency loop
    RepeatedFile,
}

/// Config struct that is passed to `inline_file()` and `inline_html_string()`
///
/// Default enables everything
#[derive(Debug, Copy, Clone)]
pub struct Config {
    /// Whether or not to inline fonts in the css as base64.
    pub inline_fonts: bool,
    /// Replace `\r` and `\r\n` with a space character. Useful to keep line numbers the same in the output to help with debugging.
    pub remove_new_lines: bool,
}

impl Default for Config {
    /// Enables everything
    fn default() -> Config {
        Config { inline_fonts: true, remove_new_lines: true }
    }
}

impl std::error::Error for FilePathError {
    fn description(&self) -> &str {
        &match *self {
            FilePathError::InvalidPath(_) => "Invalid path, file not found",
            FilePathError::FileReadError(_, _) => "Error during file reading",
            FilePathError::RepeatedFile => {
                "File is imported twice, or there is a circular dependency"
            }
        }
    }
}

impl std::fmt::Display for FilePathError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match *self {
            FilePathError::InvalidPath(ref line) => write!(f, "Invalid path: {}", line),
            FilePathError::FileReadError(ref cause, ref io_err) => {
                write!(f, "Cause: {}, File read error: {}", cause, io_err)
            }
            FilePathError::RepeatedFile => write!(
                f,
                "A file is imported twice, or there is a circular dependency"
            ),
        }
    }
}

impl FilePathError {
    fn from_elem(e: std::io::Error, elem: &str) -> Self {
        match e.kind() {
            IoErrorKind::NotFound => {
                FilePathError::InvalidPath(format!("File not found: {}", elem))
            }
            _ => FilePathError::FileReadError(elem.to_owned(), e),
        }
    }
}

impl From<std::io::Error> for FilePathError {
    fn from(e: std::io::Error) -> Self {
        match e.kind() {
            IoErrorKind::NotFound => FilePathError::InvalidPath("File not found".to_owned()),
            _ => FilePathError::FileReadError("N/A".to_owned(), e),
        }
    }
}

/// Returns a `Result<String, FilePathError>` of the html file at file path with all the assets inlined.
///
/// ## Arguments
/// * `file_path` - The path of the html file.
/// * `inline_fonts` - Pass a config file to select what features to enable. Use `Default::default()` to enable everything
pub fn inline_file<P: AsRef<Path>>(
    file_path: P,
    config: Config,
) -> Result<String, FilePathError> {
    let html = fs::read_to_string(&file_path)
        .map_err(|orig_err| FilePathError::from_elem(orig_err, "Html file not found"))?;
    inline_html_string(&html, &file_path.as_ref().parent().unwrap(), config)
}

/// Returns a `Result<String, FilePathError>` with all the assets linked in the the html string inlined.
///
/// ## Arguments
/// * `html` - The html string.
/// * `root_path` - The root all relative paths in the html will be evaluated with, usually this is the folder the html file is in.
/// * `config` - Pass a config file to select what features to enable. Use `Default::default()` to enable everything
///
pub fn inline_html_string<P: AsRef<Path>>(
    html: &str,
    root_path: P,
    config: Config,
) -> Result<String, FilePathError> {
    let root_path = root_path.as_ref();

    let link_finder =
        regex::Regex::new(r#"<link[^>]+?href\s*=\s*['"]([^"']+)['"][^>]*?>"#).unwrap(); // Finds css <link href="path"> tags
    let script_finder = regex::Regex::new(
        r#"<script[^>]+?src\s*=\s*['"]([^"']+?)['"][^>]*?>\s*?</\s*?script\s*?>"#).unwrap(); // Finds javascript <script src="path"></script> tags
    let font_url_finder = regex::Regex::new(
        r#"(@font-face[\s]*?\{[^}]*?src:[\s]*?url\()("?[^()'"]+?"?)(\))"#).unwrap(); // Finds @font-face { src: url(path) } in the css

    let new_line_finder = regex::Regex::new(r#"[\r\n]+"#).unwrap();

    let mut is_alright: Result<(), FilePathError> = Ok(());
    let mut css_path_set: HashSet<std::path::PathBuf> = HashSet::new();

    let out_html = link_finder
        .replace_all(html, |caps: &Captures| {
            let css_path = root_path.join(&caps[1]);
            //println!("{:?}", css_path);
            let mut css_data = match inline_css(&css_path, &mut css_path_set) {
                Ok(css_data) => css_data,
                Err(FilePathError::RepeatedFile) => "".to_owned(),
                Err(e) => {
                    is_alright = Err(e);
                    return "Error".to_owned();
                }
            };

            if config.inline_fonts {
                css_data = font_url_finder
                    .replace_all(css_data.as_str(), |caps: &Captures| {
                        let font_path = Path::new(&caps[2]);
                        match fs::read(font_path) {
                            Ok(font_data) => format!(
                                "{before}{font_type}charset=utf-8;base64,{data}{after}",
                                before = &caps[1],
                                font_type = match font_path
                                    .extension().unwrap_or_default()
                                    .to_str().unwrap_or_default()
                                    {
                                        "woff" => "data:application/font-woff;",
                                        "woff2" => "data:application/font-woff2;",
                                        "otf" => "data:font/opentype;",
                                        "ttf" => "data:application/font-ttf;",
                                        _ => "data:application/font-ttf;",
                                    },
                                data = base64::encode(&font_data),
                                after = &caps[3]
                            ),
                            Err(e) => {
                                is_alright = Err(FilePathError::from_elem(e, &caps[0]));
                                return "Error".to_owned();
                            }
                        }
                    })
                    .to_string()
            }

            if config.remove_new_lines {
                css_data = new_line_finder.replace_all(&css_data, " ").to_string();
            }

            format!("<style>{}</style>", css_data)
        })
        .to_string();

    if is_alright.is_err() {
        return Err(is_alright.unwrap_err());
    }

    //     TODO: Support type tags in output
    let out_html = script_finder.replace_all(out_html.as_str(), |caps: &Captures| {
        format!("<script>{}</script>",
                match fs::read_to_string(root_path.join(&caps[1])) {
                    Ok(res) => if config.remove_new_lines { new_line_finder.replace_all(&res, " ").to_string() } else { res },
                    Err(e) => {
                        is_alright = Err(FilePathError::from_elem(e, &caps[0]));
                        return "Error".to_owned();
                    }
                }
        )
    }).to_string();

    if is_alright.is_err() {
        return Err(is_alright.unwrap_err());
    }

    Ok(out_html)
}

fn inline_css<P: AsRef<Path>>(
    css_path: P,
    path_set: &mut HashSet<std::path::PathBuf>,
) -> Result<String, FilePathError> {
    let css_path = css_path.as_ref();
    if !path_set.insert(
        css_path.canonicalize()
            .map_err(|e| FilePathError::from_elem(e, css_path.to_str().unwrap()))?,
    ) {
        return Err(FilePathError::RepeatedFile);
    }

    // Some optimisation could be done here if we don't initialize these every single time.
    let css_finder: regex::Regex =
        regex::Regex::new(r#"@import[\s]+url\(["']?([^"']+)["']?\)\s*;"#).unwrap(); // Finds all @import url(style.css)
    let url_finder = regex::Regex::new(r#"url\s*?\(["']?([^"')]+?)["']?\)"#).unwrap(); // Finds all url(path) in the css and makes them relative to the html file

    let mut is_alright: Result<(), FilePathError> = Ok(());
    let css_data = css_finder
        .replace_all(
            url_finder
                .replace_all(
                    &fs::read_to_string(&css_path)
                        .map_err(|e| FilePathError::from_elem(e, css_path.to_str().unwrap()))?,
                    |caps: &Captures| {
                        if caps[1].len() > 1500 || caps[1].contains("data:") {
                            // Probably not a path if longer than 1500 characters
                            return caps[0].to_owned();
                        }
                        format!(
                            "url({})",
                            if (caps[1].as_ref() as &str).contains("://") {
                                caps[1].to_owned()
                            } else {
                                css_path
                                    .parent()
                                    .unwrap()
                                    .join(&caps[1])
                                    .to_str()
                                    .expect("Path not UTF-8")
                                    .replace("\\", "/")
                            }
                        )
                    },
                )
                .as_ref(),
            |caps: &Captures| {
                match inline_css(&caps[1], path_set) {
                    Ok(out) => out,
                    Err(FilePathError::RepeatedFile) => {
                        "".to_owned() // Ignore repeated file
                    }
                    Err(e) => {
                        is_alright = Err(e);
                        return "Error".to_owned();
                    }
                }
            },
        )
        .to_string();

    if is_alright.is_err() {
        return Err(is_alright.unwrap_err());
    }

    Ok(css_data)
}