Cotton code
331 lines · 15.9 KB · RustRaw
//! PERSON OR MACHINE: the one rule that splits a sender's mail between that//! person's conversation and the Mail tab (MAIL.md "Person or machine").//!//! The first step that answers wins://!//! 1. blocked: junk, shown nowhere for now (spam tools come later);//! 2. the owner said so on the sender's row: their verdict;//! 3. an email handle of someone in People: a person;//! 4. a machine-shaped sender: the address (noreply, bounce, a list, a role//!    mailbox, a bulk sender's domain) or the name ("Asha via Google Docs",//!    "Sarah from Acme", "The Acme Team"): a machine;//! 5. the owner has written to it (To, from one of their own addresses): a person;//! 6. machine-made mail: the sender's own words carry a bulk footer//!    (unsubscribe, "you are receiving this", "this is an automated message",//!    "do not reply"), the subject is a calendar's or a bounce's, or it went to//!    a list and not to the owner: a machine;//! 7. the old reader's word that it is a person (the thread's stored//!    `sender_kind`; its `service` was only "nothing said person", so it says nothing);//! 8. it looks like a person: a webmail address, or a person's full name that//!    the address is made of ("Wei Zhang" <wei.zhang@…>): a person;//! 9. otherwise a machine.//!//! The owner's own act (a block, a verdict, a People card) is above every//! guess; a shape the address has is above having written to it, so writing to//! a support desk never makes it a person. A person the rule finds at step 8//! is in the Mail tab's People, never in the chat list: only someone in People//! with a chat here has their mail in a conversation.//!//! The phone keeps no List-Id, List-Unsubscribe, Precedence or Auto-Submitted//! header (the Mac importer stores the body, the subject, the sender, the To and//! Cc): the words those headers stand beside are what step 6 reads, and only the//! sender's own words, never what they forwarded.use std::sync::OnceLock;use regex::Regex;/// What the rule says a sender is.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "lowercase")]pub enum Who {    Person,    Machine,    Junk,}impl Who {    pub fn as_str(self) -> &'static str {        match self {            Who::Person => "person",            Who::Machine => "machine",            Who::Junk => "junk",        }    }}/// Which step answered: said in tests and in a sender's details.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Why {    Blocked,    OwnerSaid,    InPeople,    MachineShaped,    WrittenTo,    MachineMade,    OldReader,    LooksPersonal,    Stranger,}/// What the phone knows of one address, and of the newest mail it sent.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Facts<'a> {    pub address: &'a str,    /// In `cotton_blocked_senders`.    pub blocked: bool,    /// The sender row's verdict when the owner decided it (`decided_by = owner`):    /// `person`, `service` or `junk`.    pub owner_verdict: Option<&'a str>,    /// An email handle of a person in People who is not archived.    pub in_people: bool,    /// The owner sent mail with this address in To.    pub written_to: bool,    /// The thread's stored `sender_kind` (the old reader's): `person`, `service`, `junk`.    pub stored_kind: Option<&'a str>,    /// The display name the sender's newest mail came with.    pub name: Option<&'a str>,    /// That mail's subject.    pub subject: Option<&'a str>,    /// That mail's words as the phone keeps them.    pub text: Option<&'a str>,    /// That mail went to a list's address ([`is_list_address`]) and to none of the owner's.    pub to_a_list: bool,}/// The rule.pub fn who(facts: &Facts<'_>) -> (Who, Why) {    if facts.blocked {        return (Who::Junk, Why::Blocked);    }    match facts.owner_verdict {        Some("person") => return (Who::Person, Why::OwnerSaid),        // Promotions is a machine he sorted himself (Senders 3: group.rs).        Some("service" | "promotions") => return (Who::Machine, Why::OwnerSaid),        Some("junk") => return (Who::Junk, Why::OwnerSaid),        _ => {}    }    if facts.in_people {        return (Who::Person, Why::InPeople);    }    let address = facts.address.trim().to_lowercase();    if is_machine_shaped(&address) || facts.name.is_some_and(is_machine_name) {        return (Who::Machine, Why::MachineShaped);    }    if facts.written_to {        return (Who::Person, Why::WrittenTo);    }    if facts.to_a_list || facts.subject.is_some_and(is_machine_subject) || facts.text.is_some_and(is_machine_text) {        return (Who::Machine, Why::MachineMade);    }    match facts.stored_kind {        Some("person") => return (Who::Person, Why::OldReader),        Some("service") if !looks_personal(&address, facts.name) => return (Who::Machine, Why::OldReader),        _ => {}    }    if looks_personal(&address, facts.name) {        return (Who::Person, Why::LooksPersonal);    }    (Who::Machine, Why::Stranger)}/// The mailboxes a company answers from rather than a person: their local/// part, whole or before a `-`, `_`, `.` or `+` ("billing-noreply",/// "news.letter" fold the same way).const ROLES: &[&str] = &[    "notifications", "notification", "notify", "alerts", "alert", "news", "newsletter", "newsletters", "info",    "support", "help", "helpdesk", "billing", "invoice", "invoices", "receipts", "receipt", "orders", "order",    "accounts", "account", "updates", "update", "marketing", "hello", "team", "contact", "service", "services",    "security", "admin", "mailer", "digest", "feedback", "care", "customercare", "customerservice", "statements",    "payments", "booking", "bookings", "reservations", "shipping", "delivery", "auto", "automated", "system",    "calendar", "jobs", "careers", "offers", "deals", "promo", "promotions", "rewards", "members", "community",    // Seen in the corpus (who_corpus.txt), each a mailbox no one person answers as themselves.    "tickets", "ticket", "confirmation", "confirmations", "reservation", "store", "shop", "sales", "ebill",    "bills", "statement", "reminder", "reminders", "invitations", "invitation", "invites", "invite", "announce",    "announcements", "notices", "notice", "reports", "report", "welcome", "survey", "surveys", "weekly", "daily",    "monthly", "boxoffice", "frontdesk", "giving", "donations", "events", "enquiries", "inquiries", "webmaster",    "verify", "verification", "membership", "subscriptions", "renewals", "policy", "claims", "loyalty", "mail",    "email",];/// Domains only bulk mail comes from: newsletter platforms and the senders shops/// and apps mail through. A domain is one of them, or ends with `.` and one.const BULK_DOMAINS: &[&str] = &[    "substack.com", "beehiiv.com", "buttondown.email", "ghost.io", "convertkit.com", "convertkit-mail.com",    "ck.page", "mailchimpapp.com", "mcsv.net", "mcdlv.net", "rsgsv.net", "list-manage.com", "sendgrid.net",    "amazonses.com", "mailgun.org", "mailgun.net", "sparkpostmail.com", "hubspotemail.net", "intercom-mail.com",    "mailerlite.com", "sendinblue.com", "klaviyomail.com", "customeriomail.com", "docusign.net", "createsend.com",    "cmail19.com", "cmail20.com", "exacttarget.com", "mktomail.com", "emarsys.net",];/// A label a bulk sender puts before its own domain ("email.shop.com",/// "news.paper.com"); any label but the last two. "mail." is left out: a/// university's people write from it.const BULK_LABELS: &[&str] = &[    "email", "e", "em", "news", "newsletter", "newsletters", "info", "marketing", "mailer", "mailing", "notify",    "notification", "notifications", "updates", "alerts", "txn", "transactional", "bounce", "bounces", "campaign",    "campaigns", "promo", "offers", "comms",];/// The mail people write from themselves: a domain anyone signs up at.const WEBMAIL: &[&str] = &[    "gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com", "msn.com", "yahoo.com", "ymail.com",    "rocketmail.com", "icloud.com", "me.com", "mac.com", "aol.com", "proton.me", "protonmail.com", "pm.me",    "gmx.com", "gmx.net", "gmx.de", "web.de", "yandex.com", "yandex.ru", "mail.ru", "zoho.com", "zohomail.com",    "fastmail.com", "fastmail.fm", "hey.com", "rediffmail.com", "tutanota.com", "tuta.io", "qq.com", "163.com",    "naver.com", "libero.it", "orange.fr", "free.fr", "btinternet.com", "comcast.net", "verizon.net", "att.net",    "sbcglobal.net",];/// Whether `domain` is a webmail domain anyone signs up at (gmail.com, outlook.com…): never one sender's own.pub fn is_webmail(domain: &str) -> bool {    let domain = domain.trim().to_lowercase();    domain_is(&domain, WEBMAIL) || domain.starts_with("hotmail.") || domain.starts_with("yahoo.") || domain.starts_with("outlook.")}fn domain_is(domain: &str, list: &[&str]) -> bool {    list.iter().any(|d| domain == *d || domain.strip_suffix(d).is_some_and(|head| head.ends_with('.')))}/// A list's own address: Google Groups, groups.io, a `lists.`/`list.` domain, a/// list's `-request` and `-owner`.pub fn is_list_address(address: &str) -> bool {    let address = address.trim().to_lowercase();    let Some((local, domain)) = address.rsplit_once('@') else {        return false;    };    local.ends_with("-request")        || local.ends_with("-owner")        || domain.starts_with("lists.")        || domain.starts_with("list.")        || domain == "googlegroups.com"        || domain.ends_with(".googlegroups.com")        || domain == "groups.io"}/// An address no person answers at: no-reply and bounce addresses, mailer/// daemons, lists, role mailboxes ([`ROLES`]) and bulk senders' domains/// ([`BULK_DOMAINS`], [`BULK_LABELS`]). The first half is the old reader's/// `is_machine_address` (cotton-tools `emails::kinds`), word for word.pub fn is_machine_shaped(address: &str) -> bool {    let address = address.trim().to_lowercase();    let Some((local, domain)) = address.rsplit_once('@') else {        return true;    };    let local = local.split('+').next().unwrap_or(local);    let squashed: String = local.chars().filter(char::is_ascii_alphanumeric).collect();    if squashed.contains("noreply")        || squashed.contains("donotreply")        || squashed.contains("dontreply")        || squashed == "mailerdaemon"        || squashed == "postmaster"        || local.contains("bounce")        || is_list_address(&address)    {        return true;    }    let labels: Vec<&str> = domain.split('.').collect();    if domain_is(domain, BULK_DOMAINS) || labels.iter().rev().skip(2).any(|label| BULK_LABELS.contains(label)) {        return true;    }    ROLES.contains(&squashed.as_str()) || local.split(['-', '_', '.']).next().is_some_and(|head| head != local && ROLES.contains(&head))}fn pattern(cell: &'static OnceLock<Regex>, source: &str) -> &'static Regex {    cell.get_or_init(|| Regex::new(source).expect("a literal pattern"))}/// A name a company or a service sends as: "Asha via Google Docs", "Sarah from/// Acme", "Mike at Notely", "Jake @ Fitbox", "The Acme Team", "Acme Support".pub fn is_machine_name(name: &str) -> bool {    static RE: OnceLock<Regex> = OnceLock::new();    pattern(        &RE,        r"(?i)(\s|\()via\s|\S\s+(from|at|@)\s+\S|\b(team|support|notifications?|newsletter|alerts|no-?reply|do not reply|mail delivery|customer (care|service))\b",    )    .is_match(name.trim())}/// A subject a calendar or a mail server writes: an invitation or its answer, a bounce.pub fn is_machine_subject(subject: &str) -> bool {    static RE: OnceLock<Regex> = OnceLock::new();    pattern(        &RE,        r"(?i)^\s*((updated )?invitation( updated)?|accepted|declined|tentatively accepted|cancell?ed( event)?|event cancell?ed|undeliverable|undelivered mail|delivery status notification|mail delivery failed|returned mail|delivery failure|failure notice|message not delivered)\b",    )    .is_match(subject)}/// The sender's own words: what stands before a forwarded or quoted original.pub fn own_words(text: &str) -> &str {    static RE: OnceLock<Regex> = OnceLock::new();    let cut = pattern(&RE, r"(?im)^\s*(-{2,}\s*(forwarded message|original message)\s*-{2,}|begin forwarded message:)");    cut.find(text).map_or(text, |m| &text[..m.start()])}/// Words that only bulk or automated mail carries: an unsubscribe or/// preferences footer, "you are receiving this", "view in browser", "this is an/// automated message", "do not reply", a copyright line, a calendar's footer,/// "Dear Customer". Read in the sender's own words only ([`own_words`]), so a/// friend forwarding a newsletter stays a friend.pub fn is_machine_text(text: &str) -> bool {    static RE: OnceLock<Regex> = OnceLock::new();    pattern(        &RE,        concat!(            r"(?i)unsubscribe|\bopt[- ]?out\b|\breply stop\b",            r"|manage (your )?((e-?mail|notification|communication|newsletter|subscription|mailing|marketing) )?(preferences|settings|subscriptions?|newsletters|notifications)",            r"|update (your )?((e-?mail|subscription|communication|notification) )?preferences",            r"|(e-?mail|notification|communication|subscription) (preferences|settings)",            r"|view (this |it |the )?(e-?mail |message |newsletter )?(in|on) (your |a |the )?(web )?browser|view it on github|\bread in app\b",            r"|you('re| are) receiving this|you (have )?received this (e-?mail|message|notification)",            r"|this (e-?mail|message|notification) (was|is|has been) sent (to|by|because)|you('re| are) (on the \w+ list|subscribed to)",            r"|\b(automated|automatic|auto-generated|automatically generated|system[- ]generated|computer[- ]generated) (message|e-?mail|mail|notification|receipt|reminder|alert)s?",            r"|(created|generated) automatically|automatically generated",            r"|(please )?do not reply|(don't|please don't) reply to this|(replies|responses) to this (e-?mail|message|address) (are|is) not monitored|(mailbox|inbox|address) is not monitored",            r"|all rights reserved|©\s*(19|20)\d\d|invitation from google calendar",            r"|\bdear (valued )?(customer|guest|patient|member|user|subscriber|client|policyholder|cardholder|account holder|sir|madam)s?\b",        ),    )    .is_match(own_words(text))}/// Whether an address reads as one person's own: a webmail mailbox, or a/// person's name of two words or more that the address is made of (a first or/// last name in it, or an initial and the last name).pub fn looks_personal(address: &str, name: Option<&str>) -> bool {    let address = address.trim().to_lowercase();    let Some((local, domain)) = address.rsplit_once('@') else {        return false;    };    if domain_is(domain, WEBMAIL) || domain.starts_with("hotmail.") || domain.starts_with("yahoo.") || domain.starts_with("outlook.") {        return true;    }    let Some(name) = name else { return false };    let words: Vec<String> = name        .split(|c: char| c.is_whitespace() || c == ',')        .map(|w| w.trim_matches(|c: char| !c.is_alphabetic()).to_lowercase())        .filter(|w| !w.is_empty())        .collect();    if words.len() < 2 || name.chars().any(|c| c.is_ascii_digit()) {        return false;    }    // Letters only: "marcus.brown2" is made of Marcus Brown as much as "marcus.brown" is.    let squashed: String = local.chars().filter(char::is_ascii_alphabetic).collect();    let (first, last) = (words[0].as_str(), words[words.len() - 1].as_str());    let (fi, li) = (first.chars().next().unwrap_or_default(), last.chars().next().unwrap_or_default());    // The whole first name, both names, or a name and the other's initial: "diego", "markellis", "pnovak",    // "ahmedh". A word of the name merely inside the address is not enough ("Credit Card" <cards@…>).    squashed == first        || (squashed.contains(first) && squashed.contains(last))        || squashed == format!("{fi}{last}")        || squashed == format!("{first}{li}")}#[cfg(test)]#[path = "who_tests.rs"]mod tests;#[cfg(test)]#[path = "who_corpus_tests.rs"]mod corpus;