Cotton code
249 lines · 13.9 KB · RustRaw
//! A NOTE'S ATTACHED FILES, READ-ONLY (Words, 22 Nov 2026; CONTRACT.md//! section 15): the documents and films a note carries in `note_attachment`//! that are not its pictures (a picture is drawn in the text, `notes.rs`//! `text_of`). Until this, a web page, a Markdown file or a PDF an assistant//! attached to a note was dropped from `notes.open` and never shown.//!//! - `notes.open` answers `files`: each one's name, what it is (`format`, the//!   `documents` set's word), how it opens (`opens`: `page`, `note`, `pdf`,//!   `picture`, `elsewhere`, `cotton_core::rules::file_format`), its size, its//!   media key, and `here`: whether this copy holds its row.//! - Words' kit pulls only the web pages of `document` (its `only`), never//!   every PDF, so a Markdown file or a PDF a note attaches is not in the copy.//!   `notes.file { note, id }` fetches that one row from the object//!   (`GET /v1/rows`), opens it with the database's key, keeps it for this run,//!   and answers the file as `files` does, now `here`. Offline, or on an//!   object that cannot fetch rows yet, it refuses in Words' words.use std::collections::BTreeMap;use std::sync::{Mutex, OnceLock};use serde_json::{json, Map, Value};use cotton_core::rules::file_format::{FileFormat, Opens};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::rows as query_rows;use cotton_tools::mcp::handlers::records_1::notes as note_writes;use cotton_tools::mcp::read_db::Query;use super::notes::line;use crate::handle::CottonHandle;use crate::methods::MethodError;/// The most a file drawn on the phone (a page, a Markdown file) may weigh:/// the reader's ceiling, as a page's (`notes_assistant::PAGE_CEILING_BYTES`)./// A PDF or a picture is drawn a page at a time and has none.const READ_CEILING_BYTES: i64 = super::notes_assistant::PAGE_CEILING_BYTES;/// One attachment of a note that is not a picture, in the note's order.struct Attached {    kind: String,    id: String,    caption: Option<String>,}/// Rows fetched from the object this run, by `kind:id`: the copy does not keep/// them (the kit does not pull them), so a note opened again is not fetched again.fn fetched() -> &'static Mutex<BTreeMap<String, Map<String, Value>>> {    static FETCHED: OnceLock<Mutex<BTreeMap<String, Map<String, Value>>>> = OnceLock::new();    FETCHED.get_or_init(|| Mutex::new(BTreeMap::new()))}fn said(row: &Map<String, Value>, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty()).map(str::to_string)}fn number(row: &Map<String, Value>, key: &str) -> Option<i64> {    row.get(key).and_then(|value| value.as_i64().or_else(|| value.as_f64().map(|n| n as i64)))}/// The table and the store table a kind of attachment names.fn tables_of(kind: &str) -> Option<(&'static str, &'static str)> {    match kind {        "document" => Some(("document", "cotton_documents")),        "video" => Some(("video", "cotton_videos")),        _ => None,    }}fn attachments(ctx: &Ctx<'_>, note: &str) -> Vec<Attached> {    let mut found = query_rows(ctx, &Query::on(note_writes::ATTACHMENTS).columns(&["record_kind", "record_id", "position", "caption", "created_at"]).eq("note_id", note.to_string())).unwrap_or_default();    found.sort_by(|a, b| {        let place = |row: &Map<String, Value>| row.get("position").and_then(Value::as_f64).unwrap_or(0.0);        place(a).total_cmp(&place(b)).then_with(|| said(a, "created_at").cmp(&said(b, "created_at")))    });    found        .iter()        .filter_map(|row| {            let kind = said(row, "record_kind")?;            tables_of(&kind)?;            Some(Attached { kind, id: said(row, "record_id")?, caption: said(row, "caption") })        })        .collect()}/// The attached record's row: this copy's, else one fetched this run.fn row_of(ctx: &Ctx<'_>, attached: &Attached) -> Option<Map<String, Value>> {    let (_, store) = tables_of(&attached.kind)?;    let columns: &[&str] = if attached.kind == "video" {        &["id", "key", "content_type", "size_bytes", "original_filename", "caption", "trashed_at"]    } else {        &["id", "title", "original_name", "mime", "byte_size", "storage_path", "trashed_at"]    };    query_rows(ctx, &Query::on(store).columns(columns).eq("id", attached.id.clone()))        .ok()        .and_then(|rows| rows.into_iter().next())        .or_else(|| fetched().lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&format!("{}:{}", attached.kind, attached.id)).cloned())}/// One file as the phone draws its row and opens it.fn file_entry(attached: &Attached, row: Option<&Map<String, Value>>) -> Result<Value, MethodError> {    let formats = cotton_core::rules::shell_lines::LineSet::shipped("documents");    let video = attached.kind == "video";    let (name, mime, bytes, key) = match row {        Some(row) if video => (said(row, "original_filename").or_else(|| said(row, "caption")), said(row, "content_type"), number(row, "size_bytes"), said(row, "key")),        Some(row) => (said(row, "title").or_else(|| said(row, "original_name")), said(row, "mime"), number(row, "byte_size"), said(row, "storage_path")),        None => (None, None, None, None),    };    let ending_from = row.and_then(|row| said(row, if video { "original_filename" } else { "original_name" }));    let format = if video { FileFormat::of(mime.as_deref().or(Some("video/*")), ending_from.as_deref()) } else { FileFormat::of(mime.as_deref(), ending_from.as_deref().or(name.as_deref())) };    let opens = if row.is_none() { None } else { Some(format.map_or(Opens::Elsewhere, FileFormat::opens)) };    let format_word = match (row, format) {        (None, _) => line(if video { "files.film" } else { "files.document" }, &[])?,        (Some(_), Some(format)) => formats.as_ref().and_then(|lines| lines.say(format.line(), &[])).unwrap_or_default(),        (Some(_), None) => formats.as_ref().and_then(|lines| lines.say(FileFormat::UNKNOWN_LINE, &[])).unwrap_or_default(),    };    let size = bytes.filter(|n| *n > 0).map(|n| cotton_core::records::page::bytes_words(n as f64));    let name = attached.caption.clone().or(name).unwrap_or_else(|| format_word.clone());    let refused = match (row, &key, opens) {        (Some(_), None, _) => Some(line("files.no_file", &[])?),        (Some(_), Some(_), Some(Opens::Page | Opens::Note)) if bytes.is_some_and(|n| n > READ_CEILING_BYTES) => Some(line("files.too_big", &[])?),        _ => None,    };    let about = match &size {        Some(size) => line("files.about", &[("format", &format_word), ("size", size)])?,        None => format_word.clone(),    };    Ok(json!({        "id": attached.id,        "record": attached.kind,        "name": name,        "format": format_word,        "about": about,        "opens": opens.map(Opens::id),        "mime": mime,        "bytes": bytes,        "key": key,        "here": row.is_some(),        "refused": refused,        "label": line("files.open", &[("name", &name)])?,    }))}/// The note's files, in its order (`notes.open`'s `files`).pub(crate) fn files_of(ctx: &Ctx<'_>, note: &str) -> Result<Value, MethodError> {    let mut out = Vec::new();    for attached in attachments(ctx, note) {        let row = row_of(ctx, &attached);        // A file binned since it was attached is not offered.        if row.as_ref().is_some_and(|row| said(row, "trashed_at").is_some()) {            continue;        }        out.push(file_entry(&attached, row.as_ref())?);    }    Ok(Value::Array(out))}/// `notes.file { note, id }`: one file the note attaches, its row fetched from/// the object when this copy does not hold it, answered as `files` answers it.pub fn file(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let text = |key: &str| request.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty()).map(str::to_string);    let note = text("note").ok_or_else(|| super::notes::bad("this names the note: `note`"))?;    let id = text("id").ok_or_else(|| super::notes::bad("this names the file: `id`"))?;    // Only a file this note attaches is answered, here or fetched.    let held = super::notes::with_read(handle, "notes.file", |ctx| {        let attached = attachments(ctx, &note).into_iter().find(|attached| attached.id == id).ok_or_else(|| MethodError::new("not_found", line("files.not_attached", &[]).unwrap_or_default()))?;        let row = row_of(ctx, &attached);        Ok(json!({ "kind": attached.kind, "caption": attached.caption, "here": row.is_some(), "file": file_entry(&attached, row.as_ref())? }))    })?;    if held["here"].as_bool() == Some(true) {        return Ok(held["file"].clone());    }    let kind = held["kind"].as_str().unwrap_or_default().to_string();    let (table, _) = tables_of(&kind).ok_or_else(|| MethodError::new("not_found", line("files.not_attached", &[]).unwrap_or_default()))?;    let row = from_object(handle, table, &id)?;    fetched().lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(format!("{kind}:{id}"), row.clone());    let attached = Attached { kind, id, caption: held["caption"].as_str().map(str::to_string) };    file_entry(&attached, Some(&row))}/// One row of `table` from the object (`GET /v1/rows`), opened here with the database's key.fn from_object(handle: &CottonHandle, table: &str, id: &str) -> Result<Map<String, Value>, MethodError> {    let client = handle.client();    let offline = || MethodError::new("file_offline", line("files.offline", &[]).unwrap_or_default());    let database = client.current_database().map_err(|_| offline())?;    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    let sealer = cotton_client::seal::Sealer::new(database, keys);    let door = client.object_door().ok_or_else(offline)?;    let part = |value: &str| url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>();    let answer = door.send("GET", &format!("/v1/rows?table={}&ids={}", part(table), part(id)), None).map_err(|refused| {        tracing::warn!("notes.file: the object's {table} {id} did not come ({}: {})", refused.code, refused.message);        offline()    })?;    let stored = answer        .get("rows")        .and_then(Value::as_array)        .into_iter()        .flatten()        .find(|row| row.get("id").and_then(Value::as_str) == Some(id))        .and_then(|row| row.get("data").and_then(Value::as_object).cloned())        .ok_or_else(|| MethodError::new("not_found", line("files.gone", &[]).unwrap_or_default()))?;    let mut open = sealer.open(table, id, &stored).map_err(|error| {        tracing::warn!("notes.file: {table} {id} from the object did not open ({})", error.code());        MethodError::new("unreadable", line("files.offline", &[]).unwrap_or_default())    })?;    open.insert("id".into(), Value::from(id));    Ok(open)}/// `developer.inventNoteFiles { title, body, files: [{ path, mime, name }] }`: COTTON DEV ONLY: a note with invented/// files attached, as an assistant attaches them: each file kept as a document of this copy (its bytes in the media/// store, sent up as any capture's), then a note made by `create_note` naming them in order. Answers the note's/// `id` and the documents' ids. The real Cotton refuses it by name.pub fn invent(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    if handle.flavor() != cotton_core::flavor::Flavor::Dev {        return Err(MethodError::new("not_dev", "developer.inventNoteFiles answers only in Cotton Dev"));    }    let text = |row: &Value, key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string();    let client = handle.client();    let layout = client.layout().clone();    let device_key = client.self_device_id();    let mut ids = Vec::new();    for file in request.get("files").and_then(Value::as_array).cloned().unwrap_or_default() {        let args = super::media::validate_capture(&json!({ "path": text(&file, "path"), "mime": text(&file, "mime"), "kind": "document", "filename": text(&file, "name") }))?;        let answer = client.write_rows("developer.inventNoteFiles", &mut |ctx| super::media::write_media(ctx, &layout, &args, device_key.as_deref())).map_err(|reason| MethodError::new("capture_refused", reason))?;        let answer = crate::authoring::own_answer(answer);        ids.push(answer["recordId"].as_str().ok_or_else(|| MethodError::new("capture_refused", "no document for the file"))?.to_string());    }    let attachments: Vec<Value> = ids.iter().map(|id| json!({ "kind": "document", "id": id })).collect();    let made = super::notes::with_write(handle, "developer.inventNoteFiles", |ctx| {        let args = json!({ "title": text(request, "title"), "body": text(request, "body"), "attachments": attachments }).as_object().cloned().unwrap_or_default();        let made = cotton_tools::mcp::handlers::records_1::notes::create_note(ctx, &args).map_err(super::notes::tool)?;        // `away`: documents attached elsewhere (a Mac, an assistant) whose rows this copy never pulled.        let note = made["id"].as_str().unwrap_or_default().to_string();        let now = cotton_tools::mcp::handlers::common::now_iso(ctx);        for (at, away) in request.get("away").and_then(Value::as_array).cloned().unwrap_or_default().iter().enumerate() {            let Some(away) = away.as_str() else { continue };            let row = json!({ "note_id": note, "record_kind": "document", "record_id": away, "position": ids.len() + at, "created_at": now, "updated_at": now });            let key = cotton_store::protocol::derived_id::note_attachment_id(&note, "document", away);            cotton_tools::mcp::handlers::common::insert_row(ctx, note_writes::ATTACHMENTS, &key, row.as_object().cloned().unwrap_or_default()).map_err(super::notes::tool)?;        }        ctx.commit().map_err(super::notes::tool)?;        Ok(made)    })?;    Ok(json!({ "id": made["id"], "documents": ids }))}#[cfg(test)]#[path = "notes_files_tests.rs"]mod tests;