Cotton code
182 lines · 7.1 KB · RustRaw
//! WHAT AN EPUB SAYS ABOUT ITSELF, read by the core from the file (lane//! books-android-play, 6 Nov 2026): both shells hand a book's file to//! `capture.media` and the core reads its package document, so a book's//! title, author, language, ISBN and cover are read once, the same way, on//! every platform. A PDF is the shell's to read (the core holds no PDF//! reader, and no XMP reader, so a PDF's XMP title and creator are not//! read): its page count and its first page drawn; its title is its file's//! name.//!//! `META-INF/container.xml` names the OPF, and the package document is read//! by the one OPF reader, `cotton_rules::opf` (7 Nov//! 2026: the Worker and the Mac fetcher run the same rule as WASM). Here is//! only what needs the zip: finding the package, and the cover's bytes at the//! href it names. A Calibre library's `metadata.opf` is the same document,//! read by [`read_package`]. Nothing here opens a file: the caller hands a//! [`ZipRangeReader`] over the bytes.use crate::import::zip::{list_zip_entries_ranged, read_zip_entry_ranged, ZipEntry, ZipRangeReader};use cotton_rules::opf::{self, OpfFacts};use std::fmt;use std::ops::{Deref, DerefMut};/// What an EPUB's package document (or a Calibre `metadata.opf`) says, and/// the cover the EPUB carries. The facts are the package's/// ([`OpfFacts`], read through `Deref`); an EPUB with no title is shown under/// its file's name.#[derive(Debug, Clone, Default, PartialEq)]pub struct EpubFacts {    pub package: OpfFacts,    pub cover: Option<EpubCover>,}impl Deref for EpubFacts {    type Target = OpfFacts;    fn deref(&self) -> &OpfFacts {        &self.package    }}impl DerefMut for EpubFacts {    fn deref_mut(&mut self) -> &mut OpfFacts {        &mut self.package    }}/// What a package document alone says (a Calibre library's `metadata.opf`/// beside its book): every fact but the cover, which lies beside it.pub fn read_package(xml: &[u8]) -> EpubFacts {    EpubFacts { package: opf::read(xml), cover: None }}/// The cover image the EPUB carries: its bytes as they are in the zip, and/// its file extension (`jpg`, `png`, …), lowercased.#[derive(Clone, PartialEq, Eq)]pub struct EpubCover {    pub bytes: Vec<u8>,    pub extension: String,}impl fmt::Debug for EpubCover {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        write!(f, "EpubCover({} bytes, .{})", self.bytes.len(), self.extension)    }}/// Why an EPUB could not be read. Said, never swallowed.#[derive(Debug, Clone, PartialEq, Eq)]pub enum EpubTrouble {    /// Not a zip this reader opens (or a ZIP64).    NotAZip(String),    /// No `META-INF/container.xml`, or one naming no package document.    NoPackage,    /// An entry the container names that the zip does not hold.    Missing(String),    /// An entry that would not inflate, or is encrypted.    Unreadable(String),}impl fmt::Display for EpubTrouble {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        match self {            EpubTrouble::NotAZip(why) => write!(f, "this EPUB is not a zip that can be read: {why}"),            EpubTrouble::NoPackage => f.write_str("this EPUB names no package document (META-INF/container.xml)"),            EpubTrouble::Missing(path) => write!(f, "this EPUB's package names {path}, which it does not hold"),            EpubTrouble::Unreadable(path) => write!(f, "this EPUB's {path} cannot be read"),        }    }}impl std::error::Error for EpubTrouble {}/// The most an OPF or a container document may inflate to: a package/// document is metadata, never megabytes.const MOST_PACKAGE_BYTES: u64 = 4 * 1024 * 1024;/// What the EPUB behind `reader` says about itself.pub fn read_epub<R: ZipRangeReader + ?Sized>(reader: &R) -> Result<EpubFacts, EpubTrouble> {    let entries = list_zip_entries_ranged(reader).map_err(|why| EpubTrouble::NotAZip(why.to_string()))?;    let entry = |name: &str| entries.iter().find(|entry| entry.name == name);    let read = |found: &ZipEntry| read_zip_entry_ranged(reader, found).map_err(|_| EpubTrouble::Unreadable(found.name.clone()));    let container = entry("META-INF/container.xml").ok_or(EpubTrouble::NoPackage)?;    if container.uncompressed_size > MOST_PACKAGE_BYTES {        return Err(EpubTrouble::Unreadable(container.name.clone()));    }    let opf_path = opf::container_rootfile(&read(container)?).ok_or(EpubTrouble::NoPackage)?;    let opf_entry = entry(&opf_path).ok_or_else(|| EpubTrouble::Missing(opf_path.clone()))?;    if opf_entry.uncompressed_size > MOST_PACKAGE_BYTES {        return Err(EpubTrouble::Unreadable(opf_path));    }    let package = opf::read(&read(opf_entry)?);    let cover = match package.cover_href.clone() {        None => None,        Some(href) => {            let path = resolve_href(&href, &opf_path);            match entry(&path) {                // A cover the manifest names and the zip lacks is a book with no cover, not a book refused.                None => None,                Some(found) => {                    let extension = path.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).filter(|ext| !ext.is_empty() && !ext.contains('/'));                    Some(EpubCover { bytes: read(found)?, extension: extension.unwrap_or_else(|| "jpg".to_string()) })                }            }        }    };    Ok(EpubFacts { package, cover })}/// The title a book with no title of its own is shown under: its file's/// name without folder or extension; `None` when that leaves nothing.pub fn title_from_file_name(name: &str) -> Option<String> {    let base = name.rsplit(['/', '\\']).next().unwrap_or_default();    let stem = match base.rsplit_once('.') {        Some((stem, _)) if !stem.is_empty() => stem,        _ => base,    };    let stem = stem.trim();    (!stem.is_empty()).then(|| stem.to_string())}/// An href from the OPF, against the OPF's own folder, percent-decoded: a/// path inside the zip.pub fn resolve_href(href: &str, opf_path: &str) -> String {    let decoded = percent_decoded(href);    let decoded = decoded.split(['#', '?']).next().unwrap_or_default();    let mut parts: Vec<&str> = match opf_path.rsplit_once('/') {        Some((folder, _)) => folder.split('/').filter(|part| !part.is_empty()).collect(),        None => Vec::new(),    };    for part in decoded.split('/') {        match part {            ".." => {                parts.pop();            }            "." | "" => {}            other => parts.push(other),        }    }    parts.join("/")}fn percent_decoded(text: &str) -> String {    let bytes = text.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut at = 0;    while at < bytes.len() {        let hex = |byte: u8| (byte as char).to_digit(16);        if bytes[at] == b'%' && at + 2 < bytes.len() {            if let (Some(high), Some(low)) = (hex(bytes[at + 1]), hex(bytes[at + 2])) {                out.push((high * 16 + low) as u8);                at += 3;                continue;            }        }        out.push(bytes[at]);        at += 1;    }    String::from_utf8(out).unwrap_or_else(|_| text.to_string())}#[cfg(test)]#[path = "book_file_tests.rs"]pub(crate) mod tests;