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
//! Manages the epub doc.
//!
//! Provides easy methods to navigate througth the epub content, cover,
//! chapters, etc.

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;


/// Struct that represent a navigation point in a table of content
#[derive(Eq)]
pub struct NavPoint {
    /// the title of this navpoint
    pub label: String,
    /// the resource path
    pub content: PathBuf,
    /// the order in the toc
    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
    }
}


/// Struct to control the epub document
pub struct EpubDoc {
    /// the zip archive
    archive: EpubArchive,

    /// The current chapter, is an spine index
    current: usize,

    /// epub spine ids
    pub spine: Vec<String>,

    /// resource id -> (path, mime)
    pub resources: HashMap<String, (PathBuf, String)>,

    /// table of content, list of `NavPoint` in the toc.ncx
    pub toc: Vec<NavPoint>,

    /// The epub metadata stored as key -> value
    ///
    /// #Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let title = doc.metadata.get("title");
    /// assert_eq!(title.unwrap(), &vec!["Todo es mío".to_string()]);
    /// ```
    pub metadata: HashMap<String, Vec<String>>,

    /// root file base path
    pub root_base: PathBuf,

    /// root file full path
    pub root_file: PathBuf,

    /// Custom css list to inject in every xhtml file
    pub extra_css: Vec<String>,
}

