//! A decoded message → the plain rows the object stores (moved from //! cotton-mac, which re-exports it; the Worker runs it as WASM for mail that //! arrives on a person's own domain): `email`, //! `email_thread` and `email_participant`, keyed by the column keys of the //! personal object's tables, with the values the old ingest //! (`cotton-tools`' `emails::ingest`) wrote into `cotton_emails`, //! `cotton_email_threads` and `cotton_email_participants`. //! //! IDS ARE THE OLD STORE'S. An email is `derived_id("cotton_emails", //! [namespace, external_id])`, a thread `derived_id("cotton_email_threads", //! [namespace, thread_key])` and a participant `email_participant_id(thread //! id, address)`, with the object's namespace (its database id). The rows the //! coordinator brings over from the old store carry exactly these ids, so a //! message read again lands on its own row (`409 duplicate_id`, sent again as //! update) and new mail in an old conversation joins that conversation's row //! instead of starting a second one. //! //! What the old ingest decided from the store and the Mac cannot is left to //! the object: who is blocked (Junk), a sender's kind, the photos in an //! attachment, a row its source erased. use std::collections::HashMap; use super::state::email_state_from_labels; use crate::ids::derived_id; use crate::fingerprint::email::{ email_content_fingerprint, message_id_external_id, strip_reply_prefixes, EmailContentFingerprintInput, EmailOccurrenceCounter, }; use serde_json::{json, Map, Value}; use super::mime::{Decoded, MailAddress}; use super::text::{derive_snippet, strip_quoted_reply, utf16_clip, EMAIL_BODY_MAX, TRUNCATION_MARK}; pub const EMAIL: &str = "email"; pub const THREAD: &str = "email_thread"; pub const PARTICIPANT: &str = "email_participant"; /// The ids the old store gave mail, under the object's namespace. #[derive(Debug, Clone)] pub struct Ids { namespace: String, } impl Ids { pub fn new(database_id: &str) -> Ids { Ids { namespace: database_id.to_string(), } } pub fn email(&self, external_id: &str) -> String { derived_id("cotton_emails", &[&self.namespace, external_id]) } pub fn thread(&self, thread_key: &str) -> String { derived_id("cotton_email_threads", &[&self.namespace, thread_key]) } pub fn participant(&self, thread_id: &str, address: &str) -> String { derived_id("cotton_email_participants", &[thread_id, address]) } } /// One email, ready to send. #[derive(Debug, Clone, PartialEq)] pub struct EmailRow { pub id: String, pub external_id: String, pub thread_key: String, pub thread_id: String, pub gmail_id: Option, pub sent_at: String, /// The thread's name if it has none yet: the subject, `Re:` chains cut. pub thread_subject: String, /// (address lower-cased, name, role) as the participants fold them. pub addresses: Vec<(String, Option, &'static str)>, pub data: Value, } /// Identity per email for one page: the Message-ID when the message has one, /// else the content fingerprint, its occurrence counted per thread. #[derive(Default)] pub struct Page { counters: HashMap, } fn lowered(address: &MailAddress) -> String { address.email.to_lowercase() } fn recipient(address: &MailAddress, kind: &str) -> Value { let mut entry = Map::new(); entry.insert("email".to_string(), Value::from(lowered(address))); if let Some(name) = address.name.as_ref().filter(|name| !name.is_empty()) { entry.insert("name".to_string(), Value::from(name.clone())); } entry.insert("kind".to_string(), Value::from(kind)); Value::Object(entry) } impl Page { pub fn new() -> Page { Page::default() } /// The `email` row for `email`, and what its thread folds. pub fn email(&mut self, ids: &Ids, email: &Decoded) -> Result { // The quoted tail goes before anything reads the body: the identity // and the ceiling see the one new message, not the conversation. let body = strip_quoted_reply(&email.body); let external_id = match message_id_external_id(email.message_id.as_deref()) { Some(id) => id, None => { let counter = self.counters.entry(email.thread_key.clone()).or_default(); let occurrence = counter .next(&email.sent_at, Some(&email.subject), &body) .map_err(|error| error.to_string())?; email_content_fingerprint(&EmailContentFingerprintInput { sent_at: &email.sent_at, subject: Some(&email.subject), body: &body, occurrence, }) .map_err(|error| error.to_string())? } }; let body = if body.encode_utf16().count() > EMAIL_BODY_MAX { format!("{}{TRUNCATION_MARK}", utf16_clip(&body, EMAIL_BODY_MAX)) } else { body }; let id = ids.email(&external_id); let thread_id = ids.thread(&email.thread_key); let recipients: Vec = email .to .iter() .map(|a| recipient(a, "to")) .chain(email.cc.iter().map(|a| recipient(a, "cc"))) .chain(email.bcc.iter().map(|a| recipient(a, "bcc"))) .collect(); let attachments: Vec = email .attachments .iter() .map(|attachment| { let mut out = Map::new(); out.insert("name".to_string(), Value::from(attachment.name.clone())); if let Some(mime) = &attachment.mime { out.insert("mime".to_string(), Value::from(mime.clone())); } if let Some(size) = attachment.size { out.insert("size".to_string(), Value::from(size)); } Value::Object(out) }) .collect(); let mut data = Map::new(); data.insert("thread_id".into(), Value::from(thread_id.clone())); data.insert("account".into(), Value::from(email.account.clone())); data.insert("external_id".into(), Value::from(external_id.clone())); data.insert( "subject".into(), if email.subject.is_empty() { Value::Null } else { Value::from(email.subject.clone()) }, ); data.insert("from_email".into(), Value::from(lowered(&email.from))); data.insert("from_name".into(), email.from.name.clone().map_or(Value::Null, Value::from)); // Spam, bin and drafts never reach here (`text::refused_label`), so // nothing is born in the bin. data.insert("trashed_at".into(), Value::Null); match &email.gmail { Some(gmail) => { let state = email_state_from_labels(&gmail.labels); data.insert("gmail_id".into(), Value::from(gmail.id.clone())); data.insert("gmail_account".into(), Value::from(gmail.account.clone())); data.insert("labels".into(), json!(gmail.labels)); data.insert("unread".into(), Value::from(state.unread)); data.insert("starred".into(), Value::from(state.starred)); data.insert("in_inbox".into(), Value::from(state.in_inbox)); data.insert("sync_state".into(), Value::from("synced")); } None => { if let Some(flags) = email.flags { data.insert("unread".into(), Value::from(flags.unread)); data.insert("starred".into(), Value::from(flags.starred)); } } } data.insert("recipients".into(), Value::Array(recipients)); data.insert("sent_at".into(), Value::from(email.sent_at.clone())); data.insert("body".into(), if body.is_empty() { Value::Null } else { Value::from(body.clone()) }); data.insert("snippet".into(), derive_snippet(&body).map_or(Value::Null, Value::from)); data.insert("attachments".into(), Value::Array(attachments)); // bcc folds as `cc`: the participant list has three ranks, not four. let mut addresses = vec![(lowered(&email.from), email.from.name.clone(), "from")]; addresses.extend(email.to.iter().map(|a| (lowered(a), a.name.clone(), "to"))); addresses.extend(email.cc.iter().map(|a| (lowered(a), a.name.clone(), "cc"))); addresses.extend(email.bcc.iter().map(|a| (lowered(a), a.name.clone(), "cc"))); Ok(EmailRow { id, external_id, thread_key: email.thread_key.clone(), thread_id, gmail_id: email.gmail.as_ref().map(|g| g.id.clone()), sent_at: email.sent_at.clone(), thread_subject: strip_reply_prefixes(&email.subject), addresses, data: Value::Object(data), }) } } /// A held Gmail message's state, as its labels now say. pub fn state_patch(labels: &[String]) -> Value { let state = email_state_from_labels(labels); json!({ "labels": labels, "unread": state.unread, "starred": state.starred, "in_inbox": state.in_inbox, "sync_state": "synced", }) } #[cfg(test)] mod tests { use super::super::mime::{decode, GmailFacts, MailFlags}; use super::*; const DB: &str = "00000000-0000-4000-8000-000000000001"; const MESSAGE: &[u8] = b"From: Ada Example \r\n\ To: owner@example.com, \"Bo\" \r\n\ Cc: Cy \r\n\ Subject: Re: Lunch\r\n\ Date: Mon, 5 Oct 2026 09:30:00 +0000\r\n\ Message-ID: \r\n\ References: \r\n\ MIME-Version: 1.0\r\n\ Content-Type: multipart/mixed; boundary=\"b\"\r\n\ \r\n\ --b\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ \r\n\ Noon works.\r\n\ \r\n\ On Sun, 4 Oct 2026 at 10:00, Owner wrote:\r\n\ > Lunch tomorrow?\r\n\ --b\r\n\ Content-Type: application/pdf; name=\"menu.pdf\"\r\n\ Content-Disposition: attachment; filename=\"menu.pdf\"\r\n\ \r\n\ PDFDATA\r\n\ --b--\r\n"; #[test] fn a_message_maps_to_the_exact_email_row() { let ids = Ids::new(DB); let mut decoded = decode(MESSAGE, "owner@example.com", &GmailFacts::default()).unwrap(); decoded.flags = Some(MailFlags { unread: true, starred: false }); let row = Page::new().email(&ids, &decoded).unwrap(); let external_id = message_id_external_id(Some("")).unwrap(); assert_eq!(row.external_id, external_id); assert_eq!(row.id, derived_id("cotton_emails", &[DB, &external_id])); assert_eq!(row.thread_key, "imap:root@example.org"); assert_eq!(row.thread_id, derived_id("cotton_email_threads", &[DB, "imap:root@example.org"])); assert_eq!(row.thread_subject, "Lunch"); assert_eq!( row.data, json!({ "thread_id": row.thread_id, "account": "owner@example.com", "external_id": external_id, "subject": "Re: Lunch", "from_email": "ada@example.org", "from_name": "Ada Example", "trashed_at": null, "unread": true, "starred": false, "recipients": [ { "email": "owner@example.com", "kind": "to" }, { "email": "bo@example.net", "name": "Bo", "kind": "to" }, { "email": "cy@example.com", "name": "Cy", "kind": "cc" } ], "sent_at": "2026-10-05T09:30:00.000Z", "body": "Noon works.", "snippet": "Noon works.", "attachments": [{ "name": "menu.pdf", "mime": "application/pdf", "size": 7 }] }) ); assert_eq!( row.addresses, vec![ ("ada@example.org".to_string(), Some("Ada Example".to_string()), "from"), ("owner@example.com".to_string(), None, "to"), ("bo@example.net".to_string(), Some("Bo".to_string()), "to"), ("cy@example.com".to_string(), Some("Cy".to_string()), "cc"), ] ); } #[test] fn a_gmail_message_carries_its_labels_and_state() { let ids = Ids::new(DB); let facts = GmailFacts { msgid: Some(255), thrid: Some(4096), labels: vec!["INBOX".into(), "UNREAD".into(), "Receipts".into()], received: None, }; let decoded = decode(MESSAGE, "owner@example.com", &facts).unwrap(); let row = Page::new().email(&ids, &decoded).unwrap(); assert_eq!(row.thread_key, "gmail:1000"); assert_eq!(row.gmail_id.as_deref(), Some("ff")); assert_eq!(row.data["gmail_id"], "ff"); assert_eq!(row.data["gmail_account"], "owner@example.com"); assert_eq!(row.data["labels"], json!(["INBOX", "UNREAD", "Receipts"])); assert_eq!(row.data["unread"], true); assert_eq!(row.data["in_inbox"], true); assert_eq!(row.data["starred"], false); assert_eq!(row.data["sync_state"], "synced"); assert_eq!(state_patch(&["STARRED".to_string()])["in_inbox"], false); } #[test] fn a_message_with_no_message_id_is_known_by_its_content() { let raw = b"From: a@example.org\r\nDate: Mon, 5 Oct 2026 09:30:00 +0000\r\nSubject: Hi\r\n\r\nSame words\r\n"; let ids = Ids::new(DB); let decoded = decode(raw, "me@example.com", &GmailFacts::default()).unwrap(); let mut page = Page::new(); let first = page.email(&ids, &decoded).unwrap(); let second = page.email(&ids, &decoded).unwrap(); assert!(first.external_id.starts_with("eml2:")); assert_ne!(first.external_id, second.external_id, "a second copy in one page is its own email"); assert_eq!(Page::new().email(&ids, &decoded).unwrap().id, first.id, "a re-read names the same row"); } }