Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Calendar changes made elsewhere arrive within seconds
Yashwanth Kamireddib77cd34f216b
diff --git a/crates/quince-icloud/src/calendar.rs b/crates/quince-icloud/src/calendar.rsindex eb9cd4b..ec93abe 100644--- a/crates/quince-icloud/src/calendar.rs+++ b/crates/quince-icloud/src/calendar.rs@@ -836,6 +836,34 @@ impl<'a> CalendarClient<'a> {body}+ /// Which calendars changed since `known` — each calendar's guid and the ctag last seen —+ /// from `/ca/idle`, icloud.com's own "has anything changed" call. It does not wait: it+ /// answers in a few hundred milliseconds with the calendars whose ctag is not the one+ /// sent, any it was not told of, and any gone. Nothing changed is an empty list.+ ///+ /// Measured: the body is `{ClientState: {Collection: [{guid, ctag}], alarmRange,+ /// fullState: true, userTime}}`, and the answer is `{ChangeSet: {inserts|updates|deletes:+ /// {Collection: [...]}}}`. It needs the same query a read does, dates included.+ pub async fn changed(+ &self,+ known: &[(String, String)],+ tz: &str,+ ) -> Result<Vec<(String, Option<String>)>> {+ let today = jiff::Zoned::now().date().to_string();+ let state: Vec<Value> = known+ .iter()+ .map(|(guid, ctag)| serde_json::json!({ "guid": guid, "ctag": ctag }))+ .collect();+ let body = serde_json::json!({ "ClientState": {+ "Collection": state, "alarmRange": 60, "fullState": true,+ "userTime": jiff::Timestamp::now().as_second(),+ } });+ let answer = self+ .post("/ca/idle", &body, &today, &today, Some(tz), None)+ .await?;+ Ok(changed_collections(&answer))+ }+async fn post(&self,path: &str,@@ -913,11 +941,60 @@ impl<'a> CalendarClient<'a> {}}+/// The calendars an `/ca/idle` answer says changed: guid and new ctag, `None` when gone.+#[must_use]+pub fn changed_collections(answer: &Value) -> Vec<(String, Option<String>)> {+ let mut out = Vec::new();+ for (kind, gone) in [("inserts", false), ("updates", false), ("deletes", true)] {+ let Some(list) = answer+ .pointer(&format!("/ChangeSet/{kind}/Collection"))+ .and_then(Value::as_array)+ else {+ continue;+ };+ for c in list {+ // A delete may name the calendar by guid alone, or be the guid itself.+ let guid = c.get("guid").and_then(Value::as_str).or_else(|| c.as_str());+ if let Some(guid) = guid {+ let ctag = if gone {+ None+ } else {+ c.get("ctag").and_then(Value::as_str).map(str::to_string)+ };+ out.push((guid.to_string(), ctag));+ }+ }+ }+ out+}+#[cfg(test)]mod tests {use super::*;use serde_json::json;+ /// The shapes `/ca/idle` was measured answering with: nothing, a calendar it was not told+ /// of, a calendar whose tag moved; and a calendar gone.+ #[test]+ fn idle_answers_read_as_the_calendars_that_changed() {+ assert!(+ changed_collections(&json!({"ChangeSet":{"UpcomingAlarm":[],"fullState":true}}))+ .is_empty()+ );+ let answer = json!({"ChangeSet":{"fullState":true,+ "inserts":{"Collection":[{"guid":"MMEBirthdays","ctag":"c1","title":"Untitled"}]},+ "updates":{"Collection":[{"guid":"411F","ctag":"c2"}]},+ "deletes":{"Collection":[{"guid":"OLD"}]}}});+ assert_eq!(+ changed_collections(&answer),+ vec![+ ("MMEBirthdays".to_string(), Some("c1".to_string())),+ ("411F".to_string(), Some("c2".to_string())),+ ("OLD".to_string(), None),+ ]+ );+ }+#[test]fn a_date_is_read_in_its_own_timezone() {// 14:30 in Kolkata is 09:00 UTC — the zone is what makes this unambiguous.diff --git a/probe/examples/ca_idle.rs b/probe/examples/ca_idle.rsindex eafcc55..2c65ab6 100644--- a/probe/examples/ca_idle.rs+++ b/probe/examples/ca_idle.rs@@ -1,9 +1,9 @@-//! Read-only: whether `/ca/idle` (icloud.com Calendar's push-or-poll call) holds the request-//! open until a calendar changes, and what it answers when one does.+//! Live, read-only: poll `/ca/idle` every two seconds and print each change it reports,+//! so a change made elsewhere can be timed from the moment it is made.use anyhow::{anyhow, Result};#[tokio::main]async fn main() -> Result<()> {- let wait: u64 = std::env::args()+ let secs: u64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(60);@@ -17,71 +17,32 @@ async fn main() -> Result<()> {.service_url("calendar").ok_or_else(|| anyhow!("no calendar"))?;let (http, p) = (client.http().clone(), client.service_params());- let cal = quince_icloud::calendar::CalendarClient::new(&http, &root, p.clone());- let snap = cal- .startup("2026-10-01", "2026-10-31", "Asia/Kolkata")- .await?;- let state: Vec<_> = snap- .calendars- .iter()- .filter(|c| c.ctag.is_some())- .map(|c| serde_json::json!({ "guid": c.guid, "ctag": c.ctag }))- .collect();- println!("{} calendars with a ctag", state.len());- let mut q = p.clone();- q.push(("clientVersion".into(), "5.1".into()));- q.push(("lang".into(), "en-us".into()));- q.push(("usertz".into(), "Asia/Kolkata".into()));- q.push(("requestID".into(), "9".into()));- q.push(("startDate".into(), "2026-10-01".into()));- q.push(("endDate".into(), "2026-10-31".into()));+ let cal = quince_icloud::calendar::CalendarClient::new(&http, &root, p);let now = || {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs_f64()};- let mut state = state;- for round in 0..3 {- let t = now();- println!(- "round {round}: idle sent at {t:.3} with {} collections",- state.len()- );- let r = http.post(format!("{root}/ca/idle")).query(&q).timeout(std::time::Duration::from_secs(wait))- .json(&serde_json::json!({ "ClientState": { "Collection": state, "alarmRange": 60, "fullState": true, "userTime": t as i64 } }))- .send().await;- match r {- Ok(r) => {- let st = r.status();- let v: serde_json::Value = r.json().await.unwrap_or_default();- println!(- " answered after {:.1}s: {st} {}",- now() - t,- v.to_string().chars().take(400).collect::<String>()- );- for c in v- .pointer("/ChangeSet/inserts/Collection")- .and_then(|c| c.as_array())- .cloned()- .unwrap_or_default()- .into_iter()- .chain(- v.pointer("/ChangeSet/updates/Collection")- .and_then(|c| c.as_array())- .cloned()- .unwrap_or_default(),- )- {- state.retain(|s| s["guid"] != c["guid"]);- state.push(serde_json::json!({ "guid": c["guid"], "ctag": c["ctag"] }));- }- }- Err(e) => {- println!(" no answer after {:.1}s: {e}", now() - t);- break;+ let mut known: Vec<(String, String)> = Vec::new();+ let end = std::time::Instant::now() + std::time::Duration::from_secs(secs);+ let mut first = true;+ while std::time::Instant::now() < end {+ let changed = cal.changed(&known, "Asia/Kolkata").await?;+ for (guid, ctag) in &changed {+ known.retain(|(g, _)| g != guid);+ if let Some(ctag) = ctag {+ known.push((guid.clone(), ctag.clone()));}}+ if !first && !changed.is_empty() {+ println!("change at {:.3}: {changed:?}", now());+ }+ if first {+ println!("watching {} calendars from {:.3}", known.len(), now());+ }+ first = false;+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;}Ok(())}diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rsindex 50a16b6..4d549ee 100644--- a/src-tauri/src/push.rs+++ b/src-tauri/src/push.rs@@ -40,10 +40,83 @@ fn service_of(container: &str) -> Option<&'static str> {pub fn spawn(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {let (tx, rx) = mpsc::unbounded_channel::<&'static str>();- tauri::async_runtime::spawn(refresher(app, Arc::clone(&client), rx));+ tauri::async_runtime::spawn(refresher(app.clone(), Arc::clone(&client), rx));+ tauri::async_runtime::spawn(watch_calendar(app, Arc::clone(&client), tx.clone()));tauri::async_runtime::spawn(listen(client, tx));}+/// How often Calendar is asked whether anything changed: often while the window is open,+/// rarely from the tray, where only an alert depends on it.+const CALENDAR_LOOK: Duration = Duration::from_secs(4);+const CALENDAR_LOOK_HIDDEN: Duration = Duration::from_secs(30);++/// Calendar has no push for the web. Its own "has anything changed" call, `/ca/idle`, answers+/// in a few hundred milliseconds with only the calendars whose tag moved, so it is asked every+/// few seconds and a full refresh runs only when one did — measured within the poll of a+/// change made on another device.+async fn watch_calendar(+ app: tauri::AppHandle,+ client: Arc<Mutex<Client>>,+ tx: mpsc::UnboundedSender<&'static str>,+) {+ let zone = jiff::tz::TimeZone::system()+ .iana_name()+ .unwrap_or("UTC")+ .to_string();+ // Each calendar's tag as last seen; empty until the first answer seeds it.+ let mut known: Vec<(String, String)> = Vec::new();+ let mut seeded = false;+ let mut backoff = Duration::from_secs(5);+ loop {+ let visible = app+ .get_webview_window("main")+ .and_then(|w| w.is_visible().ok())+ .unwrap_or(false);+ tokio::time::sleep(if visible {+ CALENDAR_LOOK+ } else {+ CALENDAR_LOOK_HIDDEN+ })+ .await;+ let session = {+ let guard = client.lock().await;+ let s = guard.session();+ s.webservices+ .is_some()+ .then(|| s.service_url("calendar"))+ .flatten()+ .map(|root| (guard.http().clone(), guard.service_params(), root))+ };+ let Some((http, params, root)) = session else {+ seeded = false;+ known.clear();+ continue;+ };+ let calendar = quince_icloud::calendar::CalendarClient::new(&http, &root, params);+ match calendar.changed(&known, &zone).await {+ Ok(changed) => {+ backoff = Duration::from_secs(5);+ for (guid, ctag) in &changed {+ known.retain(|(g, _)| g != guid);+ if let Some(ctag) = ctag {+ known.push((guid.clone(), ctag.clone()));+ }+ }+ // The first answer is every calendar there is, not a change.+ if seeded && !changed.is_empty() {+ tx.send("calendar").ok();+ }+ seeded = true;+ }+ Err(e) => {+ eprintln!("calendar watch: {e}");+ tokio::time::sleep(backoff).await;+ backoff = (backoff * 2).min(Duration::from_secs(5 * 60));+ }+ }+ }+}+/// Refresh what the pushes named, a burst at a time.async fn refresher(app: tauri::AppHandle,