//! One sender's mail to the provider's Trash, asked from the phone (the owner's sender clean-up, PEOPLE-FACTS.md //! "Mail"; coordinator, 23 Nov 2026). The only act that writes to the owner's mailbox. //! //! The phone asks through the outbox, as a WhatsApp send does, on the `mail` channel: //! //! 1. **`sender_count`** (`to`: the address). The Mac counts the messages FROM that exact address in the mailbox a //! run reads (Gmail's All Mail, any other server's INBOX) and answers the row `sent` with `count`, and what fixes //! the set counted: `uid_validity` and `uid_below` (the mailbox's next UID then). Nothing moves. //! 2. **`sender_trash`** (`to`, and `uid_validity`, `uid_below` and `count` copied from the count the owner saw). //! With no `uid_validity` (Senders 3: Delete everything, a mail's Delete all from this sender, which the phone //! asked with Cotton's own count) the Mac counts first and writes what fixed the set on the row, then moves in //! the same run. The Mac moves those messages to the provider's Trash in batches of [`BATCH`], writing `moved` after each, and //! answers `sent`. Mail that came after the count is never touched. A run cut short leaves the row `sending` //! and the next run goes on where it was: a moved message is no longer in the mailbox, so it is never moved twice. //! //! How it moves: `UID MOVE` (RFC 6851) to the account's `\Trash` mailbox (Gmail: "[Gmail]/Trash" when it names //! none). On Gmail without MOVE, `UID COPY` into Trash, which Gmail makes a move. A server with neither is refused //! in words. Never STORE `\Deleted`, never EXPUNGE: what goes to Trash stays there for the provider's own time //! (Gmail: 30 days) and the owner can take it back there. //! //! "From that exact address": `SEARCH FROM` matches any part of the From line, so each hit's From header is read //! (`BODY.PEEK`, nothing marked read) and only an exact address is counted or moved. //! //! The other acts the phone files on this channel (read, unread, archive, one mail to Trash, unsubscribe, a //! sender's Archive everything) are [`super::acts`]'s, drained here in the same pass. //! //! The owner's mail is never trashed from a lane: only this Mac app, signed in as the owner, drains his outbox. //! Tests run against a fake server on this machine's loopback. use serde_json::{json, Value}; use super::acts::{self, Helps}; use super::client::{ImapClient, ImapError}; use super::proto::quote; use crate::object::{Act, ObjectClient, ObjectError}; /// Messages moved per command, and per `moved` written back. pub const BATCH: usize = 200; /// From headers read per FETCH while counting. const HEADER_PAGE: usize = 500; pub const CHANNEL: &str = "mail"; pub const COUNT: &str = "sender_count"; pub const TRASH: &str = "sender_trash"; #[derive(Debug, thiserror::Error)] pub enum TrashError { #[error(transparent)] Imap(#[from] ImapError), #[error("This mail account has no Trash to move to.")] NoTrash, #[error("This mail server can't move mail without erasing it, so nothing was moved.")] CannotMove, #[error("The mailbox was renumbered since the count. Count again.")] Renumbered, #[error("\"{0}\" is not an email address.")] NotAnAddress(String), #[error("This email is no longer in your mail.")] Gone, #[error("This mail account has no Archive to move to.")] NoArchive, #[error("Cotton couldn't keep this sender's list on this Mac.")] NoList, #[error("Not something mail can do.")] NotAnAct(String), /// Counted and said, nothing moved (ACTS-CHECK, 24 Nov 2026: "the act moves what the person was told, or the /// person is told the mailbox's real count before agreeing"). His Try again moves exactly the set counted. #[error("{}", ask_trash(*.0))] AskTrash(usize), #[error("{}", ask_archive(*.0))] AskArchive(usize), /// More of theirs than the count fixed: nothing moved. #[error("Your mail holds more from them than was counted, so nothing was moved. Count again.")] MoreThanCounted, /// One mail's archive, read back with the Inbox label still on it (SENDERS TRUE). #[error("Gmail kept it in your Inbox.")] KeptIt, #[error("This email is too large to bring. Open it in your mail.")] TooBig, #[error("Cotton couldn't keep this email's page: {0}")] NotLanded(String), } fn ask_trash(n: usize) -> String { if n == 1 { "Your mail holds 1 email from them. Try again to move it to Trash.".to_string() } else { format!("Your mail holds {n} emails from them. Try again to move those {n} to Trash.") } } fn ask_archive(n: usize) -> String { if n == 1 { "1 email from them is in your Inbox. Try again to archive it.".to_string() } else { format!("{n} emails from them are in your Inbox. Try again to archive those {n}.") } } /// What a sender's archive left in the Inbox, read back (SENDERS TRUE). pub fn kept_words(kept: usize) -> String { format!("Gmail kept {kept} of them in your Inbox.") } /// Where a sender's mail is read from and moved to. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Place { pub mailbox: String, pub trash: String, /// Gmail without MOVE: COPY into Trash is the move. pub copy: bool, } /// What a count fixed: the messages, and the mailbox's numbering and next UID then. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Counted { pub mailbox: String, pub uid_validity: u32, pub uid_below: u32, pub uids: Vec, } /// An address as it is compared: trimmed and lowercased; refused unless it is one address. pub fn address_of(text: &str) -> Result { let address = text.trim().to_lowercase(); let ok = address.len() <= 320 && address.split('@').count() == 2 && !address.starts_with('@') && !address.ends_with('@') && !address.chars().any(|c| c.is_whitespace() || c.is_control() || matches!(c, '"' | '\\' | '<' | '>' | '(' | ')' | ',' | ';')); if ok { Ok(address) } else { Err(TrashError::NotAnAddress(text.trim().to_string())) } } /// The address in a From header: inside its angle brackets, else the word with an `@`. pub fn from_address(header: &str) -> Option { let line = header.split_once(':').map(|(_, rest)| rest).unwrap_or(header); let line: String = line.split(['\r', '\n']).map(str::trim).collect::>().join(" "); let found = match (line.rfind('<'), line.rfind('>')) { (Some(open), Some(close)) if open < close => line[open + 1..close].to_string(), _ => line.split_whitespace().find(|word| word.contains('@'))?.trim_matches(|c| c == '"' || c == '\'').to_string(), }; address_of(&found).ok() } /// The mailbox a run reads, and the account's Trash. pub fn place(client: &mut ImapClient) -> Result { let gmail = client.can("X-GM-EXT-1"); let uses = client.special_use()?; let mailbox = if gmail { uses.all.clone().unwrap_or_else(|| "INBOX".to_string()) } else { "INBOX".to_string() }; let trash = match uses.trash { Some(trash) => trash, None if gmail => "[Gmail]/Trash".to_string(), None => return Err(TrashError::NoTrash), }; let copy = if client.can("MOVE") { false } else if gmail { true } else { return Err(TrashError::CannotMove); }; Ok(Place { mailbox, trash, copy }) } /// The UIDs below `below` (all, at 0) whose From is exactly `address`, in the mailbox open now. pub(super) fn matching(client: &mut ImapClient, address: &str, below: u32) -> Result, TrashError> { matching_from(client, address, 0, below) } /// [`matching`] from UID `from` on (`from` 0: from the first). pub(super) fn matching_from(client: &mut ImapClient, address: &str, from: u32, below: u32) -> Result, TrashError> { let quoted = quote(address).ok_or_else(|| TrashError::NotAnAddress(address.to_string()))?; let range = if from > 0 { format!("UID {from}:* ") } else { String::new() }; let mut hits = client.uid_search(&format!("{range}FROM {quoted}"))?; // `n:*` holds the last message even when its UID is below n. hits.retain(|uid| *uid >= from && (below == 0 || *uid < below)); hits.sort_unstable(); let mut out = Vec::with_capacity(hits.len()); for page in hits.chunks(HEADER_PAGE) { let set: Vec = page.iter().map(u32::to_string).collect(); for fetched in client.uid_fetch(&set.join(","), "UID BODY.PEEK[HEADER.FIELDS (FROM)]", None)? { let header = fetched.body.as_deref().map(String::from_utf8_lossy).unwrap_or_default(); if from_address(&header).as_deref() == Some(address) { out.push(fetched.uid); } } } out.sort_unstable(); out.dedup(); Ok(out) } /// Count `address`'s messages, read only (EXAMINE). pub fn count(client: &mut ImapClient, address: &str) -> Result { let address = address_of(address)?; let place = place(client)?; let state = client.examine(&place.mailbox)?; let uids = matching(client, &address, 0)?; Ok(Counted { mailbox: place.mailbox, uid_validity: state.uid_validity, uid_below: state.uid_next, uids }) } /// Move what a count fixed to Trash (both numbers from [`count`]; the drain counts first when a row has none), [`BATCH`] at a time; `after_batch` hears the moved total of this run after /// each, and stops the move by answering false. Answers how many this run moved. /// /// `at_most` is the count he was shown with that set (DELETE FAST): more of theirs below it moves nothing. pub fn trash(client: &mut ImapClient, address: &str, uid_validity: u32, uid_below: u32, at_most: Option, after_batch: &mut dyn FnMut(usize) -> bool) -> Result { trash_naming(client, address, uid_validity, uid_below, at_most, after_batch).map(|trashed| trashed.gone.len()) } /// One mail moved to Trash, as the person's database knows it: Gmail's own id (the `gmail_id` the import wrote, on /// Gmail) and the Message-ID's `external_id`. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct GoneMail { pub gmail_id: Option, pub external: Option, } /// What a move to Trash moved: each mail, named. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Trashed { pub gone: Vec, } /// [`trash`], naming each mail it moves (read just before its batch moves, nothing marked read), so the drain can /// erase Cotton's rows of exactly those mails (DELETE FAST question 2). pub fn trash_naming(client: &mut ImapClient, address: &str, uid_validity: u32, uid_below: u32, at_most: Option, after_batch: &mut dyn FnMut(usize) -> bool) -> Result { let address = address_of(address)?; let place = place(client)?; let gmail = client.can("X-GM-EXT-1"); let state = client.select(&place.mailbox)?; if state.uid_validity != uid_validity { return Err(TrashError::Renumbered); } let uids = matching(client, &address, uid_below)?; if at_most.is_some_and(|most| uids.len() > most) { return Err(TrashError::MoreThanCounted); } let items = if gmail { "UID X-GM-MSGID BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)]" } else { "UID BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)]" }; let mut trashed = Trashed::default(); for batch in uids.chunks(BATCH) { let set: Vec = batch.iter().map(u32::to_string).collect(); let set = set.join(","); let mut named: std::collections::HashMap = std::collections::HashMap::new(); for fetched in client.uid_fetch(&set, items, None)? { let header = fetched.body.as_deref().map(super::history::headers).unwrap_or_default(); named.insert( fetched.uid, GoneMail { gmail_id: fetched.gm_msgid.filter(|_| gmail).map(super::mime::api_id), external: cotton_rules::fingerprint::email::message_id_external_id(header.message_id.as_deref()), }, ); } client.uid_move(&set, &place.trash, place.copy)?; trashed.gone.extend(batch.iter().map(|uid| named.remove(uid).unwrap_or_default())); if !after_batch(trashed.gone.len()) { break; } } Ok(trashed) } /// What one pass over the outbox's mail rows did. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Drained { pub counted: i64, pub trashed: i64, pub failed: i64, /// Acts on one mail, a sender's Archive everything and unsubscribes ([`super::acts`]). pub done: i64, /// Arrivals from a sender he unsubscribed from with no one-click, moved to Trash. pub swept: i64, /// Rows an earlier Mac refused, taken up again ([`super::acts::OLD_REFUSALS`]). pub retried: i64, /// Cotton's email rows of mail a sender's Delete everything moved to Trash, erased (DELETE FAST question 2). pub erased: i64, } fn field<'a>(row: &'a Value, key: &str) -> Option<&'a Value> { row.get("data").filter(|d| d.is_object()).unwrap_or(row).get(key) } fn text(row: &Value, key: &str) -> String { field(row, key).and_then(Value::as_str).unwrap_or_default().trim().to_string() } fn whole(row: &Value, key: &str) -> u32 { field(row, key).and_then(|v| v.as_u64().or_else(|| v.as_f64().map(|f| f as u64))).unwrap_or(0) as u32 } fn mark(object: &ObjectClient, id: &str, data: Value) -> Result<(), ObjectError> { object.act(Act::Update, crate::outbox::TABLE, id, &data).map(|_| ()) } /// The words a refusal leaves on the row for the phone. fn words(error: &TrashError) -> String { match error { TrashError::Imap(ImapError::SignIn(_)) => "The mail server refused the app password.".to_string(), TrashError::Imap(ImapError::Connect(_) | ImapError::Timeout(_) | ImapError::Wire(_)) => "The mail server couldn't be reached. It will try again.".to_string(), TrashError::Imap(ImapError::Refused { said, .. }) => format!("The mail server refused: {said}"), other => other.to_string(), } } /// Whether a failure is the connection's, so the row waits for the next run instead of failing. fn passing(error: &TrashError) -> bool { matches!(error, TrashError::Imap(ImapError::Connect(_) | ImapError::Timeout(_) | ImapError::Wire(_))) } /// Every queued `mail` row (and a Trash move a stopped run left `sending`) of `account`, done with a client from /// `connect`; then what arrived from a sender on this Mac's list goes to Trash. Rows of another channel, or of /// another account, are left as they are. pub fn drain(object: &ObjectClient, account: &str, connect: &mut dyn FnMut() -> Result, helps: &Helps<'_>) -> Result { let mut drained = Drained::default(); let mut rows = object.outbox("queued")?; rows.extend(object.outbox("sending")?.into_iter().filter(|r| text(r, "kind") == TRASH)); if helps.retry_failed { // What a Mac before this one refused only because it could not do it yet (MAIL-ACTS-NOW, 24 Nov 2026: his // Delete everything and Archive everything from the phone): asked again, as if just filed. let old = object.outbox("failed")?.into_iter().filter(|r| { let kind = text(r, "kind"); text(r, "channel") == CHANNEL && (kind == TRASH || acts::takes(&kind)) && acts::OLD_REFUSALS.contains(&text(r, "error").as_str()) }); for row in old { if let Some(id) = row.get("id").and_then(Value::as_str) { mark(object, id, json!({ "status": "queued", "error": null }))?; drained.retried += 1; rows.push(row); } } } let mut client: Option = None; let account = account.trim().to_lowercase(); for row in rows { let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { continue }; if text(&row, "channel") != CHANNEL || field(&row, "sealed_enc").and_then(Value::as_str).is_some_and(|s| !s.is_empty()) { continue; } let of = text(&row, "account").to_lowercase(); if !of.is_empty() && of != account { continue; } let kind = text(&row, "kind"); if kind != COUNT && kind != TRASH && !acts::takes(&kind) { mark(object, &id, json!({ "status": "failed", "error": "Not something mail can do." }))?; drained.failed += 1; continue; } if client.is_none() { match connect() { Ok(connected) => client = Some(connected), // The account can't be reached now: every row waits for the next run. Err(_) => return Ok(drained), } } let imap = client.as_mut().expect("connected"); let address = text(&row, "to"); let target = text(&row, "target"); let now = || chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let done = if kind == COUNT { // `target: "inbox"`: theirs in the Inbox, the set Archive everything takes (DELETE FAST question 3). let counted = if target == "inbox" { acts::inbox_of(imap, &address) } else { count(imap, &address) }; counted.map(|counted| { drained.counted += 1; json!({ "status": "sent", "count": counted.uids.len(), "uid_validity": counted.uid_validity, "uid_below": counted.uid_below, "error": null }) }) } else if kind == TRASH { // DELETE FAST and ACTS-CHECK (24 Nov 2026): what moves is the set he was told of. A row with the count's // numbering on it (the phone files it so) moves that set and at most its count, at once. A row without // (filed before, when Comms showed only the mail it holds) moves nothing: the mailbox is counted, the // set and its count kept on the row, and he is told the count; his Try again moves exactly that set. match (whole(&row, "uid_validity"), whole(&row, "uid_below")) { (0, _) | (_, 0) => match count(imap, &address) { Ok(counted) => { let n = counted.uids.len(); mark(object, &id, json!({ "count": n, "uid_validity": counted.uid_validity, "uid_below": counted.uid_below }))?; if n == 0 { drained.trashed += 1; Ok(json!({ "status": "sent", "moved": 0, "sent_at": now(), "error": null })) } else { Err(TrashError::AskTrash(n)) } } Err(error) => Err(error), }, (validity, below) => { let before = whole(&row, "moved") as usize; let at_most = Some(whole(&row, "count") as usize).filter(|&n| n > 0).map(|n| n.saturating_sub(before)); mark(object, &id, json!({ "status": "sending" }))?; let mut marked: Result<(), ObjectError> = Ok(()); let trashed = trash_naming(imap, &address, validity, below, at_most, &mut |moved| { marked = mark(object, &id, json!({ "moved": before + moved })); marked.is_ok() }); marked?; trashed.map(|trashed| { drained.trashed += 1; // DELETE FAST question 2: the phone erased what it holds of them (its 90 days); Cotton's // older rows of exactly these mails go too. Moved stands whatever the erase does: it is // tried again by nothing, and a row it missed stays until he deletes it. match (helps.erase)(&trashed.gone) { Ok(erased) => drained.erased += erased as i64, Err(why) => eprintln!("cotton-mac: mail moved to Trash, its older rows not erased: {why}"), } json!({ "status": "sent", "moved": before + trashed.gone.len(), "sent_at": now(), "error": null }) }) } } } else if kind == acts::SENDER_ARCHIVE { // The same for Archive everything: the Inbox counted and said first, then exactly that set, and done // only on reading the Inbox back (SENDERS TRUE). match (whole(&row, "uid_validity"), whole(&row, "uid_below")) { (0, _) | (_, 0) => match acts::inbox_of(imap, &address) { Ok(counted) => { let n = counted.uids.len(); mark(object, &id, json!({ "count": n, "uid_validity": counted.uid_validity, "uid_below": counted.uid_below }))?; if n == 0 { drained.done += 1; Ok(json!({ "status": "sent", "sent_external_id": acts::READ_BACK, "moved": 0, "sent_at": now(), "error": null })) } else { Err(TrashError::AskArchive(n)) } } Err(error) => Err(error), }, (validity, below) => { let at_most = Some(whole(&row, "count") as usize).filter(|&n| n > 0); acts::sender_archive(imap, &address, validity, below, at_most).map(|archived| { if archived.kept == 0 { drained.done += 1; json!({ "status": "sent", "sent_external_id": acts::READ_BACK, "moved": archived.moved, "sent_at": now(), "error": null }) } else { drained.failed += 1; json!({ "status": "failed", "moved": archived.moved, "error": kept_words(archived.kept) }) } }) } } } else if kind == acts::UNSUBSCRIBE { acts::unsubscribe(imap, helps, &account, &target, &address).map(|(how, refused)| { drained.done += 1; // Sent either way (his word stands); a click the sender's server did not take says why. json!({ "status": "sent", "sent_external_id": how, "sent_at": now(), "error": refused }) }) } else if kind == acts::MAIL_PAGE { match (!target.is_empty()).then(|| (helps.mail)(&target)).flatten() { None => Err(TrashError::Gone), Some(mail) => acts::whole(imap, &mail).and_then(|raw| (helps.land_page)(&target, &raw).map_err(TrashError::NotLanded)).map(|kept| { drained.done += 1; let mut data = json!({ "status": "sent", "sent_at": now(), "error": null }); if let (Some(data), Some(kept)) = (data.as_object_mut(), kept.as_object()) { data.extend(kept.clone()); } data }), } } else { match (!target.is_empty()).then(|| (helps.mail)(&target)).flatten() { None => Err(TrashError::Gone), Some(mail) => acts::one(imap, &kind, &mail).map(|()| { drained.done += 1; if kind == acts::ARCHIVE { // Read back before it was answered (SENDERS TRUE). json!({ "status": "sent", "sent_external_id": acts::READ_BACK, "moved": 1, "sent_at": now(), "error": null }) } else { json!({ "status": "sent", "sent_at": now(), "error": null }) } }), } }; match done { Ok(data) => mark(object, &id, data)?, Err(error) if passing(&error) => { // A Trash move goes on from `sending`; anything else is asked again. if kind != TRASH { mark(object, &id, json!({ "status": "queued" }))?; } return Ok(drained); } Err(error) => { mark(object, &id, json!({ "status": "failed", "error": words(&error) }))?; drained.failed += 1; } } } // His unsubscribes with no one-click: what came from those senders since the last look goes to Trash. if let Some(listed) = helps.listed { if listed.listened(&account).is_ok_and(|senders| !senders.is_empty()) { if client.is_none() { client = connect().ok(); } if let Some(imap) = client.as_mut() { drained.swept += acts::sweep(imap, listed, &account).unwrap_or(0) as i64; } } } if let Some(client) = client { client.logout(); } Ok(drained) } #[cfg(test)] mod tests { use super::*; #[test] fn an_address_is_read_exactly_from_a_from_line() { assert_eq!(from_address("From: Invented Shop \r\n\r\n").as_deref(), Some("deals@shop.invented")); assert_eq!(from_address("From: deals@shop.invented\r\n").as_deref(), Some("deals@shop.invented")); assert_eq!(from_address("From: \"Deals\"\r\n \r\n").as_deref(), Some("deals@shop.invented")); assert_eq!(from_address("From: no address here\r\n"), None); assert!(address_of("a b@x.invented").is_err()); assert!(address_of("x.invented").is_err()); assert!(address_of("\"a\"@x").is_err()); } }