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
extern crate regex;
extern crate base64;
use std::fs;
use std::io::ErrorKind as IoErrorKind;
use std::path::Path;
use regex::Captures;
#[derive(Debug)]
pub enum FilePathError {
InvalidPath(String),
FileReadError(String, std::io::Error),
}
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"
}
}
}
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)
}
}
}
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)
}
}
}
pub fn inline_file<P: AsRef<Path>>(file_path: P, inline_fonts: bool) -> 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(), inline_fonts)
}
pub fn inline_html_string<P: AsRef<Path>>(html: &str, root_path: P, inline_fonts: bool) -> Result<String, FilePathError> {
let root_path = root_path.as_ref();
let link_finder = regex::Regex::new(r#"<link[^>]+?href\s*=\s*['"]([^"']+)['"][^>]*?>"#).unwrap();
let script_finder = regex::Regex::new(r#"<script[^>]+?src\s*=\s*['"]([^"']+?)['"][^>]*?>\s*?</\s*?script\s*?>"#).unwrap();
let font_url_finder = regex::Regex::new(r#"(@font-face[\s]*?\{[^}]*?src:[\s]*?url\()("?[^()'"]+?"?)(\))"#).unwrap();
let url_finder = regex::Regex::new(r#"url\s*?\(([^"')]+?)\)"#).unwrap();
let mut is_alright: Result<(), FilePathError> = Ok(());
let out_html = link_finder.replace_all(html, |caps: &Captures| {
let css_path = root_path.join(&caps[1]);
let css_data = match fs::read_to_string(&css_path) {
Ok(css_data) => url_finder.replace(css_data.as_str(), |caps: &Captures|
format!("url({})", css_path.parent().unwrap().join(&caps[1]).to_str().expect("Path not UTF-8")
.replace("\\", "/"))).to_string(),
Err(e) => {
is_alright = Err(FilePathError::from_elem(e, &caps[0]));
return "Error".to_owned();
}
};
if is_alright.is_err() {
return "".to_owned();
}
let css_data = if inline_fonts {
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()
} else {
css_data
};
format!("<style>{}</style>", css_data)
}).to_string();
if is_alright.is_err() {
return Err(is_alright.unwrap_err());
}
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) => 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)
}