Cotton code
140 lines · 6.2 KB · RustRaw
//! Older WhatsApp messages (coordinator, Mac 9, 24 Nov 2026: "older WhatsApp chats"). WhatsApp hands a linked device//! a slice of the history once, when it links; older messages stay on his phone until asked for. The helper can ask//! (`history`: WhatsApp's on-demand history request to his own phone, never a message to a chat), and nothing asked//! it until now. So the Mac asks, chat by chat, for the messages before the oldest one Cotton holds of it: the phone//! answers later as history, which lands as every history message does (imported, no notice, no unread).//!//! Paced so his phone and WhatsApp see a trickle: [`ASKS_PER_PASS`] chats a pass, a pass at most every//! [`OLDER_EVERY`], [`ASK_COUNT`] messages an ask, the chats he talks in most lately first. A chat is asked again//! [`ASK_AGAIN_AFTER`] later; once [`MAX_TRIES`] asks before the same message brought nothing older, its beginning is//! taken as reached and it is asked no more. A phone that is off or a number not connected asks nothing and records//! nothing: the next pass tries again.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};/// How often a pass may ask.pub const OLDER_EVERY: Duration = Duration::from_secs(10 * 60);/// Chats asked in one pass.pub const ASKS_PER_PASS: usize = 5;/// Messages asked for before the oldest held (WhatsApp's own pages are 50).pub const ASK_COUNT: u64 = 50;/// Seconds before a chat is asked again.pub const ASK_AGAIN_AFTER: i64 = 6 * 3600;/// Asks before the same message that may bring nothing before its beginning is taken as reached.pub const MAX_TRIES: i64 = 3;/// Chats read from the copy for one pass: the asked ones are passed over until one is due.const LOOK_AT: usize = 2_000;/// One chat to ask for.#[derive(Debug, Clone, PartialEq)]pub struct Asking {    pub thread: String,    pub account: String,    pub chat: String,    /// The helper's `MessageRef`: `{ id, from_me, sender?, ts }` of the oldest message held.    pub before: Value,    /// The how-many-th ask before this same message.    pub tries: i64,}/// What one pass did.#[derive(Debug, Default, Clone, PartialEq)]pub struct Asked {    pub asked: usize,    /// Chats found at their beginning this pass.    pub reached: usize,}/// The ask for a chat whose oldest message the link wrote is `oldest`.pub fn asking(thread: &str, oldest: &Value) -> Option<Asking> {    let source = oldest.pointer("/meta/source")?;    let id = source.get("externalId").and_then(Value::as_str).filter(|id| !id.is_empty())?;    let ts = chrono::DateTime::parse_from_rfc3339(oldest.get("sent_at")?.as_str()?).ok()?.timestamp();    let mut before = json!({ "id": id, "from_me": oldest.get("direction").and_then(Value::as_str) == Some("out"), "ts": ts });    if let Some(sender) = source.get("sender").and_then(Value::as_str).filter(|s| !s.is_empty()) {        before["sender"] = Value::from(sender);    }    Some(Asking {        thread: thread.to_string(),        account: source.get("account").and_then(Value::as_str).filter(|a| !a.is_empty())?.to_string(),        chat: source.get("chat").and_then(Value::as_str).filter(|c| !c.is_empty())?.to_string(),        before,        tries: 1,    })}/// The chats to ask now, and the chats whose beginning is now taken as reached (recorded here).pub fn due(copy: &Copy, now: i64) -> CopyResult<(Vec<Asking>, usize)> {    let mut asks = Vec::new();    let mut reached = 0;    for (thread, oldest, asked) in copy.oldest_whatsapp(LOOK_AT)? {        if asks.len() >= ASKS_PER_PASS {            break;        }        let Some(mut ask) = asking(&thread, &oldest) else { continue };        let id = ask.before["id"].as_str().unwrap_or_default().to_string();        if let Some((before, at, tries, _)) = asked {            if now - at < ASK_AGAIN_AFTER {                continue;            }            if before == id {                // Asked before this same message and nothing older came.                if tries >= MAX_TRIES {                    copy.asked_older(&thread, &id, at, tries, true)?;                    reached += 1;                    continue;                }                ask.tries = tries + 1;            }        }        asks.push(ask);    }    Ok((asks, reached))}/// Asks the phone for the chats due now.pub fn ask(copy: &Copy, socket: &Path, now: i64) -> CopyResult<Asked> {    let (asks, reached) = due(copy, now)?;    let mut done = Asked { asked: 0, reached };    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_older(&one.thread, one.before["id"].as_str().unwrap_or_default(), now, one.tries, false)?;        done.asked += 1;    }    Ok(done)}#[cfg(test)]mod tests {    use super::*;    #[test]    fn a_chat_is_asked_for_what_came_before_its_oldest_message() {        let oldest = json!({ "direction": "in", "sent_at": "2024-03-01T09:00:00Z",            "meta": { "source": { "account": "15550009999@s.whatsapp.net", "chat": "15550001111@s.whatsapp.net", "externalId": "OLD1", "sender": "15550001111@s.whatsapp.net" } } });        let ask = asking("t1", &oldest).unwrap();        assert_eq!((ask.thread.as_str(), ask.chat.as_str(), ask.tries), ("t1", "15550001111@s.whatsapp.net", 1));        assert_eq!(ask.before, json!({ "id": "OLD1", "from_me": false, "ts": 1709283600, "sender": "15550001111@s.whatsapp.net" }));        assert!(asking("t2", &json!({ "sent_at": "2024-03-01T09:00:00Z", "meta": { "source": "an export line" } })).is_none(), "an export's line is not the link's");    }}