Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

iCloud Drive browsing, and Photos is empty on this account

Yashwanth Kamireddic3fbca5c5eef
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index 67f7d6d..7b33aed 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -40,6 +40,9 @@ function installStub({ screen, services, twoFactor }) {
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
case "contacts_sync": return 0;
+ case "drive_children": return [];
+ case "drive_sync_folder": return 0;
+ case "drive_item": return null;
default: return null;
}
},
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index c884e08..f14e4ba 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -28,6 +28,9 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "contacts_list") return [];
if (cmd === "contacts_last_synced") return Math.floor(Date.now() / 1000);
if (cmd === "contacts_sync") return 0;
+ if (cmd === "drive_children") return [];
+ if (cmd === "drive_sync_folder") return 0;
+ if (cmd === "drive_item") return null;
return null;
},
};
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index c920255..c5f980d 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -39,6 +39,9 @@ function installStub({ screen, services, twoFactor }) {
case "contacts_list": return [];
case "contacts_last_synced": return Math.floor(Date.now() / 1000);
case "contacts_sync": return 0;
+ case "drive_children": return [];
+ case "drive_sync_folder": return 0;
+ case "drive_item": return null;
default: return null;
}
},
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index 38e4cb1..f2f70ac 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -19,7 +19,7 @@ const SERVICES = ["account","archivews","calendar","ckdatabasews","ckdeviceservi
value it needs must arrive through the single argument. */
/* Fixture events, so the agenda's rendering is verified without inventing rows in anyone's
real library. Times are unix seconds relative to now. */
-function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture }) {
+function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture, driveFixture }) {
const HOUR = 3600, DAY = 86400;
const base = Math.floor(Date.now() / 1000 / DAY) * DAY + 9 * HOUR;
const events = !calendarFixture ? [] : [
@@ -79,6 +79,20 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
birthday: null, notes: null, etag: null,
methods: [{ kind: "phone", label: null, value: "+91 90000 11111" }] },
];
+ const driveItems = !driveFixture ? [] : [
+ { drivewsid: "FOLDER::a", parentId: null, name: "Downloads", extension: null,
+ kind: "FOLDER", size: null, childCount: 3, createdAt: 1785000000,
+ modifiedAt: 1788000000, etag: null },
+ { drivewsid: "APPLIB::b", parentId: null, name: "Keynote", extension: null,
+ kind: "APP_LIBRARY", size: null, childCount: null, createdAt: 1780000000,
+ modifiedAt: null, etag: null },
+ { drivewsid: "APPLIB::c", parentId: null, name: "Shortcuts", extension: null,
+ kind: "APP_LIBRARY", size: null, childCount: null, createdAt: 1780000000,
+ modifiedAt: null, etag: null },
+ { drivewsid: "FILE::d", parentId: null, name: "Semester Plan", extension: "pdf",
+ kind: "FILE", size: 2411724, childCount: null, createdAt: 1787000000,
+ modifiedAt: 1788600000, etag: null },
+ ];
const calendars = [
{ guid: "work", title: "Work", colour: "#cc73e1", ctag: null, sortOrder: 0, enabled: true },
{ guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true },
@@ -113,6 +127,9 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "contacts_list": return !contactsFixture ? [] : contactList;
case "contacts_last_synced": return Math.floor(Date.now() / 1000) - 300;
case "contacts_sync": return contactList.length;
+ case "drive_children": return !driveFixture ? [] : driveItems;
+ case "drive_sync_folder": return driveItems.length;
+ case "drive_item": return null;
case "auth_two_factor_options": return twoFactor;
case "auth_resend_code": return null;
case "auth_send_sms": return null;
@@ -173,18 +190,24 @@ const shots = [
await p.waitForSelector(".contact-rows .contact-row");
await p.click('.contact-row:has-text("Zoya")');
} },
+ { name: "12-drive", screen: "library", theme: "dark", driveFixture: true,
+ viewport: { width: 1100, height: 760 },
+ act: async (p) => {
+ await p.click('.nav-item:has-text("iCloud Drive")');
+ await p.waitForSelector(".drive-rows .drive-row");
+ } },
{ name: "04-library", screen: "library", theme: "light" },
{ name: "05-library-dark", screen: "library", theme: "dark" },
];
const browser = await chromium.launch();
-for (const { name, screen, theme, act, twoFactor = PUSHED, calendarFixture = false, notesFixture = false, contactsFixture = false, viewport } of shots) {
+for (const { name, screen, theme, act, twoFactor = PUSHED, calendarFixture = false, notesFixture = false, contactsFixture = false, driveFixture = false, viewport } of shots) {
const ctx = await browser.newContext({
viewport: viewport ?? { width: 1040, height: 720 },
deviceScaleFactor: 2,
colorScheme: theme,
});
- await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor, calendarFixture, notesFixture, contactsFixture });
+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor, calendarFixture, notesFixture, contactsFixture, driveFixture });
const page = await ctx.newPage();
const errors = [];
page.on("console", (m) => m.type() === "error" && errors.push(m.text()));
diff --git a/crates/quince-core/src/drive.rs b/crates/quince-core/src/drive.rs
new file mode 100644
index 0000000..69eb8c2
--- /dev/null
+++ b/crates/quince-core/src/drive.rs
@@ -0,0 +1,258 @@
+//! iCloud Drive in the local library.
+//!
+//! Apple exposes Drive as a tree addressed by `drivewsid`, an identifier that encodes both
+//! the kind and the zone. Folders are fetched one level at a time, so the library holds
+//! whatever has been visited rather than a full mirror.
+
+use crate::{Library, Result};
+use rusqlite::params;
+use serde::{Deserialize, Serialize};
+
+/// The root every Drive browse starts from.
+pub const ROOT: &str = "FOLDER::com.apple.CloudDocs::root";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct DriveItem {
+ pub drivewsid: String,
+ pub parent_id: Option<String>,
+ pub name: String,
+ pub extension: Option<String>,
+ /// `FOLDER`, `APP_LIBRARY` or `FILE`.
+ pub kind: String,
+ pub size: Option<i64>,
+ pub child_count: Option<i64>,
+ pub created_at: Option<i64>,
+ pub modified_at: Option<i64>,
+ pub etag: Option<String>,
+}
+
+impl DriveItem {
+ /// True for anything that can be opened to reveal more items.
+ #[must_use]
+ pub fn is_container(&self) -> bool {
+ self.kind == "FOLDER" || self.kind == "APP_LIBRARY"
+ }
+
+ /// The name as a person reads it, with the extension Apple keeps separate.
+ #[must_use]
+ pub fn display_name(&self) -> String {
+ match self.extension.as_deref().filter(|e| !e.is_empty()) {
+ Some(ext) if !self.is_container() => format!("{}.{}", self.name, ext),
+ _ => self.name.clone(),
+ }
+ }
+}
+
+fn now() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
+}
+
+impl Library {
+ /// Replace the contents of one folder.
+ ///
+ /// Scoped to the folder rather than the whole tree: Drive is fetched a level at a time,
+ /// so anything outside this folder is simply not part of this answer.
+ pub fn put_drive_children(&mut self, parent_id: &str, items: &[DriveItem]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ let mut stmt = tx.prepare(
+ "INSERT INTO drive_items (drivewsid, parent_id, name, extension, kind, size,
+ child_count, created_at, modified_at, etag, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
+ ON CONFLICT(drivewsid) DO UPDATE SET
+ parent_id = excluded.parent_id, name = excluded.name,
+ extension = excluded.extension, kind = excluded.kind,
+ size = excluded.size, child_count = excluded.child_count,
+ created_at = excluded.created_at, modified_at = excluded.modified_at,
+ etag = excluded.etag, updated_at = excluded.updated_at",
+ )?;
+ let stamp = now();
+ for item in items {
+ stmt.execute(params![
+ item.drivewsid,
+ parent_id,
+ item.name,
+ item.extension,
+ item.kind,
+ item.size,
+ item.child_count,
+ item.created_at,
+ item.modified_at,
+ item.etag,
+ stamp
+ ])?;
+ }
+
+ // Anything still filed under this folder that Apple no longer lists was moved or
+ // deleted elsewhere.
+ let keep: Vec<&str> = items.iter().map(|i| i.drivewsid.as_str()).collect();
+ if keep.is_empty() {
+ tx.execute(
+ "DELETE FROM drive_items WHERE parent_id = ?1",
+ params![parent_id],
+ )?;
+ } else {
+ let placeholders = vec!["?"; keep.len()].join(",");
+ let mut args: Vec<&str> = vec![parent_id];
+ args.extend(keep);
+ tx.execute(
+ &format!(
+ "DELETE FROM drive_items WHERE parent_id = ? AND drivewsid NOT IN ({placeholders})"
+ ),
+ rusqlite::params_from_iter(args),
+ )?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// What is inside a folder, folders first and then by name — how a file browser reads.
+ pub fn drive_children(&self, parent_id: &str) -> Result<Vec<DriveItem>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT drivewsid, parent_id, name, extension, kind, size, child_count,
+ created_at, modified_at, etag
+ FROM drive_items
+ WHERE parent_id = ?1
+ ORDER BY kind = 'FILE', lower(name)",
+ )?;
+ let rows = stmt.query_map(params![parent_id], |row| {
+ Ok(DriveItem {
+ drivewsid: row.get(0)?,
+ parent_id: row.get(1)?,
+ name: row.get(2)?,
+ extension: row.get(3)?,
+ kind: row.get(4)?,
+ size: row.get(5)?,
+ child_count: row.get(6)?,
+ created_at: row.get(7)?,
+ modified_at: row.get(8)?,
+ etag: row.get(9)?,
+ })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
+ }
+
+ /// One item by its identifier, for building a breadcrumb trail.
+ pub fn drive_item(&self, drivewsid: &str) -> Result<Option<DriveItem>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT drivewsid, parent_id, name, extension, kind, size, child_count,
+ created_at, modified_at, etag
+ FROM drive_items WHERE drivewsid = ?1",
+ )?;
+ let mut rows = stmt.query_map(params![drivewsid], |row| {
+ Ok(DriveItem {
+ drivewsid: row.get(0)?,
+ parent_id: row.get(1)?,
+ name: row.get(2)?,
+ extension: row.get(3)?,
+ kind: row.get(4)?,
+ size: row.get(5)?,
+ child_count: row.get(6)?,
+ created_at: row.get(7)?,
+ modified_at: row.get(8)?,
+ etag: row.get(9)?,
+ })
+ })?;
+ Ok(rows.next().transpose()?)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn item(id: &str, name: &str, kind: &str) -> DriveItem {
+ DriveItem {
+ drivewsid: id.into(),
+ parent_id: None,
+ name: name.into(),
+ extension: if kind == "FILE" {
+ Some("pdf".into())
+ } else {
+ None
+ },
+ kind: kind.into(),
+ size: if kind == "FILE" { Some(1024) } else { None },
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: None,
+ }
+ }
+
+ #[test]
+ fn folders_come_before_files_then_alphabetical() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_drive_children(
+ ROOT,
+ &[
+ item("f3", "notes", "FILE"),
+ item("f1", "Zebra", "FOLDER"),
+ item("f2", "apples", "FOLDER"),
+ item("f4", "Archive", "FILE"),
+ ],
+ )
+ .unwrap();
+
+ let names: Vec<String> = lib
+ .drive_children(ROOT)
+ .unwrap()
+ .iter()
+ .map(|i| i.name.clone())
+ .collect();
+ assert_eq!(names, vec!["apples", "Zebra", "Archive", "notes"]);
+ }
+
+ #[test]
+ fn an_extension_shows_on_files_but_not_folders() {
+ assert_eq!(item("a", "report", "FILE").display_name(), "report.pdf");
+ assert_eq!(item("b", "Downloads", "FOLDER").display_name(), "Downloads");
+ }
+
+ #[test]
+ fn app_libraries_are_containers_too() {
+ assert!(item("a", "Shortcuts", "APP_LIBRARY").is_container());
+ assert!(item("b", "Downloads", "FOLDER").is_container());
+ assert!(!item("c", "report", "FILE").is_container());
+ }
+
+ /// Refreshing one folder must not disturb another; Drive is fetched a level at a time.
+ #[test]
+ fn refreshing_a_folder_leaves_other_folders_alone() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_drive_children(ROOT, &[item("a", "Downloads", "FOLDER")])
+ .unwrap();
+ lib.put_drive_children("a", &[item("a1", "inside", "FILE")])
+ .unwrap();
+
+ // Re-fetch the root; the child folder's contents must survive.
+ lib.put_drive_children(ROOT, &[item("a", "Downloads", "FOLDER")])
+ .unwrap();
+ assert_eq!(lib.drive_children("a").unwrap().len(), 1);
+ }
+
+ #[test]
+ fn an_item_removed_from_a_folder_disappears() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_drive_children(ROOT, &[item("a", "One", "FILE"), item("b", "Two", "FILE")])
+ .unwrap();
+ lib.put_drive_children(ROOT, &[item("a", "One", "FILE")])
+ .unwrap();
+ assert_eq!(lib.drive_children(ROOT).unwrap().len(), 1);
+ }
+
+ #[test]
+ fn an_item_can_be_looked_up_for_a_breadcrumb() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_drive_children(ROOT, &[item("a", "Downloads", "FOLDER")])
+ .unwrap();
+ let found = lib.drive_item("a").unwrap().unwrap();
+ assert_eq!(found.name, "Downloads");
+ assert_eq!(found.parent_id.as_deref(), Some(ROOT));
+ assert!(lib.drive_item("nope").unwrap().is_none());
+ }
+}
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index eed20a4..0c18147 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -6,6 +6,7 @@
pub mod calendar;
pub mod contacts;
+pub mod drive;
pub mod notes;
pub mod reminders;
pub mod schema;
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index d0281ee..ad1ce90 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -144,4 +144,25 @@ pub const MIGRATIONS: &[&str] = &[
CREATE INDEX contact_methods_by_contact ON contact_methods (contact_guid, kind, position);
"#,
+ // 6 — iCloud Drive, stored as the tree Apple exposes.
+ r#"
+ CREATE TABLE drive_items (
+ -- Apple's own identifier, which encodes the kind and zone: FOLDER::com.apple.CloudDocs::root
+ drivewsid TEXT PRIMARY KEY,
+ parent_id TEXT,
+ name TEXT NOT NULL,
+ extension TEXT,
+ -- FOLDER, APP_LIBRARY or FILE.
+ kind TEXT NOT NULL,
+ size INTEGER,
+ child_count INTEGER,
+ created_at INTEGER,
+ modified_at INTEGER,
+ etag TEXT,
+ updated_at INTEGER NOT NULL
+ ) STRICT;
+
+ -- Browsing is always "what is inside this folder", ordered folders first.
+ CREATE INDEX drive_by_parent ON drive_items (parent_id, kind, name);
+ "#,
];
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
new file mode 100644
index 0000000..6bc473c
--- /dev/null
+++ b/crates/quince-icloud/src/drive.rs
@@ -0,0 +1,184 @@
+//! iCloud Drive's web service.
+//!
+//! Drive is fetched a folder at a time from `retrieveItemDetailsInFolders`, which takes a
+//! list of folder identifiers and answers with their contents.
+
+use crate::{Error, Result};
+use quince_core::drive::DriveItem;
+use serde_json::{json, Value};
+
+fn string(v: &Value, key: &str) -> Option<String> {
+ v.get(key)
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(ToString::to_string)
+}
+
+/// Apple sends dates as milliseconds in some fields and ISO strings in others.
+fn seconds(v: &Value, key: &str) -> Option<i64> {
+ match v.get(key)? {
+ Value::Number(n) => n.as_i64().map(|ms| ms / 1000),
+ Value::String(s) => jiff::Timestamp::strptime("%Y-%m-%dT%H:%M:%S%z", s)
+ .ok()
+ .map(|t| t.as_second())
+ .or_else(|| s.parse::<jiff::Timestamp>().ok().map(|t| t.as_second())),
+ _ => None,
+ }
+}
+
+fn item_from(v: &Value) -> Option<DriveItem> {
+ Some(DriveItem {
+ drivewsid: string(v, "drivewsid")?,
+ parent_id: string(v, "parentId"),
+ name: string(v, "name").unwrap_or_else(|| "Untitled".into()),
+ extension: string(v, "extension"),
+ kind: string(v, "type").unwrap_or_else(|| "FILE".into()),
+ // Apple sends -1 for things that have no size, which is not a size.
+ size: v.get("size").and_then(Value::as_i64).filter(|n| *n >= 0),
+ child_count: v.get("directChildrenCount").and_then(Value::as_i64),
+ created_at: seconds(v, "dateCreated"),
+ modified_at: seconds(v, "dateModified").or_else(|| seconds(v, "dateChanged")),
+ etag: string(v, "etag"),
+ })
+}
+
+/// Read the contents of one folder from a `retrieveItemDetailsInFolders` response.
+#[must_use]
+pub fn parse_folder(body: &Value) -> Vec<DriveItem> {
+ body.as_array()
+ .and_then(|folders| folders.first())
+ .and_then(|folder| folder.get("items"))
+ .and_then(Value::as_array)
+ .map(|items| items.iter().filter_map(item_from).collect())
+ .unwrap_or_default()
+}
+
+/// Fetch one folder's contents and store them.
+pub async fn sync_folder(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ library: &mut quince_core::Library,
+ folder_id: &str,
+) -> Result<usize> {
+ let mut query = params;
+ query.push(("clientVersion".into(), "2.1".into()));
+
+ let url = format!(
+ "{}/retrieveItemDetailsInFolders",
+ root.trim_end_matches('/')
+ );
+ let body = json!([{ "drivewsid": folder_id, "partialData": false }]);
+
+ let response = http.post(url).query(&query).json(&body).send().await?;
+ let status = response.status();
+ let text = response.text().await.unwrap_or_default();
+
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ return Err(Error::Protocol(format!(
+ "Drive returned {status}: {}",
+ text.chars().take(160).collect::<String>()
+ )));
+ }
+
+ let parsed: Value = serde_json::from_str(&text)
+ .map_err(|e| Error::Protocol(format!("Drive returned invalid JSON: {e}")))?;
+ let items = parse_folder(&parsed);
+ library.put_drive_children(folder_id, &items)?;
+ library.mark_synced("drive", None)?;
+ Ok(items.len())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn response() -> Value {
+ json!([{
+ "drivewsid": "FOLDER::com.apple.CloudDocs::root",
+ "items": [
+ { "drivewsid": "FOLDER::com.apple.CloudDocs::abc", "parentId": "FOLDER::com.apple.CloudDocs::root",
+ "name": "Downloads", "type": "FOLDER", "directChildrenCount": 3,
+ "dateCreated": "2026-08-01T10:00:00Z", "etag": "e1", "size": -1 },
+ { "drivewsid": "FILE::com.apple.CloudDocs::def", "parentId": "FOLDER::com.apple.CloudDocs::root",
+ "name": "report", "extension": "pdf", "type": "FILE", "size": 20480,
+ "dateModified": 1757000000000_i64, "etag": "e2" },
+ { "drivewsid": "APPLIBRARY::com.apple.Keynote::x", "name": "Keynote",
+ "type": "APP_LIBRARY", "size": -1 }
+ ]
+ }])
+ }
+
+ #[test]
+ fn a_folder_listing_is_read() {
+ let items = parse_folder(&response());
+ assert_eq!(items.len(), 3);
+
+ let folder = &items[0];
+ assert_eq!(folder.name, "Downloads");
+ assert!(folder.is_container());
+ assert_eq!(folder.child_count, Some(3));
+ assert!(folder.size.is_none(), "-1 is not a size");
+ assert!(folder.created_at.is_some(), "an ISO date should parse");
+
+ let file = &items[1];
+ assert_eq!(file.display_name(), "report.pdf");
+ assert_eq!(file.size, Some(20480));
+ assert_eq!(
+ file.modified_at,
+ Some(1_757_000_000),
+ "milliseconds become seconds"
+ );
+
+ assert!(
+ items[2].is_container(),
+ "an app library opens like a folder"
+ );
+ }
+
+ #[test]
+ fn an_item_without_an_identifier_is_skipped() {
+ let body = json!([{ "items": [{ "name": "ghost", "type": "FILE" }] }]);
+ assert!(parse_folder(&body).is_empty());
+ }
+
+ #[test]
+ fn an_empty_or_odd_response_is_an_empty_folder() {
+ assert!(parse_folder(&json!([])).is_empty());
+ assert!(parse_folder(&json!({})).is_empty());
+ assert!(parse_folder(&json!([{ "drivewsid": "x" }])).is_empty());
+ }
+
+ #[tokio::test]
+ async fn syncing_a_folder_stores_its_contents() {
+ use wiremock::matchers::{method, path_regex};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path_regex(r".*/retrieveItemDetailsInFolders$"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(response()))
+ .mount(&server)
+ .await;
+
+ let mut library = quince_core::Library::in_memory().unwrap();
+ let stored = sync_folder(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &mut library,
+ quince_core::drive::ROOT,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(stored, 3);
+ let children = library.drive_children(quince_core::drive::ROOT).unwrap();
+ assert_eq!(children.len(), 3);
+ assert_eq!(children[0].name, "Downloads", "folders sort first");
+ }
+}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 8ddff63..df00361 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -7,6 +7,7 @@ pub mod calendar;
pub mod ckdocument;
pub mod cloudkit;
pub mod contacts;
+pub mod drive;
pub mod notes;
pub mod reminders;
pub mod sync;
diff --git a/probe/src/main.rs b/probe/src/main.rs
index 0ff9757..02872a2 100644
--- a/probe/src/main.rs
+++ b/probe/src/main.rs
@@ -764,6 +764,178 @@ async fn main() -> Result<()> {
}
}
+ // ---- Photos: which query actually returns assets? ---------------------------
+ // changes/zone returns only CPLLibraryInfo, so assets must come from records/query —
+ // which for photos is allowed, unlike the reminders types.
+ println!("\n\x1b[1m── Photos: finding the assets ──\x1b[0m");
+ if let Some(ck) = session.service_url("ckdatabasews") {
+ let url =
+ format!("{ck}/database/1/com.apple.photos.cloud/production/private/records/query");
+ let mut q = client.service_params();
+ q.push(("ckjsBuildVersion".into(), "17DProjectDev77".into()));
+ q.push(("ckjsVersion".into(), "2.6.1".into()));
+ q.push(("remapEnums".into(), "True".into()));
+
+ // The smart-album queries Apple's own web client uses, plus the plain record types.
+ let attempts: [(&str, serde_json::Value); 4] = [
+ (
+ "index count",
+ serde_json::json!({
+ "query": {
+ "recordType": "HyperionIndexCountLookup",
+ "filterBy": [{
+ "fieldName": "indexCountID",
+ "comparator": "IN",
+ "fieldValue": { "type": "STRING_LIST",
+ "value": ["CPLAssetByAssetDateWithoutHiddenOrDeleted"] }
+ }]
+ },
+ "zoneID": { "zoneName": "PrimarySync" },
+ }),
+ ),
+ (
+ "assets by date",
+ serde_json::json!({
+ "query": {
+ "recordType": "CPLAssetAndMasterByAssetDateWithoutHiddenOrDeleted",
+ "filterBy": [
+ { "fieldName": "startRank", "comparator": "EQUALS",
+ "fieldValue": { "type": "INT64", "value": 0 } },
+ { "fieldName": "direction", "comparator": "EQUALS",
+ "fieldValue": { "type": "STRING", "value": "ASCENDING" } }
+ ]
+ },
+ "resultsLimit": 4,
+ "zoneID": { "zoneName": "PrimarySync" },
+ }),
+ ),
+ (
+ "CPLAsset",
+ serde_json::json!({
+ "query": { "recordType": "CPLAsset" },
+ "resultsLimit": 3,
+ "zoneID": { "zoneName": "PrimarySync" },
+ }),
+ ),
+ (
+ "CPLMaster",
+ serde_json::json!({
+ "query": { "recordType": "CPLMaster" },
+ "resultsLimit": 3,
+ "zoneID": { "zoneName": "PrimarySync" },
+ }),
+ ),
+ ];
+
+ for (label, body) in attempts {
+ match client.http().post(&url).query(&q).json(&body).send().await {
+ Err(e) => println!(" {label:<18} transport: {e}"),
+ Ok(r) => {
+ let status = r.status();
+ let text = r.text().await.unwrap_or_default();
+ let v: serde_json::Value =
+ serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
+ match v.get("records").and_then(|r| r.as_array()) {
+ Some(records) => {
+ println!(
+ " \x1b[32m{label:<18}\x1b[0m {status} {} record(s)",
+ records.len()
+ );
+ for rec in records.iter().take(2) {
+ let rt = rec
+ .get("recordType")
+ .and_then(|t| t.as_str())
+ .unwrap_or("?");
+ // An index count carries the library size, which is the
+ // difference between "no photos" and "wrong query".
+ if let Some(count) = rec.pointer("/fields/itemCount/value") {
+ println!(" {rt}: itemCount = {count}");
+ continue;
+ }
+ let mut fields: Vec<String> = rec
+ .get("fields")
+ .and_then(|f| f.as_object())
+ .map(|o| o.keys().cloned().collect())
+ .unwrap_or_default();
+ fields.sort();
+ println!(
+ " {rt}: {}",
+ fields.join(", ").chars().take(300).collect::<String>()
+ );
+ }
+ }
+ None => println!(
+ " {label:<18} {status} {}",
+ text.chars()
+ .take(120)
+ .collect::<String>()
+ .replace('\n', " ")
+ ),
+ }
+ }
+ }
+ }
+ }
+
+ // ---- what Drive items look like ---------------------------------------------
+ println!("\n\x1b[1m── iCloud Drive: shape ──\x1b[0m");
+ if let Some(root) = session.service_url("drivews") {
+ let mut q = client.service_params();
+ let body = serde_json::json!([{
+ "drivewsid": "FOLDER::com.apple.CloudDocs::root",
+ "partialData": false,
+ }]);
+ q.push(("clientVersion".into(), "2.1".into()));
+ match client
+ .http()
+ .post(format!(
+ "{}/retrieveItemDetailsInFolders",
+ root.trim_end_matches('/')
+ ))
+ .query(&q)
+ .json(&body)
+ .send()
+ .await
+ {
+ Err(e) => println!(" transport: {e}"),
+ Ok(r) => {
+ let status = r.status();
+ let text = r.text().await.unwrap_or_default();
+ let v: serde_json::Value =
+ serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
+ let folders = v.as_array().map(Vec::as_slice).unwrap_or(&[]);
+ println!(" {status}: {} folder(s)", folders.len());
+ for folder in folders.iter().take(1) {
+ let items = folder
+ .get("items")
+ .and_then(|i| i.as_array())
+ .map(Vec::as_slice)
+ .unwrap_or(&[]);
+ println!(" items: {}", items.len());
+ for item in items.iter().take(4) {
+ let mut keys: Vec<String> = item
+ .as_object()
+ .map(|o| o.keys().cloned().collect())
+ .unwrap_or_default();
+ keys.sort();
+ let kind = item.get("type").and_then(|t| t.as_str()).unwrap_or("?");
+ let name = item.get("name").and_then(|n| n.as_str()).unwrap_or("?");
+ let ext = item.get("extension").and_then(|e| e.as_str()).unwrap_or("");
+ let size = item
+ .get("size")
+ .and_then(serde_json::Value::as_i64)
+ .unwrap_or(-1);
+ println!(
+ " [{kind}] {name}{}{ext} size={size}",
+ if ext.is_empty() { "" } else { "." }
+ );
+ println!(" fields: {}", keys.join(", "));
+ }
+ }
+ }
+ }
+ }
+
// ---- CloudKit containers ----------------------------------------------------
// Apple's legacy /rd and /ca endpoints answer with a placeholder once data has been
// upgraded to the modern format. The real records live in CloudKit, so find out which
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index e791e45..4b8c56d 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -4,6 +4,7 @@
use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
use quince_core::calendar::{Calendar, Event};
use quince_core::contacts::Contact;
+use quince_core::drive::DriveItem;
use quince_core::notes::{Note, NoteFolder};
use quince_core::reminders::{Reminder, ReminderList};
use quince_core::Library;
@@ -446,6 +447,45 @@ async fn contacts_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
library.last_synced("contacts").map_err(|e| e.to_string())
}
+/// Fetch one Drive folder's contents from Apple and store them.
+///
+/// Drive is browsed a level at a time, so this takes the folder being opened rather than
+/// mirroring the whole tree.
+#[tauri::command]
+async fn drive_sync_folder(
+ folder_id: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<usize> {
+ let (http, root, params) = {
+ let client = auth.client.lock().await;
+ let root = client
+ .session()
+ .service_url("drivews")
+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?;
+ (client.http().clone(), root, client.service_params())
+ };
+ let mut library = data.0.lock().await;
+ quince_icloud::drive::sync_folder(&http, &root, params, &mut library, &folder_id)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn drive_children(folder_id: String, data: State<'_, Data>) -> UiResult<Vec<DriveItem>> {
+ let library = data.0.lock().await;
+ library
+ .drive_children(&folder_id)
+ .map_err(|e| e.to_string())
+}
+
+/// One item, for building the breadcrumb trail back to the root.
+#[tauri::command]
+async fn drive_item(drivewsid: String, data: State<'_, Data>) -> UiResult<Option<DriveItem>> {
+ let library = data.0.lock().await;
+ library.drive_item(&drivewsid).map_err(|e| e.to_string())
+}
+
fn main() {
tauri::Builder::default()
.setup(|app| {
@@ -490,6 +530,9 @@ fn main() {
contacts_sync,
contacts_list,
contacts_last_synced,
+ drive_sync_folder,
+ drive_children,
+ drive_item,
reminder_set_done,
])
.run(tauri::generate_context!())
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 0fcce56..bd137f2 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -53,6 +53,10 @@ export const api = {
contactsSync: () => invoke<number>("contacts_sync"),
contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
contactsLastSynced: () => invoke<number | null>("contacts_last_synced"),
+
+ driveSyncFolder: (folderId: string) => invoke<number>("drive_sync_folder", { folderId }),
+ driveChildren: (folderId: string) => invoke<DriveItem[]>("drive_children", { folderId }),
+ driveItem: (drivewsid: string) => invoke<DriveItem | null>("drive_item", { drivewsid }),
};
/** Tauri rejects with a plain string from our commands; keep it readable either way. */
@@ -141,6 +145,28 @@ export function displayName(c: Contact): string {
return c.methods[0]?.value ?? "No Name";
}
+export type DriveItem = {
+ drivewsid: string;
+ parentId: string | null;
+ name: string;
+ extension: string | null;
+ /** FOLDER, APP_LIBRARY or FILE. */
+ kind: string;
+ size: number | null;
+ childCount: number | null;
+ createdAt: number | null;
+ modifiedAt: number | null;
+ etag: string | null;
+};
+
+export const DRIVE_ROOT = "FOLDER::com.apple.CloudDocs::root";
+
+export const isContainer = (item: DriveItem) =>
+ item.kind === "FOLDER" || item.kind === "APP_LIBRARY";
+
+export const driveName = (item: DriveItem) =>
+ item.extension && !isContainer(item) ? `${item.name}.${item.extension}` : item.name;
+
export function messageOf(e: unknown): string {
if (typeof e === "string") return e;
if (e instanceof Error) return e.message;
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
new file mode 100644
index 0000000..f2ac643
--- /dev/null
+++ b/src/screens/DriveView.tsx
@@ -0,0 +1,141 @@
+import { useCallback, useEffect, useState } from "react";
+import {
+ api,
+ driveName,
+ isContainer,
+ messageOf,
+ DRIVE_ROOT,
+ type DriveItem,
+} from "../lib/ipc";
+
+const KB = 1024;
+
+function fileSize(bytes: number | null): string {
+ if (bytes === null) return "";
+ if (bytes < KB) return `${bytes} B`;
+ const units = ["KB", "MB", "GB", "TB"];
+ let value = bytes / KB;
+ let unit = 0;
+ while (value >= KB && unit < units.length - 1) {
+ value /= KB;
+ unit += 1;
+ }
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
+}
+
+const modified = (seconds: number | null) =>
+ seconds === null
+ ? ""
+ : new Date(seconds * 1000).toLocaleDateString(undefined, {
+ day: "numeric",
+ month: "short",
+ year: "numeric",
+ });
+
+/** A folder glyph for containers, and the extension for files. */
+function badge(item: DriveItem): string {
+ if (item.kind === "APP_LIBRARY") return "APP";
+ if (item.kind === "FOLDER") return "▸";
+ return (item.extension || "file").toUpperCase().slice(0, 4);
+}
+
+type Crumb = { id: string; name: string };
+
+export function DriveView() {
+ const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);
+ const [items, setItems] = useState<DriveItem[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const here = trail[trail.length - 1];
+
+ const open = useCallback(async (folderId: string) => {
+ setLoading(true);
+ setError(null);
+ try {
+ // Show what is stored first, then fetch — a folder visited before opens instantly.
+ const cached = await api.driveChildren(folderId);
+ if (Array.isArray(cached) && cached.length > 0) setItems(cached);
+ await api.driveSyncFolder(folderId);
+ const fresh = await api.driveChildren(folderId);
+ setItems(Array.isArray(fresh) ? fresh : []);
+ } catch (e) {
+ // Whatever was stored stays on screen; a failed fetch should not empty the folder.
+ setError(messageOf(e));
+ } finally {
+ setLoading(false);
+ setLoaded(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ void open(here.id);
+ }, [open, here.id]);
+
+ function enter(item: DriveItem) {
+ if (!isContainer(item)) return;
+ setTrail((t) => [...t, { id: item.drivewsid, name: driveName(item) }]);
+ }
+
+ return (
+ <div className="drive">
+ <header className="cal-bar">
+ <nav className="crumbs" aria-label="Folder path">
+ {trail.map((crumb, i) => (
+ <span key={crumb.id}>
+ {i > 0 && <span className="crumb-sep" aria-hidden="true">›</span>}
+ <button
+ className="crumb"
+ aria-current={i === trail.length - 1}
+ onClick={() => setTrail((t) => t.slice(0, i + 1))}
+ >
+ {crumb.name}
+ </button>
+ </span>
+ ))}
+ </nav>
+ <div className="cal-actions">
+ <button className="quiet" onClick={() => void open(here.id)} disabled={loading}>
+ {loading ? "Refreshing…" : "Refresh"}
+ </button>
+ </div>
+ </header>
+
+ {error && <p className="error" role="alert">{error}</p>}
+
+ <ul className="drive-rows">
+ {items.map((item) => {
+ const container = isContainer(item);
+ return (
+ <li key={item.drivewsid}>
+ <button
+ className={`drive-row${container ? " is-folder" : ""}`}
+ onClick={() => enter(item)}
+ // A file cannot be opened yet, so it must not look as though it can.
+ disabled={!container}
+ >
+ <span className={`drive-badge${container ? " folder" : ""}`} aria-hidden="true">
+ {badge(item)}
+ </span>
+ <span className="drive-name">{driveName(item)}</span>
+ <span className="drive-meta">
+ {container
+ ? item.childCount === null
+ ? ""
+ : `${item.childCount} item${item.childCount === 1 ? "" : "s"}`
+ : fileSize(item.size)}
+ </span>
+ <span className="drive-meta">{modified(item.modifiedAt ?? item.createdAt)}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+
+ {loaded && items.length === 0 && !error && (
+ <p className="cal-empty">This folder is empty.</p>
+ )}
+ </div>
+ );
+}
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index 07d1c42..1ed1517 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -4,6 +4,7 @@ import { CalendarView } from "./CalendarView";
import { RemindersView } from "./RemindersView";
import { NotesView } from "./NotesView";
import { ContactsView } from "./ContactsView";
+import { DriveView } from "./DriveView";
const NAMES: Record<string, string> = {
photos: "Photos",
@@ -43,7 +44,7 @@ const NAMES: Record<string, string> = {
/** Services with a real screen behind them. Opening on one of these beats opening on a
* placeholder, so selection prefers them. */
-const BUILT = new Set(["calendar", "reminders", "notes", "contacts"]);
+const BUILT = new Set(["calendar", "reminders", "notes", "contacts", "drivews"]);
/** What a person actually came for, in the order they'd look for it. */
const PRIMARY = [
@@ -159,6 +160,8 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
<NotesView />
) : selected === "contacts" ? (
<ContactsView />
+ ) : selected === "drivews" ? (
+ <DriveView />
) : (
<>
<div className="toolbar">
diff --git a/src/styles/app.css b/src/styles/app.css
index 9c8ad99..f14b9df 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -901,3 +901,69 @@
.contact-notes { margin-top: 20px; max-width: 60ch; color: var(--text-2); white-space: pre-wrap; }
.content:has(.contacts) { display: flex; flex-direction: column; overflow: hidden; }
+
+/* ---- iCloud Drive ---------------------------------------------------------------
+ A file browser: a path you can walk back along, then rows of what is here. */
+
+.drive { display: flex; flex-direction: column; height: 100%; min-height: 0; }
+
+.crumbs { display: flex; align-items: center; flex-wrap: wrap; gap: 2px; min-width: 0; }
+
+.crumb {
+ border: 0;
+ background: none;
+ color: var(--text-2);
+ font: inherit;
+ font-size: var(--t-15);
+ padding: 2px 5px;
+ border-radius: var(--r-field);
+ cursor: pointer;
+}
+
+.crumb:hover { background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--text); }
+.crumb[aria-current="true"] { color: var(--text); font-weight: 600; }
+.crumb:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }
+.crumb-sep { color: var(--text-3); padding: 0 1px; }
+
+.drive-rows { list-style: none; margin: 8px 0 0; padding: 0; overflow-y: auto; min-height: 0; }
+
+.drive-row {
+ display: grid;
+ grid-template-columns: 40px 1fr 90px 110px;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ border: 0;
+ background: none;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ text-align: left;
+ padding: 8px 10px;
+ border-radius: var(--r-field);
+ border-bottom: 1px solid var(--separator);
+ cursor: default;
+}
+
+.drive-row.is-folder { cursor: pointer; }
+.drive-row.is-folder:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
+.drive-row:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }
+
+.drive-badge {
+ display: grid;
+ place-items: center;
+ height: 22px;
+ border-radius: 5px;
+ background: color-mix(in srgb, var(--text) 10%, transparent);
+ color: var(--text-2);
+ font-size: 9px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+}
+
+.drive-badge.folder { background: var(--gold-tint); color: var(--gold-strong); font-size: var(--t-13); }
+
+.drive-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.drive-meta { color: var(--text-2); font-size: var(--t-11); font-variant-numeric: tabular-nums; }
+
+.content:has(.drive) { display: flex; flex-direction: column; overflow: hidden; }