Cotton code
402 lines · 16.7 KB · RustRaw
//! Whether a chat can send a text from Cotton, and where it goes: the one//! decision the thread read (`sendable`, `send_blocked_reason`), the//! composer's write and the serving Mac's send pass all ask, so a chat that//! offers the input is a chat the pass will send from.//!//! Only WhatsApp sends, through the number linked on the serving Mac. A chat//! sends when it holds WhatsApp messages, Cotton knows its WhatsApp address//! (the chat JID) and the number it is on is linked and reading under//! Connections. Anything short of that is a reason in words.//!//! The facts are spread over the chat, its contact, its newest linked message//! and the connection rows; this module says the statements and reads their//! rows, and the caller runs them in the file it holds.use std::collections::HashMap;use cotton_store::driver::Row;use sha2::{Digest, Sha256};pub const NOT_WHATSAPP: &str = "Sending works only in WhatsApp chats";pub const NOT_LINKED: &str = "WhatsApp is not linked on your Mac";pub const PAUSED: &str = "WhatsApp is paused on your Mac";pub const NEEDS_LINKING: &str = "WhatsApp needs linking again on your Mac";pub const NO_ADDRESS: &str = "Cotton does not know this chat's WhatsApp address";pub const WHICH_NUMBER: &str = "Cotton does not know which of your WhatsApp numbers this chat is on";pub const NO_REPLY: &str = "This WhatsApp conversation cannot receive a message";pub const ARCHIVED: &str = "This chat is archived";pub const LEFT: &str = "You have left this chat";/// Where a text from this chat goes: the linked number (the helper's account/// JID) and the chat's JID.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SendTarget {    pub account: String,    pub chat: String,}/// A chat's target, or why it cannot send.pub type SendDecision = Result<SendTarget, &'static str>;/// What one chat says about where it sits on WhatsApp.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ChatFacts {    /// It holds at least one WhatsApp message.    pub whatsapp: bool,    /// `dm` or `group`.    pub kind: String,    pub archived: bool,    pub self_left: bool,    pub external_key: Option<String>,    /// A direct chat's contact's number, digits only.    pub phone: Option<String>,    /// From its newest message the linked number brought in (`meta.source`).    pub linked_account: Option<String>,    pub linked_chat: Option<String>,}/// One `whatsapp` connection row.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LinkedNumber {    pub id: String,    /// reading, paused, needs_sign_in, failed.    pub state: String,    /// `config.account`: the helper's JID for the number.    pub account: Option<String>,}impl LinkedNumber {    /// The number's digits: from its JID, else from its row id    /// (`conn:whatsapp:+15551234567`).    fn digits(&self) -> String {        match &self.account {            Some(account) => digits_of(account),            None => self.id.rsplit(':').next().unwrap_or("").chars().filter(char::is_ascii_digit).collect(),        }    }    fn jid(&self) -> String {        self.account.clone().unwrap_or_else(|| format!("{}@s.whatsapp.net", self.digits()))    }}/// A JID's number: the user part, without a device suffix, digits only.fn digits_of(jid: &str) -> String {    let user = jid.split('@').next().unwrap_or(jid);    let user = user.split(':').next().unwrap_or(user);    user.chars().filter(char::is_ascii_digit).collect()}/// The group key a WhatsApp group is stored under when the backup or the/// linked number brought it in: `wa:group:<jid>`. An export's key is a slug/// of the title, which names no JID.fn group_jid(external_key: &str) -> Option<String> {    let jid = external_key.strip_prefix(crate::import::group::GROUP_EXTERNAL_KEY_PREFIX)?;    jid.ends_with("@g.us").then(|| jid.to_string())}/// The decision, from what the file says./// The chat's WhatsApp address, when the chat itself lets a text go there:/// a WhatsApp chat, not archived, not left, not a broadcast.fn chat_of(facts: &ChatFacts) -> Result<Option<String>, &'static str> {    if !facts.whatsapp {        return Err(NOT_WHATSAPP);    }    if facts.archived {        return Err(ARCHIVED);    }    if facts.self_left {        return Err(LEFT);    }    let chat = facts.linked_chat.clone().or_else(|| match facts.kind.as_str() {        "group" => facts.external_key.as_deref().and_then(group_jid),        _ => facts            .phone            .as_deref()            .map(|phone| phone.chars().filter(char::is_ascii_digit).collect::<String>())            .filter(|digits| !digits.is_empty())            .map(|digits| format!("{digits}@s.whatsapp.net")),    });    if chat.as_deref().is_some_and(|jid| jid.trim().ends_with("@broadcast")) {        return Err(NO_REPLY);    }    Ok(chat)}/// Where a text written on a phone goes: the chat's address, and the number/// that brought the chat in when a message says so (else the Mac sends from/// the number it has linked).#[derive(Debug, Clone, PartialEq, Eq)]pub struct PhoneTarget {    pub account: Option<String>,    pub chat: String,}/// The decision as a phone makes it (owner, 22 Nov 2026: a text written in/// Comms in a WhatsApp chat goes out through the Mac's link). A phone holds no/// connection rows (they are the Mac's), so whether the link is up is not its/// to say: the text waits, "Waiting to send", until the Mac sends it or says/// why it cannot.pub fn decide_on_phone(facts: &ChatFacts) -> Result<PhoneTarget, &'static str> {    let chat = chat_of(facts)?.ok_or(NO_ADDRESS)?;    Ok(PhoneTarget { account: facts.linked_account.clone(), chat })}/// The words a text to a number WhatsApp holds no account for fails with:/// the Mac writes exactly these as the outbox row's `error` (it asks WhatsApp/// before it sends to a one-to-one chat), and the phone draws "Not sent: This/// number is not on WhatsApp" with Retry (owner, 23 Nov 2026, FEEDBACK-2 A).pub const NOT_ON_WHATSAPP: &str = "This number is not on WhatsApp";/// What a phone's copy shows of the owner's WhatsApp link: messages the Mac's/// link brought in (`meta.source.account`, kept only by the linked-device/// reader, never by a backup or an export). A copy holding none is not linked,/// and nothing about writing to a number changes for it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Link {    /// The linked number's JID when the link brought messages in through one    /// number only; with two, the Mac sends from the one it has linked.    pub account: Option<String>,}/// The link's first two numbers, newest index entry first, over/// `idx_cotton_msg_messages_source_account` (a seek, however large the copy)./// Parameters: workspace, the account to look past ('' for the first).pub const LINK_SQL: &str = "SELECT json_extract(meta, '$.source.account') AS account FROM cotton_msg_messages  WHERE workspace_id = ? AND channel = 'whatsapp' AND deleted_at IS NULL AND hidden_at IS NULL    AND json_extract(meta, '$.source.account') IS NOT NULL AND json_extract(meta, '$.source.account') > ?  ORDER BY json_extract(meta, '$.source.account') LIMIT 1";/// Whether this copy is linked to WhatsApp through the Mac, and through which number.pub fn link_of<E>(read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>, workspace: &str) -> Result<Option<Link>, E> {    let account = |read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>, after: &str| -> Result<Option<String>, E> {        Ok(read(LINK_SQL, &[workspace.to_string(), after.to_string()])?.first().and_then(|row| row.text("account")).map(str::to_string))    };    let Some(first) = account(read, "")? else { return Ok(None) };    let second = account(read, &first)?;    Ok(Some(Link { account: second.is_none().then_some(first) }))}/// Where a message written to a phone number goes (owner, 23 Nov 2026,/// FEEDBACK-2 A: "one place to write to a number"). The one rule every way/// of writing to a number asks: a new message, a contact, a person's page, a/// number tapped anywhere.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Route {    /// The number is one of the person's Cotton connections: the Cotton chat.    Cotton,    /// Not on Cotton, and the copy is linked to WhatsApp through the Mac: that    /// number's WhatsApp, by the outbox the Mac drains.    Whatsapp(PhoneTarget),    /// Not on Cotton and no link: the Cotton chat, whose words wait for them,    /// with the invite (as before the link).    Invite,}impl Route {    /// The place a screen marks: `cotton` or `whatsapp`.    pub fn place(&self) -> &'static str {        match self {            Route::Whatsapp(_) => "whatsapp",            Route::Cotton | Route::Invite => "cotton",        }    }}/// [`Route`] for `number` (any spelling: its digits are what WhatsApp/// addresses), `on_cotton` when the person's copy knows the number on Cotton/// (they wrote, were written to and reached, or were found).pub fn route(number: &str, on_cotton: bool, link: Option<&Link>) -> Route {    if on_cotton {        return Route::Cotton;    }    let digits: String = number.chars().filter(char::is_ascii_digit).collect();    match link {        Some(link) if !digits.is_empty() => Route::Whatsapp(PhoneTarget { account: link.account.clone(), chat: format!("{digits}@s.whatsapp.net") }),        _ => Route::Invite,    }}/// [`decide_on_phone`] for every chat in `thread_ids`, one statement per few/// hundred chats over the phone's copy.pub fn phone_targets<E>(    read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>,    thread_ids: &[String],) -> Result<HashMap<String, Result<PhoneTarget, &'static str>>, E> {    let mut out = HashMap::new();    for chunk in thread_ids.chunks(500) {        for row in read(&chat_facts_sql(chunk.len()), chunk)? {            if let Some((id, facts)) = facts_of_row(&row) {                out.insert(id, decide_on_phone(&facts));            }        }    }    for id in thread_ids {        out.entry(id.clone()).or_insert(Err(NOT_WHATSAPP));    }    Ok(out)}pub fn decide(facts: &ChatFacts, numbers: &[LinkedNumber]) -> SendDecision {    let chat = chat_of(facts)?;    let account = match &facts.linked_account {        // The number that brought this chat in is the one it sends from.        Some(account) => {            let digits = digits_of(account);            let number = numbers.iter().find(|number| number.digits() == digits).ok_or(NOT_LINKED)?;            usable(number)?;            account.clone()        }        // Never read through a linked number: the one number reading, when        // there is exactly one.        None => {            let reading: Vec<&LinkedNumber> = numbers.iter().filter(|number| number.state == "reading").collect();            match reading.as_slice() {                [number] => number.jid(),                [] => {                    return Err(match numbers.first() {                        None => NOT_LINKED,                        Some(_) if numbers.iter().any(|number| number.state == "paused") => PAUSED,                        Some(_) => NEEDS_LINKING,                    })                }                _ => return Err(WHICH_NUMBER),            }        }    };    let chat = chat.ok_or(NO_ADDRESS)?;    Ok(SendTarget { account, chat })}fn usable(number: &LinkedNumber) -> Result<(), &'static str> {    match number.state.as_str() {        "reading" => Ok(()),        "paused" => Err(PAUSED),        _ => Err(NEEDS_LINKING),    }}/// The linked numbers, every `whatsapp` connection row.pub const LINKED_NUMBERS_SQL: &str = "SELECT id, state, json_extract(config, '$.account') AS account   FROM cotton_connections WHERE kind = 'whatsapp' ORDER BY id";/// What a page of chats says, one statement for `count` ids.pub fn chat_facts_sql(count: usize) -> String {    let marks = vec!["?"; count].join(", ");    format!(        "SELECT t.id AS id, t.kind AS kind, t.archived AS archived, t.external_key AS external_key, c.phone_e164 AS phone,                EXISTS (SELECT 1 FROM cotton_msg_thread_participants p                         WHERE p.thread_id = t.id AND p.is_self = 1 AND NULLIF(trim(p.left_at), '') IS NOT NULL) AS self_left,                EXISTS (SELECT 1 FROM cotton_msg_messages m WHERE m.thread_id = t.id AND m.channel = 'whatsapp') AS whatsapp,                (SELECT json_object('account', json_extract(m.meta, '$.source.account'), 'chat', json_extract(m.meta, '$.source.chat'))                   FROM cotton_msg_messages m                  WHERE m.thread_id = t.id AND m.channel = 'whatsapp'                    AND json_extract(m.meta, '$.source.account') IS NOT NULL                    AND json_extract(m.meta, '$.source.chat') IS NOT NULL                  ORDER BY m.sent_at DESC LIMIT 1) AS linked           FROM cotton_msg_threads t LEFT JOIN cotton_msg_contacts c ON c.id = t.contact_id          WHERE t.id IN ({marks})"    )}fn number_of_row(row: &Row) -> Option<LinkedNumber> {    Some(LinkedNumber {        id: row.text("id")?.to_string(),        state: row.text("state").unwrap_or("").to_string(),        account: row.text("account").map(str::trim).filter(|account| !account.is_empty()).map(str::to_string),    })}fn facts_of_row(row: &Row) -> Option<(String, ChatFacts)> {    let linked: serde_json::Value =        row.text("linked").and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();    let field = |name: &str| {        linked.get(name).and_then(serde_json::Value::as_str).map(str::to_string).filter(|text| !text.is_empty())    };    let facts = ChatFacts {        whatsapp: row.int("whatsapp").unwrap_or(0) != 0,        kind: row.text("kind").unwrap_or("").to_string(),        archived: row.int("archived").unwrap_or(0) != 0,        self_left: row.int("self_left").unwrap_or(0) != 0,        external_key: row.text("external_key").map(str::to_string),        phone: row.text("phone").map(str::to_string),        linked_account: field("account"),        linked_chat: field("chat"),    };    Some((row.text("id")?.to_string(), facts))}/// The decision for every chat in `thread_ids`, the connection rows read once/// and the chats one statement per few hundred. `read` runs a statement over/// text parameters in the caller's file — this crate opens none. A chat the/// file does not hold is not a WhatsApp chat.pub fn send_targets<E>(    read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>,    thread_ids: &[String],) -> Result<HashMap<String, SendDecision>, E> {    let numbers: Vec<LinkedNumber> = read(LINKED_NUMBERS_SQL, &[])?.iter().filter_map(number_of_row).collect();    let mut out = HashMap::new();    for chunk in thread_ids.chunks(500) {        for row in read(&chat_facts_sql(chunk.len()), chunk)? {            if let Some((id, facts)) = facts_of_row(&row) {                out.insert(id, decide(&facts, &numbers));            }        }    }    for id in thread_ids {        out.entry(id.clone()).or_insert(Err(NOT_WHATSAPP));    }    Ok(out)}/// The decision for one chat.pub fn send_target<E>(    read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>,    thread_id: &str,) -> Result<SendDecision, E> {    let mut found = send_targets(read, &[thread_id.to_string()])?;    Ok(found.remove(thread_id).unwrap_or(Err(NOT_WHATSAPP)))}/// The owner app's dispatcher; each transport keeps its own target checks./// WhatsApp is the one transport (Instagram left, owner, 22 Nov 2026).#[derive(Debug, Clone, PartialEq, Eq)]pub enum OutgoingTarget {    Whatsapp(SendTarget),}impl OutgoingTarget {    pub fn channel(&self) -> crate::constants::MessageChannel {        match self {            Self::Whatsapp(_) => crate::constants::MessageChannel::Whatsapp,        }    }}pub fn outgoing_targets<E>(    read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>,    thread_ids: &[String],) -> Result<HashMap<String, Result<OutgoingTarget, &'static str>>, E> {    Ok(send_targets(read, thread_ids)?.into_iter().map(|(id, decision)| (id, decision.map(OutgoingTarget::Whatsapp))).collect())}pub fn outgoing_target<E>(    read: &mut dyn FnMut(&str, &[String]) -> Result<Vec<Row>, E>,    thread_id: &str,) -> Result<Result<OutgoingTarget, &'static str>, E> {    Ok(outgoing_targets(read, &[thread_id.to_string()])?.remove(thread_id).unwrap_or(Err(NOT_WHATSAPP)))}/// The WhatsApp id one try of a text goes out under, derived from its row so/// a try resent after a restart carries the same id (and WhatsApp keeps one/// message), while a retry after a failure — one more attempt — gets a fresh/// one. Shaped like the ids WhatsApp's own clients mint.pub fn whatsapp_message_id(row_id: &str, attempts: i64) -> String {    let digest = Sha256::digest(format!("{row_id}:{attempts}").as_bytes());    let hex = hex::encode_upper(digest);    format!("3EB0{}", &hex[..20])}#[cfg(test)]#[path = "send_tests.rs"]mod tests;