Cotton code
552 lines · 17.8 KB · RustRaw
//! The call-history reader's decisions, pinned on a synthetic `ZCALLRECORD`.//!//! The provider table and the outcome table are the two things worth pinning://! both are read off columns whose meaning is written down nowhere but here,//! and both decide what a person sees on a call row.//!//! **Every fixture is built in this file**, row by row, from made-up values in//! reserved-for-fiction ranges. Nothing here was ever copied off a real Mac//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).//!//! The path is this reader's only seam, so the failures that seam can produce//! are covered here too: a cursor that will not parse, and a store this Mac//! cannot open.use std::path::{Path, PathBuf};use super::*;use crate::ingest::{IngestNotes, IngestSource, IngestWork, SourceState};use crate::test_support::temp_layout;/// Core Data's own table, with the columns the reader selects.const DDL: &str = "CREATE TABLE ZCALLRECORD (  Z_PK INTEGER PRIMARY KEY AUTOINCREMENT,  ZUNIQUE_ID TEXT,  ZDATE REAL,  ZDURATION REAL,  ZADDRESS BLOB,  ZORIGINATED INTEGER,  ZANSWERED INTEGER,  ZCALLTYPE INTEGER,  ZSERVICE_PROVIDER TEXT,  ZDISCONNECTED_CAUSE INTEGER,  ZORIGINATINGDEVICENAME TEXT,  ZISO_COUNTRY_CODE TEXT,  ZNAME TEXT)";/// One synthetic call, in the vocabulary the fixture writer takes.struct FixtureCall {    unique_id: &'static str,    /// Apple-epoch SECONDS, which is what this store holds.    at: f64,    duration_s: f64,    address: Option<&'static str>,    originated: i64,    answered: i64,    call_type: i64,    provider: &'static str,    cause: Option<i64>,}impl Default for FixtureCall {    fn default() -> Self {        FixtureCall {            unique_id: "CALL-0",            at: apple_seconds("2026-08-01T10:00:00Z"),            duration_s: 0.0,            address: None,            originated: 0,            answered: 0,            call_type: CALL_TYPE_PHONE,            provider: "com.apple.Telephony",            cause: None,        }    }}/// An instant as this store spells it: seconds since Apple's epoch.fn apple_seconds(at: &str) -> f64 {    let parsed = chrono::DateTime::parse_from_rfc3339(at).expect("a literal instant");    (parsed.timestamp_millis() - APPLE_EPOCH_MS) as f64 / 1000.0}fn write_call_fixture(path: &Path, calls: &[FixtureCall]) {    let db = crate::test_support::open_fixture_db(path);    db.execute_batch(DDL).expect("the table");    for call in calls {        db.execute(            "INSERT INTO ZCALLRECORD (ZUNIQUE_ID, ZDATE, ZDURATION, ZADDRESS, ZORIGINATED,                                      ZANSWERED, ZCALLTYPE, ZSERVICE_PROVIDER,                                      ZDISCONNECTED_CAUSE, ZORIGINATINGDEVICENAME,                                      ZISO_COUNTRY_CODE)             VALUES (?,?,?,?,?,?,?,?,?,?,?)",            rusqlite::params![                call.unique_id,                call.at,                call.duration_s,                call.address,                call.originated,                call.answered,                call.call_type,                call.provider,                call.cause,                "iPhone",                "in",            ],        )        .expect("a row");    }}fn a_source(layout: &crate::Layout, path: &Path) -> CallHistorySource {    CallHistorySource::new(layout.clone(), Path::new("/nowhere"), "Mac (test)").at_path(path)}struct ReadAll {    calls: Vec<DeviceCall>,    cursor: String,    notes: IngestNotes,    /// The cursor each batch carried, in order.    batch_cursors: Vec<Option<String>>,}fn read_all(layout: &crate::Layout, path: &Path, cursor: Option<&str>) -> ReadAll {    let source = a_source(layout, path);    let mut calls: Vec<DeviceCall> = Vec::new();    let mut batch_cursors: Vec<Option<String>> = Vec::new();    let outcome = {        let mut emit = |batch: crate::ingest::IngestBatch| {            batch_cursors.push(batch.cursor.clone());            if let IngestWork::Calls { calls: page } = batch.work {                calls.extend(page);            }            Ok(())        };        source.read(cursor, &mut emit).expect("a read")    };    ReadAll {        calls,        cursor: outcome.cursor,        notes: outcome.notes,        batch_cursors,    }}fn fixture_at(dir: &Path) -> PathBuf {    dir.join("CallHistory.storedata")}// ---------------------------------------------------------------- providerFor#[test]fn it_names_apples_two_bundles_and_keeps_every_other_one_verbatim() {    assert_eq!(        provider_for(Some("com.apple.Telephony"), Some(1)),        "cellular"    );    assert_eq!(        provider_for(Some("com.apple.FaceTime"), Some(16)),        "facetime_audio"    );    assert_eq!(        provider_for(Some("com.apple.FaceTime"), Some(8)),        "facetime_video"    );    assert_eq!(        provider_for(Some("net.whatsapp.WhatsApp"), Some(1)),        "whatsapp"    );    assert_eq!(        provider_for(Some("com.example.Dialler"), Some(1)),        "com.example.Dialler"    );    assert_eq!(provider_for(None, Some(1)), "unknown");}// ----------------------------------------------------------------- outcomeFor#[test]fn it_reads_an_outgoing_call_by_its_duration_and_an_incoming_one_by_whether_it_was_answered() {    assert_eq!(outcome_for(Some(1), Some(0), 42), "answered");    assert_eq!(outcome_for(Some(1), Some(0), 0), "cancelled");    assert_eq!(outcome_for(Some(0), Some(1), 30), "answered");    assert_eq!(outcome_for(Some(0), Some(0), 0), "missed");}#[test]fn it_calls_an_unanswered_incoming_call_missed_never_declined_the_file_cannot_tell() {    assert_eq!(outcome_for(Some(0), Some(0), 0), "missed");}// --------------------------------------------------------------- callDateToIso#[test]fn it_reads_apple_epoch_seconds_unlike_messages_nanoseconds() {    assert_eq!(call_date_to_iso(Some(0.0)), None);    assert_eq!(        call_date_to_iso(Some(788_918_400.0)).as_deref(),        Some("2026-01-01T00:00:00.000Z")    );}#[test]fn a_date_that_is_no_instant_at_all_is_no_date_rather_than_a_panic() {    assert_eq!(call_date_to_iso(None), None);    assert_eq!(call_date_to_iso(Some(-1.0)), None);    assert_eq!(call_date_to_iso(Some(f64::NAN)), None);    assert_eq!(call_date_to_iso(Some(f64::INFINITY)), None);    assert_eq!(call_date_to_iso(Some(1.0e18)), None);}// ----------------------------------------------------------------- readAddress#[test]fn it_takes_the_string_this_macos_writes_and_the_blob_some_others_do() {    assert_eq!(        read_address(&rusqlite::types::Value::Text("+919000000001".to_string())).as_deref(),        Some("+919000000001")    );    assert_eq!(        read_address(&rusqlite::types::Value::Blob(b"+919000000002".to_vec())).as_deref(),        Some("+919000000002")    );    assert_eq!(read_address(&rusqlite::types::Value::Null), None);    // A column holding nothing but spaces is a column holding nothing.    assert_eq!(        read_address(&rusqlite::types::Value::Text("   ".to_string())),        None    );}// --------------------------------------------------------- the reader itself#[test]fn it_reads_a_cellular_call_with_its_handle_normalised_and_its_provenance_in_meta() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-1",            at: apple_seconds("2026-08-01T10:00:00Z"),            duration_s: 125.0,            address: Some("+91 90000 00001"),            originated: 1,            cause: Some(6),            ..FixtureCall::default()        }],    );    let read = read_all(&layout, &path, None);    assert_eq!(read.calls.len(), 1);    let call = &read.calls[0];    assert_eq!(call.source, "ios_call_history");    assert_eq!(call.external_id, "CALL-1");    assert_eq!(call.provider, "cellular");    assert_eq!(call.direction, "out");    assert_eq!(call.outcome, "answered");    assert_eq!(call.started_at, "2026-08-01T10:00:00.000Z");    assert_eq!(call.duration_s, 125);    assert_eq!(call.handle.as_deref(), Some("919000000001"));    assert_eq!(call.handle_kind, "phone");    assert_eq!(call.device.as_deref(), Some("Mac (test)"));    assert_eq!(call.meta["disconnectedCause"], 6);    assert_eq!(call.meta["callType"], 1);    assert_eq!(call.meta["serviceProvider"], "com.apple.Telephony");    assert_eq!(call.meta["originatingDevice"], "iPhone");    assert_eq!(call.meta["isoCountryCode"], "in");}#[test]fn it_reads_a_facetime_call_to_an_apple_id_as_an_email_handle() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-FT",            at: apple_seconds("2026-08-02T10:00:00Z"),            duration_s: 600.0,            address: Some("Someone@Example.com"),            originated: 0,            answered: 1,            call_type: CALL_TYPE_FACETIME_VIDEO,            provider: "com.apple.FaceTime",            ..FixtureCall::default()        }],    );    let read = read_all(&layout, &path, None);    let call = &read.calls[0];    assert_eq!(call.provider, "facetime_video");    assert_eq!(call.direction, "in");    assert_eq!(call.outcome, "answered");    assert_eq!(call.handle.as_deref(), Some("someone@example.com"));    assert_eq!(call.handle_kind, "email");}#[test]fn it_keeps_a_handle_it_cannot_normalise_verbatim_rather_than_losing_it() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-SHORT",            at: apple_seconds("2026-08-03T10:00:00Z"),            address: Some("121"),            originated: 1,            ..FixtureCall::default()        }],    );    let read = read_all(&layout, &path, None);    assert_eq!(read.calls[0].handle.as_deref(), Some("121"));    assert_eq!(read.calls[0].handle_kind, "phone");}#[test]fn it_skips_a_row_with_no_unique_id_and_counts_it_an_id_is_what_makes_a_re_read_free() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    let db = crate::test_support::open_fixture_db(&path);    db.execute_batch(DDL).expect("the table");    db.execute(        "INSERT INTO ZCALLRECORD (ZUNIQUE_ID, ZDATE) VALUES (NULL, 788918400)",        [],    )    .expect("a row");    drop(db);    let read = read_all(&layout, &path, None);    assert!(read.calls.is_empty());    assert_eq!(read.notes.get("noExternalId"), Some(&1));}#[test]fn it_skips_a_row_whose_date_the_store_never_wrote_and_counts_that_too() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    let db = crate::test_support::open_fixture_db(&path);    db.execute_batch(DDL).expect("the table");    db.execute(        "INSERT INTO ZCALLRECORD (ZUNIQUE_ID, ZDATE) VALUES ('CALL-NO-DATE', NULL)",        [],    )    .expect("a row");    drop(db);    let read = read_all(&layout, &path, None);    assert!(read.calls.is_empty());    assert_eq!(read.notes.get("noDate"), Some(&1));}#[test]fn it_resumes_from_its_z_pk_cursor() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[            FixtureCall {                unique_id: "CALL-A",                at: apple_seconds("2026-08-04T10:00:00Z"),                originated: 1,                duration_s: 5.0,                ..FixtureCall::default()            },            FixtureCall {                unique_id: "CALL-B",                at: apple_seconds("2026-08-04T11:00:00Z"),                originated: 1,                duration_s: 5.0,                ..FixtureCall::default()            },        ],    );    let first = read_all(&layout, &path, None);    let ids: Vec<&str> = first        .calls        .iter()        .map(|call| call.external_id.as_str())        .collect();    assert_eq!(ids, ["CALL-A", "CALL-B"]);    assert_eq!(first.cursor, "2");    let second = read_all(&layout, &path, Some(&first.cursor));    assert!(second.calls.is_empty());    let partial = read_all(&layout, &path, Some("1"));    let ids: Vec<&str> = partial        .calls        .iter()        .map(|call| call.external_id.as_str())        .collect();    assert_eq!(ids, ["CALL-B"]);}#[test]fn it_carries_a_cursor_on_every_batch_so_an_interrupted_run_resumes_where_it_stopped() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-C",            at: apple_seconds("2026-08-05T10:00:00Z"),            originated: 1,            duration_s: 5.0,            ..FixtureCall::default()        }],    );    let read = read_all(&layout, &path, None);    assert_eq!(read.batch_cursors, vec![Some("1".to_string())]);}#[test]fn it_treats_a_cursor_it_cannot_parse_as_no_cursor_at_all() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-P",            at: apple_seconds("2026-08-05T10:00:00Z"),            ..FixtureCall::default()        }],    );    // Re-reading is free — every row carries its own id — and guessing a    // position is not.    for cursor in ["", "  ", "not-a-number", "-4"] {        let read = read_all(&layout, &path, Some(cursor));        assert_eq!(read.calls.len(), 1, "{cursor}");    }}#[test]fn it_probes_not_found_when_this_mac_has_no_call_history() {    let (dir, layout) = temp_layout();    let source = a_source(&layout, &dir.path().join("missing.storedata"));    let status = source.probe();    assert_eq!(status.state, SourceState::NotFound);    assert!(status        .detail        .expect("a sentence")        .contains("Calls from iPhone"));}#[test]fn it_probes_ready_with_a_count() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[            FixtureCall {                unique_id: "CALL-D",                at: apple_seconds("2026-08-06T10:00:00Z"),                ..FixtureCall::default()            },            FixtureCall {                unique_id: "CALL-E",                at: apple_seconds("2026-08-06T11:00:00Z"),                ..FixtureCall::default()            },        ],    );    let status = a_source(&layout, &path).probe();    assert_eq!(status.state, SourceState::Ready);    assert_eq!(status.total, Some(2));    assert_eq!(status.detail, None);}#[test]fn a_file_that_is_not_a_call_store_is_an_error_the_panel_can_show() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    // A SQLite file with no `ZCALLRECORD` — what a store from a macOS this    // reader has never seen would look like.    let db = crate::test_support::open_fixture_db(&path);    db.execute_batch("CREATE TABLE ZSOMETHINGELSE (Z_PK INTEGER)")        .expect("a table");    drop(db);    let status = a_source(&layout, &path).probe();    assert_eq!(status.state, SourceState::Error);    assert!(status.detail.expect("a sentence").contains("ZCALLRECORD"));    // And the read says so rather than answering an empty run.    let source = a_source(&layout, &path);    let mut emit = |_batch: crate::ingest::IngestBatch| Ok(());    assert!(source.read(None, &mut emit).is_err());}#[test]fn it_reads_the_copy_and_never_the_store_the_daemon_holds() {    let (dir, layout) = temp_layout();    let path = fixture_at(dir.path());    write_call_fixture(        &path,        &[FixtureCall {            unique_id: "CALL-COPY",            at: apple_seconds("2026-08-07T10:00:00Z"),            ..FixtureCall::default()        }],    );    read_all(&layout, &path, None);    assert!(        layout.snapshots_dir().join("call-history.db").exists(),        "the pass read its own copy"    );}#[test]fn it_watches_the_store_it_reads_so_a_call_lands_when_it_ends() {    let (dir, layout) = temp_layout();    let store = fixture_at(dir.path());    let source = a_source(&layout, &store);    let triggers = source.triggers();    assert_eq!(triggers.watch, vec![source.path().to_path_buf()]);    assert_eq!(source.id(), SourceId::CallHistory);}#[test]fn a_running_app_reads_the_store_macos_actually_keeps() {    let path = call_history_path(Path::new("/Users/someone"));    assert!(path.ends_with("Library/Application Support/CallHistoryDB/CallHistory.storedata"));}/// Writes an invented call history under `$WALK_HOME` (Library/Application Support/CallHistoryDB), for a Mac app/// flavour walked by hand with `CottonHome` pointing there. Numbers are +1555, nothing is real.#[test]#[ignore = "writes a walk home: WALK_HOME=<dir> cargo test -p cotton-client --lib write_walk_call_history -- --ignored"]fn write_walk_call_history() {    let home = PathBuf::from(std::env::var("WALK_HOME").expect("WALK_HOME"));    let dir = home.join("Library/Application Support/CallHistoryDB");    std::fs::create_dir_all(&dir).unwrap();    const IDS: [&str; 12] = ["W-1", "W-2", "W-3", "W-4", "W-5", "W-6", "W-7", "W-8", "W-9", "W-10", "W-11", "W-12"];    const NUMBERS: [&str; 4] = ["+15550100001", "+15550100002", "+15550100003", "+15550100004"];    let calls: Vec<FixtureCall> = IDS        .iter()        .enumerate()        .map(|(i, id)| FixtureCall {            unique_id: id,            at: apple_seconds("2026-11-20T09:00:00Z") + (i as f64) * 3600.0,            duration_s: if i % 3 == 0 { 0.0 } else { 60.0 + i as f64 * 7.0 },            address: Some(NUMBERS[i % NUMBERS.len()]),            originated: (i % 2) as i64,            answered: i64::from(i % 3 != 0),            ..FixtureCall::default()        })        .collect();    let path = fixture_at(&dir);    let _ = std::fs::remove_file(&path);    write_call_fixture(&path, &calls);    println!("wrote {} invented calls to {}", calls.len(), path.display());}