Cotton code
200 lines · 11.4 KB · RustRaw
//! Domains under You (CONTRACT row 15; DECISIONS question 12): addresses on his own domain, over the object's//! own-domain routes (`/v1/mail/settings`, `/v1/mail/domains`, `/v1/mail/domains/check`, `/v1/mail/domains/catch-all`,//! `/v1/mail/addresses`). Invented domains only in tests and on dev.//!//! ```text//! mail.domains                          → { title, rows: [{ domain, line, state }], add, server_reads }//! mail.domain { domain }                → { domain, records: [Record], addresses: [{ address, line, lands? }], plus,//!                                           catch_all: { label, on, line }, new_address, people_later }//! mail.domain.add { domain }            → mail.domain//! mail.domain.check { domain }          → mail.domain, its records as the DNS says them now//! mail.domain.catch_all { domain, on }  → mail.domain//! mail.address.add { address, lands? }  → mail.domain//! mail.address.remove { address, sure? } → { ask } until `sure`, then mail.domain//! ```//!//! A Record is `{ id, name, line, state: done|checking|next|wrong, fix? }`. Every refusal is the object's own words//! (unknown_domain, bad_domain, alias_loop, forward_loop…); offline is said in Post's.use super::super::*;use super::p;use cotton_core::rules::mail_predicate;fn door(client: &ClientController) -> Result<std::sync::Arc<crate::phone::personal_object::ObjectDoor>, MethodError> {    client.object_door().ok_or_else(|| MethodError::new("offline", p("domain.offline", &[])))}fn ask_object(client: &ClientController, method: &str, path: &str, body: Option<&Value>) -> Result<Value, MethodError> {    // The object's own refusal (its code and words) comes back as it is.    door(client)?.send(method, path, body)}fn domain_of(address: &str) -> String {    address.rsplit_once('@').map(|(_, d)| d.to_lowercase()).unwrap_or_default()}fn settings(client: &ClientController) -> Result<Value, MethodError> {    ask_object(client, "GET", "/v1/mail/settings", None)}fn counted_addresses(n: usize) -> String {    super::counted("domain.addresses", n as usize)}pub(super) fn list(client: &ClientController) -> Result<Value, MethodError> {    let held = settings(client)?;    let addresses = held["addresses"].as_array().cloned().unwrap_or_default();    let rows: Vec<Value> = held["domains"]        .as_array()        .into_iter()        .flatten()        .map(|d| {            let domain = d["domain"].as_str().unwrap_or_default();            let n = addresses.iter().filter(|a| domain_of(a["address"].as_str().unwrap_or_default()) == domain).count();            let proved = d["proved"].as_bool() == Some(true);            let line = if proved { format!("{} · {}", counted_addresses(n), p("domain.working", &[])) } else { p("domain.state.next", &[]) };            json!({ "domain": domain, "line": line, "state": if proved { "done" } else { "next" } })        })        .collect();    Ok(json!({        "title": p("domain.title", &[]),        "rows": rows,        "add": p("domain.add", &[]),        "server_reads": { "label": p("domain.server_reads", &[]), "line": p("way.arrives.line", &[]) },        // In the first sync, not "none": his domains are among the mail still coming (`phone::first_sync`).        "empty": rows.is_empty().then(|| crate::phone::first_sync::of(client, crate::phone::first_sync::spec("mail.you").and_then(|spec| spec.tables)).and_then(|standing| standing.words()).unwrap_or_else(|| p("domain.none", &[]))),    }))}/// The page of one domain; `check` is the DNS's answer just now, when there is one.fn page_of(client: &ClientController, domain: &str, check: Option<&Value>) -> Result<Value, MethodError> {    let held = settings(client)?;    shape(domain, &held, check)}/// A domain's page from the object's settings (`{ domains, addresses }`) and a DNS check's answer.pub(super) fn shape(domain: &str, held: &Value, check: Option<&Value>) -> Result<Value, MethodError> {    let Some(d) = held["domains"].as_array().into_iter().flatten().find(|d| d["domain"].as_str() == Some(domain)).cloned() else {        return Err(MethodError::new("not_found", p("domain.unknown", &[("domain", domain)])));    };    let proved = d["proved"].as_bool() == Some(true);    let mut records = vec![json!({        "id": "proof",        "name": p("domain.records.proof", &[]),        "line": format!("{} {}", d["proof"]["name"].as_str().unwrap_or_default(), d["proof"]["value"].as_str().unwrap_or_default()),        "state": if proved { "done" } else { "next" },        "fix": (!proved).then(|| json!({ "type": "TXT", "name": d["proof"]["name"], "value": d["proof"]["value"] })),    })];    for c in check.and_then(|c| c["lines"].as_array()).into_iter().flatten() {        let id = c["id"].as_str().unwrap_or_default();        if id == "proof" {            continue;        }        let name = match id {            "mx" => p("domain.records.mail_in", &[]),            "spf" => p("domain.records.spf", &[]),            "dkim_routing" | "dkim_sending" => p("domain.records.dkim", &[]),            "dmarc" => p("domain.records.dmarc", &[]),            other => other.to_string(),        };        let ok = c["ok"].as_bool() == Some(true);        records.push(json!({ "id": id, "name": name, "line": c["said"], "state": if ok { "done" } else { "wrong" } }));    }    let addresses: Vec<Value> = held["addresses"]        .as_array()        .into_iter()        .flatten()        .filter(|a| domain_of(a["address"].as_str().unwrap_or_default()) == domain)        .map(|a| {            let lands = a["lands"].as_str();            json!({ "address": a["address"], "line": lands.map(|l| p("domain.alias", &[("address", l)])), "lands": lands, "default": a["isDefault"] })        })        .collect();    let first = addresses.iter().find(|a| a["lands"].is_null()).and_then(|a| a["address"].as_str()).unwrap_or_default().to_string();    let catch_all = d["catchAll"].as_bool() == Some(true);    let to_check = records.iter().filter(|r| r["state"] != "done").count();    Ok(json!({        "domain": domain,        "line": if to_check == 0 { p("domain.working", &[]) } else { p(if to_check == 1 { "domain.to_check.one" } else { "domain.to_check.other" }, &[("n", &to_check.to_string())]) },        "records": records,        "keep_checking": (to_check > 0).then(|| p("domain.keep_checking", &[])),        "addresses": { "title": counted_addresses(addresses.len()), "rows": addresses },        "new_address": p("domain.new_address", &[]),        "plus": (!first.is_empty()).then(|| {            let (local, at) = first.split_once('@').unwrap_or((&first, ""));            json!({ "label": p("domain.plus", &[]), "line": p("domain.plus_line", &[("example", &format!("{local}+shops@{at}")), ("address", &first)]) })        }),        "catch_all": { "label": p("domain.catch_all", &[("domain", domain)]), "on": catch_all, "line": if catch_all { p("domain.catch_all_on", &[("address", &first)]) } else { p("domain.catch_all_off", &[]) } },        "people_later": { "label": p("domain.people_later", &[]), "line": p("domain.people_later_line", &[]) },        "server_reads": { "label": p("domain.server_reads", &[]), "line": p("way.arrives.line", &[]) },        "remove": { "label": p("domain.remove", &[]), "call": { "method": "mail.domain.remove", "domain": domain } },    }))}pub(super) fn page(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let domain = cotton_chat::text(request, "domain")?.trim().to_lowercase();    page_of(client, &domain, None)}pub(super) fn add(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let domain = cotton_chat::text(request, "domain")?.trim().to_lowercase();    ask_object(client, "POST", "/v1/mail/domains", Some(&json!({ "domain": domain })))?;    page_of(client, &domain, None)}pub(super) fn check(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let domain = cotton_chat::text(request, "domain")?.trim().to_lowercase();    let checked = ask_object(client, "POST", "/v1/mail/domains/check", Some(&json!({ "domain": domain })))?;    page_of(client, &domain, Some(&checked))}pub(super) fn catch_all(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let domain = cotton_chat::text(request, "domain")?.trim().to_lowercase();    let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| bad("on", "true or false"))?;    ask_object(client, "POST", "/v1/mail/domains/catch-all", Some(&json!({ "domain": domain, "on": on })))?;    page_of(client, &domain, None)}pub(super) fn add_address(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let address = cotton_chat::text(request, "address")?.trim().to_lowercase();    let lands = request.get("lands").and_then(Value::as_str).map(|l| l.trim().to_lowercase()).filter(|l| !l.is_empty());    ask_object(client, "POST", "/v1/mail/addresses", Some(&json!({ "address": address, "lands": lands })))?;    page_of(client, &domain_of(&address), None)}pub(super) fn remove_address(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let address = cotton_chat::text(request, "address")?.trim().to_lowercase();    if request.get("sure").and_then(Value::as_bool) != Some(true) {        let n = read(client, "mail.address.remove", |ctx| {            Ok(rows(ctx, &format!("SELECT id, recipients FROM {EMAILS} WHERE workspace_id = ? AND {live_mail} AND recipients LIKE ?", live_mail = mail_predicate::live("")), &[ws(ctx), text(format!("%{address}%"))])?.len())        })?;        return Ok(json!({ "ask": { "title": p("domain.remove_address", &[("address", &address)]), "line": super::counted("domain.remove_line", n as usize), "go": p("domain.remove_go", &[]), "cancel": p("ask.cancel", &[]) } }));    }    ask_object(client, "DELETE", "/v1/mail/addresses", Some(&json!({ "address": address })))?;    page_of(client, &domain_of(&address), None)}/// `mail.domain.remove { domain, sure? }` (CONTRACT row 15): asks once, saying what goes (its addresses: mail sent to/// them bounces from then on) and that mail already here stays; with `sure`, the object lets the domain go and the/// list of domains answers.pub(super) fn remove(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let domain = cotton_chat::text(request, "domain")?.trim().to_lowercase().trim_start_matches('@').to_string();    let held = settings(client)?;    let asked = removal(&domain, &held)?;    if request.get("sure").and_then(Value::as_bool) != Some(true) {        return Ok(asked);    }    ask_object(client, "DELETE", &format!("/v1/mail/domains?domain={domain}"), None)?;    let mut answer = list(client)?;    answer["line"] = json!(p("domain.removed", &[("domain", &domain)]));    Ok(answer)}/// The question Remove asks of `domain`, from the object's settings: what goes, and that mail here stays.pub(super) fn removal(domain: &str, held: &Value) -> Result<Value, MethodError> {    if !held["domains"].as_array().into_iter().flatten().any(|d| d["domain"].as_str() == Some(domain)) {        return Err(MethodError::new("not_found", p("act.gone", &[])));    }    let n = held["addresses"].as_array().into_iter().flatten().filter(|a| domain_of(a["address"].as_str().unwrap_or_default()) == domain).count();    Ok(json!({ "ask": { "title": p("domain.remove_title", &[("domain", domain)]), "line": super::counted("domain.remove_domain_line", n), "go": p("domain.remove", &[]), "cancel": p("ask.cancel", &[]), "danger": true } }))}