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
Contacts changes made elsewhere arrive within seconds
Yashwanth Kamireddi283062bc7170
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex 7ab6440..d6cddd3 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -210,6 +210,63 @@ pub async fn fetch_book_with_tokens())}+/// Whether the address book changed since `tokens` were read, from `/co/changeset` —+/// icloud.com's own check, which answers in a few hundred milliseconds.+///+/// Measured: with nothing changed it answers 200 with the same sync token and no contacts.+/// After a change made anywhere it answers 420: the token is behind, read the book again.+/// A 200 that carries contacts or a new token is a change too, and its tokens are kept.+pub async fn changed(+ http: &reqwest::Client,+ root: &str,+ params: Vec<(String, String)>,+ tokens: &mut Tokens,+) -> Result<bool> {+ let mut query = params;+ query.push(("clientVersion".into(), "2.1".into()));+ query.push(("locale".into(), "en_US".into()));+ query.push(("order".into(), "last,first".into()));+ query.push(("prefToken".into(), tokens.pref.clone()));+ query.push(("syncToken".into(), tokens.sync.clone()));+ let url = format!("{}/co/changeset", root.trim_end_matches('/'));+ let response = http.post(url).query(&query).send().await?;+ match response.status().as_u16() {+ 420 => return Ok(true),+ 450 => return Err(Error::ReauthRequired),+ code if !(200..300).contains(&code) => {+ return Err(Error::Protocol(format!("/co/changeset answered {code}")));+ }+ _ => {}+ }+ let body: Value = response.json().await.unwrap_or(Value::Null);+ Ok(changeset_moved(&body, tokens))+}++/// Whether a 200 from `/co/changeset` says something changed; its tokens are taken either way.+fn changeset_moved(body: &Value, tokens: &mut Tokens) -> bool {+ let carries = |key: &str| {+ body.get(key)+ .and_then(Value::as_array)+ .is_some_and(|a| !a.is_empty())+ };+ let gone = body+ .get("deletes")+ .and_then(Value::as_object)+ .is_some_and(|d| {+ d.values()+ .any(|v| v.as_array().is_some_and(|a| !a.is_empty()))+ });+ let mut moved = carries("contacts") || carries("groups") || gone;+ if let Some(sync) = body.get("syncToken").and_then(Value::as_str) {+ moved |= sync != tokens.sync;+ tokens.sync = sync.to_string();+ }+ if let Some(pref) = body.get("prefToken").and_then(Value::as_str) {+ tokens.pref = pref.to_string();+ }+ moved+}+pub async fn fetch_with_tokens(http: &reqwest::Client,root: &str,@@ -1045,6 +1102,32 @@ mod list_tests {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn a_changeset_says_whether_anything_moved() {+ let mut t = Tokens {+ sync: "S1".into(),+ pref: "P".into(),+ };+ assert!(!changeset_moved(+ &serde_json::json!({"syncToken":"S1","prefToken":"P","contacts":[]}),+ &mut t+ ));+ assert!(changeset_moved(+ &serde_json::json!({"syncToken":"S2"}),+ &mut t+ ));+ assert_eq!(t.sync, "S2");+ assert!(changeset_moved(+ &serde_json::json!({"syncToken":"S2","deletes":{"contactIds":["x"]}}),+ &mut t+ ));+ assert!(changeset_moved(+ &serde_json::json!({"contacts":[{"contactId":"y"}]}),+ &mut t+ ));+ }+use serde_json::json;#[test]diff --git a/probe/examples/co_changeset.rs b/probe/examples/co_changeset.rsnew file mode 100644index 0000000..5ca4674--- /dev/null+++ b/probe/examples/co_changeset.rs@@ -0,0 +1,67 @@+//! Live, read-only: `/co/changeset` every two seconds from the startup tokens, printing what+//! each answer carries, so a change made elsewhere can be timed.+use anyhow::{anyhow, Result};+#[tokio::main]+async fn main() -> Result<()> {+ let secs: u64 = std::env::args()+ .nth(1)+ .and_then(|s| s.parse().ok())+ .unwrap_or(60);+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("contacts")+ .ok_or_else(|| anyhow!("no contacts"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let (_, mut tokens) =+ quince_icloud::contacts::fetch_with_tokens(&http, &root, p.clone()).await?;+ let now = || {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs_f64()+ };+ println!("from {:.3}", now());+ let end = std::time::Instant::now() + std::time::Duration::from_secs(secs);+ while std::time::Instant::now() < end {+ let mut q = p.clone();+ q.push(("clientVersion".into(), "2.1".into()));+ q.push(("locale".into(), "en_US".into()));+ q.push(("order".into(), "last,first".into()));+ q.push(("prefToken".into(), tokens.pref.clone()));+ q.push(("syncToken".into(), tokens.sync.clone()));+ let t = now();+ let r = http+ .post(format!("{root}/co/changeset"))+ .query(&q)+ .send()+ .await?;+ let st = r.status();+ let v: serde_json::Value = r.json().await.unwrap_or_default();+ let n = |k: &str| v.get(k).and_then(|a| a.as_array()).map_or(0, |a| a.len());+ let moved = v["syncToken"].as_str().is_some_and(|s| s != tokens.sync);+ if moved || n("contacts") > 0 || st != 200 {+ println!(+ "{:.3} ({:.2}s) {st}: contacts {} groups {} deletes {} token moved {moved}",+ now(),+ now() - t,+ n("contacts"),+ n("groups"),+ v["deletes"]+ );+ }+ if let Some(s) = v["syncToken"].as_str() {+ tokens.sync = s.to_string();+ }+ if let Some(s) = v["prefToken"].as_str() {+ tokens.pref = s.to_string();+ }+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;+ }+ println!("end; keys seen: {:?}", ());+ Ok(())+}diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rsindex 4d549ee..b6de8b9 100644--- a/src-tauri/src/push.rs+++ b/src-tauri/src/push.rs@@ -41,14 +41,77 @@ 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.clone(), Arc::clone(&client), rx));- tauri::async_runtime::spawn(watch_calendar(app, Arc::clone(&client), tx.clone()));+ tauri::async_runtime::spawn(watch_calendar(app.clone(), Arc::clone(&client), tx.clone()));+ tauri::async_runtime::spawn(watch_contacts(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,+/// Contacts, likewise without web push: `/co/changeset` from the last tokens answers 420+/// within seconds of a change made anywhere. Tokens are read once, and again after each+/// change, so the check stays against the book as it now is.+async fn watch_contacts(+ app: tauri::AppHandle,+ client: Arc<Mutex<Client>>,+ tx: mpsc::UnboundedSender<&'static str>,+) {+ let mut tokens: Option<quince_icloud::contacts::Tokens> = None;+ 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 {+ LOOK+ } else {+ LOOK_HIDDEN+ })+ .await;+ let session = {+ let guard = client.lock().await;+ let s = guard.session();+ s.webservices+ .is_some()+ .then(|| s.service_url("contacts"))+ .flatten()+ .map(|root| (guard.http().clone(), guard.service_params(), root))+ };+ let Some((http, params, root)) = session else {+ tokens = None;+ continue;+ };+ let result = match tokens.as_mut() {+ None => quince_icloud::contacts::fetch_with_tokens(&http, &root, params)+ .await+ .map(|(_, t)| {+ tokens = Some(t);+ false+ }),+ Some(t) => quince_icloud::contacts::changed(&http, &root, params, t).await,+ };+ match result {+ Ok(changed) => {+ backoff = Duration::from_secs(5);+ if changed {+ tx.send("contacts").ok();+ // Read afresh next time: a 420 means these tokens are behind for good.+ tokens = None;+ }+ }+ Err(e) => {+ eprintln!("contacts watch: {e}");+ tokens = None;+ tokio::time::sleep(backoff).await;+ backoff = (backoff * 2).min(Duration::from_secs(5 * 60));+ }+ }+ }+}++/// How often Calendar and Contacts are 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);+const LOOK: Duration = Duration::from_secs(4);+const 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@@ -73,9 +136,9 @@ async fn watch_calendar(.and_then(|w| w.is_visible().ok()).unwrap_or(false);tokio::time::sleep(if visible {- CALENDAR_LOOK+ LOOK} else {- CALENDAR_LOOK_HIDDEN+ LOOK_HIDDEN}).await;let session = {