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 Recently Deleted: each item's Time Left and the folder it came from, from Apple's dateExpiration and restorePath; nearly gone marked — verified live

Yashwanth Kamireddicc0232ce6f6b
diff --git a/.uiverify/drive-trash.mjs b/.uiverify/drive-trash.mjs
index bffc37d..ae6093c 100644
--- a/.uiverify/drive-trash.mjs
+++ b/.uiverify/drive-trash.mjs
@@ -18,6 +18,9 @@ await page.waitForTimeout(300);
const names = () => page.locator(".drive-rows .drive-name").allInnerTexts();
ok(JSON.stringify(await names()) === JSON.stringify(["Old notes.pdf", "Wallpaper.jpg"]), `Recently Deleted lists what was deleted ${JSON.stringify(await names())}`);
+const notes = await page.locator("li", { hasText: "Old notes" }).innerText();
+ok(/21 days/.test(notes) && /From Downloads/.test(notes), `each shows its time left and where it came from [${notes.replace(/\s+/g, " ")}]`);
+ok((await page.locator("li", { hasText: "Wallpaper" }).locator(".is-soon").count()) === 1, "and one nearly gone is marked so");
await page.locator("li", { hasText: "Old notes" }).getByRole("button", { name: "Recover" }).click();
await page.waitForTimeout(100);
ok(!(await names()).includes("Old notes.pdf"), "Recover takes it off the list at once");
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index a616da2..96a0ae0 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -241,9 +241,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
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",
- size: 177000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t1" },
+ size: 177000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t1",
+ expiresAt: Math.floor(Date.now() / 1000) + 21 * 86400 - 60, restorePath: "Downloads/Old notes.pdf" },
{ drivewsid: "FILE::t2", parentId: null, name: "Wallpaper", extension: "jpg", kind: "FILE",
- size: 1500000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t2" },
+ size: 1500000, childCount: null, createdAt: 1786000000, modifiedAt: 1786000000, etag: "t2",
+ expiresAt: Math.floor(Date.now() / 1000) + 2 * 86400 - 60, restorePath: "Wallpaper.jpg" },
]).slice();
case "drive_put_back": case "drive_delete_forever":
window.__trash = (window.__trash ?? []).filter((i) => i.drivewsid !== args.item.drivewsid);
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 34356ac..08b779b 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -536,13 +536,83 @@ pub async fn thumbnails(
/// Drive's Recently Deleted, as icloud.com lists it: a folder Apple names `TRASH_ROOT`.
pub const TRASH: &str = "TRASH_ROOT";
+/// One item in Recently Deleted: when Apple will delete it for good, and where Recover
+/// puts it back — measured on a real account as `dateExpiration` and `restorePath`.
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TrashItem {
+ #[serde(flatten)]
+ pub item: DriveItem,
+ /// Unix seconds.
+ pub expires_at: Option<i64>,
+ pub restore_path: Option<String>,
+}
+
/// What is in Recently Deleted now. Read-only.
pub async fn trash(
http: &reqwest::Client,
root: &str,
params: Vec<(String, String)>,
) -> Result<Vec<DriveItem>> {
- folder_listing(http, root, &params, TRASH).await
+ Ok(trash_items(http, root, params)
+ .await?
+ .into_iter()
+ .map(|t| t.item)
+ .collect())
+}
+
+/// [`trash`], with each item's expiry and the folder it came from.
+pub async fn trash_items(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Vec<TrashItem>> {
+ let url = format!(
+ "{}/retrieveItemDetailsInFolders",
+ root.trim_end_matches('/')
+ );
+ let body = json!([{ "drivewsid": TRASH, "partialData": false }]);
+ let response = http.post(url).query(&params).json(&body).send().await?;
+ let status = response.status();
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ let text = response.text().await.unwrap_or_default();
+ 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 raw: Vec<&Value> = parsed
+ .pointer("/0/items")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().collect())
+ .unwrap_or_default();
+ Ok(parse_folder(&parsed)
+ .into_iter()
+ .map(|item| {
+ let found = raw.iter().find(|r| {
+ r.get("drivewsid").and_then(Value::as_str) == Some(item.drivewsid.as_str())
+ });
+ let expires_at = found
+ .and_then(|r| r.get("dateExpiration"))
+ .and_then(Value::as_str)
+ .and_then(|d| d.parse::<jiff::Timestamp>().ok())
+ .map(|t| t.as_second());
+ let restore_path = found
+ .and_then(|r| r.get("restorePath"))
+ .and_then(Value::as_str)
+ .map(ToString::to_string);
+ TrashItem {
+ item,
+ expires_at,
+ restore_path,
+ }
+ })
+ .collect())
}
/// Put an item back where it was deleted from (`putBackItemsFromTrash`), or delete it for
diff --git a/probe/examples/drive_trash_expiry.rs b/probe/examples/drive_trash_expiry.rs
new file mode 100644
index 0000000..befcf7d
--- /dev/null
+++ b/probe/examples/drive_trash_expiry.rs
@@ -0,0 +1,37 @@
+//! Live, read-only: the fields Drive's Recently Deleted carries per item.
+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 v: serde_json::Value = client
+ .http()
+ .post(format!(
+ "{}/retrieveItemDetailsInFolders",
+ drivews.trim_end_matches('/')
+ ))
+ .query(&client.service_params())
+ .json(&serde_json::json!([{ "drivewsid": "TRASH_ROOT", "partialData": false }]))
+ .send()
+ .await?
+ .json()
+ .await?;
+ if let Some(i) = v[0]["items"].as_array().and_then(|a| a.first()) {
+ println!(
+ "keys: {:?}",
+ i.as_object().map(|o| o.keys().collect::<Vec<_>>())
+ );
+ println!(
+ "dateExpiration={} dateChanged={} restorePath={}",
+ i["dateExpiration"], i["dateChanged"], i["restorePath"]
+ );
+ }
+ Ok(())
+}
diff --git a/probe/examples/drive_trash_list.rs b/probe/examples/drive_trash_list.rs
index 525ee7c..b959136 100644
--- a/probe/examples/drive_trash_list.rs
+++ b/probe/examples/drive_trash_list.rs
@@ -11,9 +11,19 @@ async fn main() -> Result<()> {
.session()
.service_url("drivews")
.ok_or_else(|| anyhow!("no drivews"))?;
+ let rich =
+ quince_icloud::drive::trash_items(client.http(), &root, client.service_params()).await?;
+ for t in rich.iter().take(3) {
+ println!(
+ " {} expires_at={:?} from={:?}",
+ t.item.display_name(),
+ t.expires_at,
+ t.restore_path
+ );
+ }
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) {
+ for i in items.iter().take(2) {
println!(
" {} | {} | {:?} | etag={:?} parent={:?}",
i.drivewsid,
diff --git a/probe/examples/reminder_triggers.rs b/probe/examples/reminder_triggers.rs
new file mode 100644
index 0000000..d593c85
--- /dev/null
+++ b/probe/examples/reminder_triggers.rs
@@ -0,0 +1,49 @@
+//! Live, read-only: the kinds of alarm trigger on the account, with one example of each.
+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 root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ let zc = quince_icloud::cloudkit::ZoneClient::new(
+ client.http(),
+ &root,
+ "com.apple.reminders",
+ client.service_params(),
+ );
+ let walk = zc.all_records("Reminders", None).await?;
+ let mut seen = std::collections::BTreeMap::new();
+ for r in walk
+ .records
+ .iter()
+ .filter(|r| r["recordType"] == "AlarmTrigger")
+ {
+ let kind = r["fields"]["Type"]["value"]
+ .as_str()
+ .unwrap_or("?")
+ .to_string();
+ seen.entry(kind).or_insert_with(|| {
+ r["fields"]
+ .to_string()
+ .chars()
+ .take(500)
+ .collect::<String>()
+ });
+ }
+ let n = walk
+ .records
+ .iter()
+ .filter(|r| r["recordType"] == "AlarmTrigger")
+ .count();
+ println!("{n} triggers");
+ for (k, v) in seen {
+ println!("{k}: {v}");
+ }
+ Ok(())
+}
diff --git a/probe/examples/reminders_reorder.rs b/probe/examples/reminders_reorder.rs
index e4b03af..385ac18 100644
--- a/probe/examples/reminders_reorder.rs
+++ b/probe/examples/reminders_reorder.rs
@@ -5,22 +5,43 @@ 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("ckdatabasews").ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
let (http, p) = (client.http().clone(), client.service_params());
use quince_icloud::reminders as r;
let list = r::create_list_cloudkit(&http, &root, p.clone(), "Quince order test").await?;
let a = r::create_cloudkit(&http, &root, p.clone(), &list, "A").await?;
let _b = r::create_cloudkit(&http, &root, p.clone(), &list, "B").await?;
let c = r::create_cloudkit(&http, &root, p.clone(), &list, "C").await?;
- let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.reminders", p.clone());
- let order = |v: serde_json::Value| v["fields"]["ReminderIDs"]["value"].as_str().unwrap_or("").to_string();
- println!("made: {}", order(zc.lookup_record("Reminders", &list).await?.unwrap()));
+ let zc =
+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.reminders", p.clone());
+ let order = |v: serde_json::Value| {
+ v["fields"]["ReminderIDs"]["value"]
+ .as_str()
+ .unwrap_or("")
+ .to_string()
+ };
+ println!(
+ "made: {}",
+ order(zc.lookup_record("Reminders", &list).await?.unwrap())
+ );
r::reorder_cloudkit(&http, &root, p.clone(), &list, &c, Some(&a)).await?;
let after = zc.lookup_record("Reminders", &list).await?.unwrap();
println!("moved: {}", order(after.clone()));
- let rtm: serde_json::Value = serde_json::from_str(after["fields"]["ResolutionTokenMap"]["value"].as_str().unwrap_or("{}"))?;
- println!("order token: {}", rtm["map"]["reminderIDsMergeableOrdering"]);
+ let rtm: serde_json::Value = serde_json::from_str(
+ after["fields"]["ResolutionTokenMap"]["value"]
+ .as_str()
+ .unwrap_or("{}"),
+ )?;
+ println!(
+ "order token: {}",
+ rtm["map"]["reminderIDsMergeableOrdering"]
+ );
r::delete_list_cloudkit(&http, &root, p, &list).await?;
println!("deleted");
Ok(())
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index d23571f..e5544a3 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2070,9 +2070,9 @@ async fn storage_info(auth: State<'_, Auth>) -> UiResult<quince_icloud::drive::S
/// 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]
-async fn drive_trash(auth: State<'_, Auth>) -> UiResult<Vec<quince_core::drive::DriveItem>> {
+async fn drive_trash(auth: State<'_, Auth>) -> UiResult<Vec<quince_icloud::drive::TrashItem>> {
let (http, root, params) = drive_context(&auth).await?;
- quince_icloud::drive::trash(&http, &root, params)
+ quince_icloud::drive::trash_items(&http, &root, params)
.await
.map_err(|e| e.to_string())
}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 994f65c..15cb260 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -180,7 +180,7 @@ export const api = {
driveRename: (drivewsid: string, name: string) =>
invoke<void>("drive_rename", { drivewsid, name }),
driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),
- driveTrash: () => invoke<DriveItem[]>("drive_trash"),
+ driveTrash: () => invoke<TrashItem[]>("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"),
@@ -457,6 +457,9 @@ export type DriveItem = {
etag: string | null;
};
+/** An item in Drive's Recently Deleted: when it goes for good, and where Recover puts it. */
+export type TrashItem = DriveItem & { expiresAt: number | null; restorePath: string | null };
+
export const DRIVE_ROOT = "FOLDER::com.apple.CloudDocs::root";
export const isContainer = (item: DriveItem) =>
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index a09bc0c..77aa7b4 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -12,6 +12,7 @@ import {
DRIVE_ROOT,
UPLOAD,
type DriveItem,
+ type TrashItem,
type UploadEvent,
} from "../lib/ipc";
import { ActionGlyph, FileGlyph } from "../components/FileGlyph";
@@ -80,7 +81,7 @@ const modified = (seconds: number | null) =>
* does, because nothing brings it back.
*/
function DriveTrash({ onClose }: { onClose: () => void }) {
- const [rows, setRows] = useState<DriveItem[] | null>(null);
+ const [rows, setRows] = useState<TrashItem[] | null>(null);
const [error, setError] = useState<string | null>(null);
const read = useCallback(async () => {
try {
@@ -94,7 +95,7 @@ function DriveTrash({ onClose }: { onClose: () => void }) {
void read();
}, [read]);
- const out = async (gone: DriveItem[], run: (i: DriveItem) => Promise<void>) => {
+ const out = async (gone: TrashItem[], run: (i: DriveItem) => Promise<void>) => {
const ids = new Set(gone.map((i) => i.drivewsid));
setRows((r) => (r ?? []).filter((i) => !ids.has(i.drivewsid)));
setError(null);
@@ -104,8 +105,8 @@ function DriveTrash({ onClose }: { onClose: () => void }) {
await read();
}
};
- const recover = (items: DriveItem[]) => out(items, (i) => api.drivePutBack(i));
- const destroy = (items: DriveItem[]) => {
+ const recover = (items: TrashItem[]) => out(items, (i) => api.drivePutBack(i));
+ const destroy = (items: TrashItem[]) => {
const what = items.length === 1 ? `\u201c${driveName(items[0])}\u201d` : `these ${items.length} items`;
if (!window.confirm(`Delete ${what} now? You can\u2019t undo this.`)) return;
void out(items, (i) => api.driveDeleteForever(i));
@@ -140,10 +141,16 @@ function DriveTrash({ onClose }: { onClose: () => void }) {
<span className="drive-badge" aria-hidden="true">
<FileGlyph kind={item.kind} extension={item.extension} />
</span>
- <span className="drive-name">{driveName(item)}</span>
- <span className="drive-meta drive-kind">{kindName(item)}</span>
+ <span className="drive-name" title={item.restorePath ? `From ${item.restorePath}` : undefined}>
+ {driveName(item)}
+ </span>
+ <span className="drive-meta drive-kind">
+ {item.restorePath ? `From ${item.restorePath.split("/").slice(0, -1).join("/") || "iCloud Drive"}` : kindName(item)}
+ </span>
<span className="drive-meta">{isContainer(item) ? "" : fileSize(item.size)}</span>
- <span className="drive-meta">{modified(item.modifiedAt ?? item.createdAt)}</span>
+ <span className={`drive-meta${daysLeft(item.expiresAt) !== null && (daysLeft(item.expiresAt) ?? 99) <= 3 ? " is-soon" : ""}`}>
+ {timeLeft(item.expiresAt)}
+ </span>
</span>
<span className="drive-row-actions is-shown">
<button className="quiet" onClick={() => void recover([item])}>Recover</button>
@@ -234,6 +241,18 @@ function decimalSize(bytes: number): string {
return `${(Math.round(value * p) / p).toLocaleString()} ${units[unit]}`;
}
+/** Days until Apple deletes it for good, rounded up; `null` when Apple did not say. */
+function daysLeft(expiresAt: number | null): number | null {
+ if (expiresAt === null) return null;
+ return Math.max(0, Math.ceil((expiresAt * 1000 - Date.now()) / 86_400_000));
+}
+/** "21 days", "1 day", "Today" — icloud.com's Time Left. */
+function timeLeft(expiresAt: number | null): string {
+ const d = daysLeft(expiresAt);
+ if (d === null) return "";
+ return d === 0 ? "Today" : `${d} day${d === 1 ? "" : "s"}`;
+}
+
type Crumb = { id: string; name: string };
export function DriveView() {
diff --git a/src/styles/app.css b/src/styles/app.css
index 60932d6..70d54ae 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1811,3 +1811,4 @@
.drive > .cal-bar .with-glyph:not(.primary) svg { font-size: initial; }
}
.picker-menu.is-up { top: auto; bottom: calc(100% + 4px); }
+.drive-meta.is-soon { color: var(--sys-red, #ff453a); }