//! Cotton Post's reading calls (assets/design/mail/CONTRACT.md, "The core calls each screen needs"), answered from//! the phone's own copy of the mail tables by the same engine Comms' Mail tab reads with (the person rule, the//! groups, a conversation of mail, attachments, the object's older mail), in Post's own words (`post` set)://!//! ```text//! mail.home { account? } → People, Waiting on you, From machines (counted groups), the status//! mail.list { place, account?, after? } → inbox | people | unread | group:<id> | from:<sender> | sent | archived | bin | drafts//! mail.side { counts? } → the side page: inboxes, places, labels (counts: false → the rows alone, nothing counted)//! mail.thread { thread } → a conversation of mail; read here and in the mailbox//! mail.page { email, pictures? } → the designed page//! mail.file { email, index, dir } → an attachment, fetched and opened in Post//! mail.free { dir? } → attachments freed from this phone//! mail.files { kind?, person?, after? } → every attachment, newest first//! mail.search { text } → people, mail and files that hold the words//! ```//!//! **Everything is shown.** Unlike Comms, Post holds a person's mail even when they have a chat: only junk (blocked)//! is left out. **The Inbox** is mail not archived here (`archived_at`) and still in the mailbox's Inbox (`in_inbox`).//! **Machine groups** are by sender, by written rule: receipts by their words, Gmail's Promotions as shops, other//! mail with an unsubscribe as newsletters, every other machine as notices (`Kind`).use std::sync::OnceLock;use cotton_tools::mcp::handlers::tables;usesuper::*;use cotton_core::rules::mail_predicate;/// Every method this module answers.pubconst METHODS: &[&str] = &["mail.home", "mail.list", "mail.side", "mail.thread", "mail.page", "mail.file", "mail.free", "mail.files", "mail.search", "mail.archive", "mail.act", "mail.undo", "mail.after", "mail.ask", "mail.do", "mail.bin.empty", "mail.you", "mail.set", "mail.pictures.always", "mail.link", "mail.hold", "mail.rules", "mail.verdict", "mail.senders", "mail.sender", "mail.sender.merge", "mail.sender.part", "mail.sender.name", "mail.blocked", "mail.unblock", "mail.compose", "mail.save", "mail.discard", "mail.attach", "mail.unattach", "mail.send", "mail.unsend", "mail.sending", "mail.accounts", "mail.account.plan", "mail.account.add", "mail.account", "mail.account.way", "mail.account.set", "mail.account.forget", "mail.account.remove", "mail.fetch", "mail.domains", "mail.domain", "mail.domain.add", "mail.domain.remove", "mail.domain.check", "mail.domain.catch_all", "mail.address.add", "mail.address.remove"];/// Post's own words.pub(crate) fn post() -> &'staticLineSet {static LINES: OnceLock<LineSet> = OnceLock::new(); LINES.get_or_init(|| LineSet::shipped("post").expect("the kit ships the post line set"))}fn p(line: &str, fills: &[(&str, &str)]) -> String { say(post(), line, fills)}/// A count said in its plural form (`{ zero?, one, other }`), `{n}` filled.fn counted(line: &str, n: usize) -> String {// English calls 0 "other"; a line with a zero form of its own says that instead.let form = if n == 0 { "zero" } else { cotton_core::rules::shell_lines::plural_form(&n.to_string()) };let number = cotton_core::rules::shell_lines::number(n as i64); post().say(&format!("{line}.{form}"), &[("n", &number)]).or_else(|| post().say(&format!("{line}.other"), &[("n", &number)])).unwrap_or_default()}/// [`counted`] with other words filled too (`{sender}`, `{people}`).pub(super) fn counted_with(line: &str, n: usize, fills: &[(&str, &str)]) -> String {// English calls 0 "other"; a line with a zero form of its own says that instead.let form = if n == 0 { "zero" } else { cotton_core::rules::shell_lines::plural_form(&n.to_string()) };let number = cotton_core::rules::shell_lines::number(n as i64);letmut all: Vec<(&str, &str)> = vec![("n", number.as_str())]; all.extend_from_slice(fills); post().say(&format!("{line}.{form}"), &all).or_else(|| post().say(&format!("{line}.other"), &all)).unwrap_or_default()}/// The Bin's 30 days, kept in the background after a pass, never as the Bin opens (MAIL PREDICATE phase 2,/// decision 1): mails binned one by one that are 30 days old, and a slice of what an old whole-sender Delete covers.pub(crate) fn keep_the_bin(client: &ClientController) -> Result<usize, MethodError> {Ok(acts::sweep_bin(client)? + acts::erase_cuts(client)?)}/// After a sync pass (UNDO SEND 5): every held mail whose time is up goes, and every one on its way is resumed through/// the object's ledger, for the open account only. The lists never do this network work.pub(crate) fn send_after_pass(client: &ClientController) { writer::sweep(client);}pubfn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"mail.home" => home(client, request),"mail.list" => place(client, request),"mail.side" => side(client, request),"mail.thread" => conversation(client, request),"mail.page" => super::page(client, request),"mail.file" => super::file(client, request),"mail.free" => super::free(client, request),"mail.files" => files(client, request),"mail.search" => search(client, request),"mail.archive" => acts::archive(client, request),"mail.act" => acts::act(client, request),"mail.undo" => acts::undo(client, request),"mail.after" => acts::after(client, request),"mail.ask" => acts::ask(client, request),"mail.you" => you::you(client),"mail.set" => you::set(client, request),"mail.pictures.always" => you::pictures_always(client, request),"mail.link" => you::link(request),"mail.hold" => you::hold(client, request),"mail.rules" => you::rules(client),"mail.senders" => senders::list(client, request),"mail.domains" => domains::list(client),"mail.domain" => domains::page(client, request),"mail.domain.remove" => domains::remove(client, request),"mail.domain.add" => domains::add(client, request),"mail.domain.check" => domains::check(client, request),"mail.domain.catch_all" => domains::catch_all(client, request),"mail.address.add" => domains::add_address(client, request),"mail.address.remove" => domains::remove_address(client, request),"mail.accounts" => accounts::list(client),"mail.fetch" => fetcher::fetch(client, request),"mail.account.plan" => accounts::plan(request),"mail.account.add" => accounts::add(client, request),"mail.account" => accounts::page(client, request),"mail.account.way" => accounts::set_way(client, request),"mail.account.set" => accounts::set(client, request),"mail.account.forget" => accounts::forget(client, request),"mail.account.remove" => accounts::remove(client, request),"mail.compose" => writer::compose(client, request),"mail.save" => writer::save(client, request),"mail.discard" => writer::discard(client, request),"mail.attach" => writer::attach(client, request),"mail.unattach" => writer::unattach(client, request),"mail.send" => writer::send(client, request),"mail.unsend" => writer::unsend(client, request),"mail.sending" => writer::state(client, request),"mail.sender" => senders::page(client, request),"mail.sender.merge" => senders::merge(client, request),"mail.sender.part" => senders::part(client, request),"mail.sender.name" => senders::rename(client, request),"mail.blocked" => senders::blocked(client),"mail.unblock" => senders::unblock(client, request),"mail.verdict" => you::verdict(client, request),"mail.do" => acts::act_on_plan(client, request),"mail.bin.empty" => acts::empty_bin(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a Post method"))), }}// ── the rules Post sorts by ────────────────────────────────────────────/// The four machine groups on the home.#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub(crate) enumKind {Receipts,Shops,Newsletters,Notices,}implKind {pub(crate) const ALL: [Kind; 4] = [Kind::Receipts, Kind::Shops, Kind::Newsletters, Kind::Notices];pub(crate) fn id(self) -> &'static str {matchself {Kind::Receipts => "receipts",Kind::Shops => "shops",Kind::Newsletters => "newsletters",Kind::Notices => "notices", } }fn of_id(id: &str) -> Option<Kind> {Kind::ALL.into_iter().find(|k| k.id() == id) }}/// Words that make a machine's mail a receipt, as whole words of its subject (rules.list's sixth rule).const RECEIPT_WORDS: &[&str] = &["receipt", "invoice", "statement", "payment", "paid", "order", "refund", "transaction", "bill", "booking", "ticket", "e-ticket"];/// Which machine group a machine sender's mail stands in: by the words of its subject first, then by Gmail's own/// category and the unsubscribe it carries. `None` for a person and for junk.pub(super) fn kind_of(know: &Know, address: &str, stored: Option<&str>, mail: Option<&Map<String, Value>>) -> Option<Kind> {if know.who(address, stored, mail) != Who::Machine {returnNone; }let subject = mail.and_then(|m| s(m, "subject")).unwrap_or_default().to_lowercase();if subject.split(|c: char| !c.is_alphanumeric() && c != '-').any(|w| RECEIPT_WORDS.contains(&w)) {returnSome(Kind::Receipts); }let category = mail.and_then(|m| lower(s(m, "gmail_category"))).unwrap_or_default();if category.contains("promotions") {returnSome(Kind::Shops); }match know.group(address, stored, mail) {Some(Group::Promotions) => Some(Kind::Newsletters), _ => Some(Kind::Notices), }}// ── which mail a place holds ───────────────────────────────────────────/// Where a conversation's mail is looked for.#[derive(Clone, Copy, PartialEq, Eq)]enumScope {/// In the Inbox: not archived here, and still in the mailbox's Inbox.Inbox,/// Archived here or out of the mailbox's Inbox, and not in the Bin.Archived,/// In the Bin.Bin,/// Every mail not in the Bin.Any,/// Unread mail in the Inbox (Mail's Unread chip).Unread,}implScope {/// Where a mail (its columns prefixed by `on`: `""`, or `"e."`) is in this place, as SQL; the archived senders/// on `know` count ([`cuts`]).fn clause(self, know: &Know, on: &str) -> String {matchself {Scope::Inbox => cuts::inbox(know, on),Scope::Archived => cuts::archived(know, on),Scope::Bin => format!(" AND {binned_mail}", binned_mail = mail_predicate::binned(on)),Scope::Any => format!(" AND {live_mail}", live_mail = mail_predicate::live(on)),Scope::Unread => format!("{} AND {unread_mail}", cuts::inbox(know, on), unread_mail = mail_predicate::unread(on)), } }}/// A conversation as a place sees it: only its mail in `scope`, and `account` when one is asked for.fn conv_in(ctx: &mutCtx<'_>, know: &Know, t: &Map<String, Value>, scope: Scope, account: Option<&str>) -> Result<Option<Conv>, String> {letSome(id) = s(t, "id") else { returnOk(None) };let columns = know.mail_columns();letmut clause = scope.clause(know, "");letmut params = vec![text(id.clone())];ifletSome(account) = account { clause.push_str(" AND lower(coalesce(account, gmail_account, '')) = ?"); params.push(text(account.to_lowercase())); }let oldest = rows(ctx, &format!("SELECT {columns} FROM {EMAILS} WHERE thread_id = ?{clause} ORDER BY sent_at ASC, id ASC LIMIT 8"), ¶ms)?;if oldest.is_empty() {returnOk(None); }let newest = one(ctx, &format!("SELECT {columns} FROM {EMAILS} WHERE thread_id = ?{clause} ORDER BY sent_at DESC, id DESC LIMIT 1"), ¶ms)?;let unread = one(ctx, &format!("SELECT 1 AS u FROM {EMAILS} WHERE thread_id = ?{clause} AND {unread_mail} LIMIT 1", unread_mail = mail_predicate::unread("")), ¶ms)?.is_some();Ok(conv_with(know, t, &oldest, newest, unread))}/// Conversations newest first, each kept by `keep`, up to `want`, from after `after`, reading at most `budget`/// conversations: the home's bands look at the newest only./// Archived, as SQL on a conversation `t`: the two sets of [`walk`]'s Archived (schema 155's indexes).fn archived_sets(know: &Know, workspace_id: &str) -> String {let workspace = format!("'{}'", workspace_id.replace('\'', "''"));letmut has = format!(" AND (t.id IN (SELECT e.thread_id FROM {EMAILS} e WHERE {live_mail} AND (e.archived_at IS NOT NULL OR e.in_inbox = 0))", live_mail = mail_predicate::live("e."));if !know.cuts.is_empty() { has.push_str(&format!(" OR t.id IN (SELECT e.thread_id FROM {EMAILS} e WHERE e.workspace_id = {workspace} AND {live_mail} AND e.archived_at IS NULL AND coalesce(e.in_inbox, 1) <> 0 AND {})", cuts::covered(&know.cuts, "e."), live_mail = mail_predicate::live("e."))); } has.push(')'); has}/// Every Inbox sender's tally and today's (`in_inbox` from [`cuts::inbox`]): read from idx_cotton_emails_inbox.fn tallies_sql(in_inbox: &str, account_clause: &str) -> String { format!("SELECT lower(trim(from_email)) AS a, count(*) AS n, sum(CASE WHEN sent_at >= ? THEN 1 ELSE 0 END) AS today FROM {EMAILS} WHERE workspace_id = ?{in_inbox}{account_clause} GROUP BY lower(trim(from_email))")}/// A page of mail with files, newest first, after `cut`: read from idx_cotton_emails_files.fn files_sql(cut: &str) -> String { format!("SELECT id, from_email, from_name, sent_at, attachments FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND attachments IS NOT NULL AND attachments <> '' AND attachments <> '[]'{cut} ORDER BY sent_at DESC, id DESC LIMIT 200", live_mail = mail_predicate::live(""))}fn walk(ctx: &mutCtx<'_>, know: &Know, scope: Scope, account: Option<&str>, after: Option<&(String, String)>, want: usize, budget: usize, mut keep: implFnMut(&Know, &Conv) -> bool) -> Result<(Vec<Conv>, Option<String>), String> {letmut out = Vec::new();letmut cursor = after.cloned();letmut read_so_far = 0;let bin = if scope == Scope::Bin { String::new() } else { format!(" AND {}", mail_predicate::live_thread("t.")) };// Newest first by `last_at` itself, so the file's (workspace_id, last_at DESC) index serves the order: a// `coalesce` over it sorted all 80,000 conversations for every page (1 s a page at his size, 56 ms now).// Only conversations with mail in the place, asked of the file in one statement: a place few conversations are// in (the Bin, Archived on a mailbox kept in its Inbox) was looked for one conversation at a time and ran out of// time at his size (110,000 mails in 80,000 conversations, 25 Nov 2026).letmut has = format!(" AND EXISTS (SELECT 1 FROM {EMAILS} e WHERE e.thread_id = t.id{}", scope.clause(know, "e."));if account.is_some() { has.push_str(" AND lower(coalesce(e.account, e.gmail_account, '')) = ?"); } has.push(')');if scope == Scope::Archived && account.is_none() {// Archived as two sets the file holds in indexes (schema 155): the conversations of mail archived by its own// flag (idx_cotton_emails_archived), and of Inbox mail an Archive row covers (idx_cotton_emails_inbox, by// the row's sender). Asked one conversation at a time, a sparse Archived read every mail at his size. has = archived_sets(know, ctx.workspace_id); }loop {let (cut, mut params) = match &cursor {Some((at, id)) => (" AND (t.last_at, t.id) < (?, ?)", vec![ws(ctx), text(at.clone()), text(id.clone())]),None => ("", vec![ws(ctx)]), };ifletSome(a) = account { params.push(text(a.to_lowercase())); }// A page of a place is the same while the copy is unchanged (kept.rs): a place few conversations are in reads// most of the mailbox to fill one.let sql = format!("SELECT t.id, t.subject, t.last_at, t.email_count, t.sender_address, t.sender_kind FROM {MAIL_THREADS} t WHERE t.workspace_id = ?{bin}{cut}{has} ORDER BY t.last_at DESC, t.id DESC LIMIT 120");let key = format!("walk:{sql}:{params:?}");let batch = kept::kept(ctx, &key, |ctx| rows(ctx, &sql, ¶ms))?;if batch.is_empty() {returnOk((out, None)); }for t in &batch { cursor = Some((s(t, "last_at").unwrap_or_default(), s(t, "id").unwrap_or_default())); read_so_far += 1;ifletSome(c) = conv_in(ctx, know, t, scope, account)? {if c.who(know) != Who::Junk && keep(know, &c) { out.push(c);if out.len() == want {returnOk((out, cursor.as_ref().map(|(a, b)| format!("{a}\u{1f}{b}")))); } } }if read_so_far >= budget {returnOk((out, None)); } }if batch.len() < 120 {returnOk((out, None)); } }}fn kind_of_conv(know: &Know, c: &Conv) -> Option<Kind> { kind_of(know, &c.address, c.stored.as_deref(), c.theirs.as_ref().or(c.newest.as_ref()))}// ── one row, as every Post list draws it ───────────────────────────────/// `MailRow` (CONTRACT "Shared shapes").fn row(clock: &Clock, know: &Know, c: &Conv, own: &OwnAddresses) -> Value {let who = c.who(know);let name = know.name_of(&c.address).map(str::to_string).unwrap_or_else(|| shown_name(c.name.as_deref(), &c.address));let newest = c.newest.as_ref();let attachments = newest.map(attachments_of).map_or(0, |a| a.len());let pic = picture(&c.address, &name, None);let account = newest.and_then(|m| lower(s(m, "account").or_else(|| s(m, "gmail_account")))).and_then(|a| own.tag_of(&a));let a11y: Vec<String> = [c.unread.then(|| p("a11y.unread", &[])), Some(p(if who == Who::Person { "a11y.person" } else { "a11y.machine" }, &[])), (attachments > 0).then(|| p("a11y.attachment", &[]))].into_iter().flatten().collect(); json!({"thread": c.id,"email": newest.and_then(|m| s(m, "id")),"from": { "name": name, "address": c.address, "face": if who == Who::Person { "person" } else { "machine" }, "initials": pic.initials, "tint": pic.tint },"subject": c.subject.clone().or_else(|| newest.and_then(|m| s(m, "subject"))).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| p("list.no_subject", &[])),"line": newest.and_then(line_of),"when": clock.recent(&c.last_at),"unread": c.unread,"count": c.count,"attachments": (attachments > 0).then_some(attachments),"account": account.map(|tag| json!({ "tag": tag })),"a11y": a11y, })}/// His own addresses as `email_account` rows name them, with the short tag Post shows on a mail that came to one/// that is not his first.#[derive(Default)]pub(crate) structOwnAddresses { rows: Vec<(String, Option<String>, String)>,}implOwnAddresses {pub(crate) fn read(ctx: &mutCtx<'_>) -> OwnAddresses {letmut found: Vec<(String, Option<String>, String, f64)> = accounts(ctx) .into_iter() .filter_map(|r| Some((lower(s(&r, "address"))?, s(&r, "tag"), s(&r, "id").unwrap_or_default(), r.get("position").and_then(Value::as_f64).unwrap_or(0.0)))) .collect(); found.sort_by(|a, b| a.3.partial_cmp(&b.3).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));OwnAddresses { rows: found.into_iter().map(|(a, t, id, _)| (a, t, id)).collect() } }/// The tag of `address` when it is one of his and not the first: the mail came somewhere other than usual.fn tag_of(&self, address: &str) -> Option<String> {let at = self.rows.iter().position(|(a, _, _)| a == address)?; (at > 0).then(|| self.rows[at].1.clone().unwrap_or_else(|| address.split('@').next().unwrap_or(address).to_string())) }}/// The `email_account` rows this copy holds, by the table's own definition; none where the copy has no such table.pub(crate) fn accounts(ctx: &mutCtx<'_>) -> Vec<Map<String, Value>> {let ask = json!({ "table": "email_account", "where": {}, "limit": 100 }).as_object().cloned().unwrap_or_default();match tables::list_records(ctx, &ask) {Ok(listed) => listed["records"] .as_array() .cloned() .unwrap_or_default() .into_iter() .filter(|r| r.get("deleted_at").is_none_or(Value::is_null)) .map(|r| {letmut row = r["data"].as_object().cloned().unwrap_or_default();ifletSome(id) = r["id"].as_str() { row.insert("id".into(), json!(id)); } row }) .collect(),Err(_) => Vec::new(), }}/// The start of today in the reader's zone, as the copy's dates are written.fn today_start(clock: &Clock) -> String {let zone: chrono_tz::Tz = clock.zone.parse().unwrap_or(chrono_tz::UTC);let local = clock.now.with_timezone(&zone).date_naive().and_hms_opt(0, 0, 0).unwrap(); local.and_local_timezone(zone).earliest().map(|t| t.with_timezone(&chrono::Utc)).unwrap_or(clock.now).to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}// ── mail.home ──────────────────────────────────────────────────────────/// How many of the newest conversations the home's bands look through.const HOME_BUDGET: usize = 400;/// People rows the home shows before "more".const HOME_PEOPLE: usize = 6;/// Mail that asks for something stands in Waiting on you this long.const WAITING_DAYS: i64 = 14;/// Words in a machine's subject that ask him to act.const ASKS: &[&str] = &["confirm", "verify", "action required", "complete your", "expires", "expiring", "renew", "approve"];fn home(client: &ClientController, request: &Value) -> Result<Value, MethodError> { writer::tidy(client);let account = request.get("account").and_then(Value::as_str).map(str::to_lowercase);let clock = Clock::of(client);let now = chrono::Utc::now();let since = (now - chrono::Duration::days(WAITING_DAYS)).to_rfc3339();let today = today_start(&clock);// Every sender's tally over the whole Inbox, and how many mails he can search, are the slow part of a home the// copy has not answered since it changed: read on a second reader of the pool while this one walks the people.let (tallied, answered) = std::thread::scope(|scope| {let beside = scope.spawn(|| home_tallies(client, &today, account.as_deref()));let answered = home_people(client, account.as_deref(), &since); (beside.join().unwrap_or_else(|_| Err(MethodError::new("unreadable", "home's tallies stopped"))), answered) });let (people, waiting, senders, own, know) = answered?;let (tallies, unread_tallies, total) = tallied?;// The chips' unread counts: People by the person rule, each machine group by its senders' kind.letmut unread: HashMap<&'static str, usize> = HashMap::new();for r in &unread_tallies {letSome(a) = s(r, "a") else { continue };let n = r.get("n").and_then(Value::as_i64).unwrap_or(0) as usize;match senders.get(&a) {Some(Some(kind)) => *unread.entry(kind.id()).or_default() += n, _ if !know.is_own(&a) && know.who(&a, None, None) == Who::Person => *unread.entry("people").or_default() += n, _ => {} }if !know.is_own(&a) && know.who(&a, None, None) != Who::Junk { *unread.entry("unread").or_default() += n; } }// From machines: by sender, every mail in the Inbox counted, and how many came today.letmut counts: HashMap<&'static str, (usize, usize, Vec<String>)> = HashMap::new();for r in &tallies {letSome(a) = s(r, "a") else { continue };let n = r.get("n").and_then(Value::as_i64).unwrap_or(0) as usize;ifletSome(Some(kind)) = senders.get(&a) {let entry = counts.entry(kind.id()).or_default(); entry.0 += r.get("today").and_then(Value::as_i64).unwrap_or(0) as usize; entry.1 += n; entry.2.push(a); } }let rows_of = |convs: &[Conv]| convs.iter().map(|c| row(&clock, &know, c, &own)).collect::<Vec<_>>();let people_new = people.iter().filter(|c| c.unread).count();let waiting_rows: Vec<Value> = waiting .iter() .map(|c| {letmut r = row(&clock, &know, c, &own);let person = c.who(&know) == Who::Person; r["act"] = json!(p(if person { "home.reply" } else { "home.open" }, &[])); r["line"] = json!(p("home.waiting_asked", &[("ago", &clock.recent(&c.last_at).unwrap_or_default())])); r }) .collect();let today_machines: usize = counts.values().map(|(t, _, _)| t).sum();let groups: Vec<Value> = Kind::ALL .iter() .filter_map(|k| {let (today, inbox, senders) = counts.get(k.id())?; (*inbox > 0).then(|| {let names: Vec<String> = senders.iter().take(3).map(|a| know.name_of(a).map(str::to_string).unwrap_or_else(|| a.split('@').nth(1).unwrap_or(a).split('.').next().unwrap_or(a).to_string())).collect(); json!({ "id": format!("group:{}", k.id()), "title": p(&format!("groups.{}", k.id()), &[]), "line": names.join(", "), "count": today, "inbox": inbox }) }) }) .collect();Ok(json!({"title": p("home.title", &[]),"search": { "hint": counted("home.search", total) },"people": { "title": p("home.people", &[]), "line": (people_new > 0).then(|| counted("home.people_new", people_new)), "rows": rows_of(&people), "more": { "place": "people", "label": p("home.people", &[]) } },"waiting": (!waiting_rows.is_empty()).then(|| json!({ "title": p("home.waiting", &[]), "rows": waiting_rows })),"machines": (!groups.is_empty()).then(|| json!({ "title": p("home.machines", &[]), "line": counted("home.machines_today", today_machines), "groups": groups })),"status": status(client),"history": history_post(client),"write": p("home.write", &[]),"chips": chips(&unread),"empty": (people.is_empty() && groups.is_empty()).then(|| p(if total == 0 && !has_mail(client) { "empty.no_accounts" } else { "empty.inbox" }, &[])), }))}/// Mail's chips under its search field (owner, 26 Nov 2026): All (the whole Inbox, newest first, the default), People,/// Unread, then the machine kinds; each the `mail.list` place it opens, with its unread count when above zero (none on All).fn chips(unread: &HashMap<&'static str, usize>) -> Vec<Value> {let count = |id: &str| unread.get(id).copied().filter(|n| *n > 0).map(|n| cotton_core::rules::shell_lines::number(n as i64));letmut out = vec![json!({ "id": "all", "label": p("home.chips.all", &[]), "place": "inbox" })];for id in ["people", "unread"] { out.push(json!({ "id": id, "label": p(&format!("home.chips.{id}"), &[]), "place": id, "count": count(id) })); }for kind inKind::ALL { out.push(json!({ "id": kind.id(), "label": p(&format!("home.chips.{}", kind.id()), &[]), "place": format!("group:{}", kind.id()), "count": count(kind.id()) })); } out}/// Home's people, what waits on him and each sender's kind: the walk of the Inbox (see `home`).#[allow(clippy::type_complexity)]fn home_people(client: &ClientController, account: Option<&str>, since: &str) -> Result<(Vec<Conv>, Vec<Conv>, HashMap<String, Option<Kind>>, OwnAddresses, Know), MethodError> { read(client, "mail.home", |ctx| {let know = cuts::know(ctx)?;let own = OwnAddresses::read(ctx);letmut waiting = Vec::new();let (people, _) = walk(ctx, &know, Scope::Inbox, account, None, HOME_PEOPLE, HOME_BUDGET, |know, c| {let who = c.who(know);let theirs_last = c.newest.as_ref().and_then(|m| lower(s(m, "from_email"))).is_some_and(|f| !know.is_own(&f));let recent = c.last_at.as_str() >= since;let asks = c.newest.as_ref().and_then(|m| s(m, "body").or_else(|| s(m, "snippet"))).is_some_and(|t| t.contains('?'));let machine_asks = who == Who::Machine && c.unread && c.subject.as_deref().is_some_and(|s| {let s = s.to_lowercase(); ASKS.iter().any(|w| s.contains(w)) });if recent && theirs_last && ((who == Who::Person && asks) || machine_asks) && waiting.len() < 3 { waiting.push(c.id.clone()); } who == Who::Person })?;// People first, unread on top, each newest first.letmut people = people; people.sort_by(|a, b| b.unread.cmp(&a.unread).then(b.last_at.cmp(&a.last_at)));letmut waiting_convs: Vec<Conv> = Vec::new();for id in &waiting {letSome(t) = one(ctx, &format!("SELECT id, subject, last_at, email_count, sender_address, sender_kind FROM {MAIL_THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.clone())])? else { continue };ifletSome(c) = conv_in(ctx, &know, &t, Scope::Inbox, account)? { waiting_convs.push(c); } }// From machines: by sender, every mail in the Inbox counted, and how many came today (read beside, above).let senders = sender_kinds(ctx, &know)?;Ok((people, waiting_convs, senders, own, know)) })}/// Each sender's machine group by the rule over the newest mail they sent here; `None` for a person or junk.pub(super) fn sender_kinds(ctx: &mutCtx<'_>, know: &Know) -> Result<HashMap<String, Option<Kind>>, String> { kept::kept(ctx, "sender_kinds", |ctx| {let newest = rows(ctx, &newest_sql(&format!("lower(trim(from_email)) AS a, {}", know.mail_columns()), "1"), &[ws(ctx)])?;// His own mail is no sender's: it never counts in a group.Ok(newest.iter().filter_map(|m| Some((s(m, "a")?, m))).filter(|(a, _)| !know.is_own(a)).map(|(a, m)| (a.clone(), kind_of(know, &a, None, Some(m)))).collect()) })}fn has_mail(client: &ClientController) -> bool { read(client, "mail.any", |ctx| Ok(one(ctx, &format!("SELECT 1 AS x FROM {EMAILS} WHERE workspace_id = ? LIMIT 1"), &[ws(ctx)])?.is_some())).unwrap_or(false)}/// How mail is fetched, in one quiet line (`status.*`), from the accounts Post holds. Until the accounts' fetchers/// report (CONTRACT rows 11 to 13), an account the Mac fetches says so and nothing more.fn status(client: &ClientController) -> Value {let ways: Vec<String> = read(client, "mail.status", |ctx| {letmut rows = accounts(ctx); rows.sort_by(|a, b| a.get("position").and_then(Value::as_f64).partial_cmp(&b.get("position").and_then(Value::as_f64)).unwrap_or(std::cmp::Ordering::Equal));Ok(rows.iter().filter_map(|r| s(r, "way")).collect()) }) .unwrap_or_default();// No account, or none that says how it is fetched (signed out on a fresh phone): no foot at all, never a Mac// that fetches nothing (the Android walk, 27 Nov 2026).let line = match ways.first().map(String::as_str) {Some("cotton") => p("status.cotton", &[]),Some("phone") => p("status.phone", &[("ago", "")]).trim_end_matches([' ', '·']).to_string(),Some("arrives") => p("status.arrives", &[]),Some("mac") => p("status.mac", &[]), _ => returnValue::Null, }; json!({ "line": line, "state": "live" })}/// The history line in Post's words.fn history_post(client: &ClientController) -> Value {letSome(h) = crate::phone::mail_history::mail_history(client) else { returnValue::Null };let held = cotton_core::rules::shell_lines::number(h.held as i64);let total = cotton_core::rules::shell_lines::number(h.total as i64);let month = h.back_to.as_deref().and_then(|m| chrono::NaiveDate::parse_from_str(&format!("{m}-01"), "%Y-%m-%d").ok()).map(|d| d.format("%B %Y").to_string()).unwrap_or_default();let paused = h.paused.as_ref().map(|paused| match paused {crate::phone::mail_history::Paused::Offline => p("history.paused_offline", &[]),crate::phone::mail_history::Paused::MacOffline => p("history.paused_mac_offline", &[]),crate::phone::mail_history::Paused::Mac(_) => p("history.paused_mac_asleep", &[]), }); json!({ "line": p("history.line", &[("month", &month), ("held", &held), ("total", &total)]), "paused": paused })}// ── mail.list ──────────────────────────────────────────────────────────fn place(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let place = request.get("place").and_then(Value::as_str).unwrap_or("inbox").to_string();let account = request.get("account").and_then(Value::as_str).map(str::to_lowercase);let after = request.get("after").and_then(Value::as_str).and_then(|c| c.split_once('\u{1f}')).map(|(a, b)| (a.to_string(), b.to_string()));let clock = Clock::of(client);// The lists tidy too (local repairs only: UNDO SEND 5). writer::tidy(client);if place == "drafts" {return drafts(client, &clock); }// Opening the Bin never writes (decision 1): its 30 days are kept in the background ([`keep_the_bin`]).ifletSome(key) = place.strip_prefix("from:") {return from_sender(client, &clock, key, account.as_deref(), after.as_ref()); }let group = place.strip_prefix("group:").map(|g| Kind::of_id(g).ok_or_else(|| bad("place", "inbox, people, unread, group:receipts, group:shops, group:newsletters, group:notices, from:<sender>, sent, archived, bin or drafts"))).transpose()?;let scope = match place.as_str() {"inbox" | "sent" | "people" => Scope::Inbox,"archived" => Scope::Archived,"bin" => Scope::Bin,"unread" => Scope::Unread, _ if group.is_some() => Scope::Inbox, _ => returnErr(bad("place", "inbox, people, unread, group:receipts, group:shops, group:newsletters, group:notices, from:<sender>, sent, archived, bin or drafts")), };let scope = if place == "sent" { Scope::Any } else { scope };let (found, next, know, own, inbox_count, today_count, unread_mails, upto) = read(client, "mail.list", |ctx| {let know = cuts::know(ctx)?;let own = OwnAddresses::read(ctx);let (found, next) = walk(ctx, &know, scope, account.as_deref(), after.as_ref(), PAGE, usize::MAX, |know, c| match (place.as_str(), group) { (_, Some(kind)) => kind_of_conv(know, c) == Some(kind), ("sent", _) => know.sent.contains(&c.id), ("people", _) => know.who(&c.address, c.stored.as_deref(), c.theirs.as_ref().or(c.newest.as_ref())) == Who::Person,// Out of the Inbox because he sent it is not archived: only mail someone sent him is. ("archived", _) => c.newest.as_ref().and_then(|m| lower(s(m, "from_email"))).is_some_and(|f| !know.is_own(&f)), _ => true, })?;// A group's line counts its mail in the Inbox, and today's.// A group's Mark read counts its unread mail in the Inbox and says the newest landing this copy knows// (`upto`): the act covers what landed by then, so mail arriving after the list is never marked read unseen.let (inbox, today, unread_mails) = match group {Some(kind) => {let senders: Vec<String> = sender_kinds(ctx, &know)?.into_iter().filter(|(_, k)| *k == Some(kind)).map(|(a, _)| a).collect();let today = today_start(&clock);let tallied = rows_in(ctx, &format!("SELECT sent_at, {} AS unread FROM {EMAILS} WHERE workspace_id = ?{}", mail_predicate::unread(""), cuts::inbox(&know, "")), "lower(trim(from_email))", &senders)?;let inbox = tallied.len();let today = tallied.iter().filter(|r| s(r, "sent_at").is_some_and(|at| at >= today)).count();let unread_mails = tallied.iter().filter(|r| r.get("unread").and_then(Value::as_i64) == Some(1)).count(); (inbox, today, unread_mails) }None => (0, 0, 0), };// The newest landing this copy knows: one seek of `_mail_landed_at`, never a pass over the mail (item 2).let upto: Option<String> = if group.is_some() { cuts::newest_landed(ctx)? } else { None };Ok((found, next, know, own, inbox, today, unread_mails, upto)) })?;let rows: Vec<Value> = found.iter().map(|c| row(&clock, &know, c, &own)).collect();let title = match (place.as_str(), group) { (_, Some(kind)) => p(&format!("groups.{}", kind.id()), &[]), ("inbox", _) => p("home.title", &[]), ("people", _) => p("home.people", &[]), ("unread", _) => p("home.chips.unread", &[]), (other, _) => p(&format!("side.{other}"), &[]), };let unread = found.iter().filter(|c| c.unread).count();let (line, why, bulk) = match group {Some(_) => (Some(p("groups.line", &[("today", &today_count.to_string()), ("inbox", &cotton_core::rules::shell_lines::number(inbox_count as i64))])),Some(json!({ "line": p("groups.why", &[("rule", &p(&format!("groups.rule.{}", place.trim_start_matches("group:")), &[]))]), "rules": p("groups.see_rules", &[]) })),Some(json!([ { "act": "read", "label": counted("groups.mark_read", unread_mails), "count": unread_mails, "scope": "group", "key": place, "upto": upto }, { "act": "archive", "label": counted("groups.archive", inbox_count), "count": inbox_count }, ])), ),None => (None, None, None), };let empty = rows.is_empty().then(|| p(&format!("empty.{}", if group.is_some() || place == "people" { "inbox" } else { place.as_str() }), &[]));Ok(json!({ "title": title, "line": line, "rows": rows, "why": why, "bulk": bulk, "after": next, "empty": empty, "bin": (place == "bin").then(|| json!({ "line": p("bin.line", &[]), "empty": (!rows.is_empty()).then(|| p("bin.empty_now", &[("n", &rows.len().to_string())])) })) }))}/// `mail.list { place: "from:<sender>" }`: every conversation with mail from the sender (each of its addresses, as/// its page counts them), newest first by their newest mail from it, paged; the heading is how many mails they sent.fn from_sender(client: &ClientController, clock: &Clock, key: &str, account: Option<&str>, after: Option<&(String, String)>) -> Result<Value, MethodError> {let (addresses, count) = senders::addresses_of(client, key)?;let (found, next, know, own) = read(client, "mail.list.from", |ctx| {let know = cuts::know(ctx)?;let own = OwnAddresses::read(ctx);let marks = vec!["?"; addresses.len()].join(", ");letmut params = vec![ws(ctx)]; params.extend(addresses.iter().map(|a| text(a.clone())));letmut sql = format!("SELECT thread_id AS id, max(sent_at) AS at FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND lower(trim(from_email)) IN ({marks})", live_mail = mail_predicate::live(""));ifletSome(a) = account { sql.push_str(" AND lower(coalesce(account, gmail_account, '')) = ?"); params.push(text(a.to_lowercase())); } sql.push_str(" AND thread_id IS NOT NULL GROUP BY thread_id");ifletSome((at, id)) = after { sql.push_str(" HAVING (max(sent_at), thread_id) < (?, ?)"); params.push(text(at.clone())); params.push(text(id.clone())); } sql.push_str(&format!(" ORDER BY at DESC, id DESC LIMIT {}", PAGE + 1));let threads = rows(ctx, &sql, ¶ms)?;let more = threads.len() > PAGE;letmut found = Vec::new();letmut last = None;for t in threads.iter().take(PAGE) { last = Some((s(t, "at").unwrap_or_default(), s(t, "id").unwrap_or_default()));letSome(id) = s(t, "id") else { continue };letSome(thread) = one(ctx, &format!("SELECT id, subject, last_at, email_count, sender_address, sender_kind FROM {MAIL_THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id)])? else { continue };ifletSome(c) = conv_in(ctx, &know, &thread, Scope::Any, account)? { found.push(c); } }let next = if more { last.map(|(a, b)| format!("{a}\u{1f}{b}")) } else { None };Ok((found, next, know, own)) })?;let rows: Vec<Value> = found.iter().map(|c| row(clock, &know, c, &own)).collect();Ok(json!({ "title": counted("senders.mails", count as usize), "rows": rows, "after": next }))}fn drafts(client: &ClientController, clock: &Clock) -> Result<Value, MethodError> {let lines = list::lines();let kept = keeps_drafts(client)?;let (know, drafts) = read(client, "mail.list", |ctx| Ok((cuts::know(ctx)?, if kept { writing::drafts_of(ctx)? } else { Vec::new() })))?;let rows: Vec<Value> = drafts .iter() .map(|d| {letmut r = writing::draft_row(&lines, clock, &know, d);// Never a plain Draft while it is on its way or did not go (UNDO SEND 2 and 3): Sending with its time and// Undo, waiting, or why it did not go.let (mark, note, sending) = writer::row_of(client, d); r["mark"] = json!(mark); r["note"] = note;if !sending.is_null() { r["sending"] = sending; } r }) .collect();Ok(json!({ "title": p("side.drafts", &[]), "rows": rows, "empty": drafts.is_empty().then(|| p("empty.drafts", &[])) }))}// ── mail.side ──────────────────────────────────────────────────────────/// The side page. `counts: false` answers the rows alone, from the addresses the phone holds, counting no mail and/// reading no labels: the phone draws them the moment the page opens and asks the whole answer after (the owner's bug/// on Post build 2: with 86,000 mails mid-sync the counts took 1 to 2 seconds and the page slid in empty).fn side(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let counting = request["counts"].as_bool() != Some(false);let (own, labels, counts) = read(client, "mail.side", |ctx| {let own = OwnAddresses::read(ctx);if !counting {returnOk((own, Vec::new(), (0, 0, 0))); }let know = cuts::know(ctx)?;let inbox_unread = one(ctx, &format!("SELECT count(*) AS n FROM {EMAILS} WHERE workspace_id = ?{} AND {unread_mail}", cuts::inbox(&know, ""), unread_mail = mail_predicate::unread("")), &[ws(ctx)])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0);let drafts = writing::drafts_of(ctx).map(|d| d.len() as i64).unwrap_or(0);let bin = one(ctx, &format!("SELECT count(*) AS n FROM {EMAILS} WHERE workspace_id = ? AND {binned_mail}", binned_mail = mail_predicate::binned("")), &[ws(ctx)])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0);// Gmail's own labels on his mail, his and not the system's (`CATEGORY_*`, `INBOX`, `SENT`…), most used first.let labelled = rows(ctx, &format!("SELECT labels FROM {EMAILS} WHERE workspace_id = ? AND labels IS NOT NULL AND labels <> '' AND labels <> '[]' ORDER BY sent_at DESC LIMIT 2000"), &[ws(ctx)])?;letmut tally: HashMap<String, usize> = HashMap::new();for r in &labelled {let list: Vec<String> = match r.get("labels") {Some(Value::String(t)) => serde_json::from_str(t).unwrap_or_else(|_| t.split(',').map(|x| x.trim().to_string()).collect()),Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(), _ => Vec::new(), };for l in list {let system = l.starts_with("CATEGORY_") || l.starts_with('\\') || matches!(l.as_str(), "INBOX" | "SENT" | "DRAFT" | "SPAM" | "TRASH" | "UNREAD" | "STARRED" | "IMPORTANT" | "CHAT") || l.starts_with("Label_") && l.len() > 20;if !system && !l.is_empty() { *tally.entry(l).or_default() += 1; } } }letmut labels: Vec<(String, usize)> = tally.into_iter().collect(); labels.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));Ok((own, labels, (inbox_unread, drafts, bin))) })?;let (inbox_unread, drafts, bin) = counts;letmut inboxes = vec![json!({ "id": "all", "title": p("side.all_inboxes", &[]), "count": (inbox_unread > 0).then_some(inbox_unread) })];for (address, tag, id) in &own.rows { inboxes.push(json!({ "id": id, "title": address, "tag": tag })); }let places = [("drafts", drafts), ("sent", 0), ("archived", 0), ("bin", bin)] .iter() .map(|(id, n)| json!({ "id": id, "title": p(&format!("side.{id}"), &[]), "count": (*n > 0).then_some(*n) })) .collect::<Vec<_>>();Ok(json!({"open": p("side.open", &[]),"close": p("side.close", &[]),"inboxes": { "title": p("side.inboxes", &[]), "rows": inboxes },"places": { "title": p("side.places", &[]), "rows": places },"labels": (!labels.is_empty()).then(|| json!({ "title": p("side.labels", &[]), "rows": labels.iter().take(30).map(|(l, _)| json!({ "id": format!("label:{l}"), "title": l })).collect::<Vec<_>>() })),"you": p("tab.you", &[]), }))}// ── mail.thread ────────────────────────────────────────────────────────/// A conversation of mail, as Comms reads it, in Post's words: Reply, Reply all and Forward write in Post (never the/// phone's mail app), the designed page is a tap away with its pictures held back.fn conversation(client: &ClientController, request: &Value) -> Result<Value, MethodError> {letmut answer = super::thread_knowing(client, request, cuts::know)?;ifletSome(object) = answer.as_object_mut() { object.remove("reply"); object.remove("write"); object.remove("chat"); object.remove("drafts"); }let sender = answer["with"]["name"].as_str().unwrap_or_default().to_string();let ids: Vec<String> = answer["messages"].as_array().into_iter().flatten().filter_map(|m| m["email"].as_str().map(str::to_string)).collect();// To and Cc said in Post's words, from each mail's own recipients.let people = read(client, "mail.thread.names", |ctx| {let know = cuts::know(ctx)?;let found = rows_in(ctx, &format!("SELECT id, recipients FROM {EMAILS} WHERE workspace_id = ?"), "id", &ids)?;Ok(found.iter().filter_map(|r| {let all = recipients_of(r.get("recipients").unwrap_or(&Value::Null));let line = |kind: &str, key: &str| {let names: Vec<String> = all.iter().filter(|(_, _, k)| k == kind).map(|(a, n, _)| if know.is_own(a) { p("thread.me", &[]) } else { shown_name(n.as_deref(), a) }).collect(); (!names.is_empty()).then(|| p(key, &[("names", &names.join(", "))])) };Some((s(r, "id")?, (line("to", "thread.to"), line("cc", "thread.cc")))) }).collect::<HashMap<String, (Option<String>, Option<String>)>>()) })?;letmut several = false;ifletSome(messages) = answer["messages"].as_array_mut() {for m in messages.iter_mut() {ifletSome((to, cc)) = m["email"].as_str().and_then(|id| people.get(id)) { m["to"] = json!(to); m["cc"] = json!(cc); }// The quoted tail folded under its own label, so the phone shows what is new first.let full = m["text"].as_str().unwrap_or_default().to_string();ifletSome((new, quoted)) = split_quoted(&full) { m["text"] = json!(new); m["links"] = json!(cotton_core::messages::links::links_at(&new)); m["quoted"] = json!({ "label": p("thread.quoted", &[]), "text": quoted, "links": cotton_core::messages::links::links_at("ed) }); } several |= m["cc"].is_string() || m["to"].as_str().is_some_and(|t| t.contains(','));if m["mine"].as_bool() == Some(true) { m["from"]["name"] = json!(p("thread.you", &[])); }ifletSome(atts) = m["attachments"].as_array_mut() {for a in atts.iter_mut() {if runs_code(a["name"].as_str().unwrap_or_default()) { a["note"] = json!(p("thread.attachment_code", &[])); a["opens"] = json!(false); }if a["kept"].as_bool() == Some(true) { a["line"] = json!(p("thread.attachment_kept", &[])); } } } } } answer["acts"] = json!({"reply": { "mode": "reply", "label": p("thread.reply", &[]) },"reply_all": several.then(|| json!({ "mode": "all", "label": p("thread.reply_all", &[]) })),"forward": { "mode": "forward", "label": p("thread.forward", &[]) }, }); answer["page"] = json!({ "label": p("thread.page", &[]), "pictures": { "line": p("thread.pictures.off", &[("sender", &sender)]), "load": p("thread.pictures.load", &[]), "always": p("thread.pictures.always", &[("sender", &sender)]) } });let address = answer["messages"].as_array().into_iter().flatten().find(|m| m["mine"] != json!(true)).and_then(|m| m["from"]["address"].as_str()).unwrap_or_default().to_string(); answer["page"]["pictures"]["on"] = json!(you::pictures_on(client, &address)); answer["page"]["pictures"]["sender"] = json!(address); answer.as_object_mut().map(|o| o.remove("quoted"));Ok(answer)}/// A mail's text split at its quoted tail: what the sender wrote now, and what they quoted below it. `None` when/// nothing is quoted, or the whole mail is a quote. The tail starts at the first of: a line like "On … wrote:", a/// "-----Original Message-----" or "Forwarded message" rule, an Outlook "From: … / Sent: …" header, or the run of/// "> " lines that ends the mail.pub(super) fn split_quoted(text: &str) -> Option<(String, String)> {let lines: Vec<&str> = text.lines().collect();let starts = |i: usize| -> bool {let l = lines[i].trim();let lower = l.to_lowercase(); (lower.starts_with("on ") && (lower.ends_with("wrote:") || lines.get(i + 1).is_some_and(|n| n.trim().to_lowercase().ends_with("wrote:")))) || lower.contains("-----original message-----") || (lower.starts_with("---") && lower.contains("forwarded message")) || (lower.starts_with("from:") && lines.iter().skip(i + 1).take(4).any(|n| { let n = n.trim().to_lowercase(); n.starts_with("sent:") || n.starts_with("date:") })) };letmut cut = (0..lines.len()).find(|&i| starts(i));if cut.is_none() {// A run of "> " lines (and blanks) to the end.letmut i = lines.len();while i > 0 && (lines[i - 1].trim_start().starts_with('>') || lines[i - 1].trim().is_empty()) { i -= 1; }if i < lines.len() && lines[i..].iter().any(|l| l.trim_start().starts_with('>')) { cut = Some(i); } }let cut = cut?;let new = lines[..cut].join("\n").trim_end().to_string();let quoted = lines[cut..].join("\n").trim().to_string(); (!new.trim().is_empty() && !quoted.is_empty()).then_some((new, quoted))}// ── mail.files ─────────────────────────────────────────────────────────fn kind_of_file(name: &str, mime: Option<&str>) -> &'static str {let lower = name.to_lowercase();let mime = mime.unwrap_or_default();if mime.starts_with("image/") || [".jpg", ".jpeg", ".png", ".gif", ".heic", ".webp"].iter().any(|x| lower.ends_with(x)) {"pictures" } elseif [".xls", ".xlsx", ".csv", ".numbers", ".ods"].iter().any(|x| lower.ends_with(x)) || mime.contains("spreadsheet") {"sheets" } elseif [".pdf", ".doc", ".docx", ".pages", ".txt", ".rtf", ".odt", ".key", ".ppt", ".pptx"].iter().any(|x| lower.ends_with(x)) || mime == "application/pdf" {"documents" } else {"other" }}/// Files a page lists.const FILES_PAGE: usize = 60;fn files(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let kind = request.get("kind").and_then(Value::as_str).unwrap_or("all").to_string();if !matches!(kind.as_str(), "all" | "pictures" | "documents" | "sheets" | "other") {returnErr(bad("kind", "all, pictures, documents, sheets or other")); }let person = request.get("person").and_then(Value::as_str).map(str::to_lowercase);let after = request.get("after").and_then(Value::as_str).map(str::to_string);let clock = Clock::of(client);let (found, next) = read(client, "mail.files", |ctx| {let know = cuts::know(ctx)?;letmut params = vec![ws(ctx)];letmut cut = String::new();ifletSome((at, id)) = after.as_deref().and_then(|c| c.split_once('\u{1f}')) { cut.push_str(" AND (sent_at, id) < (?, ?)"); params.push(text(at.to_string())); params.push(text(id.to_string())); }ifletSome(person) = &person { cut.push_str(" AND lower(trim(from_email)) = ?"); params.push(text(person.clone())); }letmut out = Vec::new();letmut next = None;letmut cursor_params = params.clone();loop {let files_sql = files_sql(&cut);let files_key = format!("files:{files_sql}:{:?}", &cursor_params);let batch = kept::kept(ctx, &files_key, |ctx| rows(ctx, &files_sql, &cursor_params))?;if batch.is_empty() {break; }for m in &batch {let from = lower(s(m, "from_email")).unwrap_or_default();if know.blocked.contains(&from) {continue; }let name = know.name_of(&from).map(str::to_string).unwrap_or_else(|| shown_name(s(m, "from_name").as_deref(), &from));let at = s(m, "sent_at").unwrap_or_default();for (index, a) in attachments_of(m).iter().enumerate() {let file = a.get("name").and_then(Value::as_str).unwrap_or_default();let k = kind_of_file(file, a.get("mime").and_then(Value::as_str));if kind != "all" && k != kind {continue; }letmut row = json!({"email": s(m, "id"), "index": index, "name": file, "kind": k,"size": a.get("size").and_then(Value::as_i64).map(|b| cotton_core::records::page::bytes_words(b as f64)),"from": name.clone(), "when": clock.recent(&at), "line": p("files.from", &[("name", &name), ("when", &clock.recent(&at).unwrap_or_default())]),"can": a.get("key").and_then(Value::as_str).is_some(), });// A kind that runs code is offered only to Save, from Files as from its thread.if runs_code(file) { row["opens"] = json!(false); row["note"] = json!(p("thread.attachment_code", &[])); } out.push(row); }if out.len() >= FILES_PAGE { next = Some(format!("{}\u{1f}{}", at, s(m, "id").unwrap_or_default()));returnOk((out, next)); } }if batch.len() < 200 {break; }let last = batch.last().unwrap(); cursor_params = params.clone();if after.is_none() { cut.push_str(" AND (sent_at, id) < (?, ?)"); } cursor_params.push(text(s(last, "sent_at").unwrap_or_default())); cursor_params.push(text(s(last, "id").unwrap_or_default())); }Ok((out, next)) })?;let kinds: Vec<Value> = ["all", "pictures", "documents", "sheets", "other"].iter().map(|k| json!({ "id": k, "label": p(&format!("files.kinds.{k}"), &[]), "on": *k == kind })).collect();Ok(json!({ "title": p("files.title", &[]), "kinds": kinds, "rows": found, "after": next, "empty": found.is_empty().then(|| p("files.empty", &[])) }))}// ── mail.search ────────────────────────────────────────────────────────fn search(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let words = request.get("text").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_string();if words.is_empty() {returnOk(json!({ "hint": p("search.hint", &[]), "people": [], "mail": [], "files": [] })); }let clock = Clock::of(client);// The next page of mail (`after`, from the last answer's `mail.after`); people and files come on the first only.let after = request.get("after").and_then(Value::as_str).and_then(|c| c.split_once('\u{1f}')).map(|(a, b)| (a.to_string(), b.to_string()));let (found, next, know, own) = read(client, "mail.search", |ctx| {let know = cuts::know(ctx)?;let own = OwnAddresses::read(ctx);let (found, next) = searched_by_index(ctx, &know, &words, after.as_ref())?;Ok((found, next, know, own)) })?;letmut people = Vec::new();letmut mail = Vec::new();letmut seen_people = HashSet::new();for c in &found {let r = row(&clock, &know, c, &own);if after.is_none() && c.who(&know) == Who::Person && seen_people.insert(c.address.clone()) && people.len() < 4 {let name = r["from"]["name"].as_str().unwrap_or_default().to_lowercase();if name.contains(&words.to_lowercase()) || c.address.contains(&words.to_lowercase()) { people.push(r.clone()); } } mail.push(r); }let files_found = if after.is_some() { Vec::new() } else { files(client, &json!({}))?["rows"].as_array().cloned().unwrap_or_default().into_iter().filter(|f| f["name"].as_str().is_some_and(|n| n.to_lowercase().contains(&words.to_lowercase()))).take(6).collect::<Vec<_>>() };let none = people.is_empty() && mail.is_empty() && files_found.is_empty();Ok(json!({"people": { "title": p("search.people", &[]), "rows": people },"mail": { "title": p("search.mail", &[]), "rows": mail, "after": next },"files": { "title": p("search.files", &[]), "rows": files_found },"empty": none.then(|| p("search.empty", &[("text", &words)])), }))}#[path = "chat_mail_post_acts.rs"]mod acts;#[path = "chat_mail_post_cuts.rs"]pub(crate) mod cuts;#[path = "chat_mail_post_kept.rs"]mod kept;#[path = "chat_mail_post_you.rs"]mod you;#[path = "chat_mail_post_senders.rs"]mod senders;#[path = "chat_mail_post_write.rs"]mod writer;#[path = "chat_mail_post_accounts.rs"]mod accounts;#[path = "chat_mail_post_domains.rs"]mod domains;#[path = "chat_mail_post_fetch.rs"]mod fetcher;/// A file whose kind runs code when opened (DECISIONS: attachments): never opened in Post, offered only to Save.pub(crate) fn runs_code(name: &str) -> bool {let name = name.to_lowercase(); [".exe", ".scr", ".js", ".vbs", ".bat", ".cmd", ".msi", ".jar", ".apk", ".docm", ".xlsm", ".pptm"].iter().any(|x| name.ends_with(x))}#[cfg(test)]#[path = "chat_mail_post_tests.rs"]mod tests;/// Post's search: the copy's wide index of mail (`fts_mail`: subject, body, and who it is from), every word's start,/// newest conversation first. Its words cover what Comms' search also scanned for with LIKE (the sender's name and/// address, the subject), so that scan over every mail is left out: it read all 110,000 at his size (25 Nov 2026)./// While this device is still filling the index, Comms' search answers as before. Paged by the newest mail of each/// conversation and its id (`after`, as a sender's page is), so every hit is reachable, never the first page alone.fn searched_by_index(ctx: &mutCtx<'_>, know: &Know, words: &str, after: Option<&(String, String)>) -> Result<(Vec<Conv>, Option<String>), String> {let filled = cotton_store::fts_fill::filling(ctx.db(), crate::phone::mail_index::INDEX).is_ok_and(|fill| fill.is_none());let phrase: Vec<String> = words.split_whitespace().map(|w| format!("\"{}\"*", w.replace('"', ""))).collect();if !filled || phrase.is_empty() {return searched(ctx, know, words, after); }let index = crate::phone::mail_index::INDEX;let asked = phrase.join(" "); keyed_conversations(ctx, know, after, |ctx, cursor| {let (having, cut) = below(cursor, "e.");letmut params = vec![text(asked.clone()), ws(ctx)]; params.extend(cut);let sql = format!("SELECT e.thread_id, max(e.sent_at) AS at FROM {index} f CROSS JOIN {EMAILS} e ON e.rowid = f.rowid WHERE {index} MATCH ? AND e.workspace_id = ? AND {live_mail} AND e.thread_id IS NOT NULL GROUP BY e.thread_id{having} ORDER BY at DESC, e.thread_id DESC LIMIT {SEARCH_BATCH}", live_mail = mail_predicate::live("e.") ); kept::kept(ctx, &format!("search:{asked}:{cursor:?}"), |ctx| rows(ctx, &sql, ¶ms)) })}/// Home's tallies: every Inbox sender's count and today's, and every mail he can search, kept while the copy is/// unchanged. Only the cuts of the facts of senders shape the Inbox, so this reads those alone.#[allow(clippy::type_complexity)]fn home_tallies(client: &ClientController, today: &str, account: Option<&str>) -> Result<(Vec<Map<String, Value>>, Vec<Map<String, Value>>, usize), MethodError> { read(client, "mail.home.tallies", |ctx| {let know = Know { cuts: cuts::read_cuts(ctx), ..Know::default() };letmut account_clause = String::new();letmut params = vec![text(today.to_string()), ws(ctx)];ifletSome(a) = account { account_clause.push_str(" AND lower(coalesce(account, gmail_account, '')) = ?"); params.push(text(a.to_string())); }let in_inbox = cuts::inbox(&know, "");let sql = tallies_sql(&in_inbox, &account_clause);let tallies = kept::kept(ctx, &format!("home_tallies:{sql}:{params:?}"), |ctx| rows(ctx, &sql, ¶ms))?;// Each Inbox sender's unread mail, for the chips' counts.let unread_sql = format!("SELECT lower(trim(from_email)) AS a, count(*) AS n FROM {EMAILS} WHERE workspace_id = ?{in_inbox}{account_clause} AND {unread_mail} GROUP BY lower(trim(from_email))", unread_mail = mail_predicate::unread(""));let unread = kept::kept(ctx, &format!("home_unread:{unread_sql}:{params:?}"), |ctx| rows(ctx, &unread_sql, ¶ms[1..]))?;// The search field counts every mail he can search, not the Inbox.let total = kept::kept(ctx, "home_total", |ctx| {Ok(one(ctx, &format!("SELECT count(*) AS n FROM {EMAILS} WHERE workspace_id = ? AND {live_mail}", live_mail = mail_predicate::live("")), &[ws(ctx)])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0) as usize) })?;Ok((tallies, unread, total)) })}