Cotton code
165 lines · 9.0 KB · RustRaw
//! GOOGLE CALENDAR IN DAYS' SETTINGS (coordinator, 22 Nov 2026): a person//! connects and disconnects a Google calendar from inside Days, sees which//! account is connected and when its events were last brought in, and reads a//! notice before Google's consent page (assets/design/days/GOOGLE.md §4).//!//! - `days.google { timezone, now? }` → `{ line, accounts: [{ email, says,//!   trouble, disconnect: { id, tool, account, label, asks, yes } }],//!   connect: { id, tool, label, notice: { title, body, go, notNow } } | null,//!   unavailable: String | null }`, in Days' words, from the object's//!   `google.status`. Connect stands only while no account is connected (and//!   reads "Connect again" while Google has stopped honouring one); the phone//!   shows its notice first and, on Continue to Google, runs it as the Calendar//!   tool's own act (`tools.act`), which answers the consent page to open. On a//!   phone not signed in nothing can be connected: `unavailable` says so.//! - `days.google_disconnect { account }` → `{ account, removed, said }`: the//!   grant revoked at Google and forgotten, and every event brought in from it//!   binned by the object (`google.disconnect`); `asks` said so before.use serde_json::{json, Value};use cotton_core::cotton_rules::days::{layout::{clock, day_words}, words};use cotton_core::cotton_rules::js::parse_date_ms;use cotton_core::cotton_rules::zoned_clock::{local_day, zoned_parts};use cotton_core::rules::shell_lines::LineSet;use crate::handle::CottonHandle;use crate::methods::MethodError;pub fn settings(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let at = At::of(request)?;    match super::google::call(handle, "google.status", &json!({})) {        Ok(status) => {            super::days_people::Heard::google(&handle.client(), &status);            shape(Some(&status), &at)        }        Err(refused) if refused.code == "not_connected" => {            super::days_people::Heard::not_connected(&handle.client());            shape(None, &at)        }        Err(refused) => Err(refused),    }}/// When and where the phone stands: `timezone` (required), `now` in ms (tests; else the clock).pub struct At {    pub zone: String,    pub now_ms: i64,}impl At {    pub fn of(request: &Value) -> Result<At, MethodError> {        let zone = request.get("timezone").and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "`timezone` is the zone the phone stands in"))?;        zoned_parts(0, zone).map_err(|error| MethodError::new("bad_request", error.to_string()))?;        let now_ms = request.get("now").and_then(Value::as_i64).unwrap_or_else(|| {            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)        });        Ok(At { zone: zone.to_string(), now_ms })    }}/// "today at 9:05", "yesterday at 21:40", "on Tue at 9:05", "on 12 Nov at 9:05": when the object last brought events in.fn when(synced_ms: i64, at: &At) -> Result<String, MethodError> {    let zone_error = |error: cotton_core::cotton_rules::zoned_clock::ZoneError| MethodError::new("bad_request", error.to_string());    let parts = zoned_parts(synced_ms, &at.zone).map_err(zone_error)?;    let time = clock(parts.hour * 60 + parts.minute);    let day = local_day(synced_ms, &at.zone).map_err(zone_error)?;    let today = local_day(at.now_ms, &at.zone).map_err(zone_error)?;    match today - day {        0 => line("settings.synced_today", &[("time", &time)]),        1 => line("settings.synced_yesterday", &[("time", &time)]),        _ => line("settings.synced_on", &[("day", &day_words(day, today, words::words("en"))), ("time", &time)]),    }}/// `days.google_keep { on }` → `{ keep }`: whether the person's own events go to Google too.pub fn keep(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| MethodError::new("bad_request", "`on` is true or false"))?;    let door = handle.client().object_door().ok_or_else(|| MethodError::new("not_connected", "this phone is not connected to its database yet"))?;    let answer = door.send("POST", "/v1/google/settings", Some(&json!({ "keep": on })))?;    Ok(json!({ "keep": answer["keep"].as_bool().unwrap_or(on) }))}pub fn disconnect(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let account = request.get("account").and_then(Value::as_str).map(str::trim).filter(|a| !a.is_empty())        .ok_or_else(|| MethodError::new("bad_request", "name the Google account to disconnect"))?;    let answer = super::google::call(handle, "google.disconnect", &json!({ "account": account }))?;    disconnected(&answer, account)}/// What the object's disconnect answered, said in Days' words: the account, and how many events left with it.pub fn disconnected(answer: &Value, asked: &str) -> Result<Value, MethodError> {    let email = answer["account"].as_str().unwrap_or(asked);    let removed = answer["removed"].as_u64().unwrap_or(0);    let count = removed.to_string();    let said = counted("settings.disconnected", removed, &[("email", email), ("count", &count)])?;    Ok(json!({ "account": email, "removed": removed, "said": said }))}/// A line by how many: `<name>_none`, `<name>_one`, or `<name>` with `{count}`.fn counted(name: &str, count: u64, fills: &[(&str, &str)]) -> Result<String, MethodError> {    match count {        0 => line(&format!("{name}_none"), fills),        1 => line(&format!("{name}_one"), fills),        _ => line(name, fills),    }}/// Settings' Google group from the object's status; `None`: this phone is not connected to its object.pub fn shape(status: Option<&Value>, at: &At) -> Result<Value, MethodError> {    let line_of = |name: &str| line(name, &[]);    let Some(status) = status else {        // Signed out: say why, and offer Sign in right there, never a dead end (store pass, 24 Nov 2026).        return Ok(json!({ "line": line_of("settings.calendars_line")?, "accounts": [], "connect": null, "unavailable": line_of("settings.google_sign_in")?, "signIn": line_of("settings.sign_in")? }));    };    let available = status["available"] == json!(true);    let mut accounts = Vec::new();    let mut reconnect = false;    for account in status["accounts"].as_array().into_iter().flatten() {        let Some(email) = account["googleEmail"].as_str() else { continue };        let calendar = &account["calendar"];        let phase = calendar["phase"].as_str().unwrap_or("waiting");        let count = calendar["eventCount"].as_u64().unwrap_or(0);        let synced = calendar["syncedAt"].as_str().and_then(|iso| parse_date_ms(iso));        let (says, trouble) = match (phase, synced) {            ("reconnect", _) => { reconnect = true; (line_of("settings.google_reconnect")?, true) }            _ if calendar["lastError"].is_string() => (line_of("settings.google_trouble")?, true),            ("synced", Some(ms)) => {                let when = when(ms, at)?;                let key = if count == 1 { "settings.google_synced_one" } else { "settings.google_synced" };                (line(key, &[("when", &when), ("count", &count.to_string())])?, false)            }            _ => (line_of("settings.google_bringing")?, false),        };        accounts.push(json!({            "email": email, "says": says, "trouble": trouble,            "disconnect": { "id": "google_disconnect", "tool": "calendar", "account": email, "label": line_of("settings.disconnect")?,                            "asks": counted("settings.disconnect_ask", count, &[("email", email), ("count", &count.to_string())])?, "yes": line_of("settings.disconnect")? },        }));    }    let connect = if available && (accounts.is_empty() || reconnect) {        let label = if reconnect { line_of("settings.connect_again")? } else { line_of("settings.connect")? };        let notice = json!({ "title": line_of("settings.notice_title")?, "body": line_of("settings.notice")?, "go": line_of("settings.notice_go")?, "notNow": line_of("settings.notice_not_now")? });        json!({ "id": "google_connect", "tool": "calendar", "label": label, "notice": notice })    } else {        Value::Null    };    let unavailable = if available { Value::Null } else { json!(line_of("settings.google_unavailable")?) };    // "Also keep my Days events in Google Calendar" (CONTRACT.md section 16), default off, while an account stands.    let keep = if accounts.is_empty() {        Value::Null    } else {        json!({ "label": line_of("google.keep")?, "line": line_of("google.keep_line")?, "on": status["keep"] == json!(true) })    };    Ok(json!({ "line": line_of("settings.calendars_line")?, "accounts": accounts, "connect": connect, "unavailable": unavailable, "keep": keep }))}fn line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> {    LineSet::shipped("days")        .and_then(|lines| lines.say(name, fills))        .ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {name}")))}#[cfg(test)]#[path = "days_google_tests.rs"]mod tests;