Cotton code
160 lines · 8.4 KB · RustRaw
//! `asks.*` — the phone's half of an assistant's ask (ROUTES-AUDIT finding 8; the object's half is//! apps/business/src/owner_asks.ts). With token scopes on, an assistant's token that sends mail from the owner's//! domain, changes where an address forwards or invites guests to an event is kept waiting, and an `assistant_ask`//! row says what it would do. Every app pulls that table with the unlock tables (`rules::unlock::SHELL_TABLES`), so//! the card stands wherever the person is, beside the unlock card.//!//! - `asks.card {}` → `{ card, pollSeconds }`: the oldest waiting ask as the face draws it, or `card: null`://!   `{ askId, kind, heading, lines: [..], text, more, attachments: [..], allow: { label }, refuse: { label }, expiresAt }`.//!   A mail's card says everything Allow sends (8fa92ffb38): bcc among the lines, `text` the mail's words as the object//!   kept them (its first 4000 characters, else null), `more` "N more characters" when cut (else null), and//!   `attachments` one line per file (name, type, size). Every word is the `unlock` lines' (`asks.*`). `pollSeconds`//!   is 5 while one waits.//! - `asks.allow { askId }` → `{ state, said }`: the object runs the kept request once, as this device would.//! - `asks.refuse { askId }` → `{ state, said }`: dropped, never run.//!//! Refused by name: `not_connected` (no door), `ask_not_waiting` (already answered, or its time ran out).use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::unlock::{copy, lines_of, rows};use crate::shell::client::ClientController;pub const METHODS: [&str; 3] = ["asks.allow", "asks.card", "asks.refuse"];/// The copy keeps a served table under the `cotton_` prefix (the unlock tables' way: `unlock::REQUESTS`).const TABLE: &str = "cotton_assistant_ask";const POLL_SECONDS: u64 = 5;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_on(&handle.client(), method, request)}pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "asks.card" => card(client),        "asks.allow" => answer(client, request, "/v1/asks/allow"),        "asks.refuse" => answer(client, request, "/v1/asks/refuse"),        other => Err(MethodError::new("unknown_method", format!("{other} is not an asks method"))),    }}/// A column the copy keeps as a list: a JSON array, or its text.fn list_of(value: &Value) -> Vec<String> {    match value {        Value::Array(items) => items.iter().filter_map(Value::as_str).map(str::to_string).collect(),        Value::String(text) => serde_json::from_str::<Vec<String>>(text).unwrap_or_else(|_| if text.is_empty() { vec![] } else { vec![text.clone()] }),        _ => vec![],    }}fn text_of<'a>(row: &'a Value, key: &str) -> &'a str {    row.get(key).and_then(Value::as_str).unwrap_or_default()}/// The card for one waiting ask, in the `unlock` lines' words.pub(crate) fn card_of(row: &Value, lines: &cotton_core::rules::shell_lines::LineSet) -> Value {    let say = |line: &str, fills: &[(&str, &str)]| lines.say(&format!("asks.{line}"), fills).unwrap_or_default();    let client = Some(text_of(row, "client")).filter(|c| !c.is_empty()).unwrap_or("An assistant");    let kind = text_of(row, "kind");    let mut said: Vec<String> = Vec::new();    let (mut mail_text, mut more, mut attached): (Option<String>, Option<String>, Vec<String>) = (None, None, Vec::new());    match kind {        "mail_send" => {            said.push(say("mail_send.from", &[("from", text_of(row, "from"))]));            let mut to = list_of(row.get("to").unwrap_or(&Value::Null));            to.extend(list_of(row.get("cc").unwrap_or(&Value::Null)));            said.push(say("mail_send.to", &[("to", &to.join(", "))]));            let bcc = list_of(row.get("bcc").unwrap_or(&Value::Null));            if !bcc.is_empty() {                said.push(say("mail_send.bcc", &[("bcc", &bcc.join(", "))]));            }            if !text_of(row, "subject").is_empty() {                said.push(say("mail_send.subject", &[("subject", text_of(row, "subject"))]));            }            // AUDIT C 5 (8fa92ffb38): everything Allow sends stands on the card: the text the object kept (its head),            // how much more it holds when cut, and every attachment by name, type and size as the object wrote it.            let text = text_of(row, "text");            if !text.is_empty() {                mail_text = Some(text.to_string());                let whole = row.get("text_chars").and_then(Value::as_f64).unwrap_or(0.0) as i64;                let rest = whole - text.chars().count() as i64;                if rest > 0 {                    more = Some(say("mail_send.more", &[("n", &rest.to_string())]));                }            }            attached = list_of(row.get("attachments").unwrap_or(&Value::Null)).iter().map(|a| say("mail_send.attachment", &[("attachment", a)])).collect();        }        "mail_forward" => {            let forward = text_of(row, "forward_to");            said.push(if forward.is_empty() { say("mail_forward.stop", &[("address", text_of(row, "address"))]) } else { say("mail_forward.to", &[("address", text_of(row, "address")), ("forward_to", forward)]) });        }        _ => {            let count = row.get("count").and_then(Value::as_i64).unwrap_or(list_of(row.get("guests").unwrap_or(&Value::Null)).len() as i64);            said.push(say("guests.line", &[("title", text_of(row, "title")), ("count", &count.to_string())]));            let told = match row.get("notify") {                Some(Value::Bool(on)) => *on,                Some(Value::Number(n)) => n.as_i64() != Some(0),                _ => false,            };            if told {                said.push(say("guests.told", &[]));            }        }    }    let heading_key = match kind {        "mail_send" | "mail_forward" => format!("{kind}.heading"),        _ => "guests.heading".to_string(),    };    json!({        "askId": row.get("id").cloned().unwrap_or(Value::Null),        "kind": kind,        "heading": say(&heading_key, &[("client", client)]),        "lines": said,        "text": mail_text,        "more": more,        "attachments": attached,        "allow": { "label": say("allow", &[]) },        "refuse": { "label": say("refuse", &[]) },        "expiresAt": row.get("expires_at").cloned().unwrap_or(Value::Null),    })}fn card(client: &ClientController) -> Result<Value, MethodError> {    if client.require_personal().is_err() {        return Ok(json!({ "card": null, "pollSeconds": null }));    }    let (_, file) = copy(client)?;    let now = client.now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    let mut waiting: Vec<Value> = rows(&file, TABLE)?        .into_iter()        .filter(|r| text_of(r, "state") == "waiting" && text_of(r, "expires_at") > now.as_str())        .collect();    waiting.sort_by(|a, b| text_of(a, "asked_at").cmp(text_of(b, "asked_at")));    let Some(first) = waiting.first() else { return Ok(json!({ "card": null, "pollSeconds": null })) };    Ok(json!({ "card": card_of(first, &lines_of(client)?), "pollSeconds": POLL_SECONDS }))}fn answer(client: &ClientController, request: &Value, path: &str) -> Result<Value, MethodError> {    let ask = request.get("askId").and_then(Value::as_str).filter(|a| !a.is_empty()).ok_or_else(|| MethodError::new("bad_request", "askId names the ask"))?;    let lines = lines_of(client)?;    let say = |line: &str, fills: &[(&str, &str)]| lines.say(&format!("asks.{line}"), fills).unwrap_or_default();    let door = client.object_door().ok_or_else(|| MethodError::new("not_connected", "Not connected: try again when you're online."))?;    let answered = door.send("POST", path, Some(&json!({ "ask_id": ask }))).map_err(|error| if error.code == "ask_not_waiting" || error.code == "no_such_ask" { MethodError::new("ask_not_waiting", say("gone", &[])) } else { error })?;    client.nudge_sync();    let state = answered["state"].as_str().unwrap_or_default().to_string();    let said = match state.as_str() {        "done" => say("done", &[]),        "refused" => say("refused", &[]),        _ => {            let why = answered["answer"]["message"].as_str().or(answered["answer"].as_str()).unwrap_or("the request was refused").to_string();            say("failed", &[("why", &why)])        }    };    Ok(json!({ "state": state, "said": said }))}#[cfg(test)]#[path = "owner_asks_tests.rs"]mod tests;