[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export
This commit is contained in:
@@ -0,0 +1,432 @@
|
||||
//! EPUB 2 and 3.
|
||||
|
||||
use crate::sanitize::{Resolver, is_remote, sanitize};
|
||||
use crate::xml::{self, XEl};
|
||||
use crate::zip::Zip;
|
||||
use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, drm, text};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
struct Item {
|
||||
href: String,
|
||||
media: String,
|
||||
props: String,
|
||||
}
|
||||
|
||||
/// Percent-decodes and normalises `rel` against the directory `base` (`""` for the root). `None` if it climbs out.
|
||||
pub(crate) fn join(base: &str, rel: &str) -> Option<String> {
|
||||
let rel = rel.split(['#', '?']).next().unwrap_or("");
|
||||
let decoded = percent_decode(rel);
|
||||
let mut parts: Vec<&str> =
|
||||
if decoded.starts_with('/') { Vec::new() } else { base.split('/').filter(|s| !s.is_empty()).collect() };
|
||||
for seg in decoded.split('/') {
|
||||
match seg {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
parts.pop()?;
|
||||
}
|
||||
s => parts.push(s),
|
||||
}
|
||||
}
|
||||
Some(parts.join("/"))
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%'
|
||||
&& i + 2 < b.len()
|
||||
&& let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16))
|
||||
{
|
||||
out.push((h * 16 + l) as u8);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn dir_of(path: &str) -> &str {
|
||||
path.rfind('/').map_or("", |i| &path[..i])
|
||||
}
|
||||
|
||||
fn fragment(href: &str) -> Option<String> {
|
||||
href.split_once('#').map(|(_, f)| percent_decode(f)).filter(|f| !f.is_empty())
|
||||
}
|
||||
|
||||
/// Sniffs a raster image; `None` for anything else (SVG included).
|
||||
pub(crate) fn raster(bytes: &[u8]) -> Option<&'static str> {
|
||||
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
Some("image/png")
|
||||
} else if bytes.starts_with(b"\xff\xd8\xff") {
|
||||
Some("image/jpeg")
|
||||
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
|
||||
Some("image/gif")
|
||||
} else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||
Some("image/webp")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'z, 'a> {
|
||||
zip: &'z Zip<'a>,
|
||||
limits: &'z Limits,
|
||||
/// Spine path → chapter index.
|
||||
spine: HashMap<String, usize>,
|
||||
images: Vec<Image>,
|
||||
by_path: HashMap<String, Option<usize>>,
|
||||
base: String,
|
||||
chapter: usize,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Ctx<'_, '_> {
|
||||
fn load_image(&mut self, path: &str) -> Option<usize> {
|
||||
if let Some(i) = self.by_path.get(path) {
|
||||
return *i;
|
||||
}
|
||||
let r = (|| {
|
||||
if self.images.len() >= self.limits.max_images {
|
||||
return None;
|
||||
}
|
||||
let e = self.zip.find(path)?;
|
||||
let bytes = self.zip.read(e).ok()?;
|
||||
let media_type = raster(&bytes)?;
|
||||
let index = self.images.len();
|
||||
self.images.push(Image { index, media_type, bytes });
|
||||
Some(index)
|
||||
})();
|
||||
self.by_path.insert(path.to_owned(), r);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolver for Ctx<'_, '_> {
|
||||
fn link(&mut self, href: &str) -> Option<String> {
|
||||
if is_remote(href) {
|
||||
return None;
|
||||
}
|
||||
let frag = fragment(href);
|
||||
let path_part = href.split('#').next().unwrap_or("");
|
||||
let ch = if path_part.is_empty() { self.chapter } else { *self.spine.get(&join(&self.base, path_part)?)? };
|
||||
Some(match frag {
|
||||
Some(f) => format!("{ch}#{f}"),
|
||||
None => ch.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn image(&mut self, src: &str) -> Option<usize> {
|
||||
if is_remote(src) {
|
||||
self.warnings.push("a remote image was not loaded".into());
|
||||
return None;
|
||||
}
|
||||
let path = join(&self.base, src)?;
|
||||
self.load_image(&path)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_xml(zip: &Zip, path: &str, limits: &Limits) -> Result<Option<XEl>> {
|
||||
match zip.read_name_capped(path, limits.max_xml as u64)? {
|
||||
Some(b) => xml::parse(&text::decode_xml(&b), limits).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open(zip: &Zip, limits: &Limits) -> Result<Document> {
|
||||
drm::epub(zip, limits)?;
|
||||
let container = read_xml(zip, "META-INF/container.xml", limits)?
|
||||
.ok_or_else(|| FormatError::Malformed("no META-INF/container.xml".into()))?;
|
||||
let opf_path = container
|
||||
.descendants()
|
||||
.into_iter()
|
||||
.filter(|e| e.is("rootfile"))
|
||||
.find(|e| e.attr("media-type").is_none_or(|m| m.contains("oebps-package")))
|
||||
.and_then(|e| e.attr("full-path"))
|
||||
.and_then(|p| join("", p))
|
||||
.ok_or_else(|| FormatError::Malformed("container.xml names no package".into()))?;
|
||||
let opf =
|
||||
read_xml(zip, &opf_path, limits)?.ok_or_else(|| FormatError::Malformed(format!("{opf_path} is missing")))?;
|
||||
let opf_dir = dir_of(&opf_path).to_owned();
|
||||
|
||||
let mut items: HashMap<String, Item> = HashMap::new();
|
||||
if let Some(manifest) = opf.child("manifest") {
|
||||
for it in manifest.children_named("item") {
|
||||
if let (Some(id), Some(href)) = (it.attr("id"), it.attr("href"))
|
||||
&& let Some(href) = join(&opf_dir, href)
|
||||
{
|
||||
items.insert(
|
||||
id.to_owned(),
|
||||
Item {
|
||||
href,
|
||||
media: it.attr("media-type").unwrap_or("").to_owned(),
|
||||
props: it.attr("properties").unwrap_or("").to_owned(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let spine_el = opf.child("spine").ok_or_else(|| FormatError::Malformed("the package has no spine".into()))?;
|
||||
let mut spine: Vec<(String, bool)> = Vec::new();
|
||||
for r in spine_el.children_named("itemref") {
|
||||
if let Some(it) = r.attr("idref").and_then(|id| items.get(id))
|
||||
&& (it.media.contains("html") || it.media.is_empty())
|
||||
&& !spine.iter().any(|(h, _)| *h == it.href)
|
||||
{
|
||||
spine.push((it.href.clone(), r.attr("linear") != Some("no")));
|
||||
}
|
||||
}
|
||||
if spine.len() > limits.max_chapters {
|
||||
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
|
||||
}
|
||||
let metadata = metadata(&opf);
|
||||
|
||||
let mut ctx = Ctx {
|
||||
zip,
|
||||
limits,
|
||||
spine: spine.iter().enumerate().map(|(i, (h, _))| (h.clone(), i)).collect(),
|
||||
images: Vec::new(),
|
||||
by_path: HashMap::new(),
|
||||
base: String::new(),
|
||||
chapter: 0,
|
||||
warnings: Vec::new(),
|
||||
};
|
||||
let mut chapters = Vec::new();
|
||||
let mut footnotes = BTreeMap::new();
|
||||
for (i, (href, linear)) in spine.iter().enumerate() {
|
||||
ctx.base = dir_of(href).to_owned();
|
||||
ctx.chapter = i;
|
||||
let root = match chapter_body(zip, href, limits) {
|
||||
Ok(b) => b,
|
||||
Err(e @ (FormatError::Unsafe(_) | FormatError::TooLarge(_))) => return Err(e),
|
||||
Err(e) => {
|
||||
ctx.warnings.push(format!("{href}: {}", e.message()));
|
||||
XEl::new("body")
|
||||
}
|
||||
};
|
||||
let s = sanitize(&root, &mut ctx);
|
||||
if s.dropped > 0 {
|
||||
ctx.warnings.push(format!("{href}: {} element(s) dropped (remote or unsupported images)", s.dropped));
|
||||
}
|
||||
for (id, x) in s.notes {
|
||||
footnotes.insert(format!("{i}#{id}"), x);
|
||||
}
|
||||
chapters.push(crate::chapter(href.clone(), None, *linear, s.root));
|
||||
}
|
||||
|
||||
// Table of contents: the EPUB 3 nav, else the NCX.
|
||||
let nav = items.values().find(|it| it.props.split_whitespace().any(|p| p == "nav"));
|
||||
let mut toc = Vec::new();
|
||||
if let Some(nav) = nav
|
||||
&& let Ok(Some(doc)) = chapter_body(zip, &nav.href, limits).map(Some)
|
||||
{
|
||||
let base = dir_of(&nav.href).to_owned();
|
||||
if let Some(n) = doc
|
||||
.descendants()
|
||||
.into_iter()
|
||||
.filter(|e| e.is("nav"))
|
||||
.find(|e| e.attr("epub:type").is_some_and(|t| t.split_whitespace().any(|w| w == "toc")))
|
||||
&& let Some(ol) = n.child("ol")
|
||||
{
|
||||
toc = nav_list(ol, &base, &ctx.spine, 0);
|
||||
}
|
||||
}
|
||||
if toc.is_empty() {
|
||||
let ncx = spine_el
|
||||
.attr("toc")
|
||||
.and_then(|id| items.get(id))
|
||||
.or_else(|| items.values().find(|it| it.media == "application/x-dtbncx+xml"));
|
||||
if let Some(ncx) = ncx
|
||||
&& let Ok(Some(root)) = read_xml(zip, &ncx.href, limits)
|
||||
&& let Some(map) = root.child("navMap")
|
||||
{
|
||||
toc = ncx_list(map, dir_of(&ncx.href), &ctx.spine, 0);
|
||||
}
|
||||
}
|
||||
// Chapter titles from the TOC where the chapter has no heading of its own.
|
||||
fn first_titles(entries: &[TocEntry], out: &mut BTreeMap<usize, String>) {
|
||||
for e in entries {
|
||||
out.entry(e.chapter).or_insert_with(|| e.title.clone());
|
||||
first_titles(&e.children, out);
|
||||
}
|
||||
}
|
||||
let mut titles = BTreeMap::new();
|
||||
first_titles(&toc, &mut titles);
|
||||
for (i, c) in chapters.iter_mut().enumerate() {
|
||||
if let Some(t) = titles.get(&i) {
|
||||
c.title = Some(t.clone());
|
||||
}
|
||||
}
|
||||
|
||||
// Cover: EPUB 3 `cover-image`, else the EPUB 2 `<meta name="cover">`.
|
||||
let cover_path = items
|
||||
.values()
|
||||
.find(|it| it.props.split_whitespace().any(|p| p == "cover-image"))
|
||||
.map(|it| it.href.clone())
|
||||
.or_else(|| {
|
||||
let id = opf
|
||||
.child("metadata")?
|
||||
.children_named("meta")
|
||||
.find(|m| m.attr("name") == Some("cover"))?
|
||||
.attr("content")?
|
||||
.to_owned();
|
||||
items.get(&id).map(|it| it.href.clone())
|
||||
});
|
||||
let cover = cover_path.and_then(|p| ctx.load_image(&p));
|
||||
|
||||
Ok(Document {
|
||||
format: Format::Epub,
|
||||
metadata,
|
||||
chapters,
|
||||
toc,
|
||||
footnotes,
|
||||
images: ctx.images,
|
||||
cover,
|
||||
warnings: ctx.warnings,
|
||||
})
|
||||
}
|
||||
|
||||
/// A chapter's `<body>`: XML first, then tag soup if the chapter is not well-formed.
|
||||
fn chapter_body(zip: &Zip, href: &str, limits: &Limits) -> Result<XEl> {
|
||||
let bytes = zip
|
||||
.read_name_capped(href, limits.max_xml as u64)?
|
||||
.ok_or_else(|| FormatError::Malformed(format!("{href} is missing")))?;
|
||||
let s = text::decode_xml(&bytes);
|
||||
let root = match xml::parse(&s, limits) {
|
||||
Ok(r) => r,
|
||||
Err(e @ FormatError::Unsafe(_)) => return Err(e),
|
||||
Err(_) => crate::html::parse(&s, limits)?,
|
||||
};
|
||||
if root.is("body") {
|
||||
return Ok(root);
|
||||
}
|
||||
Ok(root.child("body").cloned().unwrap_or(root))
|
||||
}
|
||||
|
||||
fn toc_target(base: &str, href: &str, spine: &HashMap<String, usize>) -> Option<(usize, Option<String>)> {
|
||||
if is_remote(href) {
|
||||
return None;
|
||||
}
|
||||
let path = join(base, href)?;
|
||||
Some((*spine.get(&path)?, fragment(href)))
|
||||
}
|
||||
|
||||
fn nav_list(ol: &XEl, base: &str, spine: &HashMap<String, usize>, depth: usize) -> Vec<TocEntry> {
|
||||
let mut out = Vec::new();
|
||||
if depth > 16 {
|
||||
return out;
|
||||
}
|
||||
for li in ol.children_named("li") {
|
||||
let label = li.child("a").or_else(|| li.child("span"));
|
||||
let title = label.map(|l| text::collapse(&l.text())).unwrap_or_default();
|
||||
let children = li.child("ol").map(|o| nav_list(o, base, spine, depth + 1)).unwrap_or_default();
|
||||
match label.and_then(|l| l.attr("href")).and_then(|h| toc_target(base, h, spine)) {
|
||||
Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }),
|
||||
_ => out.extend(children),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn ncx_list(parent: &XEl, base: &str, spine: &HashMap<String, usize>, depth: usize) -> Vec<TocEntry> {
|
||||
let mut out = Vec::new();
|
||||
if depth > 16 {
|
||||
return out;
|
||||
}
|
||||
for p in parent.children_named("navPoint") {
|
||||
let title = p.child("navLabel").map(|l| text::collapse(&l.text())).unwrap_or_default();
|
||||
let children = ncx_list(p, base, spine, depth + 1);
|
||||
match p.child("content").and_then(|c| c.attr("src")).and_then(|h| toc_target(base, h, spine)) {
|
||||
Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }),
|
||||
_ => out.extend(children),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Strips markup from a description (it is often escaped HTML).
|
||||
pub(crate) fn plain(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut tag = false;
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'<' => tag = true,
|
||||
'>' if tag => {
|
||||
tag = false;
|
||||
out.push(' ');
|
||||
}
|
||||
c if !tag => out.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let out = out
|
||||
.replace(" ", " ")
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"");
|
||||
text::collapse(&out)
|
||||
}
|
||||
|
||||
fn metadata(opf: &XEl) -> Metadata {
|
||||
let mut m = Metadata::default();
|
||||
let Some(md) = opf.child("metadata") else { return m };
|
||||
let all: Vec<&XEl> = md.descendants();
|
||||
let refines = |id: Option<&str>, prop: &str| -> Option<String> {
|
||||
let id = id?;
|
||||
all.iter()
|
||||
.filter(|e| e.is("meta"))
|
||||
.find(|e| e.attr("refines") == Some(&format!("#{id}")) && e.attr("property") == Some(prop))
|
||||
.map(|e| text::collapse(&e.text()))
|
||||
};
|
||||
for e in md.elements() {
|
||||
let v = text::collapse(&e.text());
|
||||
match e.local() {
|
||||
"title" if m.title.is_none() && !v.is_empty() => m.title = Some(v),
|
||||
"creator" => {
|
||||
let role = e.attr("opf:role").map(str::to_owned).or_else(|| refines(e.attr("id"), "role"));
|
||||
if role.as_deref().is_none_or(|r| r == "aut") && !v.is_empty() {
|
||||
m.authors.push(v);
|
||||
}
|
||||
}
|
||||
"language" if m.language.is_none() && !v.is_empty() => m.language = Some(v),
|
||||
"identifier" if !v.is_empty() => m.identifiers.push(v),
|
||||
"publisher" if m.publisher.is_none() && !v.is_empty() => m.publisher = Some(v),
|
||||
"date" if m.published.is_none() && !v.is_empty() => m.published = Some(v),
|
||||
"description" if m.description.is_none() => {
|
||||
let p = plain(&e.text());
|
||||
if !p.is_empty() {
|
||||
m.description = Some(p);
|
||||
}
|
||||
}
|
||||
"subject" if !v.is_empty() => m.subjects.push(v),
|
||||
"meta" => {
|
||||
if e.attr("name") == Some("calibre:series")
|
||||
&& let Some(c) = e.attr("content")
|
||||
{
|
||||
m.series.get_or_insert_with(Series::default).name = c.trim().to_owned();
|
||||
}
|
||||
if e.attr("name") == Some("calibre:series_index")
|
||||
&& let Some(c) = e.attr("content")
|
||||
{
|
||||
m.series.get_or_insert_with(Series::default).index = c.trim().parse().ok();
|
||||
}
|
||||
if e.attr("property") == Some("belongs-to-collection") && !v.is_empty() {
|
||||
let kind = refines(e.attr("id"), "collection-type");
|
||||
if kind.as_deref().is_none_or(|k| k == "series") {
|
||||
let index = refines(e.attr("id"), "group-position").and_then(|p| p.parse().ok());
|
||||
m.series = Some(Series { name: v, index });
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if m.series.as_ref().is_some_and(|s| s.name.is_empty()) {
|
||||
m.series = None;
|
||||
}
|
||||
m
|
||||
}
|
||||
Reference in New Issue
Block a user