//! DAYS' CHANGES TO GOOGLE CALENDAR (CONTRACT.md section 16, 22 Nov 2026). //! //! The object cannot read a sealed event, so this phone sends Google's write //! in plain over its own door (`POST /v1/google/events`); the object hands it //! to Google and keeps nothing of it. What waits is said by the row's clear //! columns: `sync_state = 'pending'` on an event that is on Google //! (`gcal_id`) or is to go there (`on_google`). The core's own edit rules //! mark a synced row pending when it is changed or binned //! (`cotton_core::rules::event_edits`); Days marks its own events when they //! gain people going by Google, or when the person keeps their Days events //! in Google too. //! //! - **insert**: an event Google does not hold yet; with guests, Google //! emails them (`notify: all`). //! - **patch**: an event Google holds, or one occurrence of a series it holds //! (`_`); an event from Google carries its etag //! so Google refuses it when it changed first. //! - **delete**: a binned event Google holds; it stays in the bin here, //! without its Google id. //! //! Google's copy wins: when Google changed an event first the row takes //! Google's copy and what the person typed is kept in their own note, said //! once. A grant that cannot write, or one Google stopped honouring, stops //! the pass and answers the line with Connect; a Google that does not answer //! stops it quietly (the rows wait). use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use cotton_core::cotton_rules::js::parse_date_ms; use cotton_core::cotton_rules::moment_split::{join_moment, MomentSplit}; use cotton_core::cotton_rules::zoned_clock::{day_key, local_day}; use cotton_store::driver::Row; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::update_row; use super::days::{event_row, with_read, with_write}; use super::days_people::{connect_act, guests, line, say, Heard, Via}; use crate::handle::CottonHandle; use crate::methods::MethodError; /// At most this many events sent in one call. const MOST: usize = 50; /// At most this many of the person's own events put on Google in one call when they keep them there. const KEEP_MOST: usize = 200; fn sql(error: impl std::fmt::Display) -> MethodError { MethodError::new("unreadable", error.to_string()) } fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError { MethodError::new("write_refused", failure.to_string()) } fn holds(ctx: &Ctx<'_>, column: &str) -> Result { Ok(ctx.read.driver().all("SELECT name FROM pragma_table_info('cotton_events')", &[]).map_err(sql)?.iter().any(|r| r.text("name") == Some(column))) } /// `days.send_to_google { timezone }` → `{ sent, said, reconnect, more }`. pub fn send(handle: &CottonHandle, request: &Value) -> Result { 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"))?.to_string(); let client = handle.client(); let quiet = json!({ "sent": 0, "said": [], "reconnect": null, "more": false }); let Ok(status) = super::google::call(handle, "google.status", &json!({})) else { return Ok(quiet) }; Heard::google(&client, &status); let heard = Heard::of(&client); let account = heard.writable().flatten(); if status["keep"] == json!(true) && account.is_some() { keep_own(handle, &zone, request.get("today").and_then(Value::as_str))?; } let waiting = pending(handle)?; if waiting.is_empty() { return Ok(quiet); } let Some(account) = account else { // Something waits for Google and no grant can write it: ask once more, with why. let line_key = if heard.connected_google() { "google.needs_write" } else { "people.blocked" }; return Ok(json!({ "sent": 0, "said": [], "reconnect": { "line": line(line_key)?, "connect": connect_act(&heard)? }, "more": false })); }; let door = client.object_door().ok_or_else(|| MethodError::new("not_connected", "this phone is not connected to its database yet"))?; let more = waiting.len() > MOST; let mut said = Vec::new(); let mut sent = 0; for id in waiting.into_iter().take(MOST) { let Some(write) = with_read(handle, "days.send_to_google", |ctx| Ok(compose(ctx, &id, &zone, &account)?.unwrap_or(Value::Null)))? .as_object().cloned() else { continue }; let asked = Value::Object(write.clone()); if asked["op"] == json!("none") { with_write(handle, "days.send_to_google", |ctx| settle(ctx, &id, &Map::new(), &asked))?; continue; } match door.send("POST", "/v1/google/events", Some(&asked)) { Ok(answer) => { let words = with_write(handle, "days.send_to_google", |ctx| land(ctx, &id, &asked, &answer, &zone))?; if let Some(words) = words.as_str() { said.push(words.to_string()); } sent += 1; } Err(refused) if refused.code == "google_needs_write" => { return Ok(json!({ "sent": sent, "said": said, "reconnect": { "line": line("google.needs_write")?, "connect": connect_act(&heard)? }, "more": true })); } Err(refused) if refused.code == "reconnect_required" => { return Ok(json!({ "sent": sent, "said": said, "reconnect": { "line": line("google.reconnect")?, "connect": connect_act(&heard)? }, "more": true })); } // Google or the object did not answer: everything waits for the next pass. Err(_) => return Ok(json!({ "sent": sent, "said": said, "reconnect": null, "more": true })), } } Ok(json!({ "sent": sent, "said": said, "reconnect": null, "more": more })) } /// The events waiting for Google, oldest change first. fn pending(handle: &CottonHandle) -> Result, MethodError> { let found = with_read(handle, "days.send_to_google", |ctx| { let rows = ctx .read .driver() .all( // Waiting: marked pending; or one occurrence of a series Google holds, changed here and not sent yet. "SELECT id FROM cotton_events WHERE (sync_state = 'pending' AND (gcal_id IS NOT NULL OR on_google = 1)) OR (gcal_id IS NULL AND original_starts_at IS NOT NULL AND COALESCE(sync_state, '') <> 'synced' AND trashed_at IS NULL AND series_id IN (SELECT id FROM cotton_events WHERE gcal_id IS NOT NULL)) ORDER BY updated_at, id LIMIT ?", &[SqlValue::Integer((MOST + 1) as i64)], ) .map_err(sql)?; Ok(Value::from(rows.iter().filter_map(|r| r.text("id").map(str::to_string)).collect::>())) })?; Ok(found.as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect()) } /// "Also keep my Days events in Google Calendar": the person's own events from today on (repeating ones still /// running) are marked to go, a bounded number a call. fn keep_own(handle: &CottonHandle, zone: &str, today: Option<&str>) -> Result<(), MethodError> { let today = match today { Some(day) => day.to_string(), None => day_key(local_day(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0), zone).map_err(sql)?), }; let from = join_moment(&MomentSplit { date: today, time: None }, zone).map_err(sql)?; with_write(handle, "days.keep_in_google", |ctx| { let invited = if holds(ctx, "invited")? { "AND (invited IS NULL OR invited <> 'invited')" } else { "" }; let rows = ctx .read .driver() .all( &format!("SELECT id FROM cotton_events WHERE gcal_id IS NULL AND on_google = 0 AND trashed_at IS NULL AND series_id IS NULL {invited} AND (rrule IS NOT NULL OR COALESCE(ends_at, starts_at) >= ?) ORDER BY starts_at LIMIT ?"), &[SqlValue::Text(from.clone()), SqlValue::Integer(KEEP_MOST as i64)], ) .map_err(sql)?; for id in rows.iter().filter_map(|r| r.text("id").map(str::to_string)).collect::>() { let mut patch = Map::new(); patch.insert("on_google".into(), Value::Bool(true)); patch.insert("sync_state".into(), json!("pending")); update_row(ctx, "cotton_events", &id, patch).map_err(tool)?; } ctx.commit().map_err(tool)?; Ok(Value::Null) })?; Ok(()) } /// The zone an event is read in: its own, else the phone's. fn zone_of(row: &Row, zone: &str) -> String { row.text("timezone").filter(|z| !z.is_empty()).unwrap_or(zone).to_string() } /// `20261121T153000Z` for an instant; `20261121` for an all-day one's day. fn basic(iso: &str, all_day: bool, zone: &str) -> Option { let ms = parse_date_ms(iso)?; if all_day { return Some(day_key(local_day(ms, zone).ok()?).replace('-', "")); } let utc = chrono::DateTime::::from_timestamp_millis(ms)?; Some(utc.format("%Y%m%dT%H%M%SZ").to_string()) } /// An event's start and end as Google takes them. fn times(row: &Row, zone: &str) -> Result<(Value, Value), MethodError> { let starts = row.text("starts_at").ok_or_else(|| MethodError::new("unreadable", "an event with no start"))?; let all_day = row.int("all_day").unwrap_or(0) != 0; if all_day { let start_ms = parse_date_ms(starts).ok_or_else(|| sql("a start that is not an instant"))?; let first = local_day(start_ms, zone).map_err(sql)?; let last = row.text("ends_at").and_then(parse_date_ms).map(|ms| local_day(ms, zone)).transpose().map_err(sql)?.unwrap_or(first).max(first); // Google's end date is the day after the last. return Ok((json!({ "date": day_key(first) }), json!({ "date": day_key(last + 1) }))); } let ends = row.text("ends_at").unwrap_or(starts); Ok((json!({ "dateTime": starts, "timeZone": zone }), json!({ "dateTime": ends, "timeZone": zone }))) } /// A series' repeats as Google's recurrence lines. fn recurrence(row: &Row, zone: &str) -> Option { let rule = row.text("rrule")?; let all_day = row.int("all_day").unwrap_or(0) != 0; let mut lines = vec![format!("RRULE:{}", rule.trim_start_matches("RRULE:"))]; let exdates: Vec = row.text("exdates").and_then(|raw| serde_json::from_str::>(raw).ok()).unwrap_or_default(); let said: Vec = exdates.iter().filter_map(|at| basic(at, all_day, zone)).collect(); if !said.is_empty() { lines.push(if all_day { format!("EXDATE;VALUE=DATE:{}", said.join(",")) } else { format!("EXDATE:{}", said.join(",")) }); } Some(json!(lines)) } /// What one waiting event asks of Google, or `op: none` when nothing is to be sent (a binned event Google never /// held), or `None` when it waits for its series to go first. fn compose(ctx: &Ctx<'_>, id: &str, phone_zone: &str, account: &str) -> Result, MethodError> { let found = ctx .read .driver() .get("SELECT id FROM cotton_events WHERE id = ?", &[SqlValue::Text(id.to_string())]) .map_err(sql)?; if found.is_none() { return Ok(None); } // event_row hides binned rows; a binned one is read here as it stands. let row = match event_row(ctx, id)? { Some(row) => row, None => { let extra = if holds(ctx, "account")? { "account" } else { "NULL AS account" }; let row = ctx.read.driver().get(&format!("SELECT id, gcal_id, gcal_etag, series_id, original_starts_at, all_day, {extra} FROM cotton_events WHERE id = ?"), &[SqlValue::Text(id.to_string())]).map_err(sql)?.ok_or_else(|| sql("gone"))?; let Some(gcal) = row.text("gcal_id") else { return Ok(Some(json!({ "op": "none" }))) }; let mut asked = json!({ "op": "delete", "gcalId": gcal, "notify": "all" }); if let Some(etag) = row.text("gcal_etag") { asked["etag"] = json!(etag); } if let Some(acct) = row.text("account") { asked["account"] = json!(acct); } return Ok(Some(asked)); } }; let zone = zone_of(&row, phone_zone); let master = row.text("series_id").map(|s| event_row(ctx, s)).transpose()?.flatten(); let owner = row.text("series_id").filter(|_| row.text("original_starts_at").is_some()).unwrap_or(id); let people = guests(ctx, owner)?; let google_people: Vec = people .iter() .filter(|g| !g.removed && !g.organizer && g.via != Via::Cotton) .filter_map(|g| g.email.as_ref().map(|e| json!({ "email": e, "displayName": g.name }))) .collect(); let (start, end) = times(&row, &zone)?; let mut event = json!({ "summary": row.text("title").unwrap_or_default(), "start": start, "end": end }); if let Some(notes) = row.text("notes") { event["description"] = json!(notes); } if let Some(location) = row.text("location") { event["location"] = json!(location); } if let Some(lines) = recurrence(&row, &zone) { event["recurrence"] = lines; } // Days sends the list it holds; a Google event whose people were never touched here keeps Google's list. if !people.is_empty() || row.text("gcal_id").is_none() { event["attendees"] = json!(google_people); } let notify = if google_people.is_empty() && people.iter().all(|g| g.via == Via::Cotton) { "none" } else { "all" }; let mut asked = json!({ "event": event, "notify": notify, "account": row.text("account").unwrap_or(account) }); match (row.text("gcal_id"), &master) { (Some(gcal), _) => { asked["op"] = json!("patch"); asked["gcalId"] = json!(gcal); if let Some(etag) = row.text("gcal_etag") { asked["etag"] = json!(etag); } } // One occurrence of a series Google holds, moved or changed here. (None, Some(master)) if row.text("original_starts_at").is_some() => { let Some(series) = master.text("gcal_id") else { return Ok(None) }; let all_day = master.int("all_day").unwrap_or(0) != 0; let at = basic(row.text("original_starts_at").unwrap_or_default(), all_day, &zone_of(master, phone_zone)).ok_or_else(|| sql("an occurrence with no start"))?; asked["op"] = json!("patch"); asked["gcalId"] = json!(format!("{series}_{at}")); event_without_recurrence(&mut asked); } // The row's id names Google's event, so a retried insert is the same event and nobody is mailed twice. _ => { asked["op"] = json!("insert"); asked["id"] = json!(id); } } Ok(Some(asked)) } fn event_without_recurrence(asked: &mut Value) { if let Some(event) = asked["event"].as_object_mut() { event.remove("recurrence"); } } /// Google's guests as the pull keeps them in `guest_responses`. fn guest_list(attendees: &Value) -> Value { Value::from( attendees .as_array() .into_iter() .flatten() .filter_map(|a| { let mut g = json!({ "email": a["email"].as_str()?, "answer": a["responseStatus"].as_str().unwrap_or("needsAction") }); if let Some(name) = a["displayName"].as_str() { g["name"] = json!(name); } if a["self"] == json!(true) { g["self"] = json!(true); } if a["organizer"] == json!(true) { g["organizer"] = json!(true); } Some(g) }) .collect::>(), ) } /// What Google answered, laid on the row; answers the line to say, if any. fn land(ctx: &mut Ctx<'_>, id: &str, asked: &Value, answer: &Value, zone: &str) -> Result { let mut patch = Map::new(); let title = event_row(ctx, id)?.and_then(|r| r.text("title").map(str::to_string)).unwrap_or_default(); if answer["gone"] == json!(true) { // Deleted at Google: a delete is done; a change to it bins it here too. patch.insert("gcal_id".into(), Value::Null); patch.insert("gcal_etag".into(), Value::Null); patch.insert("sync_state".into(), Value::Null); let binned = ctx.read.driver().get("SELECT trashed_at FROM cotton_events WHERE id = ?", &[SqlValue::Text(id.to_string())]).map_err(sql)?.and_then(|r| r.text("trashed_at").map(str::to_string)); let words = if binned.is_none() { patch.insert("trashed_at".into(), json!(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true))); json!(say("google.gone", &[("title", &title)])?) } else { Value::Null }; update_row(ctx, "cotton_events", id, patch).map_err(tool)?; ctx.commit().map_err(tool)?; return Ok(words); } if asked["op"] == json!("delete") { // Done at Google; the row stays in the bin without its Google id. patch.insert("gcal_id".into(), Value::Null); patch.insert("gcal_etag".into(), Value::Null); patch.insert("sync_state".into(), Value::Null); update_row(ctx, "cotton_events", id, patch).map_err(tool)?; ctx.commit().map_err(tool)?; return Ok(Value::Null); } if answer["changed"] == json!(true) { return changed_first(ctx, id, asked, &answer["event"], zone, &title); } let mut patch = Map::new(); // An occurrence sent as its series' instance keeps no id of its own: the pull names it. if asked["op"] == json!("insert") || answer["gcalId"].as_str().is_some_and(|g| asked["gcalId"].as_str() == Some(g)) { if let Some(gcal) = answer["gcalId"].as_str() { patch.insert("gcal_id".into(), json!(gcal)); } } if let Some(etag) = answer["etag"].as_str() { patch.insert("gcal_etag".into(), json!(etag)); } if let Some(account) = answer["account"].as_str() { if holds(ctx, "account")? { patch.insert("account".into(), json!(account)); } } patch.insert("sync_state".into(), json!("synced")); patch.insert("on_google".into(), Value::Bool(true)); if answer.get("attendees").is_some_and(|a| a.as_array().is_some_and(|a| !a.is_empty())) && holds(ctx, "guest_responses")? { patch.insert("guest_responses".into(), json!(guest_list(&answer["attendees"]).to_string())); } update_row(ctx, "cotton_events", id, patch).map_err(tool)?; ctx.commit().map_err(tool)?; Ok(Value::Null) } /// A nothing-to-send row settled: a binned one Google never held loses its pending mark. fn settle(ctx: &mut Ctx<'_>, id: &str, _: &Map, _: &Value) -> Result { let mut patch = Map::new(); patch.insert("sync_state".into(), Value::Null); update_row(ctx, "cotton_events", id, patch).map_err(tool)?; ctx.commit().map_err(tool)?; Ok(Value::Null) } /// Google changed the event first: Google's copy on the row, what the person typed in their own note. fn changed_first(ctx: &mut Ctx<'_>, id: &str, asked: &Value, google: &Value, zone: &str, title: &str) -> Result { let typed = &asked["event"]; let row = event_row(ctx, id)?.ok_or_else(|| sql("gone"))?; let zone = zone_of(&row, zone); let clock = |at: &Value| -> Option { let ms = parse_date_ms(at["dateTime"].as_str()?)?; let parts = cotton_core::cotton_rules::zoned_clock::zoned_parts(ms, &zone).ok()?; Some(cotton_core::cotton_rules::days::layout::clock(parts.hour * 60 + parts.minute)) }; let typed_words = match (clock(&typed["start"]), clock(&typed["end"])) { (Some(s), Some(e)) if s != e => format!("{}, {s} to {e}", typed["summary"].as_str().unwrap_or(title)), (Some(s), _) => format!("{}, {s}", typed["summary"].as_str().unwrap_or(title)), _ => typed["summary"].as_str().unwrap_or(title).to_string(), }; let kept = say("google.kept_in_note", &[("words", &typed_words)])?; let mut patch = Map::new(); if let Some(summary) = google["summary"].as_str() { patch.insert("title".into(), json!(summary)); } if google.get("description").is_some() { patch.insert("notes".into(), google["description"].as_str().map_or(Value::Null, Value::from)); } let span = |at: &Value, end: bool| -> Option { if let Some(instant) = at["dateTime"].as_str() { return parse_date_ms(instant).map(|ms| chrono::DateTime::::from_timestamp_millis(ms).map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)).unwrap_or_default()); } let day = at["date"].as_str()?; let midnight = join_moment(&MomentSplit { date: day.to_string(), time: None }, &zone).ok()?; if !end { return Some(midnight); } // Google's end date is the day after the last: its midnight less a millisecond. let ms = parse_date_ms(&midnight)? - 1; chrono::DateTime::::from_timestamp_millis(ms).map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)) }; if let Some(starts) = span(&google["start"], false) { patch.insert("starts_at".into(), json!(starts)); patch.insert("all_day".into(), json!(google["start"]["date"].is_string())); } if let Some(ends) = span(&google["end"], true) { patch.insert("ends_at".into(), json!(ends)); } if let Some(etag) = google["etag"].as_str() { patch.insert("gcal_etag".into(), json!(etag)); } patch.insert("sync_state".into(), json!("synced")); // An event from Google keeps the person's own words in `your_note`; their own event, in its notes. let note_column = if row.text("gcal_id").is_some() && holds(ctx, "your_note")? { "your_note" } else { "notes" }; let held = if note_column == "notes" { patch.get("notes").and_then(Value::as_str).map(str::to_string) } else { row.text("your_note").map(str::to_string) }; let note = match held.filter(|n| !n.trim().is_empty()) { Some(note) => format!("{note}\n\n{kept}"), None => kept, }; patch.insert(note_column.into(), json!(note)); update_row(ctx, "cotton_events", id, patch).map_err(tool)?; ctx.commit().map_err(tool)?; Ok(json!(say("google.changed_first", &[("title", typed["summary"].as_str().unwrap_or(title))])?)) } #[cfg(test)] #[path = "days_push_tests.rs"] mod tests;