Cotton code
940 lines · 35.6 KB · RustRaw
//! iMessage and SMS from the Mac's `~/Library/Messages/chat.db`: everything//! iCloud (and the iPhone's Text Message Forwarding, for SMS) has delivered to//! this Mac, right up to a second ago.//!//! Restored for the Mac's importer (coordinator, 24 Nov 2026: SMS through the//! Mac stopped; the newest text in Comms dated from 26 Oct, the day this reader//! left the tree with the iPhone-backup reader). The backup half stays gone://! this reads the Mac's own file only. Every row carries its `message.guid`, so//! a re-read lands nothing twice.//!//! Everything it produces goes through the ONE message import engine, the same//! one the WhatsApp reader uses. There is no second definition of what a//! message row is on this Mac.use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use cotton_core::constants::MessageChannel;use cotton_core::import::envelope::{    Direction, EnvelopeMessage, EnvelopeReaction, EnvelopeThread, EnvelopeThreadParticipant,    ImportBatch,};use cotton_store::file_identity::Namespace;use cotton_store::protocol::derived_id::derived_id;use rusqlite::Connection;use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};use crate::ingest::attributed_body::decode_attributed_body;use crate::ingest::messages_schema::{    apple_date_to_iso, channel_for_service, group_title, is_message_row, read_handle, read_tapback,    target_guid_of, HandleKind, MessageHandle, ThreadShape, DEFAULT_COUNTRY_CODE,};use crate::ingest::snapshot::{classify_read_failure, open_live_copy};use crate::ingest::{    count, Emit, IngestBatch, IngestMediaFile, IngestNotes, IngestSource, IngestWork, ReadOutcome,    SourceId, SourceStatus, Triggers, MAX_ENVELOPES_PER_BATCH,};use crate::Layout;/// The file a row came from — kept in `meta.source.file` (`"mac"`, as before).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub enum MessagesFileId {    #[serde(rename = "mac")]    Mac,}impl MessagesFileId {    pub const fn as_str(self) -> &'static str {        match self {            MessagesFileId::Mac => "mac",        }    }}#[derive(Debug, Clone, PartialEq, Eq)]pub struct MessagesFile {    pub id: MessagesFileId,    /// The live file to copy from.    pub path: PathBuf,}pub fn mac_messages_path(home: &Path) -> PathBuf {    home.join("Library").join("Messages").join("chat.db")}/// The cursor: the Mac file's last `message.ROWID` read. A cursor an older/// build wrote (with its backup half) reads its `mac` position.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct MessagesCursor {    #[serde(default)]    pub mac: i64,}pub fn parse_messages_cursor(raw: Option<&str>) -> MessagesCursor {    // A cursor that will not parse is a cursor this build cannot trust, and a    // full re-read costs nothing but time: every row carries its guid, so the    // engine skips what it already has.    raw.and_then(|value| serde_json::from_str(value).ok())        .unwrap_or_default()}/* --------------------------------------------------------------- row shapes */#[derive(Debug, Clone)]struct MessageRow {    row_id: i64,    guid: Option<String>,    text: Option<String>,    attributed_body: Option<Vec<u8>>,    service: Option<String>,    is_from_me: i64,    date: Option<i64>,    item_type: Option<i64>,    associated_message_type: Option<i64>,    associated_message_guid: Option<String>,    associated_message_emoji: Option<String>,    thread_originator_guid: Option<String>,    handle_id: Option<i64>,    chat_row_id: Option<i64>,}#[derive(Debug, Clone)]struct ChatRow {    row_id: i64,    guid: Option<String>,    style: Option<i64>,    display_name: Option<String>,    chat_identifier: Option<String>,    service_name: Option<String>,}#[derive(Debug, Clone)]struct AttachmentRow {    message_id: i64,    filename: Option<String>,    mime_type: Option<String>,    transfer_name: Option<String>,}const MESSAGE_PAGE_SQL: &str = "  SELECT m.ROWID, m.guid, m.text, m.attributedBody, m.service, m.is_from_me, m.date,         m.item_type, m.associated_message_type, m.associated_message_guid,         m.associated_message_emoji, m.thread_originator_guid, m.handle_id,         (SELECT cmj.chat_id FROM chat_message_join cmj WHERE cmj.message_id = m.ROWID LIMIT 1)           AS chat_rowid    FROM message m   WHERE m.ROWID > ?   ORDER BY m.ROWID   LIMIT ?";/// Rows per page. Bounded so a 32k-message file never sits in one array twice.const PAGE_SIZE: i64 = 5_000;/// Every attachment in the file, with the message it hangs off.////// Read WHOLE rather than per page: a real Mac file holds a few hundred of/// these and the phone's a couple of thousand, so one query and a map beats/// thirty-two thousand lookups — and unlike the message table this one is small/// enough to say that about.const ATTACHMENT_SQL: &str = "  SELECT maj.message_id AS message_id, a.filename, a.mime_type, a.transfer_name    FROM message_attachment_join maj    JOIN attachment a ON a.ROWID = maj.attachment_id";/* ------------------------------------------------------------------ buckets *//// One conversation, in one channel — the unit an import batch describes.#[derive(Debug)]struct Bucket {    kind: ThreadShape,    channel: MessageChannel,    /// DM: the counterpart. Group: unused.    counterpart: Option<MessageHandle>,    counterpart_label: String,    title: String,    /// The group's own key in the file: `chat.guid`, and nothing derived.    external_key: String,    /// The id the thread gets IF this run has to create it — derived from the    /// chat's identity WITHOUT the channel, because one contact has ONE dm    /// thread whatever they message over (the dm uniqueness is    /// channel-agnostic).    thread_id: String,    participants: Vec<EnvelopeThreadParticipant>,    envelopes: Vec<EnvelopeMessage>,    /// The files this conversation's messages reference, by message guid.    media: Vec<IngestMediaFile>,    /// guid → where in `envelopes` it sits, so a tapback can find its target.    by_guid: BTreeMap<String, usize>,}#[derive(Debug)]struct PendingTapback {    target_guid: String,    emoji: String,    actor: String,    at: String,}/// The buckets of one pass, in the order the rows made them.#[derive(Debug, Default)]struct Buckets {    order: Vec<String>,    by_key: BTreeMap<String, Bucket>,}impl Buckets {    fn get_or_insert(&mut self, key: String, make: impl FnOnce() -> Bucket) -> &mut Bucket {        if !self.by_key.contains_key(&key) {            self.order.push(key.clone());            self.by_key.insert(key.clone(), make());        }        self.by_key.get_mut(&key).expect("the bucket just made")    }    fn in_order(&self) -> impl Iterator<Item = &Bucket> {        self.order.iter().filter_map(|key| self.by_key.get(key))    }}/* ------------------------------------------------------------------- reader */pub struct MessagesSource {    workspace_id: String,    namespace: Namespace,    layout: Layout,    /// The ingesting machine's label — rides every row as `meta.source.device`.    device: String,    home: PathBuf,    country_code: String,    /// Rows sent before this instant (ISO) are passed over, counted: where a    /// first read starts when Cotton already holds the texts before it.    since: Option<String>,    /// Test seam: read exactly these files instead of discovering them.    files: Option<Vec<MessagesFile>>,}pub struct MessagesSourceInput {    pub workspace_id: String,    /// The database's namespace, which a thread's id is derived under.    pub namespace: Namespace,    pub layout: Layout,    pub device: String,    pub home: PathBuf,    pub country_code: Option<String>,    pub files: Option<Vec<MessagesFile>>,}impl MessagesSource {    pub fn new(input: MessagesSourceInput) -> MessagesSource {        MessagesSource {            workspace_id: input.workspace_id,            namespace: input.namespace,            layout: input.layout,            device: input.device,            home: input.home,            country_code: input                .country_code                .unwrap_or_else(|| DEFAULT_COUNTRY_CODE.to_string()),            since: None,            files: input.files,        }    }    /// Rows sent before `since` (ISO) are passed over: a first read starts    /// where Cotton's texts end, never re-sending years of attachments.    pub fn since(mut self, since: Option<String>) -> MessagesSource {        self.since = since;        self    }    /// The files this pass reads: the Mac's own.    fn resolve_files(&self) -> Vec<MessagesFile> {        if let Some(files) = &self.files {            return files.clone();        }        let mac = mac_messages_path(&self.home);        if mac.exists() {            vec![MessagesFile { id: MessagesFileId::Mac, path: mac }]        } else {            Vec::new()        }    }    /// The label a handle goes by: the handle as the file spelled it (the    /// import names the person from People by their number or address).    fn label_for(&self, handle: &MessageHandle, _names: &BTreeMap<String, String>) -> String {        handle.raw.clone()    }    fn open_file(&self, file: &MessagesFile) -> Result<Connection, SourceStatus> {        // The Mac's file is LIVE and is always copied.        open_live_copy(&self.layout, &file.path, &format!("messages-{}.db", file.id.as_str()))    }    /// Where an attachment's bytes are: `~/Library/…` is this Mac's home.    fn attachment_resolver(&self, _file: &MessagesFile, _notes: &mut IngestNotes) -> AttachmentResolver {        AttachmentResolver::OnThisDisk { home: self.home.clone() }    }    #[allow(clippy::too_many_lines)]    fn read_file(        &self,        file: &MessagesFile,        from: i64,        names: &BTreeMap<String, String>,        seen_guids: &mut BTreeSet<String>,        notes: &mut IngestNotes,    ) -> Result<(Buckets, i64, i64), String> {        let db = self.open_file(file).map_err(|status| {            status                .detail                .unwrap_or_else(|| status.state.as_str().to_string())        })?;        let mut buckets = Buckets::default();        let mut tapbacks: Vec<PendingTapback> = Vec::new();        let resolver = self.attachment_resolver(file, notes);        let mut cursor = from;        let mut read: i64 = 0;        let chats = read_chats(&db).map_err(|error| error.to_string())?;        let handles = read_handles(&db).map_err(|error| error.to_string())?;        let attachments_by_message = read_attachments(&db).map_err(|error| error.to_string())?;        let members_by_chat = read_chat_members(&db).map_err(|error| error.to_string())?;        loop {            let page = read_message_page(&db, cursor).map_err(|error| error.to_string())?;            if page.is_empty() {                break;            }            let page_len = page.len() as i64;            for row in page {                cursor = cursor.max(row.row_id);                read += 1;                let Some(guid) = row                    .guid                    .as_deref()                    .map(str::trim)                    .filter(|value| !value.is_empty())                    .map(str::to_string)                else {                    count(notes, "noGuid", 1);                    continue;                };                // The phone's file is read FIRST, so a guid already seen this                // pass is the same message as one the better file produced.                if seen_guids.contains(&guid) {                    count(notes, "duplicateAcrossFiles", 1);                    continue;                }                if !is_message_row(row.item_type) {                    // A group event — renamed, joined, left. The import engine                    // writes no structured event row, and a sentence invented                    // here would be the server writing words into somebody's                    // group, which is the mistake the chat rules name outright.                    // Counted, dropped.                    count(notes, "groupEvent", 1);                    continue;                }                let Some(chat) = row.chat_row_id.and_then(|id| chats.get(&id)) else {                    count(notes, "noChat", 1);                    continue;                };                let Some(kind) = crate::ingest::messages_schema::thread_kind_for_style(chat.style)                else {                    count(notes, "unknownChatStyle", 1);                    continue;                };                let Some(channel) = channel_for_service(row.service.as_deref())                    .or_else(|| channel_for_service(chat.service_name.as_deref()))                else {                    count(notes, "unknownService", 1);                    continue;                };                let Some(sent_at) = apple_date_to_iso(row.date) else {                    count(notes, "noDate", 1);                    continue;                };                if self.since.as_deref().is_some_and(|since| sent_at.as_str() < since) {                    count(notes, "beforeSince", 1);                    continue;                }                let outbound = row.is_from_me == 1;                let sender_handle = row                    .handle_id                    .and_then(|id| handles.get(&id))                    .and_then(|raw| read_handle(Some(raw), &self.country_code));                if let Some(tapback) = read_tapback(                    row.associated_message_type,                    row.associated_message_guid.as_deref(),                    row.associated_message_emoji.as_deref(),                ) {                    seen_guids.insert(guid.clone());                    if tapback.removal {                        // The engine's reaction rows are upserts keyed on                        // (message, actor) and it exposes no delete, so a                        // removal is READ and then dropped rather than                        // pretended to.                        count(notes, "tapbackRemoval", 1);                        continue;                    }                    let actor = if outbound {                        Some("owner".to_string())                    } else {                        sender_handle                            .as_ref()                            .filter(|handle| handle.kind == HandleKind::Phone)                            .map(|handle| handle.value.clone())                    };                    let Some(actor) = actor else {                        // The engine's actor vocabulary is phone-or-self; a                        // reaction from an Apple ID has nobody it can be keyed                        // to.                        count(notes, "tapbackActorUnknown", 1);                        continue;                    };                    tapbacks.push(PendingTapback {                        target_guid: tapback.target_guid,                        emoji: tapback.emoji,                        actor,                        at: sent_at,                    });                    continue;                }                let empty: Vec<AttachmentRow> = Vec::new();                let attachments = attachments_by_message.get(&row.row_id).unwrap_or(&empty);                let body = row                    .text                    .as_deref()                    .filter(|text| !text.trim().is_empty())                    .map(str::to_string)                    .or_else(|| decode_attributed_body(row.attributed_body.as_deref()));                if body.is_none() && attachments.is_empty() {                    // No text, nothing decodable, and no file. There is nothing                    // here to import — an empty bubble is not a message                    // somebody sent.                    count(                        notes,                        if row.attributed_body.is_some() {                            "bodyUndecodable"                        } else {                            "noBody"                        },                        1,                    );                    continue;                }                let Some(bucket_key) = self.bucket_for(                    &mut buckets,                    chat,                    kind,                    channel,                    sender_handle.as_ref(),                    names,                    &members_by_chat,                    &handles,                ) else {                    count(notes, "noCounterpart", 1);                    continue;                };                let sender_label = if kind == ThreadShape::Group && !outbound {                    sender_handle                        .as_ref()                        .map(|handle| self.label_for(handle, names))                } else {                    None                };                let envelope = EnvelopeMessage {                    // The counterpart is named ONCE, on the batch's `dm` block —                    // a bucket is one conversation, so repeating the identity on                    // every row of it would be the same fact 32,000 times.                    phone: None,                    email: None,                    sender_label,                    display_name: None,                    direction: if outbound {                        Direction::Out                    } else {                        Direction::In                    },                    // A picture with no caption is a real message and its body                    // is empty; the media entry is what the bubble draws.                    body: body.unwrap_or_default(),                    media: None,                    sent_at,                    external_id: guid.clone(),                    reply_to_external_id: row                        .thread_originator_guid                        .as_deref()                        .and_then(|raw| target_guid_of(Some(raw))),                    reactions: None,                    meta: Some(provenance(                        row.service                            .as_deref()                            .or(chat.service_name.as_deref())                            .unwrap_or("unknown"),                        &self.device,                        &guid,                        file.id,                        sender_handle.as_ref().filter(|_| !outbound),                    )),                };                let bucket = buckets                    .by_key                    .get_mut(&bucket_key)                    .expect("the bucket just resolved");                bucket.by_guid.insert(guid.clone(), bucket.envelopes.len());                bucket.envelopes.push(envelope);                seen_guids.insert(guid.clone());                for attachment in attachments {                    let Some(path) = resolver.resolve(attachment) else {                        // The row names a file this Mac cannot find — an                        // attachment never downloaded, or one the person                        // deleted. The MESSAGE still lands; only the picture is                        // missing.                        count(notes, "media:notOnThisMac", 1);                        continue;                    };                    bucket.media.push(IngestMediaFile {                        external_id: guid.clone(),                        path,                        name: attachment.transfer_name.clone(),                        // iMessage is the rare source that actually RECORDS the                        // type, so it is used rather than guessed from the                        // extension.                        content_type: attachment.mime_type.clone(),                    });                }            }            if page_len < PAGE_SIZE {                break;            }        }        // Reactions ride on the envelope of the message they are ON, because        // the engine writes a reaction row only for a message it is INSERTING.        // A tapback whose target is not in this pass is counted rather than        // dropped in silence: on the first full import that is nearly none, and        // on the live tail it is the honest limit of this design.        for tapback in tapbacks {            let mut attached = false;            for key in buckets.order.clone() {                let Some(bucket) = buckets.by_key.get_mut(&key) else {                    continue;                };                let Some(at) = bucket.by_guid.get(&tapback.target_guid).copied() else {                    continue;                };                let reactions = bucket.envelopes[at].reactions.get_or_insert_with(Vec::new);                reactions.push(EnvelopeReaction {                    emoji: tapback.emoji.clone(),                    actor: tapback.actor.clone(),                    at: Some(tapback.at.clone()),                });                attached = true;                break;            }            if !attached {                count(notes, "tapbackWithoutTarget", 1);            }        }        Ok((buckets, cursor, read))    }    /// The bucket a row belongs in, creating it the first time.    #[allow(clippy::too_many_arguments)]    fn bucket_for(        &self,        buckets: &mut Buckets,        chat: &ChatRow,        kind: ThreadShape,        channel: MessageChannel,        sender_handle: Option<&MessageHandle>,        names: &BTreeMap<String, String>,        members_by_chat: &BTreeMap<i64, Vec<i64>>,        handles: &BTreeMap<i64, String>,    ) -> Option<String> {        // The chat's OWN identity, and it must be the same in both files:        // `chat.guid` carries the service (`iMessage;-;…`) and therefore differs        // between an SMS and an iMessage conversation with one person, so a DM        // keys on the counterpart and only a group keys on the guid.        let mut counterpart: Option<MessageHandle> = None;        let identity: String;        let external_key: String;        if kind == ThreadShape::Dm {            counterpart = read_handle(chat.chat_identifier.as_deref(), &self.country_code)                .or_else(|| sender_handle.cloned());            let handle = counterpart.as_ref()?;            identity = format!(                "dm:{}:{}",                match handle.kind {                    HandleKind::Phone => "phone",                    HandleKind::Email => "email",                    HandleKind::Label => "label",                },                handle.value            );            external_key = identity.clone();        } else {            let guid = chat.guid.as_deref()?;            identity = format!("group:{guid}");            // The GROUP's key in the file is the chat's own guid — what a            // second pass matches on, and what makes it land in the thread the            // first one made.            external_key = guid.to_string();        }        // The channel is in the BUCKET key and nowhere else: an import batch        // carries one channel, so a conversation held over both iMessage and        // SMS is two batches — landing in ONE thread, with the channel a        // per-message fact.        let key = format!("{identity}:{}", channel.as_str());        if buckets.by_key.contains_key(&key) {            return Some(key);        }        let mut participants: Vec<EnvelopeThreadParticipant> = Vec::new();        let mut member_labels: Vec<String> = Vec::new();        if kind == ThreadShape::Group {            for handle_row_id in members_by_chat.get(&chat.row_id).unwrap_or(&Vec::new()) {                let Some(handle) = handles                    .get(handle_row_id)                    .and_then(|raw| read_handle(Some(raw), &self.country_code))                else {                    continue;                };                let name = self.label_for(&handle, names);                member_labels.push(name.clone());                participants.push(EnvelopeThreadParticipant {                    label: name,                    phone: (handle.kind == HandleKind::Phone).then(|| handle.value.clone()),                    email: (handle.kind == HandleKind::Email).then(|| handle.value.clone()),                    person_id: None,                    handle: None,                });            }            member_labels.sort();            member_labels.dedup();            // One label, one participant: a group where two members go by the            // same saved name is one person to the engine either way, and two            // rows would be two people it cannot tell apart.            let mut seen = BTreeSet::new();            participants.retain(|participant| seen.insert(participant.label.clone()));        }        let counterpart_label = counterpart            .as_ref()            .map(|handle| self.label_for(handle, names))            .unwrap_or_else(|| "Unknown".to_string());        let title = if kind == ThreadShape::Group {            group_title(chat.display_name.as_deref(), &member_labels)        } else {            String::new()        };        let thread_id = derived_id(            "cotton_msg_threads",            &[self.namespace.as_str(), "ios-messages", &identity],        );        buckets.get_or_insert(key.clone(), || Bucket {            kind,            channel,            counterpart,            counterpart_label,            title,            external_key,            thread_id,            participants,            envelopes: Vec::new(),            media: Vec::new(),            by_guid: BTreeMap::new(),        });        Some(key)    }    fn emit_buckets(&self, buckets: &Buckets, emit: Emit<'_>) -> Result<(), String> {        for bucket in buckets.in_order() {            for chunk in bucket.envelopes.chunks(MAX_ENVELOPES_PER_BATCH) {                let ids: BTreeSet<&str> = chunk                    .iter()                    .map(|envelope| envelope.external_id.as_str())                    .collect();                let media: Vec<IngestMediaFile> = bucket                    .media                    .iter()                    .filter(|file| ids.contains(file.external_id.as_str()))                    .cloned()                    .collect();                let batch = ImportBatch {                    workspace_id: self.workspace_id.clone(),                    channel: bucket.channel.as_str().to_string(),                    thread: (bucket.kind == ThreadShape::Group).then(|| EnvelopeThread {                        kind: "group".to_string(),                        title: bucket.title.clone(),                        external_key: bucket.external_key.clone(),                        participants: bucket.participants.clone(),                    }),                    dm: (bucket.kind == ThreadShape::Dm).then(|| EnvelopeThreadParticipant {                        label: bucket.counterpart_label.clone(),                        phone: bucket                            .counterpart                            .as_ref()                            .filter(|handle| handle.kind == HandleKind::Phone)                            .map(|handle| handle.value.clone()),                        email: bucket                            .counterpart                            .as_ref()                            .filter(|handle| handle.kind == HandleKind::Email)                            .map(|handle| handle.value.clone()),                        person_id: None,                        handle: None,                    }),                    messages: chunk.to_vec(),                    // The SAME id every pass, derived from the source's own chat                    // key, so a label-only conversation (a bank's sender id, of                    // which a real file has thousands) lands in the thread it                    // landed in last time instead of a new one. Ignored wherever                    // the thread resolves by contact or by key.                    new_thread_id: Some(bucket.thread_id.clone()),                };                emit(IngestBatch {                    work: IngestWork::Messages {                        request: Box::new(batch),                        media,                    },                    read: chunk.len() as i64,                    cursor: None,                })?;            }        }        Ok(())    }}/// Provenance: the VERBATIM service label, the machine that read it, the/// source's own id, which of the two files it came out of, and — for a/// message that arrived — the number or address it came from/// (`senderHandle`), which seats a group's sender and keeps every text's/// own sender whatever its thread is named by. A sender id that is a word/// (a bank, a shortcode) is no handle anybody can be, so it is not one here.fn provenance(    service: &str,    device: &str,    external_id: &str,    file: MessagesFileId,    sender: Option<&MessageHandle>,) -> Map<String, Value> {    let mut source = json!({        "service": service,        "device": device,        "externalId": external_id,        "file": file.as_str(),    });    let kind = match sender.map(|handle| &handle.kind) {        Some(HandleKind::Phone) => Some("phone"),        Some(HandleKind::Email) => Some("email"),        Some(HandleKind::Label) | None => None,    };    if let (Some(kind), Some(handle)) = (kind, sender) {        source["senderHandle"] = json!({ "kind": kind, "value": handle.value });    }    let mut meta = Map::new();    meta.insert("source".to_string(), source);    meta}enum AttachmentResolver {    OnThisDisk { home: PathBuf },}impl AttachmentResolver {    fn resolve(&self, row: &AttachmentRow) -> Option<PathBuf> {        let named = row            .filename            .as_deref()            .map(str::trim)            .filter(|value| !value.is_empty())?;        match self {            AttachmentResolver::OnThisDisk { home } => {                let path = match named.strip_prefix("~/") {                    Some(rest) => home.join(rest),                    None => PathBuf::from(named),                };                path.exists().then_some(path)            }        }    }}/* ------------------------------------------------------------------ queries */fn read_message_page(db: &Connection, from: i64) -> rusqlite::Result<Vec<MessageRow>> {    let mut statement = db.prepare(MESSAGE_PAGE_SQL)?;    let rows = statement.query_map((from, PAGE_SIZE), |row| {        Ok(MessageRow {            row_id: row.get(0)?,            guid: row.get(1)?,            text: row.get(2)?,            attributed_body: row.get(3)?,            service: row.get(4)?,            is_from_me: row.get::<_, Option<i64>>(5)?.unwrap_or(0),            date: row.get(6)?,            item_type: row.get(7)?,            associated_message_type: row.get(8)?,            associated_message_guid: row.get(9)?,            associated_message_emoji: row.get(10)?,            thread_originator_guid: row.get(11)?,            handle_id: row.get(12)?,            chat_row_id: row.get(13)?,        })    })?;    rows.collect()}fn read_chats(db: &Connection) -> rusqlite::Result<BTreeMap<i64, ChatRow>> {    let mut statement = db.prepare(        "SELECT ROWID, guid, style, display_name, chat_identifier, service_name FROM chat",    )?;    let rows = statement.query_map([], |row| {        Ok(ChatRow {            row_id: row.get(0)?,            guid: row.get(1)?,            style: row.get(2)?,            display_name: row.get(3)?,            chat_identifier: row.get(4)?,            service_name: row.get(5)?,        })    })?;    let mut chats = BTreeMap::new();    for chat in rows {        let chat = chat?;        chats.insert(chat.row_id, chat);    }    Ok(chats)}fn read_handles(db: &Connection) -> rusqlite::Result<BTreeMap<i64, String>> {    let mut statement = db.prepare("SELECT ROWID, id FROM handle")?;    let rows = statement.query_map([], |row| {        Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(1)?))    })?;    let mut handles = BTreeMap::new();    for entry in rows {        let (row_id, id) = entry?;        if let Some(id) = id {            handles.insert(row_id, id);        }    }    Ok(handles)}fn read_attachments(db: &Connection) -> rusqlite::Result<BTreeMap<i64, Vec<AttachmentRow>>> {    let mut statement = db.prepare(ATTACHMENT_SQL)?;    let rows = statement.query_map([], |row| {        Ok(AttachmentRow {            message_id: row.get(0)?,            filename: row.get(1)?,            mime_type: row.get(2)?,            transfer_name: row.get(3)?,        })    })?;    let mut by_message: BTreeMap<i64, Vec<AttachmentRow>> = BTreeMap::new();    for attachment in rows {        let attachment = attachment?;        by_message            .entry(attachment.message_id)            .or_default()            .push(attachment);    }    Ok(by_message)}fn read_chat_members(db: &Connection) -> rusqlite::Result<BTreeMap<i64, Vec<i64>>> {    let mut statement = db.prepare("SELECT chat_id, handle_id FROM chat_handle_join")?;    let rows = statement.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))?;    let mut members: BTreeMap<i64, Vec<i64>> = BTreeMap::new();    for entry in rows {        let (chat_id, handle_id) = entry?;        members.entry(chat_id).or_default().push(handle_id);    }    Ok(members)}fn count_messages(db: &Connection) -> rusqlite::Result<i64> {    db.query_row("SELECT COUNT(*) FROM message", [], |row| row.get(0))}/* -------------------------------------------------------------- the contract */impl IngestSource for MessagesSource {    fn id(&self) -> SourceId {        SourceId::Messages    }    fn probe(&self) -> SourceStatus {        let files = self.resolve_files();        if files.is_empty() {            return SourceStatus::not_found(                "This Mac has no Messages database. Sign in to Messages and try again.",            );        }        let mut total = 0;        for file in &files {            let db = match self.open_file(file) {                Ok(db) => db,                Err(status) => return status,            };            match count_messages(&db) {                Ok(rows) => total += rows,                Err(error) => return classify_read_failure(&error.to_string(), &file.path),            }        }        SourceStatus::ready(total)    }    fn read(&self, cursor: Option<&str>, emit: Emit<'_>) -> Result<ReadOutcome, String> {        let mut next = parse_messages_cursor(cursor);        let mut notes = IngestNotes::new();        let names = BTreeMap::new();        let mut seen_guids: BTreeSet<String> = BTreeSet::new();        for file in &self.resolve_files() {            let (buckets, cursor, read) = self.read_file(file, next.mac, &names, &mut seen_guids, &mut notes)?;            self.emit_buckets(&buckets, emit)?;            next.mac = cursor;            count(&mut notes, &format!("read:{}", file.id.as_str()), read);        }        Ok(ReadOutcome {            cursor: serde_json::to_string(&next).map_err(|error| error.to_string())?,            notes,        })    }    fn triggers(&self) -> Triggers {        Triggers {            // The database names its own sidecars: the watch wakes on a            // write to `chat.db` or its `-wal`, which is what moves when a            // message arrives. The poll is the floor under a watch macOS can            // drop. A test that names its files watches the Mac's one.            watch: match &self.files {                None => vec![mac_messages_path(&self.home)],                Some(files) => files.iter().map(|file| file.path.clone()).collect(),            },            every_ms: 60_000,        }    }}#[cfg(test)]#[path = "messages_tests.rs"]mod tests;