Cotton code
243 lines · 9.8 KB · RustRaw
//! The device and member page acts (Spec 10.4, Spec 11 (c); COORDINATOR//! 07:50Z): each act is ONE allow-listed method that already does the whole//! sequence (`devices.*`, `pairing.*`, `databases.invite|remove`); this adds//! the shared rules' answer to it — a `receipt` in words, and an `undo`//! naming the method and arguments that take the act back, or `undo: null`//! with `undoable: false` where nothing can (a removed device asks to join//! again; it is never re-admitted from here).//!//! The name a receipt says is read from the same authority the act writes to//! (`devices.list`, `read.members`) just before the act, so a phone and a//! serving Mac say the same words. A name that cannot be read makes the//! receipt plainer ("Renamed to Studio Mac"), never the act fail.//!//! Spec 9.3 adds the Settings acts that answered none: the two voice-word//! writes, which are each other's Undo.use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The acts this answers for. Every one is already on the method allow-list.pub const ACTS: [&str; 11] = [    "databases.invite",    "databases.remove",    "devices.approvePending",    "devices.declinePending",    "devices.rename",    "devices.revoke",    "members.admit",    "members.claimPerson",    "pairing.approve",    "settings.forgetVoiceTerm",    "settings.voiceTerm",];/// What was true before the act, for its receipt and its undo.#[derive(Debug, Default, Clone, PartialEq)]pub struct Before {    /// The device's or member's name as the page showed it.    pub name: Option<String>,    /// A voice word's `source` before it was forgotten, so its Undo adds it    /// back as the same kind of word.    pub source: Option<String>,}/// Run `call` (the act itself) and answer it with its receipt and undo.pub fn run(    handle: &CottonHandle,    method: &str,    request: &Value,    call: impl Fn(&str, &Value) -> Result<Value, MethodError>,) -> Result<Value, MethodError> {    if !ACTS.contains(&method) {        return call(method, request);    }    let args = crate::phone::read_args(request);    let before = before(handle, method, &args, &call);    let mut answer = call(method, request)?;    decorate(method, &args, &before, &mut answer);    Ok(answer)}fn text<'a>(args: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    args.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())}fn before(    handle: &CottonHandle,    method: &str,    args: &Map<String, Value>,    call: &impl Fn(&str, &Value) -> Result<Value, MethodError>,) -> Before {    if method == "settings.forgetVoiceTerm" {        // Read in the personal file: `methods::dispatch` already named it.        let row = text(args, "id").and_then(|id| {            handle                .client()                .with_file(|file| {                    file.driver                        .get(                            "SELECT term, source FROM cotton_voice_vocabulary WHERE id = ?",                            &[rusqlite::types::Value::Text(id.to_string())],                        )                        .map_err(|error| error.to_string())                })                .ok()                .flatten()        });        return Before {            name: row.as_ref().and_then(|row| row.text("term").map(str::to_string)),            source: row.as_ref().and_then(|row| row.text("source").map(str::to_string)),        };    }    Before { name: name_before(handle, method, args, call), source: None }}fn name_before(    handle: &CottonHandle,    method: &str,    args: &Map<String, Value>,    call: &impl Fn(&str, &Value) -> Result<Value, MethodError>,) -> Option<String> {    let scoped = |extra: Value| {        let mut request = extra;        if let Some(database) = args.get(crate::phone::databases::DATABASE) {            request[crate::phone::databases::DATABASE] = database.clone();        }        request    };    match method {        "devices.rename" | "devices.revoke" => {            let device = text(args, "deviceId")?;            let list = call("devices.list", &scoped(json!({}))).ok()?;            list.get("devices")?                .as_array()?                .iter()                .find(|row| row.get("deviceId").and_then(Value::as_str) == Some(device))                .and_then(|row| row.get("name")?.as_str().map(str::to_string))        }        "devices.approvePending"        | "pairing.approve"        | "members.admit"        | "devices.declinePending" => {            let pairing = text(args, "pairingId")?;            let pending = call("devices.pending", &scoped(json!({}))).ok()?;            pending                .get("pending")?                .as_array()?                .iter()                .find(|row| row.get("pairingId").or_else(|| row.get("id")).and_then(Value::as_str) == Some(pairing))                .and_then(pending_name)        }        "databases.remove" => {            let person = text(args, "personKey")?;            let members = crate::phone::read(handle, "read.members", &scoped(json!({}))).ok()?;            members                .get("members")?                .as_array()?                .iter()                .find(|row| row.get("personKey").and_then(Value::as_str) == Some(person))                .and_then(|row| row.get("name")?.as_str().map(str::to_string))        }        _ => None,    }}/// The receipt and undo for an act that ran. Pure, so each act's words are/// a guard of their own.pub fn decorate(method: &str, args: &Map<String, Value>, before: &Before, answer: &mut Value) {    if answer.get("pending") == Some(&Value::Bool(true)) { return; }    if !answer.is_object() {        *answer = json!({ "answer": answer.clone() });    }    let named = |fallback: &str| before.name.clone().unwrap_or_else(|| fallback.to_string());    let (receipt, undo) = match method {        "devices.rename" => {            let name = text(args, "name").unwrap_or_default().trim().to_string();            let undo = match (&before.name, text(args, "deviceId")) {                (Some(old), Some(device)) if *old != name => {                    let mut undo_args = json!({ "deviceId": device, "name": old });                    if let Some(database) = args.get(crate::phone::databases::DATABASE) {                        undo_args[crate::phone::databases::DATABASE] = database.clone();                    }                    json!({ "method": "devices.rename", "args": undo_args })                }                _ => Value::Null,            };            (format!("Renamed to {name}"), undo)        }        "devices.revoke" => {            let erase = args.get("erase").and_then(Value::as_bool) == Some(true);            let name = named("the device");            let words = if erase {                format!("Removed {name} and asked it to erase itself")            } else {                format!("Removed {name}")            };            (words, Value::Null)        }        "devices.approvePending" | "pairing.approve" | "members.admit" => {            let name = before                .name                .clone()                .or_else(|| answer.pointer("/device/name").and_then(Value::as_str).map(str::to_string))                .unwrap_or_else(|| "the device".to_string());            (format!("Admitted {name}"), Value::Null)        }        "devices.declinePending" => {            (format!("Turned away {}", named("the request")), Value::Null)        }        "members.claimPerson" => ("Linked you in this database".to_string(), Value::Null),        "databases.remove" => (            format!("Removed {} from this database", named("them")),            Value::Null,        ),        "databases.invite" => ("Invite ready to send".to_string(), Value::Null),        "settings.voiceTerm" => {            let term = answer.get("term").and_then(Value::as_str).unwrap_or_default().to_string();            let added = answer.get("added").and_then(Value::as_bool) == Some(true);            let changed = answer.get("changed").and_then(Value::as_bool) == Some(true);            match (added, changed, answer.get("id").and_then(Value::as_str)) {                (true, _, Some(id)) => (                    format!("Added {term} to your voice words"),                    json!({ "method": "settings.forgetVoiceTerm", "args": { "id": id } }),                ),                (false, true, _) => (format!("Kept {term} in your voice words"), Value::Null),                _ => (format!("{term} is already in your voice words"), Value::Null),            }        }        "settings.forgetVoiceTerm" => {            let removed = answer.get("removed").and_then(Value::as_bool) == Some(true);            match (&before.name, removed) {                (Some(term), true) => {                    let source = before.source.clone().unwrap_or_else(|| "manual".to_string());                    (                        format!("Removed {term} from your voice words"),                        json!({ "method": "settings.voiceTerm", "args": { "term": term, "source": source } }),                    )                }                (None, true) => ("Removed the word from your voice words".to_string(), Value::Null),                _ => ("That word was already gone from your voice words".to_string(), Value::Null),            }        }        _ => return,    };    answer["receipt"] = json!(receipt);    answer["undoable"] = json!(!undo.is_null());    answer["undo"] = undo;}/// RULE: A waiting row is named by the person asking to join when it carries one, else by its device.pub(crate) fn pending_name(row: &Value) -> Option<String> {    row.pointer("/person/name")        .and_then(Value::as_str)        .filter(|name| !name.trim().is_empty())        .or_else(|| row.get("name").and_then(Value::as_str))        .map(str::to_string)}#[cfg(test)]#[path = "page_acts_tests.rs"]mod tests;