Cotton code
733 lines · 35.0 KB · RustRaw
//! Sends from the phone: the personal `outbox` table, drained by the Mac.//!//! The phone creates a row (`channel`, `to`, `body`, `media_key`,//! `status: queued`); the Mac reads `GET /v1/outbox?status=queued`, marks a//! row `sending` with the WhatsApp message id it is about to use, sends it//! through the linked-device helper, and marks it `sent` (with WhatsApp's id//! and time) or `failed` (with the reason, in words). The message id is the//! one Comms fixed at the owner's tap (`sent_external_id`), else derived from//! the row's own id: a send the helper took but the Mac never marked, or one//! the owner retried, goes out under the same id and WhatsApp keeps one. The//! helper keeps what it sent as the owner's message, which lands under that id. A row left `sending` by a Mac that stopped mid-send is//! not taken again: it may have gone out, and a second send is a duplicate//! message in someone's chat.//!//! A row says what it sends in `kind` (owner, FEEDBACK-3, 23 Nov 2026): a text//! (absent: a text, as before), a picture, video, voice note or document (its//! sealed file at `media_key`, fetched and opened here with the data key and//! handed to the helper as a plain file that is removed once sent; nothing//! unsealed rests on the server), a reaction, an edit, a delete for everyone, a//! poll or a vote. `target` is the WhatsApp id of the message it answers: a//! reply quotes it, the others act on it; `target_sender` is who wrote it ("me"//! for the owner). A row of another channel is left queued.use std::path::Path;use std::time::Duration;use cotton_client::ingest::sources::whatsapp_link::LinkClient;use cotton_core::messages::send::whatsapp_message_id;use serde_json::{json, Map, Value};use crate::object::{Act, ObjectClient, ObjectError};pub const TABLE: &str = "outbox";const SEND_TIMEOUT: Duration = Duration::from_secs(60);/// A file goes up to WhatsApp's media hosts first (the helper allows ten minutes).const FILE_SEND_TIMEOUT: Duration = Duration::from_secs(11 * 60);/// One queued row, read from whatever shape the object lists it in: the/// row's fields at the top, or under `data`.#[derive(Debug, Clone, PartialEq)]pub struct Queued {    pub id: String,    pub channel: String,    pub to: String,    pub body: String,    pub media_key: Option<String>,    /// The linked number the chat came in through, when the phone knew it.    pub account: Option<String>,    /// The WhatsApp id fixed at the owner's tap.    pub sent_external_id: Option<String>,    /// text (the default), picture, video, voice, audio, document, reaction, edit, delete, poll, poll_vote. The    /// phones' `photo` is read as picture, and `audio` with `voice` as voice (CONTRACT "Pictures, voice notes and    /// video").    pub kind: String,    pub target: Option<String>,    pub target_sender: Option<String>,    pub emoji: String,    pub file_name: Option<String>,    /// The file's type (`mime`, or `mimetype`).    pub mimetype: Option<String>,    pub duration_ms: Option<u64>,    pub size_bytes: Option<u64>,    pub width: Option<u32>,    pub height: Option<u32>,    /// A picture's or video's small JPEG, base64, for WhatsApp's thumbnail.    pub preview: Option<String>,    /// A voice note's levels, 0..100 (base64 of up to 64 bytes in the row, or a list of 0..1 or 0..100).    pub waveform: Vec<u8>,    /// A poll's options, or a vote's picks.    pub options: Vec<String>,    pub selectable: u32,    /// A deleted chat's newest message's time, unix seconds, from the Mac's copy (never the row's).    pub target_at: Option<i64>,}impl Queued {    pub fn from_row(row: &Value) -> Option<Queued> {        let id = row.get("id").and_then(Value::as_str)?.to_string();        let fields = row.get("data").filter(|d| d.is_object()).unwrap_or(row);        // A row still sealed (this Mac signed in with no seal door) is not this Mac's to send or to fail: it waits, queued.        if fields.get("sealed_enc").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) {            return None;        }        let text = |key: &str| fields.get(key).and_then(Value::as_str).map(str::to_string);        Some(Queued {            id,            channel: text("channel").unwrap_or_default(),            to: text("to").unwrap_or_default(),            body: text("body").unwrap_or_default(),            media_key: text("media_key").filter(|k| !k.is_empty()),            account: text("account").filter(|a| !a.trim().is_empty()),            sent_external_id: text("sent_external_id").filter(|id| !id.trim().is_empty()),            kind: match text("kind").filter(|k| !k.trim().is_empty()) {                None if text("reaction_to").is_some_and(|t| !t.trim().is_empty()) => "reaction".to_string(),                kind => kind_of(kind.as_deref(), fields.get("voice").and_then(Value::as_bool).unwrap_or(false)),            },            // The phones write a reply's quote as `quoted_id` and a reaction's message as `reaction_to` (CONTRACT            // "Replies and reactions"); `target` is the later kinds' (edit, delete, poll_vote).            target: text("target").or_else(|| text("quoted_id")).or_else(|| text("reaction_to")).filter(|t| !t.trim().is_empty()),            target_sender: text("target_sender").filter(|t| !t.trim().is_empty()),            emoji: text("emoji").unwrap_or_default(),            file_name: text("file_name").filter(|n| !n.trim().is_empty()),            mimetype: text("mime").or_else(|| text("mimetype")).filter(|m| !m.trim().is_empty()),            duration_ms: number(fields.get("duration_ms")),            size_bytes: number(fields.get("size_bytes")),            width: number(fields.get("width")).map(|w| w as u32),            height: number(fields.get("height")).map(|h| h as u32),            preview: text("preview").filter(|p| !p.trim().is_empty()),            waveform: levels(fields.get("waveform")),            options: list(fields.get("options")).iter().filter_map(|o| o.as_str().map(str::to_string)).collect(),            selectable: fields.get("selectable").and_then(Value::as_u64).unwrap_or(0) as u32,            target_at: None,        })    }}/// A message of the chat as the Mac's copy holds it, for a reply's quote or the message a reaction acts on: who/// wrote it (a WhatsApp address), whether it is his own, what it is and its words.#[derive(Debug, Clone, PartialEq, Default)]pub struct Held {    pub sender: Option<String>,    pub from_me: bool,    pub kind: String,    pub text: String,    /// When it was sent, unix seconds (`sent_at`): a chat deleted for him names its newest message and this time.    pub at: Option<i64>,}impl Held {    /// From a message row of the copy (opened): `meta.source.sender`, `direction`, `meta.source.messageType` (else    /// its first file's type), and its words, caption or file name.    pub fn of(data: &Value) -> Held {        let source = &data["meta"]["source"];        let media = data["media"].as_array().and_then(|m| m.first()).cloned().unwrap_or(Value::Null);        let content_type = media["contentType"].as_str().or_else(|| media["content_type"].as_str()).unwrap_or_default();        let kind = match source["messageType"].as_str().filter(|k| !k.is_empty()) {            Some(kind) => kind.to_string(),            None if content_type.starts_with("image/") => "image".to_string(),            None if content_type.starts_with("video/") => "video".to_string(),            None if content_type.starts_with("audio/") => "audio".to_string(),            None if !content_type.is_empty() => "document".to_string(),            None => "text".to_string(),        };        let body = data["body"].as_str().unwrap_or_default().to_string();        let text = if body.is_empty() && kind == "document" { media["name"].as_str().unwrap_or_default().to_string() } else { body };        Held {            sender: source["sender"].as_str().filter(|s| s.contains('@')).map(str::to_string),            from_me: data["direction"].as_str() == Some("out"),            kind,            text,            at: data["sent_at"].as_str().and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok()).map(|at| at.timestamp()),        }    }}/// What a row answering a message the copy does not hold fails with (CONTRACT "Replies and reactions").pub const NOT_IN_WHATSAPP_REPLY: &str = "That message isn't in WhatsApp, so you can't reply to it there.";pub const NOT_IN_WHATSAPP_REACT: &str = "That message isn't in WhatsApp, so you can't react to it there.";/// What a chat deleted for him fails with when the copy holds none of its WhatsApp messages (a draft).pub const NOT_IN_WHATSAPP_CHAT: &str = "This chat's messages aren't in WhatsApp, so it can't be deleted there.";/// The row's kind in the helper's words.fn kind_of(kind: Option<&str>, voice: bool) -> String {    match kind.map(str::trim).filter(|k| !k.is_empty()) {        None => "text".to_string(),        Some("photo") => "picture".to_string(),        Some("audio") if voice => "voice".to_string(),        Some(kind) => kind.to_string(),    }}/// A count column, as a number or its text.fn number(value: Option<&Value>) -> Option<u64> {    match value? {        Value::Number(n) => n.as_f64().map(|f| f.max(0.0) as u64),        Value::String(s) => s.trim().parse::<f64>().ok().map(|f| f.max(0.0) as u64),        _ => None,    }}/// A voice note's levels, 0..100: base64 of bytes (the phones' wire), or a list of 0..1 or 0..100.fn levels(value: Option<&Value>) -> Vec<u8> {    use base64::Engine as _;    if let Some(Value::String(text)) = value {        if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(text.trim()) {            return bytes.into_iter().take(64).map(|b| b.min(100)).collect();        }    }    let items: Vec<f64> = list(value).iter().filter_map(Value::as_f64).collect();    let scale = if items.iter().all(|l| *l <= 1.0) { 100.0 } else { 1.0 };    items.iter().take(64).map(|l| (l * scale).clamp(0.0, 100.0).round() as u8).collect()}/// A list column, whether the row holds it as a JSON array or as its text.fn list(value: Option<&Value>) -> Vec<Value> {    match value {        Some(Value::Array(items)) => items.clone(),        Some(Value::String(text)) => serde_json::from_str::<Vec<Value>>(text).unwrap_or_default(),        _ => Vec::new(),    }}const FILE_KINDS: &[&str] = &["picture", "video", "voice", "audio", "document"];const KINDS: &[&str] = &["text", "picture", "video", "voice", "audio", "document", "reaction", "edit", "delete", "poll", "poll_vote", "block", "unblock", "delete_chat"];/// Acts on his WhatsApp itself, not a message (owner, 24 Nov 2026; CONTRACT "Blocking a WhatsApp sender, deleting a/// WhatsApp chat"): a person blocked or unblocked, and a person's chat deleted for him alone. Never in a group.const SOURCE_ACTS: &[&str] = &["block", "unblock", "delete_chat"];/// WhatsApp's own limit for a picture, video or recording (`chat::files::FILE_MAX` on the phones); a document may/// be larger.const MEDIA_MAX: u64 = 16 << 20;const DOCUMENT_MAX: u64 = 100 << 20;pub const TOO_LARGE: &str = "This file is too large for WhatsApp.";pub const COULD_NOT_OPEN: &str = "Your Mac could not open this file.";/// `cotton_core::messages::send::NOT_ON_WHATSAPP` (CONTRACT "Writing to a number"), word for word.pub const NUMBER_NOT_ON_WHATSAPP: &str = cotton_core::messages::send::NOT_ON_WHATSAPP;fn too_large(kind: &str, bytes: u64) -> bool {    bytes > if kind == "document" { DOCUMENT_MAX } else { MEDIA_MAX }}/// The send's own fields for the helper, beside account, chat, text and message id; the opened file's path for a/// file. What a row cannot send is said in words.fn kind_fields(queued: &Queued, file: Option<&Path>) -> Result<Map<String, Value>, String> {    let mut f = Map::new();    let kind = queued.kind.as_str();    if !KINDS.contains(&kind) {        return Err(format!("Cotton cannot send a \"{kind}\" to WhatsApp yet."));    }    // An edit and a delete for everyone act on his own message only (CONTRACT "Editing and deleting his own    // message"): the phones write no `target_sender` for them.    let mine = queued.target_sender.as_deref() == Some("me") || matches!(kind, "edit" | "delete");    let replying = kind == "text" || FILE_KINDS.contains(&kind);    if let Some(target) = &queued.target {        if replying {            f.insert("quoted_id".into(), Value::from(target.as_str()));            if let Some(sender) = queued.target_sender.as_deref().filter(|_| !mine) {                f.insert("quoted_sender".into(), Value::from(sender));            }        } else {            f.insert("target".into(), Value::from(target.as_str()));            f.insert("target_from_me".into(), Value::from(mine));            if let Some(sender) = queued.target_sender.as_deref().filter(|_| !mine) {                f.insert("target_sender".into(), Value::from(sender));            }        }    } else if !replying && !matches!(kind, "poll" | "block" | "unblock") {        return Err("This needs the message it acts on.".to_string());    }    if SOURCE_ACTS.contains(&kind) && queued.to.ends_with("@g.us") {        return Err("This is for a person's chat, not a group.".to_string());    }    if kind == "text" {        return Ok(f);    }    f.insert("kind".into(), Value::from(kind));    match kind {        "reaction" => {            f.insert("emoji".into(), Value::from(queued.emoji.as_str()));        }        "block" | "unblock" => {            // A block names nobody's message: what went with it as a target is not said to WhatsApp.            f.remove("target");            f.remove("target_from_me");            f.remove("target_sender");        }        "delete_chat" => {            let at = queued.target_at.ok_or_else(|| NOT_IN_WHATSAPP_CHAT.to_string())?;            f.insert("target_ts".into(), Value::from(at));        }        "poll" | "poll_vote" => {            if kind == "poll" && queued.options.len() < 2 {                return Err("A poll needs at least two options.".to_string());            }            f.insert("options".into(), json!(queued.options));            if queued.selectable > 0 {                f.insert("selectable".into(), Value::from(queued.selectable));            }        }        _ if FILE_KINDS.contains(&kind) => {            let path = file.ok_or_else(|| "The file to send is missing.".to_string())?;            f.insert("path".into(), Value::from(path.to_string_lossy().as_ref()));            if let Some(mimetype) = &queued.mimetype {                f.insert("mimetype".into(), Value::from(mimetype.as_str()));            }            if let Some(name) = &queued.file_name {                f.insert("file_name".into(), Value::from(name.as_str()));            }            if let Some(ms) = queued.duration_ms {                f.insert("seconds".into(), Value::from(ms.div_ceil(1000)));            }            if !queued.waveform.is_empty() && kind == "voice" {                f.insert("waveform".into(), Value::from(base64_of(&queued.waveform)));            }            if matches!(kind, "picture" | "video") {                if let Some(w) = queued.width {                    f.insert("width".into(), Value::from(w));                }                if let Some(h) = queued.height {                    f.insert("height".into(), Value::from(h));                }                if let Some(preview) = &queued.preview {                    f.insert("preview".into(), Value::from(preview.as_str()));                }            }            f.insert("landed".into(), landed(queued));        }        _ => {}    }    Ok(f)}/// What the sent message lands with: the file already in his Cotton under the row's key, so it is not fetched from/// WhatsApp again nor stored a second time.fn landed(queued: &Queued) -> Value {    let mut media = Map::new();    media.insert("key".into(), Value::from(queued.media_key.as_deref().unwrap_or_default()));    let content_type = queued.mimetype.clone().unwrap_or_else(|| "application/octet-stream".to_string());    media.insert("contentType".into(), Value::from(content_type));    if let Some(name) = &queued.file_name {        media.insert("name".into(), Value::from(name.as_str()));    }    for (field, value) in [("sizeBytes", queued.size_bytes), ("width", queued.width.map(u64::from)), ("height", queued.height.map(u64::from)), ("durationMs", queued.duration_ms)] {        if let Some(value) = value {            media.insert(field.into(), Value::from(value));        }    }    json!([media])}/// Bytes as Go's encoding/json reads a []byte: standard base64.fn base64_of(bytes: &[u8]) -> String {    use base64::Engine as _;    base64::engine::general_purpose::STANDARD.encode(bytes)}/// What became of fetching a row's file.enum Fetched {    /// The plain file the helper sends (removed once sent).    Ready(std::path::PathBuf),    /// The phone has not put it up yet (or the object could not be read this pass): the row waits, queued.    NotYet,    /// It cannot go, in the words the phone shows after "Not sent: ".    Refused(&'static str),}/// The sealed file at `key` fetched from the object and opened with this Mac's file key into `dir`.fn opened_file(object: &ObjectClient, kind: &str, key: &str, dir: &Path, id: &str) -> Fetched {    let stored = match object.media_stored(key) {        Ok(Some(stored)) => stored,        Ok(None) | Err(_) => return Fetched::NotYet,    };    let mut sealed = Vec::with_capacity(stored.size as usize);    if object.get_media_to(key, stored.size, &mut sealed).is_err() {        return Fetched::NotYet;    }    let mut plain = Vec::with_capacity(sealed.len());    if crate::object::is_person_key(key) && crate::object::is_sealed_type(&stored.content_type) {        let Ok(fk) = object.person_file_key(key) else { return Fetched::Refused(COULD_NOT_OPEN) };        if cotton_core::seal::file::open_file(&fk, key, &mut &sealed[..], &mut plain).is_err() {            return Fetched::Refused(COULD_NOT_OPEN);        }    } else {        plain = sealed;    }    if too_large(kind, plain.len() as u64) {        return Fetched::Refused(TOO_LARGE);    }    let path = dir.join(format!("{}.send", id.replace(['/', '.'], "_")));    if std::fs::create_dir_all(dir).and_then(|_| std::fs::write(&path, plain)).is_err() {        return Fetched::Refused(COULD_NOT_OPEN);    }    Fetched::Ready(path)}#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct Drained {    pub sent: i64,    pub failed: i64,    /// Rows for a channel this pass does not send, left queued.    pub left: i64,}/// A handle as WhatsApp addresses it: a JID as given, else its digits at/// `s.whatsapp.net`.pub fn whatsapp_jid(handle: &str) -> Option<String> {    let handle = handle.trim();    if handle.contains('@') {        return Some(handle.to_string());    }    let digits: String = handle.chars().filter(char::is_ascii_digit).collect();    (digits.len() >= 7).then(|| format!("{digits}@s.whatsapp.net"))}pub(crate) fn mark(object: &ObjectClient, id: &str, data: Value) -> Result<(), ObjectError> {    object.act(Act::Update, TABLE, id, &data).map(|_| ())}/// A JID's or number's digits, without a device suffix.fn number_of(jid: &str) -> String {    let user = jid.split('@').next().unwrap_or(jid);    user.split(':').next().unwrap_or(user).chars().filter(char::is_ascii_digit).collect()}/// The numbers the helper's `hello` names as linked.fn linked_accounts(hello: &Value) -> Vec<String> {    hello        .get("accounts")        .and_then(Value::as_array)        .into_iter()        .flatten()        .filter_map(|account| account.as_str().or_else(|| account.get("account").and_then(Value::as_str)))        .map(str::to_string)        .collect()}/// The helper's refusals with words of their own (`NotOnWhatsApp`, `TooLarge` and `CouldNotOpen` in the helper).const NOT_ON_WHATSAPP: &str = "not_on_whatsapp: ";const HELPER_TOO_LARGE: &str = "too_large";const HELPER_COULD_NOT_OPEN: &str = "could_not_open";/// What a helper's refusal says to the owner, after "Not sent: ".pub fn failed_words(error: &str) -> String {    let said = error.strip_prefix("the WhatsApp helper refused: ").unwrap_or(error);    if said.starts_with(NOT_ON_WHATSAPP) {        return NUMBER_NOT_ON_WHATSAPP.to_string();    }    if said.starts_with(HELPER_TOO_LARGE) {        return TOO_LARGE.to_string();    }    if said.starts_with(HELPER_COULD_NOT_OPEN) {        return COULD_NOT_OPEN.to_string();    }    format!("WhatsApp did not take it: {said}")}/// Whether a refusal was about the number alone, so the helper is still there for the next row.fn about_the_number(error: &str) -> bool {    let said = error.strip_prefix("the WhatsApp helper refused: ").unwrap_or(error);    [NOT_ON_WHATSAPP, HELPER_TOO_LARGE, HELPER_COULD_NOT_OPEN].iter().any(|p| said.starts_with(p))}pub(crate) fn fail(object: &ObjectClient, id: &str, error: &str) -> Result<(), ObjectError> {    mark(object, id, json!({ "status": "failed", "error": error }))}/// Send every queued WhatsApp row through the helper at `socket`, with no copy to find a reply's quote in.pub fn drain_whatsapp(object: &ObjectClient, socket: &Path) -> Result<Drained, ObjectError> {    drain_whatsapp_with(object, socket, &|_| None)}/// Send every queued WhatsApp row through the helper at `socket`; `find` answers a message of the copy by its/// WhatsApp id (a reply's quote, the message a reaction acts on).pub fn drain_whatsapp_with(object: &ObjectClient, socket: &Path, find: &dyn Fn(&str) -> Option<Held>) -> Result<Drained, ObjectError> {    let rows = object.outbox("queued")?;    let mut drained = Drained::default();    let mut client: Option<(LinkClient, Vec<String>)> = None;    for row in rows {        let Some(queued) = Queued::from_row(&row) else { continue };        if queued.channel != "whatsapp" {            drained.left += 1;            continue;        }        let is_file = FILE_KINDS.contains(&queued.kind.as_str());        if (queued.kind == "text" || queued.kind == "edit" || queued.kind == "poll") && queued.body.trim().is_empty() {            fail(object, &queued.id, "Nothing to send.")?;            drained.failed += 1;            continue;        }        if is_file && queued.media_key.is_none() {            fail(object, &queued.id, "The file to send is missing.")?;            drained.failed += 1;            continue;        }        // The phone's own size, before anything is fetched.        if is_file && queued.size_bytes.is_some_and(|bytes| too_large(&queued.kind, bytes)) {            fail(object, &queued.id, TOO_LARGE)?;            drained.failed += 1;            continue;        }        let Some(chat) = whatsapp_jid(&queued.to) else {            fail(object, &queued.id, &format!("\"{}\" is not a WhatsApp number.", queued.to))?;            drained.failed += 1;            continue;        };        if client.is_none() {            let connected = LinkClient::connect(socket).and_then(|mut c| c.hello().map(|hello| (c, hello)));            match connected {                Ok((connected, hello)) => {                    let accounts = linked_accounts(&hello);                    // No number linked: every row waits, queued.                    if accounts.is_empty() {                        return Ok(drained);                    }                    client = Some((connected, accounts));                }                // No helper this pass: the rows wait, queued.                Err(_) => return Ok(drained),            }        }        let Some((helper, accounts)) = client.as_mut() else { break };        // The number the chat came in through sends it; never another number of the owner's.        let account = match &queued.account {            Some(wanted) => match accounts.iter().find(|linked| number_of(linked) == number_of(wanted)) {                Some(linked) => linked.clone(),                None => {                    fail(object, &queued.id, &format!("This chat is on WhatsApp number +{}, which is not linked on your Mac.", number_of(wanted)))?;                    drained.failed += 1;                    continue;                }            },            None => accounts[0].clone(),        };        // A file is fetched and opened before the row says sending. One the phone has not put up yet waits, queued        // and untouched; one that cannot go fails in words, unsent.        let staging = socket.parent().unwrap_or(Path::new(".")).join("sending");        let file = match (is_file, queued.media_key.as_deref()) {            (true, Some(key)) => match opened_file(object, &queued.kind, key, &staging, &queued.id) {                Fetched::Ready(path) => Some(path),                Fetched::NotYet => {                    drained.left += 1;                    continue;                }                Fetched::Refused(words) => {                    fail(object, &queued.id, words)?;                    drained.failed += 1;                    continue;                }            },            _ => None,        };        // A reply or a reaction names its message by its WhatsApp id alone: who wrote it, and a quote's words, come        // from the Mac's copy (CONTRACT "Replies and reactions").        let mut queued = queued;        let mut quote: Option<Held> = None;        // An edit or a delete for everyone is of his own message: the phones name no writer, and a delete's message        // is already erased from the copy at his tap (CONTRACT "Editing and deleting his own message").        if queued.target_sender.is_none() && matches!(queued.kind.as_str(), "edit" | "delete") {            queued.target_sender = Some("me".to_string());        }        if let Some(target) = queued.target.clone() {            let found = find(&target);            if queued.target_sender.is_none() {                let writer = match &found {                    Some(held) if held.from_me => Some("me".to_string()),                    Some(held) => held.sender.clone().or_else(|| (!chat.ends_with("@g.us")).then(|| chat.clone())),                    None => None,                };                let Some(writer) = writer else {                    if let Some(path) = &file {                        let _ = std::fs::remove_file(path);                    }                    let words = match queued.kind.as_str() {                        "reaction" => NOT_IN_WHATSAPP_REACT,                        "delete_chat" => NOT_IN_WHATSAPP_CHAT,                        _ => NOT_IN_WHATSAPP_REPLY,                    };                    fail(object, &queued.id, words)?;                    drained.failed += 1;                    continue;                };                queued.target_sender = Some(writer);            }            if queued.kind == "delete_chat" {                queued.target_at = found.as_ref().and_then(|held| held.at);            }            quote = found;        }        let fields = match kind_fields(&queued, file.as_deref()) {            Ok(fields) => fields,            Err(words) => {                if let Some(path) = &file {                    let _ = std::fs::remove_file(path);                }                fail(object, &queued.id, &words)?;                drained.failed += 1;                continue;            }        };        let message_id = queued.sent_external_id.clone().unwrap_or_else(|| whatsapp_message_id(&queued.id, 0));        mark(object, &queued.id, json!({ "status": "sending", "sent_external_id": message_id }))?;        let mut request = fields;        if let Some(held) = quote.filter(|_| request.contains_key("quoted_id")) {            request.insert("quoted_kind".into(), Value::from(held.kind));            request.insert("quoted_text".into(), Value::from(held.text));            // His own message is quoted as written by his own number.            if queued.target_sender.as_deref() == Some("me") {                request.insert("quoted_sender".into(), Value::from(format!("{}@s.whatsapp.net", number_of(&account))));            }        }        request.insert("account".into(), Value::from(account.as_str()));        request.insert("chat".into(), Value::from(chat));        request.insert("text".into(), Value::from(queued.body.as_str()));        request.insert("message_id".into(), Value::from(message_id.as_str()));        let timeout = if is_file { FILE_SEND_TIMEOUT } else { SEND_TIMEOUT };        let answer = helper.call("send", Value::Object(request), timeout);        if let Some(path) = &file {            let _ = std::fs::remove_file(path);        }        match answer {            Ok(result) => {                let sent_id = result                    .get("id")                    .and_then(Value::as_str)                    .filter(|id| !id.is_empty())                    .unwrap_or(&message_id)                    .to_string();                let sent_at = result                    .get("ts")                    .and_then(Value::as_i64)                    .and_then(|ts| chrono::DateTime::from_timestamp(ts, 0))                    .unwrap_or_else(chrono::Utc::now);                let mut sent = json!({                    "status": "sent",                    "sent_at": cotton_client::seams::iso(sent_at),                    "sent_external_id": sent_id,                    "error": null,                });                // A sent reaction's emoji leaves the row in the same update (the reaction row holds it).                if queued.kind == "reaction" {                    sent["emoji"] = Value::from("");                }                mark(object, &queued.id, sent)?;                drained.sent += 1;            }            Err(error) => {                let error = error.to_string();                fail(object, &queued.id, &failed_words(&error))?;                drained.failed += 1;                if !about_the_number(&error) {                    client = None;                }            }        }    }    Ok(drained)}/// ERASES: a sent row's words, caption, preview and waveform, once its message stands in the chat (`held` answers/// for its WhatsApp id): the message holds them, so the outbox keeps no second copy. The row, its status, its WhatsApp/// id and its file's key stay (the file is the message's). Answers how many rows were emptied.pub fn empty_landed(object: &ObjectClient, held: impl Fn(&str) -> bool) -> Result<i64, ObjectError> {    let mut emptied = 0;    for row in object.outbox("sent")? {        let Some(queued) = Queued::from_row(&row) else { continue };        if queued.channel != "whatsapp" {            continue;        }        let Some(sent_id) = queued.sent_external_id.as_deref() else { continue };        let holds_words = !queued.body.is_empty() || queued.preview.is_some() || !queued.waveform.is_empty();        if holds_words && held(sent_id) {            mark(object, &queued.id, json!({ "body": "", "preview": null, "waveform": null }))?;            emptied += 1;        }    }    Ok(emptied)}#[cfg(test)]mod tests {    use super::*;    #[test]    fn jids() {        assert_eq!(whatsapp_jid("+91 98000 00001").as_deref(), Some("919800000001@s.whatsapp.net"));        assert_eq!(whatsapp_jid("120363@g.us").as_deref(), Some("120363@g.us"));        assert_eq!(whatsapp_jid("abc"), None);    }    #[test]    fn a_number_whatsapp_does_not_know_is_said_plainly() {        let refused = "the WhatsApp helper refused: not_on_whatsapp: +15550009999";        assert_eq!(failed_words(refused), "This number is not on WhatsApp");        assert!(about_the_number(refused));        assert_eq!(failed_words("the WhatsApp helper refused: busy"), "WhatsApp did not take it: busy");        assert!(!about_the_number("the WhatsApp helper refused: busy"));    }    // RULE (CONTRACT "Pictures, voice notes and video"): the phones' file row is read as written there: `photo` is a    // picture, `audio` with `voice` a voice note, `mime`, the sides, the preview and the waveform (base64 of 0..100)    // go to the helper, and the sent message lands as the file already in his Cotton.    #[test]    fn the_phones_file_row_goes_to_the_helper_as_the_contract_says() {        let photo = json!({ "id": "o1", "channel": "whatsapp", "to": "15550002222@s.whatsapp.net", "status": "queued", "kind": "photo", "body": "the view",            "media_key": "db/messages/t1/abc.jpg", "mime": "image/jpeg", "size_bytes": 2048, "width": 1200, "height": 900, "preview": "/9j/AA==" });        let q = Queued::from_row(&photo).unwrap();        assert_eq!(q.kind, "picture");        let f = kind_fields(&q, Some(Path::new("/x/o1.send"))).unwrap();        assert_eq!(f["kind"], "picture");        assert_eq!(f["mimetype"], "image/jpeg");        assert_eq!((f["width"].as_u64(), f["height"].as_u64()), (Some(1200), Some(900)));        assert_eq!(f["preview"], "/9j/AA==");        assert_eq!(f["landed"], json!([{ "key": "db/messages/t1/abc.jpg", "contentType": "image/jpeg", "sizeBytes": 2048, "width": 1200, "height": 900 }]));        let voice = json!({ "id": "o2", "channel": "whatsapp", "to": "15550002222", "kind": "audio", "voice": true, "media_key": "db/messages/t1/v.m4a",            "mime": "audio/mp4", "duration_ms": 4200, "waveform": base64_of(&[0, 50, 100, 140]) });        let q = Queued::from_row(&voice).unwrap();        assert_eq!(q.kind, "voice");        assert_eq!(q.waveform, vec![0, 50, 100, 100]);        let f = kind_fields(&q, Some(Path::new("/x/o2.send"))).unwrap();        assert_eq!((f["kind"].as_str(), f["seconds"].as_u64()), (Some("voice"), Some(5)));        assert_eq!(f["waveform"], base64_of(&[0, 50, 100, 100]));        assert!(f.get("preview").is_none());        let file = Queued::from_row(&json!({ "id": "o3", "channel": "whatsapp", "to": "1", "kind": "audio", "media_key": "k", "mime": "audio/mpeg" })).unwrap();        assert_eq!(file.kind, "audio", "audio without voice goes as the file");        assert!(kind_fields(&file, Some(Path::new("/x"))).unwrap().get("waveform").is_none());        assert_eq!(Queued::from_row(&json!({ "id": "o4", "body": "hi" })).unwrap().kind, "text");    }    #[test]    fn a_file_over_whatsapps_limit_is_too_large() {        assert!(too_large("picture", MEDIA_MAX + 1) && !too_large("picture", MEDIA_MAX));        assert!(!too_large("document", MEDIA_MAX + 1) && too_large("document", DOCUMENT_MAX + 1));        assert_eq!(failed_words("the WhatsApp helper refused: too_large (120 MB; up to 100 MB)"), TOO_LARGE);        assert_eq!(failed_words("the WhatsApp helper refused: could_not_open (sips)"), COULD_NOT_OPEN);    }    #[test]    fn a_row_this_mac_cannot_open_waits() {        let sealed = json!({ "id": "r2", "table": "outbox", "data": { "channel": "whatsapp", "status": "queued", "sealed_enc": "s1:invented", "dek_enc": "a1:invented" } });        assert!(Queued::from_row(&sealed).is_none(), "a sealed row is never sent or failed by a Mac that cannot open it");    }    #[test]    fn rows_read_flat_or_under_data() {        let flat = json!({ "id": "r1", "channel": "whatsapp", "to": "+9198", "body": "hi" });        let nested = json!({ "id": "r1", "table": "outbox", "data": { "channel": "whatsapp", "to": "+9198", "body": "hi", "media_key": "" } });        assert_eq!(Queued::from_row(&flat), Queued::from_row(&nested));        assert_eq!(Queued::from_row(&flat).unwrap().media_key, None);    }}