Cotton code
583 lines · 24.9 KB · RustRaw
//! WHAT A BOOK'S PACKAGE DOCUMENT SAYS (7 Nov 2026)://! one reader of the OPF for every host. The phone's core calls it on the//! EPUB it opens (cotton-core media::book_file) and on a Calibre library's//! `metadata.opf`; the Worker calls it as WASM (`book.opf`) on the EPUB a//! book row names; the Mac fetcher calls the same WASM on what it lands.//! Pure: the document's text in, its facts out; the zip is the caller's.//!//! What is read (7 Nov 2026): the first `dc:title`;//! every author with the first's sort name (`file-as`, as an attribute or an//! EPUB 3 refine); the first `dc:language` and `dc:publisher`;//! `dc:description` as plain text; every `dc:subject`; the identifiers that//! are an ISBN (by scheme, `identifier-type` or `urn:isbn`), a DOI and an//! Open Library work or edition; the publication's year from `dc:date`; the//! series from EPUB 3's `belongs-to-collection` + `group-position`, else//! Calibre's EPUB 2 `calibre:series` + `calibre:series_index`; Calibre's//! rating. The cover's href is the manifest item whose `properties` holds//! `cover-image` (EPUB 3), else the item `<meta name="cover" content="id">`//! names (EPUB 2), as written (relative to the OPF).use quick_xml::events::{BytesStart, Event};use quick_xml::Reader;use serde::Serialize;/// What a package document says. Each fact is `None`, or empty, where the/// OPF says nothing.#[derive(Debug, Clone, Default, PartialEq, Serialize)]pub struct OpfFacts {    pub title: Option<String>,    /// Every author (a creator whose role is `aut` or unsaid; every creator    /// when none is), in the OPF's order, joined by commas.    pub author: Option<String>,    /// The first author's sort name (`file-as`), where the OPF gives one.    pub author_sort: Option<String>,    pub language: Option<String>,    pub isbn: Option<String>,    pub publisher: Option<String>,    /// `dc:description` as plain text: its HTML stripped, paragraphs kept.    pub description: Option<String>,    /// Every `dc:subject`, once each, in order.    pub subjects: Vec<String>,    pub doi: Option<String>,    /// An Open Library work id (`OL…W`) an identifier names.    pub ol_work: Option<String>,    /// An Open Library edition id (`OL…M`) an identifier names.    pub ol_edition: Option<String>,    /// The year of the publication's `dc:date`.    pub year: Option<String>,    /// EPUB 3 `belongs-to-collection` (a series), else Calibre's    /// `calibre:series`.    pub series: Option<String>,    /// The book's place in its series: `group-position`, else    /// `calibre:series_index`.    pub series_index: Option<f64>,    /// Calibre's `calibre:rating`, out of ten, as stars out of five.    pub rating: Option<f64>,    /// The cover image's href as the manifest writes it, relative to the OPF.    pub cover_href: Option<String>,}impl OpfFacts {    /// The book row's columns these facts fill, by key: every one the file    /// says but its title (the caller's to place, a file's name standing in    /// where it says none), its cover (bytes in the zip) and its rating (a    /// file's rating is whoever wrote the file's, so only a Calibre library's    /// own `metadata.opf` gives one, read by its walk).    pub fn columns(&self) -> serde_json::Map<String, serde_json::Value> {        let mut columns = serde_json::Map::new();        let texts = [            ("author", self.author.clone()),            ("language", self.language.clone()),            ("isbn", self.isbn.clone()),            ("publisher", self.publisher.clone()),            ("description", self.description.clone()),            ("subjects", self.subjects_text()),            ("doi", self.doi.clone()),            ("ol_work", self.ol_work.clone()),            ("ol_edition", self.ol_edition.clone()),            ("year", self.year.clone()),            ("series", self.series.clone()),        ];        for (column, value) in texts {            if let Some(value) = value {                columns.insert(column.to_string(), serde_json::Value::from(value));            }        }        if let (Some(_), Some(index)) = (&self.series, self.series_index) {            columns.insert("series_number".to_string(), serde_json::Value::from(index));        }        columns    }    /// The subjects as the book's `subjects` column holds them: comma    /// separated; `None` when there are none.    pub fn subjects_text(&self) -> Option<String> {        (!self.subjects.is_empty()).then(|| self.subjects.join(", "))    }    /// The facts as the WASM boundary answers them: every fact, and the book    /// row's `columns` they fill.    pub fn answer(&self) -> serde_json::Value {        let mut answer = serde_json::to_value(self).expect("facts are plain JSON");        answer["columns"] = serde_json::Value::Object(self.columns());        answer    }}/// What a package document says: an EPUB's OPF, or a Calibre library's/// `metadata.opf` beside its book. Text that is no XML says nothing.pub fn read(xml: &[u8]) -> OpfFacts {    Opf::parse(xml).facts()}/// An element's or attribute's name without its prefix: `dc:title` → `title`.fn local(name: &[u8]) -> &[u8] {    name.rsplit(|byte| *byte == b':').next().unwrap_or(name)}/// An attribute's value by its local name, unescaped.fn attribute(start: &BytesStart<'_>, name: &[u8]) -> Option<String> {    start        .attributes()        .flatten()        .find(|found| local(found.key.as_ref()) == name)        .and_then(|found| crate::xml_text::attribute_value(&found))}/// `META-INF/container.xml`'s first rootfile's `full-path`: where the/// package document is inside the EPUB.pub fn container_rootfile(xml: &[u8]) -> Option<String> {    let mut reader = Reader::from_reader(xml);    let mut buffer = Vec::new();    loop {        match reader.read_event_into(&mut buffer) {            Ok(Event::Start(start) | Event::Empty(start)) if local(start.name().as_ref()) == b"rootfile" => {                if let Some(path) = attribute(&start, b"full-path").map(|path| path.trim().to_string()).filter(|path| !path.is_empty()) {                    return Some(path);                }            }            Ok(Event::Eof) | Err(_) => return None,            _ => {}        }        buffer.clear();    }}/// What the OPF package document says, as it is written: every element the/// metadata holds, before the refines are applied.#[derive(Debug, Default)]struct Opf {    titles: Vec<String>,    creators: Vec<Creator>,    languages: Vec<String>,    publisher: Option<String>,    description: Option<String>,    subjects: Vec<String>,    identifiers: Vec<Identifier>,    /// `dc:date` with its EPUB 2 `opf:event`.    dates: Vec<(Option<String>, String)>,    /// EPUB 3 `<meta refines="#id" property=…>`: what one element says of another.    refines: Vec<Refine>,    /// EPUB 3 `<meta property="belongs-to-collection" id=…>`: its id and name.    collections: Vec<(Option<String>, String)>,    calibre_series: Option<String>,    calibre_series_index: Option<String>,    calibre_rating: Option<String>,    cover_image: Option<String>,    cover_id: Option<String>,    hrefs: Vec<(String, String)>,}#[derive(Debug)]struct Creator {    id: Option<String>,    name: String,    file_as: Option<String>,    role: Option<String>,}#[derive(Debug)]struct Identifier {    id: Option<String>,    value: String,    scheme: Option<String>,}#[derive(Debug)]struct Refine {    target: String,    property: String,    value: String,}/// A metadata element whose words are being read, with the attributes that/// say what they are.struct Open {    name: Vec<u8>,    id: Option<String>,    scheme: Option<String>,    file_as: Option<String>,    role: Option<String>,    event: Option<String>,    property: Option<String>,    refines: Option<String>,}const METADATA: [&[u8]; 9] = [b"title", b"creator", b"language", b"publisher", b"description", b"subject", b"identifier", b"date", b"meta"];/// An element inside a description that ends a line: XHTML a description/// carries as elements rather than as escaped text.fn breaks_line(name: &[u8]) -> bool {    matches!(name, b"p" | b"div" | b"br" | b"li" | b"h1" | b"h2" | b"h3" | b"h4" | b"h5" | b"h6" | b"blockquote")}impl Opf {    fn parse(xml: &[u8]) -> Opf {        let mut opf = Opf::default();        let mut reader = Reader::from_reader(xml);        let mut buffer = Vec::new();        let mut text = String::new();        let mut open: Option<Open> = None;        let mut depth = 0usize;        loop {            match reader.read_event_into(&mut buffer) {                Ok(Event::Start(start)) => {                    let name = local(start.name().as_ref()).to_vec();                    if open.is_some() {                        depth += 1;                        if breaks_line(&name) {                            text.push_str(&format!("<{}>", String::from_utf8_lossy(&name)));                        }                    } else {                        text.clear();                        opf.manifest(&start);                        opf.named_meta(&start);                        if METADATA.contains(&name.as_slice()) {                            open = Some(Open {                                name,                                id: attribute(&start, b"id"),                                scheme: attribute(&start, b"scheme"),                                file_as: attribute(&start, b"file-as"),                                role: attribute(&start, b"role"),                                event: attribute(&start, b"event"),                                property: attribute(&start, b"property"),                                refines: attribute(&start, b"refines"),                            });                        }                    }                }                Ok(Event::Empty(start)) => {                    if open.is_some() {                        let qname = start.name();                        let name = local(qname.as_ref());                        if breaks_line(name) {                            text.push_str(&format!("<{}/>", String::from_utf8_lossy(name)));                        }                    } else {                        opf.manifest(&start);                        opf.named_meta(&start);                    }                }                // A reference is its own event; one XML does not know                // (`&nbsp;` in a description) is kept as written, for the                // description's own reading.                Ok(Event::Text(said)) => match said.decode() {                    Ok(said) => text.push_str(&said),                    Err(_) => text.push_str(&String::from_utf8_lossy(&said)),                },                Ok(Event::GeneralRef(reference)) => text.push_str(&crate::xml_text::reference_text(&reference)),                Ok(Event::CData(said)) => text.push_str(&String::from_utf8_lossy(&said)),                Ok(Event::End(end)) => {                    if open.is_some() && depth > 0 {                        depth -= 1;                        let qname = end.name();                        let name = local(qname.as_ref());                        if breaks_line(name) {                            text.push_str(&format!("</{}>", String::from_utf8_lossy(name)));                        }                        continue;                    }                    if let Some(element) = open.take() {                        let said = text.trim().to_string();                        if !said.is_empty() {                            opf.take(element, said);                        }                    }                    text.clear();                }                Ok(Event::Eof) | Err(_) => break,                _ => {}            }            buffer.clear();        }        opf    }    fn take(&mut self, element: Open, said: String) {        match element.name.as_slice() {            b"title" => self.titles.push(said),            b"creator" => self.creators.push(Creator { id: element.id, name: said, file_as: element.file_as, role: element.role }),            b"language" => self.languages.push(said),            b"publisher" if self.publisher.is_none() => self.publisher = Some(said),            b"description" if self.description.is_none() => self.description = Some(said).map(|said| plain_text(&said)).filter(|said| !said.is_empty()),            b"subject" => self.subjects.push(said),            b"identifier" => self.identifiers.push(Identifier { id: element.id, value: said, scheme: element.scheme }),            b"date" => self.dates.push((element.event, said)),            b"meta" => match (element.refines, element.property) {                (Some(target), Some(property)) => self.refines.push(Refine { target: target.trim_start_matches('#').to_string(), property, value: said }),                (None, Some(property)) if property == "belongs-to-collection" => self.collections.push((element.id, said)),                _ => {}            },            _ => {}        }    }    /// A manifest item's href by id, the EPUB 3 cover image, the EPUB 2    /// cover meta.    fn manifest(&mut self, start: &BytesStart<'_>) {        match local(start.name().as_ref()) {            b"item" => {                let (Some(id), Some(href)) = (attribute(start, b"id"), attribute(start, b"href")) else { return };                if self.cover_image.is_none() && attribute(start, b"properties").is_some_and(|properties| properties.split_whitespace().any(|one| one == "cover-image")) {                    self.cover_image = Some(href.clone());                }                self.hrefs.push((id, href));            }            b"meta" if attribute(start, b"name").as_deref() == Some("cover") => {                if let Some(content) = attribute(start, b"content").filter(|content| !content.is_empty()) {                    self.cover_id = Some(content);                }            }            _ => {}        }    }    /// Calibre's EPUB 2 metas: `<meta name="calibre:series" content=…>`,    /// its index and the owner's rating (out of ten).    fn named_meta(&mut self, start: &BytesStart<'_>) {        if local(start.name().as_ref()) != b"meta" {            return;        }        let Some(name) = attribute(start, b"name") else { return };        let Some(content) = attribute(start, b"content").map(|content| content.trim().to_string()).filter(|content| !content.is_empty()) else { return };        let slot = match name.as_str() {            "calibre:series" => &mut self.calibre_series,            "calibre:series_index" => &mut self.calibre_series_index,            "calibre:rating" => &mut self.calibre_rating,            _ => return,        };        slot.get_or_insert(content);    }    fn cover_href(&self) -> Option<String> {        self.cover_image.clone().or_else(|| {            let id = self.cover_id.as_deref()?;            self.hrefs.iter().find(|(found, _)| found == id).map(|(_, href)| href.clone())        })    }    /// What an element with `id` is refined to say for `property`.    fn refined(&self, id: Option<&str>, property: &str) -> Option<&str> {        let id = id?;        self.refines.iter().find(|refine| refine.target == id && refine.property == property).map(|refine| refine.value.as_str())    }    /// The facts the package says, refines applied.    fn facts(&self) -> OpfFacts {        let role = |creator: &Creator| creator.role.clone().or_else(|| self.refined(creator.id.as_deref(), "role").map(str::to_string));        let mut authors: Vec<&Creator> = self.creators.iter().filter(|creator| role(creator).is_none_or(|role| role.eq_ignore_ascii_case("aut"))).collect();        if authors.is_empty() {            authors = self.creators.iter().collect();        }        let mut names: Vec<&str> = Vec::new();        for author in &authors {            if !names.contains(&author.name.as_str()) {                names.push(&author.name);            }        }        let author_sort = authors.first().and_then(|first| first.file_as.clone().or_else(|| self.refined(first.id.as_deref(), "file-as").map(str::to_string)));        let mut subjects: Vec<String> = Vec::new();        for subject in &self.subjects {            if !subjects.iter().any(|held| held.eq_ignore_ascii_case(subject)) {                subjects.push(subject.clone());            }        }        let (mut isbn, mut doi, mut ol_work, mut ol_edition) = (None, None, None, None);        for identifier in &self.identifiers {            let said = identifier.scheme.clone().or_else(|| self.refined(identifier.id.as_deref(), "identifier-type").map(str::to_string)).unwrap_or_default().to_ascii_lowercase();            if isbn.is_none() {                isbn = isbn_in(&identifier.value, matches!(said.as_str(), "isbn" | "15" | "02"));            }            if doi.is_none() {                doi = doi_in(&identifier.value);            }            match open_library_in(&identifier.value) {                Some(OpenLibrary::Work(id)) if ol_work.is_none() => ol_work = Some(id),                Some(OpenLibrary::Edition(id)) if ol_edition.is_none() => ol_edition = Some(id),                _ => {}            }        }        // The publication's date, never its file's: EPUB 2 says which by its event.        let event = |wanted: Option<&str>| self.dates.iter().find(|(event, _)| event.as_deref().map(str::to_ascii_lowercase).as_deref() == wanted).and_then(|(_, date)| year_in(date));        let year = event(Some("publication")).or_else(|| event(None)).or_else(|| event(Some("creation")));        let collection = self.collections.iter().find(|(id, _)| self.refined(id.as_deref(), "collection-type").is_none_or(|kind| kind.eq_ignore_ascii_case("series")));        let (series, series_index) = match collection {            Some((id, name)) => (Some(name.clone()), self.refined(id.as_deref(), "group-position").and_then(number_in)),            None => (self.calibre_series.clone(), self.calibre_series.as_ref().and(self.calibre_series_index.as_deref()).and_then(number_in)),        };        let rating = self.calibre_rating.as_deref().and_then(number_in).filter(|out_of_ten| *out_of_ten > 0.0 && *out_of_ten <= 10.0).map(|out_of_ten| (out_of_ten).round() / 2.0);        OpfFacts {            title: self.titles.first().cloned(),            author: (!names.is_empty()).then(|| names.join(", ")),            author_sort,            language: self.languages.first().cloned(),            isbn,            publisher: self.publisher.clone(),            description: self.description.clone(),            subjects,            doi,            ol_work,            ol_edition,            year,            series,            series_index,            rating,            cover_href: self.cover_href(),        }    }}/// A description's HTML as plain text: tags gone, a paragraph (or any block)/// a blank line, a `<br>` a line break, entities read, runs of spaces one.fn plain_text(html: &str) -> String {    // The source's own line breaks are layout, not the text's.    let html = html.split_whitespace().collect::<Vec<_>>().join(" ");    let mut out = String::with_capacity(html.len());    let mut rest = html.as_str();    while let Some(at) = rest.find('<') {        out.push_str(&rest[..at]);        let Some(close) = rest[at..].find('>') else {            out.push_str(&rest[at..]);            rest = "";            break;        };        let tag = rest[at + 1..at + close].trim_start_matches('/').trim();        let name = tag.chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();        match name.as_str() {            "br" => out.push('\n'),            _ if breaks_line(name.as_bytes()) => out.push_str("\n\n"),            _ => {}        }        rest = &rest[at + close + 1..];    }    out.push_str(rest);    let read = html_entities(&out);    let mut paragraphs: Vec<Vec<String>> = vec![Vec::new()];    for line in read.split('\n') {        let words = line.split_whitespace().collect::<Vec<_>>().join(" ");        match (words.is_empty(), paragraphs.last_mut()) {            (true, Some(last)) if !last.is_empty() => paragraphs.push(Vec::new()),            (false, Some(last)) => last.push(words),            _ => {}        }    }    paragraphs.iter().filter(|lines| !lines.is_empty()).map(|lines| lines.join("\n")).collect::<Vec<_>>().join("\n\n")}/// The HTML entities a description carries, read: the named few and every/// numeric one.fn html_entities(text: &str) -> String {    let mut out = String::with_capacity(text.len());    let mut rest = text;    while let Some(at) = rest.find('&') {        out.push_str(&rest[..at]);        let after = &rest[at + 1..];        let end = after.find(';').filter(|end| *end <= 10);        let read = end.and_then(|end| {            let name = &after[..end];            let numeric = |digits: &str, radix: u32| u32::from_str_radix(digits, radix).ok().and_then(char::from_u32);            match name {                "amp" => Some('&'),                "lt" => Some('<'),                "gt" => Some('>'),                "quot" => Some('"'),                "apos" => Some('\''),                "nbsp" => Some(' '),                "mdash" => Some('—'),                "ndash" => Some('–'),                "hellip" => Some('…'),                "rsquo" => Some('’'),                "lsquo" => Some('‘'),                "rdquo" => Some('”'),                "ldquo" => Some('“'),                _ if name.starts_with("#x") || name.starts_with("#X") => numeric(&name[2..], 16),                _ if name.starts_with('#') => numeric(&name[1..], 10),                _ => None,            }        });        match (read, end) {            (Some(read), Some(end)) => {                out.push(read);                rest = &after[end + 1..];            }            _ => {                out.push('&');                rest = after;            }        }    }    out.push_str(rest);    out}/// A number an OPF writes as words: `2`, `2.0`, `1.5`.fn number_in(text: &str) -> Option<f64> {    text.trim().parse::<f64>().ok().filter(|number| number.is_finite() && *number >= 0.0)}/// The year a `dc:date` names (`1897`, `1897-05-26`, `1897-05-26T00:00:00`);/// `None` for Calibre's unknown date, the year 101.fn year_in(date: &str) -> Option<String> {    let year: String = date.trim().chars().take(4).collect();    (year.len() == 4 && year.chars().all(|c| c.is_ascii_digit()) && year != "0101" && year != "0000").then_some(year)}/// A DOI in an identifier's words (`doi:10.1000/x`, `urn:doi:…`,/// `https://doi.org/…`, or a bare `10.NNNN/…`), as the DOI itself.pub fn doi_in(text: &str) -> Option<String> {    let text = text.trim();    let lower = text.to_ascii_lowercase();    let rest = ["https://doi.org/", "http://doi.org/", "https://dx.doi.org/", "http://dx.doi.org/", "urn:doi:", "doi:"]        .iter()        .find_map(|prefix| lower.starts_with(prefix).then(|| &text[prefix.len()..]))        .unwrap_or(text)        .trim();    let (registrant, suffix) = rest.split_once('/')?;    let digits = registrant.strip_prefix("10.")?;    (digits.len() >= 4 && digits.chars().all(|c| c.is_ascii_digit() || c == '.') && !suffix.trim().is_empty() && !suffix.contains(char::is_whitespace)).then(|| rest.to_string())}/// An Open Library id, a work's (`OL…W`) or an edition's (`OL…M`).#[derive(Debug, Clone, PartialEq, Eq)]pub enum OpenLibrary {    Work(String),    Edition(String),}/// An Open Library id in an identifier's words: `OL7353617M`,/// `openlibrary:OL…`, `https://openlibrary.org/works/OL…W`.pub fn open_library_in(text: &str) -> Option<OpenLibrary> {    let text = text.trim().trim_end_matches('/');    let last = text.rsplit(['/', ':']).next().unwrap_or(text);    let body = last.strip_prefix("OL")?;    let (digits, kind) = body.split_at(body.len().checked_sub(1)?);    if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {        return None;    }    match kind {        "W" => Some(OpenLibrary::Work(last.to_string())),        "M" => Some(OpenLibrary::Edition(last.to_string())),        _ => None,    }}/// An ISBN in an identifier's words — `urn:isbn:978…`, `978-0-…`, an/// identifier the OPF schemes ISBN — as its digits (an ISBN-10 may end in/// X); `None` when the words are no ISBN. A bare thirteen digits starting/// 978/979 is an ISBN even unsaid; ten digits only when something says so (a/// UUID's digits are not one).pub fn isbn_in(text: &str, schemed: bool) -> Option<String> {    let said = schemed || text.to_ascii_lowercase().contains("isbn");    let digits: String = text.to_ascii_uppercase().chars().filter(|c| c.is_ascii_digit() || *c == 'X').collect();    let thirteen = digits.len() == 13 && !digits.contains('X') && (digits.starts_with("978") || digits.starts_with("979"));    let ten = digits.len() == 10 && !digits[..9].contains('X');    match (thirteen, ten) {        (true, _) => Some(digits),        (_, true) if said => Some(digits),        _ => None,    }}#[cfg(test)]#[path = "opf_tests.rs"]mod tests;