//! Texts: iMessage and SMS from this Mac's Messages (coordinator, 24 Nov 2026: SMS through the Mac stopped; the//! newest text in Comms dated from 26 Oct, the day the Messages reader left the tree, and the Mac's importer that//! replaced the old app never carried one). The reader is `cotton_client`'s `MessagesSource` over//! `~/Library/Messages/chat.db`, read the way Calls reads the call history: Cotton holds Full Disk Access, the live//! file is copied and the copy read. Its batches land through the sink like WhatsApp's, sealed.//!//! Continuous: checked every minute, and a pass whose database has not moved since the last copies nothing. A//! first read on a Mac whose texts Cotton already holds starts just after the newest of them, so the catch-up never//! re-sends years of attachments; from then on the cursor (the file's row id) follows every row.use std::path::{Path, PathBuf};use std::sync::Mutex;use std::time::{Duration, SystemTime};use cotton_client::ingest::sources::messages::{mac_messages_path, MessagesSource, MessagesSourceInput};use cotton_client::ingest::{IngestBatch, IngestSource};use cotton_client::Layout;use cotton_store::file_identity::Namespace;usecrate::importer::{Importer, Need, Probe, RunContext, RunError, Schedule, SourceKey};/// How often the Messages database is looked at.pubconst TEXTS_EVERY: Duration = Duration::from_secs(60);pubstructTextsImporter { layout: Layout, home: PathBuf, machine: String,/// The database and its write-ahead log as the last pass found them. seen: Mutex<Option<Stamp>>,}/// What moves when a text arrives: the database's and its log's size and time.typeStamp = Vec<(u64, Option<SystemTime>)>;implTextsImporter {pubfn new(layout: Layout, home: &Path, machine: String) -> TextsImporter {TextsImporter { layout, home: home.to_path_buf(), machine, seen: Mutex::new(None) } }fn database(&self) -> PathBuf { mac_messages_path(&self.home) }fn stamp(&self) -> Stamp {let db = self.database();let wal = db.with_extension("db-wal"); [db, wal].iter().map(|path| std::fs::metadata(path).map(|m| (m.len(), m.modified().ok())).unwrap_or((0, None))).collect() }fn source(&self, database_id: &str, since: Option<String>) -> MessagesSource {MessagesSource::new(MessagesSourceInput { workspace_id: database_id.to_string(), namespace: Namespace::of_database(database_id), layout: self.layout.clone(), device: self.machine.clone(), home: self.home.clone(), country_code: None, files: None, }) .since(since) }}implImporterforTextsImporter {fn key(&self) -> SourceKey {SourceKey::Texts }fn schedule(&self) -> Schedule {Schedule::Continuous(TEXTS_EVERY) }/// Whether Messages can be read, without copying it: a plain read-only open and one row.fn probe(&self) -> Probe {let db = self.database();if !db.exists() {returnmatch std::fs::metadata(db.parent().unwrap_or(Path::new("/"))) {Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => Probe { ready: false, need: Some(Need::FullDiskAccess), detail: None }, _ => Probe::unavailable("Messages is not set up on this Mac.".to_string()), }; }let opened = rusqlite::Connection::open_with_flags(&db, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) .and_then(|conn| conn.query_row("SELECT count(*) FROM message LIMIT 1", [], |r| r.get::<_, i64>(0)));match opened {Ok(_) => Probe::ready(),Err(error) => {let said = error.to_string();if said.contains("unable to open") || said.contains("authorization denied") || said.contains("not permitted") {Probe { ready: false, need: Some(Need::FullDiskAccess), detail: None } } else {Probe::unavailable(said) } } } }fn run(&self, cursor: Option<&str>, ctx: &mutRunContext<'_>) -> Result<String, RunError> {let stamp = self.stamp();ifletSome(cursor) = cursor {ifself.seen.lock().unwrap_or_else(|p| p.into_inner()).as_ref() == Some(&stamp) {returnOk(cursor.to_string()); } }// A first read starts just after the newest text Cotton holds.let since = match cursor {Some(_) => None,None => ctx.sink.copy().ok().and_then(|copy| copy.newest_text_at().ok().flatten()).map(|at| just_after(&at)), };let source = self.source(ctx.sink.database_id(), since);let outcome = {letmut emit = |batch: IngestBatch| ctx.emit(batch); source.read(cursor, &mut emit) };match outcome {Ok(outcome) => { *self.seen.lock().unwrap_or_else(|p| p.into_inner()) = Some(stamp);Ok(outcome.cursor) }Err(error) => Err(ctx.failed(error)), } }}/// The instant one millisecond after `at` (ISO), so the text at `at` itself is not read again.fn just_after(at: &str) -> String { chrono::DateTime::parse_from_rfc3339(at) .map(|t| (t + chrono::Duration::milliseconds(1)).with_timezone(&chrono::Utc).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) .unwrap_or_else(|_| at.to_string())}#[cfg(test)]mod tests {usesuper::*; #[test]fn a_first_read_starts_one_millisecond_after_the_newest_text() { assert_eq!(just_after("2026-10-26T11:08:00.804Z"), "2026-10-26T11:08:00.805Z"); assert_eq!(just_after("2026-10-26T11:08:00Z"), "2026-10-26T11:08:00.001Z"); }}