Cotton code
245 lines · 9.7 KB · RustRaw
//! A FOLDER OF BOOKS WALKED IN (7 Nov 2026). The//! caller lists the folder's files (paths relative to the folder, `/`//! between parts) and hands two readers: one for a small file's whole bytes//! (a `metadata.opf`), one for an EPUB's facts ([`super::book_file::read_epub`]//! over the file). The walk answers which books come in, what each says,//! and the words of its answer.//!//! A Calibre library is `Author/Title (id)/{book.epub, metadata.opf,//! cover.jpg}`: a book file with a `metadata.opf` beside it is read from//! that document and that cover first and from its own file second (the//! file fills only what the OPF leaves unsaid), and Calibre's rating is the//! owner's own. One book per Calibre folder, its EPUB before its PDF. Any//! other EPUB or PDF is a book from its file alone (a PDF's title its name).//! A book whose ISBN or Open Library id (work or edition) is already held,//! or came earlier in the same walk, is skipped and counted.use super::book_file::{title_from_file_name, EpubCover, EpubFacts, EpubTrouble};use std::collections::HashSet;/// What a book already held is known by: the ids a duplicate is found by.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct HeldBook {    pub isbn: Option<String>,    pub ol_work: Option<String>,    pub ol_edition: Option<String>,}/// A book's cover: a picture beside it (a Calibre `cover.jpg`, by its path/// in the folder) or the one its EPUB carries.#[derive(Debug, Clone, PartialEq)]pub enum WalkedCover {    Beside(String),    Inside(EpubCover),}/// One book the walk lets in.#[derive(Debug, Clone, PartialEq)]pub struct WalkedBook {    /// The book's file, by its path in the folder.    pub file: String,    /// `epub` or `pdf`.    pub format: &'static str,    /// What its `metadata.opf` and its file say (the cover apart); its title    /// is always set, its file's name where nothing says one.    pub facts: EpubFacts,    pub cover: Option<WalkedCover>,    /// Read from a Calibre library's `metadata.opf`.    pub calibre: bool,}impl WalkedBook {    /// The book row's columns, its title among them (cover, file and format    /// are the caller's to place): what the file says, and a Calibre    /// library's rating.    pub fn columns(&self) -> serde_json::Map<String, serde_json::Value> {        let mut columns = self.facts.columns();        if let Some(title) = &self.facts.title {            columns.insert("title".to_string(), serde_json::Value::from(title.clone()));        }        if let (true, Some(rating)) = (self.calibre, self.facts.rating) {            columns.insert("rating".to_string(), serde_json::Value::from(rating));        }        columns    }}/// What a walk of one folder found.#[derive(Debug, Clone, Default, PartialEq)]pub struct FolderWalk {    pub books: Vec<WalkedBook>,    /// Books skipped for an ISBN or Open Library id already held or already    /// met in this walk.    pub duplicates: usize,    /// Loose EPUBs that could not be read, by path, with why.    pub unreadable: Vec<(String, String)>,}impl FolderWalk {    /// The walk's answer in words: how many books came in, how many from    /// Calibre's metadata, how many were here already and how many files    /// could not be read.    pub fn answer(&self) -> String {        let books = |count: usize| if count == 1 { "1 book".to_string() } else { format!("{count} books") };        let calibre = self.books.iter().filter(|book| book.calibre).count();        let mut words = match (self.books.len(), calibre) {            (0, _) => "Added no books.".to_string(),            (_, 0) => format!("Added {}.", books(self.books.len())),            (all, from) if all == from => format!("Added {} from a Calibre library.", books(all)),            (all, from) => format!("Added {}, {from} from a Calibre library.", books(all)),        };        if self.duplicates > 0 {            let were = if self.duplicates == 1 { "was" } else { "were" };            words.push_str(&format!(" {} {were} here already (the same ISBN or Open Library id).", books(self.duplicates)));        }        match self.unreadable.len() {            0 => {}            1 => words.push_str(" 1 file could not be read."),            many => words.push_str(&format!(" {many} files could not be read.")),        }        words    }}/// The ids a walk has met, held ones first.struct Seen {    isbns: HashSet<String>,    open_library: HashSet<String>,}impl Seen {    /// Whether `facts` is a book met already; when not, its ids are met now.    fn met(&mut self, facts: &EpubFacts) -> bool {        let isbn = facts.isbn.as_ref().is_some_and(|isbn| self.isbns.contains(isbn));        let open_library = [&facts.ol_work, &facts.ol_edition].into_iter().flatten().any(|id| self.open_library.contains(id));        if isbn || open_library {            return true;        }        self.isbns.extend(facts.isbn.clone());        self.open_library.extend([&facts.ol_work, &facts.ol_edition].into_iter().flatten().cloned());        false    }}/// A book file's format by its extension: `epub` or `pdf`.fn format_of(path: &str) -> Option<&'static str> {    let (_, extension) = path.rsplit_once('.')?;    match extension.to_ascii_lowercase().as_str() {        "epub" => Some("epub"),        "pdf" => Some("pdf"),        _ => None,    }}/// A path's folder: `a/b/c.epub` → `a/b`; `` for a file at the top.fn folder_of(path: &str) -> &str {    path.rsplit_once('/').map(|(folder, _)| folder).unwrap_or("")}/// A file beside a folder's books, by its name: `a/b` + `metadata.opf`.fn beside(folder: &str, name: &str) -> String {    if folder.is_empty() {        name.to_string()    } else {        format!("{folder}/{name}")    }}/// `facts` with every fact it leaves unsaid taken from `file`.fn filled_from(mut facts: EpubFacts, file: EpubFacts) -> EpubFacts {    fn fill<T>(slot: &mut Option<T>, from: Option<T>) {        if slot.is_none() {            *slot = from;        }    }    let EpubFacts { package: from, cover } = file;    let into = &mut facts.package;    fill(&mut into.title, from.title);    fill(&mut into.author, from.author);    fill(&mut into.author_sort, from.author_sort);    fill(&mut into.language, from.language);    fill(&mut into.isbn, from.isbn);    fill(&mut into.publisher, from.publisher);    fill(&mut into.description, from.description);    fill(&mut into.doi, from.doi);    fill(&mut into.ol_work, from.ol_work);    fill(&mut into.ol_edition, from.ol_edition);    fill(&mut into.year, from.year);    if into.series.is_none() {        into.series = from.series;        into.series_index = from.series_index;    }    if into.subjects.is_empty() {        into.subjects = from.subjects;    }    fill(&mut facts.cover, cover);    facts}/// Walk `files` (every file in the folder, by its path in it): `whole` reads/// a small file's bytes (a `metadata.opf`), `epub` an EPUB's facts; `held`/// are the books already in the database.pub fn walk_folder(    files: &[String],    mut whole: impl FnMut(&str) -> Option<Vec<u8>>,    mut epub: impl FnMut(&str) -> Result<EpubFacts, EpubTrouble>,    held: &[HeldBook],) -> FolderWalk {    let mut seen = Seen {        isbns: held.iter().filter_map(|book| book.isbn.clone()).collect(),        open_library: held.iter().flat_map(|book| [book.ol_work.clone(), book.ol_edition.clone()]).flatten().collect(),    };    let present: HashSet<&str> = files.iter().map(String::as_str).collect();    let mut ordered: Vec<&String> = files.iter().filter(|path| format_of(path).is_some()).collect();    // Paths in order, and in a Calibre folder its EPUB before its PDF.    ordered.sort_by(|a, b| (folder_of(a), format_of(a) != Some("epub"), a.as_str()).cmp(&(folder_of(b), format_of(b) != Some("epub"), b.as_str())));    let mut walk = FolderWalk::default();    let mut calibre_folders: HashSet<&str> = HashSet::new();    for path in ordered {        let format = format_of(path).expect("a book file");        let folder = folder_of(path);        let opf_path = beside(folder, "metadata.opf");        let calibre = present.contains(opf_path.as_str());        if calibre && !calibre_folders.insert(folder) {            continue; // one book per Calibre folder: its EPUB came first        }        let from_file = match format {            "epub" => match epub(path) {                Ok(facts) => Some(facts),                Err(trouble) if !calibre => {                    walk.unreadable.push((path.clone(), trouble.to_string()));                    continue;                }                // A Calibre book whose file will not read is still its metadata's book.                Err(_) => None,            },            _ => None,        };        let opf = if calibre { whole(&opf_path) } else { None };        let from_opf = opf.is_some();        let mut facts = match (opf, from_file) {            (Some(opf), Some(file)) => filled_from(super::book_file::read_package(&opf), file),            (Some(opf), None) => super::book_file::read_package(&opf),            (None, file) => file.unwrap_or_default(),        };        if facts.title.is_none() {            facts.title = title_from_file_name(path);        }        let inside = facts.cover.take();        let cover = calibre            .then(|| ["cover.jpg", "cover.jpeg", "cover.png"].into_iter().map(|name| beside(folder, name)).find(|cover| present.contains(cover.as_str())))            .flatten()            .map(WalkedCover::Beside)            .or(inside.map(WalkedCover::Inside));        if seen.met(&facts) {            walk.duplicates += 1;            continue;        }        walk.books.push(WalkedBook { file: path.clone(), format, facts, cover, calibre: from_opf });    }    walk}#[cfg(test)]#[path = "book_folder_tests.rs"]mod tests;