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
use std::path::{PathBuf, Path};
use std::io::{self, Write};
use self::super::Error;
use url::Url;
use reqwest;
pub static CONTAINER: &'static str = include_str!("../assets/container.xml");
pub static MIME_TYPE: &'static str = "application/epub+zip";
pub static CONTENT_TABLE_HEADER: &'static str = include_str!("../assets/content.opf.header");
pub fn uppercase_first(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
pub fn xhtml_path_id<P: AsRef<Path>>(p: P) -> String {
book_filename(p).to_string_lossy().replace('.', "_")
}
pub fn book_filename<P: AsRef<Path>>(p: P) -> PathBuf {
p.as_ref()
.to_string_lossy()
.replace('\u{FFFD}', "")
.replace('\\', "/")
.replace("../", "")
.replace("./", "")
.replace('/', "-")
.into()
}
pub fn xhtml_url_id(url: &Url) -> String {
url.path_segments().unwrap().last().unwrap().replace('.', "_")
}
pub fn write_string_content<W: Write>(to: &mut W, ctnt: &str) -> Result<(), Error> {
fn e(more: &'static str) -> Error {
Error::Io {
desc: "string content",
op: "write",
more: Some(more),
}
}
try!(writeln!(to, r#"<html xmlns="http://www.w3.org/1999/xhtml">"#).map_err(|_| e("string content html start")));
try!(writeln!(to, r#" <head></head>"#).map_err(|_| e("string content head start end")));
try!(writeln!(to, r#" <body>"#).map_err(|_| e("string content body start")));
try!(writeln!(to, r#" {}"#, ctnt).map_err(|_| e("string content string")));
try!(writeln!(to, r#" </body>"#).map_err(|_| e("string content body end")));
try!(writeln!(to, r#"</html>"#).map_err(|_| e("string content html end")));
Ok(())
}
pub fn download_to<W: Write>(w: &mut W, what: &Url) -> Result<(), Error> {
let mut resp = try!(reqwest::get(what.as_str()).map_err(|_| {
Error::Io {
desc: "network content",
op: "request",
more: None,
}
}));
if !resp.status().is_success() {
Err(Error::Io {
desc: "network content",
op: "inspect",
more: resp.status().canonical_reason(),
})
} else {
try!(io::copy(&mut resp, w).map_err(|_| {
Error::Io {
desc: "network content",
op: "read",
more: None,
}
}));
Ok(())
}
}