Cotton code
465 lines · 24.8 KB · RustRaw
//! SMS on Android (DECISIONS "SMS on Android", CONTRACT "SMS on Android"; owner via the coordinator, 24 Nov 2026).//! Comms holds Android's SMS role only when he gives it. The phone reads the texts and the core lands them in his own//! copy, so they go up sealed like every chat. The phone sends what the core queues and says how each send went.//!//! ```text//! chat.sms.here   { held }                                    → { held, stale }//! chat.sms.land   { texts: [{ from, number?, body, at, out, live?, failed?, mms? }] } → { landed, already, threads }//! chat.sms.outbox {}                                          → { texts: [{ id, to, body, at }] }//! chat.sms.sent   { id, ok, why? }                            → { state }//! ```//!//! - `from` is the address as Android's store holds it; `number` is the phone's own E.164 reading of it (Android knows//!   the SIM's country), absent for a sender with a name ("JD-HDFCBK") or a short code.//! - `at` is the text's time in ms, exactly as the phone writes it to Android's store, so a text read again from the//!   store is the one landed before (`external_id` is made from who, when, which way and the words).//! - `live` is a text that arrived or was sent just now: unread until read, and it notifies. A text from the history//!   is read and never notifies.use std::collections::{BTreeMap, BTreeSet, HashSet};use std::sync::Mutex;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use super::cotton_chat::{iso, namespace, now_ms, one, rows, touch_thread, write, ws, CONTACTS, MESSAGES, THREADS};use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};/// The channel's name on every row.pub(crate) const CHANNEL: &str = "sms";/// A thread's key: `sms:` and the sender's key ([`key_of`]).pub(crate) const SMS_PREFIX: &str = "sms:";/// The most texts one landing takes; the phone sends the history in pieces this size.pub const BATCH_MAX: usize = 1_000;/// A text handed to the phone to send whose answer never came (the app was closed mid-send) is told failed after/// this long, never sent again by itself: a second copy would reach the person.pub const SENDING_STALE_MS: i64 = 120_000;/// The copies (by workspace) on this phone whose app holds Android's SMS role, as the phone last said/// (`chat.sms.here`): it says so at every start and whenever it changes. Kept in memory only, since it is this phone's/// and no other's. Elsewhere (an iPhone) it is never said, so there SMS chats read only.static HELD: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());pub(crate) fn held(ctx: &Ctx<'_>) -> bool {    let ws = ctx.workspace_id.to_string();    HELD.lock().map(|held| held.contains(&ws)).unwrap_or(false)}pub fn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.sms.here" => here(client, request),        "chat.sms.land" => land(client, request),        "chat.sms.outbox" => outbox(client),        "chat.sms.sent" => sent(client, request),        _ => Err(MethodError::new("unknown_method", method.to_string())),    }}/// Who a text is with: the thread's key, the contact's digits where it is a phone number, and a sender's own name./// A number is its E.164 (`+919876543210`). A sender with a name keeps only the name after Indian operators' two-letter/// prefix ("JD-HDFCBK", "VM-HDFCBK-S" → "HDFCBK"), so one bank is one chat. Anything else (a short code) as written.pub(crate) fn key_of(from: &str, number: Option<&str>) -> Option<(String, Option<String>, Option<String>)> {    if let Some(number) = number.map(str::trim).filter(|n| n.starts_with('+')) {        let figures: String = number.chars().filter(char::is_ascii_digit).collect();        if (8..=15).contains(&figures.len()) {            return Some((format!("+{figures}"), Some(figures), None));        }    }    let from = from.trim();    if from.is_empty() {        return None;    }    let parts: Vec<&str> = from.split('-').collect();    let named = |p: &str| p.len() >= 3 && p.len() <= 11 && p.chars().all(|c| c.is_ascii_alphanumeric()) && p.chars().any(|c| c.is_ascii_alphabetic());    let name = match parts.as_slice() {        [prefix, name] | [prefix, name, _] if prefix.len() == 2 && prefix.chars().all(|c| c.is_ascii_alphabetic()) && named(name) => Some(name.to_ascii_uppercase()),        [name] if named(name) => Some(name.to_ascii_uppercase()),        _ => None,    };    if let Some(name) = name {        return Some((name.clone(), None, Some(name)));    }    let figures: String = from.chars().filter(char::is_ascii_digit).collect();    if figures.is_empty() {        return Some((from.to_string(), None, Some(from.to_string())));    }    if from.starts_with('+') && (8..=15).contains(&figures.len()) {        return Some((format!("+{figures}"), Some(figures), None));    }    // A short code, or a local number the phone could not read as E.164: kept as its figures, named by them.    Some((figures.clone(), None, Some(figures)))}/// One text's id outside Cotton: the same text read twice (or from two of his phones) is one row.pub(crate) fn external_of(key: &str, at: i64, out: bool, body: &str) -> String {    let mut h = Sha256::new();    h.update(key.as_bytes());    h.update(b"\x1f");    h.update(at.to_string().as_bytes());    h.update(if out { b"\x1fout\x1f" } else { b"\x1fin\x1f\x1f" });    h.update(body.as_bytes());    format!("sms-{}", &hex::encode(h.finalize())[..24])}fn derived(table: &str, ns: &str, part: &str) -> String {    cotton_core::cotton_rules::ids::derived_id(table, &[ns, CHANNEL, part])}/// The texts' number for a thread written to: the key of an SMS thread when texts can go to it (a number or a short/// code, never a sender's name).pub(crate) fn to_of(external_key: &str) -> Option<String> {    let key = external_key.strip_prefix(SMS_PREFIX)?;    let digits = key.strip_prefix('+').unwrap_or(key);    (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit())).then(|| key.to_string())}fn here(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let held = request.get("held").and_then(Value::as_bool).ok_or_else(|| MethodError::new("bad_request", "held: whether Comms holds the SMS role"))?;    // A text handed out to send whose answer never came: failed, so he sees it and chooses Retry.    let before = now_ms(client) - SENDING_STALE_MS;    let stale = write(client, "chat.sms.here", move |ctx| {        if let Ok(mut all) = HELD.lock() {            let ws = ctx.workspace_id.to_string();            if held {                all.insert(ws);            } else {                all.remove(&ws);            }        }        let found = rows(            ctx,            &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND channel = 'sms' AND direction = 'out' AND send_state = 'sending' AND coalesce(json_extract(meta, '$.sms.handed'), 0) < ? AND trashed_at IS NULL"),            &[ws(ctx), SqlValue::Integer(before)],        )?;        for row in &found {            let mut patch = Map::new();            patch.insert("send_state".into(), json!("failed"));            patch.insert("send_error".into(), json!("unknown"));            update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?;        }        // The role gone: a text he chose and that waits to go is not sent later, when the role may come back without        // him thinking of it; it fails, saying why, and Retry is his (DISCOVERY OFF 3).        if !held {            let queued = rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND channel = 'sms' AND direction = 'out' AND send_state = 'queued' AND trashed_at IS NULL"), &[ws(ctx)])?;            for row in &queued {                let mut patch = Map::new();                patch.insert("send_state".into(), json!("failed"));                patch.insert("send_error".into(), json!("no_role"));                update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?;            }        }        Ok(json!(found.len()))    })?;    Ok(json!({ "held": held, "stale": stale }))}/// The contact and thread for one sender, made once: a number already in his chats (WhatsApp's, Cotton's) keeps its/// contact, so its name and picture; a sender with a name is a contact with no number. The store keeps one chat per/// contact (`uq_cotton_msg_threads_dm`), so a contact that already has one (a Cotton chat waiting for them to accept,/// a WhatsApp chat) takes its texts there, as `ensure_thread` does (DISCOVERY OFF 3 H1): never a second chat.fn thread_for(ctx: &mut Ctx<'_>, ns: &str, address: &str, digits: Option<&str>, name: Option<&str>) -> Result<String, String> {    let thread = derived(THREADS, ns, address);    if one(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.clone())])?.is_some() {        return Ok(thread);    }    let existing = match digits {        Some(digits) => one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.to_string())])?,        None => None,    };    let contact = match existing.and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string)) {        Some(id) => {            let chat = one(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND contact_id = ? AND kind = 'dm' LIMIT 1"), &[ws(ctx), SqlValue::Text(id.clone())])?;            if let Some(found) = chat.and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string)) {                return Ok(found);            }            id        }        None => {            let id = derived(CONTACTS, ns, address);            if one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.is_none() {                let mut columns = Map::new();                columns.insert("phone_e164".into(), digits.map_or(Value::Null, |d| json!(d)));                if let Some(name) = name {                    columns.insert("display_name".into(), json!(name));                }                insert_row(ctx, CONTACTS, &id, columns).map_err(|f| f.to_string())?;            }            id        }    };    if let Some(digits) = digits {        crate::phone::cotton_chat::contact_handle_here(ctx, ns, &contact, digits)?;    }    let mut columns = Map::new();    columns.insert("contact_id".into(), json!(contact));    columns.insert("kind".into(), json!("dm"));    columns.insert("external_key".into(), json!(format!("{SMS_PREFIX}{address}")));    columns.insert("archived".into(), json!(false));    columns.insert("read_seq".into(), json!(0));    if let Some(name) = name {        columns.insert("title".into(), json!(name));    }    insert_row(ctx, THREADS, &thread, columns).map_err(|f| f.to_string())?;    Ok(thread)}struct Text {    key: String,    digits: Option<String>,    name: Option<String>,    body: String,    at: i64,    out: bool,    live: bool,    failed: bool,    mms: bool,}fn land(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let given = request.get("texts").and_then(Value::as_array).ok_or_else(|| MethodError::new("bad_request", "texts: the texts to land"))?;    if given.len() > BATCH_MAX {        return Err(MethodError::new("too_many", format!("at most {BATCH_MAX} texts a call")));    }    let texts: Vec<Text> = given        .iter()        .filter_map(|t| {            let (key, digits, name) = key_of(t["from"].as_str().unwrap_or_default(), t["number"].as_str())?;            Some(Text {                key,                digits,                name,                body: t["body"].as_str().unwrap_or_default().to_string(),                at: t["at"].as_i64()?,                out: t["out"].as_bool().unwrap_or(false),                live: t["live"].as_bool().unwrap_or(false),                failed: t["failed"].as_bool().unwrap_or(false),                mms: t["mms"].as_bool().unwrap_or(false),            })        })        .collect();    let ns = namespace(client)?;    // A picture message Comms cannot open yet says so in its chat rather than vanishing.    let mms_words = cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "app.sms.mms", &[]);    let landed = write(client, "chat.sms.land", move |ctx| {        let mut threads: BTreeMap<String, String> = BTreeMap::new();        let mut newest: BTreeMap<String, (i64, String)> = BTreeMap::new();        let (mut landed, mut already) = (0usize, 0usize);        let mut seen: HashSet<String> = HashSet::new();        let mut skipped = 0usize;        for t in &texts {            // One sender's text that cannot land never fails the others in the batch: it is skipped and counted in            // `skipped` (the phone logs it), and everyone else's texts land (DISCOVERY OFF 3 H1).            let thread = match threads.get(&t.key) {                Some(id) => id.clone(),                None => match thread_for(ctx, &ns, &t.key, t.digits.as_deref(), t.name.as_deref()) {                    Ok(id) => {                        threads.insert(t.key.clone(), id.clone());                        id                    }                    Err(_) => {                        skipped += 1;                        continue;                    }                },            };            let external = external_of(&t.key, t.at, t.out, &t.body);            let id = derived(MESSAGES, &ns, &external);            // Landed before, or erased since (Delete everything, Blocked's 30 days): its marker stands, so it never comes back.            let marker = cotton_core::chat::ids::erased_marker_id(&thread, CHANNEL, &external);            let held = |ctx: &mut Ctx<'_>, id: &str| -> Result<bool, String> { Ok(one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.to_string())])?.is_some()) };            if !seen.insert(id.clone()) || held(ctx, &id)? || held(ctx, &marker)? {                already += 1;                continue;            }            let at = iso(t.at);            let mut columns = Map::new();            columns.insert("thread_id".into(), json!(thread));            columns.insert("direction".into(), json!(if t.out { "out" } else { "in" }));            columns.insert("channel".into(), json!(CHANNEL));            columns.insert("origin".into(), json!(if t.live { "live" } else { "imported" }));            columns.insert("body".into(), json!(if t.mms && t.body.trim().is_empty() { mms_words.clone() } else { t.body.clone() }));            columns.insert("sent_at".into(), json!(at));            columns.insert("external_id".into(), json!(external));            if t.out {                columns.insert("send_state".into(), json!(if t.failed { "failed" } else { "sent" }));            }            if !t.live || t.out {                columns.insert("read_at".into(), json!(at));            }            if t.mms {                columns.insert("meta".into(), json!({ "sms": { "mms": true } }));            }            if insert_row(ctx, MESSAGES, &id, columns).is_err() {                skipped += 1;                continue;            }            landed += 1;            let preview = if t.body.trim().is_empty() && t.mms { mms_words.clone() } else { t.body.clone() };            if newest.get(&thread).is_none_or(|(n, _)| *n < t.at) {                newest.insert(thread.clone(), (t.at, preview));            }        }        for (thread, (at, body)) in &newest {            touch_thread(ctx, thread, &iso(*at), Some(body), false)?;        }        Ok(json!({ "landed": landed, "already": already, "skipped": skipped, "threads": threads.values().collect::<HashSet<_>>().into_iter().collect::<Vec<_>>() }))    })?;    Ok(landed)}/// The SMS chat with a number already here, on the phone holding the role and not linked to WhatsApp through the Mac:/// never made (DISCOVERY OFF 2: a new chat with a number this phone does not know is a Cotton chat that asks them).pub(crate) fn existing(client: &ClientController, number: &str) -> Result<Option<String>, MethodError> {    let Some((key, _, _)) = key_of(number, Some(number)) else { return Ok(None) };    let ns = namespace(client)?;    let found = super::cotton_chat::read(client, "chat.sms.existing", move |ctx| {        if !held(ctx) || super::chat_app::whatsapp_send::link(ctx)?.is_some() {            return Ok(Value::Null);        }        let thread = derived(THREADS, &ns, &key);        Ok(one(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone())])?.map_or(Value::Null, |_| json!(thread)))    })?;    Ok(found.as_str().map(str::to_string))}/// Whether this phone holds Android's SMS role for this copy and the copy is not linked to WhatsApp through the Mac:/// where a text can be the person's own choice.pub(crate) fn texts_here(client: &ClientController) -> Result<bool, MethodError> {    let found = super::cotton_chat::read(client, "chat.sms.texts_here", |ctx| Ok((held(ctx) && super::chat_app::whatsapp_send::link(ctx)?.is_none()).into()))?;    Ok(found == json!(true))}/// A text written in an SMS chat on the phone holding the role: one message row, waiting for the phone to send it.pub(crate) fn queue(ctx: &mut Ctx<'_>, ns: &str, thread: &str, to: &str, body: &str, at: i64) -> Result<String, String> {    let external = external_of(to, at, true, body);    let id = derived(MESSAGES, ns, &external);    let when = iso(at);    let mut columns = Map::new();    columns.insert("thread_id".into(), json!(thread));    columns.insert("direction".into(), json!("out"));    columns.insert("channel".into(), json!(CHANNEL));    columns.insert("origin".into(), json!("live"));    columns.insert("body".into(), json!(body));    columns.insert("sent_at".into(), json!(when));    columns.insert("read_at".into(), json!(when));    columns.insert("external_id".into(), json!(external));    columns.insert("send_state".into(), json!("queued"));    columns.insert("send_attempts".into(), json!(0));    insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?;    touch_thread(ctx, thread, &when, Some(body), false)?;    Ok(id)}/// What waits to be sent, each handed out once: marked sending in the same write, so a second pass never sends it again.fn outbox(client: &ClientController) -> Result<Value, MethodError> {    let handed = now_ms(client);    write(client, "chat.sms.outbox", move |ctx| {        if !held(ctx) {            return Ok(json!({ "texts": [] }));        }        let found = rows(            ctx,            &format!(                "SELECT m.id, m.body, m.sent_at, t.external_key FROM {MESSAGES} m JOIN {THREADS} t ON t.id = m.thread_id                 WHERE m.workspace_id = ? AND m.channel = 'sms' AND m.direction = 'out' AND m.send_state = 'queued' AND m.trashed_at IS NULL                 ORDER BY m.sent_at"            ),            &[ws(ctx)],        )?;        let mut texts = Vec::new();        for row in found {            let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string();            let mut patch = Map::new();            // A text the person chose in a Cotton chat ("Send as SMS instead") goes to that chat's number.            let key = row.get("external_key").and_then(Value::as_str);            let Some(to) = key.and_then(to_of).or_else(|| key.and_then(cotton_core::chat::ids::number_of_key).map(str::to_string)) else {                patch.insert("send_state".into(), json!("failed"));                patch.insert("send_error".into(), json!("no_reply"));                update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;                continue;            };            // When it was handed out: a send whose answer never comes is told failed after a while (`here`).            patch.insert("send_state".into(), json!("sending"));            patch.insert("meta".into(), json!({ "sms": { "handed": handed } }));            update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;            let at = row.get("sent_at").and_then(Value::as_str).and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()).map(|d| d.timestamp_millis()).unwrap_or_default();            texts.push(json!({ "id": id, "to": to, "body": row.get("body").cloned().unwrap_or(Value::Null), "at": at }));        }        Ok(json!({ "texts": texts }))    })}/// How a send went, as Android's radio said: sent, or failed with its reason (`no_service`, `radio_off`, `limit`,/// `generic`). A failed text offers Retry, which queues it again.fn sent(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "id: the text's id"))?.to_string();    let ok = request.get("ok").and_then(Value::as_bool).unwrap_or(false);    let why = request.get("why").and_then(Value::as_str).unwrap_or("generic").to_string();    let state = if ok { "sent" } else { "failed" };    write(client, "chat.sms.sent", move |ctx| {        let found = one(ctx, &format!("SELECT send_state, channel FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?;        if found.as_ref().and_then(|r| r.get("channel")).and_then(Value::as_str) != Some(CHANNEL) {            return Err("not an SMS text".into());        }        let mut patch = Map::new();        patch.insert("send_state".into(), json!(state));        patch.insert("send_error".into(), if ok { Value::Null } else { json!(why) });        update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?;        Ok(Value::Null)    })?;    Ok(json!({ "state": state }))}/// An SMS chat's sender key as SENDERS.md keys senders (`senders::chat_key`): its number, else its name. `None` for/// any other chat.pub(crate) fn sender_key(client: &ClientController, thread: &str) -> Result<Option<String>, MethodError> {    let id = thread.to_string();    let found = super::cotton_chat::read(client, "chat.sms.sender", move |ctx| Ok(key_in(ctx, &id)?.map(Value::String).unwrap_or(Value::Null)))?;    Ok(found.as_str().map(str::to_string))}fn key_in(ctx: &mut Ctx<'_>, thread: &str) -> Result<Option<String>, String> {    let row = one(        ctx,        &format!("SELECT t.external_key, t.title, c.phone_e164 FROM {THREADS} t LEFT JOIN {CONTACTS} c ON c.id = t.contact_id WHERE t.workspace_id = ? AND t.id = ?"),        &[ws(ctx), SqlValue::Text(thread.to_string())],    )?;    let Some(row) = row.filter(|r| r.get("external_key").and_then(Value::as_str).is_some_and(|k| k.starts_with(SMS_PREFIX))) else { return Ok(None) };    let text = |k: &str| row.get(k).and_then(Value::as_str).map(str::to_string);    Ok(super::chat_app::senders::chat_key(text("phone_e164").as_deref(), text("title").as_deref(), text("external_key").as_deref()).map(|k| k.key))}/// `chat.contact` for an SMS chat: `{ thread, number?, blocked, mutedUntil, between, sms: true }`; `None` for any other.pub(crate) fn contact_answer(client: &ClientController, thread: &str) -> Result<Option<Value>, MethodError> {    let id = thread.to_string();    let found = super::cotton_chat::read(client, "chat.sms.contact", move |ctx| {        let Some(t) = one(ctx, &format!("SELECT external_key, contact_id, muted_until FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { return Ok(Value::Null) };        let Some(key) = t.get("external_key").and_then(Value::as_str).filter(|k| k.starts_with(SMS_PREFIX)).map(str::to_string) else { return Ok(Value::Null) };        let blocked = match key_in(ctx, &id)? {            Some(sender) => super::chat_app::senders::Blocked::read(ctx)?.has(&super::chat_app::senders::stored_key(&sender)),            None => false,        };        let links: u64 = rows(ctx, &format!("SELECT body FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(id.clone())])?            .iter()            .map(|m| m.get("body").and_then(Value::as_str).unwrap_or_default().split_whitespace().filter(|w| w.starts_with("http://") || w.starts_with("https://")).count() as u64)            .sum();        let number = to_of(&key).filter(|n| n.starts_with('+'));        Ok(json!({            "thread": id,            "number": number,            "blocked": blocked,            "mutedUntil": t.get("muted_until").cloned().unwrap_or(Value::Null),            "between": { "photos": 0, "videos": 0, "voice": 0, "files": 0, "links": links },            "sms": true,        }))    })?;    Ok((!found.is_null()).then_some(found))}#[cfg(test)]#[path = "chat_sms_tests.rs"]mod tests;