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
Drive: each app's own folder follows its changes too
Yashwanth Kamireddi09544156204a
diff --git a/crates/quince-icloud/src/drive_changes.rs b/crates/quince-icloud/src/drive_changes.rsindex dc4383a..79f4d8d 100644--- a/crates/quince-icloud/src/drive_changes.rs+++ b/crates/quince-icloud/src/drive_changes.rs@@ -12,6 +12,11 @@//! - a structure record's `parent` field is a reference to its folder's `directory/<id>`; a//! deletion is a move into Recently Deleted's directory, a purge a `deleted` record.//!+//! Each app's own folder (Pages, Numbers, Shortcuts…) is a zone of its own named for the app,+//! with the same records: `directory/<id>` is Drive's `FOLDER::<zone>::<id>`, and+//! `directory/documents` the app's top folder, `FOLDER::<zone>::documents`. The database's+//! changes name the zones that moved, so only those are read.+//!//! Names are encrypted there, so the feed is read for *which* folders changed — never what//! is in them: those folders are then listed again through Drive's web service, as before.@@ -20,7 +25,7 @@ use serde_json::{json, Value};/// Drive's container and its main zone.pub const CONTAINER: &str = "com.apple.clouddocs";-const ZONE: &str = "com.apple.CloudDocs";+pub const MAIN_ZONE: &str = "com.apple.CloudDocs";/// One record the feed named, as Drive knows it.#[derive(Debug, Clone, PartialEq, Eq)]@@ -43,8 +48,8 @@ pub struct Page {pub more: bool,}-/// Drive's identifier for a record of the main zone, or `None` for anything else it holds.-pub fn drivewsid_of(record_name: &str) -> Option<String> {+/// Drive's identifier for a record of `zone`, or `None` for anything else it holds.+pub fn drivewsid_of(zone: &str, record_name: &str) -> Option<String> {let (kind, id) = record_name.split_once('/')?;if id.is_empty() {return None;@@ -54,12 +59,13 @@ pub fn drivewsid_of(record_name: &str) -> Option<String> {"documentStructure" | "documentContent" => "FILE",_ => return None,};- Some(format!("{kind}::{ZONE}::{id}"))+ Some(format!("{kind}::{zone}::{id}"))}/// A page of `changes/zone`, as Drive knows its items. The same item named twice (its/// structure and its content) is told once, with what the structure said of its folder.-pub fn parse_page(body: &Value) -> Result<Page> {+pub fn parse_page(zone_name: &str, body: &Value) -> Result<Page> {+ let id_of = |name: &str| drivewsid_of(zone_name, name);let zone = body["zones"].get(0).ok_or_else(|| Error::Protocol("changes/zone answered no zone".into()))?;@@ -72,12 +78,12 @@ pub fn parse_page(body: &Value) -> Result<Page> {}let mut changed: Vec<Changed> = Vec::new();for record in zone["records"].as_array().into_iter().flatten() {- let Some(drivewsid) = record["recordName"].as_str().and_then(drivewsid_of) else {+ let Some(drivewsid) = record["recordName"].as_str().and_then(id_of) else {continue;};let parent = record["fields"]["parent"]["value"]["recordName"].as_str()- .and_then(drivewsid_of);+ .and_then(id_of);let gone = record["deleted"].as_bool().unwrap_or(false);match changed.iter_mut().find(|c| c.drivewsid == drivewsid) {Some(seen) => {@@ -98,12 +104,21 @@ pub fn parse_page(body: &Value) -> Result<Page> {})}-/// One page of Drive's change feed from `token` (from the start with none). Read-only; asks-/// only for the `parent` field, so a page is small whatever the files hold.+/// CloudKit's query, as CloudKit JS asks — the way every other CloudKit read here does.+fn query(params: &[(String, String)]) -> Vec<(String, String)> {+ let mut query = params.to_vec();+ query.push(("ckjsBuildVersion".into(), "17DProjectDev77".into()));+ query.push(("ckjsVersion".into(), "2.6.1".into()));+ query+}++/// One page of a Drive zone's change feed from `token` (from the start with none). Read-only;+/// asks only for the `parent` field, so a page is small whatever the files hold.pub async fn page(http: &reqwest::Client,ckdatabasews_root: &str,params: &[(String, String)],+ zone_name: &str,token: Option<&str>,) -> Result<Page> {let url = format!(@@ -111,20 +126,16 @@ pub async fn page(ckdatabasews_root.trim_end_matches('/'));let mut zone = json!({- "zoneID": { "zoneName": ZONE, "zoneType": "REGULAR_CUSTOM_ZONE" },+ "zoneID": { "zoneName": zone_name, "zoneType": "REGULAR_CUSTOM_ZONE" },"resultsLimit": 200,"desiredKeys": ["parent"],});if let Some(t) = token.filter(|t| !t.is_empty()) {zone["syncToken"] = Value::String(t.to_string());}- // As CloudKit JS asks, the way every other CloudKit read here does.- let mut query = params.to_vec();- query.push(("ckjsBuildVersion".into(), "17DProjectDev77".into()));- query.push(("ckjsVersion".into(), "2.6.1".into()));let response = http.post(url)- .query(&query)+ .query(&query(params)).json(&json!({ "zones": [zone] })).send().await?;@@ -141,7 +152,80 @@ pub async fn page(}let body: Value = serde_json::from_str(&text).map_err(|e| Error::Protocol(format!("changes/zone sent invalid JSON: {e}")))?;- parse_page(&body)+ parse_page(zone_name, &body)+}++/// The zones of Drive a page of `changes/database` names — every zone there is when asked+/// with no token — leaving out each app's settings zone, which holds no files.+pub fn parse_zones(body: &Value) -> (Vec<String>, Option<String>, bool) {+ let zones = body["zones"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|z| z["zoneID"]["zoneName"].as_str())+ .filter(|z| !z.ends_with(".container-metadata"))+ .map(str::to_string)+ .collect();+ (+ zones,+ body["syncToken"].as_str().map(str::to_string),+ body["moreComing"].as_bool().unwrap_or(false),+ )+}++/// The zones of Drive that moved since `token` — with none, every zone there is — and the+/// token to ask from next time. Read-only; a few hundred bytes when nothing moved.+pub async fn zones_moved(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: &[(String, String)],+ token: Option<&str>,+) -> Result<(Vec<String>, Option<String>)> {+ let url = format!(+ "{}/database/1/{CONTAINER}/production/private/changes/database",+ ckdatabasews_root.trim_end_matches('/')+ );+ let mut token = token.filter(|t| !t.is_empty()).map(str::to_string);+ let asked_with_token = token.is_some();+ let mut all: Vec<String> = Vec::new();+ for _ in 0..50 {+ let mut body = json!({});+ if let Some(t) = &token {+ body["syncToken"] = Value::String(t.clone());+ }+ let response = http+ .post(&url)+ .query(&query(params))+ .json(&body)+ .send()+ .await?;+ let status = response.status();+ if matches!(status.as_u16(), 401 | 421 | 450) {+ return Err(Error::ReauthRequired);+ }+ let text = response.text().await.unwrap_or_default();+ if !status.is_success() {+ if text.contains("CHANGE_TOKEN_EXPIRED") || status.as_u16() == 400 && asked_with_token {+ return Err(Error::StaleCursor);+ }+ return Err(Error::Protocol(format!(+ "changes/database answered {status}"+ )));+ }+ let body: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("changes/database sent invalid JSON: {e}")))?;+ let (zones, next, more) = parse_zones(&body);+ for z in zones {+ if !all.contains(&z) {+ all.push(z);+ }+ }+ token = next.or(token);+ if !more {+ break;+ }+ }+ Ok((all, token))}/// The folders to list again for what changed: where each item is now, and where it was —@@ -184,22 +268,28 @@ mod tests {#[test]fn records_are_read_as_drive_knows_them() {- assert_eq!(drivewsid_of("directory/root").as_deref(), Some(ROOT));+ let of = |name| drivewsid_of(MAIN_ZONE, name);+ assert_eq!(of("directory/root").as_deref(), Some(ROOT));assert_eq!(- drivewsid_of("directory/12121DA4").as_deref(),+ of("directory/12121DA4").as_deref(),Some("FOLDER::com.apple.CloudDocs::12121DA4"));assert_eq!(- drivewsid_of("documentStructure/7D85").as_deref(),+ of("documentStructure/7D85").as_deref(),Some("FILE::com.apple.CloudDocs::7D85"));assert_eq!(- drivewsid_of("documentContent/7D85").as_deref(),+ of("documentContent/7D85").as_deref(),Some("FILE::com.apple.CloudDocs::7D85"));- assert_eq!(drivewsid_of("AppContainer/x"), None);- assert_eq!(drivewsid_of("directory/"), None);- assert_eq!(drivewsid_of("nothing"), None);+ assert_eq!(of("AppContainer/x"), None);+ assert_eq!(of("directory/"), None);+ assert_eq!(of("nothing"), None);+ // An app's own folder (measured on Shortcuts' zone).+ assert_eq!(+ drivewsid_of("iCloud.is.workflow.my.workflows", "directory/documents").as_deref(),+ Some("FOLDER::iCloud.is.workflow.my.workflows::documents")+ );}/// The shape measured live when a folder was made in the top level and then deleted.@@ -215,7 +305,7 @@ mod tests {record("documentStructure/P", None, true),{ "recordName": "AppContainer/x", "recordType": "AppContainer" },] }] });- let page = parse_page(&body).unwrap();+ let page = parse_page(MAIN_ZONE, &body).unwrap();assert_eq!(page.token.as_deref(), Some("T2"));assert!(!page.more);assert_eq!(@@ -248,13 +338,35 @@ mod tests {#[test]fn a_token_apple_no_longer_knows_starts_over() {let body = json!({ "zones": [{ "serverErrorCode": "CHANGE_TOKEN_EXPIRED" }] });- assert!(matches!(parse_page(&body), Err(Error::StaleCursor)));assert!(matches!(- parse_page(&json!({ "zones": [] })),+ parse_page(MAIN_ZONE, &body),+ Err(Error::StaleCursor)+ ));+ assert!(matches!(+ parse_page(MAIN_ZONE, &json!({ "zones": [] })),Err(Error::Protocol(_))));}+ #[test]+ fn the_database_names_the_zones_that_moved_but_not_settings() {+ let body = json!({ "syncToken": "D2", "moreComing": false, "zones": [+ { "zoneID": { "zoneName": "com.apple.CloudDocs" } },+ { "zoneID": { "zoneName": "com.apple.CloudDocs.container-metadata" } },+ { "zoneID": { "zoneName": "com.apple.Pages" } } ] });+ assert_eq!(+ parse_zones(&body),+ (+ vec![+ "com.apple.CloudDocs".to_string(),+ "com.apple.Pages".to_string()+ ],+ Some("D2".to_string()),+ false+ )+ );+ }+/// A file moved from one folder to another: both are listed again, once each; a folder/// this computer never saw is left for when it is opened.#[test]diff --git a/probe/examples/drive_app_zones.rs b/probe/examples/drive_app_zones.rsnew file mode 100644index 0000000..65c80a2--- /dev/null+++ b/probe/examples/drive_app_zones.rs@@ -0,0 +1,81 @@+//! Read-only: how iCloud Drive's app-library zones (Pages, Keynote, Scriptable…) name their+//! records and parents in the change feed, to match them with Drive's own ids+//! (`FOLDER::<zone>::documents`, `FILE::<zone>::<id>`). Ids only.+use anyhow::{anyhow, Result};+use serde_json::{json, Value};++#[tokio::main]+async fn main() -> Result<()> {+ 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 s = client.session();+ let ck = s+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let drivews = s+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let base = format!(+ "{}/database/1/com.apple.clouddocs/production/private",+ ck.trim_end_matches('/')+ );+ let db: Value = http+ .post(format!("{base}/changes/database"))+ .query(&p)+ .json(&json!({}))+ .send()+ .await?+ .json()+ .await?;+ for z in db["zones"].as_array().into_iter().flatten() {+ let name = z["zoneID"]["zoneName"].as_str().unwrap_or("");+ if name == "com.apple.CloudDocs" || name.ends_with("container-metadata") {+ continue;+ }+ let mut token: Option<String> = None;+ let mut shown = 0;+ for _ in 0..20 {+ let mut zone =+ json!({"zoneID": z["zoneID"], "resultsLimit": 200, "desiredKeys": ["parent"]});+ if let Some(t) = &token {+ zone["syncToken"] = json!(t);+ }+ let body: Value = http+ .post(format!("{base}/changes/zone"))+ .query(&p)+ .json(&json!({"zones": [zone]}))+ .send()+ .await?+ .json()+ .await?;+ let zz = &body["zones"][0];+ token = zz["syncToken"].as_str().map(str::to_string);+ for r in zz["records"].as_array().into_iter().flatten() {+ if shown < 4 && r["deleted"] != true {+ println!(+ "{name}: {} parent={}",+ r["recordName"], r["fields"]["parent"]["value"]["recordName"]+ );+ shown += 1;+ }+ }+ if zz["moreComing"] != true {+ break;+ }+ }+ let root = format!("FOLDER::{name}::documents");+ match quince_icloud::drive::fetch_folder(&http, &drivews, p.clone(), &root).await {+ Ok(items) => {+ for i in items.iter().take(3) {+ println!("{name}: drivews {}", i.drivewsid);+ }+ }+ Err(e) => println!("{name}: drivews {root}: {e}"),+ }+ }+ Ok(())+}diff --git a/probe/examples/drive_watch_live.rs b/probe/examples/drive_watch_live.rsindex 62ba70e..adcf683 100644--- a/probe/examples/drive_watch_live.rs+++ b/probe/examples/drive_watch_live.rs@@ -16,7 +16,14 @@ async fn read() -> Result<Vec<Changed>> {let mut all = Vec::new();loop {- let pg = page(http, ck, p, token.as_deref()).await?;+ let pg = page(+ http,+ ck,+ p,+ quince_icloud::drive_changes::MAIN_ZONE,+ token.as_deref(),+ )+ .await?;all.extend(pg.changed);*token = pg.token.or(token.take());if !pg.more {diff --git a/src-tauri/src/drive_watch.rs b/src-tauri/src/drive_watch.rsindex 26a7bf3..9ff16db 100644--- a/src-tauri/src/drive_watch.rs+++ b/src-tauri/src/drive_watch.rs@@ -9,14 +9,17 @@//! Stored, every view reads them at once: the window is told which folders changed, and the//! Drive folder on this computer sees the library move.//!-//! The feed's position is kept in the library, so changes made while the app was closed are-//! read when it starts. The first run reads the feed through to now once — identifiers only,+//! Each app's own folder (Pages, Numbers, Shortcuts…) is a zone of its own, read the same way+//! when the database names it as moved.+//!+//! Each zone's position is kept in the library, so changes made while the app was closed are+//! read when it starts. The first run reads each zone through to now once — identifiers only,//! a few hundred bytes a record — before it can tell what is new.use crate::push::{poll_every, presence, sleep_or_wake, WAKE};use crate::Data;use quince_auth::Client;-use quince_icloud::drive_changes::{self, Changed, CONTAINER};+use quince_icloud::drive_changes::{self, Changed};use quince_icloud::Error;use std::sync::Arc;use std::time::Duration;@@ -26,18 +29,18 @@ use tokio::sync::Mutex;/// Told to the window with the folders listed again, so an open one redraws.pub const CHANGED: &str = "quince://drive-changed";-/// Where the feed was last read to, with the account it belongs to: `<dsid>\t<token>`.-const POSITION: &str = "drive.changes";+/// Where each zone's feed was last read to, with the account it belongs to ([`Positions`]).+const POSITION: &str = "drive.positions";/// The most pages one catch-up reads before it stores what it has and lets the next check go/// on. A first read of a large Drive is a few dozen pages.const PAGES_AT_ONCE: usize = 500;pub async fn watch(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {+ // The database's own position, in memory: asked with none, it names every zone there is,+ // so the first check after a start reads every zone from where it was left — changes made+ // while the app was closed included.let mut database: Option<String> = None;- // Read the feed on the first check whatever the database says: changes made while the- // app was closed are behind a database token seeded only now.- let mut catch_up = true;let mut backoff: Option<Duration> = None;let mut woken = WAKE.subscribe();loop {@@ -65,40 +68,30 @@ pub async fn watch(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {})};let Some((http, params, ck, drivews, dsid)) = session else {- (database, catch_up) = (None, true);+ database = None;sleep_or_wake(Duration::from_secs(30), &mut woken).await;continue;};- let moved = match quince_icloud::push::database_changed(- &http,- &ck,- ¶ms,- CONTAINER,- database.as_deref(),- )- .await- {- Ok((moved, next)) => {- database = next;- Ok(moved)- }- Err(Error::StaleCursor) => {- database = None;- Ok(true)- }- Err(e) => Err(e),- };- let result = match moved {- Ok(moved) if moved || catch_up => {- let read = read_feed(&app, &http, ¶ms, &ck, &drivews, &dsid).await;- if read.is_ok() {- catch_up = false;+ let result =+ match drive_changes::zones_moved(&http, &ck, ¶ms, database.as_deref()).await {+ Ok((zones, next)) => {+ let read = if zones.is_empty() {+ Ok(())+ } else {+ read_zones(&app, &http, ¶ms, &ck, &drivews, &dsid, &zones).await+ };+ // Moved on only once what it named is read: a failure asks the same again.+ if read.is_ok() {+ database = next;+ }+ read}- read- }- Ok(_) => Ok(()),- Err(e) => Err(e),- };+ Err(Error::StaleCursor) => {+ database = None;+ Ok(())+ }+ Err(e) => Err(e),+ };backoff = match result {Ok(()) => None,Err(e) => {@@ -116,50 +109,72 @@ pub async fn watch(app: tauri::AppHandle, client: Arc<Mutex<Client>>) {}}-/// Read the feed from where it was left, list again the folders it touched, and keep the new-/// position — only once they are stored, so a failure part way reads the same changes again.-async fn read_feed(+/// Where each zone's feed was last read to, for one account.+#[derive(Default, serde::Serialize, serde::Deserialize)]+struct Positions {+ dsid: String,+ zones: std::collections::BTreeMap<String, String>,+}++/// Read each zone's feed from where it was left, list again the folders it touched, and keep+/// the new positions — only once they are stored, so a failure part way reads the same+/// changes again. A zone never read before (the first run, an app newly using iCloud) is read+/// through to now, and only its end position kept: everything there is, not news.+async fn read_zones(app: &tauri::AppHandle,http: &reqwest::Client,params: &[(String, String)],ck: &str,drivews: &str,dsid: &str,+ zones: &[String],) -> quince_icloud::Result<()> {let data = app.state::<Data>();- let kept = data- .0- .lock()- .await- .state(POSITION)- .ok()- .flatten()- .and_then(|v| {- let (who, token) = v.split_once('\t')?;- (who == dsid).then(|| token.to_string())+ let kept: Option<String> = data.0.lock().await.state(POSITION).ok().flatten();+ let mut positions = kept+ .and_then(|v| serde_json::from_str::<Positions>(&v).ok())+ .filter(|p| p.dsid == dsid)+ .unwrap_or_else(|| Positions {+ dsid: dsid.to_string(),+ ..Positions::default()});- let first = kept.is_none();- let mut token = kept;let mut changed: Vec<Changed> = Vec::new();- for _ in 0..PAGES_AT_ONCE {- let page = match drive_changes::page(http, ck, params, token.as_deref()).await {- Err(Error::StaleCursor) if token.is_some() => {- // Apple no longer knows this position: forgotten, so the next check reads- // through to now as a first run does. What changed in between is found as- // before this watch, when each folder is next listed.- quiet!("drive watch: position expired; reading Drive's changes afresh");- let _ = data.0.lock().await.set_state(POSITION, "");- return Err(Error::StaleCursor);+ let mut failed = None;+ for zone in zones {+ let first = !positions.zones.contains_key(zone);+ let mut token = positions.zones.get(zone).cloned();+ let mut ok = true;+ for _ in 0..PAGES_AT_ONCE {+ match drive_changes::page(http, ck, params, zone, token.as_deref()).await {+ Ok(page) => {+ if !first {+ changed.extend(page.changed);+ }+ token = page.token.or(token);+ if !page.more {+ break;+ }+ }+ Err(Error::StaleCursor) if !first => {+ // Apple no longer knows this position (or the zone is gone): forgotten,+ // so the next look reads it through as new. What changed in between is+ // found when each folder is next listed.+ quiet!("drive watch: {zone}'s position expired; reading it afresh");+ positions.zones.remove(zone);+ ok = false;+ break;+ }+ Err(e) => {+ failed = Some(e);+ ok = false;+ break;+ }}- other => other?,- };- // A first read is everything there is, not news: only its end position is kept.- if !first {- changed.extend(page.changed);}- token = page.token.or(token);- if !page.more {- break;+ if ok {+ if let Some(t) = token {+ positions.zones.insert(zone.clone(), t);+ }}}let folders = {@@ -194,16 +209,12 @@ async fn read_feed(}listed.push(folder);}- if let Some(t) = token {- let _ = data- .0- .lock()- .await- .set_state(POSITION, &format!("{dsid}\t{t}"));+ if let Ok(json) = serde_json::to_string(&positions) {+ let _ = data.0.lock().await.set_state(POSITION, &json);}if !listed.is_empty() {quiet!("drive watch: {} folder(s) changed", listed.len());app.emit(CHANGED, &listed).ok();}- Ok(())+ failed.map_or(Ok(()), Err)}