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: Apple's own thumbnails in Grid, List and Get Info, verified live — download/batch's thumbnail_token, cached on disk by item and version; files without one keep their icon
Yashwanth Kamireddi12c0bdd559e9
diff --git a/.uiverify/drive-sort.mjs b/.uiverify/drive-sort.mjsindex 0362624..f7a4501 100644--- a/.uiverify/drive-sort.mjs+++ b/.uiverify/drive-sort.mjs@@ -56,6 +56,8 @@ await page.getByRole("option", { name: "Grid" }).click();await page.waitForTimeout(200);const tops = async () => page.evaluate(() => [...document.querySelectorAll(".drive-rows .drive-row")].map((r) => Math.round(r.getBoundingClientRect().top)));ok(new Set((await tops()).slice(0, 3)).size === 1, "Grid sets items side by side");+ok((await page.locator(".drive-row", { hasText: "Semester Plan" }).locator("img.drive-thumb").count()) === 1,+ "a file Apple has a picture of shows it, as icloud.com's grid does");await page.reload({ waitUntil: "networkidle" });await openScreen(page, "iCloud Drive");await page.waitForTimeout(400);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex b4a4b6a..803e02e 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -188,6 +188,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "contact_save": (window.__contactSaves ??= []).push(args); return "C-new";case "contact_delete": return null;case "contacts_list": return !contactsFixture ? [] : contactList;+ case "drive_thumbnails": return driveFixture ? { "FILE::d": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='60'><rect width='80' height='60' fill='%23eee'/></svg>" } : {};case "drive_duplicate": (window.__dups ??= []).push(args.drivewsid); return null;case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };case "drive_children": return !driveFixture ? [] : driveItems;diff --git a/Cargo.lock b/Cargo.lockindex d108e0d..317732a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3224,6 +3224,7 @@ name = "quince-app"version = "0.1.0"dependencies = ["anyhow",+ "base64 0.22.1","futures-util","jiff","notify-rust",diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rsindex 89aeaf6..34356ac 100644--- a/crates/quince-icloud/src/drive.rs+++ b/crates/quince-icloud/src/drive.rs@@ -466,6 +466,73 @@ pub async fn duplicate(Ok(())}+/// Apple's own thumbnails for the files in one folder, as `(drivewsid, image bytes)`.+///+/// Measured on a real account: `POST {docws}/ws/com.apple.CloudDocs/download/batch` with+/// `[{document_id}]` answers each file with a `data_token`, and — for the kinds Apple renders+/// itself, Office and iWork documents among them — a `thumbnail_token.url` to fetch as-is.+/// PDFs come back without one; those keep their icon. One batch for the folder, then each+/// image; a file whose thumbnail fails is simply left out.+pub async fn thumbnails(+ http: &reqwest::Client,+ docws_root: &str,+ params: Vec<(String, String)>,+ files: &[DriveItem],+) -> Result<Vec<(String, Vec<u8>)>> {+ let wanted: Vec<(&DriveItem, &str)> = files+ .iter()+ .filter(|f| f.kind == "FILE")+ .map(|f| (f, docwsid_of(&f.drivewsid)))+ .collect();+ if wanted.is_empty() {+ return Ok(Vec::new());+ }+ let body: Vec<Value> = wanted+ .iter()+ .map(|(_, d)| json!({ "document_id": d }))+ .collect();+ let url = format!(+ "{}/ws/com.apple.CloudDocs/download/batch",+ docws_root.trim_end_matches('/')+ );+ let response = http.post(url).query(¶ms).json(&body).send().await?;+ if response.status().as_u16() == 450 {+ return Err(Error::ReauthRequired);+ }+ if !response.status().is_success() {+ return Err(Error::Protocol(format!(+ "thumbnails returned {}",+ response.status()+ )));+ }+ let answer: Value = response+ .json()+ .await+ .map_err(|e| Error::Protocol(format!("thumbnails: {e}")))?;+ let mut out = Vec::new();+ for entry in answer.as_array().into_iter().flatten() {+ let (Some(doc), Some(thumb)) = (+ entry.get("document_id").and_then(Value::as_str),+ entry+ .pointer("/thumbnail_token/url")+ .and_then(Value::as_str),+ ) else {+ continue;+ };+ let Some((item, _)) = wanted.iter().find(|(_, d)| d.eq_ignore_ascii_case(doc)) else {+ continue;+ };+ if let Ok(r) = http.get(thumb).send().await {+ if r.status().is_success() {+ if let Ok(bytes) = r.bytes().await {+ out.push((item.drivewsid.clone(), bytes.to_vec()));+ }+ }+ }+ }+ Ok(out)+}+/// Drive's Recently Deleted, as icloud.com lists it: a folder Apple names `TRASH_ROOT`.pub const TRASH: &str = "TRASH_ROOT";diff --git a/probe/examples/drive_thumbs.rs b/probe/examples/drive_thumbs.rsnew file mode 100644index 0000000..bca42fb--- /dev/null+++ b/probe/examples/drive_thumbs.rs@@ -0,0 +1,21 @@+//! Live, read-only: Apple's thumbnails for the files in Downloads, through Quince's own call.+use anyhow::{anyhow, Result};+#[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 drivews = client.session().service_url("drivews").ok_or_else(|| anyhow!("no drivews"))?;+ let docws = client.session().service_url("docws").ok_or_else(|| anyhow!("no docws"))?;+ let (http, p) = (client.http().clone(), client.service_params());+ let mut lib = quince_core::Library::open(&std::env::temp_dir().join(format!("qth-{}", uuid::Uuid::new_v4())))?;+ quince_icloud::drive::sync_folder(&http, &drivews, p.clone(), &mut lib, quince_core::drive::ROOT).await?;+ let downloads = lib.drive_children(quince_core::drive::ROOT)?.into_iter().find(|i| i.name == "Downloads").ok_or_else(|| anyhow!("no Downloads"))?;+ quince_icloud::drive::sync_folder(&http, &drivews, p.clone(), &mut lib, &downloads.drivewsid).await?;+ let files = lib.drive_children(&downloads.drivewsid)?;+ for (id, bytes) in quince_icloud::drive::thumbnails(&http, &docws, p, &files).await? {+ let name = files.iter().find(|f| f.drivewsid == id).map(|f| f.display_name()).unwrap_or_default();+ println!("{name}: {} bytes, starts {:02x?}", bytes.len(), &bytes[..4.min(bytes.len())]);+ }+ Ok(())+}diff --git a/probe/examples/drive_urls.rs b/probe/examples/drive_urls.rsnew file mode 100644index 0000000..04f288d--- /dev/null+++ b/probe/examples/drive_urls.rs@@ -0,0 +1,94 @@+//! Live, read-only: the `urls` Drive's listing carries for files in a folder.+use anyhow::{anyhow, Result};+#[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 drivews = client+ .session()+ .service_url("drivews")+ .ok_or_else(|| anyhow!("no drivews"))?;+ let http = client.http().clone();+ let p = client.service_params();+ let root: serde_json::Value = http+ .post(format!(+ "{}/retrieveItemDetailsInFolders",+ drivews.trim_end_matches('/')+ ))+ .query(&p)+ .json(&serde_json::json!([{ "drivewsid": quince_core::drive::ROOT, "partialData": false }]))+ .send()+ .await?+ .json()+ .await?;+ let downloads = root[0]["items"]+ .as_array()+ .unwrap()+ .iter()+ .find(|i| i["name"] == "Downloads")+ .cloned()+ .unwrap();+ let folder: serde_json::Value = http+ .post(format!(+ "{}/retrieveItemDetailsInFolders",+ drivews.trim_end_matches('/')+ ))+ .query(&p)+ .json(&serde_json::json!([{ "drivewsid": downloads["drivewsid"], "partialData": false }]))+ .send()+ .await?+ .json()+ .await?;+ let docws = client+ .session()+ .service_url("docws")+ .ok_or_else(|| anyhow!("no docws"))?;+ let ids: Vec<_> = folder[0]["items"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|i| i["type"] == "FILE")+ .map(|i| serde_json::json!({ "document_id": i["docwsid"] }))+ .collect();+ let r = http+ .post(format!(+ "{}/ws/com.apple.CloudDocs/download/batch",+ docws.trim_end_matches('/')+ ))+ .query(&p)+ .json(&ids)+ .send()+ .await?;+ println!("batch {}", r.status());+ let t = r.text().await?;+ let v: serde_json::Value = serde_json::from_str(&t)?;+ for d in v.as_array().unwrap() {+ println!(+ "{} thumb={} keys={:?}",+ d["document_id"],+ d.get("thumbnail_token")+ .map(|x| x["url"]+ .as_str()+ .unwrap_or("")+ .chars()+ .take(80)+ .collect::<String>())+ .unwrap_or("NONE".into()),+ d.as_object().unwrap().keys().collect::<Vec<_>>()+ );+ }+ for i in folder[0]["items"].as_array().unwrap().iter().take(0) {+ let keys: Vec<_> = i.as_object().unwrap().keys().cloned().collect();+ println!(+ "{} {}: keys={:?}\n urls={}",+ i["name"],+ i["extension"],+ keys,+ i["urls"].to_string().chars().take(300).collect::<String>()+ );+ }+ Ok(())+}diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex bf23704..47dbde2 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -22,6 +22,7 @@ tokio = { workspace = true }anyhow.workspace = truejiff = "0.2.37"uuid.workspace = true+base64 = "0.22"tauri-plugin-dialog = "2.7.3"notify-rust = "4"zbus = "5"diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex f25dffe..8f61b8a 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -1751,6 +1751,105 @@ async fn drive_duplicate(resync_drive_folder(&http, &drivews, params, &data, parent).await}+/// Apple's thumbnails for one folder's files, as `data:` URLs keyed by drivewsid.+///+/// Kept on disk beside the library, named by item and version, so a folder opened again+/// shows its pictures at once and only a changed file is fetched anew.+#[tauri::command]+async fn drive_thumbnails(+ folder_id: String,+ app: tauri::AppHandle,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<std::collections::HashMap<String, String>> {+ use base64::Engine;+ let files = {+ let library = data.0.lock().await;+ library+ .drive_children(&folder_id)+ .map_err(|e| e.to_string())?+ };+ let cache = state_dir(&app).join("thumbnails");+ std::fs::create_dir_all(&cache).ok();+ let key = |f: &quince_core::drive::DriveItem| {+ let safe = |s: &str| {+ s.chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })+ .collect::<String>()+ };+ cache.join(format!(+ "{}-{}",+ safe(&f.drivewsid),+ safe(f.etag.as_deref().unwrap_or(""))+ ))+ };+ let mut out = std::collections::HashMap::new();+ let mut missing = Vec::new();+ for f in files.iter().filter(|f| f.kind == "FILE") {+ match std::fs::read(key(f)) {+ Ok(bytes) if bytes.is_empty() => {} // known to have none+ Ok(bytes) => {+ out.insert(+ f.drivewsid.clone(),+ data_url(+ &bytes,+ &base64::engine::general_purpose::STANDARD.encode(&bytes),+ ),+ );+ }+ Err(_) => missing.push(f.clone()),+ }+ }+ if !missing.is_empty() {+ let (http, docws, params) = {+ let client = auth.client.lock().await;+ (+ client.http().clone(),+ client+ .session()+ .service_url("docws")+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?,+ client.service_params(),+ )+ };+ let got = quince_icloud::drive::thumbnails(&http, &docws, params, &missing)+ .await+ .map_err(|e| e.to_string())?;+ for f in &missing {+ let bytes = got+ .iter()+ .find(|(id, _)| id == &f.drivewsid)+ .map(|(_, b)| b.clone());+ // An empty file records "Apple has no picture for this version", so it is not asked again.+ std::fs::write(key(f), bytes.as_deref().unwrap_or(&[])).ok();+ if let Some(bytes) = bytes {+ out.insert(+ f.drivewsid.clone(),+ data_url(+ &bytes,+ &base64::engine::general_purpose::STANDARD.encode(&bytes),+ ),+ );+ }+ }+ }+ Ok(out)+}++/// An image as a `data:` URL, its type read from its first bytes.+fn data_url(bytes: &[u8], b64: &str) -> String {+ let mime = if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {+ "image/png"+ } else if bytes.starts_with(b"RIFF") {+ "image/webp"+ } else if bytes.starts_with(b"GIF8") {+ "image/gif"+ } else {+ "image/jpeg"+ };+ format!("data:{mime};base64,{b64}")+}+/// How much iCloud storage is used and how much there is, for "X GB available".#[tauri::command]async fn storage_info(auth: State<'_, Auth>) -> UiResult<quince_icloud::drive::Storage> {@@ -2239,6 +2338,7 @@ fn main() {drive_trash,storage_info,drive_duplicate,+ drive_thumbnails,drive_put_back,drive_delete_forever,drive_move,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex a2f962c..9dac038 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -167,6 +167,7 @@ export const api = {invoke<void>("drive_rename", { drivewsid, name }),driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),driveTrash: () => invoke<DriveItem[]>("drive_trash"),+ driveThumbnails: (folderId: string) => invoke<Record<string, string>>("drive_thumbnails", { folderId }),driveDuplicate: (drivewsid: string) => invoke<void>("drive_duplicate", { drivewsid }),storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex 1191526..be88532 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -174,7 +174,7 @@ function kindName(item: DriveItem) {}/** File Info, as icloud.com shows it: the mark, the name, then what it is and where. */-function InfoSheet({ item, where, onClose }: { item: DriveItem; where: string; onClose: () => void }) {+function InfoSheet({ item, where, thumb, onClose }: { item: DriveItem; where: string; thumb?: string; onClose: () => void }) {const done = useRef<HTMLButtonElement | null>(null);useEffect(() => {const id = window.setTimeout(() => done.current?.focus(), 0);@@ -199,7 +199,9 @@ function InfoSheet({ item, where, onClose }: { item: DriveItem; where: string; o<h2>{isContainer(item) ? "Folder Info" : "File Info"}</h2><button ref={done} className="quiet info-done" onClick={onClose}>Done</button></header>- <div className="info-mark" aria-hidden="true"><FileGlyph kind={item.kind} extension={item.extension} /></div>+ <div className={`info-mark${thumb ? " has-thumb" : ""}`} aria-hidden="true">+ {thumb ? <img src={thumb} alt="" draggable={false} /> : <FileGlyph kind={item.kind} extension={item.extension} />}+ </div><p className="info-name">{driveName(item)}</p><dl className="info-rows">{rows.map(([k, v]) => (@@ -234,6 +236,8 @@ export function DriveView() {const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "iCloud Drive" }]);const [items, setItems] = useState<DriveItem[]>([]);const [inTrash, setInTrash] = useState(false);+ /** Apple's own pictures of this folder's files, where it has them; the rest keep icons. */+ const [thumbs, setThumbs] = useState<Record<string, string>>({});/** What is free, as icloud.com says it under a folder's name: "5.18 GB available". */const [available, setAvailable] = useState<string | null>(null);useEffect(() => {@@ -322,11 +326,17 @@ export function DriveView() {// while a slow fetch ran meant a click landed on a row from the level just left, and// Drive seemed to jump into folders nobody opened.setItems(Array.isArray(cached) ? cached : []);+ setThumbs({});await api.driveSyncFolder(folderId);if (token !== openToken.current) return;const fresh = await api.driveChildren(folderId);if (token !== openToken.current) return;setItems(Array.isArray(fresh) ? fresh : []);+ // Pictures last, and never in the way: a folder is usable before they arrive.+ api.driveThumbnails(folderId).then(+ (t) => { if (token === openToken.current && t) setThumbs(t); },+ () => {},+ );} catch (e) {if (token === openToken.current) setError(messageOf(e));} finally {@@ -855,7 +865,7 @@ export function DriveView() {{busy ? (<span className="drive-spinner" />) : (- <FileGlyph kind={item.kind} extension={item.extension} />+ thumbs[item.drivewsid] ? <img className="drive-thumb" src={thumbs[item.drivewsid]} alt="" draggable={false} /> : <FileGlyph kind={item.kind} extension={item.extension} />)}</span><span className="drive-name">{driveName(item)}</span>@@ -924,7 +934,7 @@ export function DriveView() {)}{info && (- <InfoSheet item={info} where={trail.map((c) => c.name).join(" › ")} onClose={() => setInfo(null)} />+ <InfoSheet item={info} where={trail.map((c) => c.name).join(" › ")} thumb={thumbs[info.drivewsid]} onClose={() => setInfo(null)} />)}<UploadTray uploads={[...uploads.values()]} onDismiss={() => setUploads(new Map())} />diff --git a/src/styles/app.css b/src/styles/app.cssindex 89fad68..afe9924 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1763,3 +1763,10 @@.drive-row.is-selected .drive-name, .drive-row.is-selected .drive-meta { color: #fff; }.drive-rows.is-grid .drive-row.is-selected { background: color-mix(in srgb, var(--sys-blue, #0a84ff) 28%, transparent); box-shadow: inset 0 0 0 2px var(--sys-blue, #0a84ff); }.drive-rows.is-grid .drive-row.is-selected .drive-name { color: var(--text); }+/* Apple's own picture of a file: small in a list, the tile's face in Grid, as icloud.com. */+.drive-thumb { width: 22px; height: 22px; object-fit: contain; border-radius: 3px; box-shadow: 0 0 0 0.5px rgba(0,0,0,0.25); background: #fff; }+.drive-rows.is-grid .drive-badge:has(.drive-thumb) { transform: none; height: 76px; }+.drive-rows.is-grid .drive-thumb { width: 88px; height: 72px; border-radius: 6px; box-shadow: 0 1px 4px rgba(0,0,0,0.35), 0 0 0 0.5px rgba(0,0,0,0.2); }+.info-mark.has-thumb { background: none; width: auto; height: auto; }+.info-mark.has-thumb > * { transform: none; }+.info-mark.has-thumb img { max-width: 160px; max-height: 140px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.35); }