447 lines · 19.5 KB · RustRaw
//! THE BOOKS KIT'S ACTS, RUN ON THE PHONE (local-first, owner, 1 Nov 2026)://! a book's Start reading and Finished, and a Goodreads export brought in,//! write the phone's own copy and queue for the object like any write, signed//! in or not. The object holds the same acts for an assistant//! (apps/business/src/books.ts); these are the phone's, and agree with them//! act for act://!//! - `start_book { book }`: reading, started today; a finished book started//! again is a re-read, its finished day cleared. Refused while it is read.//! - `finish_book { book, rating? }`: finished today, one more reading//! counted, and the stars Finish asked for written as `rating` (out of 5 in//! half steps; Skip sends none). Refused once finished.//! - `import_goodreads { file }`: a Goodreads library export's CSV text, read//! by header name. Each book is found again by its Goodreads id, so a second//! import updates, never moving a book backwards or over what the owner set//! in Cotton; other shelves become lists of books, one per shelf name.//! Answers `{ books, made, updated, lists, first }`.//!//! TODAY is the phone's own day, in the zone the app opened the core with, as//! a book added from a file says its day (`phone::media`).use std::collections::BTreeMap;use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::tables;use cotton_tools::mcp::handlers::tables::groups;use crate::methods::MethodError;use crate::shell::client::ClientController;/// The acts this module runs, each in the phone's own copy.pub const ACTS: [&str; 3] = ["start_book", "finish_book", "import_goodreads"];const BOOK: &str = "book";/// One act, written in this phone's copy; the write queues for the object.pub fn run(client: &ClientController, name: &str, args: &Value) -> Result<Value, MethodError> { let zone = client .time_zone() .map(str::to_string) .ok_or_else(|| MethodError::new("bad_request", "this phone named no time zone, so a book's day cannot be said"))?; let args = args.as_object().cloned().unwrap_or_default(); let mut refusal: Option<MethodError> = None; let answer = client.write_rows(name, &mut |ctx| { let today = cotton_tools::mcp::handlers::common::today_in(&zone, cotton_tools::mcp::handlers::common::now_ms(ctx)).map_err(|failure| failure.to_string())?; let done = match name { "start_book" => start(ctx, &args, &today), "finish_book" => finish(ctx, &args, &today), "import_goodreads" => import(ctx, &args), other => Err(MethodError::new("bad_request", format!("`{other}` is not a book act this phone runs"))), }; done.map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); match (answer, refusal) { (Ok(answer), _) => Ok(crate::authoring::own_answer(answer)), (Err(_), Some(refused)) => Err(refused), (Err(why), None) => Err(MethodError::new("write_refused", why)), }}fn refuse(code: &str, why: impl Into<String>) -> MethodError { MethodError::new(code, why.into())}fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError { MethodError::new("write_refused", failure.to_string())}fn object(value: Value) -> Map<String, Value> { value.as_object().cloned().unwrap_or_default()}/// The named book's columns, or a refusal when there is none.fn live_book(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> Result<(String, Map<String, Value>), MethodError> { let id = args .get("book") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .ok_or_else(|| refuse("bad_args", "name the book: { book: <id> }"))?; let record = tables::get_record_by_table(ctx, &object(json!({"table": BOOK, "id": id}))) .map_err(|_| refuse("no_such_book", format!("no book with id {id}")))?; Ok((id.to_string(), object(record["data"].clone())))}fn update(ctx: &mut Ctx<'_>, id: &str, patch: Map<String, Value>, produced: bool) -> Result<(), MethodError> { let args = object(json!({"table": BOOK, "id": id, "patch": Value::Object(patch)})); if produced { tables::update_produced_record(ctx, &args) } else { tables::update_record(ctx, &args) }.map_err(tool)?; Ok(())}fn start(ctx: &mut Ctx<'_>, args: &Map<String, Value>, today: &str) -> Result<Value, MethodError> { let (id, data) = live_book(ctx, args)?; if data.get("status").and_then(Value::as_str) == Some("reading") { return Err(refuse("already_reading", "that book is being read already")); } let mut patch = Map::new(); patch.insert("status".into(), json!("reading")); patch.insert("started_on".into(), json!(today)); if data.get("status").and_then(Value::as_str) == Some("finished") { patch.insert("finished_on".into(), Value::Null); } update(ctx, &id, patch, false)?; Ok(json!({ "book": id }))}fn finish(ctx: &mut Ctx<'_>, args: &Map<String, Value>, today: &str) -> Result<Value, MethodError> { let (id, data) = live_book(ctx, args)?; if data.get("status").and_then(Value::as_str) == Some("finished") { return Err(refuse("already_finished", "that book is finished already; start it again to read it again")); } let count = data.get("read_count").and_then(Value::as_f64).unwrap_or(0.0); let mut patch = Map::new(); patch.insert("status".into(), json!("finished")); patch.insert("finished_on".into(), json!(today)); patch.insert("read_count".into(), number(count + 1.0)); // The stars Finish asked for; Skip sends none, and the rating stands. match args.get("rating") { None | Some(Value::Null) => {} Some(rating) => { let stars = rating.as_f64().filter(|n| (0.5..=5.0).contains(n) && (n * 2.0).fract() == 0.0).ok_or_else(|| refuse("bad_args", "a rating is out of 5 in half steps"))?; patch.insert("rating".into(), number(stars)); } } update(ctx, &id, patch, false)?; Ok(json!({ "book": id }))}/// A whole number as an integer, else as it is.fn number(n: f64) -> Value { if n.fract() == 0.0 && n.abs() < 1e15 { json!(n as i64) } else { json!(n) }}// ── import_goodreads ─────────────────────────────────────────────────────/// The headers an export must carry to be read as one.const NEEDED: [&str; 4] = ["Book Id", "Title", "Author", "Exclusive Shelf"];/// The three shelves every Goodreads library has, each a status, not a list.fn exclusive_status(shelf: &str) -> Option<&'static str> { match shelf { "to-read" => Some("want_to_read"), "currently-reading" => Some("reading"), "read" => Some("finished"), _ => None, }}/// RFC 4180 rows: quoted fields may hold commas, quotes ("") and line breaks;/// a CRLF or an LF ends a row; a blank line is no row.pub(crate) fn csv_rows(text: &str) -> Vec<Vec<String>> { let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut rows = Vec::new(); let mut row: Vec<String> = Vec::new(); let mut field = String::new(); let mut quoted = false; let mut chars = text.chars().peekable(); while let Some(ch) = chars.next() { if quoted { if ch == '"' && chars.peek() == Some(&'"') { field.push('"'); chars.next(); } else if ch == '"' { quoted = false; } else { field.push(ch); } } else if ch == '"' && field.is_empty() { quoted = true; } else if ch == ',' { row.push(std::mem::take(&mut field)); } else if ch == '\n' || ch == '\r' { if ch == '\r' && chars.peek() == Some(&'\n') { chars.next(); } row.push(std::mem::take(&mut field)); if row.iter().any(|f| !f.is_empty()) { rows.push(std::mem::take(&mut row)); } else { row.clear(); } } else { field.push(ch); } } row.push(field); if row.iter().any(|f| !f.is_empty()) { rows.push(row); } rows}fn digits(isbn: &str) -> String { isbn.chars().filter(|c| c.is_ascii_digit() || *c == 'X' || *c == 'x').collect::<String>().to_uppercase()}/// A Goodreads ISBN as written (`="0141439513"`), as its digits.pub(crate) fn isbn_of(cell: &str) -> String { let cell = cell.strip_prefix("=\"").or_else(|| cell.strip_prefix('=')).unwrap_or(cell); digits(cell.strip_suffix('"').unwrap_or(cell))}/// `yyyy/mm/dd` as `yyyy-mm-dd`; anything else is no date.fn day_of(cell: &str) -> Option<String> { let parts: Vec<&str> = cell.trim().split('/').collect(); match parts[..] { [y, m, d] if y.len() == 4 && m.len() == 2 && d.len() == 2 && [y, m, d].iter().all(|p| p.chars().all(|c| c.is_ascii_digit())) => Some(format!("{y}-{m}-{d}")), _ => None, }}/// A count or a rating, Goodreads' 0 meaning none.fn number_of(cell: &str) -> Option<Value> { let n: f64 = cell.trim().parse().ok()?; (n.is_finite() && n > 0.0).then(|| number(n))}fn text_of(cell: &str) -> Option<String> { let t = cell.trim(); (!t.is_empty()).then(|| t.to_string())}/// A review as Goodreads keeps it (HTML with `<br/>`), as plain text.fn review_of(cell: &str) -> Option<String> { let mut out = String::new(); let mut rest = cell; while let Some(at) = rest.find('<') { out.push_str(&rest[..at]); let tag_end = rest[at..].find('>').map(|end| at + end + 1); let Some(end) = tag_end else { out.push_str(&rest[at..]); rest = ""; break; }; let tag = rest[at + 1..end - 1].trim().trim_end_matches('/').trim().to_ascii_lowercase(); if tag == "br" { out.push('\n'); } rest = &rest[end..]; } out.push_str(rest); let out = out.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'"); text_of(&out)}/// One export row: the book's columns, and the shelves that are lists.#[derive(Debug, Clone, PartialEq)]pub(crate) struct GoodreadsBook { pub goodreads_id: String, pub data: Map<String, Value>, pub lists: Vec<String>,}/// The export's books, read by header name; a file that is not one is refused.pub(crate) fn read_export(text: &str) -> Result<Vec<GoodreadsBook>, MethodError> { let rows = csv_rows(text); let header: Vec<String> = rows.first().map(|row| row.iter().map(|h| h.trim().to_string()).collect()).unwrap_or_default(); let missing: Vec<&str> = NEEDED.iter().copied().filter(|h| !header.iter().any(|have| have == h)).collect(); if !missing.is_empty() { return Err(refuse("not_goodreads", format!("this is not a Goodreads library export: its first line names no {}", missing.join(", ")))); } let at = |name: &str| header.iter().position(|h| h == name); let mut books = Vec::new(); for cells in rows.iter().skip(1) { let cell = |name: &str| at(name).and_then(|i| cells.get(i)).map(String::as_str).unwrap_or(""); let id = cell("Book Id").trim().to_string(); let Some(title) = text_of(cell("Title")) else { continue }; if id.is_empty() { continue; } let exclusive_cell = cell("Exclusive Shelf").trim().to_string(); let exclusive = exclusive_cell.to_lowercase(); let shelves: Vec<String> = cell("Bookshelves") .split(',') .map(str::trim) .filter(|s| !s.is_empty() && exclusive_status(&s.to_lowercase()).is_none() && s.to_lowercase() != exclusive) .map(str::to_string) .collect(); let stopped = exclusive.contains("dnf") || shelves.iter().any(|s| s.to_lowercase().contains("dnf")); let status = if stopped { "stopped" } else { exclusive_status(&exclusive).unwrap_or("want_to_read") }; let mut lists: Vec<String> = Vec::new(); if !exclusive.is_empty() && exclusive_status(&exclusive).is_none() && !exclusive.contains("dnf") { lists.push(exclusive_cell.clone()); } for shelf in shelves.iter().filter(|s| !s.to_lowercase().contains("dnf")) { if !lists.contains(shelf) { lists.push(shelf.clone()); } } let isbn = Some(isbn_of(cell("ISBN13"))).filter(|i| !i.is_empty()).or_else(|| Some(isbn_of(cell("ISBN"))).filter(|i| !i.is_empty())); let year = [cell("Original Publication Year"), cell("Year Published")] .iter() .map(|y| y.trim()) .find(|y| !y.is_empty() && *y != "0" && y.trim_start_matches('-').chars().all(|c| c.is_ascii_digit()) && !y.trim_start_matches('-').is_empty()) .map(str::to_string); let mut data = Map::new(); let mut put = |key: &str, value: Option<Value>| { data.insert(key.to_string(), value.unwrap_or(Value::Null)); }; put("title", Some(json!(title))); put("author", text_of(cell("Author")).map(Value::from)); put("isbn", isbn.map(Value::from)); put("rating", number_of(cell("My Rating"))); put("review", review_of(cell("My Review")).map(Value::from)); put("added_on", day_of(cell("Date Added")).map(Value::from)); put("finished_on", day_of(cell("Date Read")).map(Value::from)); put("read_count", number_of(cell("Read Count"))); put("pages", number_of(cell("Number of Pages"))); put("year", year.map(Value::from)); put("status", Some(json!(status))); put("goodreads_id", Some(json!(id))); put("source", Some(json!("goodreads"))); books.push(GoodreadsBook { goodreads_id: id, data, lists }); } Ok(books)}/// How far along a book is; a status moves only up this order on a re-import.fn rank(status: Option<&str>) -> i32 { match status { Some("want_to_read") => 0, Some("reading") => 1, Some("stopped") => 2, Some("finished") => 3, _ => -1, }}/// Columns the owner keeps in Cotton: a re-import fills them only when empty.const OWNER_HELD: [&str; 7] = ["started_on", "finished_on", "position", "progress", "position_at", "rating", "review"];fn empty(value: Option<&Value>) -> bool { matches!(value, None | Some(Value::Null)) || value.and_then(Value::as_str) == Some("")}/// A re-import's patch: Goodreads' columns written over (one it leaves empty/// kept), the status moved only forward, the owner's filled only where empty.pub(crate) fn reimport_patch(held: &Map<String, Value>, file: &Map<String, Value>) -> Map<String, Value> { let held_status = held.get("status").and_then(Value::as_str); let file_status = file.get("status").and_then(Value::as_str); // A finish the file dates before the row's started_on is an earlier reading. let earlier = file_status == Some("finished") && matches!((held.get("started_on").and_then(Value::as_str), file.get("finished_on").and_then(Value::as_str)), (Some(started), Some(finished)) if finished < started); let status = if rank(file_status) > rank(held_status) && !earlier { file_status } else { held_status }; let mut patch = Map::new(); for (key, value) in file { if value.is_null() || key == "status" { continue; } if OWNER_HELD.contains(&key.as_str()) && !empty(held.get(key)) { continue; } if key == "finished_on" && status != Some("finished") { continue; } if held.get(key).unwrap_or(&Value::Null) != value { patch.insert(key.clone(), value.clone()); } } if status != held_status { if let Some(status) = status { patch.insert("status".into(), json!(status)); } } patch}/// The book holding this Goodreads id, its id and columns.fn held_by_goodreads(ctx: &mut Ctx<'_>, goodreads_id: &str) -> Result<Option<(String, Map<String, Value>)>, MethodError> { let listed = tables::list_records(ctx, &object(json!({"table": BOOK, "where": {"goodreads_id": goodreads_id}, "limit": 1}))).map_err(tool)?; Ok(listed["records"].as_array().and_then(|rows| rows.first()).and_then(|row| { Some((row["id"].as_str()?.to_string(), object(row["data"].clone()))) }))}fn import(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> Result<Value, MethodError> { let file = args .get("file") .and_then(Value::as_str) .filter(|file| !file.trim().is_empty()) .ok_or_else(|| refuse("bad_args", "import_goodreads takes the export's CSV text as file"))?; let books = read_export(file)?; let (mut made, mut updated, mut lists) = (0, 0, 0); let mut first_made: Option<String> = None; let mut first_found: Option<String> = None; // The book table's lists by name, as they stand before this import. let mut groups_by_name: BTreeMap<String, String> = BTreeMap::new(); let standing = groups::list_groups(ctx, &object(json!({"table": BOOK}))).map_err(tool)?; for group in standing["groups"].as_array().into_iter().flatten() { if let (Some(name), Some(id)) = (group["name"].as_str(), group["id"].as_str()) { groups_by_name.entry(name.to_string()).or_insert_with(|| id.to_string()); } } for book in &books { let id = match held_by_goodreads(ctx, &book.goodreads_id)? { Some((id, held)) => { let patch = reimport_patch(&held, &book.data); if !patch.is_empty() { update(ctx, &id, patch, true)?; updated += 1; } id } None => { let data: Map<String, Value> = book.data.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(); let written = tables::create_produced_record(ctx, &object(json!({"table": BOOK, "data": Value::Object(data)}))).map_err(tool)?; let id = written.pointer("/record/id").and_then(Value::as_str).map(str::to_string).ok_or_else(|| refuse("write_refused", "the book was made and named no id"))?; made += 1; first_made.get_or_insert_with(|| id.clone()); id } }; first_found.get_or_insert_with(|| id.clone()); for name in &book.lists { let group = match groups_by_name.get(name) { Some(group) => group.clone(), None => { let written = groups::create_group(ctx, &object(json!({"table": BOOK, "name": name, "records": [id]}))).map_err(tool)?; let group = written.pointer("/group/id").and_then(Value::as_str).map(str::to_string).ok_or_else(|| refuse("write_refused", "the list was made and named no id"))?; groups_by_name.insert(name.clone(), group); lists += 1; continue; } }; let holds = groups::list_groups(ctx, &object(json!({"table": BOOK, "record": id}))).map_err(tool)?; let held = holds["groups"].as_array().into_iter().flatten().any(|g| g["id"].as_str() == Some(group.as_str()) && g["holds"] == json!(true)); if !held { groups::update_group(ctx, &object(json!({"id": group, "add": [id]}))).map_err(tool)?; } } } let mut answer = json!({ "books": books.len(), "made": made, "updated": updated, "lists": lists }); if let Some(first) = first_made.or(first_found) { answer["first"] = json!(first); } Ok(answer)}#[cfg(test)]#[path = "book_acts_tests.rs"]mod tests;