Cotton code
507 lines · 21.6 KB · RustRaw
//! Everyone who writes to him (owner, 24 Nov 2026; `assets/design/chat/SENDERS.md`): one ranked list of the//! senders of his WhatsApp, SMS and mail, each a number or an address (an SMS short code by its name), how much they//! sent and whether he ever replied; Block and Delete everything, each said with its count first; and a blocked//! sender's Blocked place, where what they sent waits 30 days before it is erased.//!//! The rules and words are here; the phone's copy is read by `cotton-ffi` (`phone/chat_senders.rs`).use serde::Serialize;use super::list::say;pub use crate::mail::group::Group;use super::shapes::FanTile;use crate::rules::shell_lines::LineSet;/// Days what sits in Blocked is kept before it is erased.pub const BLOCKED_DAYS: i64 = 30;/// What a sender's key is.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]#[serde(rename_all = "lowercase")]pub enum KeyKind {    /// A phone number, `+` and its international digits.    Number,    /// A mail address, lower case.    Address,    /// An SMS sender with a name and no number (a short code), by its name.    Name,}impl KeyKind {    pub fn id(self) -> &'static str {        match self {            KeyKind::Number => "number",            KeyKind::Address => "address",            KeyKind::Name => "name",        }    }}/// Who a sender is, across every channel: one number, one address or one short-code name.#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct SenderKey {    pub key: String,    pub kind: KeyKind,}/// The key of a chat's sender, from its number or its name: a number by its international form, else the name an/// SMS short code goes by ([`short_code`]). `None` for nothing usable.pub fn key_of_sender(raw: &str) -> Option<SenderKey> {    let raw = raw.trim();    if raw.is_empty() {        return None;    }    if raw.contains('@') {        return key_of_address(raw);    }    if let Some(number) = cotton_rules::phone::normalize_phone(raw) {        return Some(SenderKey { key: format!("+{number}"), kind: KeyKind::Number });    }    short_code(raw).map(|key| SenderKey { key, kind: KeyKind::Name })}/// A mail sender's key: the address, lower case, without spaces.pub fn key_of_address(raw: &str) -> Option<SenderKey> {    let address: String = raw.trim().to_lowercase().chars().filter(|c| !c.is_whitespace()).collect();    (address.contains('@') && address.len() > 2).then_some(SenderKey { key: address, kind: KeyKind::Address })}/// The name an SMS sender with no number goes by: without its two-letter prefix (the carrier and circle, `VM-`)/// and its one-letter suffix (the kind of message, `-S`, `-T`, `-P`, `-G`), upper case. `VM-HDFCBK-S`, `AD-HDFCBK`/// and `HDFCBK` are one sender, `HDFCBK`. `None` when nothing is left.pub fn short_code(raw: &str) -> Option<String> {    let parts: Vec<&str> = raw.trim().split('-').map(str::trim).filter(|p| !p.is_empty()).collect();    let mut kept: &[&str] = &parts;    if kept.len() >= 2 && kept[0].len() == 2 && kept[0].chars().all(|c| c.is_ascii_alphabetic()) {        kept = &kept[1..];    }    if kept.len() >= 2 && kept[kept.len() - 1].len() == 1 && kept[kept.len() - 1].chars().all(|c| c.is_ascii_alphabetic()) {        kept = &kept[..kept.len() - 1];    }    let name = kept.join("-").to_uppercase();    (!name.is_empty()).then_some(name)}/// The channels the list draws from, in the chips' order.pub const CHANNELS: [&str; 3] = ["whatsapp", "sms", "mail"];/// One channel's share of a sender, as the phone's copy counts it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Tally {    pub key: SenderKey,    /// `whatsapp`, `sms` or `mail`.    pub channel: String,    /// The best name this channel knows them by (a person in People, the chat's or the mail's name).    pub name: Option<String>,    /// Messages or mails they sent him there.    pub sent: u32,    /// Whether he ever wrote to them there.    pub replied: bool,    /// Their newest message there.    pub last_at: Option<String>,}/// One sender, every channel together.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Sender {    pub key: SenderKey,    pub name: Option<String>,    /// In [`CHANNELS`]' order.    pub channels: Vec<String>,    pub sent: u32,    pub replied: bool,    pub last_at: Option<String>,}/// Every sender from the channels' tallies: one per key, the counts added, replied if he replied anywhere, the name of/// the channel that sent most (a person in People wins: the phone names a tally by them first). Ranked ([`rank`]).pub fn senders_of(tallies: Vec<Tally>) -> Vec<Sender> {    let mut by_key: std::collections::BTreeMap<SenderKey, (Sender, u32)> = std::collections::BTreeMap::new();    for t in tallies {        let entry = by_key.entry(t.key.clone()).or_insert_with(|| (Sender { key: t.key.clone(), name: None, channels: Vec::new(), sent: 0, replied: false, last_at: None }, 0));        let (sender, named_by) = entry;        sender.sent += t.sent;        sender.replied |= t.replied;        if !sender.channels.contains(&t.channel) {            sender.channels.push(t.channel.clone());        }        if t.last_at > sender.last_at {            sender.last_at = t.last_at.clone();        }        if let Some(name) = t.name.filter(|n| !n.trim().is_empty()) {            if sender.name.is_none() || t.sent > *named_by {                sender.name = Some(name);                *named_by = t.sent;            }        }    }    let mut out: Vec<Sender> = by_key        .into_values()        .map(|(mut s, _)| {            s.channels.sort_by_key(|c| CHANNELS.iter().position(|k| k == c).unwrap_or(CHANNELS.len()));            s        })        .filter(|s| s.sent > 0)        .collect();    rank(&mut out);    out}/// The default order: those he never replied to first, then the most sent, then the newest, then by key.pub fn rank(senders: &mut [Sender]) {    senders.sort_by(|a, b| {        a.replied            .cmp(&b.replied)            .then(b.sent.cmp(&a.sent))            .then(b.last_at.cmp(&a.last_at))            .then(a.key.cmp(&b.key))    });}/// Which senders the list shows: all, or those of one channel.pub fn keeps(filter: &str, sender: &Sender) -> bool {    filter == "all" || sender.channels.iter().any(|c| c == filter)}/// The chips above the list: All, then each channel any sender came by, with how many senders.pub fn filters(lines: &LineSet, senders: &[Sender], on: &str) -> Vec<FanTile> {    let mut chips = vec![FanTile { id: "all".into(), label: say(lines, "app.senders.filter.all", &[]), count: None, on: on == "all" }];    for channel in CHANNELS {        let n = senders.iter().filter(|s| s.channels.iter().any(|c| c == channel)).count() as u32;        if n > 0 {            chips.push(FanTile { id: channel.into(), label: say(lines, &format!("app.senders.filter.{channel}"), &[]), count: Some(n), on: on == channel });        }    }    chips}/// A sender's name as the list says it: the name, else the number, address or short code itself.pub fn name_of(sender: &Sender) -> String {    sender.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or_else(|| sender.key.key.clone())}/// "214 messages", "1 message".pub fn sent_line(lines: &LineSet, sent: u32) -> String {    if sent == 1 {        say(lines, "app.senders.sent_one", &[])    } else {        say(lines, "app.senders.sent", &[("n", &sent.to_string())])    }}/// One row of the list.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct SenderRow {    /// The sender's key: what Block, Delete everything and Unblock name.    pub key: String,    pub kind: KeyKind,    pub name: String,    /// The number, address or short code under the name, when the name is another.    #[serde(skip_serializing_if = "Option::is_none")]    pub handle: Option<String>,    pub channels: Vec<String>,    /// The channels as words: "WhatsApp · SMS".    #[serde(rename = "channelsLine")]    pub channels_line: String,    pub sent: u32,    #[serde(rename = "sentLine")]    pub sent_line: String,    pub replied: bool,    /// "You replied" or "Never replied".    #[serde(rename = "repliedLine")]    pub replied_line: String,    #[serde(rename = "lastAt", skip_serializing_if = "Option::is_none")]    pub last_at: Option<String>,    /// The long-press acts, in order: Block, Delete everything (each asks first with its count, `chat.sender.ask`),    /// and for a mail sender Move to Trash in your mail (`chat.mail.sender`).    pub hold: Vec<HoldAct>,}/// A long-press act.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct HoldAct {    pub id: String,    pub label: String,}pub fn channels_line(lines: &LineSet, channels: &[String]) -> String {    channels.iter().map(|c| say(lines, &format!("app.senders.channel.{c}"), &[])).collect::<Vec<_>>().join(" · ")}pub fn row(lines: &LineSet, sender: &Sender) -> SenderRow {    let name = name_of(sender);    SenderRow {        key: sender.key.key.clone(),        kind: sender.key.kind,        handle: (name != sender.key.key).then(|| sender.key.key.clone()),        name,        channels: sender.channels.clone(),        channels_line: channels_line(lines, &sender.channels),        sent: sender.sent,        sent_line: sent_line(lines, sender.sent),        replied: sender.replied,        replied_line: say(lines, if sender.replied { "app.senders.replied" } else { "app.senders.never" }, &[]),        last_at: sender.last_at.clone(),        hold: {            let mut acts = vec![                HoldAct { id: "block".into(), label: say(lines, "app.senders.hold.block", &[]) },                HoldAct { id: "delete".into(), label: say(lines, "app.senders.hold.delete", &[]) },            ];            // A mail sender's mail can also go to Trash at the provider: the act opens            // `chat.mail.sender { address: key }`, which counts on the Mac first (CONTRACT.md "Mail to Trash").            if sender.key.kind == KeyKind::Address && sender.channels.iter().any(|c| c == "mail") {                acts.push(HoldAct { id: "trash".into(), label: say(lines, "app.senders.hold.trash", &[]) });            }            acts        },    }}// ── Senders 3: the Senders tab (SENDERS.md "DECIDED: Senders 3") ─────────────────────────────────────────────/// The groups the tab's chips choose, in order, after All.pub const GROUPS: [Group; 3] = [Group::People, Group::Notices, Group::Promotions];/// A mail sender's domain, when it is one sender's own: `None` for a webmail address (each stands alone), a number/// or a short code.pub fn domain_of(key: &SenderKey) -> Option<String> {    if key.kind != KeyKind::Address {        return None;    }    let (_, domain) = key.key.rsplit_once('@')?;    (!domain.is_empty() && !crate::mail::who::is_webmail(domain)).then(|| domain.to_string())}/// The key a domain's row goes by: `@` and the domain.pub fn domain_key(domain: &str) -> String {    format!("@{domain}")}/// An SMS sender's group by its name alone: a short code is a business; India's `-P` suffix marks promotions./// A number is a person until his own verdict says otherwise.pub fn chat_group(key: &SenderKey, raw_name: Option<&str>) -> Group {    match key.kind {        KeyKind::Name if raw_name.is_some_and(|n| n.trim().to_uppercase().ends_with("-P")) => Group::Promotions,        KeyKind::Name => Group::Notices,        _ => Group::People,    }}/// Senders joined by hand: each `(member, into)` adds the member's counts and channels to `into`'s row, which keeps/// its own key and name (its name only if it has none). A member whose `into` is not here stands alone. Answers the/// senders, ranked again, and each kept key's members, in lower case.pub fn merged(senders: Vec<Sender>, merges: &[(String, String)]) -> (Vec<Sender>, std::collections::HashMap<String, Vec<String>>) {    use std::collections::HashMap;    let into_of: HashMap<String, String> = merges.iter().map(|(m, i)| (m.to_lowercase(), i.to_lowercase())).filter(|(m, i)| m != i).collect();    let present: std::collections::HashSet<String> = senders.iter().map(|s| s.key.key.to_lowercase()).collect();    let mut kept: Vec<Sender> = Vec::new();    let mut absorbed: Vec<(String, Sender)> = Vec::new();    for s in senders {        let k = s.key.key.to_lowercase();        match into_of.get(&k) {            // Not a chain: a member of a member stands with its own row.            Some(into) if present.contains(into) && !into_of.contains_key(into) => absorbed.push((into.clone(), s)),            _ => kept.push(s),        }    }    let mut members: HashMap<String, Vec<String>> = HashMap::new();    for (into, m) in absorbed {        let Some(target) = kept.iter_mut().find(|s| s.key.key.to_lowercase() == into) else { continue };        target.sent += m.sent;        target.replied |= m.replied;        if m.last_at > target.last_at {            target.last_at = m.last_at.clone();        }        for c in &m.channels {            if !target.channels.contains(c) {                target.channels.push(c.clone());            }        }        target.channels.sort_by_key(|c| CHANNELS.iter().position(|k| k == c).unwrap_or(CHANNELS.len()));        if target.name.is_none() {            target.name = m.name.clone();        }        members.entry(into).or_default().push(m.key.key.to_lowercase());    }    for list in members.values_mut() {        list.sort();    }    rank(&mut kept);    (kept, members)}/// A merged row's group: People if any of it is a person, else its own.pub fn group_with(own: Option<Group>, members: &[Option<Group>]) -> Option<Group> {    if own == Some(Group::People) || members.contains(&Some(Group::People)) {        return Some(Group::People);    }    own.or_else(|| members.iter().flatten().next().copied())}/// The tab's chips: All, then People, Notices and Promotions with how many senders each holds (a chip with none/// stays, so the row does not move as mail lands).pub fn group_filters(lines: &LineSet, groups: &[Option<Group>], on: &str) -> Vec<FanTile> {    let mut chips = vec![FanTile { id: "all".into(), label: say(lines, "app.senders.filter.all", &[]), count: Some(groups.len() as u32), on: on == "all" }];    for g in GROUPS {        let n = groups.iter().filter(|x| **x == Some(g)).count() as u32;        chips.push(FanTile { id: g.as_str().into(), label: say(lines, &format!("app.senders.filter.{}", g.as_str()), &[]), count: Some(n), on: on == g.as_str() });    }    chips}/// One row of the Senders tab: a sender, or a domain holding two or more of them.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct TabRow {    /// `domain` or `sender`.    pub level: &'static str,    #[serde(flatten)]    pub row: SenderRow,    #[serde(skip_serializing_if = "Option::is_none")]    pub group: Option<&'static str>,    /// A domain's addresses, how many.    #[serde(skip_serializing_if = "Option::is_none")]    pub addresses: Option<u32>,    /// The keys joined into this row by hand.    #[serde(skip_serializing_if = "Vec::is_empty")]    pub merged: Vec<String>,}/// A merged row's line under its name: "With +91 98450 12345".fn merged_handle(lines: &LineSet, row: &SenderRow, members: &[String]) -> Option<String> {    if members.is_empty() {        return row.handle.clone();    }    Some(say(lines, "app.senders.merged", &[("who", &members.join(", "))]))}/// The tab's rows, in rank order: each mail domain with two or more senders as one row in the place of its first/// (`by_domain`), every other sender as its own. `groups` and `members` are by key in lower case.pub fn tab_rows(lines: &LineSet, senders: &[&Sender], groups: &std::collections::HashMap<String, Option<Group>>, members: &std::collections::HashMap<String, Vec<String>>, by_domain: bool) -> Vec<TabRow> {    use std::collections::HashMap;    let mut domains: HashMap<String, Vec<&Sender>> = HashMap::new();    if by_domain {        for s in senders {            if let Some(d) = domain_of(&s.key) {                domains.entry(d).or_default().push(s);            }        }    }    let mut out = Vec::new();    let mut drawn: std::collections::HashSet<String> = std::collections::HashSet::new();    for s in senders {        let k = s.key.key.to_lowercase();        let group = groups.get(&k).copied().flatten();        let held = members.get(&k).cloned().unwrap_or_default();        match domain_of(&s.key).filter(|d| domains.get(d).is_some_and(|all| all.len() >= 2)) {            Some(domain) => {                if !drawn.insert(domain.clone()) {                    continue;                }                let all = &domains[&domain];                let sent: u32 = all.iter().map(|x| x.sent).sum();                let replied = all.iter().any(|x| x.replied);                let mut channels: Vec<String> = Vec::new();                for x in all {                    for c in &x.channels {                        if !channels.contains(c) {                            channels.push(c.clone());                        }                    }                }                let n = all.len() as u32;                let its: Vec<Option<Group>> = all.iter().map(|x| groups.get(&x.key.key.to_lowercase()).copied().flatten()).collect();                let first = its.first().copied().flatten();                let shared = its.iter().all(|g| *g == first).then_some(first).flatten();                out.push(TabRow {                    level: "domain",                    row: SenderRow {                        key: domain_key(&domain),                        kind: KeyKind::Address,                        name: domain.clone(),                        handle: Some(say(lines, "app.senders.addresses", &[("n", &n.to_string())])),                        channels_line: channels_line(lines, &channels),                        channels,                        sent,                        sent_line: sent_line(lines, sent),                        replied,                        replied_line: say(lines, if replied { "app.senders.replied" } else { "app.senders.never" }, &[]),                        last_at: all.iter().filter_map(|x| x.last_at.clone()).max(),                        hold: sender_acts(lines, true, true),                    },                    group: shared.map(Group::as_str),                    addresses: Some(n),                    merged: Vec::new(),                });            }            None => {                let mut built = row(lines, s);                built.hold = sender_acts(lines, s.channels.iter().any(|c| c == "mail"), false);                built.hold.push(HoldAct { id: "merge".into(), label: say(lines, "app.senders.hold.merge", &[]) });                if !held.is_empty() {                    built.hold.push(HoldAct { id: "part".into(), label: say(lines, "app.senders.hold.part", &[]) });                }                built.handle = merged_handle(lines, &built, &held);                out.push(TabRow { level: "sender", row: built, group: group.map(Group::as_str), addresses: None, merged: held });            }        }    }    out}/// What an act asks before it runs: the count first, always.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Ask {    pub act: String,    pub key: String,    pub count: u32,    pub title: String,    pub line: String,    /// The button that runs it.    pub confirm: String,    pub cancel: String,}/// The acts a whole sender takes (`chat.sender.ask`, then `chat.sender.act` with the count it showed).pub const ASKED: [&str; 4] = ["block", "delete", "archive", "unsubscribe"];/// The long-press of a whole sender on the Senders tab and their page, in order: Block, Delete everything, and for/// one who sends mail, Archive everything and Unsubscribe (SENDERS.md "Acts"). A domain is a mail sender always, and/// takes the same acts.pub fn sender_acts(lines: &LineSet, mail: bool, domain: bool) -> Vec<HoldAct> {    let act = |id: &str| HoldAct { id: id.into(), label: say(lines, &format!("app.senders.hold.{id}"), &[]) };    let mut acts = vec![act("block"), act("delete")];    if mail || domain {        acts.push(act("archive"));        acts.push(act("unsubscribe"));    }    acts}/// Block or Delete everything, asked with how much it takes. `ios_sms`: some of it is SMS on an iPhone, where/// nothing can be done at the source, and the ask says so.pub fn ask(lines: &LineSet, act: &str, key: &str, name: &str, count: u32, ios_sms: bool) -> Ask {    let n = count.to_string();    let what = sent_line(lines, count);    let fills: [(&str, &str); 3] = [("name", name), ("n", &n), ("what", &what)];    let (title, line, confirm) = match act {        "block" => ("app.senders.ask.block_title", "app.senders.ask.block_line", "app.senders.ask.block"),        "archive" => ("app.senders.ask.archive_title", "app.senders.ask.archive_line", "app.senders.ask.archive"),        "unsubscribe" => ("app.senders.ask.unsubscribe_title", "app.senders.ask.unsubscribe_line", "app.senders.ask.unsubscribe"),        _ => ("app.senders.ask.delete_title", "app.senders.ask.delete_line", "app.senders.ask.delete"),    };    let mut said = say(lines, line, &fills);    if ios_sms {        said = format!("{said} {}", say(lines, "app.senders.ask.ios_sms", &[]));    }    Ask { act: act.into(), key: key.into(), count, title: say(lines, title, &fills), line: said, confirm: say(lines, confirm, &fills), cancel: say(lines, "app.senders.ask.cancel", &[]) }}/// When what a blocked sender sent is erased: [`BLOCKED_DAYS`] after it came into Blocked, which is when they were/// blocked, or when it arrived if that was later. Milliseconds.pub fn erased_at(blocked_ms: i64, sent_ms: i64) -> i64 {    blocked_ms.max(sent_ms) + BLOCKED_DAYS * 86_400_000}#[cfg(test)]#[path = "senders_tests.rs"]mod tests;