Cotton code
264 lines · 13.7 KB · RustRaw
//! This phone fetches (CONTRACT row 12): one round of reading an account's new mail over IMAP, on the phone.//!//! ```text//! mail.fetch { account, password, server?: { host, port, tls } } → { account, fetched, state, line, notify }//! ```//!//! The password comes from the phone's own key store for each round and is never kept by the core. The shell runs a//! round when Post opens, on iOS when the system grants background time, and on Android under its quiet notification.//! `server` is for a test's scripted server on this machine alone.//!//! A round reads Gmail's All Mail (any other server's INBOX) read-only: the first round takes the newest//! [`FIRST_ROUND`] messages, every later one what came after the highest UID read and then up to [`FIRST_ROUND`]//! older ones, until the whole mailbox is here (a new UIDVALIDITY starts again).//! Each message becomes the very rows the Mac and the Worker write for it (`cotton_rules::mail::arrive`, the same ids),//! so mail read by two roads lands on one row; a row already here is left as it is.//!//! `notify` is the new mail of this round a notification is for (Post's Notifications, `mail.set`): mail that came in//! after the round before (never an account's first round, nor the older mail a round fills in), to him, unread and//! in the Inbox; from people only by default (the rule's Person), from anyone with `everyone`, none with `none`. Each//! is `{ id, thread, title, body }`: who it is from and its subject, in the post words.use cotton_core::cotton_rules::mail::arrive::{arrive, Arriving, Fetched as Read};use super::super::*;use super::p;use crate::phone::mail_imap::{connect, ImapClient, ImapError, Server};/// Messages the first round of an account reads, newest first.// One under test, so a test can see the backfill bring the rest.const FIRST_ROUND: usize = if cfg!(test) { 1 } else { 200 };/// Messages fetched in one command.const PAGE: usize = 25;#[derive(serde::Serialize, serde::Deserialize, Default)]struct Cursor {    uid_validity: u32,    top_uid: u32,    /// The lowest UID read: everything below it is the backfill still to read (1 when the mailbox is whole).    #[serde(default)]    low_uid: u32,}fn cursor_path(client: &ClientController, account: &str) -> std::path::PathBuf {    client.layout().client_dir().join(format!("post-fetch-{account}.json"))}fn cursor(client: &ClientController, account: &str) -> Cursor {    std::fs::read(cursor_path(client, account)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()}fn keep_cursor(client: &ClientController, account: &str, at: &Cursor) {    if let Ok(bytes) = serde_json::to_vec(at) {        // not a copy: Post's fetch cursor.        let _ = std::fs::write(cursor_path(client, account), bytes);    }}fn imap_host(kind: &str, host: Option<&str>) -> Option<String> {    match kind {        "gmail" => Some("imap.gmail.com".into()),        "icloud" => Some("imap.mail.me.com".into()),        "fastmail" => Some("imap.fastmail.com".into()),        "yahoo" => Some("imap.mail.yahoo.com".into()),        _ => host.map(str::to_string),    }}pub(super) fn fetch(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = cotton_chat::text(request, "account")?.to_string();    let password = cotton_chat::text(request, "password")?.to_string();    let account = read(client, "mail.fetch", |ctx| Ok(super::accounts(ctx).into_iter().find(|a| a.get("id").and_then(Value::as_str) == Some(id.as_str()))))?        .ok_or_else(|| MethodError::new("not_found", p("act.gone", &[])))?;    let get = |k: &str| account.get(k).and_then(Value::as_str).map(str::to_string);    let address = get("address").unwrap_or_default().to_lowercase();    let kind = get("kind").unwrap_or_default();    let gmail = kind == "gmail";    let server = match request.get("server") {        Some(s) => Server { host: s["host"].as_str().unwrap_or_default().to_string(), port: s["port"].as_u64().unwrap_or(993) as u16, tls: s["tls"].as_bool().unwrap_or(true) },        None => Server { host: imap_host(&kind, get("host").as_deref()).ok_or_else(|| bad("host", "the account's mail server"))?, port: 993, tls: true },    };    let provider = match kind.as_str() {        "gmail" => "Gmail",        "icloud" => "iCloud Mail",        "fastmail" => "Fastmail",        "yahoo" => "Yahoo Mail",        _ => "your mail server",    };    let answer = |state: &str, line: String, fetched: usize| json!({ "account": id, "fetched": fetched, "state": state, "line": line, "notify": [] });    let mut imap = match connect(&server).and_then(ImapClient::start) {        Ok(c) => c,        Err(error) => return Ok(answer("stopped", p("status.stopped", &[("why", &error.to_string())]), 0)),    };    match imap.login(&address, &password) {        Ok(()) => {}        Err(ImapError::SignIn(_)) => return Ok(answer("refused", p("status.refused", &[("provider", provider)]), 0)),        Err(error) => return Ok(answer("stopped", p("status.stopped", &[("why", &error.to_string())]), 0)),    }    let mailbox = if gmail { imap.special_use().ok().and_then(|s| s.all).unwrap_or_else(|| "[Gmail]/All Mail".into()) } else { "INBOX".into() };    let state = match imap.examine(&mailbox) {        Ok(s) => s,        Err(error) => return Ok(answer("stopped", p("status.stopped", &[("why", &error.to_string())]), 0)),    };    let mut at = cursor(client, &id);    if at.uid_validity != state.uid_validity {        at = Cursor { uid_validity: state.uid_validity, top_uid: 0, low_uid: 0 };    }    let first = at.top_uid == 0;    let wanted: Vec<u32> = if first {        let mut all = imap.uid_search("ALL").unwrap_or_default();        all.sort_unstable();        let from = all.len().saturating_sub(FIRST_ROUND);        all.split_off(from)    } else {        let mut newer: Vec<u32> = imap.uid_search(&format!("UID {}:*", at.top_uid + 1)).unwrap_or_default().into_iter().filter(|u| *u > at.top_uid).collect();        newer.sort_unstable();        newer    };    let items = if gmail { "UID FLAGS INTERNALDATE X-GM-MSGID X-GM-THRID X-GM-LABELS BODY.PEEK[]" } else { "UID FLAGS INTERNALDATE BODY.PEEK[]" };    let mut landed = 0usize;    // New mail this round, for `notify`: none on an account's first round, which brings the mailbox as it stands.    let mut fresh: Vec<Value> = Vec::new();    for page in wanted.chunks(PAGE) {        let set: Vec<String> = page.iter().map(u32::to_string).collect();        let fetched = match imap.uid_fetch(&set.join(","), items, None) {            Ok(f) => f,            Err(error) => {                keep_cursor(client, &id, &at);                return Ok(answer("stopped", p("status.stopped", &[("why", &error.to_string())]), landed));            }        };        let mut rows = Vec::new();        for f in fetched {            let Some(raw) = f.body.as_deref() else { continue };            let read = Read { msgid: f.gm_msgid, thrid: f.gm_thrid, gm_labels: f.gm_labels.clone(), flags: f.flags.clone(), in_inbox: !gmail };            rows.push((f.uid, raw.to_vec(), f.internal_date, read));        }        let top = page.iter().copied().max().unwrap_or(at.top_uid);        let (n, came) = write(client, "mail.fetch", |ctx| {            let database = ctx.file.namespace().as_str().to_string();            let mut n = 0;            let mut came = Vec::new();            for (_, raw, received, read) in &rows {                let Ok(arrived) = arrive(raw, &Arriving { database: &database, account: &address, received: *received, fetched: Some(read.clone()) }) else { continue };                if land(ctx, &arrived)? {                    n += 1;                    if !first {                        came.push(arrived);                    }                }            }            Ok((n, came))        })?;        landed += n;        fresh.extend(came);        at.top_uid = at.top_uid.max(top);        let low = page.iter().copied().min().unwrap_or(0);        if at.low_uid == 0 || (low > 0 && low < at.low_uid && first) {            at.low_uid = low;        }        keep_cursor(client, &id, &at);    }    // All his mail on the phone (owner, 25 Nov 2026): each later round also reads up to FIRST_ROUND older messages,    // newest first, below the lowest read, until the mailbox is whole.    if !first && at.low_uid > 1 {        let mut older: Vec<u32> = imap.uid_search(&format!("UID 1:{}", at.low_uid - 1)).unwrap_or_default().into_iter().filter(|u| *u < at.low_uid).collect();        older.sort_unstable();        let from = older.len().saturating_sub(FIRST_ROUND);        let older = older.split_off(from);        if older.is_empty() {            at.low_uid = 1;        }        for page in older.rchunks(PAGE) {            let set: Vec<String> = page.iter().map(u32::to_string).collect();            let Ok(fetched) = imap.uid_fetch(&set.join(","), items, None) else { break };            let rows: Vec<(Vec<u8>, Option<i64>, Read)> = fetched                .into_iter()                .filter_map(|f| Some((f.body.clone()?, f.internal_date, Read { msgid: f.gm_msgid, thrid: f.gm_thrid, gm_labels: f.gm_labels.clone(), flags: f.flags.clone(), in_inbox: !gmail })))                .collect();            landed += write(client, "mail.fetch.older", |ctx| {                let database = ctx.file.namespace().as_str().to_string();                let mut n = 0;                for (raw, received, read) in &rows {                    let Ok(arrived) = arrive(raw, &Arriving { database: &database, account: &address, received: *received, fetched: Some(read.clone()) }) else { continue };                    if land(ctx, &arrived)? {                        n += 1;                    }                }                Ok(n)            })?;            at.low_uid = page.iter().copied().min().unwrap_or(at.low_uid).max(1);            keep_cursor(client, &id, &at);        }    }    imap.logout();    let mut said = answer("live", super::counted("status.phone_fetched", landed), landed);    said["notify"] = json!(notify_of(client, &fresh)?);    Ok(said)}/// Which of `fresh` (mail this round brought in) a notification is for, by Post's Notifications setting.pub(super) fn notify_of(client: &ClientController, fresh: &[Value]) -> Result<Vec<Value>, MethodError> {    let setting = super::you::prefs(client).notify().to_string();    if setting == "none" || fresh.is_empty() {        return Ok(Vec::new());    }    let know = read(client, "mail.fetch.notify", |ctx| super::cuts::know(ctx))?;    Ok(fresh        .iter()        .filter_map(|arrived| {            let data = arrived["email"]["data"].as_object()?;            let from = data.get("from_email").and_then(Value::as_str).unwrap_or_default().to_lowercase();            let to_him = data.get("direction").and_then(Value::as_str) != Some("out") && !know.is_own(&from);            let waiting = data.get("unread").and_then(Value::as_bool) == Some(true) && data.get("in_inbox").and_then(Value::as_bool) != Some(false);            if !to_him || !waiting {                return None;            }            if setting != "everyone" && know.who(&from, None, Some(data)) != Who::Person {                return None;            }            let name = data.get("from_name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&from);            let subject = data.get("subject").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| p("list.no_subject", &[]));            Some(json!({ "id": arrived["email"]["id"], "thread": arrived["thread"]["id"], "title": name, "body": subject }))        })        .collect())}/// One arrival's rows into this copy: its email (when not here already), its conversation (new, or its last mail and/// count moved), its participants. Whether a new mail landed.fn land(ctx: &mut Ctx<'_>, arrived: &Value) -> Result<bool, String> {    use cotton_tools::mcp::handlers::common::{insert_row, update_row};    let ws_id = ctx.workspace_id.to_string();    let with_ws = |data: &Value| {        let mut row = data.as_object().cloned().unwrap_or_default();        row.insert("workspace_id".into(), json!(ws_id));        row    };    let email_id = arrived["email"]["id"].as_str().unwrap_or_default().to_string();    if email_id.is_empty() || one(ctx, &format!("SELECT id FROM {EMAILS} WHERE id = ?"), &[text(email_id.clone())])?.is_some() {        return Ok(false);    }    let thread = &arrived["thread"];    let thread_id = thread["id"].as_str().unwrap_or_default().to_string();    let sent_at = arrived["email"]["data"]["sent_at"].as_str().unwrap_or_default().to_string();    match one(ctx, &format!("SELECT last_at, email_count FROM {MAIL_THREADS} WHERE id = ?"), &[text(thread_id.clone())])? {        Some(held) => {            let last = s(&held, "last_at").unwrap_or_default();            let count = held.get("email_count").and_then(Value::as_i64).unwrap_or(0) + 1;            let mut patch = json!({ "email_count": count });            if sent_at > last {                patch["last_at"] = json!(sent_at);            }            update_row(ctx, MAIL_THREADS, &thread_id, patch.as_object().cloned().unwrap_or_default()).map_err(|e| e.to_string())?;        }        None => insert_row(ctx, MAIL_THREADS, &thread_id, with_ws(&thread["data"])).map_err(|e| e.to_string())?,    }    insert_row(ctx, EMAILS, &email_id, with_ws(&arrived["email"]["data"])).map_err(|e| e.to_string())?;    for person in arrived["participants"].as_array().into_iter().flatten() {        let Some(pid) = person["id"].as_str() else { continue };        if one(ctx, "SELECT id FROM cotton_email_participants WHERE id = ?", &[text(pid.to_string())])?.is_none() {            insert_row(ctx, "cotton_email_participants", pid, with_ws(&person["data"])).map_err(|e| e.to_string())?;        }    }    Ok(true)}