Cotton code
294 lines · 10.6 KB · RustRaw
//! A raw RFC 5322 message, as IMAP hands it over, → the email the mapper//! turns into rows, field for field as the old ingest received it.//!//! Copied from `cotton-server`'s `mailbox::mime` (that crate retires on its//! own), with the ingest argument it built replaced by [`Decoded`].use mail_parser::{Address, MessageParser, MimeHeaders};use super::text::{html_to_text, refused_label};/// What Gmail's IMAP says about one message, beside its bytes.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct GmailFacts {    /// X-GM-MSGID, decimal on the wire.    pub msgid: Option<u64>,    /// X-GM-THRID.    pub thrid: Option<u64>,    /// The API's label ids, already mapped (the Mac's `labels::api_labels`).    pub labels: Vec<String>,    /// When the mailbox received the message (IMAP INTERNALDATE), in    /// milliseconds: its date when the `Date` header is not believable.    pub received: Option<i64>,}/// The API's id for a message or thread is X-GM-MSGID / X-GM-THRID in hex —/// the same 64-bit number, so a row the old OAuth path wrote and one this/// path writes carry the same `gmail_id` and the same `gmail:<thread>` key.pub fn api_id(decimal: u64) -> String {    format!("{decimal:x}")}#[derive(Debug, Clone, PartialEq, Eq)]pub struct MailAddress {    pub email: String,    pub name: Option<String>,}#[derive(Debug, Clone, PartialEq, Eq)]pub struct MailAttachment {    pub name: String,    pub mime: Option<String>,    pub size: Option<i64>,}/// Gmail's identity and labels for a message read from Gmail.#[derive(Debug, Clone, PartialEq, Eq)]pub struct GmailBlock {    pub id: String,    pub account: String,    pub labels: Vec<String>,}/// IMAP's `\Seen` and `\Flagged`, for a server without Gmail's labels.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct MailFlags {    pub unread: bool,    pub starred: bool,}impl MailFlags {    pub fn of(flags: &[String]) -> MailFlags {        let has = |name: &str| flags.iter().any(|f| f.eq_ignore_ascii_case(name));        MailFlags {            unread: !has("\\Seen"),            starred: has("\\Flagged"),        }    }}/// One message, decoded.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Decoded {    /// `gmail:<hex thread id>` or `imap:<root message id>`.    pub thread_key: String,    pub subject: String,    /// ISO-8601 with milliseconds.    pub sent_at: String,    /// The body as read (plain text, else HTML as text), before storage cuts it.    pub body: String,    /// The header's Message-ID with its angle brackets.    pub message_id: Option<String>,    pub gmail: Option<GmailBlock>,    pub account: String,    pub flags: Option<MailFlags>,    pub from: MailAddress,    pub to: Vec<MailAddress>,    pub cc: Vec<MailAddress>,    pub bcc: Vec<MailAddress>,    pub attachments: Vec<MailAttachment>,}/// Why a message is not archived.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Skip {    /// SPAM, TRASH, DRAFT or CHAT.    Refused(&'static str),    Missing,    NoDate,    NoSender,}/// Decode one message. `account` is the mailbox address; with Gmail facts the/// email carries the `gmail` block exactly as the API path filled it.////// A server without X-GM gives no thread id; the conversation is then keyed by/// the first message of its `References` chain (else `In-Reply-To`, else the/// message's own id), which every reply in it names.pub fn decode(raw: &[u8], account: &str, facts: &GmailFacts) -> Result<Decoded, Skip> {    if let Some(label) = refused_label(&facts.labels) {        return Err(Skip::Refused(label));    }    let message = MessageParser::default().parse(raw).ok_or(Skip::Missing)?;    let sent_at = super::mail_date::sent_ms(message.date().map(|date| date.to_timestamp() * 1000), facts.received)        .and_then(crate::js::to_iso_string)        .ok_or(Skip::NoDate)?;    let from = addresses(message.from()).into_iter().next().ok_or(Skip::NoSender)?;    let body = match message.body_text(0).filter(|_| {        message.text_body.first().is_some_and(|&i| {            message                .part(i)                .is_some_and(|part| part.is_text() && !part.is_text_html())        })    }) {        Some(plain) => plain.into_owned(),        None => message.body_html(0).map(|html| html_to_text(&html)).unwrap_or_default(),    };    let attachments = message        .attachments()        .map(|part| MailAttachment {            name: part.attachment_name().unwrap_or("attachment").to_string(),            mime: part.content_type().map(|ct| match ct.subtype() {                Some(sub) => format!("{}/{sub}", ct.ctype()),                None => ct.ctype().to_string(),            }),            size: i64::try_from(part.len()).ok(),        })        .collect();    let thread_key = match facts.thrid {        Some(thrid) => format!("gmail:{}", api_id(thrid)),        None => {            let root = message                .references()                .as_text_list()                .and_then(|ids| ids.first().map(|id| id.to_string()))                .or_else(|| message.in_reply_to().as_text().map(str::to_string))                .or_else(|| message.message_id().map(str::to_string))                .unwrap_or_else(|| format!("{}|{}", from.email, message.subject().unwrap_or_default()));            format!(                "imap:{}",                crate::fingerprint::email::normalize_message_id(&root)            )        }    };    Ok(Decoded {        thread_key,        subject: message.subject().unwrap_or_default().to_string(),        sent_at,        body,        // Angle brackets back on: the header's own text, which the identity        // normalises either way.        message_id: message.message_id().map(|id| format!("<{id}>")),        gmail: facts.msgid.map(|msgid| GmailBlock {            id: api_id(msgid),            account: account.to_string(),            labels: facts.labels.clone(),        }),        account: account.to_string(),        flags: None,        from,        to: addresses(message.to()),        cc: addresses(message.cc()),        bcc: addresses(message.bcc()),        attachments,    })}fn addresses(address: Option<&Address<'_>>) -> Vec<MailAddress> {    let Some(address) = address else {        return Vec::new();    };    address        .iter()        .filter_map(|addr| {            let email = addr.address.as_deref()?.trim().to_string();            if email.is_empty() {                return None;            }            Some(MailAddress {                email,                name: addr                    .name                    .as_deref()                    .map(str::trim)                    .filter(|name| !name.is_empty())                    .map(str::to_string),            })        })        .collect()}#[cfg(test)]mod tests {    use super::*;    const PLAIN: &[u8] = b"From: Ada Example <ada@example.org>\r\n\To: owner@example.com, \"Bo\" <bo@example.net>\r\n\Subject: =?UTF-8?Q?Caf=C3=A9_tomorrow?=\r\n\Date: Mon, 5 Oct 2026 09:30:00 +0000\r\n\Message-ID: <abc.123@example.org>\r\n\Content-Type: text/plain; charset=utf-8\r\n\\r\n\See you at ten.\r\n";    /// The API's id for a message is X-GM-MSGID in hex. If this drifted, every    /// message already imported would be read again as new.    #[test]    fn gmail_ids_are_the_apis_hex_and_the_thread_key_is_the_apis() {        assert_eq!(api_id(1_278_455_344_230_334_865), "11bdfc5cae0c8191");        let facts = GmailFacts {            msgid: Some(1_278_455_344_230_334_865),            thrid: Some(1_266_894_439_832_287_888),            labels: vec!["INBOX".into()],            received: None,        };        let email = decode(PLAIN, "owner@example.com", &facts).expect("decodes");        assert_eq!(email.thread_key, format!("gmail:{}", api_id(1_266_894_439_832_287_888)));        let gmail = email.gmail.expect("the gmail block");        assert_eq!(gmail.id, "11bdfc5cae0c8191");        assert_eq!(gmail.account, "owner@example.com");        assert_eq!(email.message_id.as_deref(), Some("<abc.123@example.org>"));        assert_eq!(email.subject, "Café tomorrow");        assert_eq!(email.from.email, "ada@example.org");        assert_eq!(email.from.name.as_deref(), Some("Ada Example"));        assert_eq!(email.to.len(), 2);        assert_eq!(email.sent_at, "2026-10-05T09:30:00.000Z");        assert_eq!(email.body.trim(), "See you at ten.");    }    #[test]    fn spam_trash_and_drafts_are_refused_as_the_api_path_refuses_them() {        for label in ["SPAM", "TRASH", "DRAFT"] {            let facts = GmailFacts {                labels: vec![label.into()],                ..GmailFacts::default()            };            assert!(decode(PLAIN, "owner@example.com", &facts).is_err());        }    }    #[test]    fn an_html_only_message_reads_as_text_and_a_server_without_thread_ids_keys_by_references() {        let raw = b"From: shop@example.org\r\n\Date: Mon, 5 Oct 2026 09:30:00 +0000\r\n\Subject: Receipt\r\n\Content-Type: text/html\r\n\\r\n\<p>Total <b>12.00</b></p>\r\n";        let email = decode(raw, "me@example.com", &GmailFacts::default()).expect("ok");        assert!(email.body.contains("Total"));        assert!(!email.body.contains('<'));        assert!(email.thread_key.starts_with("imap:"));        assert!(email.gmail.is_none());        let reply = b"From: bo@example.net\r\n\Date: Mon, 5 Oct 2026 10:00:00 +0000\r\n\Message-ID: <r2@example.net>\r\n\In-Reply-To: <r1@example.org>\r\n\References: <root@example.org> <r1@example.org>\r\n\\r\n\ok\r\n";        let email = decode(reply, "me@example.com", &GmailFacts::default()).expect("ok");        assert_eq!(email.thread_key, "imap:root@example.org");    }    /// RULE: A message whose `Date` header carries a year outside 1900–2100 is dated by its mailbox's INTERNALDATE, and with none it is not ingested with a date at all — never drawn in the wrong century (14 Oct 2026: a Google notice read "Mon 16 Sep 2611").    #[test]    fn a_header_in_the_wrong_century_takes_the_mailboxs_receipt_time() {        let raw = b"From: Google <no-reply@accounts.example.com>\r\n\Date: Mon, 16 Sep 2611 18:03:30 +0000\r\n\Subject: Access will expire soon\r\n\\r\n\Synthetic.\r\n";        let received = chrono::DateTime::parse_from_rfc3339("2024-09-16T18:03:31Z")            .unwrap()            .timestamp_millis();        let facts = GmailFacts { received: Some(received), ..GmailFacts::default() };        let email = decode(raw, "me@example.com", &facts).expect("dated by the mailbox");        assert_eq!(email.sent_at, "2024-09-16T18:03:31.000Z");        assert!(decode(raw, "me@example.com", &GmailFacts::default()).is_err(), "no believable date, no slip");    }}