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.

Drive: '4 items, 5.19 GB available' under the folder's name, from Apple's storageUsageInfo — measured live, counted in thousands as icloud.com counts

Yashwanth Kamireddia7c28024956c
diff --git a/.uiverify/drive-info.mjs b/.uiverify/drive-info.mjs
index 70e91b1..a15d472 100644
--- a/.uiverify/drive-info.mjs
+++ b/.uiverify/drive-info.mjs
@@ -40,5 +40,8 @@ ok(downloads === 0 && (await page.locator(".drive-row.is-selected", { hasText: "
await page.locator(".drive-row-hit", { hasText: "Downloads" }).dblclick();
await page.waitForTimeout(300);
ok((await page.locator(".crumb", { hasText: "Downloads" }).count()) === 1, "a double-click opens the folder");
+// Under the folder's name, as icloud.com: its count and what is free, in thousands.
+const status = await page.locator(".drive-count").innerText();
+ok(status === "4 items, 5.19 GB available", `the folder's status line [${status}]`);
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 8561adb..84896ea 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -188,6 +188,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "contact_save": (window.__contactSaves ??= []).push(args); return "C-new";
case "contact_delete": return null;
case "contacts_list": return !contactsFixture ? [] : contactList;
+ case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };
case "drive_children": return !driveFixture ? [] : driveItems;
case "drive_trash": return !driveFixture ? [] : (window.__trash ??= [
{ drivewsid: "FILE::t1", parentId: null, name: "Old notes", extension: "pdf", kind: "FILE",
diff --git a/crates/quince-auth/src/lib.rs b/crates/quince-auth/src/lib.rs
index 0721d93..afab4fc 100644
--- a/crates/quince-auth/src/lib.rs
+++ b/crates/quince-auth/src/lib.rs
@@ -926,6 +926,12 @@ impl Client {
params
}
+ /// The account service's root (`…/setup/ws/1`), where storage use is asked for.
+ #[must_use]
+ pub fn setup_url(&self) -> &str {
+ &self.endpoints.setup
+ }
+
/// Shared HTTP client, for the service crates that ride this session.
pub fn http(&self) -> &HttpClient {
&self.http
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index d9f4319..66d49c0 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -1886,3 +1886,76 @@ mod download_zone_tests {
assert!(ordinary.ends_with("com.apple.CloudDocs"), "{ordinary}");
}
}
+
+/// The account's iCloud storage, as icloud.com's "X GB available" reads it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Storage {
+ pub used_bytes: u64,
+ pub total_bytes: u64,
+}
+
+/// `POST {setup}/storageUsageInfo`, no body — what icloud.com's shell asks. Measured on a real
+/// account: `storageUsageInfo.{usedStorageInBytes,totalStorageInBytes}`.
+pub async fn storage(
+ http: &reqwest::Client,
+ setup_root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Storage> {
+ let url = format!("{}/storageUsageInfo", setup_root.trim_end_matches('/'));
+ let response = http.post(url).query(&params).send().await?;
+ let status = response.status();
+ if status.as_u16() == 450 || status.as_u16() == 421 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ return Err(Error::Protocol(format!("storage returned {status}")));
+ }
+ let body: Value = response
+ .json()
+ .await
+ .map_err(|e| Error::Protocol(format!("storage: {e}")))?;
+ let n = |k: &str| {
+ body.pointer(&format!("/storageUsageInfo/{k}"))
+ .and_then(Value::as_u64)
+ };
+ match (n("usedStorageInBytes"), n("totalStorageInBytes")) {
+ (Some(used_bytes), Some(total_bytes)) => Ok(Storage {
+ used_bytes,
+ total_bytes,
+ }),
+ _ => Err(Error::Protocol("storage: no usage in the answer".into())),
+ }
+}
+
+#[cfg(test)]
+mod storage_tests {
+ use super::*;
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ /// The shape measured on a real account.
+ #[tokio::test]
+ async fn storage_is_read_from_apples_answer() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/storageUsageInfo"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "storageUsageInfo": { "compStorageInBytes": 0, "usedStorageInBytes": 182_196_857_u64,
+ "totalStorageInBytes": 5_368_709_120_u64, "commerceStorageInBytes": 0 },
+ "quotaStatus": { "overQuota": false }
+ })))
+ .mount(&server)
+ .await;
+ let got = storage(&reqwest::Client::new(), &server.uri(), vec![])
+ .await
+ .unwrap();
+ assert_eq!(
+ got,
+ Storage {
+ used_bytes: 182_196_857,
+ total_bytes: 5_368_709_120
+ }
+ );
+ }
+}
diff --git a/probe/examples/drive_trash_list.rs b/probe/examples/drive_trash_list.rs
index 8d40c31..525ee7c 100644
--- a/probe/examples/drive_trash_list.rs
+++ b/probe/examples/drive_trash_list.rs
@@ -4,12 +4,24 @@ use anyhow::{anyhow, Result};
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 root = client.session().service_url("drivews").ok_or_else(|| anyhow!("no drivews"))?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("drivews")
+ .ok_or_else(|| anyhow!("no drivews"))?;
let items = quince_icloud::drive::trash(client.http(), &root, client.service_params()).await?;
println!("{} in Recently Deleted", items.len());
for i in items.iter().take(5) {
- println!(" {} | {} | {:?} | etag={:?} parent={:?}", i.drivewsid, i.display_name(), i.size, i.etag, i.parent_id);
+ println!(
+ " {} | {} | {:?} | etag={:?} parent={:?}",
+ i.drivewsid,
+ i.display_name(),
+ i.size,
+ i.etag,
+ i.parent_id
+ );
}
Ok(())
}
diff --git a/probe/examples/drive_trash_roundtrip.rs b/probe/examples/drive_trash_roundtrip.rs
index c32a4ee..9059d71 100644
--- a/probe/examples/drive_trash_roundtrip.rs
+++ b/probe/examples/drive_trash_roundtrip.rs
@@ -5,29 +5,74 @@ use anyhow::{anyhow, Result};
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"))?;
+ 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 = client.http().clone();
let p = client.service_params();
let tmp = std::env::temp_dir().join("quince-trash-test.txt");
std::fs::write(&tmp, b"Quince trash round trip. Safe to delete.")?;
- let item = quince_icloud::drive::upload(&http, &docws, &drivews, p.clone(), quince_core::drive::ROOT, &tmp,
- std::sync::Arc::new(|_, _| {})).await?;
+ let item = quince_icloud::drive::upload(
+ &http,
+ &docws,
+ &drivews,
+ p.clone(),
+ quince_core::drive::ROOT,
+ &tmp,
+ std::sync::Arc::new(|_, _| {}),
+ )
+ .await?;
println!("uploaded {}", item.drivewsid);
- let in_trash = |id: String| { let (h, d, p) = (http.clone(), drivews.clone(), p.clone());
- async move { Ok::<bool, anyhow::Error>(quince_icloud::drive::trash(&h, &d, p).await?.iter().any(|i| i.drivewsid == id)) } };
+ let in_trash = |id: String| {
+ let (h, d, p) = (http.clone(), drivews.clone(), p.clone());
+ async move {
+ Ok::<bool, anyhow::Error>(
+ quince_icloud::drive::trash(&h, &d, p)
+ .await?
+ .iter()
+ .any(|i| i.drivewsid == id),
+ )
+ }
+ };
quince_icloud::drive::delete(&http, &drivews, p.clone(), &item).await?;
- println!("trashed; in trash = {}", in_trash(item.drivewsid.clone()).await?);
+ println!(
+ "trashed; in trash = {}",
+ in_trash(item.drivewsid.clone()).await?
+ );
quince_icloud::drive::put_back(&http, &drivews, p.clone(), &item).await?;
- println!("recovered; in trash = {}", in_trash(item.drivewsid.clone()).await?);
+ println!(
+ "recovered; in trash = {}",
+ in_trash(item.drivewsid.clone()).await?
+ );
// Re-read its etag where it landed, as Quince would after a refresh.
- let mut lib = quince_core::Library::open(&std::env::temp_dir().join(format!("qtt-{}", uuid::Uuid::new_v4())))?;
- quince_icloud::drive::sync_folder(&http, &drivews, p.clone(), &mut lib, quince_core::drive::ROOT).await?;
- let back = lib.drive_item(&item.drivewsid)?.ok_or_else(|| anyhow!("not back in the root"))?;
+ let mut lib = quince_core::Library::open(
+ &std::env::temp_dir().join(format!("qtt-{}", uuid::Uuid::new_v4())),
+ )?;
+ quince_icloud::drive::sync_folder(
+ &http,
+ &drivews,
+ p.clone(),
+ &mut lib,
+ quince_core::drive::ROOT,
+ )
+ .await?;
+ let back = lib
+ .drive_item(&item.drivewsid)?
+ .ok_or_else(|| anyhow!("not back in the root"))?;
println!("back in the root: {}", back.display_name());
quince_icloud::drive::delete(&http, &drivews, p.clone(), &back).await?;
quince_icloud::drive::delete_forever(&http, &drivews, p.clone(), &back).await?;
- println!("deleted for good; in trash = {}", in_trash(item.drivewsid.clone()).await?);
+ println!(
+ "deleted for good; in trash = {}",
+ in_trash(item.drivewsid.clone()).await?
+ );
Ok(())
}
diff --git a/probe/examples/storage_info.rs b/probe/examples/storage_info.rs
new file mode 100644
index 0000000..a86cb3d
--- /dev/null
+++ b/probe/examples/storage_info.rs
@@ -0,0 +1,20 @@
+//! Live, read-only: the account's storage, as icloud.com's "X GB available" reads it.
+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 r = client
+ .http()
+ .post("https://setup.icloud.com/setup/ws/1/storageUsageInfo")
+ .query(&client.service_params())
+ .send()
+ .await?;
+ println!("{}", r.status());
+ let t = r.text().await?;
+ println!("{}", &t.chars().take(900).collect::<String>());
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 828c22e..c2da490 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1713,6 +1713,22 @@ async fn drive_delete(
resync_drive_folder(&http, &root, params, &data, parent).await
}
+/// 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> {
+ let (http, setup, params) = {
+ let client = auth.client.lock().await;
+ (
+ client.http().clone(),
+ client.setup_url().to_string(),
+ client.service_params(),
+ )
+ };
+ quince_icloud::drive::storage(&http, &setup, params)
+ .await
+ .map_err(|e| e.to_string())
+}
+
/// Drive's Recently Deleted, read live: Apple decides how long things stay there, so a copy
/// kept here would only ever be a wrong count.
#[tauri::command]
@@ -2183,6 +2199,7 @@ fn main() {
drive_rename,
drive_delete,
drive_trash,
+ storage_info,
drive_put_back,
drive_delete_forever,
drive_move,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 5698aa1..a2befed 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"),
+ storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),
drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),
driveDeleteForever: (item: DriveItem) => invoke<void>("drive_delete_forever", { item }),
driveMove: (drivewsid: string, destinationId: string) =>
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 5001dec..20c1d4f 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -211,12 +211,37 @@ function InfoSheet({ item, where, onClose }: { item: DriveItem; where: string; o
);
}
+/**
+ * Sizes as icloud.com writes storage: in thousands, not 1024s — so a 5 GB plan reads "5 GB"
+ * — kB with no decimals, MB with one, GB and up with two.
+ */
+function decimalSize(bytes: number): string {
+ const units = ["bytes", "kB", "MB", "GB", "TB", "PB"];
+ const places = [0, 0, 1, 2, 2, 2];
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1000 && unit < units.length - 1) {
+ value /= 1000;
+ unit += 1;
+ }
+ const p = 10 ** places[unit];
+ return `${(Math.round(value * p) / p).toLocaleString()} ${units[unit]}`;
+}
+
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 [inTrash, setInTrash] = useState(false);
+ /** 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(() => {
+ api.storageInfo().then(
+ ({ usedBytes, totalBytes }) => setAvailable(decimalSize(Math.max(0, totalBytes - usedBytes))),
+ () => setAvailable(null),
+ );
+ }, []);
/** icloud.com's "View as": Grid or List, remembered. */
const [grid, setGrid] = useState(() => {
try {
@@ -629,7 +654,7 @@ export function DriveView() {
<p className="drive-count" aria-live="polite">
{(() => {
const n = items.filter((x) => !gone.has(x.drivewsid)).length;
- return `${n} item${n === 1 ? "" : "s"}`;
+ return `${n} item${n === 1 ? "" : "s"}${available ? `, ${available} available` : ""}`;
})()}
</p>
)}