//! Goodreads and StoryGraph CSV import. Every row is imported or listed with its reason; columns Liber does not //! map are kept on the book (`import_extra`) and named in the report. The CSV is hostile: the input and each field //! are capped, values are stored as text and never evaluated. use crate::library::{BookInfo, Field, Library, Outcome, Possession}; use crate::{MOODS, Op, isbn13, parse_date}; use serde::Serialize; use serde_json::json; use std::collections::{BTreeMap, BTreeSet}; pub const MAX_INPUT: usize = 32 * 1024 * 1024; pub const MAX_FIELD: usize = 64 * 1024; pub const MAX_ROWS: usize = 100_000; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum Source { Goodreads, StoryGraph, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Report { pub source: Source, pub rows: usize, pub imported: usize, /// (row number, 1-based after the header; why) pub skipped: Vec<(usize, String)>, /// Columns Liber does not know: their values are kept on each book. pub unknown_columns: Vec, /// Columns Liber knows but does not use (also kept on each book). pub unused_columns: Vec, /// (row, column) of fields cut at 64 KiB. pub truncated: Vec<(usize, String)>, } #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum ImportError { #[error("The file is larger than 32 MiB, which is too large for a reading-list export.")] TooLarge, #[error("This is not a Goodreads or StoryGraph export (the header is not one Liber knows).")] UnknownFormat, #[error("The file is not valid CSV: {0}")] Csv(String), #[error("The file has more than 100,000 rows.")] TooManyRows, } const GOODREADS_USED: &[&str] = &[ "Title", "Author", "Additional Authors", "ISBN", "ISBN13", "My Rating", "Publisher", "Binding", "Number of Pages", "Year Published", "Original Publication Year", "Date Read", "Date Added", "Bookshelves", "Exclusive Shelf", "My Review", "Private Notes", "Read Count", "Owned Copies", ]; const GOODREADS_UNUSED: &[&str] = &["Book Id", "Author l-f", "Average Rating", "Bookshelves with positions", "Spoiler"]; const STORYGRAPH_USED: &[&str] = &[ "Title", "Authors", "ISBN/UID", "Format", "Read Status", "Date Added", "Last Date Read", "Dates Read", "Read Count", "Moods", "Star Rating", "Review", "Tags", "Owned?", ]; const STORYGRAPH_UNUSED: &[&str] = &[ "Contributors", "Pace", "Character- or Plot-Driven?", "Strong Character Development?", "Loveable Characters?", "Diverse Characters?", "Flawed Characters?", "Content Warnings", "Content Warning Description", ]; /// Goodreads writes `="0441172717"` so spreadsheets keep leading zeros. fn unwrap_excel(s: &str) -> &str { s.trim().strip_prefix("=\"").and_then(|x| x.strip_suffix('"')).unwrap_or(s.trim()) } fn ms_of(date: &str) -> Option { let d = parse_date(date)?; let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?); let days = crate::days_from_civil(y, m, dd); (days >= 0).then(|| days as u64 * 86_400_000) } /// Goodreads reviews are HTML with `
`. fn review_text(s: &str) -> String { let s = s.replace("
", "\n").replace("
", "\n").replace("
", "\n"); let mut out = String::new(); let mut tag = false; for c in s.chars() { match c { '<' => tag = true, '>' if tag => tag = false, c if !tag => out.push(c), _ => {} } } out.trim().to_owned() } fn list(s: &str) -> Vec { s.split(',').map(|x| x.trim().to_owned()).filter(|x| !x.is_empty()).collect() } fn norm_key(title: &str, author: &str) -> String { let f = |s: &str| s.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect::(); format!("{}|{}", f(title), f(author)) } struct Row<'a> { cols: &'a [String], vals: Vec, } impl Row<'_> { fn get(&self, c: &str) -> &str { self.cols.iter().position(|x| x == c).and_then(|i| self.vals.get(i)).map(|s| s.trim()).unwrap_or("") } } /// Parses an export into events. `new_id` makes ids (books, reads); `now_ms` is the fallback "added" time. pub fn import_csv( bytes: &[u8], existing: &Library, new_id: &mut dyn FnMut() -> String, now_ms: u64, ) -> Result<(Vec, Report), ImportError> { if bytes.len() > MAX_INPUT { return Err(ImportError::TooLarge); } let (text, _) = liber_format::text::decode_text(bytes); let mut rdr = csv::ReaderBuilder::new().flexible(true).has_headers(true).from_reader(text.as_bytes()); let cols: Vec = rdr .headers() .map_err(|e| ImportError::Csv(e.to_string()))? .iter() .map(|h| h.trim().trim_start_matches('\u{feff}').to_owned()) .collect(); let has = |c: &str| cols.iter().any(|x| x == c); let source = if has("Exclusive Shelf") && has("Title") { Source::Goodreads } else if has("Read Status") && has("Title") { Source::StoryGraph } else { return Err(ImportError::UnknownFormat); }; let (used, unused) = match source { Source::Goodreads => (GOODREADS_USED, GOODREADS_UNUSED), Source::StoryGraph => (STORYGRAPH_USED, STORYGRAPH_UNUSED), }; let mut report = Report { source, rows: 0, imported: 0, skipped: vec![], unknown_columns: cols .iter() .filter(|c| !c.is_empty() && !used.contains(&c.as_str()) && !unused.contains(&c.as_str())) .cloned() .collect(), unused_columns: cols.iter().filter(|c| unused.contains(&c.as_str())).cloned().collect(), truncated: vec![], }; let mut seen: BTreeSet = existing .books .values() .map(|b| norm_key(&b.info.title, b.info.authors.first().map(String::as_str).unwrap_or(""))) .collect(); let mut seen_isbn: BTreeSet = existing.books.values().filter_map(|b| b.info.isbn13.clone()).collect(); let mut ops = Vec::new(); for (i, rec) in rdr.records().enumerate() { let n = i + 1; if n > MAX_ROWS { return Err(ImportError::TooManyRows); } report.rows += 1; let rec = match rec { Ok(r) => r, Err(e) => { report.skipped.push((n, format!("not valid CSV: {e}"))); continue; } }; let mut vals = Vec::with_capacity(rec.len()); for (ci, v) in rec.iter().enumerate() { if v.len() > MAX_FIELD { let mut end = MAX_FIELD; while !v.is_char_boundary(end) { end -= 1; } report.truncated.push((n, cols.get(ci).cloned().unwrap_or_default())); vals.push(v[..end].to_owned()); } else { vals.push(v.to_owned()); } } let row = Row { cols: &cols, vals }; let title = row.get("Title").to_owned(); if title.is_empty() { report.skipped.push((n, "no title".into())); continue; } let mut extra = BTreeMap::new(); for (ci, c) in cols.iter().enumerate() { if !used.contains(&c.as_str()) && !c.is_empty() { let v = row.vals.get(ci).map(|s| s.trim()).unwrap_or(""); if !v.is_empty() { let prefix = match source { Source::Goodreads => "goodreads", Source::StoryGraph => "storygraph", }; extra.insert(format!("{prefix}:{c}"), v.to_owned()); } } } let r = match source { Source::Goodreads => goodreads(&row, extra, now_ms), Source::StoryGraph => storygraph(&row, extra, now_ms), }; let author = r.info.authors.first().cloned().unwrap_or_default(); let key = norm_key(&r.info.title, &author); if r.info.isbn13.as_ref().is_some_and(|i| seen_isbn.contains(i)) || seen.contains(&key) { report.skipped.push((n, format!("“{}” is already in your library", r.info.title))); continue; } seen.insert(key); if let Some(i) = &r.info.isbn13 { seen_isbn.insert(i.clone()); } let book = new_id(); ops.push(Op::BookAdd { book: book.clone(), info: r.info, restore: false }); let set = |field: Field, value: serde_json::Value| Op::BookSet { book: book.clone(), field, value, base: None }; if let Some(rt) = r.rating { ops.push(set(Field::Rating, json!(rt))); } if !r.review.is_empty() { ops.push(set(Field::Review, json!(r.review))); } if !r.notes.is_empty() { ops.push(set(Field::Notes, json!(r.notes))); } if r.owned { ops.push(set(Field::Possession, serde_json::to_value(Possession::Owned).unwrap_or_default())); } if r.paper { ops.push(set(Field::Paper, json!(true))); } if !r.moods.is_empty() { ops.push(set(Field::Moods, json!(r.moods))); } if !r.tags.is_empty() { ops.push(set(Field::Tags, json!(r.tags))); } if r.to_read { ops.push(set(Field::ToRead, json!(true))); } for s in r.shelves { ops.push(Op::ShelfAdd { book: book.clone(), shelf: s }); } for (start, end, outcome) in r.reads { let read = new_id(); ops.push(Op::ReadStart { book: book.clone(), read: read.clone(), date: start }); if let Some(o) = outcome { ops.push(Op::ReadEnd { read, date: end, outcome: o }); } } report.imported += 1; } Ok((ops, report)) } struct Parsed { info: BookInfo, rating: Option, review: String, notes: String, owned: bool, paper: bool, moods: BTreeSet, tags: BTreeSet, to_read: bool, shelves: Vec, /// (started, finished, outcome) reads: Vec<(Option, Option, Option)>, } fn paper_binding(b: &str) -> bool { let b = b.to_lowercase(); ["paperback", "hardcover", "mass market", "hardback", "board book", "library binding", "leather", "spiral"] .iter() .any(|p| b.contains(p)) } fn goodreads(row: &Row, extra: BTreeMap, now_ms: u64) -> Parsed { let mut authors = vec![row.get("Author").to_owned()]; authors.extend(list(row.get("Additional Authors"))); authors.retain(|a| !a.is_empty()); let isbn = isbn13(unwrap_excel(row.get("ISBN13"))).or_else(|| isbn13(unwrap_excel(row.get("ISBN")))); let published = [row.get("Original Publication Year"), row.get("Year Published")] .iter() .find(|y| !y.is_empty()) .map(|y| y.to_string()); let rating: u8 = row.get("My Rating").parse().unwrap_or(0); let exclusive = row.get("Exclusive Shelf").to_owned(); let mut shelves: Vec = list(row.get("Bookshelves")) .into_iter() .filter(|s| !matches!(s.as_str(), "read" | "currently-reading" | "to-read")) .collect(); let read_count: usize = row.get("Read Count").parse().unwrap_or(0); let date_read = parse_date(row.get("Date Read")); let mut reads = Vec::new(); let mut to_read = false; match exclusive.as_str() { "read" => { for _ in 1..read_count.clamp(1, 50) { reads.push((None, None, Some(Outcome::Read))); } reads.push((None, date_read.clone(), Some(Outcome::Read))); } "currently-reading" => reads.push((None, None, None)), "to-read" => to_read = true, other if !other.is_empty() && !shelves.iter().any(|s| s == other) => { shelves.push(other.to_owned()); } _ => {} } Parsed { info: BookInfo { title: row.get("Title").to_owned(), authors, isbn13: isbn, publisher: Some(row.get("Publisher").to_owned()).filter(|s| !s.is_empty()), published, pages: row.get("Number of Pages").parse().ok().filter(|p| *p > 0), added: ms_of(row.get("Date Added")).unwrap_or(now_ms), import_extra: extra, ..BookInfo::default() }, rating: (1..=5).contains(&rating).then_some(rating * 2), review: review_text(row.get("My Review")), notes: row.get("Private Notes").to_owned(), owned: row.get("Owned Copies").parse::().unwrap_or(0) > 0, paper: paper_binding(row.get("Binding")), moods: BTreeSet::new(), tags: BTreeSet::new(), to_read, shelves, reads, } } fn storygraph(row: &Row, extra: BTreeMap, now_ms: u64) -> Parsed { let uid = row.get("ISBN/UID"); let star: f64 = row.get("Star Rating").parse().unwrap_or(0.0); let rating = (star > 0.0 && star <= 5.0).then(|| ((star * 2.0).round() as u8).clamp(1, 10)); let status = row.get("Read Status").to_lowercase(); let mut reads = Vec::new(); for range in list(row.get("Dates Read")) { let (a, b) = range.split_once('-').map(|(a, b)| (parse_date(a), parse_date(b))).unwrap_or((None, parse_date(&range))); reads.push((a, b, Some(Outcome::Read))); } let mut to_read = false; match status.as_str() { "read" if reads.is_empty() => { let n: usize = row.get("Read Count").parse().unwrap_or(1); for i in 0..n.clamp(1, 50) { let last = (i + 1 == n.max(1)).then(|| parse_date(row.get("Last Date Read"))).flatten(); reads.push((None, last, Some(Outcome::Read))); } } "read" => {} "currently-reading" | "paused" => reads.push((None, None, None)), "did-not-finish" => reads.push((None, parse_date(row.get("Last Date Read")), Some(Outcome::DidNotFinish))), "to-read" => to_read = true, _ => {} } let mut moods = BTreeSet::new(); let mut tags: BTreeSet = list(row.get("Tags")).into_iter().collect(); for m in list(row.get("Moods")) { let l = m.to_lowercase(); if MOODS.contains(&l.as_str()) { moods.insert(l); } else { tags.insert(m); } } let mut info = BookInfo { title: row.get("Title").to_owned(), authors: list(row.get("Authors")), isbn13: isbn13(uid), added: ms_of(row.get("Date Added")).unwrap_or(now_ms), import_extra: extra, ..BookInfo::default() }; if info.isbn13.is_none() && !uid.is_empty() { info.import_extra.insert("storygraph:ISBN/UID".into(), uid.to_owned()); } let format = row.get("Format").to_lowercase(); Parsed { info, rating, review: row.get("Review").to_owned(), notes: String::new(), owned: matches!(row.get("Owned?").to_lowercase().as_str(), "yes" | "true"), paper: format.contains("paperback") || format.contains("hardcover"), moods, tags, to_read, shelves: vec![], reads, } }