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
extern crate zip;
use std::fs;
use std::path::{Path, PathBuf};
use failure::Error;
use std::io::Read;
pub struct EpubArchive {
zip: zip::ZipArchive<fs::File>,
pub path: PathBuf,
pub files: Vec<String>,
}
impl EpubArchive {
pub fn new<P: AsRef<Path>>(path: P) -> Result<EpubArchive, Error> {
let path = path.as_ref();
let file = fs::File::open(path)?;
let mut zip = zip::ZipArchive::new(file)?;
let mut files = vec![];
for i in 0..(zip.len()) {
let file = zip.by_index(i)?;
files.push(String::from(file.name()));
}
Ok(EpubArchive {
zip: zip,
path: path.to_path_buf(),
files: files,
})
}
pub fn get_entry<P: AsRef<Path>>(&mut self, name: P) -> Result<Vec<u8>, Error> {
let mut entry: Vec<u8> = vec![];
let name = name.as_ref().display().to_string();
let mut zipfile = self.zip.by_name(&name)?;
zipfile.read_to_end(&mut entry)?;
Ok(entry)
}
pub fn get_entry_as_str<P: AsRef<Path>>(&mut self, name: P) -> Result<String, Error> {
let content = self.get_entry(name)?;
String::from_utf8(content).map_err(Error::from)
}
pub fn get_container_file(&mut self) -> Result<Vec<u8>, Error> {
let content = self.get_entry("META-INF/container.xml")?;
Ok(content)
}
}