aboutsummaryrefslogtreecommitdiffstats
path: root/src/epub.rs
blob: 795f4d12625df2779bd0262e1e2f55d1c735f013 (plain)
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
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;

use roxmltree::{Document, Node};

pub struct Epub {
    container: zip::ZipArchive<File>,
    pub chapters: Vec<(String, String)>,
}

impl Epub {
    pub fn new(path: &str) -> std::io::Result<Self> {
        let file = File::open(path)?;
        let mut epub = Epub {
            container: zip::ZipArchive::new(file)?,
            chapters: Vec::new(),
        };
        epub.chapters = epub
            .get_nav()
            .into_iter()
            .filter_map(|(path, title)| {
                let xml = epub.get_text(&path);
                // https://github.com/RazrFalcon/roxmltree/issues/12
                // UnknownEntityReference for HTML entities
                let doc = Document::parse(&xml).unwrap();
                let body = doc.root_element().last_element_child().unwrap();
                let mut chapter = String::new();
                Epub::render(&mut chapter, body);
                if chapter.is_empty() {
                    None
                } else {
                    Some((title, chapter))
                }
            })
            .collect();
        Ok(epub)
    }
    fn render(buf: &mut String, n: Node) {
        if n.is_text() {
            let text = n.text().unwrap();
            if !text.trim().is_empty() {
                buf.push_str(text);
            }
            return;
        }

        match n.tag_name().name() {
            "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
                buf.push_str("\n\x1b\x5b1m");
                for c in n.children() {
                    Self::render(buf, c);
                }
                buf.push_str("\x1b\x5b0m\n");
            }
            "blockquote" | "p" => {
                buf.push('\n');
                for c in n.children() {
                    Self::render(buf, c);
                }
                buf.push('\n');
            }
            "li" => {
                buf.push_str("\n- ");
                for c in n.children() {
                    Self::render(buf, c);
                }
                buf.push('\n');
            }
            "br" => buf.push('\n'),
            _ => {
                for c in n.children() {
                    Self::render(buf, c);
                }
            }
        }
    }
    fn get_text(&mut self, name: &str) -> String {
        let mut text = String::new();
        self.container
            .by_name(name)
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        text
    }
    fn get_nav(&mut self) -> Vec<(String, String)> {
        let xml = self.get_text("META-INF/container.xml");
        let doc = Document::parse(&xml).unwrap();
        let path = doc
            .descendants()
            .find(|n| n.has_tag_name("rootfile"))
            .unwrap()
            .attribute("full-path")
            .unwrap();

        let xml = self.get_text(path);
        let doc = Document::parse(&xml).unwrap();
        // zip expects unix path even on windows
        let rootdir = match path.rfind('/') {
            Some(n) => &path[..n + 1],
            None => "",
        };

        let mut manifest = HashMap::new();
        doc.root_element()
            .children()
            .find(|n| n.has_tag_name("manifest"))
            .unwrap()
            .children()
            .filter(Node::is_element)
            .for_each(|n| {
                manifest.insert(n.attribute("id").unwrap(), n.attribute("href").unwrap());
            });

        let mut nav = HashMap::new();
        if doc.root_element().attribute("version") == Some("3.0") {
            let path = doc
                .root_element()
                .children()
                .find(|n| n.has_tag_name("manifest"))
                .unwrap()
                .children()
                .find(|n| n.attribute("properties") == Some("nav"))
                .unwrap()
                .attribute("href")
                .unwrap();
            let xml = self.get_text(&format!("{}{}", rootdir, path));
            let doc = Document::parse(&xml).unwrap();

            doc.descendants()
                .find(|n| n.has_tag_name("nav"))
                .unwrap()
                .descendants()
                .filter(|n| n.has_tag_name("a"))
                .for_each(|n| {
                    let path = n.attribute("href").unwrap().to_string();
                    let text = n
                        .descendants()
                        .filter(Node::is_text)
                        .map(|n| n.text().unwrap())
                        .collect();
                    nav.insert(path, text);
                })
        } else {
            let path = manifest.get("ncx").unwrap();
            let xml = self.get_text(&format!("{}{}", rootdir, path));
            let doc = Document::parse(&xml).unwrap();

            doc.descendants()
                .find(|n| n.has_tag_name("navMap"))
                .unwrap()
                .descendants()
                .filter(|n| n.has_tag_name("navPoint"))
                .for_each(|n| {
                    let path = n
                        .descendants()
                        .find(|n| n.has_tag_name("content"))
                        .unwrap()
                        .attribute("src")
                        .unwrap()
                        .to_string();
                    let text = n
                        .descendants()
                        .find(|n| n.has_tag_name("text"))
                        .unwrap()
                        .text()
                        .unwrap()
                        .to_string();
                    nav.insert(path, text);
                })
        }

        doc.root_element()
            .children()
            .find(|n| n.has_tag_name("spine"))
            .unwrap()
            .children()
            .filter(Node::is_element)
            .enumerate()
            .map(|(i, n)| {
                let id = n.attribute("idref").unwrap();
                let path = manifest.remove(id).unwrap();
                let label = nav.remove(path).unwrap_or_else(|| i.to_string());
                let path = format!("{}{}", rootdir, path);
                (path, label)
            })
            .collect()
    }
}

#[test]
fn test_dir() {
    let path = "/mnt/lit/read";
    for entry in std::fs::read_dir(path).unwrap() {
        let path = entry.unwrap().path();
        let s = path.to_str().unwrap();
        println!("testing: {}", s);
        Epub::new(s).unwrap();
    }
}