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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use templates;
use errors::Result;
use errors::ResultExt;
use zip::Zip;
use toc::Toc;
use toc::TocElement;
use epub_content::EpubContent;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use chrono;
use uuid;
use mustache::MapBuilder;
#[derive(Debug, Copy, Clone)]
pub enum EpubVersion {
V20,
V30,
#[doc(hidden)]
__NonExhaustive,
}
#[derive(Debug)]
struct Metadata {
pub title: String,
pub author: String,
pub lang: String,
pub generator: String,
pub toc_name: String,
pub description: Option<String>,
pub subject: Option<String>,
pub license: Option<String>,
}
impl Metadata {
pub fn new() -> Metadata {
Metadata {
title: String::new(),
author: String::new(),
lang: String::from("en"),
generator: String::from("Rust EPUB library"),
toc_name: String::from("Table Of Contents"),
description: None,
subject: None,
license: None,
}
}
}
#[derive(Debug)]
struct Content {
pub file: String,
pub mime: String,
pub itemref: bool,
}
impl Content {
pub fn new<S1:Into<String>, S2: Into<String>>(file: S1, mime: S2) -> Content {
Content {
file: file.into(),
mime: mime.into(),
itemref: false,
}
}
}
#[derive(Debug)]
pub struct EpubBuilder<Z:Zip> {
version: EpubVersion,
zip: Z,
files: Vec<Content>,
metadata: Metadata,
toc: Toc,
stylesheet: bool,
inline_toc: bool,
}
impl<Z:Zip> EpubBuilder<Z> {
pub fn new(zip: Z) -> Result<EpubBuilder<Z>> {
let mut epub = EpubBuilder {
version: EpubVersion::V20,
zip: zip,
files: vec!(),
metadata: Metadata::new(),
toc: Toc::new(),
stylesheet: false,
inline_toc: false,
};
epub.zip.write_file("mimetype", "application/epub+zip".as_bytes())?;
epub.zip.write_file("META-INF/container.xml", templates::CONTAINER)?;
epub.zip.write_file("META-INF/com.apple.ibooks.display-options.xml", templates::IBOOKS)?;
Ok(epub)
}
pub fn epub_version(&mut self, version: EpubVersion) -> &mut Self {
self.version = version;
self
}
pub fn metadata<S1: AsRef<str>, S2: Into<String>>(&mut self, key: S1, value: S2) -> Result<&mut Self> {
match key.as_ref() {
"author" => self.metadata.author = value.into(),
"title" => self.metadata.title = value.into(),
"lang" => self.metadata.lang = value.into(),
"generator" => self.metadata.generator = value.into(),
"description" => self.metadata.description = Some(value.into()),
"subject" => self.metadata.subject = Some(value.into()),
"license" => self.metadata.license = Some(value.into()),
"toc_name" => self.metadata.toc_name = value.into(),
s => bail!("invalid metadata '{}'", s),
}
Ok(self)
}
pub fn stylesheet<R:Read>(&mut self, content: R) -> Result<&mut Self> {
self.add_resource("stylesheet.css", content, "text/css")?;
self.stylesheet = true;
Ok(self)
}
pub fn inline_toc(&mut self) -> &mut Self {
self.inline_toc = true;
self.toc.add(TocElement::new("toc.xhtml", self.metadata.toc_name.as_ref()));
let mut file = Content::new("toc.xhtml", "application/xhtml+xml");
file.itemref = true;
self.files.push(file);
self
}
pub fn add_resource<R: Read, P: AsRef<Path>, S: Into<String>>(&mut self,
path: P,
content: R,
mime_type: S) -> Result<&mut Self> {
self.zip.write_file(Path::new("OEBPS").join(path.as_ref()), content)?;
self.files.push(Content::new(format!("{}", path.as_ref().display()), mime_type));
Ok(self)
}
pub fn add_content<R: Read>(&mut self, content: EpubContent<R>)-> Result<&mut Self> {
self.zip.write_file(Path::new("OEBPS").join(content.toc.url.as_str()),
content.content)?;
let mut file = Content::new(content.toc.url.as_ref(),
"application/xhtml+xml");
file.itemref = true;
self.files.push(file);
if !content.toc.title.is_empty() {
self.toc.add(content.toc);
}
Ok(self)
}
pub fn generate<W: Write>(&mut self, to: W) -> Result<()> {
if !self.stylesheet {
self.stylesheet("".as_bytes())?;
}
let bytes = self.render_opf()?;
self.zip.write_file("OEBPS/content.opf", &bytes as &[u8])?;
let bytes = self.render_toc()?;
self.zip.write_file("OEBPS/toc.ncx", &bytes as &[u8])?;
let bytes = self.render_nav(true)?;
self.zip.write_file("OEBPS/nav.xhtml", &bytes as &[u8])?;
if self.inline_toc {
let bytes = self.render_nav(false)?;
self.zip.write_file("OEBPS/toc.xhtml", &bytes as &[u8])?;
}
self.zip.generate(to)?;
Ok(())
}
fn render_opf(&mut self) -> Result<Vec<u8>> {
let mut optional = String::new();
if let Some(ref desc) = self.metadata.description {
optional.push_str(&format!("<dc:description>{}</dc:description>\n", desc));
}
if let Some(ref subject) = self.metadata.subject {
optional.push_str(&format!("<dc:subject>{}</dc:subject>\n", subject));
}
if let Some(ref rights) = self.metadata.license {
optional.push_str(&format!("<dc:rights>{}</dc:rights>\n", rights));
}
let date = chrono::UTC::now().format("%Y-%m-%dT%H:%M:%SZ");
let uuid = uuid::Uuid::new_v4().urn().to_string();
let mut items = String::new();
let mut itemrefs = String::new();
for content in self.files.iter() {
items.push_str(&format!("<item media-type = \"{mime}\" \
id = \"{id}\" \
href = \"{href}\" />\n",
mime = content.mime,
id = to_id(&content.file),
href = content.file));
if content.itemref {
itemrefs.push_str(&format!("<itemref idref = \"{id}\" />\n",
id = to_id(&content.file)));
}
}
let data = MapBuilder::new()
.insert_str("lang", &self.metadata.lang)
.insert_str("author", &self.metadata.author)
.insert_str("title", &self.metadata.title)
.insert_str("generator", &self.metadata.generator)
.insert_str("optional", optional)
.insert_str("items", items)
.insert_str("itemrefs", itemrefs)
.insert_str("date", date)
.insert_str("uuid", uuid)
.build();
let mut content = vec!();
let res = match self.version {
EpubVersion::V20 => templates::v2::CONTENT_OPF.render_data(&mut content, &data),
EpubVersion::V30 => templates::v3::CONTENT_OPF.render_data(&mut content, &data),
EpubVersion::__NonExhaustive => unreachable!(),
};
res
.chain_err(|| "could not render template for content.opf")?;
Ok(content)
}
fn render_toc(&mut self) -> Result<Vec<u8>> {
let mut nav_points = String::new();
nav_points.push_str(&self.toc.render_epub());
let data = MapBuilder::new()
.insert_str("toc_name", &self.metadata.toc_name)
.insert_str("nav_points", nav_points)
.build();
let mut res: Vec<u8> = vec![];
templates::TOC_NCX.render_data(&mut res, &data)
.chain_err(|| "error rendering toc.ncx template")?;
Ok(res)
}
fn render_nav(&mut self, numbered: bool) -> Result<Vec<u8>> {
let content = self.toc.render(numbered);
let data = MapBuilder::new()
.insert_str("content", content)
.insert_str("toc_name", &self.metadata.toc_name)
.insert_str("generator", &self.metadata.generator)
.build();
let mut res = vec!();
let eh = match self.version {
EpubVersion::V20 => templates::v2::NAV_XHTML.render_data(&mut res, &data),
EpubVersion::V30 => templates::v3::NAV_XHTML.render_data(&mut res, &data),
EpubVersion::__NonExhaustive => unreachable!(),
};
eh.chain_err(|| "error rendering nav.xhtml template")?;
Ok(res)
}
}
fn to_id(s: &str) -> String {
s.replace(".", "_").replace("/", "_")
}