Cotton code
501 lines · 23.1 KB · RustRaw
//! Books on this phone: what this device alone keeps of each book's file.//!//! A book's file is a media key in its database (`book.json`'s `file`,//! content-addressed); the reader opens the bytes from this device's media//! store. Keep on phone brings the bytes down and PINS their ledger row, so the//! budget pass (`cotton_client::media::evict`) never takes a kept book; Remove//! download is the one way a kept book leaves.//!//! - `books.here.read { key }` → `{ key, state }`//! - `books.here.write { key, state, from? }`: `keeping`, `kept`, or `null`//!   to clear. `kept` needs the bytes on this device; the pin follows `kept`.//!   `from` (with `kept` only) is the file a background download brought//!   down from the object's signed address (`media.stream`): it moves into//!   the store first (`media::adopt_download`).//! - `books.remove { key }` → `{ key, freed_bytes }`: unpin and take the one//!   file off this device (`cotton_client::media::storage::evict_one`), only//!   while the bucket holds its bytes.//!//! - `books.folder { files: [{ path, name }] }` → `{ books: [{ id, title,//!   outcome, why? }], skipped: [name], words }`: Add a folder. `path` is//!   where the shell staged each file of the picked tree, `name` its path in//!   the folder (`Author/Title (12)/metadata.opf`, `/` between parts).//!   `cotton_core::media::book_folder::walk_folder` reads it (a Calibre//!   folder from its `metadata.opf` and `cover.jpg` first, its file second),//!   and each book lands through `capture.media`'s own writer//!   (`media::capture_args`), so it is kept here and queued up for the object//!   exactly as Add files does. `outcome` is `added`, `already` (the same//!   file is a book here: one book, never a second) or `refused` with `why`;//!   `skipped` names each EPUB or PDF that came in as no book (unreadable, a//!   Calibre folder's second format, the same ISBN met earlier in the walk).//!   A folder holding no book is refused, with words.//!//! WHAT IS KEPT HERE NEVER SYNCS: a file is only on the phone that kept it.//! Where the person stopped reading is NOT kept here — it is the record's own//! `position`, a write that syncs, so another phone opens there. The file is//! `books-here.json` beside the client's other device-local files, as//! `episodes-here.json` is (`phone::episodes`).//!//! A book's record answers what this device keeps of it in one column,//! `on_phone` (`cotton_core::definitions::DEVICE_ANSWERED_COLUMNS`): `absent`//! for a book with a file that is not kept here, `keeping` while it comes//! down, `kept` once it opens with no network. Its acts (Keep on phone,//! Remove download) are offered by that column, and a list reads it//! ([`narrow_where`]).use std::collections::BTreeMap;use std::sync::{Mutex, MutexGuard};use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};use cotton_client::media::storage::EvictOneError;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 5] = ["books.here.due", "books.here.read", "books.here.write", "books.remove", "books.folder"];/// The device-local file, in the client's own folder.pub const FILE: &str = "books-here.json";/// The table whose records are books, and the column naming a book's bytes.pub const BOOK_TABLE: &str = "book";pub const FILE_COLUMN: &str = "file";/// What a book's record says of this device (`book.json`'s `on_phone`).pub use super::films::{KEEPING, KEPT, ON_PHONE};pub const ABSENT: &str = "absent";/// The flows a book's acts open (`book.json`, `settings.openFlow`): Keep on/// phone, Remove download, and Add file — the document picker for a book/// with no file, whose file the share sheet's intake gives it/// (`capture.media`'s `into`).pub const FLOWS: [&str; 3] = ["keepBook", "removeBookDownload", ADD_FILE];pub const ADD_FILE: &str = "addBookFile";/// What a list matches when this device keeps nothing: no book's file is/// ever this, since every media key is under its database's id.pub const NOTHING_KEPT: &str = "nothing-kept";fn flow_holds(flow: &str) -> &'static [&'static str] {    match flow {        "keepBook" => &[ABSENT],        "removeBookDownload" => &[KEEPING, KEPT],        _ => &[],    }}/// A book's flow comes only from a book's own record with a file, and only/// while what this device keeps of it says the act is there to take.pub(crate) fn flow_origin(client: &ClientController, flow: &str, table: &str, id: &str) -> Result<(), MethodError> {    if table != BOOK_TABLE {        return Err(MethodError::new("bad_request", "this flow comes only from a book's own record"));    }    let record = crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?;    if flow == ADD_FILE {        let held = record["data"][FILE_COLUMN].as_str().is_some_and(|key| !key.is_empty());        return if held { Err(MethodError::new("flow_refused", "this book has its file already")) } else { Ok(()) };    }    let on_phone = record["data"][ON_PHONE].as_str().unwrap_or_default();    if !flow_holds(flow).contains(&on_phone) {        return Err(MethodError::new("flow_refused", "this book is not one this act is for just now"));    }    Ok(())}static WRITE_LOCK: Mutex<()> = Mutex::new(());/// Each kept book's media key, and [`KEEPING`] or [`KEPT`].#[derive(Debug, Clone, Default, Serialize, Deserialize)]struct Stored {    #[serde(default)]    books: BTreeMap<String, String>,}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    match method {        "books.here.due" => due(&client),        "books.here.read" => read(&client, request),        "books.here.write" => write(&client, request),        "books.remove" => remove(&client, request),        "books.folder" => folder(&client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a books method"))),    }}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}/// The request's fields, none but `allowed`, and the book's media key.fn key_of<'a>(request: &'a Value, allowed: &[&str]) -> Result<&'a str, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("a books method takes an object"))?;    if fields.keys().any(|key| !allowed.contains(&key.as_str())) {        return Err(bad("a books method has an unknown field"));    }    fields        .get("key")        .and_then(Value::as_str)        .map(str::trim)        .filter(|key| !key.is_empty())        .ok_or_else(|| bad("a book is named by its file's key"))}/// Every book being read whose file this phone does not keep yet, whichever/// phone set it reading: each phone keeps them (the iPhone's sweep, Android's/// at launch). `{ keys: [file] }`, each file's media key once.fn due(client: &ClientController) -> Result<Value, MethodError> {    let listed = crate::phone::records::call(client, "records.list", &json!({"table": "book", "where": {"status": "reading", ON_PHONE: "absent"}}))?;    let mut keys: Vec<String> = Vec::new();    for row in listed["records"].as_array().into_iter().flatten() {        if let Some(file) = row["data"]["file"].as_str().map(str::trim).filter(|file| !file.is_empty()) {            if !keys.iter().any(|known| known == file) {                keys.push(file.to_string());            }        }    }    Ok(json!({ "keys": keys }))}fn read(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = key_of(request, &["key"])?;    let state = stored(client)?.books.remove(key);    Ok(json!({ "key": key, "state": state }))}fn write(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = key_of(request, &["key", "state", "from"])?.to_string();    let state = match request.get("state") {        None => return Err(bad("books.here.write names the state, or null")),        Some(Value::Null) => None,        Some(Value::String(state)) if state == KEEPING || state == KEPT => Some(state.clone()),        Some(_) => return Err(bad("a book is keeping or kept on this phone")),    };    let kept = state.as_deref() == Some(KEPT);    match request.get("from") {        None => {}        Some(Value::String(from)) if kept && !from.trim().is_empty() => {            super::media::adopt_download(client, &key, std::path::Path::new(from.trim()), super::media::Expected::Named)?;        }        Some(_) => return Err(bad("`from` is the downloaded file's path, given with kept")),    }    let now = iso_now(client)?;    // The pin follows `kept`, set under the writer so no budget pass takes the    // bytes between the look and the pin.    let workspace = client        .with_writer(|f| {            if kept && super::media::local_path_of(f.driver, &key).is_none() {                return Ok(Err(MethodError::new("not_here", "a book is kept only once its file is on this phone")));            }            cotton_store::media_ledger::set_media_pinned(f.driver, &key, kept, &now).map_err(|error| error.to_string())?;            Ok(Ok(f.workspace_id.to_string()))        })        .map_err(|reason| MethodError::new("unwritable", reason))??;    {        let _guard = write_lock();        let mut all = stored(client)?;        match &state {            Some(state) => all.books.insert(key.clone(), state.clone()),            None => all.books.remove(&key),        };        write_locked(client, &all)?;    }    // The card's acts and any list read by `on_phone` follow: the table reads again.    client.emit_data(&workspace, vec!["_media".into(), format!("cotton_{BOOK_TABLE}")], "local");    Ok(json!({ "key": key, "state": state }))}/// Add a folder: every book the walk finds in the staged tree, each landed by/// `capture.media`'s one writer.fn folder(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("books.folder takes an object"))?;    if fields.keys().any(|key| key != "files") {        return Err(bad("books.folder takes only `files`"));    }    let listed = fields.get("files").and_then(Value::as_array).ok_or_else(|| bad("books.folder names the folder's `files`: [{ path, name }]"))?;    let mut staged: BTreeMap<String, std::path::PathBuf> = BTreeMap::new();    for file in listed {        let words = |key: &str| file.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty());        let (Some(path), Some(name)) = (words("path"), words("name")) else {            return Err(bad("each of a folder's files is { path, name }: where it is staged, and its path in the folder"));        };        let name = name.trim_matches('/').replace('\\', "/");        if staged.insert(name.clone(), std::path::PathBuf::from(path)).is_some() {            return Err(bad(&format!("`{name}` is named twice in this folder")));        }    }    let names: Vec<String> = staged.keys().cloned().collect();    let walk = cotton_core::media::book_folder::walk_folder(        &names,        |name| staged.get(name).and_then(|path| std::fs::read(path).ok()),        |name| {            let trouble = || cotton_core::media::book_file::EpubTrouble::Unreadable(name.to_string());            let path = staged.get(name).ok_or_else(trouble)?;            let reader = super::whatsapp_import::FileRanges::open(path, name).map_err(|_| trouble())?;            cotton_core::media::book_file::read_epub(&reader)        },        // A book already here is found by its file (`already`), so the walk        // holds none back: a second run answers each book again.        &[],    );    let taken: std::collections::HashSet<&str> = walk.books.iter().map(|book| book.file.as_str()).collect();    let skipped: Vec<String> = names        .iter()        .filter(|name| !taken.contains(name.as_str()))        .filter(|name| name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("epub") || ext.eq_ignore_ascii_case("pdf")))        .cloned()        .collect();    if walk.books.is_empty() {        let mut why = "This folder holds no EPUB or PDF that could be read.".to_string();        if !skipped.is_empty() {            why.push_str(&format!(" {} came in as no book.", skipped.join(", ")));        }        return Err(MethodError::new("refused", why));    }    let mut books = Vec::with_capacity(walk.books.len());    for book in &walk.books {        let mut columns = book.columns();        let title = columns.remove("title").and_then(|title| title.as_str().map(str::to_string)).unwrap_or_else(|| book.file.clone());        let cover = match &book.cover {            None => None,            Some(cotton_core::media::book_folder::WalkedCover::Beside(name)) => staged.get(name).cloned().map(super::media::FolderCover::Staged),            Some(cotton_core::media::book_folder::WalkedCover::Inside(cover)) => Some(super::media::FolderCover::Read(cover.clone())),        };        let file_name = book.file.rsplit('/').next().unwrap_or(&book.file);        let landed = super::media::folder_book(&staged[&book.file], file_name, book.format, title.clone(), columns, cover)            .and_then(|mut args| super::media::capture_args(client, &mut args));        books.push(match landed {            Ok(answer) => {                let answer = answer.get("answer").unwrap_or(&answer);                let outcome = if answer["existing"].as_bool() == Some(true) { "already" } else { "added" };                json!({ "id": answer["recordId"], "title": title, "outcome": outcome })            }            Err(error) => json!({ "id": Value::Null, "title": title, "outcome": "refused", "why": error.message }),        });    }    let added = books.iter().filter(|book| book["outcome"] == "added").count();    let already = books.iter().filter(|book| book["outcome"] == "already").count();    let refused = books.len() - added - already;    let count = |n: usize| if n == 1 { "1 book".to_string() } else { format!("{n} books") };    let mut words = format!("Added {}.", count(added));    if already > 0 {        words.push_str(&format!(" {} {} here already.", count(already), if already == 1 { "was" } else { "were" }));    }    if refused > 0 {        words.push_str(&format!(" {} could not be added.", count(refused)));    }    if !skipped.is_empty() {        words.push_str(&format!(" {} came in as no book.", if skipped.len() == 1 { "1 file".to_string() } else { format!("{} files", skipped.len()) }));    }    Ok(json!({ "books": books, "skipped": skipped, "words": words }))}/// A book file this phone brought in (`capture.media`) is kept here: its/// bytes are on this phone already, so its reader never asks the object.pub(crate) fn keep_here(client: &ClientController, key: &str) -> Result<(), MethodError> {    write(client, &json!({ "key": key, "state": KEPT })).map(|_| ())}/// The books this phone keeps, named again under the keys `rekey` gives/// them (a local database adopted into its object: `<local>/books/…` is/// `<object>/books/…` now): a kept one is kept under its new key, its bytes/// pinned in the copy; one still coming down starts again when asked.pub(crate) fn rekey_here(client: &ClientController, rekey: &dyn Fn(&str) -> String) -> Result<(), MethodError> {    let held = stored(client)?;    let moved: Vec<(String, String, String)> = held        .books        .iter()        .map(|(key, state)| (key.clone(), rekey(key), state.clone()))        .filter(|(key, again, _)| key != again)        .collect();    if moved.is_empty() {        return Ok(());    }    {        let _guard = write_lock();        let mut all = stored(client)?;        for (key, _, _) in &moved {            all.books.remove(key);        }        write_locked(client, &all)?;    }    for (_, again, state) in moved {        if state == KEPT {            keep_here(client, &again)?;        }    }    Ok(())}/// Remove download: the one file leaves this device, its keep with it.fn remove(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = key_of(request, &["key"])?.to_string();    // A phone that has joined nothing has no bucket: nothing it holds is backed up.    let device = client.self_device_id().ok_or_else(not_backed_up)?;    let now = client.clock().now().timestamp_millis();    let mut ids = cotton_client::seams::op_ids(client.random());    let (workspace, freed) = client        .with_writer(|f| {            let freed = cotton_client::media::storage::evict_one(                f.driver,                f.workspace_id,                &device,                client.layout(),                &cotton_client::media::SystemEvictDisk,                &key,                now,                &mut ids,                super::storage::held(f),            );            Ok((f.workspace_id.to_string(), freed))        })        .map_err(|reason| MethodError::new("unwritable", reason))?;    let freed_bytes = freed.map_err(|error| match error {        EvictOneError::NotBackedUp => not_backed_up(),        EvictOneError::SharedFileKept(_) => MethodError::new("kept_by_another", "another record keeps this book's file on this phone"),        EvictOneError::OutsideMediaFolder => MethodError::new("refused", error.to_string()),        EvictOneError::Failed(why) => MethodError::new("unwritable", why),    })?;    {        let _guard = write_lock();        let mut all = stored(client)?;        if all.books.remove(&key).is_some() {            write_locked(client, &all)?;        }    }    client.emit_data(        &workspace,        vec!["_media".into(), "cotton_media_holdings".into(), format!("cotton_{BOOK_TABLE}")],        "local",    );    // The dropped hold is an op: it goes up.    client.nudge_sync();    Ok(json!({ "key": key, "freed_bytes": freed_bytes }))}fn not_backed_up() -> MethodError {    MethodError::new("not_backed_up", "This book's file has not synced yet, so it stays on this phone.")}fn iso_now(client: &ClientController) -> Result<String, MethodError> {    cotton_store::protocol::js::to_iso_string(client.clock().now().timestamp_millis())        .ok_or_else(|| MethodError::new("unwritable", "the clock is out of range"))}/// Fill `on_phone` on every book of a records answer whose file is named:/// what this device keeps of it, else `absent`. A book with no file is left/// without it, so no act of keeping is offered on it.pub(crate) fn answer_on_phone(client: &ClientController, answer: &mut Value) -> Result<(), MethodError> {    let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) {        Some(records) => records.iter_mut().collect(),        None => vec![answer],    };    let mut kept: Option<Stored> = None;    for record in records {        let data = match record.get_mut("data").and_then(Value::as_object_mut) {            Some(data) => data,            None => match record.as_object_mut() {                Some(data) if data.contains_key(FILE_COLUMN) => data,                _ => continue,            },        };        data.remove(ON_PHONE);        let Some(file) = data.get(FILE_COLUMN).and_then(Value::as_str).map(str::trim).filter(|file| !file.is_empty()) else { continue };        if kept.is_none() {            kept = Some(stored(client)?);        }        let state = kept.as_ref().and_then(|kept| kept.books.get(file)).cloned();        data.insert(ON_PHONE.to_string(), Value::from(state.unwrap_or_else(|| ABSENT.to_string())));    }    Ok(())}/// A list of books read by `where.on_phone`: the column is this device's/// answer, never stored, so the condition is read as the files this device/// keeps in those states. `absent` alone reads as every book with a file NOT/// keeping or kept here. Other tables, and a read that names no `on_phone`,/// pass unchanged.pub(crate) fn narrow_where(client: &ClientController, args: &mut Map<String, Value>) -> Result<(), MethodError> {    if args.get("table").and_then(Value::as_str) != Some(BOOK_TABLE) {        return Ok(());    }    let Some(conditions) = args.get_mut("where").and_then(Value::as_object_mut) else { return Ok(()) };    let Some(wanted) = conditions.remove(ON_PHONE) else { return Ok(()) };    let bad = || bad("on_phone reads absent, or keeping and kept");    let states: Vec<&str> = match &wanted {        Value::String(state) => vec![state.as_str()],        Value::Array(states) => states.iter().map(|state| state.as_str().ok_or_else(bad)).collect::<Result<_, _>>()?,        Value::Object(shape) => match shape.get("values").and_then(Value::as_array) {            Some(states) if shape.len() == 1 => states.iter().map(|state| state.as_str().ok_or_else(bad)).collect::<Result<_, _>>()?,            _ => return Err(bad()),        },        _ => return Err(bad()),    };    let stored = stored(client)?;    let keys = |held: &[&str]| -> Vec<Value> {        stored            .books            .iter()            .filter(|(_, state)| held.contains(&state.as_str()))            .map(|(key, _)| Value::from(key.as_str()))            .collect()    };    let condition = match states.as_slice() {        [ABSENT] => {            let held = keys(&[KEEPING, KEPT]);            if held.is_empty() {                json!({ "present": true })            } else {                json!({ "not": held })            }        }        states if !states.is_empty() && states.iter().all(|state| *state == KEEPING || *state == KEPT) => {            let held = keys(states);            Value::Array(if held.is_empty() { vec![Value::from(NOTHING_KEPT)] } else { held })        }        _ => return Err(bad()),    };    if conditions.contains_key(FILE_COLUMN) {        return Err(MethodError::new("bad_request", "a list reads on_phone or file, not both"));    }    conditions.insert(FILE_COLUMN.to_string(), condition);    Ok(())}fn path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(FILE)}fn stored(client: &ClientController) -> Result<Stored, MethodError> {    let path = path(client);    let bytes = match std::fs::read(&path) {        Ok(bytes) => bytes,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Stored::default()),        Err(error) => return Err(MethodError::new("unreadable", format!("{FILE}: {error}"))),    };    serde_json::from_slice(&bytes).map_err(|error| MethodError::new("unreadable", format!("{FILE} is not valid JSON: {error}")))}fn write_locked(client: &ClientController, all: &Stored) -> Result<(), MethodError> {    let path = path(client);    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    }    let partial = path.with_extension(format!("json.{}.partial", std::process::id()));    // not a copy: book files.    std::fs::write(&partial, serde_json::to_vec_pretty(all).expect("books serialise"))        .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    // not a copy: book files.    std::fs::rename(&partial, path).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))}pub(crate) fn write_lock() -> MutexGuard<'static, ()> {    WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())}#[cfg(test)]#[path = "books_tests.rs"]mod tests;