Cotton code
117 lines · 5.7 KB · RustRaw
//! Old polls (owner, Comms 26 with the Mac on build 6, 23 Nov 2026: "he cannot see the OLD polls from past WhatsApp//! chats"). A linked device before build 6 kept a poll's question and not its options or its votes, so each such//! poll stands in his Cotton as words. WhatsApp hands a linked device its history once, when it links; it hands a//! piece of it again only when asked. So the Mac asks: for each poll its copy holds without options, it asks his//! phone (through the helper's `history`) for the messages just before the next message of that chat. The phone//! answers with the poll whole, its options and the votes on it, as history; the poll's row takes its options in//! place (`ObjectSink::fill_polls`) and the votes count on it.//!//! Asked a few at a time, each poll at most [`MAX_TRIES`] times, [`ASK_AGAIN_AFTER`] apart, so a phone that is off//! is asked again later and a poll WhatsApp no longer holds is not asked for ever. A poll that is the newest message//! of its chat has nothing after it to ask before, and waits (counted).use std::path::Path;use std::time::Duration;use cotton_client::ingest::sources::whatsapp_link::{LinkClient, LinkError};use serde_json::{json, Value};use crate::copy::{Copy, Result as CopyResult};/// Messages asked for before the next message: the poll, and room for what Cotton never kept between.pub const ASK_COUNT: u64 = 20;/// Polls asked for in one pass.pub const ASKS_PER_PASS: usize = 5;/// Seconds before a poll asked for and still without options is asked again.pub const ASK_AGAIN_AFTER: i64 = 6 * 3600;/// Times one poll is asked for.pub const MAX_TRIES: i64 = 3;/// One poll to ask for: its WhatsApp id, the number and chat it is in, and the message to ask before.#[derive(Debug, Clone, PartialEq)]pub struct Asking {    pub poll: String,    pub account: String,    pub chat: String,    /// The helper's `MessageRef`: `{ id, from_me, sender?, ts }`.    pub before: Value,}/// What one pass did.#[derive(Debug, Default, Clone, PartialEq)]pub struct Asked {    pub asked: usize,    /// Polls without options with no message after them yet.    pub waiting: usize,}/// The polls to ask for now, newest first, and how many have nothing after them to ask before.pub fn due(copy: &Copy, now: i64) -> CopyResult<(Vec<Asking>, usize)> {    let (rows, waiting) = copy.bare_polls(now - ASK_AGAIN_AFTER, MAX_TRIES, ASKS_PER_PASS)?;    let asks = rows.into_iter().filter_map(|(poll, next)| asking(&poll, &next)).collect();    Ok((asks, waiting))}/// The ask for `poll` (a message row) before `next` (the next message of its chat), from what the link wrote on each.pub fn asking(poll: &Value, next: &Value) -> Option<Asking> {    let source = poll.pointer("/meta/source")?;    let after = next.pointer("/meta/source")?;    let id = after.get("externalId").and_then(Value::as_str).filter(|id| !id.is_empty())?;    let ts = chrono::DateTime::parse_from_rfc3339(next.get("sent_at")?.as_str()?).ok()?.timestamp();    let mut before = json!({ "id": id, "from_me": next.get("direction").and_then(Value::as_str) == Some("out"), "ts": ts });    if let Some(sender) = after.get("sender").and_then(Value::as_str).filter(|s| !s.is_empty()) {        before["sender"] = Value::from(sender);    }    Some(Asking {        poll: poll.get("external_id").and_then(Value::as_str)?.to_string(),        account: source.get("account").and_then(Value::as_str)?.to_string(),        chat: source.get("chat").and_then(Value::as_str)?.to_string(),        before,    })}/// Asks the phone for the polls due now. A helper that is not there, or has no number connected, asks nothing and/// records nothing: the next pass tries again.pub fn ask(copy: &Copy, socket: &Path, now: i64) -> CopyResult<Asked> {    let (asks, waiting) = due(copy, now)?;    let mut done = Asked { asked: 0, waiting };    if asks.is_empty() {        return Ok(done);    }    let Ok(mut helper) = LinkClient::connect(socket) else { return Ok(done) };    if helper.hello().is_err() {        return Ok(done);    }    for one in asks {        let args = json!({ "account": one.account, "chat": one.chat, "before": one.before, "count": ASK_COUNT });        match helper.call("history", args, Duration::from_secs(35)) {            Ok(_) => {}            // Not connected now: asked again on a later pass, not counted as a try.            Err(LinkError::Refused(why)) if why == "busy" || why == "not_linked" => break,            Err(LinkError::Refused(_)) => {}            Err(_) => break,        }        copy.asked_poll(&one.poll, now)?;        done.asked += 1;    }    Ok(done)}#[cfg(test)]mod tests {    use super::*;    #[test]    fn a_poll_is_asked_for_before_the_next_message_of_its_chat() {        let poll = json!({ "external_id": "P1", "meta": { "source": { "account": "919800000000@s.whatsapp.net", "chat": "120363000000000001@g.us", "externalId": "P1" } } });        let next = json!({ "external_id": "N1", "direction": "in", "sent_at": "2026-07-01T10:00:05Z",                           "meta": { "source": { "externalId": "N1", "sender": "919800000001@s.whatsapp.net" } } });        let ask = asking(&poll, &next).unwrap();        assert_eq!(ask.poll, "P1");        assert_eq!(ask.chat, "120363000000000001@g.us");        assert_eq!(ask.before, json!({ "id": "N1", "from_me": false, "ts": 1782900005, "sender": "919800000001@s.whatsapp.net" }));        let mine = json!({ "direction": "out", "sent_at": "2026-07-01T10:00:05.250Z", "meta": { "source": { "externalId": "N2" } } });        assert_eq!(asking(&poll, &mine).unwrap().before, json!({ "id": "N2", "from_me": true, "ts": 1782900005 }));        assert!(asking(&poll, &json!({ "sent_at": "2026-07-01T10:00:05Z", "meta": { "source": "an export line" } })).is_none());    }}