//! Books out: a Calibre-shaped tree, an OPDS catalogue in both versions, a //! Goodreads CSV, and highlights as Markdown and Web Annotations. //! //! ```text //! Books/ //! catalog.json OPDS 2.0 (application/opds+json) //! catalog.xml OPDS 1.2 (Atom acquisition feed) //! goodreads.csv Goodreads' import columns (StoryGraph takes it too) //! // //! <Title>.epub|pdf the file as stored //! cover.<ext> the cover as stored //! metadata.opf EPUB 3 package metadata (Calibre reads it) //! <Title>.highlights.md when the book has highlights //! <Title>.highlights.jsonld the same, as a W3C Web Annotation collection //! ``` //! //! The kit holds no description or subjects, so the OPF carries none. use std::collections::{BTreeMap, BTreeSet}; use serde_json::{json, Value as JsonValue}; use super::{component, csv, json_number, extension, href, number, picture_type, plain_number, pretty, text, unique, xml, Out, Result, Row}; /// One book as laid: its folder and the files in it. struct Laid<'a> { row: &'a Row, id: String, /// `<Author>/<Title>`, relative to `Books/`. folder: String, /// The book file's name in its folder, when its bytes were copied. file: Option<String>, /// The cover's name in its folder, when its bytes were copied. cover: Option<String>, } pub(super) fn write(out: &mut Out) -> Result<()> { let books = out.rows("book"); let highlights = out.rows("highlight"); let exported_at = out.exported_at().to_string(); let exported_at = exported_at.as_str(); let mut sorted: Vec<&Row> = books.iter().collect(); sorted.sort_by_key(|row| { ( text(row, "author").unwrap_or_default().to_lowercase(), text(row, "title").unwrap_or_default().to_lowercase(), text(row, "id").unwrap_or_default().to_string(), ) }); // An author's folder is spelled as the first of their books spells it, so // `ana vell` and `Ana Vell` share one. let mut authors: BTreeMap<String, String> = BTreeMap::new(); let mut titles: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); let mut laid = Vec::new(); for row in sorted { let id = text(row, "id").unwrap_or_default().to_string(); let author = component(text(row, "author"), "Unknown Author"); let author = authors.entry(author.to_lowercase()).or_insert(author).clone(); let title = unique(titles.entry(author.to_lowercase()).or_default(), &component(text(row, "title"), "Untitled")); let folder = format!("{author}/{title}"); let file = match text(row, "file") { Some(media) => { let ext = extension(media).or_else(|| text(row, "format").map(str::to_string)).unwrap_or_else(|| "bin".into()); let name = format!("{title}.{ext}"); out.copy(media, &format!("Books/{folder}/{name}")).then_some(name) } None => None, }; let cover = match text(row, "cover") { Some(media) => { let name = format!("cover.{}", extension(media).unwrap_or_else(|| "jpg".into())); out.copy(media, &format!("Books/{folder}/{name}")).then_some(name) } None => None, }; let book = Laid { row, id, folder, file, cover }; out.write(&format!("Books/{}/metadata.opf", book.folder), opf(&book)); laid.push(book); } let mut marks: BTreeMap<&str, Vec<&Row>> = BTreeMap::new(); for highlight in &highlights { if let Some(book) = text(highlight, "book") { marks.entry(book).or_default().push(highlight); } } for book in &laid { let Some(list) = marks.get_mut(book.id.as_str()) else { continue }; list.sort_by(|a, b| { let progress = |row: &Row| number(row, "progress").unwrap_or(f64::MAX); progress(a) .total_cmp(&progress(b)) .then_with(|| text(a, "made_at").cmp(&text(b, "made_at"))) .then_with(|| text(a, "id").cmp(&text(b, "id"))) }); let title = book.folder.rsplit('/').next().unwrap_or_default(); out.write(&format!("Books/{}/{title}.highlights.md", book.folder), highlights_markdown(book, list)); out.write(&format!("Books/{}/{title}.highlights.jsonld", book.folder), pretty(&annotations(book, list))); } out.write("Books/catalog.json", pretty(&opds2(&laid, exported_at))); out.write("Books/catalog.xml", opds1(&laid, &out.library.database, exported_at)); out.write("Books/goodreads.csv", goodreads(&laid)); Ok(()) } /// The ISBN's digits (and a final X), or `None` when it is not ten or /// thirteen of them. fn isbn(row: &Row) -> Option<String> { let digits: String = text(row, "isbn")?.chars().filter(|c| c.is_ascii_digit() || *c == 'X' || *c == 'x').collect(); let digits = digits.to_ascii_uppercase(); matches!(digits.len(), 10 | 13).then_some(digits) } /// An ISBN-13 for an ISBN: itself, or a ten-digit one under 978. fn isbn13(isbn: &str) -> Option<String> { match isbn.len() { 13 => Some(isbn.to_string()), 10 => { let body = format!("978{}", &isbn[..9]); let sum: u32 = body .chars() .enumerate() .map(|(i, c)| c.to_digit(10).unwrap_or(0) * if i % 2 == 0 { 1 } else { 3 }) .sum(); Some(format!("{body}{}", (10 - sum % 10) % 10)) } _ => None, } } fn book_type(name: &str) -> &'static str { match name.rsplit('.').next() { Some("epub") => "application/epub+zip", Some("pdf") => "application/pdf", _ => "application/octet-stream", } } /// The book's `metadata.opf`: an EPUB 3 package document's metadata and the /// files beside it, series as `belongs-to-collection`. fn opf(book: &Laid) -> String { let row = book.row; let mut meta = Vec::new(); meta.push(format!(" <dc:identifier id=\"uid\">urn:cotton:book:{}</dc:identifier>", xml(&book.id))); if let Some(isbn) = isbn(row) { meta.push(format!(" <dc:identifier id=\"isbn\">urn:isbn:{isbn}</dc:identifier>")); } if let Some(work) = text(row, "ol_work") { meta.push(format!(" <dc:identifier id=\"olid\">https://openlibrary.org/works/{}</dc:identifier>", xml(work))); } meta.push(format!(" <dc:title>{}</dc:title>", xml(text(row, "title").unwrap_or("Untitled")))); if let Some(author) = text(row, "author") { meta.push(format!(" <dc:creator id=\"creator\">{}</dc:creator>", xml(author))); meta.push(" <meta refines=\"#creator\" property=\"role\" scheme=\"marc:relators\">aut</meta>".into()); } if let Some(language) = text(row, "language") { meta.push(format!(" <dc:language>{}</dc:language>", xml(language))); } if let Some(year) = text(row, "year") { meta.push(format!(" <dc:date>{}</dc:date>", xml(year))); } if let Some(series) = text(row, "series") { meta.push(format!(" <meta property=\"belongs-to-collection\" id=\"series\">{}</meta>", xml(series))); meta.push(" <meta refines=\"#series\" property=\"collection-type\">series</meta>".into()); if let Some(position) = number(row, "series_number") { meta.push(format!(" <meta refines=\"#series\" property=\"group-position\">{}</meta>", plain_number(position))); } } let mut manifest = Vec::new(); if let Some(file) = &book.file { manifest.push(format!(" <item id=\"book\" href=\"{}\" media-type=\"{}\"/>", xml(&href(file)), book_type(file))); } if let Some(cover) = &book.cover { let ext = cover.rsplit('.').next().unwrap_or("jpg"); manifest.push(format!( " <item id=\"cover\" href=\"{}\" media-type=\"{}\" properties=\"cover-image\"/>", xml(&href(cover)), picture_type(ext) )); } let manifest = if manifest.is_empty() { " <manifest/>\n".to_string() } else { format!(" <manifest>\n{}\n </manifest>\n", manifest.join("\n")) }; format!( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\ <package xmlns=\"http://www.idpf.org/2007/opf\" version=\"3.0\" unique-identifier=\"uid\">\n\ \x20 <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n{}\n </metadata>\n{manifest}</package>\n", meta.join("\n") ) } /// The OPDS 2.0 catalogue: one publication per book whose file is in the /// bundle (a publication is something a reader can take). fn opds2(laid: &[Laid], exported_at: &str) -> JsonValue { let publications: Vec<JsonValue> = laid .iter() .filter_map(|book| { let file = book.file.as_ref()?; let row = book.row; let mut metadata = serde_json::Map::new(); metadata.insert("@type".into(), json!("http://schema.org/Book")); metadata.insert( "identifier".into(), json!(isbn(row).map(|isbn| format!("urn:isbn:{isbn}")).unwrap_or_else(|| format!("urn:cotton:book:{}", book.id))), ); metadata.insert("title".into(), json!(text(row, "title").unwrap_or("Untitled"))); if let Some(author) = text(row, "author") { metadata.insert("author".into(), json!(author)); } if let Some(language) = text(row, "language") { metadata.insert("language".into(), json!(language)); } if let Some(year) = text(row, "year") { metadata.insert("published".into(), json!(year)); } if let Some(pages) = number(row, "pages") { metadata.insert("numberOfPages".into(), json_number(pages)); } if let Some(series) = text(row, "series") { let mut entry = serde_json::Map::new(); entry.insert("name".into(), json!(series)); if let Some(position) = number(row, "series_number") { entry.insert("position".into(), json_number(position)); } metadata.insert("belongsTo".into(), json!({ "series": entry })); } let mut publication = serde_json::Map::new(); publication.insert("metadata".into(), JsonValue::Object(metadata)); publication.insert( "links".into(), json!([{ "rel": "http://opds-spec.org/acquisition", "href": href(&format!("{}/{file}", book.folder)), "type": book_type(file), }]), ); if let Some(cover) = &book.cover { publication.insert( "images".into(), json!([{ "href": href(&format!("{}/{cover}", book.folder)), "type": picture_type(cover.rsplit('.').next().unwrap_or("jpg")) }]), ); } Some(JsonValue::Object(publication)) }) .collect(); json!({ "metadata": { "title": "Cotton Books", "modified": exported_at, "numberOfItems": publications.len() }, "links": [{ "rel": "self", "href": "catalog.json", "type": "application/opds+json" }], "publications": publications, }) } /// The OPDS 1.2 twin: an Atom acquisition feed of the same books. fn opds1(laid: &[Laid], database: &str, exported_at: &str) -> String { let kind = "application/atom+xml;profile=opds-catalog;kind=acquisition"; let mut feed = format!( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\ <feed xmlns=\"http://www.w3.org/2005/Atom\" xmlns:dc=\"http://purl.org/dc/terms/\" xmlns:opds=\"http://opds-spec.org/2010/catalog\">\n\ \x20 <id>urn:cotton:books:{}</id>\n\ \x20 <title>Cotton Books\n\ \x20 {}\n\ \x20 Cotton\n\ \x20 \n\ \x20 \n", xml(database), xml(exported_at) ); for book in laid { let Some(file) = &book.file else { continue }; let row = book.row; feed.push_str(" \n"); feed.push_str(&format!(" {}\n", xml(text(row, "title").unwrap_or("Untitled")))); feed.push_str(&format!(" urn:cotton:book:{}\n", xml(&book.id))); feed.push_str(&format!(" {}\n", xml(text(row, "updated_at").unwrap_or(exported_at)))); if let Some(author) = text(row, "author") { feed.push_str(&format!(" {}\n", xml(author))); } if let Some(isbn) = isbn(row) { feed.push_str(&format!(" urn:isbn:{isbn}\n")); } if let Some(language) = text(row, "language") { feed.push_str(&format!(" {}\n", xml(language))); } if let Some(year) = text(row, "year") { feed.push_str(&format!(" {}\n", xml(year))); } if let Some(cover) = &book.cover { let ext = cover.rsplit('.').next().unwrap_or("jpg"); feed.push_str(&format!( " \n", xml(&href(&format!("{}/{cover}", book.folder))), picture_type(ext) )); } feed.push_str(&format!( " \n", xml(&href(&format!("{}/{file}", book.folder))), book_type(file) )); feed.push_str(" \n"); } feed.push_str("\n"); feed } /// Goodreads' import columns, one row per book: Goodreads and StoryGraph take /// it, and so does Cotton's own `import_goodreads` (by Book Id). fn goodreads(laid: &[Laid]) -> String { let mut out = String::from("Book Id,Title,Author,ISBN,ISBN13,My Rating,Date Read,Date Added,Exclusive Shelf,My Review,Read Count\n"); let day = |row: &Row, column: &str| text(row, column).filter(|d| d.len() >= 10).map(|d| d[..10].replace('-', "/")).unwrap_or_default(); for book in laid { let row = book.row; let isbn = isbn(row); let shelf = match text(row, "status") { Some("reading") => "currently-reading", Some("finished") => "read", Some("stopped") => "dnf", _ => "to-read", }; let fields = [ text(row, "goodreads_id").unwrap_or_default().to_string(), text(row, "title").unwrap_or_default().to_string(), text(row, "author").unwrap_or_default().to_string(), isbn.clone().filter(|isbn| isbn.len() == 10).unwrap_or_default(), isbn.as_deref().and_then(isbn13).unwrap_or_default(), number(row, "rating").map(|r| plain_number(r.round())).unwrap_or_else(|| "0".into()), day(row, "finished_on"), day(row, "added_on"), shelf.to_string(), text(row, "review").unwrap_or_default().to_string(), number(row, "read_count").map(plain_number).unwrap_or_else(|| "0".into()), ]; out.push_str(&fields.iter().map(|field| csv(field)).collect::>().join(",")); out.push('\n'); } out } /// The parts of a highlight's Readium Locator the export speaks: the text /// around the passage and a PDF page. struct Located { before: Option, after: Option, page: Option, } fn located(row: &Row) -> Located { let locator: JsonValue = text(row, "locator").and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or(JsonValue::Null); let said = |pointer: &str| locator.pointer(pointer).and_then(JsonValue::as_str).filter(|s| !s.is_empty()).map(str::to_string); let page = locator .pointer("/locations/fragments") .and_then(JsonValue::as_array) .into_iter() .flatten() .filter_map(JsonValue::as_str) .chain(locator.get("href").and_then(JsonValue::as_str).and_then(|h| h.split_once('#')).map(|(_, f)| f)) .find_map(|fragment| fragment.strip_prefix("page=").map(str::to_string)); Located { before: said("/text/before"), after: said("/text/after"), page } } fn highlights_markdown(book: &Laid, list: &[&Row]) -> String { let mut out = format!("# {}\n\n", text(book.row, "title").unwrap_or("Untitled")); if let Some(author) = text(book.row, "author") { out.push_str(&format!("{author}\n\n")); } for highlight in list { for line in text(highlight, "text").unwrap_or_default().lines() { out.push_str(&format!("> {line}\n").replace("> \n", ">\n")); } out.push('\n'); if let Some(note) = text(highlight, "note") { out.push_str(&format!("{note}\n\n")); } let page = text(highlight, "page_label").map(|p| format!("p. {p}")); let place: Vec = [text(highlight, "chapter").map(str::to_string), page, text(highlight, "made_at").map(str::to_string)] .into_iter() .flatten() .collect(); if !place.is_empty() { out.push_str(&format!("— {}\n\n", place.join(" · "))); } } out } /// The highlights as a W3C Web Annotation collection: each a /// TextQuoteSelector on the book file beside it, and a page fragment for a PDF. fn annotations(book: &Laid, list: &[&Row]) -> JsonValue { let source = book.file.clone().unwrap_or_else(|| format!("urn:cotton:book:{}", book.id)); let items: Vec = list .iter() .map(|highlight| { let at = located(highlight); let mut quote = serde_json::Map::new(); quote.insert("type".into(), json!("TextQuoteSelector")); quote.insert("exact".into(), json!(text(highlight, "text").unwrap_or_default())); if let Some(before) = at.before { quote.insert("prefix".into(), json!(before)); } if let Some(after) = at.after { quote.insert("suffix".into(), json!(after)); } let mut selectors = vec![JsonValue::Object(quote)]; if let Some(page) = at.page { selectors.push(json!({ "type": "FragmentSelector", "conformsTo": "http://tools.ietf.org/rfc/rfc3778", "value": format!("page={page}") })); } let note = text(highlight, "note"); let mut annotation = serde_json::Map::new(); annotation.insert("id".into(), json!(format!("urn:cotton:highlight:{}", text(highlight, "id").unwrap_or_default()))); annotation.insert("type".into(), json!("Annotation")); annotation.insert("motivation".into(), json!(if note.is_some() { "commenting" } else { "highlighting" })); if let Some(made) = text(highlight, "made_at") { annotation.insert("created".into(), json!(made)); } if let Some(note) = note { annotation.insert("body".into(), json!({ "type": "TextualBody", "value": note, "format": "text/plain" })); } annotation.insert("target".into(), json!({ "source": source, "selector": selectors })); JsonValue::Object(annotation) }) .collect(); json!({ "@context": "http://www.w3.org/ns/anno.jsonld", "id": format!("urn:cotton:book:{}:highlights", book.id), "type": "AnnotationCollection", "label": text(book.row, "title").unwrap_or("Untitled"), "total": items.len(), "first": { "type": "AnnotationPage", "items": items }, }) }