311 lines · 18.1 KB · RustRaw
//! Post's You (assets/design/mail/CONTRACT.md "You"), and the choices kept on this phone.//!//! ```text//! mail.you → { title, card, groups: [{ id, title, rows: [{ id, title, value?, open? }] }] }//! mail.set { name, value } → mail.you again notifications: people | everyone | none; undo_send: 0|5|10|20|30//! mail.pictures.always { sender, on? } → { sender, always, line }//! ```//!//! The rows are the app's own (Accounts, Signature, Notifications, Sorting rules, Undo send, Domains, Look), then the//! ones every Cotton app has (Sync, Privacy, Storage, Help, About), as `vault.settings` answers Secrets. A row with//! `open` names the page the phone pushes (`page`), or the choices it offers in place (`choices`, `name`).//! Notifications, Undo send and pictures-always are this phone's choices, kept beside its copy.use super::super::*;use super::p;use cotton_core::rules::mail_predicate;const PREFS: &str = "post-prefs.json";const UNDO_CHOICES: [u64; 5] = [0, 5, 10, 20, 30];const NOTIFY_CHOICES: [&str; 3] = ["people", "everyone", "none"];#[derive(serde::Serialize, serde::Deserialize, Default, Clone)]pub(super) struct Prefs { #[serde(default)] pub(super) notifications: Option<String>, #[serde(default)] pub(super) undo_send: Option<u64>, /// Senders whose pictures load without asking, lower case. #[serde(default)] pub(super) pictures: Vec<String>,}impl Prefs { pub(super) fn undo_seconds(&self) -> u64 { self.undo_send.unwrap_or(5) } /// Which new mail a notification is for: `people` (the default), `everyone` or `none`. pub(super) fn notify(&self) -> &str { self.notifications.as_deref().unwrap_or("people") }}fn path(client: &ClientController) -> std::path::PathBuf { client.layout().client_dir().join(PREFS)}pub(super) fn prefs(client: &ClientController) -> Prefs { std::fs::read(path(client)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}fn keep(client: &ClientController, prefs: &Prefs) -> Result<(), MethodError> { let bytes = serde_json::to_vec(prefs).map_err(|e| MethodError::new("unanswerable", e.to_string()))?; // not a copy: Post's You file. std::fs::write(path(client), bytes).map_err(|e| MethodError::new("unwritable", e.to_string()))}fn page(id: &str) -> Value { json!({ "page": id })}fn row(id: &str, title: String, value: Option<String>, open: Value) -> Value { json!({ "id": id, "title": title, "value": value, "open": open })}fn group(id: &str, title: String, rows: Vec<Value>) -> Value { json!({ "id": id, "title": title, "rows": rows })}pub(super) fn you(client: &ClientController) -> Result<Value, MethodError> { let prefs = prefs(client); let (accounts, mails, exceptions, mailboxes) = read(client, "mail.you", |ctx| { let accounts = super::accounts(ctx); let mails = one(ctx, &format!("SELECT count(*) AS n FROM {EMAILS} WHERE workspace_id = ?"), &[ws(ctx)])?.and_then(|r| r.get("n").and_then(Value::as_i64)).unwrap_or(0); let exceptions = maybe(ctx, "SELECT address FROM cotton_email_senders WHERE workspace_id = ? AND decided_by = 'owner' AND verdict IN ('person', 'service')").len(); // The mailboxes his mail already here came to: Accounts says them while the account rows have not come. let mailboxes: Vec<String> = if accounts.is_empty() && mails > 0 { rows(ctx, &format!("SELECT lower(coalesce(account, gmail_account)) AS a FROM {EMAILS} WHERE workspace_id = ? AND trim(coalesce(account, gmail_account, '')) <> '' GROUP BY lower(coalesce(account, gmail_account)) LIMIT 20"), &[ws(ctx)])? .iter() .filter_map(|r| s(r, "a")) .collect() } else { Vec::new() }; Ok((accounts, mails, exceptions, mailboxes)) })?; let address = |a: &Map<String, Value>| a.get("address").and_then(Value::as_str).unwrap_or_default().to_string(); // While his mail is on its way (the first sync, `phone::first_sync`), the rows say what the phone already holds, // and a dash where it holds nothing yet, never "None" and never a sentence: the first sync's words are said once, // at the top (the card's line), and only while no mail is here (the owner, 26 Nov 2026). let coming = crate::phone::first_sync::of(client, crate::phone::first_sync::spec("mail.you").and_then(|spec| spec.tables)).and_then(|standing| standing.words()); let dash = || "—".to_string(); let accounts_value = match (accounts.as_slice(), mailboxes.as_slice()) { ([one], _) => address(one), ([], [one]) => one.clone(), ([], []) if coming.is_some() => dash(), ([], []) => p("you.accounts_none", &[]), ([], many) => p("you.accounts_many", &[("n", &many.len().to_string())]), (many, _) => p("you.accounts_many", &[("n", &many.len().to_string())]), }; let signature = accounts.iter().find_map(|a| a.get("signature").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(|s| s.lines().next().unwrap_or_default().to_string())).unwrap_or_else(|| p("you.signature_none", &[])); let domains = accounts.iter().filter(|a| a.get("kind").and_then(Value::as_str) == Some("domain")).count(); let notify_choices: Vec<Value> = NOTIFY_CHOICES.iter().map(|c| json!({ "value": c, "label": p(&format!("you.notifications_{c}"), &[]), "on": prefs.notify() == *c })).collect(); let undo_choices: Vec<Value> = UNDO_CHOICES.iter().map(|n| json!({ "value": n, "label": undo_label(*n), "on": prefs.undo_seconds() == *n })).collect(); let mine = vec![ row("accounts", p("you.accounts", &[]), Some(accounts_value), page("accounts")), row("signature", p("you.signature", &[]), Some(signature), page("signature")), row("notifications", p("you.notifications", &[]), Some(p(&format!("you.notifications_{}", prefs.notify()), &[])), json!({ "name": "notifications", "choices": notify_choices })), row("rules", p("you.rules", &[]), Some(if exceptions == 0 { p("you.rules_line", &[]) } else { super::counted("you.rules_exceptions", exceptions as usize) }), page("rules")), row("undo_send", p("you.undo_send", &[]), Some(undo_label(prefs.undo_seconds())), json!({ "name": "undo_send", "choices": undo_choices })), row("domains", p("you.domains", &[]), Some(if domains > 0 { super::counted("you.domains_many", domains as usize) } else if accounts.is_empty() && coming.is_some() { dash() } else { p("you.domains_none", &[]) }), page("domains")), row("look", p("you.look", &[]), None, page("look")), ]; // A real zero has its own words. In a first sync with no mail here yet, the card says the first sync's words, once, // and Storage is titled Storage; with mail here, both say how many the phone holds. let mails_line = match mails { 0 => p("you.count_none", &[]), 1 => p("you.count_one", &[]), n => p("you.count", &[("n", &cotton_core::rules::shell_lines::number(n))]), }; // Sync says the one line every app says (`shell_account::seen`), with its count. let seen = crate::methods::shell_account::seen(client); let sync_line = seen["line"].as_str().filter(|l| !l.is_empty()).map(str::to_string); let (card_count, storage_title) = match &coming { // The count Account says while a pass counts ("Syncing 1,200 of 3,108"), else the first sync's words. Some(words) if mails == 0 => (if seen["state"] == "catching_up" { sync_line.clone().unwrap_or_else(|| words.clone()) } else { words.clone() }, p("you.storage", &[])), _ => (mails_line.clone(), mails_line.clone()), }; Ok(json!({ "title": p("you.title", &[]), "card": { "line": accounts.first().map(address).or_else(|| mailboxes.first().cloned()), "count": card_count }, "groups": [ group("post", p("app_name", &[]), mine), group("sync", p("you.sync", &[]), vec![row("sync", p("you.sync", &[]), sync_line, page("sync"))]), group("privacy", p("you.privacy", &[]), vec![row("privacy", p("you.privacy", &[]), Some(p("you.privacy_line", &[])), page("privacy"))]), group("storage", p("you.storage", &[]), vec![row("storage", storage_title, Some(p("you.storage_line", &[])), page("storage"))]), group("help", p("you.help", &[]), vec![row("help", p("you.help", &[]), Some(p("you.help_line", &[])), page("help"))]), group("about", p("you.about", &[]), vec![row("about", p("store_name", &[]), Some(p("you.about_line", &[])), page("about"))]), ], }))}fn undo_label(n: u64) -> String { if n == 0 { p("you.undo_send_off", &[]) } else { super::counted("you.undo_send_line", n as usize) }}pub(super) fn set(client: &ClientController, request: &Value) -> Result<Value, MethodError> { let name = cotton_chat::text(request, "name")?; let mut prefs = prefs(client); match name { "notifications" => { let v = request.get("value").and_then(Value::as_str).filter(|v| NOTIFY_CHOICES.contains(v)).ok_or_else(|| bad("value", "people, everyone or none"))?; prefs.notifications = Some(v.to_string()); } "undo_send" => { let v = request.get("value").and_then(Value::as_u64).filter(|v| UNDO_CHOICES.contains(v)).ok_or_else(|| bad("value", "0, 5, 10, 20 or 30"))?; prefs.undo_send = Some(v); } _ => return Err(bad("name", "notifications or undo_send")), } keep(client, &prefs)?; you(client)}pub(super) fn pictures_always(client: &ClientController, request: &Value) -> Result<Value, MethodError> { let sender = match (request.get("sender").and_then(Value::as_str), request.get("email").and_then(Value::as_str)) { (Some(sender), _) => sender.trim().to_lowercase(), (None, Some(email)) => { let email = email.to_string(); read(client, "mail.pictures.always", |ctx| Ok(one(ctx, &format!("SELECT lower(trim(from_email)) AS a FROM {EMAILS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(email.clone())])?.and_then(|r| s(&r, "a"))))?.ok_or_else(|| MethodError::new("not_found", p("act.gone", &[])))? } _ => return Err(bad("sender", "the sender's address, or `email` for the mail being read")), }; let on = request.get("on").and_then(Value::as_bool).unwrap_or(true); let mut prefs = prefs(client); prefs.pictures.retain(|s| *s != sender); if on { prefs.pictures.push(sender.clone()); } keep(client, &prefs)?; let line = if on { p("thread.pictures_always_on", &[("sender", &sender)]) } else { p("thread.pictures_always_off", &[("sender", &sender)]) }; Ok(json!({ "sender": sender, "always": on, "line": line }))}/// Whether `sender`'s pictures load without asking.pub(super) fn pictures_on(client: &ClientController, sender: &str) -> bool { prefs(client).pictures.iter().any(|s| s == &sender.trim().to_lowercase())}// ── mail.link, mail.hold ───────────────────────────────────────────────/// `mail.link { url }`: Read here (Post's own reader, keeping nothing) or Open in Sites…, which hands the link to/// Sites and its own chooser (DECISIONS question 11, settled with Sites). Post never reads Sites' list.pub(super) fn link(request: &Value) -> Result<Value, MethodError> { let url = cotton_chat::text(request, "url")?.trim().to_string(); let scheme = url.split_once(':').map(|(s, _)| s.to_lowercase()).unwrap_or_default(); if !matches!(scheme.as_str(), "http" | "https") { return Err(MethodError::new("refused", p("link.refused", &[]))); } let encoded: String = url::form_urlencoded::byte_serialize(url.as_bytes()).collect(); let shown = url.split_once("://").map(|(_, rest)| rest).unwrap_or(&url).trim_end_matches('/').to_string(); Ok(json!({ "url": url, "shown": shown, "read": p("link.read", &[]), "sites": { "label": p("link.sites", &[]), "ios": { "live": format!("cottonsites://open?url={encoded}&from=post"), "dev": format!("cottonsitesdev://open?url={encoded}&from=post") }, "android": { "package": "com.cottondb.sites", "dev_package": "com.cottondb.sites.dev", "action": "android.intent.action.VIEW", "extra": { "from": "post" } }, }, "missing": p("link.missing", &[]), }))}/// `mail.hold { email }`: the long press's acts on one mail, in order.pub(super) fn hold(client: &ClientController, request: &Value) -> Result<Value, MethodError> { let email = cotton_chat::text(request, "email")?.to_string(); let found = read(client, "mail.hold", |ctx| { let Some(m) = one(ctx, &format!("SELECT id, from_email, {unread_col} AS unread, archived_at, coalesce(in_inbox, 1) AS in_inbox, sent_at, created_at, trashed_at, list_unsubscribe, {covered} AS covered FROM {EMAILS} WHERE workspace_id = ? AND id = ?", unread_col = mail_predicate::unread(""), covered = super::cuts::covered(&[], "")), &[ws(ctx), text(email.clone())])? else { return Ok(None) }; // Archived here, by his mailbox, or by an archived sender's row (the shared predicate): no Archive offered. let covered = m.get("covered").and_then(Value::as_i64) == Some(1); let archived = s(&m, "archived_at").is_some() || m.get("in_inbox").and_then(Value::as_i64) == Some(0) || covered; Ok(Some((m, archived))) })?; let Some((m, archived)) = found else { return Err(MethodError::new("not_found", p("act.gone", &[]))) }; let sender = lower(s(&m, "from_email")).unwrap_or_default(); let act = |id: &str| json!({ "id": id, "label": p(&format!("act.{id}"), &[]) }); let mut acts = vec![act(if truthy(&m, "unread") { "read" } else { "unread" })]; if s(&m, "trashed_at").is_some() { acts.push(act("restore")); } else { if !archived { acts.push(act("archive")); } acts.push(act("delete")); } if s(&m, "list_unsubscribe").is_some_and(|v| !v.trim().is_empty()) { acts.push(act("unsubscribe")); } acts.push(act("block")); acts.push(act("open_sender")); Ok(json!({ "email": email, "sender": sender, "acts": acts }))}// ── mail.rules, mail.verdict ───────────────────────────────────────────/// `mail.rules`: the six rules in words, in order, the fallback, and his exceptions (each sender he said is a person/// or a machine), newest first.pub(super) fn rules(client: &ClientController) -> Result<Value, MethodError> { let list: Vec<String> = super::post().value("rules.list").and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); let yours = read(client, "mail.rules", |ctx| { let know = super::cuts::know(ctx)?; let found = maybe(ctx, "SELECT address, verdict, decided_at FROM cotton_email_senders WHERE workspace_id = ? AND decided_by = 'owner' AND verdict IN ('person', 'service') ORDER BY decided_at DESC"); let mut out = Vec::new(); for r in found { let Some(address) = s(&r, "address") else { continue }; let name = match know.name_of(&address) { Some(n) => Some(n.to_string()), None => one(ctx, &format!("SELECT from_name FROM {EMAILS} WHERE workspace_id = ? AND lower(trim(from_email)) = ? AND trim(coalesce(from_name, '')) <> '' ORDER BY sent_at DESC LIMIT 1"), &[ws(ctx), text(address.clone())])?.and_then(|r| s(&r, "from_name")), }; out.push((address, name, s(&r, "verdict").as_deref() == Some("person"))); } Ok(out .into_iter() .filter_map(|(address, name, person)| { Some(json!({ "address": address, "name": name.unwrap_or_else(|| address.clone()), "who": if person { "person" } else { "machine" }, "label": p(if person { "rules.person" } else { "rules.machine" }, &[]) })) }) .collect::<Vec<_>>()) })?; Ok(json!({ "title": p("rules.title", &[]), "line": p("rules.line", &[]), "rules": list, "fallback": p("rules.fallback", &[]), "yours": { "title": p("rules.yours", &[]), "rows": yours }, "choices": [{ "id": "person", "label": p("rules.person", &[]) }, { "id": "machine", "label": p("rules.machine", &[]) }, { "id": "clear", "label": p("rules.clear", &[]) }], }))}/// `mail.verdict { address, who: person | machine | clear }`: his word on a sender, over every rule but a block./// Answers `mail.rules` again.pub(super) fn verdict(client: &ClientController, request: &Value) -> Result<Value, MethodError> { let address = cotton_chat::text(request, "address")?.trim().to_lowercase(); let who = cotton_chat::text(request, "who")?.to_string(); let verdict = match who.as_str() { "person" => Some("person"), "machine" => Some("service"), "clear" => None, _ => return Err(bad("who", "person, machine or clear")), }; if !address.contains('@') { return Err(bad("address", "a mail address")); } let at = client.clock().now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); write(client, "mail.verdict", |ctx| { let id = cotton_store::protocol::derived_id::email_sender_id(ctx.file.namespace(), &address); let patch = json!({ "verdict": verdict, "decided_by": verdict.map(|_| "owner"), "decided_at": verdict.map(|_| at.clone()) }); let held = one(ctx, "SELECT id FROM cotton_email_senders WHERE id = ?", &[text(id.clone())])?.is_some(); if held { cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_email_senders", &id, patch.as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?; } else if verdict.is_some() { let mut row = patch.as_object().cloned().unwrap_or_default(); row.insert("address".into(), json!(address)); // A sender first met by his word: their kind is that word. row.insert("kind".into(), json!(verdict)); row.insert("workspace_id".into(), json!(ctx.workspace_id.to_string())); cotton_tools::mcp::handlers::common::insert_row(ctx, "cotton_email_senders", &id, row).map_err(|e| e.to_string())?; } Ok(()) })?; rules(client)}