//! A whole sender's acts (SENDERS.md "DECIDED: Senders 3", "Acts"; step 5): Block, Archive everything and //! Unsubscribe, on one sender with those merged into them by hand, or on every sender at a domain (`@domain`). Each //! is asked first with its count (`chat.sender.ask`), and the Mac's half shows on the row as the WhatsApp acts' does //! (queued, done, failed with Retry). //! //! - **Block**: each of their keys, as Block on one sender does (a mail address through mail's own block, its mail to //! Junk). A domain blocks the addresses it holds now; an address that first writes later is not blocked by it. //! - **Archive everything**: their mail leaves every list here (`archived_at`, kept), and one `sender_archive` row per //! address asks the Mac to take everything from that address out of the Inbox (it stays in All Mail). //! - **Unsubscribe**: one `unsubscribe` row per address, on their newest mail that offers it (else their newest): the //! Mac's one-click unsubscribe, or its trash-on-arrival when they offer none. use std::collections::HashMap; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use cotton_core::messages::app::list::{self, say}; use cotton_core::messages::app::senders::{self as rule, KeyKind, SenderKey}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::{common::update_row, tables}; use super::{everyone_in, merge_rows, rows, s, stored_key, ws, SourceAct, EMAILS}; use crate::methods::MethodError; use crate::phone::chat_app::mail::acts; use crate::shell::client::ClientController; use cotton_core::rules::mail_predicate; const OUTBOX: &str = "outbox"; /// Everything from one address out of the Inbox, at the Mac. pub(crate) const SENDER_ARCHIVE: &str = "sender_archive"; /// Everything from one address to Trash, at the Mac, with no count (Delete everything; CONTRACT "Senders 3"). pub(crate) const SENDER_TRASH: &str = "sender_trash"; /// The Mac's mail acts a sender's row shows the state of, newest first. /// The mail acts whose state a sender shows (ACTS TRUTH, 24 Nov 2026): the sender-wide ones and one mail's Archive and /// Delete, each row's `to` being the sender. Mark read and unread are not shown on a sender: opening a conversation /// files them, and a row on every sender opened would say nothing he did. const SHOWN: [&str; 5] = [SENDER_ARCHIVE, "unsubscribe", SENDER_TRASH, "archive", "trash"]; /// Who a key stands for. pub(crate) struct Whole { pub(crate) name: String, /// Their keys: the sender and those merged into them, or each sender at the domain. pub(crate) keys: Vec, pub(crate) sent: u32, pub(crate) sms: bool, } impl Whole { /// Their mail addresses, in lower case. pub(crate) fn addresses(&self) -> Vec { self.keys.iter().filter(|k| k.kind == KeyKind::Address).map(|k| k.key.to_lowercase()).collect() } } /// `key` as a whole sender: `@domain` is every sender at the domain; any other key is the sender it is merged into, /// with every sender merged into that one. pub(crate) fn whole(ctx: &mut Ctx<'_>, key: &str) -> Result { let k = key.trim().to_lowercase(); let pick = |mine: Vec<&rule::Sender>, name: String, keys: Vec| Whole { name, sent: mine.iter().map(|s| s.sent).sum(), sms: mine.iter().any(|s| s.channels.iter().any(|c| c == "sms")), keys, }; if let Some(domain) = k.strip_prefix('@') { let all = everyone_in(ctx, Some(std::slice::from_ref(&k)))?; let mine: Vec<&rule::Sender> = all.iter().filter(|s| rule::domain_of(&s.key).as_deref() == Some(domain)).collect(); let mut keys: Vec = mine.iter().map(|s| s.key.clone()).collect(); // And its addresses with nothing left here whose mail act is still the Mac's (their Try again). for (address, act) in mail_states(ctx)? { if !act.done() && address.ends_with(&format!("@{domain}")) && !keys.iter().any(|k| k.key.eq_ignore_ascii_case(&address)) { keys.push(stored_key(&address)); } } return Ok(pick(mine, domain.to_string(), keys)); } let merges = merge_rows(ctx); let root = merges.iter().find(|(_, m, _)| *m == k).map_or_else(|| k.clone(), |(_, _, into)| into.clone()); let mut wanted = vec![root.clone()]; wanted.extend(merges.iter().filter(|(_, _, into)| *into == root).map(|(_, m, _)| m.clone())); let all = everyone_in(ctx, Some(&wanted))?; let mine: Vec<&rule::Sender> = all.iter().filter(|s| wanted.contains(&s.key.key.to_lowercase())).collect(); let name = mine.iter().find(|s| s.key.key.to_lowercase() == root).map_or_else(|| root.clone(), |s| rule::name_of(s)); let keys = wanted.iter().map(|w| mine.iter().find(|s| s.key.key.to_lowercase() == *w).map_or_else(|| stored_key(w), |s| s.key.clone())).collect(); Ok(pick(mine, name, keys)) } /// Their mail here, newest first, not archived: `(id, account)`. fn live_mail(ctx: &mut Ctx<'_>, address: &str) -> Result)>, String> { let found = rows( ctx, &format!("SELECT id, coalesce(account, gmail_account) AS account FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? AND {live_mail} AND archived_at IS NULL ORDER BY sent_at DESC, id DESC", live_mail = mail_predicate::live("")), &[ws(ctx), SqlValue::Text(address.to_string())], )?; Ok(found.iter().filter_map(|r| Some((s(r, "id")?, s(r, "account")))).collect()) } /// Files a sender-wide row for the Mac (`sender_archive`, `sender_trash`), naming the account of their newest mail, /// when the served outbox takes the kind. Whether it did. /// `name` rides in the row's `body` (the outbox has no column of its own for it, and the Mac reads no `body` on a /// mail act): the sender's name as Comms showed it, so a sender with nothing left here keeps it while the Mac works. pub(crate) fn file_sender_wide(ctx: &mut Ctx<'_>, kind: &str, address: &str, name: &str) -> Result { file_sender_wide_with(ctx, kind, address, name, &json!({})) } /// [`file_sender_wide`], the row carrying `fields` too (a move's `count`, `uid_validity`, `uid_below`). pub(crate) fn file_sender_wide_with(ctx: &mut Ctx<'_>, kind: &str, address: &str, name: &str, fields: &Value) -> Result { if !acts::takes(ctx, kind)? { return Ok(false); } let newest = rows( ctx, &format!("SELECT coalesce(account, gmail_account) AS account FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? ORDER BY sent_at DESC LIMIT 1"), &[ws(ctx), SqlValue::Text(address.to_string())], )?; let account = newest.first().and_then(|r| s(r, "account")); let mut data = json!({ "channel": "mail", "kind": kind, "to": address, "account": account, "body": name, "status": "queued" }); for (k, v) in fields.as_object().into_iter().flatten() { data[k] = v.clone(); } tables::create_produced_record(ctx, &json!({ "table": OUTBOX, "data": data }).as_object().cloned().unwrap_or_default()).map_err(|f| f.to_string())?; Ok(true) } /// The Mac's count of one address's mail in his mailbox (`sender_count`, CONTRACT "DELETE FAST: the mailbox count"): /// how many, and what fixed that set, so a move names exactly the mail counted. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Counted { pub(crate) count: u64, pub(crate) uid_validity: u64, pub(crate) uid_below: u64, /// When the Mac answered (the row's last write). pub(crate) at: String, } /// Each address's newest count the Mac answered, and the addresses with a count still waiting for the Mac. #[derive(Default)] pub(crate) struct Counts { pub(crate) answered: HashMap, pub(crate) waiting: std::collections::HashSet, } impl Counts { /// Their mailbox's count over every one of `addresses`: `None` while any is not counted yet. pub(crate) fn over(&self, addresses: &[String]) -> Option { addresses.iter().map(|a| self.answered.get(a).map(|c| c.count)).sum() } } pub(crate) const SENDER_COUNT: &str = "sender_count"; /// A count older than this is asked again when their page or Delete everything is opened; until the Mac answers, /// the older count stands (exact for the set it fixed). const RECOUNT_MS: i64 = 3_600_000; /// Where a count is of: all his mail (Delete everything, Gmail's All Mail), or his Inbox (Archive everything: /// `target: "inbox"`, ACTS CHECK, Mac 9). pub(crate) const INBOX: &str = "inbox"; /// The Mac's counts of all his mail (`inbox` false) or of his Inbox (`inbox` true). pub(crate) fn mailbox_counts(ctx: &mut Ctx<'_>, inbox: bool) -> Result { let mut out = Counts::default(); if !acts::takes(ctx, SENDER_COUNT)? { return Ok(out); } let mut page = 0u64; loop { let ask = json!({ "table": OUTBOX, "where": { "kind": SENDER_COUNT, "channel": "mail" }, "limit": 500, "page": page }); let listed = tables::list_records(ctx, ask.as_object().unwrap_or(&serde_json::Map::new())).map_err(|f| f.to_string())?; let records = listed["records"].as_array().cloned().unwrap_or_default(); for record in &records { if record.get("deleted_at").is_some_and(|d| !d.is_null()) { continue; } let data = &record["data"]; let Some(to) = data["to"].as_str().map(|t| t.trim().to_lowercase()) else { continue }; if (data["target"].as_str() == Some(INBOX)) != inbox { continue; } match data["status"].as_str().unwrap_or("queued") { "queued" | "sending" => { out.waiting.insert(to); } "sent" => { let whole = |k: &str| data[k].as_u64().or_else(|| data[k].as_str().and_then(|t| t.parse().ok())); let (Some(count), Some(uid_validity), Some(uid_below)) = (whole("count"), whole("uid_validity"), whole("uid_below")) else { continue }; if uid_validity == 0 || uid_below == 0 { continue; } let at = record["updated_at"].as_str().or(record["created_at"].as_str()).unwrap_or_default().to_string(); if out.answered.get(&to).is_none_or(|held| held.at < at) { out.answered.insert(to, Counted { count, uid_validity, uid_below, at }); } } _ => {} } } match listed["next_page"].as_u64() { Some(next) if !records.is_empty() && next > page => page = next, _ => break, } } Ok(out) } /// Ask the Mac to count `key`'s mail in his mailbox (each address), where no count is waiting and none was answered /// within the hour: said when their page or Delete everything opens, so the ask can show his mailbox's own number. pub(crate) fn want_counts(client: &ClientController, key: &str, inbox: bool) -> Result<(), MethodError> { let now = crate::phone::cotton_chat::now_ms(client); let wanted = crate::phone::cotton_chat::read(client, "chat.sender.counts", |ctx| { let whole = whole(ctx, key)?; let counts = mailbox_counts(ctx, inbox)?; if !acts::takes(ctx, SENDER_COUNT)? { return Ok(json!([])); } let stale = |c: &Counted| now - crate::phone::chat_app::ms(&c.at) > RECOUNT_MS; let due: Vec = whole.addresses().into_iter().filter(|a| !counts.waiting.contains(a) && counts.answered.get(a).is_none_or(stale)).collect(); Ok(json!({ "name": whole.name, "due": due })) })?; let due: Vec = wanted["due"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); if due.is_empty() { return Ok(()); } let name = wanted["name"].as_str().unwrap_or(key).to_string(); crate::phone::cotton_chat::write(client, "chat.sender.count", |ctx| { for address in &due { let place = if inbox { json!({ "target": INBOX }) } else { json!({}) }; file_sender_wide_with(ctx, SENDER_COUNT, address, &name, &place)?; } Ok(Value::Null) })?; Ok(()) } /// What Archive everything would take: their mail here not yet archived. pub(crate) fn archive_count(ctx: &mut Ctx<'_>, whole: &Whole) -> Result { let mut n = 0; for a in whole.addresses() { n += live_mail(ctx, &a)?.len() as u32; } Ok(n) } fn refused(code: &str, words: String) -> MethodError { MethodError::new(code, words) } /// `chat.sender.act { act: "archive", key }`. /// `mailbox` is the Mac's count of his Inbox the ask showed (`None`: it showed none, so only the mail here leaves /// his Inbox there, one `archive` row a mail); a count answered since asks again (ARCHIVE COUNT). pub(crate) fn archive(client: &ClientController, key: &str, mailbox: Option) -> Result { let lines = list::lines(); let now = crate::phone::cotton_chat::iso(crate::phone::cotton_chat::now_ms(client)); let mut out: Result = Ok(Value::Null); crate::phone::cotton_chat::write(client, "chat.sender.archive", |ctx| { let whole = whole(ctx, key)?; let addresses = whole.addresses(); if addresses.is_empty() { out = Err(refused("no_mail", say(&lines, "app.senders.refused.no_mail", &[("name", &whole.name)]))); return Ok(Value::Null); } let counts = mailbox_counts(ctx, true)?; if mailbox.is_some() && counts.over(&addresses) != mailbox { out = Err(refused("count_changed", say(&lines, "app.senders.refused.count_changed", &[("name", &whole.name)]))); return Ok(Value::Null); } let mac = acts::takes(ctx, SENDER_ARCHIVE)?; let mut filed = false; let mut n = 0usize; for address in &addresses { let mail = live_mail(ctx, address)?; n += mail.len(); if mac && mailbox.is_none() { // Not counted: only the mail here, each by its own id at the Mac. for (id, _) in &mail { if let Some(one) = acts::mail_of(ctx, id)?.filter(|m| m.external.is_some()) { filed |= acts::queue(ctx, &one, "archive")?; } } } for (id, _) in &mail { let mut patch = serde_json::Map::new(); patch.insert("archived_at".into(), json!(now)); update_row(ctx, EMAILS, id, patch).map_err(|f| f.to_string())?; } if mac && mailbox.is_some() { // Exactly the set the Mac counted in his Inbox and he saw. if let Some(c) = counts.answered.get(address).filter(|c| c.count > 0) { let fixed = json!({ "count": c.count, "uid_validity": c.uid_validity, "uid_below": c.uid_below }); filed |= file_sender_wide_with(ctx, SENDER_ARCHIVE, address, &whole.name, &fixed)?; } } } let mac = filed; // What Comms did, and that the mailbox's half waits for the Mac: never "done" before the Mac says so. let said = if mac { "app.senders.said.archived_mail" } else { "app.senders.said.archived" }; out = Ok(json!({ "key": key, "archived": n, "said": say(&lines, said, &[("n", &n.to_string()), ("name", &whole.name)]) })); Ok(Value::Null) })?; out } /// `chat.sender.act { act: "unsubscribe", key }`. pub(crate) fn unsubscribe(client: &ClientController, key: &str) -> Result { let lines = list::lines(); let mut out: Result = Ok(Value::Null); crate::phone::cotton_chat::write(client, "chat.sender.unsubscribe", |ctx| { let whole = whole(ctx, key)?; let addresses = whole.addresses(); if addresses.is_empty() { out = Err(refused("no_mail", say(&lines, "app.senders.refused.no_mail", &[("name", &whole.name)]))); return Ok(Value::Null); } if !acts::takes(ctx, "unsubscribe")? { out = Err(refused("not_yet", say(&lines, "app.senders.refused.not_yet", &[]))); return Ok(Value::Null); } for address in &addresses { let newest = rows( ctx, &format!("SELECT id FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? AND {live_mail} ORDER BY (list_unsubscribe IS NOT NULL AND trim(list_unsubscribe) != '') DESC, sent_at DESC, id DESC LIMIT 1", live_mail = mail_predicate::live("")), &[ws(ctx), SqlValue::Text(address.clone())], )?; let Some(id) = newest.first().and_then(|r| s(r, "id")) else { continue }; if let Some(mail) = acts::mail_of(ctx, &id)? { acts::queue(ctx, &mail, "unsubscribe")?; } } out = Ok(json!({ "key": key, "said": say(&lines, "app.senders.said.unsubscribing", &[("name", &whole.name)]) })); Ok(Value::Null) })?; out } /// What the Mac's mail acts on each address say, by the address (`to`, lower case): their newest act. An act filed /// as many rows at once (Delete everything with his mailbox not counted: one `trash` a mail) says its worst row: a /// refusal if any row was refused, else unchecked, else waiting, else done (SENDERS TRUE walk: one Try again took /// one of 50 refused rows and the page said "Moved to Trash" over the other 49). pub(crate) fn mail_states(ctx: &mut Ctx<'_>) -> Result, String> { let rank = |a: &SourceAct| match a.status.as_str() { "failed" => 0, _ if a.unchecked() => 1, "sent" => 3, _ => 2, }; Ok(newest_batches(ctx)? .into_iter() .filter_map(|(to, batch)| batch.into_iter().min_by_key(|a| rank(a)).map(|a| (to, a))) .collect()) } /// Every row of each address's newest mail act (the rows written in the same instant), by the address. pub(crate) fn newest_batches(ctx: &mut Ctx<'_>) -> Result>, String> { let mut all: HashMap> = HashMap::new(); for (to, act) in every_mail_act(ctx)? { all.entry(to).or_default().push(act); } Ok(all .into_iter() .map(|(to, acts)| { let newest = acts.iter().map(|a| a.written_at.clone()).max().unwrap_or_default(); (to, acts.into_iter().filter(|a| a.written_at == newest).collect()) }) .collect()) } fn every_mail_act(ctx: &mut Ctx<'_>) -> Result, String> { let mut out: Vec<(String, SourceAct)> = Vec::new(); for kind in SHOWN { if !acts::takes(ctx, kind)? { continue; } let mut page = 0u64; loop { let ask = json!({ "table": OUTBOX, "where": { "kind": kind, "channel": "mail" }, "limit": 500, "page": page }); let listed = tables::list_records(ctx, ask.as_object().unwrap_or(&serde_json::Map::new())).map_err(|f| f.to_string())?; let records = listed["records"].as_array().cloned().unwrap_or_default(); for record in &records { if record.get("deleted_at").is_some_and(|d| !d.is_null()) { continue; } let data = &record["data"]; let (Some(id), Some(to)) = (record["id"].as_str(), data["to"].as_str()) else { continue }; let act = SourceAct { id: id.to_string(), kind: kind.to_string(), status: data["status"].as_str().unwrap_or("queued").to_string(), error: data["error"].as_str().map(str::to_string), written_at: record["created_at"].as_str().unwrap_or_default().to_string(), name: data["body"].as_str().map(str::to_string).filter(|n| !n.trim().is_empty()), moved: data["moved"].as_u64().or_else(|| data["moved"].as_str().and_then(|t| t.parse().ok())), proof: data["sent_external_id"].as_str().map(str::to_string), count: data["count"].as_u64().or_else(|| data["count"].as_str().and_then(|t| t.parse().ok())), fixed: data["uid_validity"].as_u64().is_some_and(|v| v > 0) && data["uid_below"].as_u64().is_some_and(|v| v > 0), offered: false, }; let mut act = act; if kind == "unsubscribe" { if let Some(target) = data["target"].as_str() { let sql = format!("SELECT 1 AS y FROM {EMAILS} WHERE workspace_id = ? AND external_id = ? AND list_unsubscribe LIKE '%https://%' AND list_unsubscribe_post LIKE '%One-Click%' LIMIT 1"); act.offered = !rows(ctx, &sql, &[ws(ctx), SqlValue::Text(target.to_string())])?.is_empty(); } } out.push((to.trim().to_lowercase(), act)); } match listed["next_page"].as_u64() { Some(next) if !records.is_empty() && next > page => page = next, _ => break, } } } Ok(out) } /// The newest state among `keys`. pub(crate) fn newest_of<'a>(states: &'a HashMap, keys: impl IntoIterator) -> Option<&'a SourceAct> { keys.into_iter().filter_map(|k| states.get(&k.to_lowercase())).max_by(|a, b| (&a.written_at, &a.id).cmp(&(&b.written_at, &b.id))) }