Cotton code
749 lines · 34.6 KB · RustRaw
use super::*;use std::io::{BufRead, BufReader, Write};use std::os::unix::net::UnixListener;use std::sync::{Arc, Mutex};use std::thread;const WORKSPACE: &str = "00000000-0000-4000-8000-000000000001";const DEVICE: &str = "Test Mac";const ACCOUNT: &str = "15550009999@s.whatsapp.net";const GROUP: &str = "120363000000000001@g.us";const FRIEND: &str = "15550001111@s.whatsapp.net";fn message(seq: i64, id: &str, chat: &str, extra: Value) -> Value {    let mut msg = json!({        "id": id, "chat": chat, "from_me": false, "is_group": chat.ends_with("@g.us"),        "ts": 1_759_000_000 + seq, "kind": "text", "text": format!("hello {seq}"), "origin": "live"    });    if let (Value::Object(base), Value::Object(more)) = (&mut msg, extra) {        base.extend(more);    }    json!({ "seq": seq, "event": "message", "account": ACCOUNT, "message": msg })}fn events(values: Vec<Value>) -> Vec<WireEvent> {    values        .into_iter()        .map(|v| serde_json::from_value(v).expect("a wire event"))        .collect()}/// Media that is always there (writes a byte) or always gone.struct FakeMedia {    gone: bool,    fetched: Vec<PathBuf>,}impl MediaFetch for FakeMedia {    fn fetch(&mut self, _account: &str, _pointer: &Value, dest: &Path) -> Result<bool, String> {        if self.gone {            return Ok(false);        }        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();        std::fs::write(dest, b"x").unwrap();        self.fetched.push(dest.to_path_buf());        Ok(true)    }}fn batch(    values: Vec<Value>,    media: &mut FakeMedia,    dir: &Path,) -> (Vec<(ImportBatch, Vec<IngestMediaFile>)>, IngestNotes) {    let mut notes = IngestNotes::new();    let out = batches_from_events(        &events(values),        WORKSPACE,        crate::test_support::namespace(),        DEVICE,        dir,        media,        &mut notes,    )    .expect("batches");    (out, notes)}// A group is keyed by its JID and reserves the backup's own thread id, so a// group read here and the same group restored from an iPhone backup are one thread.#[test]fn a_group_lands_where_the_backup_puts_it() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia {        gone: false,        fetched: vec![],    };    let (out, _) = batch(        vec![            message(                1,                "A1",                GROUP,                json!({ "sender": FRIEND, "push_name": "Asha", "chat_name": "Allotment" }),            ),            message(                2,                "A2",                GROUP,                json!({ "from_me": true, "quoted_id": "A1" }),            ),        ],        &mut media,        dir.path(),    );    assert_eq!(out.len(), 1);    let (batch, files) = &out[0];    let thread = batch.thread.as_ref().expect("a group thread block");    assert_eq!(thread.external_key, whatsapp_group_key(GROUP));    assert_eq!(thread.title, "Allotment");    assert_eq!(        batch.new_thread_id.as_deref(),        Some(            whatsapp_thread_id(crate::test_support::namespace(), &format!("group:{GROUP}"))                .as_str()        )    );    assert_eq!(thread.participants.len(), 1);    assert_eq!(thread.participants[0].label, "Asha");    assert_eq!(thread.participants[0].phone.as_deref(), Some("15550001111"));    assert_eq!(batch.messages[0].sender_label.as_deref(), Some("Asha"));    assert_eq!(batch.messages[0].external_id, "A1");    assert_eq!(batch.messages[1].direction, Direction::Out);    assert_eq!(batch.messages[1].sender_label, None);    assert_eq!(        batch.messages[1].reply_to_external_id.as_deref(),        Some("A1")    );    assert!(files.is_empty());}#[test]fn a_dm_names_its_counterpart_by_number_and_a_hidden_id_chat_is_counted_not_written() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia {        gone: false,        fetched: vec![],    };    let (out, notes) = batch(        vec![            message(                1,                "D1",                FRIEND,                json!({ "sender": FRIEND, "chat_name": "Asha" }),            ),            message(2, "L1", "88888888888888@lid", json!({})),        ],        &mut media,        dir.path(),    );    assert_eq!(out.len(), 1);    let dm = out[0].0.dm.as_ref().expect("a dm block");    assert_eq!(dm.phone.as_deref(), Some("15550001111"));    assert_eq!(dm.label, "Asha");    assert!(out[0].0.thread.is_none());    assert_eq!(notes.get("dmWithoutPhone"), Some(&1));}// RULE: an edit, a delete for everyone or a reaction from the linked device changes the message it names; it never becomes a new message.#[test]fn edits_reactions_and_revokes_are_changes_not_new_messages() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia {        gone: false,        fetched: vec![],    };    let events = vec![        message(1, "E1", FRIEND, json!({ "edit_of": "D1", "text": "see you at 6" })),        message(2, "R1", FRIEND, json!({ "kind": "reaction", "reaction_to": "D1", "text": "👍" })),        message(3, "R2", FRIEND, json!({ "kind": "reaction", "reaction_to": "D1", "text": "", "from_me": true })),        json!({ "seq": 4, "event": "revoke", "account": ACCOUNT, "chat": FRIEND, "target": "D2",                "message": { "id": "X1", "chat": FRIEND, "ts": 1_790_000_000, "kind": "other" } }),        json!({ "seq": 5, "event": "chat", "account": ACCOUNT, "chat": GROUP, "name": "Allotment" }),    ];    let (out, _) = batch(events.clone(), &mut media, dir.path());    assert!(out.is_empty(), "no change is written as a new message");    let wire: Vec<WireEvent> = events.into_iter().map(|event| serde_json::from_value(event).unwrap()).collect();    let mut notes = IngestNotes::new();    let changes = changes_from_events(&wire, &mut notes);    assert_eq!(changes.len(), 4);    assert!(matches!(&changes[0], MessageChange::Edit { external_id, body, .. } if external_id == "D1" && body == "see you at 6"));    assert!(matches!(&changes[1], MessageChange::Reaction { actor, emoji, .. } if actor == "15550001111" && emoji == "👍"));    assert!(matches!(&changes[2], MessageChange::Reaction { actor, emoji, .. } if actor == "owner" && emoji.is_empty()));    assert!(matches!(&changes[3], MessageChange::Revoke { external_id, .. } if external_id == "D2"));}// RULE (27 Oct 2026): a message whose file cannot be had — gone from// WhatsApp, or a pointer that fetches nothing — is still written, saying what// it was when it has no words: it was sent, a reply may name it, and dropping// it (or refusing its page) loses it.#[test]fn a_picture_rides_with_its_message_and_a_gone_one_without_words_says_what_it_was() {    let dir = tempfile::tempdir().unwrap();    let pointer = json!({ "type": "image", "mimetype": "image/jpeg", "direct_path": "/v/x", "media_key": "AQI=" });    let mut media = FakeMedia {        gone: false,        fetched: vec![],    };    let (out, _) = batch(        vec![message(            1,            "P1",            FRIEND,            json!({ "kind": "image", "text": "", "media": pointer.clone() }),        )],        &mut media,        dir.path(),    );    let (batch_one, files) = &out[0];    assert_eq!(batch_one.messages[0].body, "");    assert_eq!(files.len(), 1);    assert_eq!(files[0].external_id, "P1");    assert_eq!(files[0].content_type.as_deref(), Some("image/jpeg"));    assert!(files[0].path.ends_with("P1.jpg"));    let mut gone = FakeMedia {        gone: true,        fetched: vec![],    };    let (out, notes) = batch(        vec![message(            1,            "P2",            FRIEND,            json!({ "kind": "image", "text": "", "media": pointer }),        )],        &mut gone,        dir.path(),    );    let (batch_two, files) = &out[0];    assert_eq!(batch_two.messages[0].body, "Photo");    assert!(files.is_empty());    assert_eq!(notes.get("media:gone"), Some(&1));    assert_eq!(notes.get("empty:image"), None);}#[test]fn only_gone_and_unfetchable_say_a_file_cannot_be_had() {    assert!(cannot_be_had("gone"));    assert!(cannot_be_had("unfetchable: media pointer incomplete: no direct path"));    assert!(cannot_be_had("unfetchable: hash of media plaintext doesn't match"));    assert!(!cannot_be_had("media pointer incomplete"));    assert!(!cannot_be_had("not_linked"));    assert!(!cannot_be_had("failed to download media from last host: synthetic"));}/// The helper's own answer to an incomplete pointer, through the socket: the/// page lands, its message says what it was, and no download is asked again.#[test]fn an_unfetchable_pointer_lands_its_message_with_a_label_and_the_page_is_acknowledged() {    let dir = tempfile::tempdir().unwrap();    let incomplete = json!({ "type": "video", "mimetype": "video/mp4", "direct_path": "", "media_key": "a2V5", "file_length": 16_051_529 });    let state = Arc::new(Mutex::new(FakeHelper {        outbox: vec![            message(1, "V1", FRIEND, json!({ "sender": FRIEND, "kind": "video", "text": "", "origin": "history", "media": incomplete })),            message(2, "T1", FRIEND, json!({ "sender": FRIEND })),        ],        media_refusal: Some("unfetchable: media pointer incomplete: no direct path".to_string()),        ..FakeHelper::default()    }));    spawn_fake(dir.path(), Arc::clone(&state));    let source = link_source(dir.path());    let mut written: Vec<IngestBatch> = Vec::new();    let outcome = source        .read(None, &mut |batch: IngestBatch| {            written.push(batch);            Ok(())        })        .expect("the page lands");    assert_eq!(state.lock().unwrap().acks, vec![2]);    assert_eq!(state.lock().unwrap().media_asks, 1);    assert_eq!(outcome.cursor, "seq:2");    let IngestWork::Messages { request, media } = &written[0].work else {        panic!("a messages batch");    };    assert_eq!(request.messages.len(), 2);    assert_eq!(request.messages[0].external_id, "V1");    assert_eq!(request.messages[0].body, "Video");    assert!(media.is_empty());}/* -------------------------------------------- a fake helper on a socket -- *//// How the fake answers one `send`.#[derive(Debug, Clone)]pub(crate) enum SendAnswer {    /// Sent, at this unix second.    Sent(i64),    /// `ok: false` with this reason.    Refused(String),    /// The line is read and the connection dropped, unanswered.    Drop,}/// The helper's outbox as the fake holds it; `ack` removes what it covers./// Every `send` is recorded and answered from `answers` in turn, `Sent` once/// they run out.#[derive(Default)]pub(crate) struct FakeHelper {    pub(crate) outbox: Vec<Value>,    pub(crate) acks: Vec<i64>,    pub(crate) sends: Vec<Value>,    pub(crate) answers: std::collections::VecDeque<SendAnswer>,    /// The chats it was told it may ask a profile picture for; `None` is a    /// helper too old to keep a list (its `hello` says no digest).    pub(crate) pictures: Option<BTreeSet<String>>,    pub(crate) told: usize,    /// The bytes every `media` request downloads (written beside `dest` and    /// renamed into place, as the helper does); `None` panics on one.    pub(crate) media_bytes: Option<Vec<u8>>,    /// The `media` requests it was asked, each one a download from WhatsApp.    pub(crate) media_asks: usize,    /// When set, every `media` request is refused with this reason.    pub(crate) media_refusal: Option<String>,}pub(crate) fn spawn_fake(dir: &Path, state: Arc<Mutex<FakeHelper>>) {    let listener = UnixListener::bind(dir.join(SOCKET_NAME)).expect("bind the fake helper");    thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { return };            let state = Arc::clone(&state);            thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                for line in BufReader::new(stream).lines() {                    let Ok(line) = line else { return };                    let request: Value = serde_json::from_str(&line).unwrap();                    let id = request["id"].as_i64().unwrap();                    let mut helper = state.lock().unwrap();                    let result = match request["op"].as_str().unwrap() {                        "hello" => {                            let mut hello = json!({ "version": PROTOCOL_VERSION, "accounts": [], "pending": helper.outbox.len() });                            if let Some(pictures) = &helper.pictures {                                hello["pictures"] = Value::from(pictures_digest(pictures));                            }                            hello                        }                        "events" => {                            let after = request["after"].as_i64().unwrap_or(0);                            let limit = request["limit"].as_u64().unwrap_or(500) as usize;                            let page: Vec<Value> = helper                                .outbox                                .iter()                                .filter(|e| e["seq"].as_i64().unwrap() > after)                                .take(limit)                                .cloned()                                .collect();                            json!({ "events": page })                        }                        "pictures" => {                            let chats = request["chats"].as_array().unwrap();                            helper.pictures = Some(chats.iter().map(|c| c.as_str().unwrap().to_string()).collect());                            helper.told += 1;                            Value::Null                        }                        "ack" => {                            let seq = request["seq"].as_i64().unwrap();                            helper.acks.push(seq);                            helper.outbox.retain(|e| e["seq"].as_i64().unwrap() > seq);                            Value::Null                        }                        "send" => {                            helper.sends.push(request.clone());                            match helper.answers.pop_front().unwrap_or(SendAnswer::Sent(1_759_100_000)) {                                SendAnswer::Sent(ts) => json!({ "id": request["message_id"], "ts": ts }),                                SendAnswer::Refused(reason) => {                                    let reply = json!({ "reply": id, "ok": false, "error": reason });                                    writer.write_all(format!("{reply}\n").as_bytes()).unwrap();                                    continue;                                }                                SendAnswer::Drop => return,                            }                        }                        "media" if helper.media_refusal.is_some() => {                            helper.media_asks += 1;                            let reply = json!({ "reply": id, "ok": false, "error": helper.media_refusal.clone() });                            writer.write_all(format!("{reply}\n").as_bytes()).unwrap();                            continue;                        }                        "media" if helper.media_bytes.is_some() => {                            helper.media_asks += 1;                            let dest = PathBuf::from(request["dest"].as_str().unwrap());                            std::fs::create_dir_all(dest.parent().unwrap()).unwrap();                            let part = dest.with_extension("part");                            std::fs::write(&part, helper.media_bytes.as_ref().unwrap()).unwrap();                            std::fs::rename(&part, &dest).unwrap();                            json!({ "path": dest, "bytes": helper.media_bytes.as_ref().unwrap().len() })                        }                        other => panic!("the reader must not ask the helper for {other}"),                    };                    let reply = json!({ "reply": id, "ok": true, "result": result });                    writer.write_all(format!("{reply}\n").as_bytes()).unwrap();                }            });        }    });}fn link_source(dir: &Path) -> WhatsappLinkSource {    WhatsappLinkSource::new(WhatsappLinkSourceInput {        workspace_id: WORKSPACE.to_string(),        namespace: crate::test_support::namespace().clone(),        device: DEVICE.to_string(),        dir: dir.to_path_buf(),        media_dir: dir.join("media"),    })}/// RULE: the WhatsApp link reader acknowledges a page of the helper's outbox only after every batch from it was written./// WhatsApp hands a linked device each live message once; an early ack would lose it for good.#[test]fn a_page_is_acknowledged_only_after_its_batches_are_written() {    let dir = tempfile::tempdir().unwrap();    let state = Arc::new(Mutex::new(FakeHelper {        outbox: vec![            message(                1,                "A1",                GROUP,                json!({ "sender": FRIEND, "push_name": "Asha", "chat_name": "Allotment" }),            ),            message(2, "D1", FRIEND, json!({ "sender": FRIEND })),            json!({ "seq": 3, "event": "state", "account": ACCOUNT, "state": "logged_out" }),        ],        acks: vec![],        ..FakeHelper::default()    }));    spawn_fake(dir.path(), Arc::clone(&state));    let source = link_source(dir.path());    assert_eq!(source.probe().state, crate::ingest::SourceState::Ready);    // A failing write leaves everything in the helper.    let mut failing = |_batch: IngestBatch| -> Result<(), String> { Err("disk full".into()) };    assert!(source.read(None, &mut failing).is_err());    assert!(state.lock().unwrap().acks.is_empty());    assert_eq!(state.lock().unwrap().outbox.len(), 3);    let mut written: Vec<IngestBatch> = Vec::new();    let mut emit = |batch: IngestBatch| -> Result<(), String> {        written.push(batch);        Ok(())    };    let outcome = source.read(None, &mut emit).expect("a read");    assert_eq!(written.len(), 2);    assert_eq!(state.lock().unwrap().acks, vec![3]);    assert!(state.lock().unwrap().outbox.is_empty());    assert_eq!(outcome.cursor, "seq:3");    assert_eq!(outcome.notes.get("read:state"), Some(&1));    let mut again: Vec<IngestBatch> = Vec::new();    let mut emit = |batch: IngestBatch| -> Result<(), String> {        again.push(batch);        Ok(())    };    source        .read(Some("seq:3"), &mut emit)        .expect("a second read");    assert!(again.is_empty());}/// RULE (27 Oct 2026): a page's media is downloaded from WhatsApp once and/// kept until the page lands. A page the object refused part way is read/// again on the next pass; its files are already in the media folder, whole/// (their length and SHA-256 the pointer's), so the helper is not asked/// again — a 112 MB document re-fetched on every 5-second pass spent 36 GB an/// hour of the owner's home line. A file there that is not the pointer's is/// fetched afresh; the landed page's files go.#[test]fn a_refused_pages_media_is_kept_and_never_fetched_again() {    use base64::Engine as _;    use sha2::Digest as _;    let bytes = b"a synthetic document, whole".to_vec();    let pointer = json!({        "type": "document", "mimetype": "application/pdf", "direct_path": "/v/t62/x", "media_key": "a2V5",        "file_length": bytes.len(),        "file_sha256": base64::engine::general_purpose::STANDARD.encode(sha2::Sha256::digest(&bytes)),    });    let dir = tempfile::tempdir().unwrap();    let state = Arc::new(Mutex::new(FakeHelper {        outbox: vec![            message(1, "DOC1", FRIEND, json!({ "sender": FRIEND, "kind": "document", "text": "", "media": pointer.clone() })),            message(2, "T1", GROUP, json!({ "sender": FRIEND, "push_name": "Asha", "chat_name": "Allotment" })),        ],        media_bytes: Some(bytes.clone()),        ..FakeHelper::default()    }));    spawn_fake(dir.path(), Arc::clone(&state));    let source = link_source(dir.path());    // The document's batch lands, the group's is refused: twice.    let mut files: Vec<PathBuf> = Vec::new();    for _ in 0..2 {        let mut refusing = |batch: IngestBatch| -> Result<(), String> {            match batch.work {                IngestWork::Messages { request, media } if request.thread.is_none() => {                    files.extend(media.into_iter().map(|file| file.path));                    Ok(())                }                _ => Err("the object refused (400 bad_batch): synthetic".to_string()),            }        };        assert!(source.read(None, &mut refusing).is_err());    }    assert_eq!(state.lock().unwrap().media_asks, 1, "the refused page's media was fetched again");    assert!(state.lock().unwrap().acks.is_empty());    let file = files[0].clone();    assert_eq!(files, vec![file.clone(), file.clone()]);    assert_eq!(std::fs::read(&file).unwrap(), bytes, "the file waits whole for its page");    // Something else under its name is not the pointer's file: fetched afresh.    std::fs::write(&file, b"a torn copy").unwrap();    assert_eq!(held_whole(&file, &pointer), Held::Wrong);    let mut landing = |_batch: IngestBatch| -> Result<(), String> { Ok(()) };    source.read(None, &mut landing).expect("the page lands");    assert_eq!(state.lock().unwrap().media_asks, 2);    assert_eq!(state.lock().unwrap().acks, vec![2]);    assert!(!file.exists(), "a landed page's staging copies go");    assert_eq!(held_whole(&file, &pointer), Held::Absent);}/// RULE: a downloaded file is the pointer's when its SHA-256 is, whatever the/// pointer's `file_length` says. The helper verifies every download against/// the hash; a length WhatsApp got wrong must not throw the file away and/// fetch it again on every pass of a refused page.#[test]fn a_file_with_the_pointers_hash_is_whole_whatever_its_length_says() {    use base64::Engine as _;    use sha2::Digest as _;    let dir = tempfile::tempdir().unwrap();    let file = dir.path().join("V1.mp4");    let bytes = b"synthetic video bytes".to_vec();    std::fs::write(&file, &bytes).unwrap();    let sha = base64::engine::general_purpose::STANDARD.encode(sha2::Sha256::digest(&bytes));    let pointer = json!({ "file_length": bytes.len() + 7, "file_sha256": sha });    assert_eq!(held_whole(&file, &pointer), Held::Whole);    let other = json!({ "file_length": bytes.len(), "file_sha256": base64::engine::general_purpose::STANDARD.encode([0u8; 32]) });    assert_eq!(held_whole(&file, &other), Held::Wrong);    // A pointer naming no hash is judged by its length.    assert_eq!(held_whole(&file, &json!({ "file_length": bytes.len() })), Held::Whole);    assert_eq!(held_whole(&file, &json!({ "file_length": 1 })), Held::Wrong);}#[test]fn no_helper_is_not_found_and_reads_nothing() {    let dir = tempfile::tempdir().unwrap();    let source = link_source(dir.path());    assert_eq!(source.probe().state, crate::ingest::SourceState::NotFound);    let mut emit = |_batch: IngestBatch| -> Result<(), String> { panic!("nothing to emit") };    let outcome = source.read(Some("seq:9"), &mut emit).expect("a quiet read");    assert_eq!(outcome.cursor, "seq:9");    assert_eq!(outcome.notes.get("unavailable"), Some(&1));}/// RULE (owner, 22 Nov 2026): WhatsApp statuses are never collected, whatever any switch says: a status a helper from/// before still holds is passed over, counted, and acked with its page, and no picture of it is fetched; the messages/// beside it are read as ever. (10 Oct 2026 the owner switched them off per number; now they are gone for everyone.)#[test]fn a_status_is_passed_over_and_acked_and_its_messages_are_read() {    let dir = tempfile::tempdir().unwrap();    // The fake helper answers no `media` op: a single picture asked for would    // fail the read, so a finished read proves none was fetched.    let video = json!({ "sender": FRIEND, "kind": "video", "text": "", "media": { "type": "video", "mimetype": "video/mp4" } });    let state = Arc::new(Mutex::new(FakeHelper {        outbox: vec![            message(1, "S1", "status@broadcast", video),            message(2, "S2", "status@broadcast", json!({ "sender": FRIEND })),            message(3, "D1", FRIEND, json!({ "sender": FRIEND })),        ],        ..FakeHelper::default()    }));    spawn_fake(dir.path(), Arc::clone(&state));    let source = link_source(dir.path());    let mut kinds = Vec::new();    let outcome = source        .read(None, &mut |batch: IngestBatch| {            kinds.push(matches!(batch.work, IngestWork::Messages { .. }));            Ok(())        })        .expect("the read finishes without asking the helper for a picture");    assert_eq!(kinds, vec![true], "the message, and not one status");    assert_eq!(outcome.notes.get("status:passedOver"), Some(&2));    assert_eq!(state.lock().unwrap().acks, vec![3], "the statuses are passed over, not left waiting");}/// Profile pictures: hidden ones answer `false`, the rest write a byte.struct Pictures {    hidden: BTreeSet<String>,    asked: Vec<String>,}impl MediaFetch for Pictures {    fn fetch(&mut self, _account: &str, _pointer: &Value, _dest: &Path) -> Result<bool, String> {        panic!("no message picture in this page")    }    fn picture(&mut self, _account: &str, chat: &str, dest: &Path) -> Result<bool, String> {        self.asked.push(chat.to_string());        if self.hidden.contains(chat) {            return Ok(false);        }        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();        std::fs::write(dest, b"jpeg").unwrap();        Ok(true)    }}/// RULE: A WhatsApp profile picture is downloaded only for a chat the file wants (its person or group would take it), once per chat per page (the newest event), and a picture its owner hides leaves the holder as it is — counted, never an error.#[test]fn a_picture_is_fetched_only_when_wanted_and_a_hidden_one_is_counted() {    let dir = tempfile::tempdir().unwrap();    let stranger = "15550002222@s.whatsapp.net";    let hidden = "15550003333@s.whatsapp.net";    let page = events(vec![        json!({ "seq": 1, "event": "picture", "account": ACCOUNT, "chat": FRIEND, "target": "100" }),        json!({ "seq": 2, "event": "picture", "account": ACCOUNT, "chat": FRIEND, "target": "101" }),        json!({ "seq": 3, "event": "picture", "account": ACCOUNT, "chat": GROUP, "is_group": true, "target": "7" }),        json!({ "seq": 4, "event": "picture", "account": ACCOUNT, "chat": stranger, "target": "9" }),        json!({ "seq": 5, "event": "picture", "account": ACCOUNT, "chat": hidden, "target": "5" }),    ]);    let wanted: BTreeSet<String> = [FRIEND, GROUP, hidden].into_iter().map(str::to_string).collect();    let mut media = Pictures { hidden: [hidden.to_string()].into_iter().collect(), asked: Vec::new() };    let mut notes = IngestNotes::new();    let pictures = pictures_from_events(&page, &wanted, dir.path(), &mut media, &mut notes).unwrap();    let mut asked = media.asked.clone();    asked.sort();    let mut expected = vec![GROUP.to_string(), FRIEND.to_string(), hidden.to_string()];    expected.sort();    assert_eq!(asked, expected, "the stranger is never asked about, the friend once");    assert_eq!(pictures.len(), 2);    let friend = pictures.iter().find(|p| p.jid == FRIEND).unwrap();    assert!(!friend.is_group && friend.file.path.to_string_lossy().ends_with("-101.jpg"), "{friend:?}");    assert!(pictures.iter().any(|p| p.jid == GROUP && p.is_group));    assert_eq!(notes.get("picture:notWanted"), Some(&1));    assert_eq!(notes.get("picture:hidden"), Some(&1));    // The messages reader passes a picture event over without a word.    let mut none = FakeMedia { gone: false, fetched: Vec::new() };    let (batches, notes) = batch(vec![json!({ "seq": 1, "event": "picture", "account": ACCOUNT, "chat": FRIEND, "target": "100" })], &mut none, dir.path());    assert!(batches.is_empty());    assert_eq!(notes.get("read:picture"), None);}/// RULE: The reader tells the helper which chats' pictures it may ask about only when the helper's own list (its hello digest) differs, so a serving Mac draining every few seconds never resends an unchanged list; a helper with no list support is told nothing.#[test]fn the_helper_is_told_the_wanted_chats_only_when_its_list_differs() {    let dir = tempfile::tempdir().unwrap();    let state = Arc::new(Mutex::new(FakeHelper { pictures: Some(BTreeSet::new()), ..FakeHelper::default() }));    spawn_fake(dir.path(), Arc::clone(&state));    let source = link_source(dir.path());    *source.pictures_wanted.lock().unwrap() = [FRIEND.to_string(), GROUP.to_string()].into_iter().collect();    for _ in 0..3 {        source.read(None, &mut |_| Ok(())).unwrap();    }    {        let helper = state.lock().unwrap();        assert_eq!(helper.told, 1, "told once, then the digests agree");        assert_eq!(helper.pictures.as_ref().unwrap().len(), 2);    }    *source.pictures_wanted.lock().unwrap() = [GROUP.to_string()].into_iter().collect();    source.read(None, &mut |_| Ok(())).unwrap();    assert_eq!(state.lock().unwrap().told, 2);    let old_dir = tempfile::tempdir().unwrap();    let old = Arc::new(Mutex::new(FakeHelper::default()));    spawn_fake(old_dir.path(), Arc::clone(&old));    let source = link_source(old_dir.path());    *source.pictures_wanted.lock().unwrap() = [FRIEND.to_string()].into_iter().collect();    source.read(None, &mut |_| Ok(())).unwrap();    assert_eq!(old.lock().unwrap().told, 0);}/// RULE: The reader's wanted-list digest is the helper's (pictures.go picturesDigest): the same vector pinned on both sides.#[test]fn the_pictures_digest_is_the_helpers() {    let chats: BTreeSet<String> = [FRIEND, GROUP].into_iter().map(str::to_string).collect();    assert_eq!(pictures_digest(&chats), "f0a1d2427c30841c3f109eefc292730f6b73c00fbf79f415b247bf31af936e50");}// RULE (owner, FEEDBACK-3, 23 Nov 2026): a WhatsApp poll lands with its question, options and counts in// `meta.poll`, and votes are votes (each a voter's whole choice), never messages; a vote whose voter has no number// is counted and left out.#[test]fn a_poll_lands_with_its_options_and_votes_are_votes() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia { gone: false, fetched: vec![] };    let events = vec![        message(1, "P1", GROUP, json!({ "kind": "poll", "text": "Which day?", "sender": FRIEND, "poll": { "options": ["Thursday", "Friday"], "selectable": 1 } })),        json!({ "seq": 2, "event": "poll_vote", "account": ACCOUNT, "chat": GROUP, "target": "P1", "votes": ["ab12"],                "message": { "id": "V1", "chat": GROUP, "sender": FRIEND, "ts": 1_790_000_000, "kind": "poll_vote", "origin": "live" } }),        json!({ "seq": 3, "event": "poll_vote", "account": ACCOUNT, "chat": GROUP, "target": "P1", "votes": [],                "message": { "id": "V2", "chat": GROUP, "from_me": true, "ts": 1_790_000_001, "kind": "poll_vote", "origin": "live" } }),        json!({ "seq": 4, "event": "poll_vote", "account": ACCOUNT, "chat": GROUP, "target": "P1", "votes": ["cd34"],                "message": { "id": "V3", "chat": GROUP, "sender": "123@lid", "ts": 1_790_000_002, "kind": "poll_vote", "origin": "live" } }),    ];    let (out, _) = batch(events.clone(), &mut media, dir.path());    assert_eq!(out.len(), 1);    let messages = &out[0].0.messages;    assert_eq!(messages.len(), 1, "votes are not messages");    let poll = &messages[0].meta.as_ref().unwrap()["poll"];    assert_eq!(poll["question"], "Which day?");    assert_eq!(poll["options"], json!([{ "text": "Thursday", "votes": 0 }, { "text": "Friday", "votes": 0 }]));    assert_eq!(poll["selectable"], 1);    let wire: Vec<WireEvent> = events.into_iter().map(|event| serde_json::from_value(event).unwrap()).collect();    let mut notes = IngestNotes::new();    let votes = votes_from_events(&wire, &mut notes);    assert_eq!(votes.len(), 2);    assert_eq!((votes[0].external_id.as_str(), votes[0].actor.as_str(), votes[0].options.clone()), ("P1", "15550001111", vec!["ab12".to_string()]));    assert_eq!((votes[1].actor.as_str(), votes[1].options.len()), ("owner", 0));    assert_eq!(notes.get("vote:withoutPhone"), Some(&1));}// RULE (CONTRACT "Pictures, voice notes and video"): a file the owner sent from Cotton comes back as his message// with the file already in his Cotton (the landed media), so it is neither fetched from WhatsApp nor stored again.#[test]fn a_file_sent_from_cotton_lands_as_his_own_copy_unfetched() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia { gone: false, fetched: vec![] };    let events = vec![message(1, "3EB0SENT", FRIEND, json!({ "kind": "image", "text": "the view", "from_me": true,        "media": { "type": "image", "direct_path": "/v/x" },        "landed": [{ "key": "db/messages/t1/abc.jpg", "contentType": "image/jpeg", "sizeBytes": 2048, "width": 1200, "height": 900 }] }))];    let (out, _) = batch(events, &mut media, dir.path());    assert!(media.fetched.is_empty(), "nothing is fetched from WhatsApp");    let m = &out[0].0.messages[0];    assert_eq!(m.body, "the view");    let landed = m.media.as_ref().unwrap();    assert_eq!((landed[0].key.as_str(), landed[0].content_type.as_str(), landed[0].width), ("db/messages/t1/abc.jpg", "image/jpeg", Some(1200.0)));    assert!(out[0].1.is_empty(), "no file is stored again");}// RULE (chat CONTRACT, WhatsApp calls; owner, 24 Nov 2026): a call the link reports lands as a message whose// `meta.call` holds its facts in CallFacts' shape and whose body says it, so the chat's last line is the call.#[test]fn a_whatsapp_call_lands_as_its_line_with_its_facts() {    let dir = tempfile::tempdir().unwrap();    let mut media = FakeMedia { gone: false, fetched: vec![] };    let call = json!({ "room": "call:C1", "direction": "in", "video": false, "outcome": "missed", "reason": "missed", "durationS": 0, "missed": true, "group": false });    let answered = json!({ "room": "call:C2", "direction": "out", "video": true, "outcome": "answered", "reason": "answered", "durationS": 192, "missed": false, "group": false });    let (out, notes) = batch(        vec![            message(1, "call:C1", FRIEND, json!({ "sender": FRIEND, "kind": "call", "text": "", "call": call })),            message(2, "call:C2", FRIEND, json!({ "from_me": true, "kind": "call", "text": "", "call": answered })),            message(3, "bad", FRIEND, json!({ "kind": "call", "text": "", "call": { "room": 7 } })),        ],        &mut media,        dir.path(),    );    let messages: Vec<&EnvelopeMessage> = out.iter().flat_map(|(b, _)| b.messages.iter()).collect();    assert_eq!(messages.len(), 2, "a call with no facts is not a call: {notes:?}");    assert_eq!(messages[0].external_id, "call:C1");    assert_eq!(messages[0].body, "Missed voice call");    assert_eq!(messages[0].meta.as_ref().unwrap()["call"], call, "the facts as the core reads them");    assert_eq!(messages[1].body, "Video call · 3:12");    assert_eq!(messages[1].direction, Direction::Out);    assert_eq!(notes.get("empty:call"), Some(&1));}