mod css;
mod entities;
mod html;
mod mathml;
use crate::model::Document;
use crate::word::zip::ZipArchive;
use anyhow::{Context, Result, bail};
use roxmltree::{Document as Xml, Node, ParsingOptions};
use std::collections::HashMap;
const MIMETYPE: &str = "application/epub+zip";
const ENCRYPTION: &str = "META-INF/encryption.xml";
const CONTAINER: &str = "META-INF/container.xml";
const OPF_NS: &str = "http://www.idpf.org/2007/opf";
const DC_NS: &str = "http://purl.org/dc/elements/1.1/";
const CONTENT_TYPES: [&str; 3] = ["application/xhtml+xml", "text/html", "image/svg+xml"];
const MAX_XML_NODES: u32 = u32::MAX;
#[derive(Debug, Default)]
struct Package {
title: Option<String>,
creators: Vec<String>,
spine: Vec<String>,
}
pub fn is_epub(data: &[u8]) -> bool {
if !data.starts_with(b"PK\x03\x04") {
return false;
}
let Ok(zip) = ZipArchive::new(data) else {
return false;
};
zip.read_text("mimetype")
.ok()
.flatten()
.is_some_and(|text| text.trim() == MIMETYPE)
|| zip.contains(CONTAINER)
}
pub fn read(data: &[u8], source: Option<String>) -> Result<Document> {
let zip = ZipArchive::new(data)?;
let opf = rootfile(&zip)?;
let package = package(&zip, &opf)?;
if package.spine.is_empty() {
bail!("the EPUB has no content documents in its spine");
}
let book = html::read_book(&zip, &package.spine, package.title.as_deref(), &package.creators).map_err(|err| {
if zip.contains(ENCRYPTION) {
err.context("the EPUB is encrypted (DRM): its content cannot be read")
} else {
err
}
})?;
let mut doc = crate::word::build_document(book, source);
doc.meta.source_format = Some("epub".to_string());
Ok(doc)
}
fn parse(text: &str) -> Result<Xml<'_>> {
let options = ParsingOptions {
allow_dtd: true,
nodes_limit: MAX_XML_NODES,
};
Ok(Xml::parse_with_options(text, options)?)
}
fn rootfile(zip: &ZipArchive<'_>) -> Result<String> {
let text = zip
.read_text(CONTAINER)?
.with_context(|| format!("the EPUB has no {CONTAINER}"))?;
let xml = parse(&text).with_context(|| format!("reading {CONTAINER}"))?;
let path = xml
.descendants()
.filter(|node| node.has_tag_name("rootfile"))
.find(|node| {
node.attribute("media-type")
.is_none_or(|media| media == "application/oebps-package+xml")
})
.and_then(|node| node.attribute("full-path"))
.context("the EPUB container names no package document")?;
Ok(percent_decode(path))
}
fn package(zip: &ZipArchive<'_>, opf: &str) -> Result<Package> {
let text = zip
.read_text(opf)?
.with_context(|| format!("the EPUB has no package document {opf}"))?;
let xml = parse(&text).with_context(|| format!("reading {opf}"))?;
let root = xml.root_element();
let metadata = |name: &'static str| {
root.descendants()
.filter(move |node| node.tag_name().name() == name && node.tag_name().namespace() == Some(DC_NS))
.map(|node| clean_text(&node))
.filter(|text| !text.is_empty())
};
let mut manifest: HashMap<&str, (String, &str)> = HashMap::new();
for item in root
.descendants()
.filter(|node| node.tag_name().name() == "item" && node.tag_name().namespace() == Some(OPF_NS))
{
if let (Some(id), Some(href)) = (item.attribute("id"), item.attribute("href")) {
let media = item.attribute("media-type").unwrap_or_default();
manifest.insert(id, (resolve(opf, href).0, media));
}
}
let spine = root
.descendants()
.filter(|node| node.tag_name().name() == "itemref" && node.tag_name().namespace() == Some(OPF_NS))
.filter_map(|itemref| manifest.get(itemref.attribute("idref")?))
.filter(|(_, media)| CONTENT_TYPES.contains(media))
.map(|(path, _)| path.clone())
.collect();
Ok(Package {
title: metadata("title").next(),
creators: metadata("creator").collect(),
spine,
})
}
fn clean_text(node: &Node<'_, '_>) -> String {
let text: String = node
.descendants()
.filter(Node::is_text)
.filter_map(|text| text.text())
.collect();
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn resolve(base: &str, href: &str) -> (String, String) {
let (path, fragment) = href.split_once('#').unwrap_or((href, ""));
let path = path.split_once('?').map_or(path, |(path, _)| path);
if path.is_empty() {
return (base.to_string(), percent_decode(fragment));
}
let mut parts: Vec<String> = if path.starts_with('/') {
Vec::new()
} else {
base.split('/').map(str::to_string).collect()
};
if !path.starts_with('/') {
parts.pop();
}
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
parts.pop();
}
_ => parts.push(percent_decode(part)),
}
}
(parts.join("/"), percent_decode(fragment))
}
fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(byte) = text.get(i + 1..i + 3).and_then(|hex| u8::from_str_radix(hex, 16).ok())
{
out.push(byte);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
#[cfg(test)]
mod tests {
use super::{percent_decode, resolve};
#[test]
fn references_resolve_to_archive_paths() {
assert_eq!(
resolve("EPUB/text/ch1.xhtml", "../media/a%20b.png"),
("EPUB/media/a b.png".to_string(), String::new())
);
assert_eq!(
resolve("EPUB/text/ch1.xhtml", "ch2.xhtml#sec-1"),
("EPUB/text/ch2.xhtml".to_string(), "sec-1".to_string())
);
assert_eq!(
resolve("EPUB/text/ch1.xhtml", "#fn1"),
("EPUB/text/ch1.xhtml".to_string(), "fn1".to_string())
);
assert_eq!(
resolve("content.opf", "text/ch1.xhtml"),
("text/ch1.xhtml".to_string(), String::new())
);
assert_eq!(percent_decode("%C3%A9t%C3%A9"), "été");
assert_eq!(percent_decode("100%"), "100%");
}
}