//! The iPhone's call log, as iCloud syncs it to this Mac. //! //! `~/Library/Application Support/CallHistoryDB/CallHistory.storedata` is a //! Core Data store — an ordinary SQLite file with Core Data's naming — whose //! `ZCALLRECORD` table is one row per call, cellular and FaceTime alike. It is //! NOT in an unencrypted iPhone backup (there is no call-history file in its //! manifest), so this is a Mac-only source and always will be until the phone //! itself can read its own log. //! //! Every row goes to the call-log applier, which derives the row id from //! (source, external id) — so a crashed pass that starts again re-writes the //! rows it already wrote and adds none. use std::path::{Path, PathBuf}; use rusqlite::Connection; use crate::ingest::apple_schema::{ read_handle, HandleKind, APPLE_EPOCH_MS, DEFAULT_COUNTRY_CODE, }; use crate::ingest::snapshot::open_live_copy; use crate::ingest::{ count, DeviceCall, Emit, IngestBatch, IngestNotes, IngestSource, IngestWork, ReadOutcome, SourceId, SourceStatus, Triggers, }; use crate::Layout; /// Where macOS keeps it. pub fn call_history_path(home: &Path) -> PathBuf { home.join("Library") .join("Application Support") .join("CallHistoryDB") .join("CallHistory.storedata") } /// The snapshot this reader copies into before it reads. const SNAPSHOT_NAME: &str = "call-history.db"; /// `ZCALLTYPE`, as Apple writes it. pub const CALL_TYPE_PHONE: i64 = 1; pub const CALL_TYPE_FACETIME_VIDEO: i64 = 8; pub const CALL_TYPE_FACETIME_AUDIO: i64 = 16; const TELEPHONY_BUNDLE: &str = "com.apple.Telephony"; const FACETIME_BUNDLE: &str = "com.apple.FaceTime"; /// The source name every row of this reader carries. pub const CALL_SOURCE: &str = "ios_call_history"; /// What carried the call. /// /// The two Apple bundles become CottonDB's own words because they are what the /// app draws an icon for; anything else keeps its BUNDLE ID verbatim rather /// than being folded into an "other" that tells nobody anything. WhatsApp logs /// its calls through CallKit and arrives as `net.whatsapp.WhatsApp`, which is /// where the `whatsapp` provider comes from. pub fn provider_for(service_provider: Option<&str>, call_type: Option) -> String { let bundle = service_provider.map(str::trim).unwrap_or(""); if bundle == TELEPHONY_BUNDLE { return "cellular".to_string(); } if bundle == FACETIME_BUNDLE { return match call_type { Some(CALL_TYPE_FACETIME_AUDIO) => "facetime_audio".to_string(), Some(CALL_TYPE_FACETIME_VIDEO) => "facetime_video".to_string(), // Audio is the default because a FaceTime row whose type this // reader does not recognise is far more often a call than a video // one, and "audio" is the claim that loses least when it is wrong. _ => "facetime_audio".to_string(), }; } if bundle.to_ascii_lowercase().contains("whatsapp") { return "whatsapp".to_string(); } if bundle.is_empty() { "unknown".to_string() } else { bundle.to_string() } } /// How the call ended. /// /// A DECLINED call is indistinguishable from a missed one in this store — there /// is no column that separates them — so it is not invented: an inbound call /// that was not answered is `missed`, and that is all the file actually knows. /// `failed` exists in the schema for a source that CAN say so, and this reader /// never writes it. pub fn outcome_for( originated: Option, answered: Option, duration_seconds: i64, ) -> String { if originated == Some(1) { return if duration_seconds > 0 { "answered".to_string() } else { "cancelled".to_string() }; } if answered == Some(1) { "answered".to_string() } else { "missed".to_string() } } /// `ZDATE` is Apple-epoch SECONDS here, unlike Messages' nanoseconds. pub fn call_date_to_iso(raw: Option) -> Option { let value = raw?; if !value.is_finite() || value <= 0.0 { return None; } let ms = (value * 1000.0).round(); // Outside this range there is no instant to name, and a stamp that wrapped // would file a call in a year nobody lived through. if !ms.is_finite() || ms.abs() > 9.0e15 { return None; } let at = chrono::DateTime::from_timestamp_millis(APPLE_EPOCH_MS + ms as i64)?; Some(crate::seams::iso(at)) } /// `ZADDRESS` is a string on this macOS and a blob on some others. pub fn read_address(raw: &rusqlite::types::Value) -> Option { let text = match raw { rusqlite::types::Value::Text(value) => value.trim().to_string(), // Lossy on purpose: a byte the phone wrote that is not UTF-8 must not // throw away the one fact the row had about who called. rusqlite::types::Value::Blob(bytes) => String::from_utf8_lossy(bytes).trim().to_string(), _ => return None, }; if text.is_empty() { None } else { Some(text) } } /// One row of `ZCALLRECORD`, in the columns this reader selects. #[derive(Debug, Clone)] pub struct CallRow { pub z_pk: i64, pub unique_id: Option, pub date: Option, pub duration: Option, pub address: rusqlite::types::Value, pub originated: Option, pub answered: Option, pub call_type: Option, pub service_provider: Option, pub disconnected_cause: Option, pub originating_device: Option, pub iso_country_code: Option, pub name: Option, } pub const CALL_PAGE_SQL: &str = " SELECT Z_PK, ZUNIQUE_ID, ZDATE, ZDURATION, ZADDRESS, ZORIGINATED, ZANSWERED, ZCALLTYPE, ZSERVICE_PROVIDER, ZDISCONNECTED_CAUSE, ZORIGINATINGDEVICENAME, ZISO_COUNTRY_CODE, ZNAME FROM ZCALLRECORD WHERE Z_PK > ? ORDER BY Z_PK LIMIT ?"; /// What one row became: a call to write, or a counted reason it was not. #[derive(Debug, Clone, PartialEq)] pub enum RowRead { Call(Box), Skip(&'static str), } /// One row, in the call-log applier's vocabulary — or a counted reason. pub fn call_from_row(row: &CallRow, device: &str, country_code: &str) -> RowRead { let external_id = row.unique_id.as_deref().map(str::trim).unwrap_or(""); if external_id.is_empty() { return RowRead::Skip("noExternalId"); } let Some(started_at) = call_date_to_iso(row.date) else { return RowRead::Skip("noDate"); }; let duration_s = row .duration .filter(|value| value.is_finite()) .map(|value| value.round() as i64) .unwrap_or(0) .max(0); let address = read_address(&row.address); let handle = address .as_deref() .and_then(|value| read_handle(Some(value), country_code)); let mut meta = serde_json::Map::new(); // RAW, not interpreted: the disconnect cause is a number whose meaning // changes between iOS versions, and a guess written into somebody's record // is worse than the number itself. meta.insert( "disconnectedCause".to_string(), json_or_null(row.disconnected_cause), ); meta.insert("callType".to_string(), json_or_null(row.call_type)); meta.insert( "serviceProvider".to_string(), text_or_null(row.service_provider.as_deref()), ); meta.insert( "originatingDevice".to_string(), text_or_null(row.originating_device.as_deref()), ); meta.insert( "isoCountryCode".to_string(), text_or_null(row.iso_country_code.as_deref()), ); RowRead::Call(Box::new(DeviceCall { source: CALL_SOURCE.to_string(), external_id: external_id.to_string(), provider: provider_for(row.service_provider.as_deref(), row.call_type), direction: if row.originated == Some(1) { "out".to_string() } else { "in".to_string() }, outcome: outcome_for(row.originated, row.answered, duration_s), started_at, duration_s, // A shortcode or a blocked-number placeholder is still what the phone // dialled: the applier stores a handle it cannot normalise verbatim // rather than losing the one fact the row had about who called. handle: handle.as_ref().map(|value| value.value.clone()).or(address), handle_kind: match handle.as_ref().map(|value| &value.kind) { Some(HandleKind::Email) => "email".to_string(), _ => "phone".to_string(), }, name: row.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).map(str::to_string), device: Some(device.to_string()), meta, })) } fn json_or_null(value: Option) -> serde_json::Value { value .map(serde_json::Value::from) .unwrap_or(serde_json::Value::Null) } fn text_or_null(value: Option<&str>) -> serde_json::Value { value .map(serde_json::Value::from) .unwrap_or(serde_json::Value::Null) } /// How many calls go in one batch — one write, one transaction. pub const CALLS_PER_BATCH: i64 = 500; /// The floor under the watch. A call is a record seconds after it ends because /// the store's folder is watched like the Messages one; iCloud's bursts of /// rewrites collapse into one run behind the scheduler's settle, and every /// read is of a copy taken with its `-wal`, so a half-written page is never /// read. The poll only covers a watch macOS dropped. pub const CALL_HISTORY_POLL_MS: u64 = 300_000; /// The sentence a person can act on when this Mac holds no call history. /// /// It is a `not_found`, not a failure: a Mac that has never been told to show /// calls from the phone is an ordinary Mac, and the only thing to say is what /// to switch on. pub const NO_CALL_HISTORY: &str = "This Mac has no call history. Turn on Calls from iPhone in \ FaceTime, and give iCloud a few minutes."; /// The reader. /// /// A plain struct holding the paths it reads — no globals, no process-wide /// state — so a test builds one over a synthetic store in a temp folder and the /// packaged app builds one over the real one. #[derive(Debug, Clone)] pub struct CallHistorySource { layout: Layout, /// The label the ingesting machine goes into every row under. device: String, country_code: String, source_path: PathBuf, } impl CallHistorySource { /// The reader a running app builds: the store where macOS keeps it. /// /// The workspace id the TypeScript carried is NOT here. The reader never /// used it — the queue takes the workspace from the replica it writes into /// — and a field nothing reads is a field that drifts. pub fn new(layout: Layout, home: &Path, device: impl Into) -> CallHistorySource { let source_path = call_history_path(home); CallHistorySource { layout, device: device.into(), country_code: DEFAULT_COUNTRY_CODE.to_string(), source_path, } } /// Read this file instead of the one on this Mac. pub fn at_path(mut self, path: impl Into) -> CallHistorySource { self.source_path = path.into(); self } /// The country a bare national number is promoted into. Stated, never /// guessed: a wrong guess files somebody's calls under a stranger. pub fn with_country_code(mut self, country_code: impl Into) -> CallHistorySource { self.country_code = country_code.into(); self } pub fn path(&self) -> &Path { &self.source_path } /// Copy the live store and open the copy — the daemon holds its own open. fn open(&self) -> Result { open_live_copy(&self.layout, &self.source_path, SNAPSHOT_NAME) } fn page(&self, db: &Connection, from: i64) -> Result, String> { let mut statement = db .prepare(CALL_PAGE_SQL) .map_err(|error| error.to_string())?; let rows = statement .query_map((from, CALLS_PER_BATCH), |row| { Ok(CallRow { z_pk: row.get(0)?, unique_id: row.get(1)?, date: row.get(2)?, duration: row.get(3)?, address: row.get(4)?, originated: row.get(5)?, answered: row.get(6)?, call_type: row.get(7)?, service_provider: row.get(8)?, disconnected_cause: row.get(9)?, originating_device: row.get(10)?, iso_country_code: row.get(11)?, name: row.get(12)?, }) }) .map_err(|error| error.to_string())?; rows.collect::>>() .map_err(|error| error.to_string()) } } impl IngestSource for CallHistorySource { fn id(&self) -> SourceId { SourceId::CallHistory } fn probe(&self) -> SourceStatus { if !self.source_path.exists() { return SourceStatus::not_found(NO_CALL_HISTORY); } let db = match self.open() { Ok(db) => db, Err(status) => return status, }; match db.query_row("SELECT COUNT(*) FROM ZCALLRECORD", [], |row| { row.get::<_, i64>(0) }) { Ok(total) => SourceStatus::ready(total), Err(error) => crate::ingest::snapshot::classify_read_failure( &error.to_string(), &self.source_path, ), } } fn read(&self, cursor: Option<&str>, emit: Emit<'_>) -> Result { let mut notes = IngestNotes::new(); // A cursor that will not parse is no cursor at all: re-reading is free // (every row carries its own id) and guessing a position is not. let mut from = cursor .and_then(|value| value.trim().parse::().ok()) .filter(|value| *value >= 0) .unwrap_or(0); let db = self.open().map_err(|status| { status .detail .unwrap_or_else(|| "this Mac's call history could not be read".to_string()) })?; loop { let page = self.page(&db, from)?; if page.is_empty() { break; } let read = page.len() as i64; let mut calls: Vec = Vec::new(); for row in &page { from = from.max(row.z_pk); match call_from_row(row, &self.device, &self.country_code) { RowRead::Call(call) => calls.push(*call), RowRead::Skip(reason) => count(&mut notes, reason, 1), } } if !calls.is_empty() { // The cursor rides the batch: a page that has been written is a // page that need never be read again, and a run killed halfway // through thousands of calls continues rather than starting // over. emit(IngestBatch { work: IngestWork::Calls { calls }, read, cursor: Some(from.to_string()), })?; } if read < CALLS_PER_BATCH { break; } } Ok(ReadOutcome { cursor: from.to_string(), notes, }) } fn triggers(&self) -> Triggers { Triggers { // A call is written into the store the moment it ends; the watch // reads it then, and the poll is the floor under it. watch: vec![self.source_path.clone()], every_ms: CALL_HISTORY_POLL_MS, } } } #[cfg(test)] #[path = "call_history_tests.rs"] mod tests;