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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
extern crate xml;
extern crate regex;
use std::collections::HashMap;
use std::cmp::Ordering;
use failure::Error;
use failure::err_msg;
use std::path::{Component, Path, PathBuf};
use archive::EpubArchive;
use xmlutils;
#[derive(Eq)]
pub struct NavPoint {
pub label: String,
pub content: PathBuf,
pub play_order: usize,
}
impl Ord for NavPoint {
fn cmp(&self, other: &NavPoint) -> Ordering {
self.play_order.cmp(&other.play_order)
}
}
impl PartialOrd for NavPoint {
fn partial_cmp(&self, other: &NavPoint) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for NavPoint {
fn eq(&self, other: &NavPoint) -> bool {
self.play_order == other.play_order
}
}
pub struct EpubDoc {
archive: EpubArchive,
current: usize,
pub spine: Vec<String>,
pub resources: HashMap<String, (PathBuf, String)>,
pub toc: Vec<NavPoint>,
pub metadata: HashMap<String, Vec<String>>,
pub root_base: PathBuf,
pub root_file: PathBuf,
pub extra_css: Vec<String>,
}
impl EpubDoc {
pub fn new<P: AsRef<Path>>(path: P) -> Result<EpubDoc, Error> {
let mut archive = EpubArchive::new(path)?;
let spine: Vec<String> = vec![];
let resources = HashMap::new();
let container = archive.get_container_file()?;
let root_file = get_root_file(container)?;
let base_path = root_file.parent().expect("All files have a parent");
let mut doc = EpubDoc {
archive: archive,
spine: spine,
toc: vec![],
resources: resources,
metadata: HashMap::new(),
root_file: root_file.clone(),
root_base: base_path.to_path_buf(),
current: 0,
extra_css: vec![],
};
doc.fill_resources()?;
Ok(doc)
}
pub fn mdata(&self, name: &str) -> Option<String> {
match self.metadata.get(name) {
Some(v) => v.get(0).cloned(),
None => None
}
}
pub fn get_cover_id(&self) -> Result<String, Error> {
match self.mdata("cover") {
Some(id) => Ok(id.to_string()),
None => Err(format_err!("Cover not found")),
}
}
pub fn get_cover(&mut self) -> Result<Vec<u8>, Error> {
let cover_id = self.get_cover_id()?;
let cover_data = self.get_resource(&cover_id)?;
Ok(cover_data)
}
pub fn get_resource_by_path<P: AsRef<Path>>(&mut self, path: P) -> Result<Vec<u8>, Error> {
let content = self.archive.get_entry(path)?;
Ok(content)
}
pub fn get_resource(&mut self, id: &str) -> Result<Vec<u8>, Error> {
let path = match self.resources.get(id) {
Some(s) => s.0.clone(),
None => return Err(format_err!("id not found")),
};
let content = self.get_resource_by_path(&path)?;
Ok(content)
}
pub fn get_resource_str_by_path<P: AsRef<Path>>(&mut self, path: P) -> Result<String, Error> {
let content = self.archive.get_entry_as_str(path)?;
Ok(content)
}
pub fn get_resource_str(&mut self, id: &str) -> Result<String, Error> {
let path = match self.resources.get(id) {
Some(s) => s.0.clone(),
None => return Err(format_err!("id not found")),
};
let content = self.get_resource_str_by_path(path)?;
Ok(content)
}
pub fn get_resource_mime(&self, id: &str) -> Result<String, Error> {
match self.resources.get(id) {
Some(&(_, ref res)) => return Ok(res.to_string()),
None => {}
}
Err(format_err!("id not found"))
}
pub fn get_resource_mime_by_path<P: AsRef<Path>>(&self, path: P) -> Result<String, Error> {
let path = path.as_ref();
for (_, v) in self.resources.iter() {
if v.0 == path {
return Ok(v.1.to_string());
}
}
Err(format_err!("path not found"))
}
pub fn get_current(&mut self) -> Result<Vec<u8>, Error> {
let current_id = self.get_current_id()?;
self.get_resource(¤t_id)
}
pub fn get_current_str(&mut self) -> Result<String, Error> {
let current_id = self.get_current_id()?;
self.get_resource_str(¤t_id)
}
pub fn get_current_with_epub_uris(&mut self) -> Result<Vec<u8>, Error> {
let path = self.get_current_path()?;
let current = self.get_current()?;
let resp = xmlutils::replace_attrs(current.as_slice(),
|element, attr, value| match (element, attr) {
("link", "href") => build_epub_uri(&path, value),
("img", "src") => build_epub_uri(&path, value),
("image", "href") => build_epub_uri(&path, value),
("a", "href") => build_epub_uri(&path, value),
_ => String::from(value),
}, &self.extra_css);
match resp {
Ok(a) => Ok(a),
Err(error) => Err(format_err!("{}", error.error)),
}
}
pub fn get_current_mime(&self) -> Result<String, Error> {
let current_id = self.get_current_id()?;
self.get_resource_mime(¤t_id)
}
pub fn get_current_path(&self) -> Result<PathBuf, Error> {
let current_id = self.get_current_id()?;
match self.resources.get(¤t_id) {
Some(&(ref p, _)) => return Ok(p.clone()),
None => return Err(format_err!("Current not found")),
}
}
pub fn get_current_id(&self) -> Result<String, Error> {
let current_id = self.spine.get(self.current);
match current_id {
Some(id) => return Ok(id.to_string()),
None => return Err(format_err!("current is broken")),
}
}
pub fn go_next(&mut self) -> Result<(), Error> {
if self.current + 1 >= self.spine.len() {
return Err(format_err!("last page"));
}
self.current += 1;
Ok(())
}
pub fn go_prev(&mut self) -> Result<(), Error> {
if self.current < 1 {
return Err(format_err!("first page"));
}
self.current -= 1;
Ok(())
}
pub fn get_num_pages(&self) -> usize {
self.spine.len()
}
pub fn get_current_page(&self) -> usize {
self.current
}
pub fn set_current_page(&mut self, n: usize) -> Result<(), Error> {
if n >= self.spine.len() {
return Err(format_err!("page not valid"));
}
self.current = n;
Ok(())
}
pub fn add_extra_css(&mut self, css: &str) {
self.extra_css.push(String::from(css));
}
pub fn resource_uri_to_chapter(&self, uri: &PathBuf) -> Option<usize> {
for (k, (path, _mime)) in self.resources.iter() {
if path == uri {
return self.resource_id_to_chapter(&k);
}
}
None
}
pub fn resource_id_to_chapter(&self, uri: &str) -> Option<usize> {
self.spine.iter().position(|item| item == uri)
}
fn fill_resources(&mut self) -> Result<(), Error> {
let container = self.archive.get_entry(&self.root_file)?;
let xml = xmlutils::XMLReader::new(container.as_slice());
let root = xml.parse_xml()?;
let manifest = root.borrow().find("manifest")?;
for r in manifest.borrow().childs.iter() {
let item = r.borrow();
let id = item.get_attr("id")?;
let href = item.get_attr("href")?;
let mtype = item.get_attr("media-type")?;
self.resources
.insert(id, (self.root_base.join(&href), mtype));
}
let spine = root.borrow().find("spine")?;
for r in spine.borrow().childs.iter() {
let item = r.borrow();
let id = item.get_attr("idref")?;
self.spine.push(id);
}
if let Ok(toc) = spine.borrow().get_attr("toc") {
let _ = self.fill_toc(&toc);
}
let metadata = root.borrow().find("metadata")?;
for r in metadata.borrow().childs.iter() {
let item = r.borrow();
if item.name.local_name == "meta" {
if let (Ok(k), Ok(v)) = (item.get_attr("name"), item.get_attr("content")) {
if self.metadata.contains_key(&k) {
if let Some(arr) = self.metadata.get_mut(&k) {
arr.push(v);
}
} else {
self.metadata.insert(k, vec![v]);
}
}
} else {
let ref k = item.name.local_name;
let v = match item.text {
Some(ref x) => x.to_string(),
None => String::from(""),
};
if self.metadata.contains_key(k) {
if let Some(arr) = self.metadata.get_mut(k) {
arr.push(v);
}
} else {
self.metadata.insert(k.to_string(), vec![v]);
}
}
}
Ok(())
}
fn fill_toc(&mut self, id: &str) -> Result<(), Error> {
let toc_res = self.resources.get(id).ok_or(err_msg("No toc found"))?;
let container = self.archive.get_entry(&toc_res.0)?;
let xml = xmlutils::XMLReader::new(container.as_slice());
let root = xml.parse_xml()?;
let mapnode = root.borrow().find("navMap")?;
for nav in mapnode.borrow().childs.iter() {
let item = nav.borrow();
if item.name.local_name != "navPoint" {
continue;
}
let play_order = item.get_attr("playOrder").ok()
.and_then(|n| usize::from_str_radix(&n, 10).ok());
let content = match item.find("content") {
Ok(c) => c.borrow().get_attr("src").ok()
.map(|p| self.root_base.join(p)),
_ => None,
};
let label = match item.find("navLabel") {
Ok(l) => l.borrow()
.childs.iter().next()
.and_then(|t| t.borrow().text.clone()),
_ => None,
};
if let (Some(o), Some(c), Some(l)) = (play_order, content, label) {
let navpoint = NavPoint {
label: l.clone(),
content: c.clone(),
play_order: o,
};
self.toc.push(navpoint);
}
}
self.toc.sort();
Ok(())
}
}
fn get_root_file(container: Vec<u8>) -> Result<PathBuf, Error> {
let xml = xmlutils::XMLReader::new(container.as_slice());
let root = xml.parse_xml()?;
let el = root.borrow();
let element = el.find("rootfile")?;
let el2 = element.borrow();
let attr = el2.get_attr("full-path")?;
Ok(PathBuf::from(attr))
}
fn build_epub_uri<P: AsRef<Path>>(path: P, append: &str) -> String {
if append.starts_with("http") {
return String::from(append);
}
let path = path.as_ref();
let mut cpath = path.to_path_buf();
cpath.pop();
for p in Path::new(append).components() {
match p {
Component::ParentDir => {
cpath.pop();
},
Component::Normal(s) => {
cpath.push(s);
},
_ => {},
};
}
format!("epub://{}", cpath.display())
}