//! A synthetic `chat.db`, built with Apple's own DDL for the tables the reader //! touches. //! //! SYNTHETIC, and it has to be: the real file on a Mac is the owner's own //! messages, and nothing derived from one may reach this tree //! ([nothing-real-ever-goes-in-cotton-s-public-tree]). Every number and every //! sentence below is invented here. use std::path::Path; use rusqlite::Connection; /// Apple's DDL for the tables this reader selects from. /// /// `message`'s other eighty columns are attachment bookkeeping, delivery /// receipts and CloudKit sync state; a fixture that carried them would be /// pretending to test something it does not. const DDL: &str = " CREATE TABLE handle (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, id TEXT NOT NULL, country TEXT, service TEXT NOT NULL, uncanonicalized_id TEXT, person_centric_id TEXT, UNIQUE (id, service)); CREATE TABLE chat (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT UNIQUE NOT NULL, style INTEGER, state INTEGER, chat_identifier TEXT, service_name TEXT, room_name TEXT, display_name TEXT, group_id TEXT, is_archived INTEGER DEFAULT 0); CREATE TABLE message (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT UNIQUE NOT NULL, text TEXT, attributedBody BLOB, service TEXT, is_from_me INTEGER DEFAULT 0, date INTEGER DEFAULT 0, item_type INTEGER DEFAULT 0, handle_id INTEGER DEFAULT 0, associated_message_type INTEGER DEFAULT 0, associated_message_guid TEXT, associated_message_emoji TEXT, thread_originator_guid TEXT); CREATE TABLE chat_message_join (chat_id INTEGER, message_id INTEGER, PRIMARY KEY (chat_id, message_id)); CREATE TABLE chat_handle_join (chat_id INTEGER, handle_id INTEGER, UNIQUE(chat_id, handle_id)); CREATE TABLE attachment (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT UNIQUE NOT NULL, filename TEXT, mime_type TEXT, transfer_name TEXT, total_bytes INTEGER DEFAULT 0); CREATE TABLE message_attachment_join (message_id INTEGER, attachment_id INTEGER, PRIMARY KEY (message_id, attachment_id)); "; /// Apple's epoch in Unix milliseconds — 2001-01-01T00:00:00Z. const APPLE_EPOCH_MS: i64 = 978_307_200_000; /// An ISO instant as the nanoseconds-since-2001 the modern files store. pub(crate) fn apple_nanos(iso: &str) -> i64 { let at = chrono::DateTime::parse_from_rfc3339(iso).expect("an instant the fixture wrote"); (at.timestamp_millis() - APPLE_EPOCH_MS) * 1_000_000 } /// An `attributedBody` blob for `text`, in the format the decoder parses. pub(crate) fn attributed_body_for(text: &str) -> Vec { let body = text.as_bytes(); let length: Vec = if body.len() < 0x80 { vec![body.len() as u8] } else { vec![ 0x81, (body.len() & 0xff) as u8, ((body.len() >> 8) & 0xff) as u8, ] }; let mut blob = vec![0x04, 0x0b, 0x84, 0x84, 0x12]; blob.extend_from_slice(b"NSString"); blob.extend_from_slice(&[0x01, 0x94, 0x84, 0x01, 0x2b]); blob.extend_from_slice(&length); blob.extend_from_slice(body); blob.extend_from_slice(&[0x86, 0x84, 0x02]); blob } #[derive(Debug, Clone, Default)] pub(crate) struct FixtureAttachment { /// `attachment.filename`, `~/`-rooted exactly as Apple writes it. pub filename: String, pub mime_type: Option, pub transfer_name: Option, } #[derive(Debug, Clone)] pub(crate) struct FixtureChat { pub guid: String, pub style: i64, pub chat_identifier: String, pub service_name: String, pub display_name: Option, pub members: Vec, } impl FixtureChat { pub fn dm(guid: &str, identifier: &str, service: &str) -> FixtureChat { FixtureChat { guid: guid.to_string(), style: 45, chat_identifier: identifier.to_string(), service_name: service.to_string(), display_name: None, members: Vec::new(), } } pub fn group(guid: &str, identifier: &str, service: &str, members: &[&str]) -> FixtureChat { FixtureChat { guid: guid.to_string(), style: 43, chat_identifier: identifier.to_string(), service_name: service.to_string(), display_name: None, members: members.iter().map(|value| value.to_string()).collect(), } } pub fn named(mut self, title: &str) -> FixtureChat { self.display_name = Some(title.to_string()); self } } #[derive(Debug, Clone)] pub(crate) struct FixtureMessage { pub guid: String, /// `None` forces the reader down the `attributedBody` path. pub text: Option, pub attributed_body: Option>, pub service: String, pub from_me: bool, pub at: String, pub chat: String, /// The handle's `id`, for an inbound message or a group sender. pub handle: Option, pub item_type: i64, pub associated_type: i64, pub associated_guid: Option, pub associated_emoji: Option, pub reply_to: Option, pub attachments: Vec, } impl FixtureMessage { pub fn new(guid: &str, service: &str, at: &str, chat: &str) -> FixtureMessage { FixtureMessage { guid: guid.to_string(), text: None, attributed_body: None, service: service.to_string(), from_me: false, at: at.to_string(), chat: chat.to_string(), handle: None, item_type: 0, associated_type: 0, associated_guid: None, associated_emoji: None, reply_to: None, attachments: Vec::new(), } } pub fn text(mut self, body: &str) -> FixtureMessage { self.text = Some(body.to_string()); self } pub fn blob(mut self, blob: Vec) -> FixtureMessage { self.attributed_body = Some(blob); self } pub fn outbound(mut self) -> FixtureMessage { self.from_me = true; self } pub fn handle(mut self, id: &str) -> FixtureMessage { self.handle = Some(id.to_string()); self } pub fn item_type(mut self, kind: i64) -> FixtureMessage { self.item_type = kind; self } pub fn tapback(mut self, kind: i64, target: &str) -> FixtureMessage { self.associated_type = kind; self.associated_guid = Some(target.to_string()); self } pub fn reply_to(mut self, target: &str) -> FixtureMessage { self.reply_to = Some(target.to_string()); self } pub fn attach(mut self, attachment: FixtureAttachment) -> FixtureMessage { self.attachments.push(attachment); self } } /// Build the file at `path`. The reader opens it itself. pub(crate) fn write_messages_fixture( path: &Path, chats: &[FixtureChat], messages: &[FixtureMessage], ) { let db = crate::test_support::open_fixture_db(path); db.execute_batch(DDL).expect("Apple's own tables"); let mut handle_ids: std::collections::BTreeMap = std::collections::BTreeMap::new(); let mut handle_row_id = |db: &Connection, id: &str, service: &str| -> i64 { let key = format!("{id}|{service}"); if let Some(existing) = handle_ids.get(&key) { return *existing; } db.execute( "INSERT INTO handle (id, service) VALUES (?, ?)", (id, service), ) .expect("a handle row"); let row_id = db.last_insert_rowid(); handle_ids.insert(key, row_id); row_id }; let mut chat_ids: std::collections::BTreeMap = std::collections::BTreeMap::new(); for chat in chats { db.execute( "INSERT INTO chat (guid, style, chat_identifier, service_name, display_name) VALUES (?, ?, ?, ?, ?)", ( &chat.guid, chat.style, &chat.chat_identifier, &chat.service_name, &chat.display_name, ), ) .expect("a chat row"); let row_id = db.last_insert_rowid(); chat_ids.insert(chat.guid.clone(), row_id); for member in &chat.members { let handle = handle_row_id(&db, member, &chat.service_name); db.execute( "INSERT OR IGNORE INTO chat_handle_join (chat_id, handle_id) VALUES (?, ?)", (row_id, handle), ) .expect("a membership row"); } } let mut attachment_seq = 0; // ROWIDs are stated rather than left to AUTOINCREMENT: the reader's cursor // IS a ROWID, and a fixture whose numbering drifted would make a cursor // test pass for the wrong reason. for (row_id, message) in (1_i64..).zip(messages.iter()) { let chat_row_id = *chat_ids .get(&message.chat) .expect("the fixture names a chat it created"); let handle = message .handle .as_deref() .map(|id| handle_row_id(&db, id, &message.service)) .unwrap_or(0); db.execute( "INSERT INTO message (ROWID, guid, text, attributedBody, service, is_from_me, date, item_type, handle_id, associated_message_type, associated_message_guid, associated_message_emoji, thread_originator_guid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", rusqlite::params![ row_id, &message.guid, &message.text, &message.attributed_body, &message.service, i64::from(message.from_me), apple_nanos(&message.at), message.item_type, handle, message.associated_type, &message.associated_guid, &message.associated_emoji, &message.reply_to, ], ) .expect("a message row"); db.execute( "INSERT INTO chat_message_join (chat_id, message_id) VALUES (?, ?)", (chat_row_id, row_id), ) .expect("a chat membership for the message"); for attachment in &message.attachments { attachment_seq += 1; db.execute( "INSERT INTO attachment (guid, filename, mime_type, transfer_name, total_bytes) VALUES (?, ?, ?, ?, 0)", ( format!("at-{attachment_seq}-{}", message.guid), &attachment.filename, &attachment.mime_type, &attachment.transfer_name, ), ) .expect("an attachment row"); let attachment_row_id = db.last_insert_rowid(); db.execute( "INSERT INTO message_attachment_join (message_id, attachment_id) VALUES (?, ?)", (row_id, attachment_row_id), ) .expect("the attachment's message"); } } }