Cotton code
163 lines · 8.3 KB · RustRaw
//! Mail to Trash at the provider, for one sender (SENDERS.md "At the source"; coordinator,//! 23 Nov 2026). Blocking is People's (`chat.sender.act`); this is the one act on the owner's mail account itself.//!//! - `chat.mail.sender { address }` → `{ address, trash: { line, act? } }`, the clean-up as it stands. `act` is//!   `{ id, label }`, its id one of `count` (nothing asked yet, or asked again) and `confirm` (a count is in); with//!   none the Mac works. Every word is the `chat` lines' (`app.mail.sender.*`). People's long-press `trash` opens it.//! - `chat.mail.countSender { address }`: an outbox row (`channel: mail`, `kind: sender_count`) for the Mac, which//!   counts on the mail server and answers the row (crates/cotton-mac/src/mail/trash.rs).//! - `chat.mail.trashSender { address }`: the move, carrying what the last count fixed (`count`, `uid_validity`,//!   `uid_below`): only the mail he saw counted goes, in batches, and a stopped Mac goes on where it was.//!   Refused `not_counted` without a count, `nothing_to_move` at 0.use cotton_tools::mcp::handlers::tables;use super::*;pub(super) const OUTBOX: &str = "outbox";const CHANNEL: &str = "mail";const COUNT: &str = "sender_count";const TRASH: &str = "sender_trash";fn object(value: Value) -> Map<String, Value> {    match value {        Value::Object(map) => map,        _ => Map::new(),    }}fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> String {    failure.to_string()}fn address_of(request: &Value) -> Result<String, MethodError> {    let address = cotton_chat::text(request, "address")?.trim().to_lowercase();    let ok = address.split('@').count() == 2 && !address.starts_with('@') && !address.ends_with('@') && !address.chars().any(|c| c.is_whitespace() || matches!(c, '"' | '<' | '>' | ',' | ';'));    if ok {        Ok(address)    } else {        Err(MethodError::new("bad_address", say(&list::lines(), "app.mail.bad_address", &[])))    }}/// Whether this copy's outbox takes Mail to Trash: the served definition's `channel` offers `mail` and its `kind`/// both asks. A Worker not yet deployed with them serves the outbox of before, and nothing offers the act there.pub(crate) fn takes(ctx: &mut Ctx<'_>) -> Result<bool, String> {    let rows = cotton_tools::definitions::definition_rows(ctx, Some(OUTBOX)).map_err(|e| e.to_string())?;    Ok(rows.iter().any(|row| {        let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null);        let choices = |key: &str| -> Vec<String> {            definition["columns"]                .as_array()                .into_iter()                .flatten()                .filter(|c| c["key"] == key)                .flat_map(|c| c["choices"].as_array().into_iter().flatten())                .filter_map(|c| c.as_str().or_else(|| c["value"].as_str()).map(str::to_string))                .collect()        };        choices("channel").iter().any(|c| c == CHANNEL) && [COUNT, TRASH].iter().all(|k| choices("kind").iter().any(|c| c == k))    }))}/// The mail rows of the outbox about `address`, oldest first: (kind, its fields).fn asked(ctx: &mut Ctx<'_>, address: &str) -> Result<Vec<(String, Map<String, Value>)>, String> {    if !takes(ctx)? {        return Ok(Vec::new());    }    let listed = tables::list_records(ctx, &object(json!({ "table": OUTBOX, "where": { "to": address }, "limit": 500 }))).map_err(tool)?;    let mut out: Vec<(String, String, Map<String, Value>)> = Vec::new();    for record in listed["records"].as_array().cloned().unwrap_or_default() {        if record.get("deleted_at").is_some_and(|d| !d.is_null()) {            continue;        }        let data = object(if record["data"].is_object() { record["data"].clone() } else { record.clone() });        if data.get("channel").and_then(Value::as_str) != Some(CHANNEL) {            continue;        }        let kind = data.get("kind").and_then(Value::as_str).unwrap_or_default().to_string();        if kind != COUNT && kind != TRASH {            continue;        }        let at = record["created_at"].as_str().or(data.get("asked_at").and_then(Value::as_str)).unwrap_or_default().to_string();        out.push((at, kind, data));    }    out.sort_by(|a, b| a.0.cmp(&b.0));    Ok(out.into_iter().map(|(_, kind, data)| (kind, data)).collect())}fn number(data: &Map<String, Value>, key: &str) -> i64 {    data.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64))).unwrap_or(0)}fn status(data: &Map<String, Value>) -> &str {    data.get("status").and_then(Value::as_str).unwrap_or("queued")}/// The clean-up as the sender's page draws it, from the newest ask.fn trash_state(lines: &LineSet, address: &str, rows: &[(String, Map<String, Value>)]) -> Value {    let act = |id: &str, line: &str, fills: &[(&str, &str)]| json!({ "id": id, "label": say(lines, line, fills) });    let Some((kind, data)) = rows.last() else {        return json!({ "line": Value::Null, "act": act("count", "app.mail.sender.trash", &[]) });    };    let n = number(data, "count").to_string();    let error = data.get("error").and_then(Value::as_str).unwrap_or_default();    match (kind.as_str(), status(data)) {        (_, "failed") => json!({ "line": say(lines, "app.mail.sender.failed", &[("why", error)]), "act": act("count", "app.mail.sender.again", &[]) }),        (COUNT, "sent") if n == "0" => json!({ "line": say(lines, "app.mail.sender.none", &[("address", address)]), "act": act("count", "app.mail.sender.again", &[]) }),        (COUNT, "sent") => json!({ "line": say(lines, "app.mail.sender.counted", &[("n", &n), ("address", address)]), "act": act("confirm", "app.mail.sender.confirm", &[("n", &n)]) }),        (COUNT, _) => json!({ "line": say(lines, "app.mail.sender.counting", &[]) }),        (_, "sent") => json!({ "line": say(lines, "app.mail.sender.moved", &[("n", &number(data, "moved").to_string())]) }),        (_, "sending") => json!({ "line": say(lines, "app.mail.sender.moving", &[("moved", &number(data, "moved").to_string()), ("n", &n)]) }),        _ => json!({ "line": say(lines, "app.mail.sender.waiting", &[("n", &n)]) }),    }}pub(super) fn page(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let address = address_of(request)?;    let lines = list::lines();    let mut rows = Vec::new();    cotton_chat::read(client, "chat.mail.sender", |ctx| {        rows = asked(ctx, &address)?;        Ok(Value::Null)    })?;    Ok(json!({ "address": address, "trash": trash_state(&lines, &address, &rows) }))}pub(super) fn count(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let address = address_of(request)?;    cotton_chat::write(client, "chat.mail.countSender", |ctx| {        if !takes(ctx)? {            return Err(say(&list::lines(), "app.mail.sender.not_yet", &[]));        }        let made = tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": { "channel": CHANNEL, "kind": COUNT, "to": address, "status": "queued" } }))).map_err(tool)?;        Ok(made)    })?;    page(client, &json!({ "address": address }))}pub(super) fn trash(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let address = address_of(request)?;    let lines = list::lines();    let mut refused: Option<MethodError> = None;    cotton_chat::write(client, "chat.mail.trashSender", |ctx| {        let rows = asked(ctx, &address)?;        let Some((_, counted)) = rows.iter().rev().find(|(kind, data)| kind == COUNT && status(data) == "sent") else {            refused = Some(MethodError::new("not_counted", say(&lines, "app.mail.sender.not_counted", &[])));            return Ok(Value::Null);        };        if number(counted, "count") == 0 {            refused = Some(MethodError::new("nothing_to_move", say(&lines, "app.mail.sender.none", &[("address", &address)])));            return Ok(Value::Null);        }        let data = json!({            "channel": CHANNEL, "kind": TRASH, "to": address, "status": "queued", "moved": 0,            "count": counted.get("count"), "uid_validity": counted.get("uid_validity"), "uid_below": counted.get("uid_below"),        });        tables::create_produced_record(ctx, &object(json!({ "table": OUTBOX, "data": data }))).map_err(tool)    })?;    if let Some(error) = refused {        return Err(error);    }    page(client, &json!({ "address": address }))}