//! `chat.*` — Cotton to Cotton messages on this phone, every decision the //! core's ([`cotton_core::chat`]). The shell hands in what happened (a send, //! a socket frame, a push, the screen showing a chat, a key press) and this //! seals, sends, opens, checks and lands; the rows are the ordinary //! `message`, `thread` and `message_contact` rows, channel `cotton`, so the //! chat screen, search and export read them as they read every other //! conversation. The routes are the person's own object's (`/v1/chat/*`, //! `apps/business/src/chat/chat.ts`), asked through the door //! `personal.connect` holds. //! //! ```text //! chat.key {} → { privateKey, publicKey, fingerprint } //! chat.register { privateKey, platform?, token?, topic?, sandbox?, ratchet? } → { ok, fingerprint, ratchet } //! chat.ratchet { privateKey } → { speaks, devices?, sessions?, pinned?, opened? } //! chat.start { number? | person? } → { thread, number, name } //! chat.send { thread, body?, replyTo?, pictures?: [{ path, mime, width?, height? }], privateKey } → { message, state, nextAt } //! chat.flush { privateKey } → { sent, failed, waiting, nextAt } //! chat.retry { message, privateKey } → { message, state, nextAt } //! chat.incoming { privateKey, items? } → { landed: [{ thread, message, out, request, peer, name }], receipts, typing, requests, changed: [{ thread, message }], read: [thread], dropped } //! chat.notices {} → what this phone's notifications should be (`phone::chat_app`, `cotton_core::messages::app::notices`) //! chat.list / chat.thread / chat.compose / chat.act → Cotton Chat's answers (`phone::chat_app`) //! chat.receipt { thread, privateKey } → { read, told } //! chat.typing { thread, on, privateKey } → { told } //! chat.accept { thread } → { ok } //! chat.refuse { thread } → { ok } //! chat.block { thread? | number? } → { ok } //! chat.unblock { thread? | number? } → { ok } //! chat.settings { readReceipts?, typing? } → { readReceipts, typing, offered } //! chat.socket {} → { url, ticket } //! chat.rows {} → { pull: asked | later | "no schedule" } //! chat.forget {} → { ok } (the object forgets this phone's chat device: its key, its token, what waits for it) //! chat.picture { message, index?, dir } → { path, mime } //! chat.file { message, index?, dir } → { path, mime, name?, kind?, kept } (any file; kept in the person's own media: `phone::chat_files`) //! chat.keep { unmetered?, limit? } → { kept, left, gone } //! ``` //! //! **The private key crosses as a call parameter and is never kept here**, as //! the vault's is (`phone::vault`). It is this phone's CHAT key, not its vault //! key: the vault key is guarded by Face ID on every read, and a notification //! extension opening a message in the background could never ask for that. //! The shell keeps the chat key in its own Keychain item //! (`AfterFirstUnlockThisDeviceOnly`, shared with the extension by the app //! group) and hands it to every call that seals or opens. //! //! **Honest receipts and typing.** A read receipt and typing go out only when //! the app's kit says its chats signal at all (`AppKit::signals`: where it //! does not, nothing is sent, nothing is drawn, no switch is offered), the //! person's own switch is on (off until they turn it on), the other person's //! last word said theirs is on too (`Payload::signals`, carried sealed in //! every message, tick and typing), and never to someone whose request is not //! accepted. Theirs is drawn only while the person's own switch is on: off //! means neither side learns anything. A delivered receipt //! is the tick every message gets, and it too waits for acceptance, so a //! stranger cannot learn a number is on Cotton by writing to it. use std::collections::HashMap; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use zeroize::Zeroizing; use cotton_client::transport::http1::Http1Request; use cotton_client::transport::object::{bearer, ObjectRefusal}; use cotton_core::chat::payload::{self, Change, Item, Kind, Payload, Picture, Receipt, Signals, What}; use cotton_core::chat::{files, ids, outbox, seal, CHANNEL}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{insert_row, update_row}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::shell::client::ClientController; /// Every method this family answers. pub const METHODS: [&str; 71] = [ "chat.export", "chat.sms.here", "chat.sms.land", "chat.sms.outbox", "chat.sms.sent", "chat.accept", "chat.act", "chat.block", "chat.blocked", "chat.call", "chat.groupCall", "chat.callScreen", "chat.calls", "chat.compose", "chat.contact", "chat.contacts", "chat.downloads", "chat.downloads.act", "chat.downloads.send", "chat.file", "chat.flush", "chat.forget", "chat.ground", "chat.incoming", "chat.invite", "chat.keep", "chat.key", "chat.link", "chat.list", "chat.mail", "chat.mail.act", "chat.mail.compose", "chat.mail.countSender", "chat.mail.discard", "chat.mail.file", "chat.mail.free", "chat.mail.page", "chat.mail.hold", "chat.mail.save", "chat.mail.send", "chat.mail.sender", "chat.mail.thread", "chat.mail.trashSender", "chat.notices", "chat.picture", "chat.profile", "chat.profile.set", "chat.profilePicture", "chat.ratchet", "chat.receipt", "chat.refuse", "chat.register", "chat.retry", "chat.rows", "chat.safety", "chat.safety.scan", "chat.safety.verify", "chat.search", "chat.send", "chat.settings", "chat.slips", "chat.socket", "chat.starred", "chat.start", "chat.text", "chat.theme", "chat.theme.set", "chat.themes", "chat.thread", "chat.typing", "chat.unblock", ]; /// The object's chat routes. pub mod routes { pub const DEVICE: &str = "/v1/chat/device"; pub const SEND: &str = "/v1/chat/send"; pub const INBOX: &str = "/v1/chat/inbox"; pub const ACK: &str = "/v1/chat/ack"; pub const SOCKET: &str = "/v1/chat/socket"; pub const FILES: &str = "/v1/chat/files"; pub fn keys(number: &str) -> String { format!("/v1/chat/keys?number={}", number.replace('+', "%2B")) } pub fn file(id: &str) -> String { format!("/v1/chat/files/{id}") } pub fn verb(verb: &str) -> String { format!("/v1/chat/{verb}") } } /// The topics an iPhone's alert token may be filed under. pub const TOPICS: [&str; 4] = ["com.cottondb.messages", "com.cottondb.messages.dev", "com.cottondb.cotton", "com.cottondb.cotton.dev"]; /// Keys asked again after this long when sending: a new device of theirs gets a box within it. pub const KEYS_FRESH_MS: i64 = 5 * 60_000; /// The object's refusal of a message whose boxes miss one of the devices it would reach now (`/v1/chat/send`). pub const STALE_DEVICES: &str = "stale_devices"; pub(crate) const MESSAGES: &str = "cotton_msg_messages"; pub(crate) const THREADS: &str = "cotton_msg_threads"; pub(crate) const CONTACTS: &str = "cotton_msg_contacts"; const PREFERENCES: &str = "chat-preferences.json"; /// The switches each person's last word carried, by number (`Payload::signals`): this phone's own, never synced. const PEER_SIGNALS: &str = "chat-peer-signals.json"; /// What the core remembers between calls: this phone's number and the keys /// it last saw. Never a private key. #[derive(Debug, Default)] pub struct ChatMemory { me: Option, keys: HashMap, /// Each device's c2 record as its keys answer last said it, by handle (`phone::chat_ratchet`). records: HashMap, } #[derive(Debug, Clone)] struct Keys { devices: Vec<(String, [u8; 32])>, own: Vec<(String, [u8; 32])>, at: i64, } pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { over(&handle.client(), method, request) } /// The same, over a named controller (the suite's phone). /// Disappeared messages erased; a refusal waits for the next answer's sweep. fn sweep(client: &ClientController) { if let Err(refusal) = super::chat_timer::sweep(client) { tracing::warn!("chat: disappearing messages were not swept — {}", refusal.message); } // What has sat in Blocked for 30 days is erased (SENDERS.md); at most once an hour. if let Err(refusal) = super::chat_app::senders::erase::sweep_blocked(client) { tracing::warn!("chat: Blocked was not swept — {}", refusal.message); } } /// A chat whose newest message a WhatsApp timer says is due (not binned yet) shows its newest message still drawn. fn hide_due_in_list(client: &ClientController, answer: &mut Value) -> Result<(), MethodError> { let hidden = super::chat_timer::due_unbinned(client, None)?; if hidden.is_empty() { return Ok(()); } let due_threads: std::collections::HashSet = read(client, "chat.timer.due.threads", |ctx| { let mut threads = Vec::new(); for id in &hidden { if let Some(row) = one(ctx, &format!("SELECT thread_id FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? { threads.push(row.get("thread_id").cloned().unwrap_or(Value::Null)); } } Ok(json!(threads)) })? .as_array() .into_iter() .flatten() .filter_map(|v| v.as_str().map(str::to_string)) .collect(); for row in answer["rows"].as_array_mut().into_iter().flatten() { let Some(thread) = row["thread"].as_str().map(str::to_string) else { continue }; if !due_threads.contains(&thread) || row.get("lastLine").is_none() { continue; } match super::chat_timer::newest_shown(client, &thread, &hidden)? { None => {} Some(Some((body, mine))) => { row["lastLine"]["text"] = json!(body); row["lastLine"]["mine"] = json!(mine); } Some(None) => { if let Some(o) = row.as_object_mut() { o.remove("lastLine"); } } } } Ok(()) } /// The sweeps after a pass, on their own turn (ABSENCE 6, M4): never inside a screen read or a search, at most once /// every few minutes, each bounded. pub(crate) fn sweep_after_pass(client: &ClientController) { static LAST: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0); let now = now_ms(client); let last = LAST.load(std::sync::atomic::Ordering::Relaxed); if last != 0 && now >= last && now - last < 10 * 60_000 { return; } LAST.store(now, std::sync::atomic::Ordering::Relaxed); sweep(client); } pub fn over(client: &ClientController, method: &str, request: &Value) -> Result { match method { "chat.key" => { let secret = cotton_core::vault::wrap::mint_vault_key(); let public = seal::key_text(&cotton_core::vault::wrap::public_of(&secret)); Ok(json!({ "privateKey": seal::key_text(&secret), "fingerprint": cotton_core::vault::wrap::fingerprint(&public), "publicKey": public })) } "chat.register" => register(client, request), "chat.ratchet" => super::chat_ratchet::status(client, &*private_key(request)?), "chat.start" => start(client, request), "chat.send" => send(client, request), "chat.flush" => { let secret = private_key(request)?; // `online`: the phone has just reached the network again; what waited out a try that got no answer goes now. flush_pass(client, &secret, request.get("online").and_then(Value::as_bool).unwrap_or(false)) } "chat.retry" => retry(client, request), "chat.incoming" => { let answer = incoming(client, request); // What arrived counts toward each person's line in Contacts (`person_fact`), at most every 15 minutes. if answer.is_ok() { super::contacts_facts::after_refresh(client); } answer } "chat.receipt" => read_receipt(client, request), "chat.typing" => typing(client, request), "chat.accept" => decide(client, request, "accept"), "chat.refuse" => decide(client, request, "refuse"), "chat.block" => decide(client, request, "block"), "chat.unblock" => decide(client, request, "unblock"), "chat.settings" => settings(client, request), "chat.linkCard" => super::chat_app::preview(client, request), "chat.socket" => socket(client), "chat.rows" => Ok(rows_moved(client)), "chat.forget" => { ask(client, "DELETE", routes::DEVICE, None).map_err(refused)?; Ok(json!({ "ok": true })) } "chat.picture" => picture(client, request), "chat.file" => super::chat_files::file(client, request), "chat.keep" => super::chat_files::keep_pass(client, request), "chat.ahead" => super::chat_ahead::ahead(client, request), "chat.warm" => super::chat_ahead::warm(client, request), "chat.previews" => super::chat_ahead::previews(client, request), "chat.storage" | "chat.storage.free" => super::chat_storage::call(client, method, request), "chat.preview" => super::chat_ahead::set_previews(client, request), "chat.waveforms" => super::chat_voice::waveforms(client, request), "chat.waveform" => super::chat_voice::set_waveforms(client, request), "chat.slips" => super::chat_face::slips(client, request), "chat.timer.binned" => super::chat_timer::binned(client, request), "chat.timer.restore" => super::chat_timer::restore(client, request), "chat.timer.erase" => super::chat_timer::erase_binned(client, request), m if m.starts_with("chat.sms.") => super::chat_sms::over(client, m, request), m if m.starts_with("chat.group.") => super::chat_group::over(client, m, request), m if m.starts_with("chat.agent.") => super::chat_agent::over(client, m, request), "chat.thread" => { // What Cotton's own timer says has gone goes before anything is drawn (chat_timer::sweep_screen); the // WhatsApp timer and Blocked run after a pass. if let Err(refusal) = super::chat_timer::sweep_screen(client) { tracing::warn!("chat: disappearing messages were not swept — {}", refusal.message); } let mut answer = super::chat_app::call(client, method, request)?; let thread = answer["thread"].as_str().unwrap_or_default().to_string(); super::chat_calls::decorate_thread(client, &thread, &mut answer)?; // A Cotton conversation says whether its person is on Cotton yet (chat-people); one whose words go to their // WhatsApp through the Mac offers no invite (FEEDBACK-2 A). let via_whatsapp = answer["header"]["place"]["id"] == "whatsapp"; // Nor a Cotton call: the person is reached on WhatsApp, where Cotton cannot ring them. if via_whatsapp { if let Some(header) = answer["header"].as_object_mut() { header.remove("calls"); } } if let Ok(reach) = super::chat_people::reach_of(client, &thread) { if !via_whatsapp { answer["reach"] = reach; } } // When its next message goes, so the phone asks again then and it leaves the screen on time. if let Some(wait) = super::chat_timer::erases_in(client, Some(&thread))? { answer["erasesIn"] = json!(wait); } // What a WhatsApp timer says is due and the sweep has not binned yet is not drawn (ABSENCE 7, item 2). let hidden = super::chat_timer::due_unbinned(client, Some(&thread))?; if !hidden.is_empty() { if let Some(items) = answer["items"].as_array_mut() { items.retain(|item| item["message"].as_str().is_none_or(|id| !hidden.contains(id))); } } // What the timer put in the Bin here, to see and bring back (ABSENCE 4, item D). if let Some(card) = super::chat_timer::binned_card(client, &thread)? { answer["timerBinned"] = card; } Ok(answer) } "chat.search" => { let mut answer = super::chat_app::call(client, method, request)?; // A message a WhatsApp timer says is due (not binned yet) is never found (ABSENCE 7, item 2). if answer["messages"].as_array().is_some_and(|m| !m.is_empty()) { let hidden = super::chat_timer::due_unbinned(client, None)?; if !hidden.is_empty() { if let Some(found) = answer["messages"].as_array_mut() { found.retain(|m| m["message"].as_str().is_none_or(|id| !hidden.contains(id))); } } } Ok(answer) } "chat.list" => { let mut answer = super::chat_app::call(client, method, request)?; hide_due_in_list(client, &mut answer)?; // The list shows each chat's last line: it is asked again when the next message anywhere goes. if let (Some(wait), Some(list)) = (super::chat_timer::erases_in(client, None)?, answer.as_object_mut()) { list.insert("erasesIn".into(), json!(wait)); } Ok(answer) } "chat.call" | "chat.calls" | "chat.callScreen" | "chat.groupCall" => super::chat_calls::over(client, method, request), m if super::chat_people::METHODS.contains(&m) => super::chat_people::over(client, method, request), m if super::chat_safety::METHODS.contains(&m) => super::chat_safety::over(client, method, request), "chat.mail" | "chat.mail.thread" | "chat.mail.file" | "chat.mail.free" | "chat.mail.page" | "chat.mail.compose" | "chat.mail.save" | "chat.mail.send" | "chat.mail.discard" | "chat.mail.sender" | "chat.mail.countSender" | "chat.mail.trashSender" | "chat.mail.hold" | "chat.mail.act" | "chat.sender.page" | "chat.senders" | "chat.sender.ask" | "chat.sender.act" | "chat.senders.blocked" | "chat.starred" | "chat.notices" | "chat.compose" | "chat.act" | "chat.themes" | "chat.theme.set" | "chat.theme" | "chat.text" | "chat.ground" | "chat.downloads" | "chat.downloads.send" | "chat.downloads.act" | "chat.export" | "chat.link" => super::chat_app::call(client, method, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a chat method"))), } } // ── the methods ───────────────────────────────────────────────────────── fn register(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; let public = seal::key_text(&cotton_core::vault::wrap::public_of(&secret)); // `can`: what this core opens beyond messages: an agent's acts (chat_agent), so the object holds them only for a phone that says so. let mut body = json!({ "publicKey": public, "can": ["agent"] }); // `ratchet: true`: this shell opens c2 boxes (SEALING.md). Its record and keys go up beside its chat key; without // it the object forgets any it held, and phones that spoke c2 with this one refuse to fall back. let ratchet = flag(request, "ratchet"); if ratchet { body["c2"] = super::chat_ratchet::register_body(client, &secret)?; } if let Some(token) = request.get("token").and_then(Value::as_str) { let platform = text(request, "platform")?; body["platform"] = json!(platform); body["token"] = json!(token); if platform == "ios" { let topic = text(request, "topic")?; if !TOPICS.contains(&topic) { return Err(bad("topic", &format!("one of {}", TOPICS.join(", ")))); } body["topic"] = json!(topic); body["sandbox"] = json!(flag(request, "sandbox")); } } let answer = ask(client, "POST", routes::DEVICE, Some(&body)).map_err(refused)?; if ratchet { super::chat_ratchet::published(client, &secret); if let Some(left) = answer["prekeys"].as_u64() { super::chat_ratchet::top_up(client, &secret, left); } } Ok(json!({ "ok": true, "fingerprint": cotton_core::vault::wrap::fingerprint(&public), "ratchet": ratchet && answer.get("prekeys").is_some() })) } /// The conversation with a number or a person, made here when it is new. fn start(client: &ClientController, request: &Value) -> Result { let (number, name, person) = match (request.get("number").and_then(Value::as_str), request.get("person").and_then(Value::as_str)) { (Some(number), _) => { let number = e164(number).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use. Start it with + and the country code."))?; let (person, name) = person_of(client, &number); (number, name, person) } (None, Some(person)) => { let (number, name) = number_of(client, person)?; (number.ok_or_else(|| words("no_number", "There's no phone number for this person."))?, name, Some(person.to_string())) } _ => return Err(bad("number", "a number starting with +, or a person")), }; if memory(client, |m| m.me.clone()).as_deref() == Some(number.as_str()) { return Err(words("own_number", "That's your own number.")); } let ns = namespace(client)?; // Whether they are on Cotton is asked once (a number of the day's); not found, the chat says "not on Cotton yet". // Asked first: a number that already has a chat (from WhatsApp first) opens that one, and it becomes their Cotton // chat when they are on Cotton (`ensure_thread`; FEEDBACK-2 A). Before, such a number was refused by the store. let on = super::chat_people::check_one(client, &number).unwrap_or(false); // On the phone where Comms is the SMS app (and no WhatsApp through the Mac), a number not known on Cotton here is // asked at once (one `POST /v1/chat/wait`), and nothing goes as SMS unless the person chooses it, message by // message (DISCOVERY OFF 2, 27 Nov 2026). An SMS chat already here opens as it was: it moves to Cotton when they // accept. if !on && super::chat_sms::texts_here(client)? { let asked = super::chat_people::ask_now(client, &number); // An ask that could not go is said, never dropped (DISCOVERY OFF 3): offline, it goes at the next pass that // reaches the object; refused (over the new-chats limit), the server's words, and no new chat is made. let said = match &asked { Err(e) if e.code == "offline" => { super::chat_people::ask_later(client, &number); Some(cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "app.reach.ask_later", &[])) } Err(e) => Some(e.message.clone()), Ok(_) => None, }; if let Some(thread) = super::chat_sms::existing(client, &number)? { let place = super::chat_app::place_of(client, &thread)?; return Ok(json!({ "thread": thread, "number": number, "name": name, "place": place, "said": said })); } match asked { Ok(true) => return start_on(client, ns, number, name, person, true), Err(e) if e.code != "offline" => return Err(e), _ => {} } let mut answer = start_on(client, ns, number, name, person, false)?; if let Some(said) = said { answer["said"] = json!(said); } return Ok(answer); } start_on(client, ns, number, name, person, on) } /// The Cotton conversation with a number, made when new, and what it answers at its start. fn start_on(client: &ClientController, ns: String, number: String, name: Option, person: Option, on: bool) -> Result { let (n, nm, p) = (number.clone(), name.clone(), person.clone()); let thread = write(client, "chat.start", move |ctx| ensure_thread(ctx, &ns, &n, nm.as_deref(), p.as_deref(), None, false).map(Value::from))?; let thread = thread.as_str().unwrap_or_default().to_string(); let mut answer = json!({ "thread": thread, "number": number, "name": name, "reach": if on { "on" } else { "notYet" } }); // Where a message written to them goes (FEEDBACK-2 A), as the chat itself will say it: on a copy linked to // WhatsApp through the Mac, a number not on Cotton goes to its WhatsApp (no invite then); unlinked, nothing changes. if let Some(place) = super::chat_app::place_of(client, &thread)? { if place.id == "whatsapp" { if let Some(fields) = answer.as_object_mut() { fields.remove("reach"); } } answer["place"] = serde_json::to_value(place).unwrap_or(Value::Null); } Ok(answer) } /// A message written here: a queued row at once, then the outbox's pass. fn send(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; let thread = text(request, "thread")?.to_string(); let body = request.get("body").and_then(Value::as_str).map(str::to_string); let pictures: Vec = request.get("pictures").and_then(Value::as_array).cloned().unwrap_or_default(); let reply_to = request.get("replyTo").and_then(Value::as_str).map(str::to_string); let id = queue(client, &thread, body, pictures, reply_to, None)?; let pass = flush(client, &secret)?; let state = message_state(client, &id)?; Ok(json!({ "message": id, "state": state, "nextAt": pass["nextAt"] })) } /// A Cotton message written into this phone's copy, queued, and nothing /// asked of the network: the bubble stands at once and `chat.flush` sends /// it. `forward_of` names the message it was forwarded from. pub(crate) fn queue(client: &ClientController, thread: &str, body: Option, pictures: Vec, reply_to: Option, forward_of: Option) -> Result { let thread = thread.to_string(); let body = body.map(|b| b.trim().to_string()).filter(|b| !b.is_empty()); if body.is_none() && pictures.is_empty() { return Err(words("empty", "Write something first.")); } if body.as_deref().map_or(0, str::len) > payload::BODY_MAX { return Err(words("too_long", "That message is too long to send.")); } if pictures.len() > payload::PICTURES_MAX { return Err(bad("pictures", &format!("at most {}", payload::PICTURES_MAX))); } for picture in &pictures { let path = picture.get("path").and_then(Value::as_str).ok_or_else(|| bad("pictures", "each { path, mime, width?, height? }"))?; let size = std::fs::metadata(path).map_err(|e| MethodError::new("unreadable", format!("the picture could not be read ({e})")))?.len(); if size as usize > files::FILE_MAX { return Err(words("picture_too_large", "That picture is too large to send.")); } } let pictures: Vec = pictures .into_iter() .map(|mut p| { if p.get("mime").and_then(Value::as_str).is_none() { p["mime"] = json!("application/octet-stream"); } // The phone's preview travels only as a small JPEG (`payload::preview_of`); anything else is no preview, and the picture still goes. match p.get("preview").and_then(Value::as_str).and_then(payload::preview_of) { Some(preview) => p["preview"] = json!(preview), None => { if let Some(o) = p.as_object_mut() { o.remove("preview"); } } } p }) .collect(); if super::chat_group::is_group_thread(client, &thread) { // A group is written in once joined, and only while this person is in it. if !accepted(client, &thread)? { return Err(words("not_joined", "Join the group to write in it.")); } super::chat_group::can_send(client, &thread)?; } else { thread_number(client, &thread)?; } let ns = namespace(client)?; let client_id = fresh_id(); let id = ids::message_id(&ns, ids::ME, &client_id); let written = now_ms(client); let now = iso(written); let (t, i, c, r, b, f) = (thread.clone(), id.clone(), client_id.clone(), reply_to.clone(), body.clone(), forward_of.clone()); let pending = json!(pictures); write(client, "chat.send", move |ctx| { // A reply names the message by its writer's id, which the other side knows it by. let reply_external = match &r { Some(row) => one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(row.clone())])?.and_then(|row| row.get("external_id").and_then(Value::as_str).map(str::to_string)), None => None, }; let mut columns = Map::new(); columns.insert("thread_id".into(), json!(t)); columns.insert("direction".into(), json!("out")); columns.insert("channel".into(), json!(CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("body".into(), json!(b.clone().unwrap_or_default())); columns.insert("external_id".into(), json!(c)); columns.insert("sent_at".into(), json!(now)); columns.insert("send_state".into(), json!("queued")); columns.insert("send_attempts".into(), json!(0)); let mut meta = json!({ "cotton": { "written_at": now, "pending_pictures": pending } }); // Written while the chat's timer is on: it names when it goes, here and in its box (chat_timer). let seconds = super::chat_timer::timer_of(ctx, &t)?; super::chat_timer::stamp(&mut meta, written, seconds); if let Some(from) = &f { columns.insert("forward_of_id".into(), json!(from)); meta["forwarded"] = json!(true); } columns.insert("meta".into(), meta); if let Some(reply) = &r { columns.insert("reply_to_id".into(), json!(reply)); } if let Some(external) = reply_external { columns.insert("reply_to_external_id".into(), json!(external)); } insert_row(ctx, MESSAGES, &i, columns).map_err(|f| f.to_string())?; touch_thread(ctx, &t, &now, b.as_deref(), !pending.as_array().is_some_and(Vec::is_empty))?; // Writing to someone answers their request. set_request(ctx, &t, "accepted", true)?; Ok(Value::Null) })?; Ok(id) } /// A transcript as it travels: trimmed, never empty, cut at a character /// boundary within [`payload::TRANSCRIPT_MAX`] bytes. pub(crate) fn transcript_of(text: &str) -> Option { let text = text.trim(); if text.is_empty() { return None; } let mut end = text.len().min(payload::TRANSCRIPT_MAX); while !text.is_char_boundary(end) { end -= 1; } Some(text[..end].trim_end().to_string()) } /// Whether the message a change names (its writer's id, in this /// conversation) has gone: a transcript never goes before its voice message, /// which would find nothing to change. `None`: no such message here. fn has_gone(client: &ClientController, thread: &str, external: &str) -> Result, MethodError> { let (thread, external) = (thread.to_string(), external.to_string()); let row = read(client, "chat.changes", move |ctx| Ok(one(ctx, &format!("SELECT send_state FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ?"), &[ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(external.clone())])?.map(Value::Object).unwrap_or(Value::Null)))?; if row.is_null() { return Ok(None); } Ok(Some(matches!(row["send_state"].as_str(), Some("sent" | "delivered" | "read")))) } /// A failed message put back in the outbox, its tries counted afresh, and a pass made. fn retry(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; let id = text(request, "message")?.to_string(); requeue(client, &id)?; let pass = flush(client, &secret)?; Ok(json!({ "message": id, "state": message_state(client, &id)?, "nextAt": pass["nextAt"] })) } /// A failed message back in the outbox, its tries counted afresh: `chat.flush` sends it. pub(crate) fn requeue(client: &ClientController, id: &str) -> Result<(), MethodError> { if message_state(client, id)? != json!("failed") { return Err(MethodError::new("not_failed", "This message isn't one that failed.")); } let i = id.to_string(); write(client, "chat.resend", move |ctx| { let mut meta = meta_of(ctx, &i)?; if let Some(cotton) = meta.get_mut("cotton").and_then(Value::as_object_mut) { cotton.remove("tried_at"); } let mut patch = Map::new(); patch.insert("send_state".into(), json!("queued")); patch.insert("send_attempts".into(), json!(0)); patch.insert("send_error".into(), Value::Null); patch.insert("meta".into(), meta); update_row(ctx, MESSAGES, &i, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; Ok(()) } /// The outbox's pass: each due message in turn, oldest first, until none is /// due or the phone is offline. A message whose attempt must wait keeps its /// conversation's younger ones waiting behind it (until it is stuck, /// [`outbox::STUCK_AFTER`]) and holds up no other conversation. fn flush(client: &ClientController, secret: &[u8; 32]) -> Result { flush_pass(client, secret, false) } /// The outbox's pass; `online` (the phone has just reached the network /// again, FEEDBACK1 item 2): a message waiting out its tries' backoff is tried /// once more now, not up to five minutes later, so what was written offline /// goes the moment the phone is back. fn flush_pass(client: &ClientController, secret: &[u8; 32], online: bool) -> Result { let mut tried_now: std::collections::HashSet = std::collections::HashSet::new(); let mut sent = Vec::new(); let mut failed = Vec::new(); let mut changes = flush_changes(client, secret)?; // Groups' changes and their object's roll: told before their messages, so a member just added is sealed for. let group_changes = super::chat_group::flush(client, secret)?; // Messages waiting for their person to be on Cotton go back in the queue once they are (chat-people). super::chat_people::wake(client)?; loop { let mut queue = waiting(client)?; if online { for w in queue.iter_mut().filter(|w| !tried_now.contains(&w.id)) { w.tried_at = None; } } let now = now_ms(client); let Some(next) = outbox::due(&queue, now).cloned() else { if !sent.is_empty() { changes += flush_changes(client, secret)?; } // What went and what landed reaches this person's agents in the chats they are in (chat_agent). super::chat_agent::feed(client); return Ok(json!({ "sent": sent, "failed": failed, "waiting": queue.len(), "nextAt": outbox::next_at(&queue), "changes": changes, "groupChanges": group_changes })); }; // A message to someone not known on Cotton waits, out of the queue, instead of going to a key nobody holds. if let Ok(false) = super::chat_people::gate(client, &next.id) { continue; } tried_now.insert(next.id.clone()); match attempt(client, secret, &next.id) { Ok((at, each)) => { let (id, at) = (next.id.clone(), iso(at)); write(client, "chat.sent", move |ctx| { let mut patch = Map::new(); if let Some(each) = &each { // A group's message: each member it went to, at sent; its delivered and read ticks are theirs together. let mut meta = meta_of(ctx, &id)?; meta["cotton"]["receipts"] = each.clone(); patch.insert("meta".into(), meta); } patch.insert("send_state".into(), json!("sent")); // The order a conversation is drawn in is the sender's object's clock. patch.insert("sent_at".into(), json!(at)); patch.insert("send_error".into(), Value::Null); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; super::chat_agent::tried(client, &next.id, true, None); sent.push(next.id); } Err(refusal) => { let outcome = outbox::outcome(refusal.status, next.attempts); let (id, attempts, tried) = (next.id.clone(), next.attempts + 1, now); let message = refusal.message.clone(); write(client, "chat.retry", move |ctx| { let meta = meta_of(ctx, &id)?; let mut meta = meta; meta["cotton"]["tried_at"] = json!(tried); let mut patch = Map::new(); patch.insert("send_attempts".into(), json!(attempts)); patch.insert("meta".into(), meta); if outcome == outbox::Outcome::Failed { patch.insert("send_state".into(), json!("failed")); patch.insert("send_error".into(), json!(message)); } update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; if outcome == outbox::Outcome::Failed { super::chat_agent::tried(client, &next.id, false, Some(&refusal.message)); failed.push(next.id); continue; } // Another conversation may go when this one could not, unless nothing answered at all. if refusal.status != 0 { continue; } let queue = waiting(client)?; return Ok(json!({ "sent": sent, "failed": failed, "waiting": queue.len(), "nextAt": outbox::next_at(&queue) })); } } } } /// The reactions, edits and deletes each Cotton conversation holds waiting /// (`thread.changes_waiting`), told in order to the other person's devices /// and this person's own; one that cannot go yet stays, and the rest of its /// conversation waits behind it. Answers how many went. fn flush_changes(client: &ClientController, secret: &[u8; 32]) -> Result { let waiting = read(client, "chat.changes", |ctx| { if !holds(ctx, THREADS, "changes_waiting")? { return Ok(json!([])); } Ok(Value::Array(rows(ctx, &format!("SELECT id, external_key, changes_waiting FROM {THREADS} WHERE workspace_id = ? AND changes_waiting IS NOT NULL"), &[ws(ctx)])?.into_iter().map(Value::Object).collect())) })?; let mut told = 0; for thread in waiting.as_array().into_iter().flatten() { let key = thread["external_key"].as_str().unwrap_or_default(); let group = super::chat_group::group_of_key(key).map(str::to_string); let Some(number) = ids::number_of_key(key).map(str::to_string).or_else(|| group.as_ref().map(|_| String::new())) else { continue }; let list: Vec = thread["changes_waiting"].as_str().and_then(|t| serde_json::from_str(t).ok()).unwrap_or_default(); let Some(me) = memory(client, |m| m.me.clone()) else { return Ok(told) }; // Changes held for their message (a transcript whose voice message has not gone), then those not yet told. let mut held: Vec = Vec::new(); let mut next = 0; for change in &list { if change["what"] == json!("transcript") { match has_gone(client, thread["id"].as_str().unwrap_or_default(), change["message"].as_str().unwrap_or_default())? { Some(false) => { held.push(change.clone()); next += 1; continue; } None => { next += 1; continue; } Some(true) => {} } } if change["what"] == json!("read") { // Read here: this person's other devices are told, never theirs (`wait_read`). let ids_: Vec = change["ids"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect(); let id = change["id"].as_str().map(str::to_string).unwrap_or_else(fresh_id); let at = change["at"].as_i64().unwrap_or_else(|| now_ms(client)); if !ids_.is_empty() && tell_own(client, secret, &number, Payload::receipt(&id, &me, &number, at, Receipt::Read, ids_)).is_err() { break; } next += 1; told += 1; continue; } let parsed: Option<(String, Change, Option, i64)> = (|| { let what: What = serde_json::from_value(change["what"].clone()).ok()?; Some((change["id"].as_str()?.to_string(), Change { what, message: change["message"].as_str()?.to_string(), emoji: change["emoji"].as_str().map(str::to_string) }, change["body"].as_str().map(str::to_string), change["at"].as_i64().unwrap_or_else(|| now_ms(client)))) })(); let Some((id, what, body, at)) = parsed else { next += 1; continue; }; // Said by this person's agent (chat_agent): marked, in a group only. let agent: Option = change["agent"]["id"].as_str().map(|a| payload::AgentMark { id: a.to_string(), name: change["agent"]["name"].as_str().unwrap_or("Claude").to_string(), body: None }); let gone = match &group { // In a group a change goes to every member, as its message did. Some(_) => super::chat_group::tell_change(client, secret, thread["id"].as_str().unwrap_or_default(), &me, &|to| { let mut p = Payload::change(&id, &me, to, at, what.clone(), body.clone()); p.agent = agent.clone(); p }), None if agent.is_some() => Ok(()), None => tell(client, secret, &number, Payload::change(&id, &me, &number, at, what, body), true), }; if gone.is_err() { break; } if let Some(act) = change["act"].as_str() { super::chat_agent::report(client, act, true, None); } next += 1; told += 1; } let left: Vec = held.into_iter().chain(list[next..].iter().cloned()).collect(); if left != list { let id = thread["id"].as_str().unwrap_or_default().to_string(); let kept = if left.is_empty() { Value::Null } else { json!(serde_json::to_string(&left).unwrap_or_default()) }; write(client, "chat.changes", move |ctx| { let mut patch = Map::new(); patch.insert("changes_waiting".into(), kept.clone()); update_row(ctx, THREADS, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; } } Ok(told) } /// A change waiting on a Cotton conversation's row until `chat.flush` tells it. pub(crate) fn wait_change(ctx: &mut Ctx<'_>, thread: &str, what: What, message_external: &str, emoji: Option<&str>, body: Option<&str>, at: i64) -> Result<(), String> { let row = one(ctx, &format!("SELECT changes_waiting FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string())])?; let mut list: Vec = row.and_then(|r| r.get("changes_waiting").and_then(Value::as_str).and_then(|t| serde_json::from_str(t).ok())).unwrap_or_default(); let mut change = json!({ "id": fresh_id(), "what": what, "message": message_external, "at": at }); if let Some(emoji) = emoji { change["emoji"] = json!(emoji); } if let Some(body) = body { change["body"] = json!(body); } list.push(change); let mut patch = Map::new(); patch.insert("changes_waiting".into(), json!(serde_json::to_string(&list).unwrap_or_default())); update_row(ctx, THREADS, thread, patch).map_err(|f| f.to_string()) } /// A conversation read on this phone, waiting on its row until `chat.flush` /// tells this person's OTHER devices, so their notifications go and their /// list stops saying unread. Never the other person: their read receipt is /// `chat.receipt`'s, under both switches, and this one is sealed for the /// person's own devices alone. `ids` are their messages' own ids, the newest /// [`payload::RECEIPT_IDS_MAX`]. pub(crate) fn wait_read(ctx: &mut Ctx<'_>, thread: &str, ids: &[String], at: i64) -> Result<(), String> { if ids.is_empty() || !holds(ctx, THREADS, "changes_waiting")? { return Ok(()); } let row = one(ctx, &format!("SELECT changes_waiting FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string())])?; let mut list: Vec = row.and_then(|r| r.get("changes_waiting").and_then(Value::as_str).and_then(|t| serde_json::from_str(t).ok())).unwrap_or_default(); let keep = ids.len().saturating_sub(payload::RECEIPT_IDS_MAX); list.push(json!({ "id": fresh_id(), "what": "read", "ids": ids[keep..], "at": at })); let mut patch = Map::new(); patch.insert("changes_waiting".into(), json!(serde_json::to_string(&list).unwrap_or_default())); update_row(ctx, THREADS, thread, patch).map_err(|f| f.to_string()) } /// A change arriving: a reaction from whoever sent it, an edit or delete only of the sender's own message. fn apply_change(ctx: &mut Ctx<'_>, ns: &str, item: &Item, payload: &Payload) -> Result { let thread = chat_with(ctx, ns, &item.peer)?; apply_change_in(ctx, ns, &thread, item, payload, &item.peer) } /// The same in a named conversation; `sender` is who said it (in a group, the member: an edit or delete must be of their own message). pub(crate) fn apply_change_in(ctx: &mut Ctx<'_>, ns: &str, thread: &str, item: &Item, payload: &Payload, sender: &str) -> Result { let Some(change) = &payload.change else { return Ok(Value::Null) }; // The chat's timer set, by either side: its line lands (chat_timer). if change.what == What::Timer { return super::chat_timer::land(ctx, ns, thread, item, payload, sender); } // A group's call started: its line lands, with Join (chat_calls). if change.what == What::Call { return if item.group.is_some() { super::chat_calls::land_group_call(ctx, ns, thread, item.out, payload, sender) } else { Ok(Value::Null) }; } let thread = thread.to_string(); let Some(target) = one(ctx, &format!("SELECT id, direction, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ?"), &[ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(change.message.clone())])? else { return Ok(Value::Null); }; let message = target.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); let theirs = if item.out { "out" } else { "in" }; // In a group, "theirs" is the one member's: the message must name them as its writer. let written_by = meta_value(target.get("meta").unwrap_or(&Value::Null))["cotton"]["from"].as_str().map(str::to_string); let by_sender = item.group.is_none() || item.out || written_by.as_deref() == Some(sender); match change.what { What::React | What::Unreact => { // An agent's reaction is its own, never its person's (chat_agent). let actor = match &payload.agent { Some(agent) => super::chat_agent::actor(&agent.id), None if item.out => cotton_core::constants::REACTION_ACTOR_SELF.to_string(), None => sender.trim_start_matches('+').to_string(), }; let row_id = cotton_core::messages::ids::reaction_row_id(&message, &actor).map_err(|e| e.to_string())?; let held = exists(ctx, "cotton_msg_reactions", &row_id)?; match (change.what, change.emoji.as_deref()) { (What::React, Some(emoji)) => { let mut columns = Map::new(); columns.insert("emoji".into(), json!(emoji.trim())); if held { update_row(ctx, "cotton_msg_reactions", &row_id, columns).map_err(|f| f.to_string())?; } else { columns.insert("thread_id".into(), json!(thread)); columns.insert("message_id".into(), json!(message)); columns.insert("actor".into(), json!(actor)); insert_row(ctx, "cotton_msg_reactions", &row_id, columns).map_err(|f| f.to_string())?; } } _ if held => ctx.writer().map_err(|f| f.to_string())?.retract("cotton_msg_reactions", &row_id, cotton_tools::mcp::writer::Retract::Relation), _ => {} } } What::Timer | What::Call => {} What::Transcript => { if target.get("direction").and_then(Value::as_str) != Some(theirs) || !by_sender { return Ok(Value::Null); } let Some(words) = payload.body.as_deref().and_then(transcript_of) else { return Ok(Value::Null) }; let mut meta = meta_value(target.get("meta").unwrap_or(&Value::Null)); meta["cotton"]["transcript"] = json!(words); let mut patch = Map::new(); patch.insert("meta".into(), meta); update_row(ctx, MESSAGES, &message, patch).map_err(|f| f.to_string())?; } What::Edit | What::Delete => { if target.get("direction").and_then(Value::as_str) != Some(theirs) || !by_sender { return Ok(Value::Null); } let mut patch = Map::new(); let at = iso(payload.at); if change.what == What::Edit { let mut meta = meta_value(target.get("meta").unwrap_or(&Value::Null)); meta["edited"] = json!(true); patch.insert("body".into(), json!(payload.body.clone().unwrap_or_default())); patch.insert("edited_at".into(), json!(at)); patch.insert("meta".into(), meta); } else { patch.insert("deleted_at".into(), json!(at)); patch.insert("body".into(), Value::Null); patch.insert("media".into(), json!([])); } update_row(ctx, MESSAGES, &message, patch).map_err(|f| f.to_string())?; } } Ok(json!({ "thread": thread, "message": message })) } /// One message's one try: its pictures put up, its boxes sealed, the envelope sent. The object's clock on success, and in a group whom it went to. fn attempt(client: &ClientController, secret: &[u8; 32], id: &str) -> Result<(i64, Option), ObjectRefusal> { let row = read(client, "chat.attempt", { let id = id.to_string(); move |ctx| one(ctx, &format!("SELECT m.id, m.thread_id, m.body, m.external_id, m.reply_to_external_id, m.meta, t.external_key FROM {MESSAGES} m JOIN {THREADS} t ON t.id = m.thread_id WHERE m.workspace_id = ? AND m.id = ?"), &[ws(ctx), SqlValue::Text(id.clone())]).map(|row| row.map(Value::Object).unwrap_or(Value::Null)) }) .map_err(|e| local(e.message))?; let key = row["external_key"].as_str().unwrap_or_default().to_string(); let group = super::chat_group::group_of_key(&key).is_some(); let number = if group { String::new() } else { ids::number_of_key(&key).ok_or_else(|| local("not a Cotton chat".into()))?.to_string() }; let client_id = row["external_id"].as_str().unwrap_or_default().to_string(); let mut meta: Value = meta_value(&row["meta"]); // Pictures go up first, side by side, each sealed with its own key; the row then names them. let pending: Vec = meta["cotton"]["pending_pictures"].as_array().cloned().unwrap_or_default(); let mut pictures: Vec = serde_json::from_value(meta["cotton"]["pictures"].clone()).unwrap_or_default(); let mut sent_paths: Vec = Vec::new(); if !pending.is_empty() { let put: Vec> = std::thread::scope(|scope| { let jobs: Vec<_> = pending .iter() .map(|picture| { scope.spawn(move || { let path = picture["path"].as_str().unwrap_or_default(); let plain = std::fs::read(path).map_err(|e| ObjectRefusal { status: 400, code: "unreadable".into(), message: format!("the picture could not be read ({e})") })?; let sealed = files::seal_file(&plain).ok_or_else(|| ObjectRefusal { status: 413, code: "picture_too_large".into(), message: "That picture is too large to send.".into() })?; let answer = put_bytes(client, routes::FILES, &sealed.bytes)?; Ok((answer, sealed, plain.len() as u64)) }) }) .collect(); jobs.into_iter().map(|job| job.join().unwrap_or_else(|_| Err(local("a picture's upload stopped".into())))).collect() }); // One that could not go fails the try whole; the next try puts them all up again. let put: Vec<(Value, files::Sealed, u64)> = put.into_iter().collect::>()?; for (picture, (answer, sealed, bytes)) in pending.iter().zip(put) { let file = answer["file"].as_str().unwrap_or_default().to_string(); sent_paths.push(picture["path"].as_str().unwrap_or_default().to_string()); let plain_len = bytes; pictures.push(Picture { file, key: seal::key_text(&sealed.key), sha256: sealed.sha256, mime: picture["mime"].as_str().unwrap_or("image/jpeg").to_string(), width: picture["width"].as_u64().map(|w| w as u32), height: picture["height"].as_u64().map(|h| h as u32), bytes: plain_len, kind: picture["kind"].as_str().map(str::to_string), name: picture["name"].as_str().map(str::to_string), duration_ms: picture["durationMs"].as_u64(), waveform: picture["waveform"].as_array().map(|w| w.iter().filter_map(Value::as_f64).take(payload::WAVEFORM_MAX).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8).collect()).unwrap_or_default(), preview: picture["preview"].as_str().and_then(payload::preview_of), }); } meta["cotton"]["pictures"] = json!(pictures); meta["cotton"]["pending_pictures"] = json!([]); let (id, sent_pictures) = (id.to_string(), json!(pictures)); write(client, "chat.pictures", move |ctx| { // The row as it is now: what was written on it while the files went up (a transcript) stays. let mut now = meta_of(ctx, &id)?; now["cotton"]["pictures"] = sent_pictures.clone(); now["cotton"]["pending_pictures"] = json!([]); let mut patch = Map::new(); patch.insert("meta".into(), now); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) }) .map_err(|e| local(e.message))?; // The sender keeps their own copy in their own media, past the chat store's thirty days (`chat_files`). let thread = row["thread_id"].as_str().unwrap_or_default().to_string(); let first = pictures.len() - sent_paths.len(); for (offset, path) in sent_paths.iter().enumerate() { let _ = super::chat_files::keep(client, row["id"].as_str().unwrap_or_default(), &thread, first + offset, std::path::Path::new(path), &pictures[first + offset]); } } // One to one, the keys' answer says this phone's number too; a group asks it of the object when not yet known. let keys = if group { None } else { Some(keys_for(client, &number, KEYS_FRESH_MS)?) }; let me = my_number(client).ok_or_else(|| local("this phone's number is not known yet".into()))?; let written = meta["cotton"]["written_at"].as_str().and_then(ms_of).unwrap_or_else(|| now_ms(client)); let body = row["body"].as_str().filter(|b| !b.is_empty()).map(str::to_string); let reply = row["reply_to_external_id"].as_str().map(str::to_string); if group { let timer = super::chat_timer::seconds_of(&meta); // Written by this person's agent: its words labelled for phones that know no agents, and marked (chat_agent). let agent = super::chat_agent::agent_of(&meta); let make = |to: &str| { let words = match (&agent, &body) { (Some((_, name)), Some(b)) => Some(payload::AgentMark::labelled(name, b)), _ => body.clone(), }; let mut p = Payload::message(&client_id, &me, to, written, words, reply.clone(), pictures.clone()); p.timer = timer; p.agent = agent.as_ref().map(|(id, name)| payload::AgentMark { id: id.clone(), name: name.clone(), body: body.clone() }); p.preview = preview_of_meta(&meta); p }; let (at, each) = super::chat_group::attempt(client, secret, &row, &make)?; return Ok((at, Some(each))); } let keys = keys.ok_or_else(|| local("no keys".into()))?; let mut message = Payload::message(&client_id, &me, &number, written, body, reply, pictures); message.timer = super::chat_timer::seconds_of(&meta); message.preview = preview_of_meta(&meta); // The person's own name and picture, sealed in the box (chat-people). message.profile = super::chat_people::own_profile(client); let sealed = boxes(client, secret, &number, &keys.devices, &me, &keys.own, &message)?; let answer = match ask(client, "POST", routes::SEND, Some(&json!({ "to": number, "id": client_id, "kind": "message", "boxes": sealed, "check": true }))) { // Their devices (or this person's own) changed since the keys were kept: a phone just signed in would // never get this message. The keys are asked again and it is sealed again, once. Err(refusal) if refusal.code == STALE_DEVICES => { let keys = keys_for(client, &number, 0)?; let sealed = boxes(client, secret, &number, &keys.devices, &me, &keys.own, &message)?; ask(client, "POST", routes::SEND, Some(&json!({ "to": number, "id": client_id, "kind": "message", "boxes": sealed, "check": true })))? } other => other?, }; Ok((answer["at"].as_i64().unwrap_or_else(|| now_ms(client)), None)) } /// What arrived: the items a socket frame carried, or everything the object holds for this phone. fn incoming(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; // The inbox also says who asks to chat (`asks`, a key older Workers never send): someone who wrote to this // person while they keep "can be found" off, or added them from Your people. let mut asks: Option> = None; let items: Vec = match request.get("items") { Some(items) => serde_json::from_value(items.clone()).map_err(|_| bad("items", "the socket's envelope items"))?, None => { let mut answer = ask(client, "GET", routes::INBOX, None).map_err(refused)?; remember_me(client, &answer); // An ask that keeps only its sealed copy opens here (b.4 step B); one that does not open is left out. super::circle::open_sealed(client, &mut answer); if let Some(list) = answer.get_mut("asks").and_then(Value::as_array_mut) { list.retain(|a| a["number"].as_str().is_some_and(|n| !n.is_empty())); } asks = answer.get("asks").and_then(|a| serde_json::from_value(a.clone()).ok()); // A c2 device's one-time keys left on its object: below the mark, more go up. if let Some(left) = answer.get("prekeys").and_then(Value::as_u64) { super::chat_ratchet::top_up(client, &secret, left); } serde_json::from_value(answer["items"].clone()).unwrap_or_default() } }; if memory(client, |m| m.me.is_none()) { // The socket's frames do not say this phone's number: asked once. let answer = ask(client, "GET", routes::INBOX, None).map_err(refused)?; remember_me(client, &answer); } let me = memory(client, |m| m.me.clone()).ok_or_else(not_connected)?; let ns = namespace(client)?; let signals = signals(client); let (own_read, own_typing) = preferences(client); let mut landed = Vec::new(); let mut receipts = Vec::new(); let mut typing = Vec::new(); let mut requests = Vec::new(); let mut changed = Vec::new(); let mut read = Vec::new(); let mut dropped = 0u32; let mut taken = Vec::new(); let mut to_tell: HashMap> = HashMap::new(); let mut group_ticks: HashMap<(String, String), Vec> = HashMap::new(); let mut ordered = items; ordered.sort_by(|a, b| (a.at, &a.id).cmp(&(b.at, &b.id))); let mut waits = 0u32; let now = now_ms(client); // The envelopes taken, by the name their opened words are kept under (`chat_ratchet`), and the c2 boxes no session opened. let mut taken_keys: Vec = Vec::new(); let mut unreadable: Vec = Vec::new(); // Devices whose lost session could not open words of this person's: (peer, out, the device's handle, the ids). let mut lost: Vec<(String, bool, String, Vec)> = Vec::new(); // An agent's act taken here: its words go out in this same call, whichever shell woke the phone (chat_agent). let mut acted = false; for item in ordered { // What this person's own agent asks, sealed by their own object for this device (chat_agent). if item.kind == Kind::Agent { taken.push(json!({ "id": item.id, "kind": item.kind.as_str() })); match super::chat_agent::take(client, &secret, &item) { Some(c) => { changed.push(c); acted = true; } None => dropped += 1, } continue; } let payload = match open_item(client, &secret, &item, &me) { super::chat_ratchet::Opened::Payload(payload) => payload, other => { if item.kind != Kind::Typing { taken.push(json!({ "id": item.id, "kind": item.kind.as_str() })); if matches!(other, super::chat_ratchet::Opened::Unreadable) { unreadable.push(item.clone()); } } dropped += 1; continue; } }; let item_key = super::chat_ratchet::item_key(&item); // A box its sealer could not have meant: one that tells this phone its own box opened nothing there. // The fresh session it came on is the answer; nothing lands. if payload.kind == Kind::Receipt && payload.state == Some(Receipt::Unreadable) { taken.push(json!({ "id": item.id, "kind": item.kind.as_str() })); taken_keys.push(item_key); // The messages it names are sealed again for that one device, below, once each (SEALING.md). if item.group.is_none() { if let Some(handle) = sender_handle(client, &item) { lost.push((item.peer.clone(), item.out, handle, payload.ids.clone())); } } continue; } let mut payload = payload; if !item.out { // Their switches as they say them now: a message says them always (an older app's says nothing: off). match payload.signals { Some(said) => keep_peer_signals(client, &payload.from, payload.at, said), None if payload.kind == Kind::Message => keep_peer_signals(client, &payload.from, payload.at, Signals::default()), None => {} } // Their Read is drawn only while this person's own switch is on: off, it says no more than delivered. if payload.kind == Kind::Receipt && payload.state == Some(Receipt::Read) && !(signals && own_read) { payload.state = Some(Receipt::Delivered); } } if item.group.is_some() { // Said in a group: the group's own rules (chat_group); one this phone cannot place yet stays held. let arrival = super::chat_group::arrive(client, &ns, &me, &item, &payload, now)?; if arrival.wait { waits += 1; continue; } if item.kind != Kind::Typing { taken.push(json!({ "id": item.id, "kind": item.kind.as_str() })); taken_keys.push(item_key.clone()); } if let Some(landed_) = arrival.landed { if landed_["request"] == json!(true) { let thread = landed_["thread"].clone(); if !requests.contains(&thread) { requests.push(thread); } } landed.push(landed_); } if let Some(thread) = arrival.request { let thread = json!(thread); if !requests.contains(&thread) { requests.push(thread); } } if let Some(r) = arrival.receipt { // Read on another of this person's phones: the shell takes that chat's notices down. if item.out && payload.state == Some(Receipt::Read) && r["messages"].as_array().is_some_and(|a| !a.is_empty()) && !read.contains(&r["thread"]) { read.push(r["thread"].clone()); } receipts.push(r); } if let Some(c) = arrival.changed { changed.push(c); } if let Some((peer, id)) = arrival.tick { group_ticks.entry((peer, item.group.clone().unwrap_or_default())).or_default().push(id); } continue; } if item.kind != Kind::Typing { taken.push(json!({ "id": item.id, "kind": item.kind.as_str() })); taken_keys.push(item_key); } match payload.kind { // A group's change outside any group: no such thing. Kind::Group | Kind::Agent => dropped += 1, Kind::Typing => { // Drawn only while this person's own typing switch is on. if !item.out && signals && own_typing { typing.push(json!({ "thread": chat_with_number(client, &ns, &item.peer), "on": payload.on == Some(true) })); } } Kind::Message => { let (n, it, p) = (ns.clone(), item.clone(), payload.clone()); let (person, name) = person_of(client, &item.peer); let said = name.clone(); let answer = write(client, "chat.land", move |ctx| land(ctx, &n, &it, &p, person.as_deref(), name.as_deref()))?; if answer["new"] == json!(true) { let thread = answer["thread"].as_str().unwrap_or_default().to_string(); if answer["request"] == json!(true) { if !requests.contains(&json!(thread)) { requests.push(json!(thread)); } } else if !item.out { to_tell.entry(item.peer.clone()).or_default().push(payload.id.clone()); } // Who it is with, by the name this phone knows them by: the shell titles the lock screen's alerts with it. landed.push(json!({ "thread": thread, "message": answer["message"], "out": item.out, "request": answer["request"], "peer": item.peer, "name": said })); } } Kind::Change => { let (n, it, p) = (ns.clone(), item.clone(), payload.clone()); let answer = write(client, "chat.change", move |ctx| apply_change(ctx, &n, &it, &p))?; if !answer.is_null() { changed.push(answer); } } Kind::Receipt => { // Their Read was made a delivered above where this phone draws none. let (n, it, p) = (ns.clone(), item.clone(), payload.clone()); let answer = write(client, "chat.receipt", move |ctx| apply_receipt(ctx, &n, &it, &p))?; let thread = chat_with_number(client, &ns, &item.peer); if item.out && payload.state == Some(Receipt::Read) && answer.as_array().is_some_and(|a| !a.is_empty()) && !read.contains(&json!(thread)) { read.push(json!(thread)); } receipts.push(json!({ "thread": thread, "state": payload.state, "messages": answer })); } } } if let Some(asks) = asks { let (n, mine) = (ns.clone(), me.clone()); let answer = write(client, "chat.asks", move |ctx| land_asks(ctx, &n, &mine, &asks))?; for thread in answer.as_array().into_iter().flatten() { if !requests.contains(&thread["thread"]) { requests.push(thread["thread"].clone()); } landed.push(thread.clone()); } } if !taken.is_empty() { // Taken, whether it landed or was dropped: a box that does not open never will. if ask(client, "POST", routes::ACK, Some(&json!({ "items": taken }))).is_ok() { super::chat_ratchet::taken(client, &secret, &taken_keys); } } // A c2 box no session opened: its sealer is told on a fresh session, which its next words then go on. Only a sender // this person accepted is ever answered (DISCOVERY OFF 3): a box from anyone else (a request, or a number with no // accepted chat here) goes unanswered, so a crafted box never tells its maker whether this person accepted them. let mut reset: Vec<(String, bool, Vec)> = Vec::new(); for item in &unreadable { if !item.out && (item.request || !answers_to(client, &item.peer)?) { continue; } match reset.iter_mut().find(|(peer, out, _)| peer == &item.peer && *out == item.out) { Some((_, _, ids_)) => ids_.push(item.id.clone()), None => reset.push((item.peer.clone(), item.out, vec![item.id.clone()])), } } for (peer, out, mut ids_) in reset { ids_.truncate(payload::RECEIPT_IDS_MAX); let notice = Payload::receipt(&fresh_id(), &me, &peer, now_ms(client), Receipt::Unreadable, ids_); let _ = if out { tell_own(client, &secret, &peer, notice) } else { tell(client, &secret, &peer, notice, false) }; } // A device told this phone it lost these: each of this person's messages among them goes again, to it alone. let mut resent = Vec::new(); for (peer, out, handle, ids_) in lost { resent.extend(resend_lost(client, &secret, &peer, out, &handle, &ids_)); } // The tick: each accepted conversation is told what arrived, from this phone, at once. for (peer, ids_) in to_tell { let _ = tell(client, &secret, &peer, Payload::receipt(&fresh_id(), &me, &peer, now_ms(client), Receipt::Delivered, ids_), false); } // In a group the tick goes to the message's writer alone, naming the group. for ((peer, group), ids_) in group_ticks { let _ = tell(client, &secret, &peer, Payload::receipt(&fresh_id(), &me, &peer, now_ms(client), Receipt::Delivered, ids_).in_group(&group), false); } if acted { let _ = flush(client, &secret); } // What landed reaches this person's agents in the chats they are in (chat_agent). super::chat_agent::feed(client); Ok(json!({ "landed": landed, "receipts": receipts, "typing": typing, "requests": requests, "changed": changed, "read": read, "dropped": dropped, "waiting": waits, "resent": resent })) } /// The handle of the device that sealed a c2 item: one the sender's number publishes (this person's own for `out`). fn sender_handle(client: &ClientController, item: &Item) -> Option { let identity = super::chat_ratchet::sealer_of(item)?; let keys = keys_for(client, &item.peer, i64::MAX).ok()?; let senders = if item.out { keys.own } else { keys.devices }; senders.into_iter().find(|(h, k)| super::chat_ratchet::names(client, h, k, &identity)).map(|(h, _)| h) } /** * A ratchet reset's lost words sent again (SEALING.md, "A session lost on one side"): a device told this phone, on a * fresh session, that boxes it got opened nothing. Each of this person's own messages among them (one to one, with * `peer`; sent and still there: never one deleted or hidden) is sealed again for that one device alone, on the * session its notice made, and marked so it goes once (`meta.cotton.resent` names the device): a second notice for * the same id sends nothing, from this phone or, as the row syncs, the person's others. The object takes it once for * that device too, at the first send's time, so it lands in its place. With `out` the device is one of this person's * own, which lost its copy. Answers the messages that went. */ fn resend_lost(client: &ClientController, secret: &[u8; 32], peer: &str, out: bool, handle: &str, lost: &[String]) -> Vec { let (Ok(ns), Some(me), Ok(keys)) = (namespace(client), my_number(client), keys_for(client, peer, KEYS_FRESH_MS)) else { return Vec::new() }; let Some(key) = (if out { &keys.own } else { &keys.devices }).iter().find(|(h, _)| h == handle).map(|(_, k)| *k) else { return Vec::new() }; let thread = chat_with_number(client, &ns, peer); let mut went = Vec::new(); for external in lost.iter().take(payload::RECEIPT_IDS_MAX) { let id = ids::message_id(&ns, ids::ME, external); let Ok(row) = read(client, "chat.lost", |ctx| { one(ctx, &format!("SELECT thread_id, direction, body, reply_to_external_id, meta, send_state, deleted_at, hidden_at, trashed_at FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())]).map(|r| r.map(Value::Object).unwrap_or(Value::Null)) }) else { continue; }; let meta = meta_value(&row["meta"]); let sent = matches!(row["send_state"].as_str(), Some("sent" | "delivered" | "read")); let gone = !row["deleted_at"].is_null() || !row["hidden_at"].is_null() || !row["trashed_at"].is_null(); let once = meta["cotton"]["resent"].as_array().is_some_and(|a| a.iter().any(|h| h == handle)); if row["thread_id"].as_str() != Some(thread.as_str()) || row["direction"] != json!("out") || !sent || gone || once { continue; } let pictures: Vec = serde_json::from_value(meta["cotton"]["pictures"].clone()).unwrap_or_default(); let written = meta["cotton"]["written_at"].as_str().and_then(ms_of).unwrap_or_else(|| now_ms(client)); let body = row["body"].as_str().filter(|b| !b.is_empty()).map(str::to_string); let mut message = Payload::message(external, &me, peer, written, body, row["reply_to_external_id"].as_str().map(str::to_string), pictures); message.profile = super::chat_people::own_profile(client); message.timer = super::chat_timer::seconds_of(&meta); message.preview = preview_of_meta(&meta); let target = super::chat_ratchet::Target { number: if out { me.as_str() } else { peer }, handle, key: &key }; let answer = super::chat_ratchet::seal_boxes(client, secret, &[target], &message) .and_then(|boxes| ask(client, "POST", routes::SEND, Some(&json!({ "to": peer, "id": external, "kind": "message", "boxes": boxes, "resend": true })))); match answer { Ok(_) => {} // Nothing answered: a later notice may try again. A refusal is the object's last word. Err(refusal) if refusal.status == 0 => continue, Err(_) => {} } let (id_, h) = (id.clone(), handle.to_string()); let marked = write(client, "chat.resent", move |ctx| { let mut meta = meta_of(ctx, &id_)?; let mut list = meta["cotton"]["resent"].as_array().cloned().unwrap_or_default(); list.push(json!(h)); meta["cotton"]["resent"] = json!(list); let mut patch = Map::new(); patch.insert("meta".into(), meta); update_row(ctx, MESSAGES, &id_, patch).map_err(|f| f.to_string())?; Ok(Value::Null) }); if marked.is_ok() { went.push(id); } } went } /// The person read a conversation: every message of theirs is marked read here, and they are told so when the person's setting says. fn read_receipt(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; let thread = text(request, "thread")?.to_string(); let group = super::chat_group::is_group_thread(client, &thread); let number = if group { String::new() } else { thread_number(client, &thread)? }; // A request is not read until it is accepted: its sender learns nothing // before then, and the receipt the acceptance asks for tells them then. if !accepted(client, &thread)? { return Ok(json!({ "read": 0, "told": false })); } let now = iso(now_ms(client)); let t = thread.clone(); let read_ids = write(client, "chat.read", move |ctx| { let rows = rows(ctx, &format!("SELECT id, external_id, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'in' AND read_at IS NULL AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(t.clone())])?; let mut said = Vec::new(); for row in rows { let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); let mut patch = Map::new(); patch.insert("read_at".into(), json!(now)); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; // A group's event line, or an ask's, is nobody's message to tell of. let meta = meta_value(row.get("meta").unwrap_or(&Value::Null)); if meta.get("system").is_some_and(|s| s.is_object() || s == &json!(true)) || meta["cotton"]["ask"] == json!(true) { continue; } if let Some(external) = row.get("external_id").and_then(Value::as_str) { let from = meta["cotton"]["from"].clone(); said.push(json!({ "id": external, "from": from })); } } Ok(Value::Array(said)) })?; let said: Vec<(String, Option)> = read_ids.as_array().into_iter().flatten().filter_map(|v| Some((v["id"].as_str()?.to_string(), v["from"].as_str().map(str::to_string)))).collect(); if said.is_empty() { return Ok(json!({ "read": 0, "told": false })); } // Told only where both switches are on, this person's and the writer's (`may_tell_read`); the // person's own other devices are told either way, with the receipt or at the next flush. let mut told = false; let mut own_told = false; if group { // In a group each writer is told of their own messages, naming the group. let mut by: HashMap> = HashMap::new(); for (id, from) in &said { if let Some(from) = from.as_ref().filter(|from| may_tell_read(client, from)) { by.entry(from.clone()).or_default().push(id.clone()); } } if !by.is_empty() { let gid = super::chat_group::group_of_thread(client, &thread)?; let me = my_number(client).ok_or_else(not_connected)?; told = true; for (writer, ids_) in by { told &= tell(client, &secret, &writer, Payload::receipt(&fresh_id(), &me, &writer, now_ms(client), Receipt::Read, ids_).in_group(&gid), true).is_ok(); } own_told = told; } } else if may_tell_read(client, &number) { let me = me_or_ask(client, &number)?; let ids_: Vec = said.iter().map(|(id, _)| id.clone()).collect(); told = tell(client, &secret, &number, Payload::receipt(&fresh_id(), &me, &number, now_ms(client), Receipt::Read, ids_), true).is_ok(); own_told = told; } if !own_told { // Nobody else told: this person's other phones still learn it was read here (`wait_read`, sent at the flush). let (t, ids_, at) = (thread.clone(), said.iter().map(|(id, _)| id.clone()).collect::>(), now_ms(client)); write(client, "chat.read", move |ctx| wait_read(ctx, &t, &ids_, at).map(|_| Value::Null))?; } Ok(json!({ "read": said.len(), "told": told, "flush": !own_told })) } fn typing(client: &ClientController, request: &Value) -> Result { let secret = private_key(request)?; let thread = text(request, "thread")?.to_string(); let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| bad("on", "true or false"))?; // Nobody in a group is told of typing (it would fan out to every member at every key). if super::chat_group::is_group_thread(client, &thread) { return Ok(json!({ "told": false })); } let number = thread_number(client, &thread)?; if !may_tell_typing(client, &number) || !accepted(client, &thread)? { return Ok(json!({ "told": false })); } let me = me_or_ask(client, &number)?; let told = tell(client, &secret, &number, Payload::typing(&fresh_id(), &me, &number, now_ms(client), on), false).is_ok(); Ok(json!({ "told": told })) } /// The person's answer to a conversation's request, or a block. fn decide(client: &ClientController, request: &Value, verb: &'static str) -> Result { // An SMS chat's sender is blocked as every sender is (SENDERS.md): a row of his copy, synced to his phones, his // chat then only in Blocked. Nothing goes to Cotton's server (DECISIONS "SMS on Android"). if let (Some(thread), "block" | "unblock") = (request.get("thread").and_then(Value::as_str), verb) { if let Some(key) = super::chat_sms::sender_key(client, thread)? { return super::chat_app::senders::act(client, &json!({ "key": key, "act": verb })); } } if let Some(thread) = request.get("thread").and_then(Value::as_str).filter(|t| super::chat_group::is_group_thread(client, t)) { return super::chat_group::decide(client, thread, verb); } let (thread, number) = match request.get("thread").and_then(Value::as_str) { // A WhatsApp chat is blocked on WhatsApp itself, through the Mac (owner, 24 Nov 2026). Some(thread) if matches!(verb, "block" | "unblock") && thread_number(client, thread).is_err_and(|e| e.code == "not_cotton") => { return whatsapp_block(client, thread, verb == "block"); } Some(thread) => (Some(thread.to_string()), thread_number(client, thread)?), None => (None, e164(text(request, "number")?).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use."))?), }; ask(client, "POST", &routes::verb(verb), Some(&json!({ "number": number }))).map_err(refused)?; let ns = namespace(client)?; let thread = thread.unwrap_or_else(|| chat_with_number(client, &ns, &number)); let now = iso(now_ms(client)); let (decided, whose) = (thread.clone(), number.clone()); write(client, "chat.decide", move |ctx| { match verb { "accept" => { set_request(ctx, &thread, "accepted", false)?; // An ask's line said "Accept to see their messages": answered, it goes; their messages follow. for row in rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id LIKE '{ASK_ID}%' AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone())])? { let mut patch = Map::new(); patch.insert("trashed_at".into(), json!(now)); update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?; } } "refuse" | "block" => { // What the request brought goes; a conversation the person had kept stays (a block of a friend keeps the past). let pending = request_of(ctx, &thread)?.as_deref() == Some("pending"); if pending { for row in rows(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone())])? { let mut patch = Map::new(); patch.insert("trashed_at".into(), json!(now)); update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?; } let mut patch = Map::new(); patch.insert("trashed_at".into(), json!(now)); if exists(ctx, THREADS, &thread)? { update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?; } } if verb == "block" { set_blocked(ctx, &number, true)?; } } "unblock" => set_blocked(ctx, &number, false)?, _ => {} } Ok(Value::Null) })?; // Accepted: what the request brought is told delivered now (the tick waited for this, so a stranger learned // nothing before). Without the chat key nothing is told, as before. if verb == "accept" && request.get("privateKey").is_some() { tick_accepted(client, &*private_key(request)?, &decided, &whose)?; } Ok(json!({ "ok": true })) } /// The delivered tick for their messages in a conversation just accepted: never their ask's line or an event line. fn tick_accepted(client: &ClientController, secret: &[u8; 32], thread: &str, number: &str) -> Result<(), MethodError> { let t = thread.to_string(); let found = read(client, "chat.accepted", move |ctx| { let rows = rows(ctx, &format!("SELECT external_id, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'in' AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(t.clone())])?; let ids: Vec = rows .iter() .filter(|row| { let meta = meta_value(row.get("meta").unwrap_or(&Value::Null)); !(meta.get("system").is_some_and(|s| s.is_object() || s == &json!(true)) || meta["cotton"]["ask"] == json!(true)) }) .filter_map(|row| row.get("external_id").and_then(Value::as_str).map(|id| json!(id))) .collect(); Ok(Value::Array(ids)) })?; let mut ids_: Vec = found.as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect(); if ids_.is_empty() { return Ok(()); } ids_.truncate(payload::RECEIPT_IDS_MAX); let me = me_or_ask(client, number)?; let _ = tell(client, secret, number, Payload::receipt(&fresh_id(), &me, number, now_ms(client), Receipt::Delivered, ids_), false); Ok(()) } fn settings(client: &ClientController, request: &Value) -> Result { let (mut read, mut typing) = preferences(client); if let Some(on) = request.get("readReceipts").and_then(Value::as_bool) { read = on; } if let Some(on) = request.get("typing").and_then(Value::as_bool) { typing = on; } // Link previews: this phone's fetching, on unless turned off here (FEEDBACK-4 B4). let previews = request.get("linkPreviews").and_then(Value::as_bool).unwrap_or_else(|| link_previews(client)); let kept = json!({ "readReceipts": read, "typing": typing, "linkPreviews": previews }); // The voice speed is the person's, synced (chat_voice); the switches are this phone's. let voice_speed = match request.get("voiceSpeed") { Some(asked) => super::chat_voice::set_speed(client, asked)?, None => super::chat_voice::speed(client), }; // `offered`: whether the app's chats signal at all; where they do not the shell draws no switch. let answer = json!({ "readReceipts": read, "typing": typing, "offered": signals(client), "voiceSpeed": voice_speed, "linkPreviews": previews }); if request.get("readReceipts").is_some() || request.get("typing").is_some() || request.get("linkPreviews").is_some() { let path = client.layout().client_dir().join(PREFERENCES); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| MethodError::new("unwritable", format!("{PREFERENCES}: {e}")))?; } // not a copy: Chat's own files (preferences, a plain export, what it holds). std::fs::write(&path, kept.to_string()).map_err(|e| MethodError::new("unwritable", format!("{PREFERENCES}: {e}")))?; } Ok(answer) } /// A picture a message carries, fetched, opened and checked, written into `dir`. fn picture(client: &ClientController, request: &Value) -> Result { let message = text(request, "message")?.to_string(); let index = request.get("index").and_then(Value::as_u64).unwrap_or(0) as usize; let dir = std::path::PathBuf::from(text(request, "dir")?); // A file on its way to WhatsApp through the Mac (`outbox:`): his own media's copy, kept at the tap, so it // is drawn at once and asked of no one. if let Some(row) = message.strip_prefix(super::chat_app::whatsapp_send::PENDING) { let row = row.to_string(); let found = read(client, "chat.picture.outbox", |ctx| Ok(json!(super::chat_app::whatsapp_send::file_of(ctx, &row)?)))?; let (key, mime): (String, String) = serde_json::from_value(found).ok().filter(|_| index == 0).ok_or_else(|| MethodError::new("not_found", "This message has no such picture."))?; let landed = super::media::land(client, key, super::media::Tier::Original, super::media::Asker::Person)?; return Ok(json!({ "path": landed.path.to_string_lossy(), "mime": mime })); } // Counted as the bubble counts them: an import's pictures first (the person's own media, a // WhatsApp picture uploaded from the Mac), then the Cotton message's files. let row = super::chat_files::message_row(client, "chat.picture", &message)?; match super::chat_files::attached(&row, index).ok_or_else(|| MethodError::new("not_found", "This message has no such picture."))? { super::chat_files::Attached::Imported(media) => { let path = super::chat_files::imported_path(client, &media)?; // No preview yet: the phone makes one from this file and hands it to `chat.preview` (chat_ahead). Ok(json!({ "path": path.to_string_lossy(), "mime": media.content_type, "previewWanted": media.preview.is_none() })) } super::chat_files::Attached::Cotton(at, picture) => { let wanted = picture.preview.is_none(); // Kept in the person's own media: from there, as `chat.file` does, so it still opens once the chat store's thirty days are over. let meta = meta_value(&row["meta"]); if let Some(key) = meta["cotton"]["pictures"][at]["kept"].as_str() { if let Ok(landed) = super::media::land(client, key.to_string(), super::media::Tier::Original, super::media::Asker::Person) { return Ok(json!({ "path": landed.path.to_string_lossy(), "mime": picture.mime, "previewWanted": wanted })); } } // One fetch of a file at a time: a fetch ahead of the scroll may be bringing it now (chat_ahead), and is waited for. let _turn = super::chat_ahead::file_turn(&picture.file); let row = super::chat_files::message_row(client, "chat.picture", &message)?; if let Some(key) = meta_value(&row["meta"])["cotton"]["pictures"][at]["kept"].as_str() { if let Ok(landed) = super::media::land(client, key.to_string(), super::media::Tier::Original, super::media::Asker::Person) { return Ok(json!({ "path": landed.path.to_string_lossy(), "mime": picture.mime, "previewWanted": wanted })); } } let may_be_gone = super::chat_files::may_be_gone(client, &row); // Within minutes of it, whatever kept the picture (no connection, the store not settled) is "not yet": the phone asks again soon and never says it is not available. let opened = open_picture(client, &picture, &dir, may_be_gone).map_err(|e| if may_be_gone || e.code == "unreadable" { e } else { MethodError::new("not_yet", e.message) })?; // Seen, so kept in the person's own media as `chat.file` keeps a file: counted under // Storage's Photos and files, and opened from there again, past the chat store's thirty days. if let Some(path) = opened["path"].as_str() { let _ = super::chat_files::keep(client, &message, row["thread_id"].as_str().unwrap_or_default(), at, std::path::Path::new(path), &picture); } let mut opened = opened; opened["previewWanted"] = json!(wanted); Ok(opened) } // Still going up: the phone's own file, at once, asked of no one. super::chat_files::Attached::Pending(path, mime) if path.is_file() => Ok(json!({ "path": path.to_string_lossy(), "mime": mime })), // Written on another phone of theirs and still going up there: on its way here, never gone. super::chat_files::Attached::Pending(..) => Err(MethodError::new("not_yet", "The picture is still going up from the phone it was sent from.")), } } /// A sealed chat file fetched, opened, checked and written into `dir`. A /// file the chat store answered it does not hold for waits, as the person's /// own media does (`cotton_client::media::absent`): the same refusal, with no /// request, until its wait is over. Unless `may_be_gone` (a message still /// sending, or written or landed within minutes: `files::may_be_gone`), a miss /// is only "not yet": asked again, never kept as gone. pub(crate) fn open_picture(client: &ClientController, picture: &Picture, dir: &std::path::Path, may_be_gone: bool) -> Result { let gone = || MethodError::new("not_found", "The picture has gone from the store."); let key = seal::key_from_text(&picture.key).ok_or_else(|| MethodError::new("unreadable", "the picture's key is not one"))?; let now = client.now().timestamp_millis(); if may_be_gone && client.absent_media().waits(&picture.file, now).is_some() { return Err(gone()); } let door = client.object_door().ok_or_else(not_connected)?; let (status, bytes) = door.address.send_bytes(door.exchange.as_ref(), "GET", &routes::file(&picture.file), bearer(&door.credential), None).map_err(refused)?; if status != 200 { if !may_be_gone { return Err(MethodError::new("not_yet", "The picture is not in the store yet.")); } if cotton_client::media::absent::is_held_answer(status) { client.absent_media().note(&picture.file, status, now); } return Err(gone()); } client.absent_media().forget(&picture.file); let plain = files::open_file(&key, &bytes, &picture.sha256).ok_or_else(|| MethodError::new("unreadable", "The picture did not open."))?; std::fs::create_dir_all(dir).map_err(|e| MethodError::new("unwritable", e.to_string()))?; let path = dir.join(format!("{}.{}", picture.sha256, extension(&picture.mime))); // not a copy: Chat's own files (preferences, a plain export, what it holds). std::fs::write(&path, plain).map_err(|e| MethodError::new("unwritable", e.to_string()))?; Ok(json!({ "path": path.to_string_lossy(), "mime": picture.mime })) } // ── sealing, opening and telling ──────────────────────────────────────── /// One payload sealed for `number`'s devices and this person's own (`me`'s) ones, each `c2` or `c1` as it speaks. #[allow(clippy::too_many_arguments)] fn boxes(client: &ClientController, secret: &[u8; 32], number: &str, theirs: &[(String, [u8; 32])], me: &str, own: &[(String, [u8; 32])], payload: &Payload) -> Result, ObjectRefusal> { // A message, a tick, typing: each carries this person's two switches, sealed, so the other side knows what it may tell. let carried; let says = matches!(payload.kind, Kind::Message | Kind::Typing) || (payload.kind == Kind::Receipt && payload.state != Some(Receipt::Unreadable)); let payload = if says && payload.signals.is_none() { let mut with = payload.clone(); with.signals = own_signals(client); carried = with; &carried } else { payload }; let targets: Vec> = theirs .iter() .map(|(handle, key)| super::chat_ratchet::Target { number, handle, key }) .chain(own.iter().map(|(handle, key)| super::chat_ratchet::Target { number: me, handle, key })) .collect(); let out = super::chat_ratchet::seal_boxes(client, secret, &targets, payload)?; if out.is_empty() { return Err(local("no device to seal for".into())); } Ok(out) } /// A receipt or typing for one person: their devices, and with `own` this person's other devices too. fn tell(client: &ClientController, secret: &[u8; 32], number: &str, payload: Payload, own: bool) -> Result<(), ObjectRefusal> { let keys = keys_for(client, number, KEYS_FRESH_MS)?; let me = my_number(client).ok_or_else(not_connected_refusal)?; let boxes = boxes(client, secret, number, &keys.devices, &me, if own { &keys.own } else { &[] }, &payload)?; let mut body = json!({ "to": number, "id": payload.id, "kind": payload.kind.as_str(), "boxes": boxes }); if let Some(group) = &payload.group { body["group"] = json!(group); } ask(client, "POST", routes::SEND, Some(&body)).map(|_| ()) } /// A receipt for this person's own other devices alone: none of theirs. No other device is no one to tell. fn tell_own(client: &ClientController, secret: &[u8; 32], number: &str, payload: Payload) -> Result<(), ObjectRefusal> { // The person's own devices asked afresh (uncounted by the object): a phone they signed in on a minute ago is told too. let me = my_number(client).ok_or_else(not_connected_refusal)?; let keys = keys_for(client, &me, 0)?; if keys.own.is_empty() { return Ok(()); } let boxes = boxes(client, secret, &me, &[], &me, &keys.own, &payload)?; ask(client, "POST", routes::SEND, Some(&json!({ "to": number, "id": payload.id, "kind": payload.kind.as_str(), "boxes": boxes }))).map(|_| ()) } fn not_connected_refusal() -> ObjectRefusal { ObjectRefusal { status: 0, code: "not_connected".into(), message: "this phone's number is not known yet".into() } } /// An item opened and checked against the keys its sender published (asked again once when its key is new here). fn open_item(client: &ClientController, secret: &[u8; 32], item: &Item, me: &str) -> super::chat_ratchet::Opened { use super::chat_ratchet::Opened; // Who could have sealed it: the sender's devices, or for a copy of this person's own words their own. let mine = cotton_core::vault::wrap::public_of(secret); let sealer = if seal_is_c2(item) { super::chat_ratchet::sealer_of(item) } else { seal::open(secret, &item.sealed).map(|o| o.sender) }; let Some(sealer) = sealer else { return Opened::Dropped }; let senders = |keys: &Keys| if item.out { keys.own.clone() } else { keys.devices.clone() }; let known = |keys: &Keys| { senders(keys).iter().any(|(h, k)| if seal_is_c2(item) { super::chat_ratchet::names(client, h, k, &sealer) } else { k == &sealer }) || (!seal_is_c2(item) && item.out && sealer == mine) }; let Ok(mut keys) = keys_for(client, &item.peer, i64::MAX) else { return Opened::Dropped }; if !known(&keys) { // A device new here, or one whose ratchet is new: its keys are asked again, once. let Ok(fresh) = keys_for(client, &item.peer, 0) else { return Opened::Dropped }; keys = fresh; } if !known(&keys) { return Opened::Dropped; } super::chat_ratchet::open(client, secret, item, me, &senders(&keys)) } fn seal_is_c2(item: &Item) -> bool { cotton_core::chat::ratchet::is_c2(&item.sealed) } /// Tests: every number's keys asked again at the next send. #[cfg(test)] pub(crate) fn forget_keys(client: &ClientController) { memory(client, |m| m.keys.clear()); } /// A device's c2 record, as its keys answer last said it. pub(crate) fn record_of(client: &ClientController, handle: &str) -> Option { memory(client, |m| m.records.get(handle).cloned()) } /// The c2 records a keys answer carries, remembered by handle; a device answered without one has none. fn remember_records(client: &ClientController, list: &Value) { let records = super::chat_ratchet::records_of(list); memory(client, move |m| { for (handle, record) in records { match record { Some(r) => m.records.insert(handle, r), None => m.records.remove(&handle), }; } }); } /// The keys to seal for when writing to `number`, asked again when older than `fresh_ms`. fn keys_for(client: &ClientController, number: &str, fresh_ms: i64) -> Result { let now = now_ms(client); if let Some(held) = memory(client, |m| m.keys.get(number).cloned()) { if now.saturating_sub(held.at) < fresh_ms { return Ok(held); } } let answer = ask(client, "GET", &routes::keys(number), None)?; remember_me(client, &answer); remember_records(client, &answer["devices"]); remember_records(client, &answer["own"]); let list = |field: &str| -> Vec<(String, [u8; 32])> { answer[field].as_array().into_iter().flatten().filter_map(|k| Some((k["device"].as_str()?.to_string(), seal::key_from_text(k["key"].as_str()?)?))).collect() }; let keys = Keys { devices: list("devices"), own: list("own"), at: now }; let held = keys.clone(); memory(client, move |m| m.keys.insert(number.to_string(), held)); // Asked afresh: their safety number is compared with the one kept (chat_safety). super::chat_safety::observe(client, number, &keys.devices); Ok(keys) } /// `number`'s devices and this person's own other devices, asked afresh (`chat.safety`). pub(crate) fn keys_now(client: &ClientController, number: &str) -> Result<(Vec<(String, [u8; 32])>, Vec<(String, [u8; 32])>), ObjectRefusal> { let keys = keys_for(client, number, 0)?; Ok((keys.devices, keys.own)) } fn me_or_ask(client: &ClientController, number: &str) -> Result { if let Some(me) = memory(client, |m| m.me.clone()) { return Ok(me); } keys_for(client, number, 0).map_err(refused)?; memory(client, |m| m.me.clone()).ok_or_else(not_connected) } /// This phone's own number, when known. pub(crate) fn me(client: &ClientController) -> Option { memory(client, |m| m.me.clone()) } /// This phone's own number, learnt elsewhere. pub(crate) fn remember(client: &ClientController, me: &str) { let me = me.to_string(); memory(client, move |m| m.me = Some(me)); } /// A test's phone that knows its own number already, as one signed in does. #[cfg(test)] pub(crate) fn remember_number(client: &ClientController, number: &str) { let number = number.to_string(); memory(client, move |m| m.me = Some(number)); } fn remember_me(client: &ClientController, answer: &Value) { if let Some(me) = answer["me"].as_str().and_then(e164) { memory(client, move |m| m.me = Some(me)); } } fn memory(client: &ClientController, f: impl FnOnce(&mut ChatMemory) -> R) -> R { let mut held = client.chat_memory().lock().unwrap_or_else(|p| p.into_inner()); f(&mut held) } /// This phone's number: remembered, else asked of its object once. /// The person's own number as this phone already knows it, never asked of the server (a page drawn reads it). pub(crate) fn own_number(client: &ClientController) -> Option { memory(client, |m| m.me.clone()) } /// This person's number as this phone already holds it, never asking the object. pub(crate) fn known_number(client: &ClientController) -> Option { memory(client, |m| m.me.clone()) } pub(crate) fn my_number(client: &ClientController) -> Option { if let Some(me) = memory(client, |m| m.me.clone()) { return Some(me); } let answer = ask(client, "GET", routes::INBOX, None).ok()?; remember_me(client, &answer); memory(client, |m| m.me.clone()) } /// The keys to seal for when saying something to several numbers (a group's /// members) and this person's own other devices: each number's devices, asked /// together, kept as `keys_for` keeps one number's, asked again when older /// than `fresh_ms`. #[allow(clippy::type_complexity)] pub(crate) fn keys_many(client: &ClientController, numbers: &[String], fresh_ms: i64) -> Result<(HashMap>, Vec<(String, [u8; 32])>), ObjectRefusal> { let now = now_ms(client); let mut out = HashMap::new(); let mut own: Option> = None; let mut stale = Vec::new(); for number in numbers { match memory(client, |m| m.keys.get(number).cloned()) { Some(held) if now.saturating_sub(held.at) < fresh_ms => { own.get_or_insert(held.own.clone()); out.insert(number.clone(), held.devices); } _ => stale.push(number.clone()), } } for chunk in stale.chunks(64) { let answer = ask(client, "POST", "/v1/chat/keys", Some(&json!({ "numbers": chunk })))?; remember_me(client, &answer); remember_records(client, &answer["own"]); for list in answer["peers"].as_object().into_iter().flatten().map(|(_, l)| l) { remember_records(client, list); } let list = |value: &Value| -> Vec<(String, [u8; 32])> { value.as_array().into_iter().flatten().filter_map(|k| Some((k["device"].as_str()?.to_string(), seal::key_from_text(k["key"].as_str()?)?))).collect() }; let own_now = list(&answer["own"]); for number in chunk { let devices = list(&answer["peers"][number]); let held = Keys { devices: devices.clone(), own: own_now.clone(), at: now }; let n = number.clone(); memory(client, move |m| m.keys.insert(n, held)); super::chat_safety::observe(client, number, &devices); out.insert(number.clone(), devices); } own = Some(own_now); } let own = match own { Some(own) => own, None => own_keys(client)?, }; Ok((out, own)) } /// This person's own other devices' keys. pub(crate) fn own_keys(client: &ClientController) -> Result, ObjectRefusal> { let me = my_number(client).ok_or_else(|| local("this phone's number is not known yet".into()))?; Ok(keys_for(client, &me, KEYS_FRESH_MS)?.own) } /// One payload sealed for each of `number`'s devices, by handle, `c2` or `c1` as each speaks (a device whose key is /// unusable is left out); refused whole for a device that spoke c2 and no longer offers it. pub(crate) fn seal_for(client: &ClientController, secret: &[u8; 32], number: &str, keys: &[(String, [u8; 32])], payload: &Payload) -> Result, ObjectRefusal> { let targets: Vec> = keys.iter().map(|(handle, key)| super::chat_ratchet::Target { number, handle, key }).collect(); super::chat_ratchet::seal_boxes(client, secret, &targets, payload) } pub(crate) fn private_key_of(request: &Value) -> Result, MethodError> { private_key(request) } /// A sealed file put in the chat file store: `{ file }`. pub(crate) fn put_sealed(client: &ClientController, bytes: &[u8]) -> Result { put_bytes(client, routes::FILES, bytes) } /// A person's first phone in this copy. pub(crate) fn first_number(client: &ClientController, person: &str) -> Result, MethodError> { Ok(number_of(client, person)?.0) } pub(crate) fn request_state(ctx: &mut Ctx<'_>, thread: &str) -> Result, String> { request_of(ctx, thread) } // ── the rows ──────────────────────────────────────────────────────────── /// The phone handle row of a contact reached by `number` (PEOPLE BUILD 1: every channel writes its contact's handle, /// so who(handle), Senders and how often he is in touch with someone read Cotton chat, SMS and groups as they read /// WhatsApp). Under the id every device derives for it, written once; a number already held by another contact's /// handle stays that contact's. A number the one normaliser does not read writes nothing. pub(crate) fn contact_handle_here(ctx: &mut Ctx<'_>, ns: &str, contact: &str, number: &str) -> Result<(), String> { let Some((kind, value)) = cotton_store::protocol::who::who_key(cotton_store::protocol::person_handles::HandleKind::Phone, number, None) else { return Ok(()); }; let held = one(ctx, "SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ? AND kind = ? AND value = ?", &[ws(ctx), SqlValue::Text(kind.to_string()), SqlValue::Text(value.clone())])?; if held.is_some() { return Ok(()); } let id = cotton_core::cotton_rules::ids::contact_handle_id(ns, kind, &value); let mut columns = Map::new(); columns.insert("contact_id".into(), json!(contact)); columns.insert("kind".into(), json!(kind)); columns.insert("value".into(), json!(value)); insert_row(ctx, "cotton_msg_contact_handles", &id, columns).map_err(|f| f.to_string()) } /// The thread with `number`, its contact, made when new. `request` sets a new thread's request state. /// `on_cotton`: the number is known to be on Cotton (it wrote here); a chat this person starts says so only once Cotton finds them (chat-people). pub(crate) fn ensure_thread(ctx: &mut Ctx<'_>, ns: &str, number: &str, name: Option<&str>, person: Option<&str>, request: Option<&str>, on_cotton: bool) -> Result { let digits = number.trim_start_matches('+').to_string(); let contact = match one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])? { Some(row) => row.get("id").and_then(Value::as_str).unwrap_or_default().to_string(), None => { let id = ids::contact_id(ns, number); let mut columns = Map::new(); columns.insert("phone_e164".into(), json!(digits)); columns.insert("display_name".into(), json!(name.unwrap_or(number))); if let Some(person) = person { columns.insert("person_id".into(), json!(person)); } if on_cotton { columns.insert("on_cotton_at".into(), json!(now_iso(ctx))); } insert_row(ctx, CONTACTS, &id, columns).map_err(|f| f.to_string())?; id } }; contact_handle_here(ctx, ns, &contact, &digits)?; let mut thread = chat_with(ctx, ns, number)?; if !exists(ctx, THREADS, &thread)? { // The store keeps one chat per contact (`uq_cotton_msg_threads_dm`): a chat that came from WhatsApp first is // that person's chat. Once they are one of the person's Cotton connections it becomes their Cotton chat too // (keyed `cotton:+…`), WhatsApp's messages standing in it; before that it is opened as it is (FEEDBACK-2 A). let held = one(ctx, &format!("SELECT id, external_key FROM {THREADS} WHERE workspace_id = ? AND contact_id = ? AND kind = 'dm' LIMIT 1"), &[ws(ctx), SqlValue::Text(contact.clone())])?; if let Some(found) = held { let id = found.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); let on = on_cotton || super::chat_people::on_cotton(ctx, number)?; if on { let mut patch = Map::new(); patch.insert("external_key".into(), json!(ids::external_key(number))); update_row(ctx, THREADS, &id, patch).map_err(|f| f.to_string())?; } // Never a request: a person he already has a chat with is someone he knows. return Ok(id); } } if !exists(ctx, THREADS, &thread)? { thread = ids::thread_id(ns, number); let mut columns = Map::new(); columns.insert("contact_id".into(), json!(contact)); columns.insert("kind".into(), json!("dm")); columns.insert("external_key".into(), json!(ids::external_key(number))); columns.insert("archived".into(), json!(false)); if let Some(request) = request { if holds(ctx, THREADS, "request")? { columns.insert("request".into(), json!(request)); } } insert_row(ctx, THREADS, &thread, columns).map_err(|f| f.to_string())?; } else if request == Some("pending") && request_of(ctx, &thread)?.is_none() { // A conversation the person never answered is still a request; one they wrote in or accepted is not. let written = one(ctx, &format!("SELECT 1 AS one FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'out' LIMIT 1"), &[ws(ctx), SqlValue::Text(thread.clone())])?; if written.is_none() { set_request(ctx, &thread, "pending", false)?; } } Ok(thread) } /// The Cotton chat with `number`: the one-to-one chat keyed `cotton:+…`, Cotton's own or one that came from WhatsApp /// first and became theirs on Cotton (`ensure_thread`), else the id Cotton's own is made under. pub(crate) fn chat_with(ctx: &mut Ctx<'_>, ns: &str, number: &str) -> Result { let found = one(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND kind = 'dm' AND external_key = ? LIMIT 1"), &[ws(ctx), SqlValue::Text(ids::external_key(number))])?; Ok(found.and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string)).unwrap_or_else(|| ids::thread_id(ns, number))) } /// [`chat_with`] from outside a read. pub(crate) fn chat_with_number(client: &ClientController, ns: &str, number: &str) -> String { let (n, nm) = (ns.to_string(), number.to_string()); read(client, "chat.with", move |ctx| chat_with(ctx, &n, &nm).map(Value::from)).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| ids::thread_id(ns, number)) } /// One opened message into its conversation: `{thread, message, new, request}`; a message already here is not written again. fn land(ctx: &mut Ctx<'_>, ns: &str, item: &Item, payload: &Payload, person: Option<&str>, name: Option<&str>) -> Result { let thread = ensure_thread(ctx, ns, &item.peer, name, person, item.request.then_some("pending"), true)?; if !item.out { // They wrote: they are on Cotton, and what they show of themselves is kept (chat-people). super::chat_people::mark_on_cotton_here(ctx, &item.peer)?; if let Some(profile) = &payload.profile { super::chat_people::take_profile(ctx, ns, &item.peer, profile)?; } } let request = item.request && request_of(ctx, &thread)?.as_deref() != Some("accepted"); let author = if item.out { ids::ME } else { item.peer.as_str() }; let id = ids::message_id(ns, author, &payload.id); if exists(ctx, MESSAGES, &id)? { return Ok(json!({ "thread": thread, "message": id, "new": false, "request": request })); } let sent_at = iso(item.at); let mut columns = Map::new(); columns.insert("thread_id".into(), json!(thread)); columns.insert("direction".into(), json!(if item.out { "out" } else { "in" })); columns.insert("channel".into(), json!(CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("body".into(), json!(payload.body.clone().unwrap_or_default())); columns.insert("external_id".into(), json!(payload.id)); columns.insert("sent_at".into(), json!(sent_at)); if item.out { columns.insert("send_state".into(), json!("sent")); } if let Some(reply) = &payload.reply_to { columns.insert("reply_to_external_id".into(), json!(reply)); let replied = one(ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND external_id = ?"), &[ws(ctx), SqlValue::Text(thread.clone()), SqlValue::Text(reply.clone())])?; if let Some(replied) = replied.and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) { columns.insert("reply_to_id".into(), json!(replied)); } } let mut meta = json!({ "cotton": { "pictures": payload.pictures, "written_at": iso(payload.at) } }); if let Some(seconds) = payload.timer { super::chat_timer::stamp(&mut meta, payload.at, seconds); } // Its link card, as the sender's phone fetched it, kept after the sender's own checks (FEEDBACK-4 B4). if let Some(card) = payload.preview.as_ref().and_then(|p| p.kept(payload.body.as_deref().unwrap_or_default())) { meta["preview"] = serde_json::to_value(card).unwrap_or(Value::Null); } columns.insert("meta".into(), meta); insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?; link_waiting_replies(ctx, &thread, &payload.id, &id)?; touch_thread(ctx, &thread, &sent_at, payload.body.as_deref(), !payload.pictures.is_empty())?; Ok(json!({ "thread": thread, "message": id, "new": true, "request": request })) } /// A reply that landed before the message it quotes (the object's order is its clock; a re-send can come late) /// names it only by its writer's id: once that message is here, the reply links to it, as an import links its /// replies (`UNLINKED_REPLIES_SQL`), so its quote stands. pub(crate) fn link_waiting_replies(ctx: &mut Ctx<'_>, thread: &str, external: &str, id: &str) -> Result<(), String> { let waiting = rows( ctx, &format!("SELECT id FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND reply_to_id IS NULL AND reply_to_external_id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string()), SqlValue::Text(external.to_string())], )?; for reply in waiting.iter().filter_map(|row| row.get("id").and_then(Value::as_str)) { let mut patch = Map::new(); patch.insert("reply_to_id".into(), json!(id)); update_row(ctx, MESSAGES, reply, patch).map_err(|f| f.to_string())?; } Ok(()) } /// Someone who asks to chat, as the inbox says them: their number, the name they gave by asking, and when. #[derive(Debug, Clone, serde::Deserialize)] pub(crate) struct Ask { pub number: String, #[serde(default)] pub name: Option, pub at: String, } /// The external id an ask's line is kept by: one line per ask, whichever of the person's phones lands it. const ASK_ID: &str = "ask:"; /** * Every ask the inbox lists lands as an ordinary request (21 Nov 2026): a conversation with them, * pending, holding one line of theirs in the chat set's words (`request.asked`): never a word of what they wrote, * which waits on their phone until this person accepts. Accept, Delete and Block are the request card's, as for a * stranger's message. An ask's line whose ask is no longer listed (refused or blocked on another phone, or taken * back) goes while the conversation is still a request. Answers the requests landed now, as `landed` entries. */ fn land_asks(ctx: &mut Ctx<'_>, ns: &str, me: &str, asks: &[Ask]) -> Result { let mut listed = std::collections::HashSet::new(); let mut landed = Vec::new(); for asked in asks { let Some(number) = e164(&asked.number) else { continue }; listed.insert(number.clone()); if number == me { continue; } let digits = number.trim_start_matches('+').to_string(); let blocked = one(ctx, &format!("SELECT blocked FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])?.is_some_and(|r| r.get("blocked") == Some(&json!(true)) || r.get("blocked") == Some(&json!(1))); let thread = chat_with(ctx, ns, &number)?; if blocked || request_of(ctx, &thread)?.as_deref() == Some("accepted") { continue; } let thread = ensure_thread(ctx, ns, &number, None, None, Some("pending"), true)?; let at = ms_of(&asked.at).unwrap_or(0); if let Some(name) = asked.name.as_deref().map(str::trim).filter(|n| !n.is_empty() && holds(ctx, CONTACTS, "profile").unwrap_or(false)) { // The name they gave by asking, as a stranger's own name is kept: theirs, never how this phone knows them. super::chat_people::take_profile(ctx, ns, &number, &payload::Profile { name: Some(name.to_string()), picture: None, at })?; } let external = format!("{ASK_ID}{}", asked.at); let id = ids::message_id(ns, &number, &external); if exists(ctx, MESSAGES, &id)? { continue; } let body = cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "request.asked", &[]); let mut columns = Map::new(); columns.insert("thread_id".into(), json!(thread)); columns.insert("direction".into(), json!("in")); columns.insert("channel".into(), json!(CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("body".into(), json!(body)); columns.insert("external_id".into(), json!(external)); let sent_at = iso(at); columns.insert("sent_at".into(), json!(sent_at)); columns.insert("meta".into(), json!({ "cotton": { "ask": true, "written_at": sent_at } })); insert_row(ctx, MESSAGES, &id, columns).map_err(|f| f.to_string())?; touch_thread(ctx, &thread, &sent_at, Some(&body), false)?; landed.push(json!({ "thread": thread, "message": id, "out": false, "request": true, "peer": number, "name": Value::Null, "ask": true })); } // An ask answered or taken back elsewhere: its line goes from a conversation that is still only a request. let held = rows(ctx, &format!("SELECT m.id AS id, m.thread_id AS thread_id, t.external_key AS external_key FROM {MESSAGES} m JOIN {THREADS} t ON t.id = m.thread_id WHERE m.workspace_id = ? AND m.external_id LIKE '{ASK_ID}%' AND m.trashed_at IS NULL"), &[ws(ctx)])?; let now = now_iso(ctx); for row in held { let thread = row.get("thread_id").and_then(Value::as_str).unwrap_or_default().to_string(); let number = row.get("external_key").and_then(Value::as_str).and_then(ids::number_of_key).map(str::to_string); if number.as_ref().is_some_and(|n| listed.contains(n)) || request_of(ctx, &thread)?.as_deref() == Some("accepted") { continue; } let mut patch = Map::new(); patch.insert("trashed_at".into(), json!(now)); update_row(ctx, MESSAGES, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?; let left = one(ctx, &format!("SELECT 1 AS one FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND (external_id IS NULL OR external_id NOT LIKE '{ASK_ID}%') LIMIT 1"), &[ws(ctx), SqlValue::Text(thread.clone())])?; if left.is_none() { let mut patch = Map::new(); patch.insert("trashed_at".into(), json!(now)); update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?; } } Ok(Value::Array(landed)) } /// A receipt moves the messages it names forward: theirs about this person's messages, or this person's own (read on another phone) about theirs. fn apply_receipt(ctx: &mut Ctx<'_>, ns: &str, item: &Item, payload: &Payload) -> Result { let state = match payload.state { Some(Receipt::Read) => "read", _ => "delivered", }; let mut moved = Vec::new(); let mut read_to: i64 = 0; for external in &payload.ids { if item.out { let id = ids::message_id(ns, &item.peer, external); if state == "read" { if let Some(row) = one(ctx, &format!("SELECT seq, read_at FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? { read_to = read_to.max(row.get("seq").and_then(Value::as_i64).unwrap_or(0)); if row.get("read_at").is_none_or(Value::is_null) { let mut patch = Map::new(); patch.insert("read_at".into(), json!(iso(payload.at))); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; } moved.push(json!(id)); } } continue; } let id = ids::message_id(ns, ids::ME, external); let Some(row) = one(ctx, &format!("SELECT send_state FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { continue }; let current = row.get("send_state").and_then(Value::as_str).unwrap_or("sent").to_string(); let next = outbox::advanced(¤t, state); if next != current { let mut patch = Map::new(); patch.insert("send_state".into(), json!(next)); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; moved.push(json!(id)); } } if item.out && !moved.is_empty() { // Read on another of this person's phones: the conversation is read here too. let thread = chat_with(ctx, ns, &item.peer)?; if let Some(row) = one(ctx, &format!("SELECT read_seq, unread_marked_at FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.clone())])? { let mut patch = Map::new(); if read_to > row.get("read_seq").and_then(Value::as_i64).unwrap_or(0) { patch.insert("read_seq".into(), json!(read_to)); } if row.get("unread_marked_at").is_some_and(|v| !v.is_null()) { patch.insert("unread_marked_at".into(), Value::Null); } if !patch.is_empty() { update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?; } } } Ok(Value::Array(moved)) } pub(crate) fn touch_thread(ctx: &mut Ctx<'_>, thread: &str, at: &str, body: Option<&str>, picture: bool) -> Result<(), String> { let current = one(ctx, &format!("SELECT last_message_at FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string())])?; let later = current.and_then(|row| row.get("last_message_at").and_then(Value::as_str).map(str::to_string)).is_none_or(|last| last.as_str() <= at); if !later { return Ok(()); } let preview: String = match body.filter(|b| !b.trim().is_empty()) { Some(body) => body.chars().take(120).collect(), None if picture => "Photo".into(), None => String::new(), }; let mut patch = Map::new(); patch.insert("last_message_at".into(), json!(at)); patch.insert("last_message_preview".into(), json!(preview)); patch.insert("trashed_at".into(), Value::Null); update_row(ctx, THREADS, thread, patch).map_err(|f| f.to_string()) } fn set_request(ctx: &mut Ctx<'_>, thread: &str, state: &str, only_if_pending: bool) -> Result<(), String> { if !holds(ctx, THREADS, "request")? || !exists(ctx, THREADS, thread)? { return Ok(()); } if only_if_pending && request_of(ctx, thread)?.as_deref() != Some("pending") { return Ok(()); } let mut patch = Map::new(); patch.insert("request".into(), json!(state)); update_row(ctx, THREADS, thread, patch).map_err(|f| f.to_string()) } fn request_of(ctx: &mut Ctx<'_>, thread: &str) -> Result, String> { if !holds(ctx, THREADS, "request")? { return Ok(None); } Ok(one(ctx, &format!("SELECT request FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.to_string())])?.and_then(|row| row.get("request").and_then(Value::as_str).map(str::to_string))) } /// Block or unblock the person a WhatsApp chat is with, on WhatsApp's own block list (CONTRACT "Blocking a WhatsApp /// sender, deleting a WhatsApp chat"): one outbox row the Mac sends through the link, and the contact marked here at /// once, so the chat says so. Refused where the served outbox does not take it yet, and for a group. pub(crate) fn whatsapp_block(client: &ClientController, thread: &str, block: bool) -> Result { let th = thread.to_string(); let queued = write(client, "chat.block.whatsapp", move |ctx| { if !super::chat_app::whatsapp_send::takes_source_acts(ctx)? { return Ok(json!({ "refused": "not_yet" })); } let Ok(to) = super::chat_app::whatsapp_send::target(ctx, &th)? else { return Ok(json!({ "refused": "not_whatsapp" })) }; if to.chat.ends_with("@g.us") { return Ok(json!({ "refused": "group" })); } let id = super::chat_app::whatsapp_send::queue_block(ctx, &th, block)?; let number = format!("+{}", to.chat.split('@').next().unwrap_or_default()); set_blocked(ctx, &number, block)?; Ok(json!({ "id": id })) })?; match queued["refused"].as_str() { None => Ok(json!({ "ok": true, "on": "whatsapp", "queued": queued["id"] })), Some("group") => Err(words("group", "A group can't be blocked. Leave it on your phone instead.")), Some(_) => Err(words("not_cotton", "This chat isn't a Cotton chat.")), } } /// The person on `number` blocked (or not) on this phone, as `chat.block` marks them: Your people's Block blocks /// their chat here too, so the chat says so and offers Unblock (`chat_face`). pub(crate) fn mark_blocked(client: &ClientController, number: &str, blocked: bool) -> Result<(), MethodError> { let number = e164(number).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use."))?; write(client, "chat.blocked", move |ctx| set_blocked(ctx, &number, blocked).map(|_| Value::Null)).map(|_| ()) } fn set_blocked(ctx: &mut Ctx<'_>, number: &str, blocked: bool) -> Result<(), String> { let digits = number.trim_start_matches('+').to_string(); if let Some(row) = one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])? { let mut patch = Map::new(); patch.insert("blocked".into(), json!(blocked)); update_row(ctx, CONTACTS, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?; } Ok(()) } fn meta_of(ctx: &mut Ctx<'_>, id: &str) -> Result { let row = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.to_string())])?; Ok(row.map(|row| meta_value(row.get("meta").unwrap_or(&Value::Null))).unwrap_or_else(|| json!({ "cotton": {} }))) } /// Every waiting message of this copy, oldest first. fn waiting(client: &ClientController) -> Result, MethodError> { let found = read(client, "chat.waiting", |ctx| { let rows = rows(ctx, &format!("SELECT id, thread_id, meta, send_attempts, created_at FROM {MESSAGES} WHERE workspace_id = ? AND channel = 'cotton' AND direction = 'out' AND send_state = 'queued' AND trashed_at IS NULL"), &[ws(ctx)])?; Ok(Value::Array(rows.into_iter().map(Value::Object).collect())) })?; Ok(found .as_array() .into_iter() .flatten() // A message waiting for its person to be on Cotton is out of the queue until they are (chat-people). .filter(|row| !super::chat_people::waits(&meta_value(&row["meta"]))) .map(|row| { let meta = meta_value(&row["meta"]); outbox::Waiting { id: row["id"].as_str().unwrap_or_default().to_string(), thread: row["thread_id"].as_str().unwrap_or_default().to_string(), written_at: meta["cotton"]["written_at"].as_str().and_then(ms_of).or_else(|| row["created_at"].as_str().and_then(ms_of)).unwrap_or(0), attempts: row["send_attempts"].as_u64().unwrap_or(0) as u32, tried_at: meta["cotton"]["tried_at"].as_i64(), } }) .collect()) } fn message_state(client: &ClientController, id: &str) -> Result { let id = id.to_string(); read(client, "chat.state", move |ctx| Ok(one(ctx, &format!("SELECT send_state FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.and_then(|row| row.get("send_state").cloned()).unwrap_or(Value::Null))) } /// The number a Cotton conversation is with. pub(crate) fn thread_number(client: &ClientController, thread: &str) -> Result { let id = thread.to_string(); let found = read(client, "chat.thread", move |ctx| Ok(one(ctx, &format!("SELECT external_key FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.map(Value::Object).unwrap_or(Value::Null)))?; if found.is_null() { return Err(words("not_found", "This chat isn't here any more.")); } found["external_key"].as_str().and_then(ids::number_of_key).map(str::to_string).ok_or_else(|| words("not_cotton", "This chat isn't a Cotton chat.")) } /// Whether this person may answer `number` at all: a one-to-one chat with them is here and is not a request they left /// unanswered. fn answers_to(client: &ClientController, number: &str) -> Result { let ns = namespace(client)?; let n = number.to_string(); let found = read(client, "chat.answers_to", move |ctx| { let thread = chat_with(ctx, &ns, &n)?; if !exists(ctx, THREADS, &thread)? { return Ok(Value::Bool(false)); } Ok(Value::Bool(request_of(ctx, &thread)?.as_deref() != Some("pending"))) })?; Ok(found == Value::Bool(true)) } fn accepted(client: &ClientController, thread: &str) -> Result { let id = thread.to_string(); let state = read(client, "chat.request", move |ctx| Ok(request_of(ctx, &id)?.map(Value::from).unwrap_or(Value::Null)))?; Ok(state.as_str() != Some("pending")) } /// Whether this app's Cotton chats say more than delivery: its kit's /// `signals`. An app that keeps to no kit, or whose kit does not say so, /// sends no read receipt and no typing and draws neither. pub(crate) fn signals(client: &ClientController) -> bool { cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().is_some_and(|kit| kit.signals) } /// The person's two switches: read receipts, typing. Both off until they turn them on (DECISIONS.md, 20 Nov 2026). /// Whether this phone fetches link previews (chat CONTRACT.md "Link previews"): on unless he turned it off here. pub(crate) fn link_previews(client: &ClientController) -> bool { let held: Value = std::fs::read(client.layout().client_dir().join(PREFERENCES)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); held["linkPreviews"].as_bool().unwrap_or(true) } /// A message's link card as kept (`meta.preview`), as it travels. fn preview_of_meta(meta: &Value) -> Option { serde_json::from_value::(meta["preview"].clone()).ok().map(|kept| payload::LinkPreview::of(&kept)) } /// Keep `card` as message `id`'s link card (`meta.preview`), so it is drawn and travels with it. pub(crate) fn put_preview(client: &ClientController, id: &str, card: &cotton_core::messages::MessageLinkPreview) -> Result<(), MethodError> { let (id, card) = (id.to_string(), serde_json::to_value(card).unwrap_or(Value::Null)); write(client, "chat.preview.keep", |ctx| { let mut meta = meta_of(ctx, &id)?; meta["preview"] = card.clone(); let mut patch = Map::new(); patch.insert("meta".into(), meta); update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) }) .map(|_| ()) } pub(crate) fn preferences(client: &ClientController) -> (bool, bool) { let held: Value = std::fs::read(client.layout().client_dir().join(PREFERENCES)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); (held["readReceipts"].as_bool().unwrap_or(false), held["typing"].as_bool().unwrap_or(false)) } /// The switches this phone's words carry: none where the app's chats do not signal (the other side then takes both as off). pub(crate) fn own_signals(client: &ClientController) -> Option { signals(client).then(|| { let (read, typing) = preferences(client); Signals { read, typing } }) } /// Someone's switches as their last word said them; nobody heard from yet has both off. pub(crate) fn peer_signals(client: &ClientController, number: &str) -> Signals { let held: Value = std::fs::read(client.layout().client_dir().join(PEER_SIGNALS)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); serde_json::from_value(held[number].clone()).unwrap_or_default() } /// Their switches, kept when what they said is no older (their clock) than what was kept. fn keep_peer_signals(client: &ClientController, number: &str, at: i64, said: Signals) { let path = client.layout().client_dir().join(PEER_SIGNALS); let mut held: Value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_else(|| json!({})); if !held.is_object() { held = json!({}); } if held[number]["at"].as_i64().is_some_and(|was| was > at) { return; } held[number] = json!({ "read": said.read, "typing": said.typing, "at": at }); if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } // not a copy: Chat's own files (preferences, a plain export, what it holds). let _ = std::fs::write(&path, held.to_string()); } /// Whether `number` is told this person read: the app signals, this person's switch is on, and so is theirs. pub(crate) fn may_tell_read(client: &ClientController, number: &str) -> bool { signals(client) && preferences(client).0 && peer_signals(client, number).read } /// Whether `number` is told this person is typing: the same rule, with the typing switches. fn may_tell_typing(client: &ClientController, number: &str) -> bool { signals(client) && preferences(client).1 && peer_signals(client, number).typing } // ── people ────────────────────────────────────────────────────────────── /// The person's first phone in this copy, and their name. fn number_of(client: &ClientController, person: &str) -> Result<(Option, Option), MethodError> { let person = person.to_string(); let found = read(client, "chat.person", move |ctx| { let id = SqlValue::Text(person.clone()); let name = one(ctx, "SELECT full_name FROM cotton_people WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[ws(ctx), id.clone()])?; let phones = rows(ctx, "SELECT value FROM cotton_person_handles WHERE workspace_id = ? AND person_id = ? AND kind = 'phone' AND trashed_at IS NULL ORDER BY position, created_at", &[ws(ctx), id])?; let phone = phones.iter().find_map(|row| row.get("value").and_then(Value::as_str).and_then(e164)); Ok(json!({ "known": name.is_some(), "name": name.and_then(|row| row.get("full_name").cloned()), "phone": phone })) })?; if found["known"] != json!(true) { return Err(MethodError::new("person_not_found", "Nobody with this id is kept here.")); } Ok((found["phone"].as_str().map(str::to_string), found["name"].as_str().map(str::to_string))) } /// The one person in this copy holding `number`, and their name: who(handle) /// (`cotton_store::protocol::who`), the one rule every matcher asks. pub(crate) fn person_of(client: &ClientController, number: &str) -> (Option, Option) { let Some((kind, value)) = cotton_store::protocol::who::who_key(cotton_store::protocol::person_handles::HandleKind::Phone, number, None) else { return (None, None); }; let found = read(client, "chat.caller", move |ctx| { let who = cotton_store::protocol::who::who(ctx.db(), ctx.workspace_id, kind, &value).map_err(|e| e.to_string())?; Ok(crate::phone::calls::who_answer(&who)) }); match found { Ok(found) => (found["person"].as_str().map(str::to_string), found["name"].as_str().map(str::to_string)), Err(_) => (None, None), } } /// The socket said `{ t: "rows" }`: another device of the person (his Mac /// landing a WhatsApp message, a vote, a reaction, a delete; another phone; /// an assistant) moved rows in his file. A pass is asked for now, so the /// change is drawn in seconds instead of at the loop's next minute: the /// loop's own wake, one pass for any number of frames that come while one /// runs, and none while it waits out a failure (`later`), so a burst of /// frames during an outage never climbs the ladder. fn rows_moved(client: &ClientController) -> Value { let pull = match client.nudge_sync() { Some(true) => "asked", Some(false) => "later", None => "no schedule", }; json!({ "pull": pull }) } /// The socket's address and a ticket for it: asked of the object on this /// door (the device's credential stays in Rust), the ticket opens one socket /// for this device within a minute and is no credential of the app's. The /// shell opens the WebSocket with it as the Bearer the object checks. fn socket(client: &ClientController) -> Result { let answer = ask(client, "POST", routes::SOCKET, Some(&json!({}))).map_err(refused)?; let ticket = answer["ticket"].as_str().ok_or_else(|| MethodError::new("refused", "the object minted no socket ticket"))?; let door = client.object_door().ok_or_else(not_connected)?; Ok(json!({ "url": door.address.url(routes::SOCKET).replacen("http", "ws", 1), "ticket": ticket })) } // ── the door and the replica ──────────────────────────────────────────── pub(crate) fn ask(client: &ClientController, method: &str, path: &str, body: Option<&Value>) -> Result { let door = client.object_door().ok_or_else(|| ObjectRefusal { status: 0, code: "not_connected".into(), message: "this phone is not connected to its database yet".into() })?; door.address.send(door.exchange.as_ref(), method, path, bearer(&door.credential), body) } /// A PUT of raw bytes (a sealed picture), answered as JSON. fn put_bytes(client: &ClientController, path: &str, bytes: &[u8]) -> Result { put_typed(client, path, bytes, "application/octet-stream") } /// A PUT of raw bytes of a content type (a sealed file a Keep reseals), answered as JSON. pub(crate) fn put_typed(client: &ClientController, path: &str, bytes: &[u8], content_type: &str) -> Result { let door = client.object_door().ok_or_else(|| ObjectRefusal { status: 0, code: "not_connected".into(), message: "this phone is not connected to its database yet".into() })?; let full = door.address.url(path); let path = full.strip_prefix(door.address.origin().text.as_str()).unwrap_or(path).to_string(); let authority = door.address.origin().authority(); let mut headers = bearer(&door.credential); headers.push(("Content-Type".into(), content_type.into())); let request = Http1Request { method: "PUT", path: &path, authority: &authority, headers, body: Some(bytes) }; let mut answer = door.exchange.send(door.address.origin(), &request, std::time::Duration::from_secs(120)).map_err(|message| ObjectRefusal { status: 0, code: "offline".into(), message })?; let status = answer.status(); let mut text = Vec::new(); std::io::Read::read_to_end(&mut answer, &mut text).map_err(|e| ObjectRefusal { status: 0, code: "offline".into(), message: e.to_string() })?; let value: Value = serde_json::from_slice(&text).unwrap_or(Value::Null); if (200..300).contains(&status) { Ok(value) } else { Err(ObjectRefusal { status, code: value["code"].as_str().unwrap_or("refused").into(), message: value["message"].as_str().unwrap_or("refused").into() }) } } pub(crate) fn write(client: &ClientController, label: &str, mut work: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let answer = client.write_rows(label, &mut |ctx| work(ctx)).map_err(|why| MethodError::new("write_refused", why))?; Ok(crate::authoring::own_answer(answer)) } pub(crate) fn read(client: &ClientController, label: &str, mut work: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let answer = client.read_rows(label, &mut |ctx| work(ctx)).map_err(|why| MethodError::new("unreadable", why))?; Ok(crate::authoring::own_answer(answer)) } pub(crate) fn ws(ctx: &Ctx<'_>) -> SqlValue { SqlValue::Text(ctx.workspace_id.to_string()) } pub(crate) fn rows(ctx: &mut Ctx<'_>, sql: &str, params: &[SqlValue]) -> Result>, String> { Ok(ctx.db().all(sql, params).map_err(|e| e.to_string())?.iter().map(|row| crate::phone::passwords::json_row(row)).collect()) } pub(crate) fn one(ctx: &mut Ctx<'_>, sql: &str, params: &[SqlValue]) -> Result>, String> { Ok(rows(ctx, sql, params)?.into_iter().next()) } pub(crate) fn exists(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Result { Ok(one(ctx, &format!("SELECT 1 AS one FROM {table} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.to_string())])?.is_some()) } /// Whether this copy's table holds a column (the object's definitions lay theirs at the first paint). pub(crate) fn holds(ctx: &mut Ctx<'_>, table: &str, column: &str) -> Result { Ok(rows(ctx, &format!("SELECT name FROM pragma_table_info('{table}')"), &[])?.iter().any(|row| row.get("name").and_then(Value::as_str) == Some(column))) } pub(crate) fn now_iso(ctx: &Ctx<'_>) -> String { cotton_tools::mcp::handlers::common::now_iso(ctx) } // ── small things ──────────────────────────────────────────────────────── /// A row's `meta`, whether the copy answers it as text or as JSON: always an object with a `cotton` object. pub(crate) fn meta_value(raw: &Value) -> Value { let mut meta = match raw { Value::String(text) => serde_json::from_str(text).unwrap_or_else(|_| json!({})), Value::Object(_) => raw.clone(), _ => json!({}), }; if !meta.is_object() { meta = json!({}); } if !meta["cotton"].is_object() { meta["cotton"] = json!({}); } meta } fn private_key(request: &Value) -> Result, MethodError> { let text = request.get("privateKey").and_then(Value::as_str).ok_or_else(|| bad("privateKey", "this phone's chat key, from its Keychain"))?; seal::key_from_text(text).map(Zeroizing::new).ok_or_else(|| bad("privateKey", "32 bytes as base64url")) } pub(crate) fn namespace(client: &ClientController) -> Result { client.current_database().map_err(|why| MethodError::new("not_attached", why)) } pub(crate) fn now_ms(client: &ClientController) -> i64 { client.now().timestamp_millis() } pub(crate) fn iso(ms: i64) -> String { chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } fn ms_of(text: &str) -> Option { chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis()) } /// A message's own id: what its writer names it by, and the other side too. pub(crate) fn fresh_id() -> String { let bytes: [u8; 16] = rand::random(); bytes.iter().map(|b| format!("{b:02x}")).collect() } pub(crate) fn e164(raw: &str) -> Option { cotton_core::import::phone::normalize_phone(raw).map(|digits| format!("+{digits}")) } fn extension(mime: &str) -> &'static str { match mime { "image/png" => "png", "image/heic" => "heic", "image/gif" => "gif", "image/webp" => "webp", _ => "jpg", } } pub(crate) fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> { request.get(field).and_then(Value::as_str).ok_or_else(|| bad(field, "text")) } fn flag(request: &Value, field: &str) -> bool { request.get(field).and_then(Value::as_bool).unwrap_or(false) } pub(crate) fn bad(field: &str, shape: &str) -> MethodError { MethodError::new("invalid_request", format!("`{field}`: {shape}")) } /// A refusal in the chat set's words (kits/shell/lines/chat.json `refused.`). pub(crate) fn words(code: &str, said: &str) -> MethodError { MethodError::new(code, said) } pub(crate) fn not_connected() -> MethodError { MethodError::new("not_connected", "Sign in to send Cotton messages.") } fn local(message: String) -> ObjectRefusal { ObjectRefusal { status: 400, code: "refused".into(), message } } pub(crate) fn refused(refusal: ObjectRefusal) -> MethodError { MethodError::new(&refusal.code, refusal.message) } #[cfg(test)] #[path = "cotton_chat_tests.rs"] mod tests;