impl EpubDoc {
    /// Opens the epub file in `path`.
    ///
    /// Initialize some internal variables to be able to access to the epub
    /// spine definition and to navigate trhough the epub.
    ///
    /// # Examples
    ///
    /// ```
    /// use epub::doc::EpubDoc;
    ///
    /// let doc = EpubDoc::new("test.epub");
    /// assert!(doc.is_ok());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the epub is broken or if the file doesn't
    /// exists.
    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)
    }

    /// Returns the first metadata found with this name.
    ///
    /// #Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let title = doc.mdata("title");
    /// assert_eq!(title.unwrap(), "Todo es mío");
    pub fn mdata(&self, name: &str) -> Option<String> {
        match self.metadata.get(name) {
            Some(v) => v.get(0).cloned(),
            None => None
        }
    }

    /// Returns the id of the epub cover.
    ///
    /// The cover is searched in the doc metadata, by the tag <meta name="cover" value"..">
    ///
    /// # Examples
    ///
    /// ```rust
    /// use epub::doc::EpubDoc;
    ///
    /// let doc = EpubDoc::new("test.epub");
    /// assert!(doc.is_ok());
    /// let mut doc = doc.unwrap();
    ///
    /// let cover_id = doc.get_cover_id().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the cover path can't be found.
    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")),
        }
    }

    /// Returns the cover as Vec<u8>
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use std::fs;
    /// use std::io::Write;
    /// use epub::doc::EpubDoc;
    ///
    /// let doc = EpubDoc::new("test.epub");
    /// assert!(doc.is_ok());
    /// let mut doc = doc.unwrap();
    ///
    /// let cover_data = doc.get_cover().unwrap();
    ///
    /// let f = fs::File::create("/tmp/cover.png");
    /// assert!(f.is_ok());
    /// let mut f = f.unwrap();
    /// let resp = f.write_all(&cover_data);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the cover can't be 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)
    }

    /// Returns the resource content by full path in the epub archive
    ///
    /// # Errors
    ///
    /// Returns an error if the path doesn't exists in the epub
    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)
    }

    /// Returns the resource content by the id defined in the spine
    ///
    /// # Errors
    ///
    /// Returns an error if the id doesn't exists in the epub
    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)
    }

    /// Returns the resource content by full path in the epub archive, as String
    ///
    /// # Errors
    ///
    /// Returns an error if the path doesn't exists in the epub
    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)
    }

    /// Returns the resource content by the id defined in the spine, as String
    ///
    /// # Errors
    ///
    /// Returns an error if the id doesn't exists in the epub
    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)
    }

    /// Returns the resource mime-type
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let mime = doc.get_resource_mime("portada.png");
    /// assert_eq!("image/png", mime.unwrap());
    /// ```
    /// # Errors
    ///
    /// Fails if the resource can't be found.
    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"))
    }

    /// Returns the resource mime searching by source full path
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let mime = doc.get_resource_mime_by_path("OEBPS/Images/portada.png");
    /// assert_eq!("image/png", mime.unwrap());
    /// ```
    ///
    /// # Errors
    ///
    /// Fails if the resource can't be 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"))
    }

    /// Returns the current chapter content
    ///
    /// The current follows the epub spine order. You can modify the current
    /// calling to `go_next`, `go_prev` or `set_current` methods.
    ///
    /// # Errors
    ///
    /// This call shouldn't fail, but can return an error if the epub doc is
    /// broken.
    pub fn get_current(&mut self) -> Result<Vec<u8>, Error> {
        let current_id = self.get_current_id()?;
        self.get_resource(&current_id)
    }

    pub fn get_current_str(&mut self) -> Result<String, Error> {
        let current_id = self.get_current_id()?;
        self.get_resource_str(&current_id)
    }


    /// Returns the current chapter data, with resource uris renamed so they
    /// have the epub:// prefix and all are relative to the root file
    ///
    /// This method is useful to render the content with a html engine, because inside the epub
    /// local paths are relatives, so you can provide that content, because the engine will look
    /// for the relative path in the filesystem and that file isn't there. You should provide files
    /// with epub:// using the get_resource_by_path
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let mut doc = EpubDoc::new("test.epub").unwrap();
    /// let current = doc.get_current_with_epub_uris().unwrap();
    /// let text = String::from_utf8(current).unwrap();
    /// assert!(text.contains("epub://OEBPS/Images/portada.png"));

    /// doc.go_next();
    /// let current = doc.get_current_with_epub_uris().unwrap();
    /// let text = String::from_utf8(current).unwrap();
    /// assert!(text.contains("epub://OEBPS/Styles/stylesheet.css"));
    /// assert!(text.contains("http://creativecommons.org/licenses/by-sa/3.0/"));
    /// ```
    ///
    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)),
        }
    }

    /// Returns the current chapter mimetype
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let m = doc.get_current_mime();
    /// assert_eq!("application/xhtml+xml", m.unwrap());
    /// ```
    pub fn get_current_mime(&self) -> Result<String, Error> {
        let current_id = self.get_current_id()?;
        self.get_resource_mime(&current_id)
    }

    /// Returns the current chapter full path
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # use std::path::Path;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let p = doc.get_current_path();
    /// assert_eq!(Path::new("OEBPS/Text/titlepage.xhtml"), p.unwrap());
    /// ```
    pub fn get_current_path(&self) -> Result<PathBuf, Error> {
        let current_id = self.get_current_id()?;
        match self.resources.get(&current_id) {
            Some(&(ref p, _)) => return Ok(p.clone()),
            None => return Err(format_err!("Current not found")),
        }
    }

    /// Returns the current chapter id
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let doc = doc.unwrap();
    /// let id = doc.get_current_id();
    /// assert_eq!("titlepage.xhtml", id.unwrap());
    /// ```
    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")),
        }
    }

    /// Changes current to the next chapter
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let mut doc = doc.unwrap();
    /// doc.go_next();
    /// assert_eq!("000.xhtml", doc.get_current_id().unwrap());
    ///
    /// let len = doc.spine.len();
    /// for i in 1..len {
    ///     doc.go_next();
    /// }
    /// assert!(doc.go_next().is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// If the page is the last, will not change and an error will be returned
    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(())
    }

    /// Changes current to the prev chapter
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let mut doc = doc.unwrap();
    /// assert!(doc.go_prev().is_err());
    ///
    /// doc.go_next(); // 000.xhtml
    /// doc.go_next(); // 001.xhtml
    /// doc.go_next(); // 002.xhtml
    /// doc.go_prev(); // 001.xhtml
    /// assert_eq!("001.xhtml", doc.get_current_id().unwrap());
    /// ```
    ///
    /// # Errors
    ///
    /// If the page is the first, will not change and an error will be returned
    pub fn go_prev(&mut self) -> Result<(), Error> {
        if self.current < 1 {
            return Err(format_err!("first page"));
        }
        self.current -= 1;
        Ok(())
    }

    /// Returns the number of chapters
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let mut doc = doc.unwrap();
    /// assert_eq!(17, doc.get_num_pages());
    /// ```
    pub fn get_num_pages(&self) -> usize {
        self.spine.len()
    }

    /// Returns the current chapter number, starting from 0
    pub fn get_current_page(&self) -> usize {
        self.current
    }

    /// Changes the current page
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let mut doc = doc.unwrap();
    /// assert_eq!(0, doc.get_current_page());
    /// doc.set_current_page(2);
    /// assert_eq!("001.xhtml", doc.get_current_id().unwrap());
    /// assert_eq!(2, doc.get_current_page());
    /// assert!(doc.set_current_page(50).is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// If the page isn't valid, will not change and an error will be returned
    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(())
    }

    /// This will inject this css in every html page getted with the
    /// get_current_with_epub_uris call
    ///
    /// # Examples
    ///
    /// ```
    /// # use epub::doc::EpubDoc;
    /// # let doc = EpubDoc::new("test.epub");
    /// # let mut doc = doc.unwrap();
    /// # let _ = doc.set_current_page(2);
    /// let extracss = "body { background-color: black; color: white }";
    /// doc.add_extra_css(extracss);
    /// let current = doc.get_current_with_epub_uris().unwrap();
    /// let text = String::from_utf8(current).unwrap();
    /// assert!(text.contains(extracss));
    /// ```
    pub fn add_extra_css(&mut self, css: &str) {
        self.extra_css.push(String::from(css));
    }

    /// Function to convert a resource path to a chapter number in the spine
    /// If the resourse isn't in the spine list, None will be returned
    ///
    /// This method is useful to convert a toc NavPoint content to a chapter number
    /// to be able to navigate easily
    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
    }

    /// Function to convert a resource id to a chapter number in the spine
    /// If the resourse isn't in the spine list, None will be returned
    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()?;

        // resources from manifest
        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));
        }

        // items from spine
        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);
        }

        // toc.ncx
        if let Ok(toc) = spine.borrow().get_attr("toc") {
            let _ = self.fill_toc(&toc);
        }

        // metadata
        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")?;

        // TODO: get docTitle
        // TODO: parse metadata (dtb:totalPageCount, dtb:depth, dtb:maxPageNumber)

        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 {
    // allowing external links
    if append.starts_with("http") {
        return String::from(append);
    }

    let path = path.as_ref();
    let mut cpath = path.to_path_buf();

    // current file base dir
    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())
}