deepdoc_core/extract/
epub.rs1use std::path::Path;
9
10use crate::detect::{Format, Sniff};
11use crate::error::{Error, Result};
12use crate::extract::container::Container;
13use crate::extract::xml::{self, Element};
14use crate::extract::{ExtractOpts, Extractor, html};
15use crate::model::{Block, Document, Inline, Metadata};
16
17pub struct EpubExtractor;
18
19impl Extractor for EpubExtractor {
20 fn name(&self) -> &'static str {
21 "epub"
22 }
23
24 fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
25 crate::detect::detect(sniff) == Some(Format::Epub)
26 }
27
28 fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
29 let mut container = Container::open(path)?;
30 let parse_error = |message: String| Error::parse(path, message);
31
32 let container_xml = container
33 .read("META-INF/container.xml")
34 .map_err(parse_error)?;
35 let package_path = root_file(&container_xml).map_err(parse_error)?;
36
37 let package_xml = container.read(&package_path).map_err(parse_error)?;
38 let package = Package::parse(&package_xml).map_err(parse_error)?;
39
40 let base = directory_of(&package_path);
41 let mut blocks = Vec::new();
42 for href in &package.spine {
43 let entry = resolve(&base, href);
44 let Some(source) = container.read_optional(&entry) else {
45 continue;
48 };
49 blocks.extend(chapter(&source));
50 }
51
52 let mut meta = package.meta;
53 meta.source_format = Some(Format::Epub);
54 meta.source_path = Some(path.display().to_string());
55
56 Ok(Document { meta, blocks })
57 }
58}
59
60fn chapter(source: &str) -> Vec<Block> {
62 let parsed = html::parse(source);
63 let mut blocks = parsed.blocks;
64
65 if blocks.is_empty() {
66 return blocks;
67 }
68 if !matches!(blocks.first(), Some(Block::Heading { .. }))
71 && let Some(title) = parsed.title.filter(|title| !title.trim().is_empty())
72 {
73 blocks.insert(
74 0,
75 Block::Heading {
76 level: 1,
77 text: Inline::text(title.trim()),
78 },
79 );
80 }
81
82 blocks
83}
84
85#[derive(Debug, Default, PartialEq)]
87pub struct Package {
88 pub meta: Metadata,
89 pub spine: Vec<String>,
91}
92
93impl Package {
94 pub fn parse(source: &str) -> std::result::Result<Package, String> {
96 let root = xml::parse(source)?;
97
98 let meta = root
99 .child("metadata")
100 .map(package_metadata)
101 .unwrap_or_default();
102
103 let manifest = root.child("manifest");
105 let items: Vec<(&str, &str)> = manifest
106 .map(|manifest| {
107 manifest
108 .find_all("item")
109 .into_iter()
110 .filter_map(|item| Some((item.attr("id")?, item.attr("href")?)))
111 .collect()
112 })
113 .unwrap_or_default();
114
115 let spine = root
116 .child("spine")
117 .map(|spine| {
118 spine
119 .find_all("itemref")
120 .into_iter()
121 .filter(|item| item.attr("linear") != Some("no"))
122 .filter_map(|item| {
123 let idref = item.attr("idref")?;
124 items
125 .iter()
126 .find(|(id, _)| *id == idref)
127 .map(|(_, href)| (*href).to_string())
128 })
129 .collect()
130 })
131 .unwrap_or_default();
132
133 Ok(Package { meta, spine })
134 }
135}
136
137fn package_metadata(metadata: &Element) -> Metadata {
138 let text_of = |name: &str| {
139 metadata
140 .find(name)
141 .map(|element| element.text().trim().to_string())
142 .filter(|text| !text.is_empty())
143 };
144
145 Metadata {
146 title: text_of("title"),
147 author: text_of("creator"),
148 created: text_of("date"),
149 language: text_of("language"),
150 publisher: text_of("publisher"),
151 ..Metadata::default()
152 }
153}
154
155fn root_file(container_xml: &str) -> std::result::Result<String, String> {
157 let root = xml::parse(container_xml)?;
158 root.find_all("rootfile")
159 .into_iter()
160 .find_map(|rootfile| rootfile.attr("full-path"))
161 .map(str::to_string)
162 .ok_or_else(|| "container.xml names no rootfile".to_string())
163}
164
165fn directory_of(path: &str) -> String {
167 match path.rfind('/') {
168 Some(index) => path[..=index].to_string(),
169 None => String::new(),
170 }
171}
172
173fn resolve(base: &str, href: &str) -> String {
178 let href = href.split(['#', '?']).next().unwrap_or(href);
179 let joined = format!("{base}{}", percent_decode(href));
180
181 let mut parts: Vec<&str> = Vec::new();
182 for part in joined.split('/') {
183 match part {
184 "." | "" => {}
185 ".." => {
186 parts.pop();
187 }
188 part => parts.push(part),
189 }
190 }
191 parts.join("/")
192}
193
194fn percent_decode(text: &str) -> String {
195 let bytes = text.as_bytes();
196 let mut out = Vec::with_capacity(bytes.len());
197
198 let mut index = 0;
199 while index < bytes.len() {
200 if bytes[index] == b'%' && index + 2 < bytes.len() {
201 let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).unwrap_or("");
202 if let Ok(byte) = u8::from_str_radix(hex, 16) {
203 out.push(byte);
204 index += 3;
205 continue;
206 }
207 }
208 out.push(bytes[index]);
209 index += 1;
210 }
211
212 String::from_utf8_lossy(&out).into_owned()
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 const PACKAGE: &str = r#"<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
220 <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
221 <dc:title>A Short Book</dc:title>
222 <dc:creator>Ada Lovelace</dc:creator>
223 <dc:language>en-GB</dc:language>
224 <dc:publisher>DeepLab Press</dc:publisher>
225 <dc:date>2026-07-24</dc:date>
226 </metadata>
227 <manifest>
228 <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml"/>
229 <item id="c1" href="text/chapter1.xhtml" media-type="application/xhtml+xml"/>
230 <item id="c2" href="text/chapter2.xhtml" media-type="application/xhtml+xml"/>
231 <item id="css" href="style.css" media-type="text/css"/>
232 </manifest>
233 <spine>
234 <itemref idref="nav" linear="no"/>
235 <itemref idref="c2"/>
236 <itemref idref="c1"/>
237 </spine>
238 </package>"#;
239
240 #[test]
241 fn reads_metadata_from_the_package() {
242 let package = Package::parse(PACKAGE).unwrap();
243 assert_eq!(package.meta.title.as_deref(), Some("A Short Book"));
244 assert_eq!(package.meta.author.as_deref(), Some("Ada Lovelace"));
245 assert_eq!(package.meta.language.as_deref(), Some("en-GB"));
246 assert_eq!(package.meta.publisher.as_deref(), Some("DeepLab Press"));
247 assert_eq!(package.meta.created.as_deref(), Some("2026-07-24"));
248 }
249
250 #[test]
251 fn the_spine_sets_the_order_not_the_manifest() {
252 let package = Package::parse(PACKAGE).unwrap();
253 assert_eq!(
254 package.spine,
255 vec!["text/chapter2.xhtml", "text/chapter1.xhtml"],
256 "non-linear items are skipped and the spine order wins"
257 );
258 }
259
260 #[test]
261 fn finds_the_package_document() {
262 let container = r#"<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
263 <rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>
264 </container>"#;
265 assert_eq!(root_file(container).unwrap(), "OEBPS/content.opf");
266 assert!(root_file("<container/>").is_err());
267 }
268
269 #[test]
270 fn hrefs_resolve_against_the_package_directory() {
271 assert_eq!(resolve("OEBPS/", "text/ch1.xhtml"), "OEBPS/text/ch1.xhtml");
272 assert_eq!(resolve("OEBPS/", "ch1.xhtml#part2"), "OEBPS/ch1.xhtml");
273 assert_eq!(resolve("OEBPS/text/", "../ch1.xhtml"), "OEBPS/ch1.xhtml");
274 assert_eq!(
275 resolve("OEBPS/", "my%20chapter.xhtml"),
276 "OEBPS/my chapter.xhtml"
277 );
278 assert_eq!(resolve("", "ch1.xhtml"), "ch1.xhtml");
279 }
280
281 #[test]
282 fn directory_of_a_package_path() {
283 assert_eq!(directory_of("OEBPS/content.opf"), "OEBPS/");
284 assert_eq!(directory_of("content.opf"), "");
285 }
286
287 #[test]
288 fn a_chapter_without_a_heading_gets_one_from_its_title() {
289 let blocks =
290 chapter("<html><head><title>Chapter One</title></head><body><p>text</p></body></html>");
291 assert_eq!(
292 blocks,
293 vec![
294 Block::Heading {
295 level: 1,
296 text: Inline::text("Chapter One")
297 },
298 Block::paragraph("text"),
299 ]
300 );
301 }
302
303 #[test]
304 fn a_chapter_that_has_a_heading_keeps_it() {
305 let blocks = chapter(
306 "<html><head><title>Chapter One</title></head><body><h1>The Beginning</h1><p>text</p></body></html>",
307 );
308 assert_eq!(
309 blocks,
310 vec![
311 Block::Heading {
312 level: 1,
313 text: Inline::text("The Beginning")
314 },
315 Block::paragraph("text"),
316 ]
317 );
318 }
319
320 #[test]
321 fn an_empty_chapter_adds_nothing() {
322 assert!(chapter("<html><head><title>Blank</title></head><body></body></html>").is_empty());
323 }
324
325 #[test]
326 fn a_package_without_a_spine_is_not_an_error() {
327 let package = Package::parse(r#"<package xmlns="o"/>"#).unwrap();
328 assert!(package.spine.is_empty());
329 }
330}