//! Writing mail in Comms (MAIL.md "Writing, and sending"): a new mail or a reply, kept as a draft in the //! person's own copy (`email_draft`). Cotton cannot send mail yet: nothing on a phone, the Mac or the Worker holds //! a way out, so every draft says "Not sent yet: sending from Comms is not set up", and the person may hand it to //! their own mail app (a `mailto:` with its words) to send it from there. //! //! ```text //! chat.mail.compose { thread?, email?, draft?, to? } → the form: to, cc, subject, body, quoted, from, words, note //! chat.mail.save { draft?, to, cc?, subject?, body?, thread?, replyTo?, quoted? } → { draft, said, mailto } //! refused no_recipient, bad_address //! chat.mail.discard { draft } → { said } //! ``` //! //! The Mail tab's Drafts (`chat.mail { filter: drafts }`) and a conversation's own drafts (`chat.mail.thread`'s //! `drafts`) read the same rows ([`drafts_of`]). use cotton_tools::mcp::handlers::tables; use super::*; use cotton_core::rules::mail_predicate; pub(super) const DRAFTS: &str = "email_draft"; fn object(value: Value) -> Map { value.as_object().cloned().unwrap_or_default() } fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> String { failure.to_string() } /// Every draft in the copy not yet sent, newest saved first. pub(super) fn drafts_of(ctx: &mut Ctx<'_>) -> Result>, String> { // A sent draft is mail now: its Sent copy stands in the conversation, and Drafts no longer holds it. Ok(every_draft(ctx)?.into_iter().filter(|d| s(d, "status").as_deref() != Some("sent")).collect()) } /// Every draft row in the copy, sent ones too. pub(super) fn every_draft(ctx: &mut Ctx<'_>) -> Result>, String> { let mut out = Vec::new(); let mut page = 0u64; loop { let ask = object(json!({ "table": DRAFTS, "where": {}, "limit": 500, "page": page })); let listed = tables::list_records(ctx, &ask).map_err(tool)?; let records = listed["records"].as_array().cloned().unwrap_or_default(); let got = records.len(); for record in records { if record.get("deleted_at").is_some_and(|d| !d.is_null()) { continue; } let mut data = object(record["data"].clone()); if let Some(id) = record["id"].as_str() { data.insert("id".into(), json!(id)); } out.push(data); } match listed["next_page"].as_u64() { Some(next) if got > 0 && next > page => page = next, _ => break, } } out.sort_by(|a, b| (s(b, "saved_at"), s(b, "id")).cmp(&(s(a, "saved_at"), s(a, "id")))); Ok(out) } pub(super) fn draft_of(ctx: &mut Ctx<'_>, id: &str) -> Result>, String> { Ok(drafts_of(ctx)?.into_iter().find(|d| s(d, "id").as_deref() == Some(id))) } /// A list of addresses as a draft keeps it (a JSON array as text) or as a shell sends it (an array, or one line /// split at commas, semicolons and spaces). pub(super) fn addresses(value: Option<&Value>) -> Vec { let parts: Vec = match value { Some(Value::Array(list)) => list.iter().filter_map(Value::as_str).map(str::to_string).collect(), Some(Value::String(text)) => match serde_json::from_str::>(text) { Ok(list) => list, Err(_) => text.split([',', ';', ' ', '\n']).map(str::to_string).collect(), }, _ => Vec::new(), }; let mut out: Vec = Vec::new(); for part in parts { let address = part.trim().trim_matches(['<', '>']).trim().to_string(); if !address.is_empty() && !out.iter().any(|a| a.eq_ignore_ascii_case(&address)) { out.push(address); } } out } /// One address a mail server would take: a local part, one `@`, a domain with a dot, no spaces. pub(super) fn is_address(address: &str) -> bool { let Some((local, domain)) = address.rsplit_once('@') else { return false }; !local.is_empty() && !local.contains('@') && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.') && !address.chars().any(char::is_whitespace) } fn encoded(value: &str) -> String { url::form_urlencoded::byte_serialize(value.as_bytes()).collect::().replace('+', "%20") } /// The draft as a `mailto:` the phone's own mail app opens, its words and the quoted text in the body. fn mailto(to: &[String], cc: &[String], subject: &str, body: &str, quoted: Option<&str>) -> String { let mut text = body.trim_end().to_string(); if let Some(quoted) = quoted.filter(|q| !q.trim().is_empty()) { text = if text.is_empty() { quoted.to_string() } else { format!("{text}\n\n{quoted}") }; } let mut asks = Vec::new(); if !cc.is_empty() { asks.push(format!("cc={}", encoded(&cc.join(",")))); } if !subject.is_empty() { asks.push(format!("subject={}", encoded(subject))); } if !text.is_empty() { asks.push(format!("body={}", encoded(&text))); } // The addresses as they are: checked to hold no space, and a mail app reads them plainly. let to: Vec = to.to_vec(); let mut out = format!("mailto:{}", to.join(",")); if !asks.is_empty() { out.push('?'); out.push_str(&asks.join("&")); } out } /// The words the form carries. fn words(lines: &LineSet) -> Value { let w = |line: &str| say(lines, &format!("app.mail.{line}"), &[]); json!({ "to": w("to_label"), "cc": w("cc_label"), "subject": w("subject_label"), "body": w("body_hint"), "quoted": w("quoted"), "save": w("save"), "mailApp": w("mail_app"), "discard": w("discard"), }) } /// The reply's quoted text: who wrote when, then their words, each line marked. fn quote(lines: &LineSet, clock: &Clock, m: &Map) -> Option { let text = s(m, "body").or_else(|| s(m, "snippet"))?; let address = s(m, "from_email").unwrap_or_default(); let name = shown_name(s(m, "from_name").as_deref(), &address); let at = s(m, "sent_at").unwrap_or_default(); let (time, heading, _) = clock.slip(&at); let head = say(lines, "app.mail.quote_head", &[("when", &format!("{heading}, {time}")), ("name", &name)]); let body: Vec = text.lines().map(|l| if l.is_empty() { ">".to_string() } else { format!("> {l}") }).collect(); Some(format!("{head}\n{}", body.join("\n"))) } pub(super) fn compose(client: &ClientController, request: &Value) -> Result { let lines = list::lines(); let clock = Clock::of(client); 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 form = read(client, "chat.mail.compose", |ctx| { let know = Know::read(ctx)?; let own_first = know.own_first(); if let Some(id) = &draft { let Some(d) = draft_of(ctx, id)? else { return Ok(None) }; return Ok(Some(json!({ "draft": id, "title": say(&lines, if s(&d, "thread_id").is_some() { "app.mail.reply_title" } else { "app.mail.new" }, &[]), "to": addresses(d.get("to")), "cc": addresses(d.get("cc")), "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"), "replyTo": s(&d, "reply_to"), "from": s(&d, "account").or(own_first), }))); } let Some(thread) = &thread else { return Ok(Some(json!({ "title": say(&lines, "app.mail.new", &[]), "to": asked_to, "cc": [], "subject": "", "body": "", "from": own_first }))); }; let mail = rows(ctx, &format!("SELECT {MAIL_COLUMNS}, account 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())])?; // The mail answered: the one asked for, else the newest the other side wrote, else the newest. 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 from = lower(s(m, "from_email")).unwrap_or_default(); let to: Vec = if know.is_own(&from) { recipients_of(m.get("recipients").unwrap_or(&Value::Null)).into_iter().filter(|(a, _, k)| k == "to" && !know.is_own(a)).map(|(a, _, _)| a).collect() } else { vec![from.clone()] }; let subject = subject_or(&lines, s(m, "subject")); let subject = if subject.to_lowercase().starts_with("re:") { subject } else { format!("Re: {subject}") }; Ok(Some(json!({ "title": say(&lines, "app.mail.reply_title", &[]), "to": to, "cc": [], "subject": subject, "body": "", "quoted": quote(&lines, &clock, m), "thread": thread, "replyTo": s(m, "id"), "from": lower(s(m, "account")).filter(|a| know.is_own(a)).or(own_first), }))) })?; let Some(mut form) = form else { return Err(MethodError::new("not_found", say(&lines, "app.mail.gone", &[]))); }; form["words"] = words(&lines); form["note"] = json!(say(&lines, "app.mail.not_sent", &[])); Ok(form) } pub(super) fn save(client: &ClientController, request: &Value) -> Result { let lines = list::lines(); let to = addresses(request.get("to")); let cc = addresses(request.get("cc")); if to.is_empty() { return Err(MethodError::new("no_recipient", say(&lines, "app.mail.no_recipient", &[]))); } if let Some(wrong) = to.iter().chain(cc.iter()).find(|a| !is_address(a)) { return Err(MethodError::new("bad_address", say(&lines, "app.mail.bad_address", &[("address", wrong)]))); } let field = |key: &str| request.get(key).and_then(Value::as_str).map(str::to_string); let subject = field("subject").map(|s| s.trim().to_string()).unwrap_or_default(); let body = field("body").unwrap_or_default(); let quoted = field("quoted").filter(|q| !q.trim().is_empty()); let draft = field("draft"); let now = Clock::of(client).now_iso(); let id = write(client, "chat.mail.save", |ctx| { let know = Know::read(ctx)?; let mut data = object(json!({ "to": json!(to).to_string(), "cc": json!(cc).to_string(), "subject": subject, "body": body, "status": "draft", "saved_at": now, })); match &draft { Some(id) => { draft_of(ctx, id)?.ok_or_else(|| say(&lines, "app.mail.draft_gone", &[]))?; tables::update_produced_record(ctx, &object(json!({ "table": DRAFTS, "id": id, "patch": Value::Object(data) }))).map_err(tool)?; Ok(id.clone()) } None => { for (key, value) in [("thread_id", field("thread")), ("reply_to", field("replyTo")), ("quoted", quoted.clone()), ("account", know.own_first())] { if let Some(value) = value { data.insert(key.into(), json!(value)); } } let made = tables::create_produced_record(ctx, &object(json!({ "table": DRAFTS, "data": Value::Object(data) }))).map_err(tool)?; 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()) } } })?; let quoted = match (&draft, quoted) { (Some(id), _) => read(client, "chat.mail.save", |ctx| Ok(draft_of(ctx, id)?.and_then(|d| s(&d, "quoted"))))?, (None, q) => q, }; Ok(json!({ "draft": id, "said": say(&lines, "app.mail.saved", &[]), "mailto": mailto(&to, &cc, &subject, &body, quoted.as_deref()), })) } pub(super) fn discard(client: &ClientController, request: &Value) -> Result { let lines = list::lines(); let id = cotton_chat::text(request, "draft")?.to_string(); write(client, "chat.mail.discard", |ctx| { if draft_of(ctx, &id)?.is_some() { tables::delete_record(ctx, &object(json!({ "table": DRAFTS, "id": id }))).map_err(tool)?; } Ok(()) })?; Ok(json!({ "said": say(&lines, "app.mail.discarded", &[]) })) } /// A draft as the Mail tab's Drafts and a conversation's foot draw it, named by whom it goes to: their name in People /// when they are there (seen on emulator-5554, 22 Nov 2026: a draft to Ada Invented's address read "ada"). pub(super) fn draft_row(lines: &LineSet, clock: &Clock, know: &super::Know, d: &Map) -> Value { let to = addresses(d.get("to")); let name = to.first().map(|a| shown_name(know.name_of(a), a)).unwrap_or_default(); let names = if to.len() > 1 { format!("{name} +{}", to.len() - 1) } else { name.clone() }; let body = d.get("body").and_then(Value::as_str).unwrap_or_default(); let flat: String = body.split_whitespace().collect::>().join(" "); let line: String = flat.chars().take(140).collect(); json!({ "draft": s(d, "id"), "thread": s(d, "thread_id").unwrap_or_default(), "from": { "name": names, "address": to.first().cloned().unwrap_or_default(), "picture": picture(to.first().map_or("", String::as_str), &name, None) }, "who": "person", "subject": subject_or(lines, s(d, "subject")), "line": (!line.is_empty()).then_some(line), "when": s(d, "saved_at").and_then(|at| clock.recent(&at)), "unread": false, "count": 1, "mark": say(lines, "app.mail.draft_mark", &[]), "note": say(lines, "app.mail.not_sent", &[]), }) } /// The person's own addresses Cotton sends from, as the object holds them (OWN-MAIL.md): each at a domain they /// proved, the default first. Empty where sending is not set up. pub(super) fn sending_addresses(settings: &Value) -> Vec { if settings.get("sending").and_then(Value::as_bool) != Some(true) { return Vec::new(); } let proved: Vec = settings["domains"].as_array().into_iter().flatten().filter(|d| d["proved"].as_bool() == Some(true)).filter_map(|d| d["domain"].as_str().map(str::to_string)).collect(); let mut out: Vec<(bool, String)> = settings["addresses"] .as_array() .into_iter() .flatten() .filter_map(|a| Some((a["isDefault"].as_bool() == Some(true), a["address"].as_str()?.to_lowercase()))) .filter(|(_, a)| a.rsplit_once('@').is_some_and(|(_, d)| proved.iter().any(|p| p == d))) .collect(); out.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); out.into_iter().map(|(_, a)| a).collect() } /// The mail a reply answers: its Message-ID and References, for In-Reply-To and References. A copy made before the /// columns were served has neither, and the reply goes unthreaded rather than not at all. pub(super) fn answered_ids(ctx: &mut Ctx<'_>, email: &str) -> (Option, Vec) { let Ok(Some(row)) = one(ctx, "SELECT message_id, message_refs FROM cotton_emails WHERE id = ?", &[text(email.to_string())]) else { return (None, Vec::new()); }; let refs = s(&row, "message_refs").map(|r| r.split_whitespace().map(str::to_string).collect()).unwrap_or_default(); (s(&row, "message_id"), refs) } /// Whether the draft `id` stands sent (and so out of [`drafts_of`]). fn was_sent(ctx: &mut Ctx<'_>, id: &str) -> Result { Ok(every_draft(ctx)?.iter().any(|d| s(d, "id").as_deref() == Some(id) && s(d, "status").as_deref() == Some("sent"))) } /// chat.mail.send { draft } → { draft, state, said, email? } (OWN-MAIL.md "Sending"): the person's own tap on Send. /// The draft goes to the object once; the object's ledger makes a second tap, or a retry after a lost answer, send /// nothing more. Sent: the draft says so, and the Sent copy the object kept arrives by sync. Not sent: the draft says /// why, and Retry is this same call. Refused before anything goes: offline, no_sender, no_recipient, bad_address, /// not_found. pub(super) fn send(client: &ClientController, request: &Value) -> Result { let lines = list::lines(); let id = cotton_chat::text(request, "draft")?.to_string(); let Some(d) = read(client, "chat.mail.send", |ctx| draft_of(ctx, &id))? else { if read(client, "chat.mail.send", |ctx| was_sent(ctx, &id))? { return Ok(json!({ "draft": id, "state": "sent", "said": say(&lines, "app.mail.sent", &[]) })); } return Err(MethodError::new("not_found", say(&lines, "app.mail.draft_gone", &[]))); }; let to = addresses(d.get("to")); let cc = addresses(d.get("cc")); if to.is_empty() { return Err(MethodError::new("no_recipient", say(&lines, "app.mail.no_recipient", &[]))); } if let Some(wrong) = to.iter().chain(cc.iter()).find(|a| !is_address(a)) { return Err(MethodError::new("bad_address", say(&lines, "app.mail.bad_address", &[("address", wrong)]))); } let offline = || MethodError::new("offline", say(&lines, "app.mail.send_offline", &[])); let door = client.object_door().ok_or_else(offline)?; let settings = door.send("GET", "/v1/mail/settings", None).map_err(|_| offline())?; let own = sending_addresses(&settings); let Some(default) = own.first().cloned() else { return Err(MethodError::new("no_sender", say(&lines, "app.mail.no_sender", &[]))); }; let from = s(&d, "account").map(|a| a.to_lowercase()).filter(|a| own.contains(a)).unwrap_or(default); let (in_reply_to, mut references) = match s(&d, "reply_to") { Some(email) => read(client, "chat.mail.send", |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(), }; let ask = json!({ "draft": id, "from": from, "to": to, "cc": cc, "subject": s(&d, "subject").unwrap_or_default(), "text": text, "inReplyTo": in_reply_to, "references": references, "thread": s(&d, "thread_id"), }); let mark = |patch: Value| write(client, "chat.mail.send", |ctx| tables::update_produced_record(ctx, &object(json!({ "table": DRAFTS, "id": id, "patch": patch }))).map(|_| ()).map_err(tool)); mark(json!({ "status": "sending", "account": from }))?; let answer = match door.send("POST", "/v1/mail/send", Some(&ask)) { Ok(answer) => answer, Err(_) => { // The answer was lost, not necessarily the mail: the object's ledger knows, and Retry asks it. let said = say(&lines, "app.mail.send_unknown", &[]); mark(json!({ "status": "failed", "error": said }))?; return Ok(json!({ "draft": id, "state": "unknown", "said": said })); } }; let state = answer["state"].as_str().unwrap_or("failed").to_string(); let now = Clock::of(client).now_iso(); match state.as_str() { "sent" => { let mut patch = json!({ "status": "sent", "sent_at": now, "error": Value::Null }); if let Some(email) = answer["email"].as_str() { patch["sent_email"] = json!(email); } mark(patch)?; Ok(json!({ "draft": id, "state": "sent", "said": say(&lines, "app.mail.sent", &[]), "email": answer["email"].clone() })) } "sending" => Ok(json!({ "draft": id, "state": "sending", "said": say(&lines, "app.mail.sending", &[]) })), other => { let why = answer["said"].as_str().map(str::to_string).unwrap_or_else(|| say(&lines, "app.mail.send_unknown", &[])); mark(json!({ "status": "failed", "error": why }))?; let said = if other == "unknown" { why.clone() } else { say(&lines, "app.mail.send_failed", &[("why", &why)]) }; Ok(json!({ "draft": id, "state": if other == "unknown" { "unknown" } else { "failed" }, "said": said })) } } }