Cotton code
1151 lines · 58.2 KB · RustRaw
//! Writing in Post (CONTRACT row 10): every mail is written and sent here, never in another app.//!//! ```text//! mail.compose { mode: new|reply|all|forward, thread?, email?, draft?, to? }//!     → { draft?, mode, title, from: { address, choices: [{ address, label }], why? }, to, cc, subject, body,//!         quoted?, signature?, words, undo_seconds }//! mail.save    { draft?, mode?, from?, to?, cc?, subject?, body?, quoted?, thread?, reply_to? } → { draft, said }//! mail.discard { draft }                → { said }//! mail.send    { draft }                → Sending      held for Undo send, then sent by the account's way//! mail.unsend  { draft }                → { state: "draft", line }   while it is held//! mail.sending { draft }                → Sending      sends a held mail whose time is up; Retry is this call//! ```//!//! Sending is `{ draft, state, line, undo?, until?, retry? }`, `state` one of `holding`, `waiting`, `sending`,//! `sent`, `failed`, `unknown`. A held mail waits on this phone (Undo send, You); when its time is up, `mail.sending`//! (or the next home or list) sends it once through the object's one ledger, `/v1/mail/send`: an address at his own//! domain by `route: "domain"`, any other account by `route: "smtp"` (the object holds the account's password when//! Cotton fetches). The ledger makes a second tap, or a retry after a lost answer, send nothing more.//!//! Drafts saved without anyone to send to are kept; only Send asks for a recipient.//!//! A send is held by ONE record on this phone (UNDO SEND FIX, 27 Nov 2026: on Android a mail he took back went out)://! `held` until its time, then `going` once the send takes it, `cancelled` by Undo, or `failed` once the object said//! no or could not tell. Every change to a record is made under one lock (this process's, and a file lock for any//! other process opening the folder) and written whole, so Undo and the screen's poll cannot interleave: Undo flips//! `held` to `cancelled` and nothing else; the send goes only from a `held` record whose time is up, re-read under//! the same lock that marks it `going`, and only while the draft is still what Send was tapped on (the hold carries a//! hash of it). The draft row's status (`queued`, `draft`) only says it; it never decides.//!//! UNDO SEND 2 (27 Nov 2026): opening or saving a held mail makes it a draft again (the hold is cancelled in the same//! step; it needs a new Send); a held mail lists as Sending with Undo; a failed send ends `failed` and Send again is a//! fresh hold with its Undo; a hold whose time passed while Post was closed for more than [`STALE_MS`] is not sent//! late: it goes back to Drafts, "Not sent: Post was closed".use cotton_tools::mcp::handlers::tables;use super::super::writing::{addresses, answered_ids, draft_of, every_draft, is_address, DRAFTS};use super::super::*;use super::p;use cotton_core::rules::mail_predicate;/// Held sends on this phone: draft → its hold.const HOLDS: &str = "post-holds.json";/// The file every process opening this folder locks while it changes a hold.const HOLDS_LOCK: &str = "post-holds.lock";/// The builds before UNDO SEND FIX kept their holds here (draft → ms); read once at the upgrade, then removed.const OLD_HOLDS: &str = "post-held.json";/// A hold due longer ago than this was due while nothing of Post ran (the screen reads every second and every list/// sweeps): it is not sent late, it goes back to Drafts and says so. Two minutes: past any slow read or a phone/// locked a moment after Send, well short of "hours late".const STALE_MS: i64 = 2 * 60 * 1000;#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]#[serde(rename_all = "lowercase")]enum Stage {    /// Waiting for its Undo time.    Held,    /// Undo took it back: it never goes.    Cancelled,    /// The send took it (sending, or waiting for a connection: never posted).    Going,    /// The object refused it, or could not tell whether it went (`maybe`): Send again is a fresh hold.    Failed,    /// Back in Drafts (Undo, or not sent with a reason in `said`): kept a day so Undo and the row answer from what    /// happened, never from absence.    Returned,    /// The object sent it: kept a day for the same reason.    Sent,}#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]struct Hold {    stage: Stage,    /// When it goes (ms, this phone's clock).    until: i64,    /// What Send was tapped on (a hash of the draft's words, addresses, files and account): a draft changed since is    /// never sent by this hold. None on a record from before UNDO SEND 2: never sent.    #[serde(default)]    hash: Option<String>,    /// Failed, but the object may have it (no answer, or it could not tell).    #[serde(default)]    maybe: bool,    /// The account it goes from, settled at Send (UNDO SEND 3): one of his, never the first by default later.    #[serde(default)]    from: Option<String>,    /// Why it is back in Drafts, when it did not go (`Returned`).    #[serde(default)]    said: Option<String>,    /// When it ended (`Returned`, `Sent`, `Failed`; ms), to be let go a day on.    #[serde(default)]    ended: Option<i64>,    /// The account's database the hold belongs to (UNDO SEND 5): only that account, open, ever touches it.    #[serde(default)]    db: Option<String>,}impl Hold {    fn held(until: i64, hash: String, from: String, db: Option<String>) -> Hold {        Hold { stage: Stage::Held, until, hash: Some(hash), maybe: false, from: Some(from), said: None, ended: None, db }    }    /// Whether the hold is the open account's (a hold from before its database was kept counts as the open one's).    fn of(&self, db: &Option<String>) -> bool {        self.db.is_none() || self.db == *db    }}/// An ended hold is kept this long.const ENDED_KEPT_MS: i64 = 24 * 60 * 60 * 1000;/// Each hold's moment on this process's steady clock (UNDO SEND 3): a wall clock jumping by minutes never makes a/// hold look due while Post was closed. Across a restart there is only the wall clock, which is fine.static DUE_AT: std::sync::Mutex<Vec<(String, std::time::Instant)>> = std::sync::Mutex::new(Vec::new());fn due_at(id: &str, seconds: u64) {    let mut all = DUE_AT.lock().unwrap_or_else(|e| e.into_inner());    all.retain(|(i, _)| i != id);    all.push((id.to_string(), std::time::Instant::now() + std::time::Duration::from_secs(seconds)));}/// A test moves a hold's time by hand, as if that much had passed: the steady clock did not see it go by.#[cfg(test)]pub(super) fn forget_steady(id: &str) {    DUE_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|(i, _)| i != id);}/// Whether a due hold was due so long ago that nothing of Post ran meanwhile (UNDO SEND 5): within this process the/// steady clock decides, so a wall clock moved during an open hold changes nothing; across a restart the wall clock/// decides.fn stale(id: &str, until: i64, now: i64) -> bool {    let steady = DUE_AT.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|(i, _)| i == id).map(|(_, at)| *at);    match steady {        Some(at) => std::time::Instant::now().saturating_duration_since(at) > std::time::Duration::from_millis(STALE_MS as u64),        None => now - until > STALE_MS,    }}/// A test sets a hold's steady moment, as if the steady clock had run on without the wall clock.#[cfg(test)]pub(super) fn steady_moves(id: &str, at: std::time::Instant) {    let mut all = DUE_AT.lock().unwrap_or_else(|e| e.into_inner());    all.retain(|(i, _)| i != id);    all.push((id.to_string(), at));}/// The one lock every hold changes under, and the sends under way in this process.static HOLDING: std::sync::Mutex<()> = std::sync::Mutex::new(());static IN_FLIGHT: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());/// The holds' lock: this process's, and the folder's file lock for any other (an extension opening the folder).struct Locked {    _mine: std::sync::MutexGuard<'static, ()>,    _file: Option<std::fs::File>,}/// How long Send waits for the holds' lock before it is refused as busy (only Send may be).const SEND_WAIT: std::time::Duration = std::time::Duration::from_secs(3);/// How long everything else waits (Undo first): longer than the core ever holds the lock, so Undo is never refused/// as busy and answers from the record (UNDO SEND 5).const LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);/// Both locks within `wait`, or the act is refused: no hold is ever changed unlocked, and nothing waits for ever.fn lock_within(client: &ClientController, wait: std::time::Duration) -> Result<Locked, MethodError> {    let busy = || MethodError::new("busy", p("send.busy", &[]));    let began = std::time::Instant::now();    let mine = loop {        match HOLDING.try_lock() {            Ok(guard) => break guard,            Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(),            Err(std::sync::TryLockError::WouldBlock) if began.elapsed() < wait => std::thread::sleep(std::time::Duration::from_millis(5)),            Err(std::sync::TryLockError::WouldBlock) => return Err(busy()),        }    };    let unlockable = |e: std::io::Error| MethodError::new("unwritable", format!("the send's lock: {e}"));    // not a copy: mail files.    let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(client.layout().client_dir().join(HOLDS_LOCK)).map_err(unlockable)?;    loop {        match file.try_lock() {            Ok(()) => break,            Err(std::fs::TryLockError::WouldBlock) if began.elapsed() < wait => std::thread::sleep(std::time::Duration::from_millis(5)),            Err(std::fs::TryLockError::WouldBlock) => return Err(busy()),            Err(std::fs::TryLockError::Error(e)) => return Err(unlockable(e)),        }    }    Ok(Locked { _mine: mine, _file: Some(file) })}fn lock(client: &ClientController) -> Result<Locked, MethodError> {    lock_within(client, LOCK_WAIT)}/// What Send is tapped on, as a hash: a draft changed since is not the mail the hold was made for.fn content_of(d: &Map<String, Value>) -> String {    use sha2::Digest;    let words = json!([addresses(d.get("to")), addresses(d.get("cc")), addresses(d.get("bcc")), s(d, "subject"), d.get("body"), s(d, "quoted"), s(d, "attachments"), s(d, "account")]);    hex::encode(sha2::Sha256::digest(words.to_string().as_bytes()))}fn object(value: Value) -> Map<String, Value> {    value.as_object().cloned().unwrap_or_default()}fn holds_path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(HOLDS)}fn holds(client: &ClientController) -> HashMap<String, Hold> {    std::fs::read(holds_path(client)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}/// The open account's database: holds of any other are never touched.fn open_db(client: &ClientController) -> Option<String> {    client.attached_database()}fn hold_of(client: &ClientController, id: &str) -> Result<Option<Hold>, MethodError> {    let _lock = lock(client)?;    let db = open_db(client);    Ok(holds(client).get(id).filter(|h| h.of(&db)).cloned())}/// The open account's holds.fn holds_open(client: &ClientController) -> Result<Vec<(String, Hold)>, MethodError> {    let _lock = lock(client)?;    let db = open_db(client);    Ok(holds(client).into_iter().filter(|(_, h)| h.of(&db)).collect())}/// One change to the holds: read, changed and written whole (a new file, synced to the disk, renamed over the old)/// under the one lock.fn change<R>(client: &ClientController, f: impl FnOnce(&mut HashMap<String, Hold>) -> R) -> Result<R, MethodError> {    change_within(client, LOCK_WAIT, f)}/// [`change`] within a given wait for the lock: the open account's holds only are handed to `f`; every other/// account's are written back as they were (UNDO SEND 5).fn change_within<R>(client: &ClientController, wait: std::time::Duration, f: impl FnOnce(&mut HashMap<String, Hold>) -> R) -> Result<R, MethodError> {    use std::io::Write;    let _lock = lock_within(client, wait)?;    let db = open_db(client);    let (mut all, others): (HashMap<String, Hold>, HashMap<String, Hold>) = holds(client).into_iter().partition(|(_, h)| h.of(&db));    let answer = f(&mut all);    let now = chrono::Utc::now().timestamp_millis();    all.retain(|_, h| h.ended.is_none_or(|at| now - at < ENDED_KEPT_MS));    for h in all.values_mut().filter(|h| h.db.is_none()) {        h.db = db.clone();    }    all.extend(others);    let bytes = serde_json::to_vec(&all).map_err(|e| MethodError::new("unanswerable", e.to_string()))?;    let path = holds_path(client);    let next = path.with_extension("json.next");    let unwritable = |e: std::io::Error| MethodError::new("unwritable", e.to_string());    // not a copy: mail files.    let mut file = std::fs::File::create(&next).map_err(unwritable)?;    file.write_all(&bytes).map_err(unwritable)?;    file.sync_all().map_err(unwritable)?;    drop(file);    // not a copy: mail files, put in place.    std::fs::rename(&next, &path).map_err(unwritable)?;    Ok(answer)}/// Back in Drafts with the reason it did not go: the record kept as `Returned` (so Undo and the row say what/// happened), the draft saying why.fn not_sent(client: &ClientController, id: &str, line: String) -> Result<Value, MethodError> {    returned(client, id, Some(line.clone()))?;    let _ = mark_draft(client, id, json!({ "status": "draft", "error": line }));    Ok(sending(id, "draft", line))}/// The record ends as `Returned` (kept a day), whatever it was.fn returned(client: &ClientController, id: &str, said: Option<String>) -> Result<(), MethodError> {    let now = chrono::Utc::now().timestamp_millis();    change(client, |all| {        if let Some(h) = all.get_mut(id) {            h.stage = Stage::Returned;            h.said = said;            h.ended = Some(now);        }    })}/// A failed send in words, with Send again (`retry`: the shells' Retry saves and sends, a fresh hold). "Could not/// tell" says a second send may arrive twice (the object's ledger sends an unknown one again on Retry).fn failed_answer(id: &str, maybe: bool, why: Option<String>) -> Value {    let mut out = if maybe { sending(id, "unknown", p("send.unknown", &[])) } else { sending(id, "failed", p("send.failed", &[("why", &why.unwrap_or_else(|| p("send.unknown", &[])))])) };    out["retry"] = json!(p("send.retry", &[]));    out}/// The builds before UNDO SEND FIX: their hold file goes, and a draft they left `queued` (never sent by this build)/// goes back to Drafts saying it was not sent.fn upgrade(client: &ClientController) {    let old = client.layout().client_dir().join(OLD_HOLDS);    if !old.exists() {        return;    }    let holds = holds(client);    let queued: Vec<String> = read(client, "mail.sending", |ctx| Ok(super::super::writing::drafts_of(ctx)?.into_iter().filter(|d| s(d, "status").as_deref() == Some("queued")).filter_map(|d| s(&d, "id")).collect::<Vec<_>>())).unwrap_or_default();    for id in queued.iter().filter(|id| !holds.contains_key(*id)) {        let _ = mark_draft(client, id, json!({ "status": "draft", "error": p("send.closed", &[]) }));    }    // not a copy: mail files.    let _ = std::fs::remove_file(old);}/// How the Drafts list shows a draft that has a send (UNDO SEND 2 and 3): never a plain Draft while it is on its way/// or did not go. `(mark, note, sending)`.pub(super) fn row_of(client: &ClientController, d: &Map<String, Value>) -> (String, Value, Value) {    let draft = (p("list.draft", &[]), json!(s(d, "error")), Value::Null);    let Some(id) = s(d, "id") else { return draft };    let Ok(Some(hold)) = hold_of(client, &id) else { return draft };    let now = now_ms(client);    match hold.stage {        Stage::Held => {            let held = holding(&id, hold.until, now);            (p("send.sending", &[]), held["line"].clone(), held)        }        Stage::Going if s(d, "status").as_deref() == Some("queued") => (p("send.sending", &[]), json!(p("send.waiting_offline", &[])), sending(&id, "waiting", p("send.waiting_offline", &[]))),        Stage::Going => (p("send.sending", &[]), json!(p("send.sending", &[])), sending(&id, "sending", p("send.sending", &[]))),        Stage::Failed => {            let failed = failed_answer(&id, hold.maybe, s(d, "error"));            (p("list.draft", &[]), failed["line"].clone(), failed)        }        Stage::Returned => (p("list.draft", &[]), json!(hold.said.or_else(|| s(d, "error"))), Value::Null),        Stage::Cancelled | Stage::Sent => draft,    }}/// Opening a mail that has a hold makes it a draft again (round 2's rule, UNDO SEND 5): a held one, or one waiting for/// a connection that never reached the object, is taken back, "Back in Drafts. Nothing was sent.". One the object/// may have is only opened.fn reopen(client: &ClientController, id: &str) -> Result<bool, MethodError> {    let took = change(client, |all| match all.get_mut(id) {        Some(h) if h.stage == Stage::Held || (h.stage == Stage::Going && never_posted(client, id)) => {            h.stage = Stage::Cancelled;            true        }        _ => false,    })?;    if took {        back_in_drafts(client, id);    }    Ok(took)}/// A send under way in this process, let go when dropped.struct Flight(String);impl Flight {    fn take(id: &str) -> Option<Flight> {        let mut all = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner());        if all.iter().any(|i| i == id) {            return None;        }        all.push(id.to_string());        Some(Flight(id.to_string()))    }}impl Drop for Flight {    fn drop(&mut self) {        IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()).retain(|i| *i != self.0);    }}/// A cancelled hold's draft put back in Drafts; the record goes once that write lands (until then it still stops/// the send, and the next look writes it again).fn back_in_drafts(client: &ClientController, id: &str) {    if mark_draft(client, id, json!({ "status": "draft" })).is_ok() {        let now = chrono::Utc::now().timestamp_millis();        let _ = change(client, |all| {            if let Some(h) = all.get_mut(id).filter(|h| h.stage == Stage::Cancelled) {                h.stage = Stage::Returned;                h.ended = Some(now);            }        });    }}fn holding(id: &str, until: i64, now: i64) -> Value {    let now = now.min(until);    let left = ((until - now + 999) / 1000).max(1);    let mut answer = sending(id, "holding", super::counted("send.holding", left as usize));    answer["undo"] = json!(p("send.undo", &[]));    answer["until"] = json!(until);    answer["seconds"] = json!(left);    answer}fn undone(id: &str) -> Value {    sending(id, "draft", p("send.undone", &[]))}/// The draft row told where its send stands: only the fields that change (the table refuses a patch that changes/// nothing, which is how Undo's write was refused on Android), and nothing for a draft already gone.fn mark_draft(client: &ClientController, id: &str, patch: Value) -> Result<(), MethodError> {    write(client, "mail.sending", |ctx| {        let Some(d) = draft_of(ctx, id)? else { return Ok(()) };        let changed: Map<String, Value> = object(patch.clone()).into_iter().filter(|(k, v)| d.get(k).unwrap_or(&Value::Null) != v).collect();        if !changed.is_empty() {            tables::update_produced_record(ctx, &object(json!({ "table": DRAFTS, "id": id, "patch": Value::Object(changed) }))).map_err(|f| f.to_string())?;        }        Ok(())    })    .map(|_| ())}fn in_flight(id: &str) -> bool {    IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|i| i == id)}/// A taken send that never reached the object (no connection: waiting to send) can still be stopped.fn never_posted(client: &ClientController, id: &str) -> bool {    !in_flight(id) && read(client, "mail.sending", |ctx| Ok(draft_of(ctx, id)?.and_then(|d| s(&d, "status")).as_deref() == Some("queued"))).unwrap_or(false)}fn now_ms(client: &ClientController) -> i64 {    client.clock().now().timestamp_millis()}/// His accounts he can write from, the first as he ordered them first.fn from_choices(ctx: &mut Ctx<'_>, know: &Know) -> Vec<(String, Option<String>, Option<String>)> {    let mut out: Vec<(String, Option<String>, Option<String>)> = super::accounts(ctx)        .iter()        .filter_map(|a| Some((a.get("address")?.as_str()?.to_lowercase(), a.get("tag").and_then(Value::as_str).map(str::to_string), a.get("signature").and_then(Value::as_str).map(str::to_string).filter(|s| !s.trim().is_empty()))))        .collect();    if out.is_empty() {        out.extend(know.own_first().map(|a| (a, None, None)));    }    out}fn signed(body: &str, signature: Option<&str>) -> String {    match signature {        Some(sig) => format!("{body}\n\n-- \n{}", sig.trim()),        None => body.to_string(),    }}/// The quoted mail under a reply or a forward.fn quote_of(clock: &Clock, m: &Map<String, Value>, forward: bool) -> String {    let name = s(m, "from_name").filter(|n| !n.trim().is_empty()).or_else(|| s(m, "from_email")).unwrap_or_default();    let at = s(m, "sent_at").unwrap_or_default();    let when = clock.recent(&at).unwrap_or_default();    let text = s(m, "body").or_else(|| s(m, "snippet")).unwrap_or_default();    if forward {        let head = p("write.forward_head", &[("name", &name), ("address", &s(m, "from_email").unwrap_or_default()), ("when", &when), ("subject", &s(m, "subject").unwrap_or_default())]);        return format!("{head}\n\n{text}");    }    let head = p("write.quote_head", &[("name", &name), ("when", &when)]);    let body: Vec<String> = text.lines().map(|l| if l.is_empty() { ">".to_string() } else { format!("> {l}") }).collect();    format!("{head}\n{}", body.join("\n"))}fn prefixed(subject: &str, prefix: &str) -> String {    if subject.to_lowercase().starts_with(&prefix.to_lowercase()) { subject.to_string() } else { format!("{prefix} {subject}") }}pub(super) fn compose(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let clock = Clock::of(client);    let mode = request.get("mode").and_then(Value::as_str).unwrap_or("new").to_string();    if !matches!(mode.as_str(), "new" | "reply" | "all" | "forward") {        return Err(bad("mode", "new, reply, all or forward"));    }    let draft = request.get("draft").and_then(Value::as_str).map(str::to_string);    let thread = request.get("thread").and_then(Value::as_str).map(str::to_string);    let email = request.get("email").and_then(Value::as_str).map(str::to_string);    let asked_to = addresses(request.get("to"));    let undo = super::you::prefs(client).undo_seconds();    // Opening a held mail takes it back: an ordinary draft again, said so (no Undo inside the form).    let taken_back = match &draft {        Some(id) => reopen(client, id)?,        None => false,    };    let form = read(client, "mail.compose", |ctx| {        let know = super::cuts::know(ctx)?;        let choices = from_choices(ctx, &know);        let first = choices.first().map(|c| c.0.clone());        let signature_of = |address: &str| choices.iter().find(|c| c.0 == address).and_then(|c| c.2.clone());        if let Some(id) = &draft {            let Some(d) = draft_of(ctx, id)? else { return Ok(None) };            let from = s(&d, "account").or(first.clone()).unwrap_or_default();            return Ok(Some((json!({                "draft": id, "mode": if s(&d, "thread_id").is_some() { "reply" } else { "new" },                "to": addresses(d.get("to")), "cc": addresses(d.get("cc")), "bcc": addresses(d.get("bcc")),                "attachments": shown_attachments(&attached(&d)),                "subject": s(&d, "subject").unwrap_or_default(), "body": d.get("body").and_then(Value::as_str).unwrap_or_default(),                "quoted": s(&d, "quoted"), "thread": s(&d, "thread_id"), "reply_to": s(&d, "reply_to"),            }), from, None, choices.clone())));        }        if mode == "new" || thread.is_none() {            let from = first.clone().unwrap_or_default();            let body = signed("", signature_of(&from).as_deref());            return Ok(Some((json!({ "mode": "new", "to": asked_to, "cc": [], "bcc": [], "attachments": [], "subject": "", "body": body }), from, None, choices.clone())));        }        let thread = thread.clone().unwrap_or_default();        let mail = rows(ctx, &format!("SELECT {MAIL_COLUMNS}, coalesce(account, gmail_account) AS acct FROM {EMAILS} WHERE thread_id = ? AND {live_mail} ORDER BY sent_at DESC, id DESC LIMIT 100", live_mail = mail_predicate::live("")), &[text(thread.clone())])?;        let answered = match &email {            Some(e) => mail.iter().find(|m| s(m, "id").as_deref() == Some(e.as_str())),            None => mail.iter().find(|m| lower(s(m, "from_email")).is_some_and(|f| !know.is_own(&f))).or(mail.first()),        };        let Some(m) = answered else { return Ok(None) };        let sender = lower(s(m, "from_email")).unwrap_or_default();        let everyone = recipients_of(m.get("recipients").unwrap_or(&Value::Null));        let (to, cc): (Vec<String>, Vec<String>) = match mode.as_str() {            "forward" => (asked_to.clone(), Vec::new()),            _ if know.is_own(&sender) => (everyone.iter().filter(|(a, _, k)| k == "to" && !know.is_own(a)).map(|(a, _, _)| a.clone()).collect(), if mode == "all" { everyone.iter().filter(|(a, _, k)| k == "cc" && !know.is_own(a)).map(|(a, _, _)| a.clone()).collect() } else { Vec::new() }),            "all" => (vec![sender.clone()], everyone.iter().filter(|(a, _, _)| !know.is_own(a) && *a != sender).map(|(a, _, _)| a.clone()).collect()),            _ => (vec![sender.clone()], Vec::new()),        };        let subject = s(m, "subject").unwrap_or_default();        let subject = if mode == "forward" { prefixed(&subject, "Fwd:") } else { prefixed(&subject, "Re:") };        // From the address the mail came to, when it is one of his; else his first.        let came_to = lower(s(m, "acct")).filter(|a| choices.iter().any(|c| c.0 == *a));        let why = came_to.as_ref().map(|_| p("write.from_reply", &[]));        let from = came_to.or(first.clone()).unwrap_or_default();        let body = signed("", signature_of(&from).as_deref());        Ok(Some((json!({            "mode": mode, "to": to, "cc": cc, "bcc": [], "subject": subject, "body": body,            "attachments": if mode == "forward" {                attachments_of(m).iter().enumerate().map(|(index, a)| json!({                    "index": index, "name": a.get("name").and_then(Value::as_str).unwrap_or("attachment"), "mime": a.get("mime"),                    "size": a.get("size").and_then(Value::as_i64).map(|b| cotton_core::records::page::bytes_words(b as f64)),                    "carry": { "email": s(m, "id"), "index": index },                })).collect::<Vec<_>>()            } else { Vec::new() },            "quoted": quote_of(&clock, m, mode == "forward"), "thread": (mode != "forward").then_some(thread), "reply_to": (mode != "forward").then(|| s(m, "id")).flatten(),        }), from, why, choices.clone())))    })?;    let Some((mut form, from, why, choices)) = form else {        return Err(MethodError::new("not_found", p("act.gone", &[])));    };    let title = match form["mode"].as_str().unwrap_or("new") {        "forward" => p("write.forward", &[]),        "reply" | "all" => p("write.reply", &[]),        _ => p("write.new", &[]),    };    form["title"] = json!(title);    form["from"] = json!({        "address": from,        "choices": choices.iter().map(|(a, tag, _)| json!({ "address": a, "label": tag.clone().map(|t| format!("{a} · {t}")).unwrap_or_else(|| a.clone()) })).collect::<Vec<_>>(),        "why": why,    });    form["signature"] = json!(choices.iter().find(|c| c.0 == from).and_then(|c| c.2.clone()));    form["undo_seconds"] = json!(undo);    if taken_back {        form["said"] = json!(p("send.undone", &[]));    }    form["words"] = json!({        "from": p("write.from", &[]), "to": p("write.to", &[]), "cc": p("write.cc", &[]), "bcc": p("write.bcc", &[]),        "subject": p("write.subject", &[]), "body": p("write.body", &[]), "send": p("write.send", &[]),        "save": p("write.save", &[]), "discard": p("write.discard", &[]), "cancel": p("write.cancel", &[]),        "attach": p("write.attach", &[]), "cc_bcc": p("write.cc_bcc", &[]),    });    Ok(form)}pub(super) fn save(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let to = addresses(request.get("to"));    let cc = addresses(request.get("cc"));    let bcc = addresses(request.get("bcc"));    if let Some(wrong) = to.iter().chain(cc.iter()).chain(bcc.iter()).find(|a| !is_address(a)) {        return Err(MethodError::new("bad_address", p("write.bad_address", &[("address", wrong)])));    }    let field = |key: &str| request.get(key).and_then(Value::as_str).map(str::to_string);    let draft = field("draft");    let now = Clock::of(client).now_iso();    // A mail on its way (UNDO SEND 3): a save that changes nothing Send was tapped on (an autosave landing after Send)    // leaves it going; a real change takes it back, "Not sent: it changed after Send". Once the object may have it,    // it is not saved under the send.    // A change to a mail the object may already have (UNDO SEND 5): saved in the same row, never sent; when the send    // lands, the row stays a draft holding his change and saying so. A row already gone refuses the save in words, so    // the shell keeps his text on screen.    let mut went = false;    let on_its_way = match draft.clone() {        Some(id) => match hold_of(client, &id)? {            Some(h) if h.stage == Stage::Held => Some(h),            Some(h) if h.stage == Stage::Going && never_posted(client, &id) => Some(h),            Some(h) if h.stage == Stage::Going => {                went = true;                Some(h)            }            Some(h) if h.stage == Stage::Sent => return Err(MethodError::new("gone", p("send.gone_unsaved", &[]))),            _ => None,        },        None => None,    };    let id = write(client, "mail.save", |ctx| {        let mut data = object(json!({ "to": json!(to).to_string(), "cc": json!(cc).to_string(), "bcc": json!(bcc).to_string(), "subject": field("subject").map(|s| s.trim().to_string()).unwrap_or_default(), "body": field("body").unwrap_or_default(), "status": "draft", "saved_at": now }));        if on_its_way.is_some() {            data.remove("status");        }        if let Some(from) = field("from") {            data.insert("account".into(), json!(from.trim().to_lowercase()));        }        // A forward's files, carried from the mail it forwards (fetched as it is sent).        if let Some(carry) = request.get("carry").and_then(Value::as_array).filter(|c| !c.is_empty()) {            let mut kept = match &draft { Some(id) => draft_of(ctx, id)?.map(|d| attached(&d)).unwrap_or_default(), None => Vec::new() };            for c in carry {                let (Some(email), Some(index)) = (c["email"].as_str(), c["index"].as_u64()) else { continue };                let Some(row) = one(ctx, &format!("SELECT attachments FROM {EMAILS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(email.to_string())])? else { continue };                let Some(a) = attachments_of(&row).get(index as usize).cloned() else { continue };                if kept.iter().any(|k| k.from.as_ref() == Some(&(email.to_string(), index as usize))) {                    continue;                }                kept.push(Attached {                    name: a.get("name").and_then(Value::as_str).unwrap_or("attachment").to_string(),                    mime: a.get("mime").and_then(Value::as_str).map(str::to_string),                    size: a.get("size").and_then(Value::as_u64).unwrap_or(0),                    file: String::new(),                    from: Some((email.to_string(), index as usize)),                });            }            data.insert("attachments".into(), json!(serde_json::to_string(&kept).unwrap_or_default()));        }        match &draft {            Some(id) => {                let had = draft_of(ctx, id)?.ok_or_else(|| if went { p("send.gone_unsaved", &[]) } else { p("act.gone", &[]) })?;                if on_its_way.is_none() && had.get("error").is_some_and(|e| !e.is_null()) {                    data.insert("error".into(), Value::Null);                }                tables::update_produced_record(ctx, &object(json!({ "table": DRAFTS, "id": id, "patch": Value::Object(data) }))).map_err(|f| f.to_string())?;                Ok(id.clone())            }            None => {                for key in ["thread", "reply_to", "quoted"] {                    if let Some(value) = field(key).filter(|v| !v.trim().is_empty()) {                        data.insert(if key == "thread" { "thread_id".into() } else { key.into() }, json!(value));                    }                }                let made = tables::create_produced_record(ctx, &object(json!({ "table": DRAFTS, "data": Value::Object(data) }))).map_err(|f| f.to_string())?;                made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| "no id for the new draft".to_string())            }        }    })?;    if let Some(hold) = on_its_way {        let now_is = read(client, "mail.save", |ctx| Ok(draft_of(ctx, &id)?.map(|d| content_of(&d))))?;        if hold.hash.is_some() && now_is != hold.hash {            let stage = hold_of(client, &id)?;            match stage {                Some(h) if !went && (h.stage == Stage::Held || (h.stage == Stage::Going && never_posted(client, &id))) => {                    let line = p("send.changed", &[]);                    not_sent(client, &id, line.clone())?;                    return Ok(json!({ "draft": id, "said": line }));                }                Some(h) if h.stage == Stage::Returned => {                    let line = h.said.unwrap_or_else(|| p("send.changed", &[]));                    return Ok(json!({ "draft": id, "said": line }));                }                // On its way, or gone as tapped: his change stays in this row, not sent.                _ => return Ok(json!({ "draft": id, "said": p("send.went_kept", &[]) })),            }        }    }    Ok(json!({ "draft": id, "said": p("write.saved", &[]) }))}pub(super) fn discard(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "draft")?.to_string();    // A draft on its way to the object right now is not discarded under it.    if change(client, |all| {        if in_flight(&id) {            return true;        }        all.remove(&id);        false    })? {        return Err(MethodError::new("too_late", p("send.too_late", &[])));    }    // not a copy: mail files.    let _ = std::fs::remove_dir_all(attachments_dir(client, &id));    write(client, "mail.discard", |ctx| {        if draft_of(ctx, &id)?.is_some() {            tables::delete_record(ctx, &object(json!({ "table": DRAFTS, "id": id }))).map_err(|f| f.to_string())?;        }        Ok(())    })?;    Ok(json!({ "said": p("write.discarded", &[]) }))}fn sending(draft: &str, state: &str, line: String) -> Value {    json!({ "draft": draft, "state": state, "line": line })}/// `mail.send { draft }`: checked, then held for the Undo time (none: sent now).pub(super) fn send(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "draft")?.to_string();    let Some(d) = read(client, "mail.send", |ctx| draft_of(ctx, &id))? else {        return already(client, &id);    };    let to = addresses(d.get("to"));    let cc = addresses(d.get("cc"));    if to.is_empty() {        return Err(MethodError::new("no_recipient", p("write.no_recipient", &[])));    }    if let Some(wrong) = to.iter().chain(cc.iter()).find(|a| !is_address(a)) {        return Err(MethodError::new("bad_address", p("write.bad_address", &[("address", wrong)])));    }    // No account to send from: refused before anything is held or sent, with the act that adds one (launch-ios    // walk, POST IPHONE 5: it said "Post couldn't tell whether this went"). The account is settled here, before the    // hold (UNDO SEND 3): the draft's own if it is one of his (else refused in words), his first if it names none.    let choices = read(client, "mail.send", |ctx| {        let know = super::cuts::know(ctx)?;        Ok(from_choices(ctx, &know).into_iter().map(|c| c.0).collect::<Vec<_>>())    })?;    let Some(first) = choices.first().cloned() else {        return Err(no_sender());    };    let from = match s(&d, "account").map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()) {        Some(named) if choices.contains(&named) => named,        Some(named) => return Err(MethodError::new("not_yours", p("write.not_yours", &[("address", &named)]))),        None => first,    };    let seconds = super::you::prefs(client).undo_seconds();    let now = now_ms(client);    let until = now + seconds as i64 * 1000;    let mut tapped = d.clone();    tapped.insert("account".into(), json!(from));    let hash = content_of(&tapped);    // Already on its way: a second tap sends nothing more. Anything else (failed, returned) is a fresh hold.    let db = open_db(client);    if !change_within(client, SEND_WAIT, |all| match all.get(&id).map(|h| h.stage) {        Some(Stage::Going) => false,        _ => {            all.insert(id.clone(), Hold::held(until, hash.clone(), from.clone(), db.clone()));            true        }    })? {        return state(client, &json!({ "draft": id }));    }    due_at(&id, seconds);    let mut mark = json!({ "account": from, "error": Value::Null });    if seconds > 0 {        mark["status"] = json!("queued");    }    let queued = mark_draft(client, &id, mark);    if seconds == 0 && queued.is_ok() {        return go(client, &id);    }    if let Err(refused) = queued {        // Not held after all: the hold goes with the refusal, so nothing goes that the screen did not show held.        change(client, |all| {            if all.get(&id).is_some_and(|h| h.stage == Stage::Held) {                all.remove(&id);            }        })?;        return Err(refused);    }    Ok(holding(&id, until, now))}/// A draft no longer in Drafts: sent, or gone.fn already(client: &ClientController, id: &str) -> Result<Value, MethodError> {    let sent = read(client, "mail.send", |ctx| Ok(every_draft(ctx)?.into_iter().find(|d| s(d, "id").as_deref() == Some(id) && s(d, "status").as_deref() == Some("sent"))))?;    match sent {        Some(d) => {            let when = s(&d, "sent_at").and_then(|at| Clock::of(client).recent(&at)).unwrap_or_default();            Ok(sending(id, "sent", p("send.sent", &[("time", &when)])))        }        None => Err(MethodError::new("not_found", p("act.gone", &[]))),    }}/// `mail.unsend { draft }`: one change, `held` to `cancelled`, which no draft write can refuse (a send waiting for a/// connection, never posted, can be taken back too). Once the object may have it, it says so: never Undone and then/// sent.pub(super) fn unsend(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "draft")?.to_string();    let took = change(client, |all| match all.get_mut(&id) {        Some(h) if matches!(h.stage, Stage::Held | Stage::Cancelled) || (h.stage == Stage::Going && never_posted(client, &id)) || (h.stage == Stage::Failed && !h.maybe) => {            h.stage = Stage::Cancelled;            Ok(())        }        // It may have gone: said as it is, never "already gone" nor "Undone".        Some(h) if h.stage == Stage::Failed => Err(Some(MethodError::new("unknown", p("send.unknown", &[])))),        // Already back in Drafts: said from what happened.        Some(h) if h.stage == Stage::Returned => Err(None),        _ => Err(Some(MethodError::new("too_late", p("send.too_late", &[])))),    })?;    match took {        Ok(()) => {            back_in_drafts(client, &id);            Ok(undone(&id))        }        Err(Some(refused)) => Err(refused),        Err(None) => Ok(match hold_of(client, &id)?.and_then(|h| h.said) {            Some(said) => sending(&id, "draft", said),            None => undone(&id),        }),    }}/// `mail.sending { draft }`: where a send stands, from its hold's real time; a held mail whose time is up goes now,/// and a taken one is resumed (Retry). A mail Undo took back, or one never sent, never goes from here.pub(super) fn state(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "draft")?.to_string();    let now = now_ms(client);    match hold_of(client, &id)? {        Some(Hold { stage: Stage::Held, until, .. }) if until > now => Ok(holding(&id, until, now)),        Some(Hold { stage: Stage::Held, until, .. }) if stale(&id, until, now) => not_sent(client, &id, p("send.closed", &[])),        Some(Hold { stage: Stage::Held | Stage::Going, .. }) => go(client, &id),        Some(Hold { stage: Stage::Returned, said, .. }) => Ok(sending(&id, "draft", said.unwrap_or_else(|| p("send.undone", &[])))),        Some(Hold { stage: Stage::Sent, .. }) => already(client, &id),        Some(Hold { stage: Stage::Cancelled, .. }) => {            back_in_drafts(client, &id);            Ok(undone(&id))        }        Some(Hold { stage: Stage::Failed, maybe, .. }) => {            let why = read(client, "mail.sending", |ctx| Ok(draft_of(ctx, &id)?.and_then(|d| s(&d, "error"))))?;            Ok(failed_answer(&id, maybe, why))        }        None => match already(client, &id) {            Ok(sent) => Ok(sent),            Err(gone) => match read(client, "mail.sending", |ctx| draft_of(ctx, &id))? {                // A draft an older build left failed: said, and Send again works (a fresh hold).                Some(d) if s(&d, "status").as_deref() == Some("failed") => Ok(failed_answer(&id, false, s(&d, "error"))),                Some(_) => Ok(sending(&id, "draft", String::new())),                None => Err(gone),            },        },    }}/// Send every held mail whose time is up and resume every one on its way (the sync pass calls this, so a held mail/// goes even when the screen that held it closed), and put back in Drafts any Undo whose draft write has not landed/// yet. Only the open account's holds, through its own door.pub(super) fn sweep(client: &ClientController) {    upgrade(client);    let now = now_ms(client);    let Ok(all) = holds_open(client) else { return };    for (id, hold) in all {        match hold.stage {            Stage::Held if hold.until <= now && stale(&id, hold.until, now) => {                let _ = not_sent(client, &id, p("send.closed", &[]));            }            // Due, and every send on its way (UNDO SEND 3: one killed while sending, or waiting for a connection,            // is resumed here through the object's ledger, never left to sit).            Stage::Held if hold.until <= now => {                let _ = go(client, &id);            }            Stage::Going if !in_flight(&id) => {                let _ = go(client, &id);            }            Stage::Cancelled => back_in_drafts(client, &id),            _ => {}        }    }}/// What the home and every list do (UNDO SEND 5): the local repairs only, never the network (a hold due while Post was/// closed goes back to Drafts; an Undo whose draft write has not landed is written again). Due sends go from the/// screen's own poll and from the sync pass ([`sweep`]).pub(super) fn tidy(client: &ClientController) {    upgrade(client);    let now = now_ms(client);    let Ok(all) = holds_open(client) else { return };    for (id, hold) in all {        match hold.stage {            Stage::Held if hold.until <= now && stale(&id, hold.until, now) => {                let _ = not_sent(client, &id, p("send.closed", &[]));            }            Stage::Cancelled => back_in_drafts(client, &id),            _ => {}        }    }}/// The send itself, once, through the object's ledger: only from a `held` record whose time is up, marked `going`/// under the same lock that re-reads it, or a `going` one resumed.fn go(client: &ClientController, id: &str) -> Result<Value, MethodError> {    let Some(_flight) = Flight::take(id) else {        return Ok(sending(id, "sending", p("send.sending", &[])));    };    let now = now_ms(client);    let taken: Result<Hold, Option<Hold>> = change(client, |all| match all.get_mut(id) {        Some(h) if h.stage == Stage::Held && h.until <= now && !stale(id, h.until, now) => {            h.stage = Stage::Going;            Ok(h.clone())        }        Some(h) if h.stage == Stage::Going => Ok(h.clone()),        other => Err(other.cloned()),    })?;    let hold = match taken {        Ok(hold) => hold,        Err(Some(Hold { stage: Stage::Held, until, .. })) if until > now => return Ok(holding(id, until, now)),        Err(Some(Hold { stage: Stage::Cancelled, .. })) => {            back_in_drafts(client, id);            return Ok(undone(id));        }        // Failed, stale, or never held: nothing goes from here; where it stands is said.        Err(_) => return state(client, &json!({ "draft": id })),    };    let Some(d) = read(client, "mail.sending", |ctx| draft_of(ctx, id))? else {        change(client, |all| {            all.remove(id);        })?;        return already(client, id);    };    // Posted before (a send killed while sending), or a hold from before its hash was kept: the object's ledger says    // where it stands before anything is posted again (UNDO SEND 3).    if hold.hash.is_none() || s(&d, "status").as_deref() == Some("sending") {        match ledger(client, id) {            // A hold from before its hash was kept, that the object never took: what is in the draft now may not be            // what Send was tapped on (UNDO SEND 4), so it is not sent by that hold.            Ledger::NotSeen if hold.hash.is_none() => return not_sent(client, id, p("send.updated", &[])),            Ledger::NotSeen => {}            Ledger::Answer(answer) => return landed(client, id, answer),            Ledger::Unreachable => return Ok(sending(id, "sending", p("send.sending", &[]))),        }    }    // Changed since Send (on this phone or another): not the mail the hold was made for.    if hold.hash.is_some() && hold.hash.as_deref() != Some(content_of(&d).as_str()) {        return not_sent(client, id, p("send.changed", &[]));    }    match ask_of(client, id, &d, hold.from.as_deref()) {        Ok(ask) => post(client, id, ask),        // Refused before anything went (no account, a file not here): back in Drafts with the reason.        Err(refused) => {            not_sent(client, id, refused.message.clone())?;            Err(refused)        }    }}enum Ledger {    /// The object never took this draft: it can be posted.    NotSeen,    /// The object's word on it (sending, sent, failed, unknown).    Answer(Value),    /// No connection, or no answer: asked again at the next look.    Unreachable,}/// The object's ledger on one draft (`GET /v1/mail/sends?draft=`).fn ledger(client: &ClientController, id: &str) -> Ledger {    let Some(door) = client.object_door() else { return Ledger::Unreachable };    match door.send("GET", &format!("/v1/mail/sends?draft={id}"), None) {        Ok(answer) => match answer["sends"].get(0) {            Some(word) if !word["state"].is_null() => Ledger::Answer(json!({ "state": word["state"], "said": word["words"].as_str().or(word["said"].as_str()), "email": word["email"] })),            _ => Ledger::NotSeen,        },        Err(_) => Ledger::Unreachable,    }}/// What goes to the ledger for a taken draft, or why it cannot go.fn ask_of(client: &ClientController, id: &str, d: &Map<String, Value>, settled: Option<&str>) -> Result<Value, MethodError> {    // The account settled at Send; one that is no longer his is refused in words, never swapped for his first.    let named = settled.map(str::to_string).or_else(|| s(d, "account")).unwrap_or_default();    let (from, kind) = read(client, "mail.sending", |ctx| {        let know = super::cuts::know(ctx)?;        let choices = from_choices(ctx, &know);        let from = if named.is_empty() { choices.first().map(|c| c.0.clone()) } else { choices.iter().find(|c| c.0 == named).map(|c| c.0.clone()) };        let kind = from.as_ref().and_then(|f| super::accounts(ctx).iter().find(|a| a.get("address").and_then(Value::as_str).map(str::to_lowercase).as_deref() == Some(f.as_str())).and_then(|a| a.get("kind").and_then(Value::as_str).map(str::to_string)));        Ok((from, kind))    })?;    let Some(from) = from else {        return Err(if named.is_empty() { no_sender() } else { MethodError::new("not_yours", p("write.not_yours", &[("address", &named)])) });    };    let route = if kind.as_deref() == Some("domain") { "domain" } else { "smtp" };    let (in_reply_to, mut references) = match s(d, "reply_to") {        Some(email) => read(client, "mail.sending", |ctx| Ok(answered_ids(ctx, &email)))?,        None => (None, Vec::new()),    };    if let Some(answered) = &in_reply_to {        references.retain(|r| r != answered);        references.push(answered.clone());    }    let body = d.get("body").and_then(Value::as_str).unwrap_or_default();    let text = match s(d, "quoted").filter(|q| !q.trim().is_empty()) {        Some(quoted) => format!("{body}\n\n{quoted}"),        None => body.to_string(),    };    // The files go with the mail, in the request: the server has to see them once to hand them on.    let mut files = Vec::new();    for a in attached(d) {        let path = match &a.from {            Some((email, index)) => {                let landed = super::super::file(client, &json!({ "email": email, "index": index, "dir": attachments_dir(client, id).to_string_lossy() }))                    .map_err(|_| MethodError::new("attachment_coming", p("write.attachment_coming", &[("name", &a.name)])))?;                std::path::PathBuf::from(landed["path"].as_str().unwrap_or_default())            }            None => attachments_dir(client, id).join(&a.file),        };        let bytes = std::fs::read(&path).map_err(|_| MethodError::new("attachment_gone", p("write.attachment_gone", &[("name", &a.name)])))?;        files.push(json!({ "name": a.name, "mime": a.mime, "content": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes) }));    }    Ok(json!({        "draft": id, "route": route, "from": from, "to": addresses(d.get("to")), "cc": addresses(d.get("cc")), "bcc": addresses(d.get("bcc")),        "attachments": files,        "subject": s(d, "subject").unwrap_or_default(), "text": text, "inReplyTo": in_reply_to, "references": references, "thread": s(d, "thread_id"),    }))}/// The taken draft to the object's ledger; the record stays `going` until it is sent (Retry resumes it).fn post(client: &ClientController, id: &str, ask: Value) -> Result<Value, MethodError> {    let mark = |patch: Value| mark_draft(client, id, patch);    let retry = |mut v: Value| {        v["retry"] = json!(p("send.retry", &[]));        v    };    let Some(door) = client.object_door() else {        mark(json!({ "status": "queued" }))?;        return Ok(retry(sending(id, "waiting", p("send.waiting_offline", &[]))));    };    mark(json!({ "status": "sending" }))?;    let answer = match door.send("POST", "/v1/mail/send", Some(&ask)) {        Ok(answer) => answer,        Err(_) => json!({ "state": "unknown" }),    };    landed(client, id, answer)}/// The object's word on a send, laid on the record and the draft: sent, still sending, failed, or could not tell.fn landed(client: &ClientController, id: &str, answer: Value) -> Result<Value, MethodError> {    let mark = |patch: Value| mark_draft(client, id, patch);    let retry = |mut v: Value| {        v["retry"] = json!(p("send.retry", &[]));        v    };    let failed = |maybe: bool| {        let ended = chrono::Utc::now().timestamp_millis();        change(client, |all| {            if let Some(h) = all.get_mut(id) {                h.stage = Stage::Failed;                h.maybe = maybe;                h.ended = Some(ended);            }        })    };    match answer["state"].as_str().unwrap_or("failed") {        "sent" => {            let now = Clock::of(client).now_iso();            // An edit saved into the row while it went (UNDO SEND 5): the row stays a draft holding it, saying so.            let tapped = hold_of(client, id)?.and_then(|h| h.hash);            let now_is = read(client, "mail.sending", |ctx| Ok(draft_of(ctx, id)?.map(|d| content_of(&d))))?;            let edited = tapped.is_some() && now_is.is_some() && now_is != tapped;            let mut patch = if edited { json!({ "status": "draft", "sent_at": now, "error": p("send.went_kept", &[]) }) } else { json!({ "status": "sent", "sent_at": now, "error": Value::Null }) };            if let Some(email) = answer["email"].as_str() {                patch["sent_email"] = json!(email);            }            mark(patch)?;            let ended = chrono::Utc::now().timestamp_millis();            change(client, |all| {                if let Some(h) = all.get_mut(id) {                    h.stage = Stage::Sent;                    h.ended = Some(ended);                }            })?;            let when = Clock::of(client).recent(&now).unwrap_or_default();            let mut out = sending(id, "sent", p("send.sent", &[("time", &when)]));            out["email"] = answer["email"].clone();            Ok(out)        }        "sending" => Ok(sending(id, "sending", p("send.sending", &[]))),        "unknown" => {            let line = p("send.unknown", &[]);            failed(true)?;            mark(json!({ "status": "failed", "error": line }))?;            Ok(retry(sending(id, "unknown", line)))        }        _ => {            let why = answer["said"].as_str().map(str::to_string).unwrap_or_else(|| p("send.unknown", &[]));            failed(false)?;            mark(json!({ "status": "failed", "error": why }))?;            Ok(retry(sending(id, "failed", p("send.failed", &[("why", &why)]))))        }    }}// ── attachments ────────────────────────────────────────────────────────/// A mail's files at most, all together (what Gmail and most mailboxes take).const MAX_BYTES: u64 = 25 * 1024 * 1024;#[derive(serde::Serialize, serde::Deserialize, Clone)]struct Attached {    name: String,    mime: Option<String>,    size: u64,    /// The file's name beside this phone's copy (`post-attachments/<draft>/`); empty for a file carried from a mail.    file: String,    /// A forwarded mail's file: the mail and its index, fetched as it is sent.    #[serde(default)]    from: Option<(String, usize)>,}fn attachments_dir(client: &ClientController, draft: &str) -> std::path::PathBuf {    client.layout().client_dir().join("post-attachments").join(draft)}fn attached(d: &Map<String, Value>) -> Vec<Attached> {    s(d, "attachments").and_then(|a| serde_json::from_str(&a).ok()).unwrap_or_default()}fn shown_attachments(all: &[Attached]) -> Vec<Value> {    all.iter().enumerate().map(|(index, a)| json!({ "index": index, "name": a.name, "mime": a.mime, "size": cotton_core::records::page::bytes_words(a.size as f64) })).collect()}fn keep_attached(client: &ClientController, draft: &str, all: &[Attached]) -> Result<(), MethodError> {    let list = serde_json::to_string(all).unwrap_or_default();    write(client, "mail.attach", |ctx| tables::update_produced_record(ctx, &object(json!({ "table": DRAFTS, "id": draft, "patch": { "attachments": list } }))).map(|_| ()).map_err(|f| f.to_string()))}/// `mail.attach { draft, path, name?, mime? }`: the file the phone picked, copied beside this copy and listed on the/// draft. Refused when the mail's files would pass what a mailbox takes.pub(super) fn attach(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let draft = cotton_chat::text(request, "draft")?.to_string();    let path = std::path::PathBuf::from(cotton_chat::text(request, "path")?);    let d = read(client, "mail.attach", |ctx| draft_of(ctx, &draft))?.ok_or_else(|| MethodError::new("not_found", p("act.gone", &[])))?;    let name = request.get("name").and_then(Value::as_str).map(str::to_string).or_else(|| path.file_name().map(|n| n.to_string_lossy().to_string())).unwrap_or_else(|| "file".into());    let size = std::fs::metadata(&path).map_err(|_| MethodError::new("not_found", p("write.attachment_gone", &[("name", &name)])))?.len();    let mut all = attached(&d);    let total: u64 = all.iter().map(|a| a.size).sum::<u64>() + size;    if total > MAX_BYTES {        let words = |b: u64| cotton_core::records::page::bytes_words(b as f64);        return Err(MethodError::new("too_large", p("write.too_large", &[("provider", &p("write.a_mailbox", &[])), ("max", &words(MAX_BYTES)), ("size", &words(total))])));    }    let dir = attachments_dir(client, &draft);    std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    let file = format!("{}-{}", cotton_chat::fresh_id(), name.replace(['/', '\\'], "_"));    // not a copy: mail files.    std::fs::copy(&path, dir.join(&file)).map_err(|e| MethodError::new("unwritable", e.to_string()))?;    all.push(Attached { name, mime: request.get("mime").and_then(Value::as_str).map(str::to_string), size, file, from: None });    keep_attached(client, &draft, &all)?;    Ok(json!({ "draft": draft, "attachments": shown_attachments(&all) }))}/// `mail.unattach { draft, index }`.pub(super) fn unattach(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let draft = cotton_chat::text(request, "draft")?.to_string();    let index = request.get("index").and_then(Value::as_u64).ok_or_else(|| bad("index", "the file's index"))? as usize;    let d = read(client, "mail.unattach", |ctx| draft_of(ctx, &draft))?.ok_or_else(|| MethodError::new("not_found", p("act.gone", &[])))?;    let mut all = attached(&d);    if index >= all.len() {        return Err(bad("index", "one of the draft's files"));    }    let gone = all.remove(index);    // not a copy: mail files.    let _ = std::fs::remove_file(attachments_dir(client, &draft).join(&gone.file));    keep_attached(client, &draft, &all)?;    Ok(json!({ "draft": draft, "attachments": shown_attachments(&all) }))}/// No account to send from, and the act that adds one.fn no_sender() -> MethodError {    MethodError::new("no_sender", p("send.no_sender", &[])).with_details(json!({ "act": { "label": p("account.add", &[]), "method": "mail.account.plan" } }))}