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.

Photos; contacts mass import; instant reminder ticks; a window that opens drawn

Yashwanth Kamireddi57f9fe028e45
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 40144be..cdcfe2f 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -98,7 +98,7 @@ console.log("nav items :", JSON.stringify(names));
console.log("page errors :", errs.length ? errs : "none");
const collapsed =
JSON.stringify(names) ===
- JSON.stringify(["Reminders", "Notes", "iCloud Drive", "Calendar", "Contacts"]);
+ JSON.stringify(["Reminders", "Notes", "iCloud Drive", "Photos", "Calendar", "Contacts"]);
const selectsBuilt = selected === "Reminders";
console.log(collapsed ? "PASS the sidebar holds only what works, most used first" : `FAIL the sidebar holds ${JSON.stringify(names)}`);
console.log(selectsBuilt ? "PASS opens on the first screen" : `FAIL opened on ${selected}`);
diff --git a/.uiverify/boundary.mjs b/.uiverify/boundary.mjs
index b5e8010..6e2cabb 100644
--- a/.uiverify/boundary.mjs
+++ b/.uiverify/boundary.mjs
@@ -33,7 +33,7 @@ const after = await page.evaluate(() => ({
sidebar: document.querySelectorAll(".nav-item").length,
said: document.querySelector(".screen-failed")?.textContent ?? null,
}));
-ok(after.sidebar === 5, "a screen that fails to draw leaves the sidebar", `the app went blank: ${JSON.stringify(after)}`);
+ok(after.sidebar === 6, "a screen that fails to draw leaves the sidebar", `the app went blank: ${JSON.stringify(after)}`);
ok(Boolean(after.said?.includes("Contacts couldn’t be shown")), "and says so in its place", `nothing said: ${JSON.stringify(after)}`);
if (after.sidebar === 5) {
await page.locator(".nav-item", { hasText: "Notes" }).click();
diff --git a/.uiverify/contacts-vcard.mjs b/.uiverify/contacts-vcard.mjs
index 90a5014..1951ed8 100644
--- a/.uiverify/contacts-vcard.mjs
+++ b/.uiverify/contacts-vcard.mjs
@@ -33,11 +33,13 @@ await page.waitForTimeout(200);
sent = await page.evaluate(() => window.__exports?.at(-1));
ok(sent?.fileName === "iCloud vCards.vcf" && sent.guids.length === 4, `everyone goes out as iCloud vCards ${JSON.stringify(sent?.fileName)}`);
-await page.evaluate(() => { window.__pick = "/home/test/people.vcf"; });
+// Mass import: several files at once, a Google Contacts CSV among them.
+await page.evaluate(() => { window.__pick = ["/home/test/people.vcf", "/home/test/google.csv"]; });
await page.getByRole("button", { name: "More" }).click();
-await page.getByRole("menuitem", { name: "Import vCard…" }).click();
+await page.getByRole("menuitem", { name: "Import Contacts…" }).click();
await page.waitForTimeout(300);
-ok((await page.evaluate(() => window.__imports?.at(-1)?.path)) === "/home/test/people.vcf", "a chosen file is imported");
+const paths = await page.evaluate(() => window.__imports?.at(-1)?.paths);
+ok(JSON.stringify(paths) === JSON.stringify(["/home/test/people.vcf", "/home/test/google.csv"]), `every chosen file, vCard and CSV, is imported at once ${JSON.stringify(paths)}`);
ok(/2 contacts imported/.test(await page.locator(".drive-saved").innerText()), "and the count is said");
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/drive-upload.mjs b/.uiverify/drive-upload.mjs
index 25188c3..32c09b1 100644
--- a/.uiverify/drive-upload.mjs
+++ b/.uiverify/drive-upload.mjs
@@ -38,6 +38,7 @@ await ctx.addInitScript(() => {
say({ ...a, sent: 500, state: "sending" });
await wait(400);
window.__midway = document.querySelector(".upload-tray")?.innerText ?? "";
+ window.__midwayBars = [...document.querySelectorAll(".upload-bar:not(.is-waiting) > span")].map((b) => [b.style.transform, b.style.width]);
say({ ...a, sent: 1000, state: "verifying" });
await wait(100);
say({ ...a, sent: 1000, state: "done" });
@@ -77,6 +78,11 @@ ok(/a\.jpg/.test(midway) && /50%/.test(midway) && /b\.jpg/.test(midway) && /Wait
"while going up, each file shows by name with its own progress",
`midway the tray said ${JSON.stringify(midway)}`);
+// The bars grow by scale on the compositor, never by width: a width laid the tray out on every
+// step, and coming back to the window replayed every step at once as a glitch.
+const bars = await page.evaluate(() => window.__midwayBars ?? []);
+ok(bars.length > 0 && bars.every(([t, w]) => /^scaleX\(/.test(t) && !w), "progress bars grow by scale, not width", `bars were ${JSON.stringify(bars)}`);
+
const rows = await page.locator(".upload-row").evaluateAll((els) =>
els.map((e) => ({ cls: e.className, text: e.innerText.replace(/\s+/g, " ") })));
ok(rows.length === 2 && /is-done/.test(rows[0].cls) && /is-failed/.test(rows[1].cls) &&
diff --git a/.uiverify/notes-delete.mjs b/.uiverify/notes-delete.mjs
new file mode 100644
index 0000000..e8a91e1
--- /dev/null
+++ b/.uiverify/notes-delete.mjs
@@ -0,0 +1,39 @@
+// Deleting a note, as in Notes: the note below opens in its place, and Delete is ready again at
+// once; a second delete while the first is still on its way goes too.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Notes");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const titles = () => page.locator(".note-row .note-row-title, .note-row strong").allInnerTexts();
+const rows = page.locator(".note-row");
+const openTitle = () => page.locator(".note-row[aria-current='true'], .note-row.is-open, .note-row[aria-selected='true']").first().innerText();
+
+await page.evaluate(() => { window.__slowDelete = 1500; });
+const before = await rows.allInnerTexts();
+await rows.nth(1).click();
+await page.waitForTimeout(300);
+const second = before[1].split("\n")[0];
+const third = before[2].split("\n")[0];
+await page.getByRole("button", { name: "Delete", exact: true }).click();
+await page.waitForTimeout(150);
+ok((await openTitle()).startsWith(third), `the note below opens in its place ${second} → ${(await openTitle()).split("\n")[0]}`);
+ok(await page.getByRole("button", { name: "Delete", exact: true }).isEnabled(), "and Delete is ready again at once");
+await page.getByRole("button", { name: "Delete", exact: true }).click();
+await page.waitForTimeout(2200);
+const gone = await page.evaluate(() => window.__noteDeletes);
+ok(gone?.length === 2 && gone[0] !== gone[1], `a second delete while the first is on its way goes too ${JSON.stringify(gone)}`);
+// The engine's own menu (Back, Reload, Inspect Element) never opens; a text field keeps its own.
+const blocked = await page.evaluate(() => {
+ const at = (el) => { const e = new MouseEvent("contextmenu", { bubbles: true, cancelable: true }); el.dispatchEvent(e); return e.defaultPrevented; };
+ return { empty: at(document.querySelector(".note-rows") ?? document.body), text: at(document.querySelector(".note-rich")) };
+});
+ok(blocked.empty && !blocked.text, `the engine's menu is kept out, a text field keeps its own ${JSON.stringify(blocked)}`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/photos.mjs b/.uiverify/photos.mjs
new file mode 100644
index 0000000..7f6e372
--- /dev/null
+++ b/.uiverify/photos.mjs
@@ -0,0 +1,94 @@
+// Photos: the library grouped by month, newest first; views from the sidebar; a photo opens on
+// a dark stage, the arrows go through, Escape closes; the original downloads.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+const months = await page.locator(".px-month-title").allInnerTexts();
+ok(months.length === 2 && /2026/.test(months[0]), `the library is grouped by month, newest first ${JSON.stringify(months)}`);
+ok((await page.locator(".px-tile").count()) === 5, "every photo in the library is a tile; a deleted one is not");
+ok((await page.locator(".px-duration").innerText()).includes("0:12"), "a video shows its length");
+ok((await page.locator(".px-tile .px-heart").count()) === 1, "a favorite shows its heart");
+
+await page.locator(".px-source", { hasText: "Favorites" }).click();
+await page.waitForTimeout(200);
+ok((await page.locator(".px-tile").count()) === 1, "Favorites holds the favorite");
+await page.locator(".px-source", { hasText: "Recently Deleted" }).click();
+await page.waitForTimeout(200);
+ok((await page.locator(".px-tile").count()) === 1, "Recently Deleted holds the deleted one");
+// An album: in the sidebar with its count, its photos in one grid with no month headings.
+await page.locator(".px-source", { hasText: "Trips" }).click();
+await page.waitForTimeout(200);
+ok((await page.locator(".px-tile").count()) === 2 && (await page.locator(".px-month-title").count()) === 0 &&
+ (await page.locator(".px-bar h1").innerText()) === "Trips", "an album opens to its photos, one grid, titled with its name");
+await page.locator(".px-source", { hasText: "Library" }).click();
+await page.waitForTimeout(200);
+
+await page.locator(".px-tile").first().click();
+await page.waitForTimeout(150);
+ok((await page.locator(".px-viewer").count()) === 1, "a photo opens in the viewer");
+const first = await page.locator(".px-stage img").getAttribute("src");
+await page.keyboard.press("ArrowRight");
+await page.waitForTimeout(100);
+const second = await page.locator(".px-stage img").getAttribute("src");
+ok(first && second && first !== second && /medium/.test(second), "the right arrow goes to the next photo, at screen size");
+await page.getByRole("button", { name: "Download" }).click();
+await page.waitForTimeout(200);
+ok((await page.evaluate(() => window.__downloads?.at(-1)?.id)) === "p2", "Download saves that photo's original");
+// Favorite, from the heart and from ".", at once; then Delete, after asking, moves on and the
+// photo is in Recently Deleted, from where Recover brings it back.
+await page.getByRole("button", { name: "Favorite", exact: true }).click();
+ok((await page.getByRole("button", { name: "Unfavorite" }).count()) === 1, "the heart fills at once");
+await page.keyboard.press(".");
+await page.waitForTimeout(200);
+ok((await page.getByRole("button", { name: "Favorite", exact: true }).count()) === 1, '"." takes it back');
+const flags = await page.evaluate(() => window.__flags.map((f) => `${f.id}:${f.flag}:${f.on}`));
+ok(JSON.stringify(flags) === JSON.stringify(["p2:favorite:true", "p2:favorite:false"]), `and each goes to iCloud ${JSON.stringify(flags)}`);
+page.once("dialog", (d) => void d.accept());
+await page.getByRole("button", { name: "Delete", exact: true }).click();
+await page.waitForTimeout(300);
+const next = await page.locator(".px-stage img, .px-stage video").first().getAttribute("src");
+ok(/p3|p4/.test(next ?? "") && (await page.locator(".px-tile").count()) === 4, "Delete, once agreed, takes it out and shows the next");
+// A video shows its still; Play opens it in the computer's own player.
+if (await page.getByRole("button", { name: "Play in your video player" }).count()) {
+ await page.getByRole("button", { name: "Play in your video player" }).click();
+ await page.waitForTimeout(150);
+ ok((await page.evaluate(() => window.__plays?.at(-1)?.id)) === "p3", "a video plays in the computer's own player");
+}
+await page.keyboard.press("Escape");
+await page.locator(".px-source", { hasText: "Recently Deleted" }).click();
+await page.waitForTimeout(200);
+ok((await page.locator(".px-tile").count()) === 2, "the deleted photo is in Recently Deleted");
+await page.locator(".px-tile").first().click();
+await page.getByRole("button", { name: "Recover" }).click();
+await page.waitForTimeout(300);
+ok((await page.evaluate(() => window.__flags.at(-1))).on === false, "Recover brings it back");
+await page.keyboard.press("Escape");
+await page.locator(".px-source", { hasText: "Library" }).click();
+await page.waitForTimeout(200);
+await page.evaluate(() => { window.__flagFail = true; });
+await page.locator(".px-tile").nth(1).click();
+await page.getByRole("button", { name: "Favorite", exact: true }).click();
+await page.waitForTimeout(300);
+ok((await page.getByRole("button", { name: "Favorite", exact: true }).count()) === 1 && (await page.locator(".notice").count()) === 1,
+ "a change iCloud refuses goes back, and says why");
+await page.keyboard.press("Escape");
+await page.evaluate(() => { window.__flagFail = false; });
+ok((await page.locator(".px-viewer").count()) === 0, "Escape closes the viewer");
+
+const across = async () => page.locator(".px-grid").first().evaluate((g) => getComputedStyle(g).gridTemplateColumns.split(" ").length);
+const before = await across();
+await page.getByLabel("Zoom").fill("3");
+await page.waitForTimeout(100);
+ok((await across()) < before, `zooming in shows fewer across ${before} → ${await across()}`);
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/reminders-instant.mjs b/.uiverify/reminders-instant.mjs
index 7f69f4f..52dcb5f 100644
--- a/.uiverify/reminders-instant.mjs
+++ b/.uiverify/reminders-instant.mjs
@@ -38,8 +38,8 @@ await tick.click();
await page.waitForTimeout(150);
const ticked = (await tick.getAttribute("aria-checked")) === "true";
ok(ticked, "a tick shows at once");
-// Two writes at once: the first finishing must not free the second's row while it is
-// still on its way. Each row stays held until its own answer comes.
+// Two writes at once: the first finishing must not undo the second's tick while it is still
+// on its way.
const a = page.getByRole("checkbox", { name: "Evening run" });
await a.click();
await page.waitForTimeout(600);
@@ -47,7 +47,10 @@ const c = page.getByRole("checkbox", { name: "Pick up the parcel" });
if (await c.count()) {
await c.click();
await page.waitForTimeout(1100); // the first has answered; the second has not
- ok(await c.isDisabled(), "a row stays held while its own write is still on its way");
+ // Ticks can be undone at once now (they queue in order), so the row is not held; what
+ // matters is that the first answer's re-read does not undo the second tick.
+ const still = (await c.count()) === 0 || (await c.getAttribute("aria-checked")) === "true";
+ ok(still, "a row's tick holds while its own write is still on its way");
}
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/reminders-tick.mjs b/.uiverify/reminders-tick.mjs
new file mode 100644
index 0000000..cc4b8a1
--- /dev/null
+++ b/.uiverify/reminders-tick.mjs
@@ -0,0 +1,34 @@
+// Ticking a reminder is instant, as on the phone: the circle fills at once, the row stays a
+// moment and then leaves, never waiting on Apple; unticking in that moment keeps it, and both
+// ticks reach Apple in order.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, remindersFixture: true });
+const page = await ctx.newPage();
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Reminders");
+await page.locator(".rx-list", { hasText: "Daily" }).click();
+await page.waitForTimeout(300);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+await page.evaluate(() => { window.__doneDelay = 4000; });
+const row = (t) => page.locator(".rx-row", { has: page.getByLabel(`Rename ${t}`) });
+
+await row("Pick up the parcel").locator(".rx-tick").click();
+await page.waitForTimeout(80);
+ok((await row("Pick up the parcel").locator(".rx-tick").getAttribute("aria-checked")) === "true", "the circle fills at once, while Apple is still answering");
+await page.waitForTimeout(1500);
+ok((await row("Pick up the parcel").count()) === 0, "and the row leaves after a moment, before Apple has answered");
+
+await row("Plan tomorrow").locator(".rx-tick").click();
+await page.waitForTimeout(300);
+await row("Plan tomorrow").locator(".rx-tick").click();
+await page.waitForTimeout(1600);
+ok((await row("Plan tomorrow").count()) === 1 && (await row("Plan tomorrow").locator(".rx-tick").getAttribute("aria-checked")) === "false", "unticked in that moment, it stays");
+await page.waitForTimeout(9000);
+const sent = await page.evaluate(() => window.__done.filter((d) => d.guid === "r1").map((d) => d.done));
+ok(JSON.stringify(sent) === JSON.stringify([true, false]), `and Apple gets both ticks, in order ${JSON.stringify(sent)}`);
+await b.close();
+process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 451510a..23f958d 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -200,7 +200,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
flagged: args.flagged ?? false, parentGuid: null, etag: null });
return null;
case "reminder_delete": return null;
- case "reminder_set_done": (window.__done ??= []).push(args); return null;
+ case "reminder_set_done":
+ (window.__done ??= []).push(args);
+ // A slow network, when a test asks for one.
+ if (window.__doneDelay) await new Promise((r) => setTimeout(r, window.__doneDelay));
+ return null;
case "reminder_set_repeat": return null;
case "reminder_edit": {
(window.__edits ??= []).push(args.edit);
@@ -274,7 +278,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (args.runs && kept === args.body) (window.__savedRuns ??= {})[args.guid] = args.runs;
return kept;
}
- case "note_delete": return null;
+ case "note_delete":
+ (window.__noteDeletes ??= []).push(args.guid);
+ if (window.__slowDelete) await new Promise((r) => setTimeout(r, window.__slowDelete));
+ return null;
case "note_move":
if (window.__slowMove) await new Promise((r) => setTimeout(r, window.__slowMove));
return null;
@@ -300,6 +307,39 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
: { id: "M2", uti: "org.openxmlformats.spreadsheetml.sheet", kind: "file", filename: "Budget.xlsx", title: null, width: null, height: null, size: 9100, hasPreview: false };
case "note_attachment_open": (window.__opened ??= []).push(args.id); return null;
case "note_table": if (String(args.id).startsWith("M")) return null; return (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]).map((r) => r.slice());
+ case "photos_list": case "photos_counts": {
+ const P = (id, takenAt, extra = {}) => ({ id, master: `m${id}`, takenAt, addedAt: takenAt, kind: "image",
+ width: 4032, height: 3024, duration: null, filename: `IMG_${id}.JPG`, size: 2400000, uti: "public.jpeg",
+ favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra });
+ const all = (window.__photos ??= [
+ P("p1", 1792500000, { favorite: true }), P("p2", 1792400000), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),
+ P("p4", 1789900000), P("p5", 1789800000), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000 }),
+ ]);
+ const live = all.filter((p) => !p.deleted && !p.hidden);
+ const views = {
+ library: live, recents: live, favorites: live.filter((p) => p.favorite), videos: live.filter((p) => p.kind === "video"),
+ screenshots: live.filter((p) => p.uti === "public.png"), recentlyDeleted: all.filter((p) => p.deleted),
+ };
+ if (cmd === "photos_counts") return Object.entries(views).map(([k, v]) => [k, v.length]);
+ return views[args.view] ?? [];
+ }
+ case "photos_albums": return [[{ id: "AL1", name: "Trips", position: 0, changeTag: null }, 2]];
+ case "photos_in_album": {
+ const all = window.__photos ?? [];
+ return args.album === "AL1" ? all.filter((p) => p.id === "p4" || p.id === "p2") : [];
+ }
+ case "photo_set_flag": {
+ (window.__flags ??= []).push(args);
+ if (window.__flagFail) throw "iCloud didn’t accept that change.";
+ const p = (window.__photos ?? []).find((x) => x.id === args.id);
+ if (p) {
+ if (args.flag === "favorite") p.favorite = args.on;
+ if (args.flag === "deleted") { p.deleted = args.on; p.deletedAt = args.on ? 1792700000 : null; }
+ }
+ return p;
+ }
+ case "photo_play": (window.__plays ??= []).push(args); return null;
+ case "photo_download": (window.__downloads ??= []).push(args); return `/home/test/Downloads/IMG_${args.id}.JPG`;
case "note_table_add_row": {
const t = (window.__table ??= [["Item", "Qty"], ["Milk", "2"], ["", ""]]);
if (args.column) t.forEach((r) => r.splice(args.at, 0, ""));
diff --git a/README.md b/README.md
index e1cd473..7b5ec9c 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,8 @@
Your iCloud, on your own computer.
-Quince signs into iCloud once and keeps a copy of your calendar, reminders, notes, contacts
-and Drive on your machine. Everything opens straight away and works with no connection, and
+Quince signs into iCloud once and keeps a copy of your calendar, reminders, notes, contacts,
+Drive and photos on your machine. Everything opens straight away and works with no connection, and
what you change here reaches your phone.
It is a native Linux application — Rust underneath, a real window, no browser wrapper.
@@ -16,9 +16,11 @@ Everything here is read from and written to your real iCloud account, shows the
make it — before Apple has answered — and is put back with the reason if Apple refuses.
**Notes** — pictures, scans, PDFs, recordings, films and files shown where they sit and opened
-in your own apps; tables shown as the grids they are, their cells edited in place; edited formatted, as on a Mac: titles, headings, monospaced text, bulleted,
-dashed and numbered lists, checklists you tick, bold, italic, underline and strikethrough,
-from the Aa panel, the checklist button or the Mac's keys. Folders: new, rename, nest,
+in your own apps; tables shown as the grids they are, kept up to date as they change on your
+phone; text coloured on the phone in its colour; edited formatted, as on a Mac: titles,
+headings, monospaced text, bulleted, dashed and numbered lists (typed as on the phone: "- ",
+"* ", "1. ", "[ ] "), checklists you tick, bold, italic, underline and strikethrough, from the
+Aa panel, the checklist button or the Mac's keys. Delete opens the note below, as Notes does. Folders: new, rename, nest,
delete. Pin, move, Recently Deleted and Recover. An edit made on your phone at the same time
is merged in, not overwritten, and nothing either side typed is lost.
@@ -27,14 +29,16 @@ due dates and all-day dates, flags, priorities, alerts that ring on this compute
reorder, Today / Scheduled / Flagged / All, and completing a repeating reminder the way your
phone does.
-**Calendar** — Day, Week, Month and Year; make an event by dragging or double-clicking;
+**Calendar** — Day, Week, Month and Year; make, rename, recolour and delete calendars; Go to
+Date (⇧⌃T); make an event by dragging or double-clicking;
move and resize by dragging, or nudge with ⌃⌥ and the arrows; alerts; repeats, with Only
This Event, All Future Events and All Events for one day of a series; your reminders on the
schedule in their list's colour; birthdays and holidays; the Mac's keyboard throughout.
**Contacts** — cards with phones, emails, links, birthdays and notes; lists in a sidebar,
with people added by menu or by dragging; select several to add, remove, export or delete
-together; vCard import and export; My Card.
+together; labels from Apple's own list; import many contacts at once from vCard or from a CSV
+exported by Google Contacts or Outlook, and export; My Card.
**iCloud Drive** — browse in a list or grid with Apple's own thumbnails; sort; upload files
or whole folders by button or by dropping them on the window, each file's progress shown and
@@ -42,8 +46,13 @@ any of them cancellable while it is still on its way up; download, rename, dupli
dialog or by dragging onto a folder; Recents; Recently Deleted with the time each item has
left, Recover and Delete Now; your storage.
-**Instant, both ways.** A change made on your phone reaches Quince in about a second: Notes
-and Reminders through Apple's own push channel, Calendar and Contacts through the same quick
+**Photos** — your whole library, edge to edge and by month, with a zoom; Favorites, Recents,
+Videos, Screenshots, Recently Deleted and your albums; a viewer with the arrow keys, details,
+Favorite (.), Delete to Recently Deleted and Recover, and the original downloaded. Videos open
+in your own player. Pictures are fetched once and kept, so the library scrolls from disk.
+
+**Instant, both ways.** A change made on your phone reaches Quince in about a second: Notes,
+Reminders and Photos through Apple's own push channel, Calendar and Contacts through the same quick
"has anything changed" checks icloud.com makes, every few seconds while the window is open.
What you change shows the moment you make it and is put back, with the reason, only if Apple
refuses it — and a refresh landing mid-change never undoes what is still on its way.
@@ -62,8 +71,9 @@ outside your devices can read your iCloud. Quince says exactly that, once, and n
switch — on your iPhone, Settings, your name, iCloud, Access iCloud Data on the Web — rather
than failing screen by screen.
-Not yet: Photos, Mail, Find My; typing into a table cell that has never been typed in (cells
-with text are edited in place); calendar invitations.
+Not yet: Mail, Find My, calendar invitations, uploading photos. Notes tables are read-only for
+now: edits made here were stored by Apple but did not show on an iPhone, so no table is changed
+until one is seen there.
## Installing
diff --git a/check.sh b/check.sh
index 8c0b3f5..c032309 100755
--- a/check.sh
+++ b/check.sh
@@ -53,6 +53,9 @@ step "calendar go to date" node .uiverify/calendar-goto.mjs
step "calendar calendars" node .uiverify/calendar-collections.mjs
step "drive names" node .uiverify/drive-names.mjs
step "notes autoformat" node .uiverify/notes-autoformat.mjs
+step "reminder ticks" node .uiverify/reminders-tick.mjs
+step "photos" node .uiverify/photos.mjs
+step "notes delete" node .uiverify/notes-delete.mjs
step "empty today" node .uiverify/reminders-empty.mjs
step "calendar keys" node .uiverify/calendar-keys.mjs
step "reminders instant" node .uiverify/reminders-instant.mjs
@@ -88,6 +91,9 @@ step "webkit: go to date" env ENGINE=webkit node .uiverify/calendar-goto.mjs
step "webkit: calendars" env ENGINE=webkit node .uiverify/calendar-collections.mjs
step "webkit: drive names" env ENGINE=webkit node .uiverify/drive-names.mjs
step "webkit: autoformat" env ENGINE=webkit node .uiverify/notes-autoformat.mjs
+step "webkit: ticks" env ENGINE=webkit node .uiverify/reminders-tick.mjs
+step "webkit: photos" env ENGINE=webkit node .uiverify/photos.mjs
+step "webkit: delete" env ENGINE=webkit node .uiverify/notes-delete.mjs
step "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjs
step "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjs
step "reminder colours" node .uiverify/calendar-reminder-colour.mjs
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index 817d45c..1e8c333 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -11,6 +11,7 @@ pub mod drive;
pub mod fold;
pub mod health;
pub mod notes;
+pub mod photos;
pub mod reminders;
pub mod schema;
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
new file mode 100644
index 0000000..4f5e496
--- /dev/null
+++ b/crates/quince-core/src/photos.rs
@@ -0,0 +1,390 @@
+//! iCloud Photos in the local library.
+//!
+//! The whole library is mirrored through CloudKit's change feed, so every view (Library,
+//! Favorites, Videos, Recently Deleted) is a query here and draws at once. Only the photos'
+//! descriptions are kept; the images themselves are cached on disk by the app as they are
+//! seen, and their download links, which expire, are never stored.
+
+use crate::{Library, Result};
+use rusqlite::params;
+use serde::{Deserialize, Serialize};
+
+/// What a photo is, as Photos sorts it.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum Kind {
+ Image,
+ Video,
+ /// A still with its moving part beside it.
+ Live,
+}
+
+impl Kind {
+ fn as_str(self) -> &'static str {
+ match self {
+ Kind::Image => "image",
+ Kind::Video => "video",
+ Kind::Live => "live",
+ }
+ }
+ fn parse(s: &str) -> Self {
+ match s {
+ "video" => Kind::Video,
+ "live" => Kind::Live,
+ _ => Kind::Image,
+ }
+ }
+}
+
+/// One photo or video: an asset (what the person sees, with its edits and flags) and the
+/// master it shows (the original file).
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Photo {
+ /// The asset's record name: what writes are addressed to.
+ pub id: String,
+ pub master: String,
+ /// When it was taken, unix seconds.
+ pub taken_at: i64,
+ /// When it came into the library, unix seconds.
+ pub added_at: Option<i64>,
+ pub kind: Kind,
+ pub width: i64,
+ pub height: i64,
+ /// Seconds, for a video.
+ pub duration: Option<f64>,
+ pub filename: Option<String>,
+ /// The original's size in bytes.
+ pub size: Option<i64>,
+ /// The original's type, as a UTI (`public.jpeg`, `public.mpeg-4` …).
+ pub uti: Option<String>,
+ pub favorite: bool,
+ pub hidden: bool,
+ /// In Recently Deleted.
+ pub deleted: bool,
+ /// When it was deleted: Photos counts its 30 days from here.
+ pub deleted_at: Option<i64>,
+ /// Photos' subtype: 1 and 3 mark screenshots and the like (`assetSubtypeV2`).
+ pub subtype: i64,
+ /// The asset's change tag, for writing back to it.
+ pub change_tag: Option<String>,
+}
+
+/// An album the person made.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Album {
+ pub id: String,
+ pub name: String,
+ pub position: i64,
+ pub change_tag: Option<String>,
+}
+
+/// Which photos a view shows.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub enum View {
+ Library,
+ Favorites,
+ Videos,
+ Screenshots,
+ /// Newest added first.
+ Recents,
+ RecentlyDeleted,
+}
+
+const COLUMNS: &str = "id, master, taken_at, added_at, kind, width, height, duration, filename, \
+ size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag";
+
+fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
+ Ok(Photo {
+ id: r.get(0)?,
+ master: r.get(1)?,
+ taken_at: r.get(2)?,
+ added_at: r.get(3)?,
+ kind: Kind::parse(&r.get::<_, String>(4)?),
+ width: r.get(5)?,
+ height: r.get(6)?,
+ duration: r.get(7)?,
+ filename: r.get(8)?,
+ size: r.get(9)?,
+ uti: r.get(10)?,
+ favorite: r.get::<_, i64>(11)? != 0,
+ hidden: r.get::<_, i64>(12)? != 0,
+ deleted: r.get::<_, i64>(13)? != 0,
+ deleted_at: r.get(14)?,
+ subtype: r.get(15)?,
+ change_tag: r.get(16)?,
+ })
+}
+
+impl Library {
+ /// Photos written or replaced, by asset id.
+ pub fn put_photos(&mut self, photos: &[Photo]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ let mut stmt = tx.prepare(
+ "INSERT INTO photos (id, master, taken_at, added_at, kind, width, height, duration,
+ filename, size, uti, favorite, hidden, deleted, deleted_at,
+ subtype, change_tag)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
+ ON CONFLICT(id) DO UPDATE SET
+ master = excluded.master, taken_at = excluded.taken_at,
+ added_at = excluded.added_at, kind = excluded.kind, width = excluded.width,
+ height = excluded.height, duration = excluded.duration,
+ filename = excluded.filename, size = excluded.size, uti = excluded.uti,
+ favorite = excluded.favorite, hidden = excluded.hidden,
+ deleted = excluded.deleted, deleted_at = excluded.deleted_at,
+ subtype = excluded.subtype, change_tag = excluded.change_tag",
+ )?;
+ for p in photos {
+ stmt.execute(params![
+ p.id,
+ p.master,
+ p.taken_at,
+ p.added_at,
+ p.kind.as_str(),
+ p.width,
+ p.height,
+ p.duration,
+ p.filename,
+ p.size,
+ p.uti,
+ i64::from(p.favorite),
+ i64::from(p.hidden),
+ i64::from(p.deleted),
+ p.deleted_at,
+ p.subtype,
+ p.change_tag
+ ])?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Photos gone from iCloud for good (expunged), by asset id.
+ pub fn forget_photos(&mut self, ids: &[String]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ for id in ids {
+ tx.execute("DELETE FROM photos WHERE id = ?1", params![id])?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Every photo, replaced by `photos`: a full pass, where anything not in it is gone.
+ pub fn replace_photos(&mut self, photos: &[Photo]) -> Result<()> {
+ self.conn.execute("DELETE FROM photos", [])?;
+ self.put_photos(photos)
+ }
+
+ /// A view's photos, newest first.
+ pub fn photos(&self, view: View) -> Result<Vec<Photo>> {
+ let (filter, order) = match view {
+ View::Library => ("deleted = 0 AND hidden = 0", "taken_at DESC"),
+ View::Favorites => (
+ "deleted = 0 AND hidden = 0 AND favorite = 1",
+ "taken_at DESC",
+ ),
+ View::Videos => (
+ "deleted = 0 AND hidden = 0 AND kind = 'video'",
+ "taken_at DESC",
+ ),
+ View::Screenshots => (
+ "deleted = 0 AND hidden = 0 AND (subtype IN (1, 3) OR uti = 'public.png')",
+ "taken_at DESC",
+ ),
+ View::Recents => (
+ "deleted = 0 AND hidden = 0",
+ "COALESCE(added_at, taken_at) DESC",
+ ),
+ View::RecentlyDeleted => ("deleted = 1", "COALESCE(deleted_at, taken_at) DESC"),
+ };
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT {COLUMNS} FROM photos WHERE {filter} ORDER BY {order}, id"
+ ))?;
+ let rows = stmt.query_map([], row_to_photo)?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
+ /// One photo, by asset id, wherever it is (Recently Deleted and hidden included).
+ pub fn photo(&self, id: &str) -> Result<Option<Photo>> {
+ let mut stmt = self
+ .conn
+ .prepare(&format!("SELECT {COLUMNS} FROM photos WHERE id = ?1"))?;
+ let mut rows = stmt.query_map(params![id], row_to_photo)?;
+ Ok(rows.next().transpose()?)
+ }
+
+ /// How many photos each view holds.
+ pub fn photo_counts(&self) -> Result<Vec<(View, i64)>> {
+ let mut out = Vec::new();
+ for view in [
+ View::Library,
+ View::Favorites,
+ View::Videos,
+ View::Screenshots,
+ View::RecentlyDeleted,
+ ] {
+ out.push((view, self.photos(view)?.len() as i64));
+ }
+ Ok(out)
+ }
+
+ /// The albums, replaced by `albums`.
+ pub fn replace_albums(&mut self, albums: &[Album]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ tx.execute("DELETE FROM photo_albums", [])?;
+ for a in albums {
+ tx.execute(
+ "INSERT INTO photo_albums (id, name, position, change_tag) VALUES (?1, ?2, ?3, ?4)",
+ params![a.id, a.name, a.position, a.change_tag],
+ )?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Which photos are in which album: `(album, asset, position)`, added or moved.
+ pub fn put_album_items(&mut self, items: &[(String, String, i64)]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ for (album, asset, position) in items {
+ tx.execute(
+ "INSERT INTO photo_album_items (album, asset, position) VALUES (?1, ?2, ?3)
+ ON CONFLICT(album, asset) DO UPDATE SET position = excluded.position",
+ params![album, asset, position],
+ )?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Photos taken out of albums: `(album, asset)`.
+ pub fn forget_album_items(&mut self, items: &[(String, String)]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ for (album, asset) in items {
+ tx.execute(
+ "DELETE FROM photo_album_items WHERE album = ?1 AND asset = ?2",
+ params![album, asset],
+ )?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// Every album's photos, replaced: a full pass.
+ pub fn replace_album_items(&mut self, items: &[(String, String, i64)]) -> Result<()> {
+ self.conn.execute("DELETE FROM photo_album_items", [])?;
+ self.put_album_items(items)
+ }
+
+ /// An album's photos, in the album's order; none deleted or hidden.
+ pub fn album_photos(&self, album: &str) -> Result<Vec<Photo>> {
+ let columns = COLUMNS
+ .split(", ")
+ .map(|c| format!("p.{}", c.trim()))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let mut stmt = self.conn.prepare(&format!(
+ "SELECT {columns} FROM photo_album_items i JOIN photos p ON p.id = i.asset
+ WHERE i.album = ?1 AND p.deleted = 0 AND p.hidden = 0
+ ORDER BY i.position, p.taken_at DESC, p.id"
+ ))?;
+ let rows = stmt.query_map(params![album], row_to_photo)?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
+ pub fn albums(&self) -> Result<Vec<Album>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT id, name, position, change_tag FROM photo_albums ORDER BY position, name",
+ )?;
+ let rows = stmt.query_map([], |r| {
+ Ok(Album {
+ id: r.get(0)?,
+ name: r.get(1)?,
+ position: r.get(2)?,
+ change_tag: r.get(3)?,
+ })
+ })?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn photo(id: &str, taken: i64) -> Photo {
+ Photo {
+ id: id.into(),
+ master: format!("m-{id}"),
+ taken_at: taken,
+ added_at: Some(taken),
+ kind: Kind::Image,
+ width: 4032,
+ height: 3024,
+ duration: None,
+ filename: Some(format!("{id}.jpg")),
+ size: Some(1_000_000),
+ uti: Some("public.jpeg".into()),
+ favorite: false,
+ hidden: false,
+ deleted: false,
+ deleted_at: None,
+ subtype: 0,
+ change_tag: None,
+ }
+ }
+
+ /// Each view is the right photos, newest first; Recently Deleted holds only the deleted.
+ #[test]
+ fn views_sort_and_filter() {
+ let mut lib = Library::in_memory().unwrap();
+ let mut fav = photo("b", 200);
+ fav.favorite = true;
+ let mut video = photo("c", 300);
+ video.kind = Kind::Video;
+ let mut gone = photo("d", 400);
+ gone.deleted = true;
+ let mut hidden = photo("e", 500);
+ hidden.hidden = true;
+ lib.put_photos(&[photo("a", 100), fav, video, gone, hidden])
+ .unwrap();
+ let ids = |lib: &Library, v| {
+ lib.photos(v)
+ .unwrap()
+ .into_iter()
+ .map(|p| p.id)
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(ids(&lib, View::Library), ["c", "b", "a"]);
+ assert_eq!(ids(&lib, View::Favorites), ["b"]);
+ assert_eq!(ids(&lib, View::Videos), ["c"]);
+ assert_eq!(ids(&lib, View::RecentlyDeleted), ["d"]);
+ // An album holds what was put in it, in its order; a deleted photo leaves it.
+ lib.put_photos(&[photo("a", 100)]).unwrap();
+ lib.put_album_items(&[
+ ("AL".into(), "b".into(), 2048),
+ ("AL".into(), "a".into(), 1024),
+ ("AL".into(), "d".into(), 0),
+ ])
+ .unwrap();
+ let in_album: Vec<String> = lib
+ .album_photos("AL")
+ .unwrap()
+ .into_iter()
+ .map(|p| p.id)
+ .collect();
+ assert_eq!(
+ in_album,
+ ["a", "b"],
+ "in position order, the deleted one not shown"
+ );
+ lib.forget_album_items(&[("AL".into(), "a".into())])
+ .unwrap();
+ assert_eq!(lib.album_photos("AL").unwrap().len(), 1);
+ lib.forget_photos(&["a".into()]).unwrap();
+ assert_eq!(ids(&lib, View::Library), ["c", "b"]);
+ }
+}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index 3387dc9..187e4d8 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -377,4 +377,40 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE notes ADD COLUMN runs TEXT;
UPDATE sync_state SET token = NULL WHERE service = 'notes';
"#,
+ // iCloud Photos: every photo's description, mirrored through the change feed, so each
+ // view is a query here. The images are cached on disk, not in here.
+ r#"
+ CREATE TABLE photos (
+ id TEXT PRIMARY KEY,
+ master TEXT NOT NULL,
+ taken_at INTEGER NOT NULL,
+ added_at INTEGER,
+ kind TEXT NOT NULL,
+ width INTEGER NOT NULL,
+ height INTEGER NOT NULL,
+ duration REAL,
+ filename TEXT,
+ size INTEGER,
+ uti TEXT,
+ favorite INTEGER NOT NULL DEFAULT 0,
+ hidden INTEGER NOT NULL DEFAULT 0,
+ deleted INTEGER NOT NULL DEFAULT 0,
+ deleted_at INTEGER,
+ subtype INTEGER NOT NULL DEFAULT 0,
+ change_tag TEXT
+ ) STRICT;
+ CREATE INDEX photos_by_taken ON photos (deleted, hidden, taken_at DESC);
+ CREATE TABLE photo_albums (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ position INTEGER NOT NULL DEFAULT 0,
+ change_tag TEXT
+ ) STRICT;
+ CREATE TABLE photo_album_items (
+ album TEXT NOT NULL,
+ asset TEXT NOT NULL,
+ position INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (album, asset)
+ ) STRICT;
+ "#,
];
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index 28eb671..5b6bcf7 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -868,6 +868,204 @@ pub async fn export_vcards(
Ok(text)
}
+/// Each `BEGIN:VCARD … END:VCARD` in a file, whole, in order.
+#[must_use]
+pub fn split_vcards(text: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut card = String::new();
+ let mut inside = false;
+ for line in text.lines() {
+ let upper = line.trim().to_ascii_uppercase();
+ if upper == "BEGIN:VCARD" {
+ inside = true;
+ card.clear();
+ }
+ if inside {
+ card.push_str(line.trim_end_matches('\r'));
+ card.push_str("\r\n");
+ }
+ if inside && upper == "END:VCARD" {
+ inside = false;
+ out.push(std::mem::take(&mut card));
+ }
+ }
+ out
+}
+
+/// Cards gathered into batches Apple takes in one import: under `max_bytes` and `max_cards`.
+#[must_use]
+pub fn batch_vcards(cards: &[String], max_bytes: usize, max_cards: usize) -> Vec<String> {
+ let mut out = Vec::new();
+ let (mut batch, mut n) = (String::new(), 0);
+ for card in cards {
+ if n > 0 && (batch.len() + card.len() > max_bytes || n >= max_cards) {
+ out.push(std::mem::take(&mut batch));
+ n = 0;
+ }
+ batch.push_str(card);
+ n += 1;
+ }
+ if n > 0 {
+ out.push(batch);
+ }
+ out
+}
+
+/// One CSV record per row (RFC 4180: quoted fields, doubled quotes, line breaks in quotes).
+fn csv_rows(text: &str) -> Vec<Vec<String>> {
+ let mut rows = Vec::new();
+ let (mut row, mut field) = (Vec::new(), String::new());
+ let (mut quoted, mut chars) = (
+ false,
+ text.trim_start_matches('\u{feff}').chars().peekable(),
+ );
+ while let Some(c) = chars.next() {
+ match (quoted, c) {
+ (true, '"') if chars.peek() == Some(&'"') => {
+ field.push('"');
+ chars.next();
+ }
+ (true, '"') => quoted = false,
+ (true, c) => field.push(c),
+ (false, '"') if field.is_empty() => quoted = true,
+ (false, ',') => row.push(std::mem::take(&mut field)),
+ (false, '\r') => {}
+ (false, '\n') => {
+ row.push(std::mem::take(&mut field));
+ if row.iter().any(|f| !f.trim().is_empty()) {
+ rows.push(std::mem::take(&mut row));
+ } else {
+ row.clear();
+ }
+ }
+ (false, c) => field.push(c),
+ }
+ }
+ if !field.is_empty() || !row.is_empty() {
+ row.push(field);
+ if row.iter().any(|f| !f.trim().is_empty()) {
+ rows.push(row);
+ }
+ }
+ rows
+}
+
+fn vcard_escape(v: &str) -> String {
+ v.replace('\\', "\\\\")
+ .replace('\n', "\\n")
+ .replace(',', "\\,")
+ .replace(';', "\\;")
+}
+
+/// Contacts exported as CSV (Google Contacts, Outlook, most address books) as vCards: names,
+/// company, every phone and email column, birthday and notes, by their usual headings.
+/// Answers the cards and how many rows held nothing to make one from.
+#[must_use]
+pub fn csv_to_vcards(text: &str) -> (Vec<String>, usize) {
+ let rows = csv_rows(text);
+ let Some((head, body)) = rows.split_first() else {
+ return (Vec::new(), 0);
+ };
+ let head: Vec<String> = head.iter().map(|h| h.trim().to_ascii_lowercase()).collect();
+ let col = |names: &[&str]| head.iter().position(|h| names.contains(&h.as_str()));
+ let given = col(&["first name", "given name", "firstname"]);
+ let middle = col(&["middle name", "additional name"]);
+ let family = col(&["last name", "family name", "surname", "lastname"]);
+ let full = col(&["name", "full name", "display name"]);
+ let company = col(&[
+ "company",
+ "organization",
+ "organization 1 - name",
+ "organization name",
+ ]);
+ let title = col(&["job title", "title", "organization 1 - title"]);
+ let birthday = col(&["birthday"]);
+ let notes = col(&["notes", "note"]);
+ let is_phone = |h: &str| {
+ (h.contains("phone") || h.contains("mobile")) && !h.contains("type") && !h.contains("label")
+ };
+ let is_email = |h: &str| {
+ (h.contains("e-mail") || h.contains("email"))
+ && !h.contains("type")
+ && !h.contains("label")
+ && !h.contains("display")
+ };
+ let (mut cards, mut skipped) = (Vec::new(), 0);
+ for row in body {
+ let get = |i: Option<usize>| {
+ i.and_then(|i| row.get(i))
+ .map(|v| v.trim())
+ .filter(|v| !v.is_empty())
+ };
+ let (g, m, f) = (get(given), get(middle), get(family));
+ let name = get(full).map(ToString::to_string).or_else(|| {
+ let joined = [g, m, f]
+ .iter()
+ .flatten()
+ .copied()
+ .collect::<Vec<_>>()
+ .join(" ");
+ (!joined.is_empty()).then_some(joined)
+ });
+ let mut phones = Vec::new();
+ let mut emails = Vec::new();
+ for (i, h) in head.iter().enumerate() {
+ let Some(v) = row.get(i).map(|v| v.trim()).filter(|v| !v.is_empty()) else {
+ continue;
+ };
+ // Google keeps several numbers in one cell, " ::: " between them.
+ for one in v.split(":::").map(str::trim).filter(|x| !x.is_empty()) {
+ if is_phone(h) {
+ phones.push(one.to_string());
+ } else if is_email(h) {
+ emails.push(one.to_string());
+ }
+ }
+ }
+ let org = get(company);
+ if name.is_none() && org.is_none() && phones.is_empty() && emails.is_empty() {
+ skipped += 1;
+ continue;
+ }
+ let mut card = String::from("BEGIN:VCARD\r\nVERSION:3.0\r\n");
+ card.push_str(&format!(
+ "N:{};{};{};;\r\n",
+ vcard_escape(f.unwrap_or("")),
+ vcard_escape(g.unwrap_or(if f.is_none() {
+ name.as_deref().unwrap_or("")
+ } else {
+ ""
+ })),
+ vcard_escape(m.unwrap_or(""))
+ ));
+ card.push_str(&format!(
+ "FN:{}\r\n",
+ vcard_escape(name.as_deref().or(org).unwrap_or(""))
+ ));
+ if let Some(o) = org {
+ card.push_str(&format!("ORG:{}\r\n", vcard_escape(o)));
+ }
+ if let Some(t) = get(title) {
+ card.push_str(&format!("TITLE:{}\r\n", vcard_escape(t)));
+ }
+ for p in &phones {
+ card.push_str(&format!("TEL;TYPE=CELL:{}\r\n", vcard_escape(p)));
+ }
+ for e in &emails {
+ card.push_str(&format!("EMAIL;TYPE=INTERNET:{}\r\n", vcard_escape(e)));
+ }
+ if let Some(b) = get(birthday).filter(|b| b.len() >= 8) {
+ card.push_str(&format!("BDAY:{b}\r\n"));
+ }
+ if let Some(n) = get(notes) {
+ card.push_str(&format!("NOTE:{}\r\n", vcard_escape(n)));
+ }
+ card.push_str("END:VCARD\r\n");
+ cards.push(card);
+ }
+ (cards, skipped)
+}
+
/// Add the people in a vCard file to Contacts. Answers with the ids Apple gave them, and
/// how many cards it could not read.
pub async fn import_vcards(
@@ -1157,6 +1355,37 @@ mod list_tests {
mod tests {
use super::*;
+ /// A Google Contacts export: names, a company with a comma, two numbers in one cell, an
+ /// email. An empty row is not a contact; a row with only a note is skipped and counted.
+ #[test]
+ fn a_csv_export_becomes_vcards() {
+ let csv = "First Name,Last Name,Organization 1 - Name,Phone 1 - Value,E-mail 1 - Value,Notes\r\n\
+ Zoya,Ahuja,\"Acme, Inc\",+91 90000 00001 ::: +91 80000 00000,[email protected],\"Line one\nline two\"\r\n\
+ ,,,,,\r\n\
+ ,,,,,only a note\r\n";
+ let (cards, skipped) = csv_to_vcards(csv);
+ assert_eq!((cards.len(), skipped), (1, 1));
+ let c = &cards[0];
+ assert!(c.contains("N:Ahuja;Zoya;;;"), "{c}");
+ assert!(c.contains("FN:Zoya Ahuja"));
+ assert!(c.contains("ORG:Acme\\, Inc"));
+ assert_eq!(c.matches("TEL;TYPE=CELL:").count(), 2);
+ assert!(c.contains("EMAIL;TYPE=INTERNET:[email protected]"));
+ assert!(c.contains("NOTE:Line one\\nline two"));
+ }
+
+ /// A file of many cards is read card by card and sent in batches under Apple's limits.
+ #[test]
+ fn many_cards_are_split_and_batched() {
+ let one = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:A\r\nEND:VCARD\r\n";
+ let text = one.repeat(5);
+ let cards = split_vcards(&text);
+ assert_eq!(cards.len(), 5);
+ assert_eq!(batch_vcards(&cards, 1_000_000, 2).len(), 3);
+ assert_eq!(batch_vcards(&cards, one.len() * 2, 100).len(), 3);
+ assert_eq!(batch_vcards(&cards, 1_000_000, 100).concat(), text);
+ }
+
/// A book whose startup names more cards than it holds is read to the end, a page at a
/// time with its tokens, as icloud.com reads one — never stored short.
#[tokio::test]
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 2a707e8..7cdef8c 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -12,6 +12,7 @@ pub mod mergeable;
pub mod note_media;
pub mod notes;
pub mod occasions;
+pub mod photos;
pub mod push;
pub mod reminders;
pub mod sync;
diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rs
new file mode 100644
index 0000000..ff1387a
--- /dev/null
+++ b/crates/quince-icloud/src/photos.rs
@@ -0,0 +1,462 @@
+//! iCloud Photos: the library mirrored through CloudKit's change feed.
+//!
+//! Container `com.apple.photos.cloud`, zone `PrimarySync`. A photo is two records: a
+//! `CPLAsset` (what the person sees: the date, the flags, edits) pointing by `masterRef` at a
+//! `CPLMaster` (the original file and its renditions). Measured on his library: a full walk is
+//! 273 records in eight seconds, and a pass from the token with nothing new is under half a
+//! second. See docs/icloud-web/photos.md.
+
+use crate::cloudkit::{field, ZoneClient};
+use crate::Result;
+use base64::Engine;
+use quince_core::photos::{Album, Kind, Photo};
+use serde_json::Value;
+use std::collections::HashMap;
+
+pub const CONTAINER: &str = "com.apple.photos.cloud";
+pub const ZONE: &str = "PrimarySync";
+/// The library's sync token, in the library's sync state.
+pub const SERVICE: &str = "photos";
+
+/// What a walk of the zone brought.
+pub struct PhotosFetch {
+ pub records: Vec<Value>,
+ pub token: Option<String>,
+ /// From a token: only what changed. Without one: everything, and anything not in it is gone.
+ pub incremental: bool,
+ pub complete: bool,
+}
+
+/// The change feed from `since` (or from the start).
+pub async fn fetch(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ since: Option<&str>,
+) -> Result<PhotosFetch> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let walk = client.all_records(ZONE, since).await?;
+ Ok(PhotosFetch {
+ records: walk.records,
+ token: walk.token,
+ incremental: since.is_some(),
+ complete: walk.complete,
+ })
+}
+
+/// Where each of a photo's pictures can be downloaded now. They expire: never stored.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct Links {
+ pub thumb: Option<String>,
+ pub medium: Option<String>,
+ pub original: Option<String>,
+ /// A video's playable rendition, or a Live Photo's moving part.
+ pub video: Option<String>,
+}
+
+fn link(fields: &Value, key: &str, name: &str) -> Option<String> {
+ fields
+ .pointer(&format!("/{key}/value/downloadURL"))
+ .and_then(Value::as_str)
+ .map(|u| u.replace("${f}", name))
+}
+
+/// A master's download links, as icloud.com takes them (`${f}` is the file name it asks for).
+#[must_use]
+pub fn links_of(master: &Value) -> Links {
+ let f = &master["fields"];
+ Links {
+ thumb: link(f, "resJPEGThumbRes", "thumb.jpg")
+ .or_else(|| link(f, "resJPEGMedRes", "med.jpg")),
+ medium: link(f, "resJPEGMedRes", "med.jpg")
+ .or_else(|| link(f, "resJPEGFullRes", "full.jpg")),
+ original: link(f, "resOriginalRes", "original"),
+ video: link(f, "resVidMedRes", "video.mp4")
+ .or_else(|| link(f, "resVidSmallRes", "video.mp4"))
+ .or_else(|| link(f, "resOriginalVidComplRes", "live.mov")),
+ }
+}
+
+fn decoded(record: &Value, name: &str) -> Option<String> {
+ let v = record.pointer(&format!("/fields/{name}/value"))?.as_str()?;
+ let bytes = base64::engine::general_purpose::STANDARD.decode(v).ok()?;
+ String::from_utf8(bytes).ok().filter(|s| !s.is_empty())
+}
+
+fn millis(record: &Value, name: &str) -> Option<i64> {
+ record
+ .pointer(&format!("/fields/{name}/value"))
+ .and_then(Value::as_i64)
+ .map(|ms| ms / 1000)
+}
+
+/// A photo from its asset and the master it shows.
+#[must_use]
+pub fn photo_of(asset: &Value, master: &Value) -> Option<Photo> {
+ let id = field::record_name(asset)?;
+ let master_id = field::record_name(master)?;
+ let m = &master["fields"];
+ let uti = m
+ .pointer("/itemType/value")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let video = uti
+ .as_deref()
+ .is_some_and(|t| t.contains("movie") || t.contains("mpeg") || t.contains("video"));
+ let kind = if video {
+ Kind::Video
+ } else if m.get("resOriginalVidComplRes").is_some() {
+ Kind::Live
+ } else {
+ Kind::Image
+ };
+ let size = |k: &str| m.pointer(&format!("/{k}/value")).and_then(Value::as_i64);
+ let (mut width, mut height) = (
+ size("resOriginalWidth")
+ .or(size("resJPEGMedWidth"))
+ .unwrap_or(0),
+ size("resOriginalHeight")
+ .or(size("resJPEGMedHeight"))
+ .unwrap_or(0),
+ );
+ // EXIF orientations 5 to 8 are turned a quarter: the picture is as tall as it is wide.
+ let orientation =
+ field::int(asset, "orientation").or(field::int(master, "originalOrientation"));
+ if matches!(orientation, Some(5..=8)) {
+ std::mem::swap(&mut width, &mut height);
+ }
+ Some(Photo {
+ id,
+ master: master_id,
+ taken_at: millis(asset, "assetDate")
+ .or(millis(master, "originalCreationDate"))
+ .unwrap_or(0),
+ added_at: millis(asset, "addedDate"),
+ kind,
+ width,
+ height,
+ duration: asset
+ .pointer("/fields/duration/value")
+ .and_then(Value::as_f64)
+ .filter(|d| *d > 0.0),
+ filename: decoded(master, "filenameEnc"),
+ size: size("resOriginalFileSize"),
+ uti,
+ favorite: field::int(asset, "isFavorite") == Some(1),
+ hidden: field::int(asset, "isHidden") == Some(1),
+ deleted: field::int(asset, "isDeleted") == Some(1),
+ deleted_at: field::int(asset, "isDeleted")
+ .filter(|&d| d == 1)
+ .and(millis(asset, "recordModificationDate")),
+ subtype: field::int(asset, "assetSubtypeV2").unwrap_or(0),
+ change_tag: asset
+ .get("recordChangeTag")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ })
+}
+
+/// An asset's own fields laid over the photo it already is: what an asset-only change (a
+/// favourite, a delete) brings, when its master did not change.
+fn with_asset(mut p: Photo, asset: &Value) -> Photo {
+ if let Some(t) = millis(asset, "assetDate") {
+ p.taken_at = t;
+ }
+ p.added_at = millis(asset, "addedDate").or(p.added_at);
+ p.favorite = field::int(asset, "isFavorite") == Some(1);
+ p.hidden = field::int(asset, "isHidden") == Some(1);
+ p.deleted = field::int(asset, "isDeleted") == Some(1);
+ p.deleted_at = if p.deleted {
+ millis(asset, "recordModificationDate").or(p.deleted_at)
+ } else {
+ None
+ };
+ p.change_tag = asset
+ .get("recordChangeTag")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ p
+}
+
+/// A pass applied to the library: everything replaced on a full pass, merged on an incremental
+/// one. Answers how many photos changed, and every master's links seen, for the app to keep.
+pub fn apply(
+ library: &mut quince_core::Library,
+ fetched: PhotosFetch,
+) -> Result<(usize, HashMap<String, Links>)> {
+ let PhotosFetch {
+ records,
+ token,
+ incremental,
+ complete,
+ } = fetched;
+ let mut masters: HashMap<String, &Value> = HashMap::new();
+ let mut assets: Vec<&Value> = Vec::new();
+ let mut gone: Vec<String> = Vec::new();
+ let mut albums: Vec<Album> = Vec::new();
+ let mut albums_seen = false;
+ // Which photo is in which album: a relation record each, named `<asset>-IN-<album>`.
+ let mut in_albums: Vec<(String, String, i64)> = Vec::new();
+ let mut out_of_albums: Vec<(String, String)> = Vec::new();
+ for r in &records {
+ if r.get("deleted").and_then(Value::as_bool) == Some(true) {
+ if let Some(name) = field::record_name(r) {
+ match name.split_once("-IN-") {
+ Some((asset, album)) => {
+ out_of_albums.push((album.to_string(), asset.to_string()))
+ }
+ None => gone.push(name),
+ }
+ }
+ continue;
+ }
+ match field::record_type(r).as_deref() {
+ Some("CPLMaster") => {
+ if let Some(name) = field::record_name(r) {
+ masters.insert(name, r);
+ }
+ }
+ Some("CPLAsset") => assets.push(r),
+ Some("CPLContainerRelation") => {
+ let album = field::string(r, "containerId");
+ let asset = field::string(r, "itemId");
+ if let (Some(album), Some(asset)) = (album, asset) {
+ if field::int(r, "isDeleted") == Some(1) {
+ out_of_albums.push((album, asset));
+ } else {
+ in_albums.push((album, asset, field::int(r, "position").unwrap_or(0)));
+ }
+ }
+ }
+ Some("CPLAlbum") => {
+ albums_seen = true;
+ // Folders and smart albums are not albums a photo is put in.
+ if field::int(r, "isDeleted") != Some(1)
+ && field::int(r, "albumType").unwrap_or(0) == 0
+ {
+ if let (Some(id), Some(name)) =
+ (field::record_name(r), decoded(r, "albumNameEnc"))
+ {
+ albums.push(Album {
+ id,
+ name,
+ position: field::int(r, "position").unwrap_or(0),
+ change_tag: r
+ .get("recordChangeTag")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ });
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ let links: HashMap<String, Links> = masters
+ .iter()
+ .map(|(k, m)| (k.clone(), links_of(m)))
+ .collect();
+ let mut photos = Vec::new();
+ for a in assets {
+ let master = a
+ .pointer("/fields/masterRef/value/recordName")
+ .and_then(Value::as_str);
+ let built = match master.and_then(|m| masters.get(m)) {
+ Some(m) => photo_of(a, m),
+ // Only the asset changed: its flags laid over the photo already known.
+ None => field::record_name(a)
+ .and_then(|id| library.photo(&id).ok().flatten())
+ .map(|p| with_asset(p, a)),
+ };
+ if let Some(p) = built {
+ photos.push(p);
+ }
+ }
+ let changed = photos.len() + gone.len();
+ if incremental {
+ library.put_photos(&photos)?;
+ library.forget_photos(&gone)?;
+ library.put_album_items(&in_albums)?;
+ library.forget_album_items(&out_of_albums)?;
+ if albums_seen {
+ let mut all = library.albums()?;
+ all.retain(|a| !albums.iter().any(|b| b.id == a.id) && !gone.contains(&a.id));
+ all.extend(albums);
+ library.replace_albums(&all)?;
+ }
+ } else if complete {
+ // A full pass that finished is the whole truth; one that stopped early is not, and
+ // pruning on it would drop photos that are fine.
+ library.replace_photos(&photos)?;
+ library.replace_albums(&albums)?;
+ library.replace_album_items(&in_albums)?;
+ } else {
+ library.put_photos(&photos)?;
+ library.put_album_items(&in_albums)?;
+ }
+ if complete {
+ library.mark_synced(SERVICE, token.as_deref())?;
+ }
+ Ok((changed, links))
+}
+
+/// A photo's flag set, as icloud.com sets it: its `CPLAsset` record updated with the one
+/// field, against the asset's change tag. Favorite is `isFavorite`; Delete (to Recently
+/// Deleted, never for good) is `isDeleted: 1`; Recover is `isDeleted: 0`; Hide is `isHidden`.
+/// Answers the asset as Apple now holds it.
+pub async fn set_flag(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ asset: &str,
+ change_tag: Option<&str>,
+ flag: Flag,
+ on: bool,
+) -> Result<Value> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ let name = match flag {
+ Flag::Favorite => "isFavorite",
+ Flag::Deleted => "isDeleted",
+ Flag::Hidden => "isHidden",
+ };
+ client
+ .update_record(
+ ZONE,
+ asset,
+ "CPLAsset",
+ change_tag,
+ serde_json::json!({ name: { "value": i64::from(on) } }),
+ )
+ .await
+}
+
+/// The flags a photo carries that this app sets.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Flag {
+ Favorite,
+ Deleted,
+ Hidden,
+}
+
+/// One master's links, read from Apple now: for a picture whose cached link expired, or one
+/// never seen in this run.
+pub async fn links(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ master: &str,
+) -> Result<Option<Links>> {
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ Ok(client
+ .lookup_record(ZONE, master)
+ .await?
+ .map(|m| links_of(&m)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn master() -> Value {
+ json!({"recordName": "M1", "recordType": "CPLMaster", "fields": {
+ "itemType": {"value": "public.jpeg"},
+ "filenameEnc": {"value": base64::engine::general_purpose::STANDARD.encode("IMG_0001.JPG")},
+ "resOriginalWidth": {"value": 4032}, "resOriginalHeight": {"value": 3024},
+ "resOriginalFileSize": {"value": 2_400_000},
+ "resJPEGThumbRes": {"value": {"downloadURL": "https://cvws.example/thumb/${f}"}},
+ "resOriginalRes": {"value": {"downloadURL": "https://cvws.example/orig/${f}"}}
+ }})
+ }
+
+ fn asset(flags: Value) -> Value {
+ let mut fields = json!({
+ "masterRef": {"value": {"recordName": "M1"}},
+ "assetDate": {"value": 1_789_640_832_217_i64}, "addedDate": {"value": 1_792_337_452_485_i64},
+ "orientation": {"value": 6}
+ });
+ for (k, v) in flags.as_object().unwrap() {
+ fields[k] = json!({"value": v});
+ }
+ json!({"recordName": "A1", "recordType": "CPLAsset", "recordChangeTag": "t1", "fields": fields})
+ }
+
+ /// An asset and its master read as one photo: its date, size (turned for orientation 6),
+ /// name, flags and download links.
+ #[test]
+ fn an_asset_and_its_master_are_one_photo() {
+ let p = photo_of(&asset(json!({"isFavorite": 1})), &master()).unwrap();
+ assert_eq!((p.id.as_str(), p.master.as_str()), ("A1", "M1"));
+ assert_eq!(p.taken_at, 1_789_640_832);
+ assert_eq!(
+ (p.width, p.height),
+ (3024, 4032),
+ "orientation 6 is a portrait"
+ );
+ assert_eq!(p.filename.as_deref(), Some("IMG_0001.JPG"));
+ assert!(p.favorite && !p.deleted);
+ assert_eq!(p.kind, Kind::Image);
+ let l = links_of(&master());
+ assert_eq!(
+ l.thumb.as_deref(),
+ Some("https://cvws.example/thumb/thumb.jpg")
+ );
+ assert_eq!(
+ l.original.as_deref(),
+ Some("https://cvws.example/orig/original")
+ );
+ }
+
+ /// A full pass replaces the library; a later asset-only change (deleted) is laid over the
+ /// photo already known; an expunged asset goes.
+ #[test]
+ fn passes_build_and_keep_the_library() {
+ let mut lib = quince_core::Library::in_memory().unwrap();
+ let full = PhotosFetch {
+ records: vec![
+ master(),
+ asset(json!({})),
+ json!({"recordName": "A1-IN-AL", "recordType": "CPLContainerRelation", "fields": {"containerId": {"value": "AL"}, "itemId": {"value": "A1"}, "position": {"value": 1024}}}),
+ ],
+ token: Some("T1".into()),
+ incremental: false,
+ complete: true,
+ };
+ apply(&mut lib, full).unwrap();
+ assert_eq!(
+ lib.photos(quince_core::photos::View::Library)
+ .unwrap()
+ .len(),
+ 1
+ );
+ let change = PhotosFetch {
+ records: vec![asset(json!({"isDeleted": 1}))],
+ token: Some("T2".into()),
+ incremental: true,
+ complete: true,
+ };
+ apply(&mut lib, change).unwrap();
+ assert!(lib
+ .photos(quince_core::photos::View::Library)
+ .unwrap()
+ .is_empty());
+ let deleted = lib
+ .photos(quince_core::photos::View::RecentlyDeleted)
+ .unwrap();
+ assert_eq!(deleted.len(), 1);
+ assert_eq!(
+ deleted[0].filename.as_deref(),
+ Some("IMG_0001.JPG"),
+ "the master's details are kept"
+ );
+ let expunged = PhotosFetch {
+ records: vec![json!({"recordName": "A1", "deleted": true})],
+ token: Some("T3".into()),
+ incremental: true,
+ complete: true,
+ };
+ apply(&mut lib, expunged).unwrap();
+ assert!(lib.photo("A1").unwrap().is_none());
+ }
+}
diff --git a/probe/examples/notes_delete_now.rs b/probe/examples/notes_delete_now.rs
new file mode 100644
index 0000000..527c35b
--- /dev/null
+++ b/probe/examples/notes_delete_now.rs
@@ -0,0 +1,30 @@
+//! Live: one note in Recently Deleted deleted for good ("Delete Now"), by record name, with his
+//! say-so (2026-10-19: the damaged "Heli" note). Refused unless the note is in Recently Deleted.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let guid = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("note record name"))?;
+ 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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let mut lib = quince_core::Library::in_memory()?;
+ let fetched = quince_icloud::notes::fetch_cloudkit(&http, &root, p.clone(), None).await?;
+ quince_icloud::notes::apply_cloudkit(&mut lib, fetched)?;
+ let note = lib.note(&guid)?.ok_or_else(|| anyhow!("no such note"))?;
+ println!("note {:?} in folder {:?}", note.title, note.folder_guid);
+ if note.folder_guid.as_deref() != Some("TrashFolder-CloudKit") {
+ return Err(anyhow!("not in Recently Deleted; left alone"));
+ }
+ quince_icloud::notes::delete_cloudkit(&http, &root, p, &note).await?;
+ println!("deleted for good");
+ Ok(())
+}
diff --git a/probe/examples/photos_album.rs b/probe/examples/photos_album.rs
new file mode 100644
index 0000000..fee7ef4
--- /dev/null
+++ b/probe/examples/photos_album.rs
@@ -0,0 +1,103 @@
+//! Read-only: each album's contents, asked as icloud.com asks (CPLContainerRelationLiveByAssetDate
+//! with parentId), to see what comes back. Nothing is written.
+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 root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let params = p.clone();
+ let fetched = quince_icloud::photos::fetch(&http, &root, p, None).await?;
+ let mut lib = quince_core::Library::in_memory()?;
+ quince_icloud::photos::apply(&mut lib, fetched)?;
+ for album in lib.albums()? {
+ let body = json!({"query":{"recordType":"CPLContainerRelationLiveByAssetDate","filterBy":[
+ {"fieldName":"startRank","comparator":"EQUALS","fieldValue":{"value":0,"type":"INT64"}},
+ {"fieldName":"direction","comparator":"EQUALS","fieldValue":{"value":"ASCENDING","type":"STRING"}},
+ {"fieldName":"parentId","comparator":"EQUALS","fieldValue":{"value":album.id,"type":"STRING"}}]},
+ "zoneID":{"zoneName":"PrimarySync"},"resultsLimit":200});
+ let mut q = params.clone();
+ q.push(("remapEnums".into(), "true".into()));
+ let v: Value = http
+ .post(format!(
+ "{}/database/1/com.apple.photos.cloud/production/private/records/query",
+ root.trim_end_matches('/')
+ ))
+ .query(&q)
+ .header("content-type", "text/plain")
+ .body(body.to_string())
+ .send()
+ .await?
+ .json()
+ .await?;
+ let count_body = json!({"query":{"recordType":"HyperionIndexCountLookup","filterBy":[{"fieldName":"indexCountID","comparator":"IN","fieldValue":{"value":[format!("CPLContainerRelationNotDeletedByAssetDate:{}", album.id)],"type":"STRING_LIST"}}]},"zoneID":{"zoneName":"PrimarySync"}});
+ let c: Value = http
+ .post(format!(
+ "{}/database/1/com.apple.photos.cloud/production/private/records/query",
+ root.trim_end_matches('/')
+ ))
+ .query(&q)
+ .header("content-type", "text/plain")
+ .body(count_body.to_string())
+ .send()
+ .await?
+ .json()
+ .await?;
+ println!(
+ "{:?} count: {}",
+ album.name, c["records"][0]["fields"]["itemCount"]
+ );
+ if v.get("records").is_none() {
+ println!(
+ "{:?}: {}",
+ album.name,
+ v.to_string().chars().take(300).collect::<String>()
+ );
+ continue;
+ }
+ let records = v["records"].as_array().cloned().unwrap_or_default();
+ let kinds: Vec<String> = records
+ .iter()
+ .map(|r| r["recordType"].as_str().unwrap_or("?").to_string())
+ .collect();
+ let items: Vec<String> = records
+ .iter()
+ .filter(|r| r["recordType"] == "CPLContainerRelation")
+ .map(|r| {
+ r["fields"]["itemId"]["value"]
+ .as_str()
+ .unwrap_or("?")
+ .chars()
+ .take(8)
+ .collect()
+ })
+ .collect();
+ let known = items
+ .iter()
+ .filter(|i| {
+ lib.photos(quince_core::photos::View::Library)
+ .unwrap()
+ .iter()
+ .any(|p| p.id.starts_with(i.as_str()))
+ })
+ .count();
+ println!(
+ "{:?} ({}): {} records {:?}; relations {} (in library: {known})",
+ album.name,
+ album.id,
+ records.len(),
+ kinds.iter().collect::<std::collections::BTreeSet<_>>(),
+ items.len()
+ );
+ let _ = Value::Null;
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_apply.rs b/probe/examples/photos_apply.rs
new file mode 100644
index 0000000..2981eaa
--- /dev/null
+++ b/probe/examples/photos_apply.rs
@@ -0,0 +1,50 @@
+//! Read-only: his Photos library walked and applied to an in-memory library, each view's
+//! count and the newest few, and how many have links. Nothing is written to Apple.
+use anyhow::{anyhow, Result};
+use quince_core::photos::View;
+#[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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let fetched = quince_icloud::photos::fetch(&http, &root, p, None).await?;
+ let mut lib = quince_core::Library::in_memory()?;
+ let (changed, links) = quince_icloud::photos::apply(&mut lib, fetched)?;
+ println!(
+ "applied {changed}; links for {} masters ({} with a thumbnail)",
+ links.len(),
+ links.values().filter(|l| l.thumb.is_some()).count()
+ );
+ for v in [
+ View::Library,
+ View::Favorites,
+ View::Videos,
+ View::Screenshots,
+ View::Recents,
+ View::RecentlyDeleted,
+ ] {
+ println!("{v:?}: {}", lib.photos(v)?.len());
+ }
+ for ph in lib.photos(View::Library)?.iter().take(3) {
+ println!(
+ " {} {:?} {}x{} {:?} taken {}",
+ ph.id, ph.kind, ph.width, ph.height, ph.filename, ph.taken_at
+ );
+ }
+ for a in lib.albums()? {
+ let inside = lib.album_photos(&a.id)?;
+ let names: Vec<String> = inside
+ .iter()
+ .map(|p| p.filename.clone().unwrap_or_default())
+ .collect();
+ println!("album {:?}: {} photos {names:?}", a.name, inside.len());
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_fields.rs b/probe/examples/photos_fields.rs
new file mode 100644
index 0000000..5e230d8
--- /dev/null
+++ b/probe/examples/photos_fields.rs
@@ -0,0 +1,133 @@
+//! Read-only: every field the library's assets and masters carry, the item types present,
+//! and one video's and one Live Photo's fields in full, to model Photos on. Nothing is written.
+use anyhow::{anyhow, Result};
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, BTreeSet};
+#[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 ck"))?;
+ let (http, mut p) = (client.http().clone(), client.service_params());
+ p.push(("remapEnums".into(), "true".into()));
+ let url = format!(
+ "{}/database/1/com.apple.photos.cloud/production/private/records/query",
+ root.trim_end_matches('/')
+ );
+ for dir in ["DESCENDING", "ASCENDING"] {
+ for rank in [0i64, 1, 50, 133, 134] {
+ let body = json!({"query":{"recordType":"CPLAssetAndMasterByAssetDateWithoutHiddenOrDeleted","filterBy":[
+ {"fieldName":"direction","comparator":"EQUALS","fieldValue":{"value":dir,"type":"STRING"}},
+ {"fieldName":"startRank","comparator":"EQUALS","fieldValue":{"value":rank,"type":"INT64"}}]},
+ "zoneID":{"zoneName":"PrimarySync"},"resultsLimit":4});
+ let v: Value = http
+ .post(&url)
+ .query(&p)
+ .header("content-type", "text/plain")
+ .body(body.to_string())
+ .send()
+ .await?
+ .json()
+ .await?;
+ let names: Vec<String> = v["records"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|r| r["recordType"] == "CPLAsset")
+ .map(|r| {
+ format!(
+ "{}@{}",
+ &r["recordName"].as_str().unwrap_or("")[..6],
+ r["fields"]["assetDate"]["value"]
+ )
+ })
+ .collect();
+ println!(
+ "{dir} startRank={rank}: {names:?} more={}",
+ v.get("continuationMarker").is_some()
+ );
+ }
+ }
+ if std::env::var("ONLY_RANKS").is_ok() {
+ return Ok(());
+ }
+ let (mut keys_a, mut keys_m) = (BTreeSet::new(), BTreeSet::new());
+ let mut types: BTreeMap<String, u32> = BTreeMap::new();
+ let mut subtypes: BTreeMap<String, u32> = BTreeMap::new();
+ let mut shown = BTreeSet::new();
+ let mut rank = 0i64;
+ let mut total = 0;
+ loop {
+ let body = json!({"query":{"recordType":"CPLAssetAndMasterByAssetDateWithoutHiddenOrDeleted","filterBy":[
+ {"fieldName":"direction","comparator":"EQUALS","fieldValue":{"value":"DESCENDING","type":"STRING"}},
+ {"fieldName":"startRank","comparator":"EQUALS","fieldValue":{"value":rank,"type":"INT64"}}]},
+ "zoneID":{"zoneName":"PrimarySync"},"resultsLimit":200});
+ let v: Value = http
+ .post(&url)
+ .query(&p)
+ .header("content-type", "text/plain")
+ .body(body.to_string())
+ .send()
+ .await?
+ .json()
+ .await?;
+ let recs = v["records"].as_array().cloned().unwrap_or_default();
+ let assets = recs
+ .iter()
+ .filter(|r| r["recordType"] == "CPLAsset")
+ .count();
+ for r in &recs {
+ let f = r["fields"].as_object().cloned().unwrap_or_default();
+ if r["recordType"] == "CPLAsset" {
+ keys_a.extend(f.keys().cloned());
+ *subtypes
+ .entry(format!(
+ "{}",
+ f.get("assetSubtypeV2")
+ .map(|x| x["value"].clone())
+ .unwrap_or(Value::Null)
+ ))
+ .or_default() += 1;
+ } else {
+ keys_m.extend(f.keys().cloned());
+ let t = f
+ .get("itemType")
+ .and_then(|x| x["value"].as_str())
+ .unwrap_or("?")
+ .to_string();
+ *types.entry(t.clone()).or_default() += 1;
+ if (t.contains("movie")
+ || t.contains("mpeg")
+ || f.contains_key("resOriginalVidComplRes"))
+ && shown.insert("video")
+ || f.contains_key("resOriginalVidComplRes") && shown.insert("live")
+ {
+ let mut short = serde_json::Map::new();
+ for (k, x) in &f {
+ short.insert(
+ k.clone(),
+ json!(x.to_string().chars().take(90).collect::<String>()),
+ );
+ }
+ println!("MASTER {t}: {}", serde_json::to_string_pretty(&short)?);
+ }
+ }
+ }
+ total += assets;
+ if assets == 0 || recs.is_empty() {
+ break;
+ }
+ rank += assets as i64;
+ if total > 5000 {
+ break;
+ }
+ }
+ println!("assets: {total}\nitem types: {types:?}\nasset subtypes: {subtypes:?}\nasset keys: {keys_a:?}\nmaster keys: {keys_m:?}");
+ Ok(())
+}
diff --git a/probe/examples/photos_flags_live.rs b/probe/examples/photos_flags_live.rs
new file mode 100644
index 0000000..8e83e16
--- /dev/null
+++ b/probe/examples/photos_flags_live.rs
@@ -0,0 +1,79 @@
+//! Live, on one wallpaper he named as throwaway (2026-10-19): favorite then unfavorite, delete
+//! (to Recently Deleted) then recover, each read back from Apple. It ends as it began.
+use anyhow::{anyhow, Result};
+use quince_icloud::photos::Flag;
+#[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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let mut lib = quince_core::Library::in_memory()?;
+ quince_icloud::photos::apply(
+ &mut lib,
+ quince_icloud::photos::fetch(&http, &root, p.clone(), None).await?,
+ )?;
+ let photo = lib
+ .photos(quince_core::photos::View::Library)?
+ .into_iter()
+ .find(|x| {
+ x.filename
+ .as_deref()
+ .is_some_and(|n| n.starts_with("wildflower-meadows-wallpaper"))
+ })
+ .ok_or_else(|| anyhow!("the wallpaper is not in the library"))?;
+ println!(
+ "throwaway: {:?} {} favorite={} deleted={}",
+ photo.filename, photo.id, photo.favorite, photo.deleted
+ );
+ let zc =
+ quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.photos.cloud", p.clone());
+ let read = |name: &'static str| {
+ let (zc, id) = (&zc, photo.id.clone());
+ async move {
+ let r = zc
+ .lookup_record("PrimarySync", &id)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ anyhow::Ok((
+ quince_icloud::cloudkit::field::int(&r, name).unwrap_or(0),
+ r["recordChangeTag"].as_str().map(str::to_string),
+ ))
+ }
+ };
+ let steps = [
+ (Flag::Favorite, true, "isFavorite"),
+ (Flag::Favorite, false, "isFavorite"),
+ (Flag::Deleted, true, "isDeleted"),
+ (Flag::Deleted, false, "isDeleted"),
+ ];
+ for (flag, on, name) in steps {
+ let (_, tag) = read(name).await?;
+ quince_icloud::photos::set_flag(
+ &http,
+ &root,
+ p.clone(),
+ &photo.id,
+ tag.as_deref(),
+ flag,
+ on,
+ )
+ .await?;
+ let (now, _) = read(name).await?;
+ println!(
+ "{flag:?} → {on}: Apple holds {name}={now} {}",
+ if (now == 1) == on {
+ "✓"
+ } else {
+ "✗ MISMATCH"
+ }
+ );
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_push_live.rs b/probe/examples/photos_push_live.rs
new file mode 100644
index 0000000..dee04aa
--- /dev/null
+++ b/probe/examples/photos_push_live.rs
@@ -0,0 +1,74 @@
+//! Live: does Apple push a Photos change? A channel parked on com.apple.photos.cloud, then the
+//! throwaway wallpaper favorited and unfavorited (he named the wallpapers throwaway,
+//! 2026-10-19); prints when each push lands after its write. Ends as it began.
+use anyhow::{anyhow, Result};
+use quince_icloud::photos::Flag;
+#[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 device = client
+ .session()
+ .service_url("ckdeviceservice")
+ .ok_or_else(|| anyhow!("no ckdevice"))?;
+ let ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let ch = quince_icloud::push::open(
+ &http,
+ &device,
+ &p,
+ "PROBE-PHOTOS",
+ &["com.apple.photos.cloud"],
+ )
+ .await?;
+ let mut lib = quince_core::Library::in_memory()?;
+ quince_icloud::photos::apply(
+ &mut lib,
+ quince_icloud::photos::fetch(&http, &ck, p.clone(), None).await?,
+ )?;
+ let photo = lib
+ .photos(quince_core::photos::View::Library)?
+ .into_iter()
+ .find(|x| {
+ x.filename
+ .as_deref()
+ .is_some_and(|n| n.starts_with("wildflower-meadows-wallpaper"))
+ })
+ .ok_or_else(|| anyhow!("no wallpaper"))?;
+ for on in [true, false] {
+ let zc = quince_icloud::cloudkit::ZoneClient::new(
+ &http,
+ &ck,
+ "com.apple.photos.cloud",
+ p.clone(),
+ );
+ let tag = zc
+ .lookup_record("PrimarySync", &photo.id)
+ .await?
+ .and_then(|r| r["recordChangeTag"].as_str().map(str::to_string));
+ let t = std::time::Instant::now();
+ quince_icloud::photos::set_flag(
+ &http,
+ &ck,
+ p.clone(),
+ &photo.id,
+ tag.as_deref(),
+ Flag::Favorite,
+ on,
+ )
+ .await?;
+ let wrote = t.elapsed();
+ let got = quince_icloud::push::wait(&http, &ch, std::time::Duration::from_secs(20)).await?;
+ println!(
+ "favorite → {on}: written in {wrote:?}; push {got:?} {:?} after the write began",
+ t.elapsed()
+ );
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_upload_live.rs b/probe/examples/photos_upload_live.rs
new file mode 100644
index 0000000..c7250e9
--- /dev/null
+++ b/probe/examples/photos_upload_live.rs
@@ -0,0 +1,85 @@
+//! Live: one small test JPEG ("Quince upload test") uploaded to his library as icloud.com
+//! uploads one, Apple's answer printed, the new photo looked up, then sent to Recently Deleted.
+use anyhow::{anyhow, Result};
+use quince_icloud::photos::Flag;
+#[tokio::main]
+async fn main() -> Result<()> {
+ let path = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("jpeg path"))?;
+ 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 upload = client
+ .session()
+ .service_url("uploadimagews")
+ .ok_or_else(|| anyhow!("no uploadimagews"))?;
+ let ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let bytes = std::fs::read(&path)?;
+ let name = std::path::Path::new(&path)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .to_string();
+ let mut q: Vec<(String, String)> = p.clone();
+ q.push(("filename".into(), name.clone()));
+ q.push((
+ "lastModDate".into(),
+ (std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)?
+ .as_millis())
+ .to_string(),
+ ));
+ q.push(("timezoneOffset".into(), "-330".into()));
+ let t = std::time::Instant::now();
+ let r = http
+ .post(format!("{}/upload", upload.trim_end_matches('/')))
+ .query(&q)
+ .body(bytes)
+ .send()
+ .await?;
+ let status = r.status();
+ let text = r.text().await?;
+ println!(
+ "upload {name}: {status} in {:?}\n{}",
+ t.elapsed(),
+ text.chars().take(600).collect::<String>()
+ );
+ let v: serde_json::Value = serde_json::from_str(&text)?;
+ let zc =
+ quince_icloud::cloudkit::ZoneClient::new(&http, &ck, "com.apple.photos.cloud", p.clone());
+ let mut asset = None;
+ for rec in v["records"].as_array().into_iter().flatten() {
+ let n = rec["recordName"].as_str().unwrap_or("");
+ let found = zc.lookup_record("PrimarySync", n).await?;
+ println!(
+ "{} {n}: in the zone now: {}",
+ rec["recordType"],
+ found.is_some()
+ );
+ if rec["recordType"] == "CPLAsset" {
+ asset = found;
+ }
+ }
+ if let Some(a) = asset {
+ let name = quince_icloud::cloudkit::field::record_name(&a).unwrap_or_default();
+ quince_icloud::photos::set_flag(
+ &http,
+ &ck,
+ p,
+ &name,
+ a["recordChangeTag"].as_str(),
+ Flag::Deleted,
+ true,
+ )
+ .await?;
+ println!("test photo sent to Recently Deleted");
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_upload_v2.rs b/probe/examples/photos_upload_v2.rs
new file mode 100644
index 0000000..88deaa6
--- /dev/null
+++ b/probe/examples/photos_upload_v2.rs
@@ -0,0 +1,122 @@
+//! Live: one small test JPEG ("Quince upload test") through icloud.com's current upload
+//! (photosupload: createUploadUrl → bytes → putAsset → uploadStatus), each answer printed, the
+//! new photo looked up, then sent to Recently Deleted.
+use anyhow::{anyhow, Result};
+use quince_icloud::photos::Flag;
+use serde_json::{json, Value};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let path = std::env::args()
+ .nth(1)
+ .ok_or_else(|| anyhow!("jpeg path"))?;
+ 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 up = client
+ .session()
+ .service_url("photosupload")
+ .ok_or_else(|| anyhow!("no photosupload"))?;
+ let ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let dsid = p
+ .iter()
+ .find(|(k, _)| k == "dsid")
+ .map(|(_, v)| v.clone())
+ .ok_or_else(|| anyhow!("no dsid"))?;
+ let call = |endpoint: &str, body: Value| {
+ let (http, url, dsid) = (
+ http.clone(),
+ format!("{}/photosupload/{endpoint}", up.trim_end_matches('/')),
+ dsid.clone(),
+ );
+ async move {
+ let r = http
+ .post(url)
+ .query(&[("dsid", dsid)])
+ .header("content-type", "text/plain;charset=UTF-8")
+ .body(body.to_string())
+ .send()
+ .await?;
+ let s = r.status();
+ let t = r.text().await?;
+ println!(" {s} {}", t.chars().take(400).collect::<String>());
+ anyhow::Ok(serde_json::from_str::<Value>(&t).unwrap_or(Value::Null))
+ }
+ };
+ let bytes = std::fs::read(&path)?;
+ let name = std::path::Path::new(&path)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .to_string();
+ let id = uuid::Uuid::new_v4().to_string();
+ println!("createUploadUrl");
+ let urls = call(
+ "createUploadUrl",
+ json!({"zoneName": "PrimarySync", "assets": {&id: bytes.len()}}),
+ )
+ .await?;
+ let url = urls["uploadUrls"][&id]
+ .as_str()
+ .ok_or_else(|| anyhow!("no upload url"))?
+ .to_string();
+ println!("bytes → upload url");
+ let r = http
+ .post(&url)
+ .header("content-type", "text/plain")
+ .body(bytes)
+ .send()
+ .await?;
+ let s = r.status();
+ let receipt: Value = serde_json::from_str(&r.text().await?).unwrap_or(Value::Null);
+ println!(
+ " {s} isDuplicate={} singleFile keys={:?}",
+ receipt["isDuplicate"],
+ receipt["singleFile"]
+ .as_object()
+ .map(|o| o.keys().collect::<Vec<_>>())
+ );
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)?
+ .as_millis() as i64;
+ println!("putAsset");
+ let put = call("putAsset", json!({"zoneName": "PrimarySync", "localTimeZoneId": "Asia/Kolkata", "importGroup": uuid::Uuid::new_v4().to_string(),
+ "files": [{"fileName": name, "lastModDate": now, "timeZoneOffset": -330, "singleFileUploadRequest": receipt["singleFile"]}]})).await?;
+ let job = put[0]["uploadJobId"]
+ .as_str()
+ .ok_or_else(|| anyhow!("no job"))?
+ .to_string();
+ let asset = put[0]["cplAsset"].as_str().unwrap_or("").to_string();
+ for i in 0..30 {
+ tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
+ println!("uploadStatus #{i}");
+ let st = call("uploadStatus", json!({"uploadJobIds": [&job]})).await?;
+ let s = &st[&job];
+ if s.get("errorCode").is_some() || s["progress"].as_f64().unwrap_or(0.0) >= 100.0 {
+ break;
+ }
+ }
+ let zc =
+ quince_icloud::cloudkit::ZoneClient::new(&http, &ck, "com.apple.photos.cloud", p.clone());
+ let rec = zc.lookup_record("PrimarySync", &asset).await?;
+ println!("asset {asset} in the zone: {}", rec.is_some());
+ if let Some(a) = rec {
+ quince_icloud::photos::set_flag(
+ &http,
+ &ck,
+ p,
+ &asset,
+ a["recordChangeTag"].as_str(),
+ Flag::Deleted,
+ true,
+ )
+ .await?;
+ println!("test photo sent to Recently Deleted");
+ }
+ Ok(())
+}
diff --git a/probe/examples/photos_walk.rs b/probe/examples/photos_walk.rs
new file mode 100644
index 0000000..8799f5b
--- /dev/null
+++ b/probe/examples/photos_walk.rs
@@ -0,0 +1,69 @@
+//! Read-only: the Photos zone walked through its change feed — record types, how long, whether
+//! assets carry their image links, and the sync token for later passes. Nothing is written.
+use anyhow::{anyhow, Result};
+use std::collections::BTreeMap;
+#[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 ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.photos.cloud", p);
+ let t = std::time::Instant::now();
+ let walk = zc.all_records("PrimarySync", None).await?;
+ let mut types: BTreeMap<String, u32> = BTreeMap::new();
+ let (mut with_thumb, mut deleted, mut hidden) = (0, 0, 0);
+ for r in &walk.records {
+ *types
+ .entry(r["recordType"].as_str().unwrap_or("(gone)").to_string())
+ .or_default() += 1;
+ let f = &r["fields"];
+ if f["resJPEGThumbRes"]["value"]["downloadURL"].is_string() {
+ with_thumb += 1;
+ }
+ if f["isDeleted"]["value"] == 1 {
+ deleted += 1;
+ }
+ if f["isHidden"]["value"] == 1 {
+ hidden += 1;
+ }
+ }
+ println!(
+ "walked in {:?}: {} records, complete={}, token={}",
+ t.elapsed(),
+ walk.records.len(),
+ walk.complete,
+ walk.token.is_some()
+ );
+ println!("types: {types:?}");
+ if let Some(r) = walk
+ .records
+ .iter()
+ .find(|r| r["recordType"] == "CPLContainerRelation")
+ {
+ println!(
+ "relation: {}",
+ serde_json::to_string(r)?
+ .chars()
+ .take(700)
+ .collect::<String>()
+ );
+ }
+ println!(
+ "masters with a thumbnail link: {with_thumb}; assets deleted: {deleted}; hidden: {hidden}"
+ );
+ let t = std::time::Instant::now();
+ let again = zc.all_records("PrimarySync", walk.token.as_deref()).await?;
+ println!(
+ "incremental pass from the token: {} records in {:?}",
+ again.records.len(),
+ t.elapsed()
+ );
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 6d41474..10f9a63 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod alerts;
+mod photos;
mod push;
mod refresh;
@@ -91,6 +92,8 @@ pub static CONTACTS_PASS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new
/// listing last and the rename looked undone. Held from fetch to store, the re-read after a
/// write — which starts only once the write is made — always lands last.
pub static DRIVE_PASS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+/// One Photos pass at a time, from reading its sync position through storing what came back.
+pub static PHOTOS_PASS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
async fn refresh_reminders(
http: &reqwest::Client,
@@ -2236,23 +2239,51 @@ async fn contacts_export(
/// Add everyone in a vCard file to Contacts. Answers how many came in and how many could not.
#[tauri::command]
async fn contacts_import(
- path: String,
+ paths: Vec<String>,
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<(usize, usize)> {
let _one = CONTACTS_PASS.lock().await;
- let text =
- std::fs::read_to_string(&path).map_err(|e| format!("Couldn't read that file: {e}"))?;
+ // Every file chosen, vCard or CSV (Google Contacts, Outlook), read into cards first, so a
+ // file that cannot be read stops the import before anything is sent.
+ let mut cards = Vec::new();
+ let mut unreadable = 0;
+ for path in &paths {
+ let text = std::fs::read_to_string(path).map_err(|e| {
+ format!(
+ "Couldn't read {}: {e}",
+ std::path::Path::new(path)
+ .file_name()
+ .map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())
+ )
+ })?;
+ if path.to_ascii_lowercase().ends_with(".csv") {
+ let (from_csv, skipped) = quince_icloud::contacts::csv_to_vcards(&text);
+ cards.extend(from_csv);
+ unreadable += skipped;
+ } else {
+ cards.extend(quince_icloud::contacts::split_vcards(&text));
+ }
+ }
+ if cards.is_empty() {
+ return Err("Those files hold no contacts.".into());
+ }
let (http, root, params) = contacts_context(&auth).await?;
let (_, tokens) = quince_icloud::contacts::fetch_with_tokens(&http, &root, params.clone())
.await
.map_err(|e| e.to_string())?;
- let (ids, failed) =
- quince_icloud::contacts::import_vcards(&http, &root, params.clone(), &tokens, &text)
- .await
- .map_err(|e| e.to_string())?;
+ // In batches Apple takes in one import: well under its 10 MB, a few hundred cards each.
+ let mut imported = 0;
+ for batch in quince_icloud::contacts::batch_vcards(&cards, 8 * 1024 * 1024, 400) {
+ let (ids, failed) =
+ quince_icloud::contacts::import_vcards(&http, &root, params.clone(), &tokens, &batch)
+ .await
+ .map_err(|e| e.to_string())?;
+ imported += ids.len();
+ unreadable += failed;
+ }
settle(resync_contacts(&http, &root, params, &data).await)?;
- Ok((ids.len(), failed))
+ Ok((imported, unreadable))
}
/// The card that is this person's own, as the last pass stored it.
@@ -3446,6 +3477,27 @@ fn tiling_compositor() -> bool {
})
}
+/// The window, shown once its first frame is drawn. It is made hidden, so a launch never shows
+/// an empty or half-drawn window that then flickers into the app: the page says when it has
+/// painted, and the window appears whole. Shown anyway after a few seconds, so a page that
+/// never says so still leaves a window to use.
+#[tauri::command]
+fn window_ready(app: tauri::AppHandle) {
+ show_window(&app);
+}
+
+fn show_when_ready(app: &tauri::AppHandle) {
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ if let Some(w) = app.get_webview_window("main") {
+ if !w.is_visible().unwrap_or(true) {
+ show_window(&app);
+ }
+ }
+ });
+}
+
/// Bring the window back, wherever it went.
fn show_window(app: &tauri::AppHandle) {
if let Some(window) = app.get_webview_window("main") {
@@ -3545,7 +3597,23 @@ fn main() {
let uri = request.uri();
let wanted = photo_guid(uri.host(), uri.path());
let attachment = note_part(uri.path());
+ let picture = photos::requested(uri.path());
tauri::async_runtime::spawn(async move {
+ // A photo's picture: from the disk cache, or fetched from Apple once and kept.
+ if let Some((id, size)) = picture {
+ let response = match photos::picture(&app, &id, size).await {
+ Ok(bytes) => tauri::http::Response::builder()
+ .status(200)
+ .header("Content-Type", photos::content_type(&bytes, size))
+ .header("Cache-Control", "private, max-age=86400")
+ .body(bytes),
+ Err(_) => tauri::http::Response::builder()
+ .status(404)
+ .body(Vec::new()),
+ };
+ responder.respond(response.unwrap_or_default());
+ return;
+ }
// A note's picture, or the rendering of a document or film in it.
if let Some((id, part)) = attachment {
let response = match note_media_cached(&app, &id, part).await {
@@ -3630,6 +3698,7 @@ fn main() {
if let Err(e) = build_tray(app) {
eprintln!("no tray on this desktop, so closing the window quits: {e}");
}
+ show_when_ready(app.handle());
Ok(())
})
.invoke_handler(tauri::generate_handler![
@@ -3683,6 +3752,14 @@ fn main() {
note_runs,
note_table,
note_table_set_cell,
+ window_ready,
+ photos::photos_list,
+ photos::photos_counts,
+ photos::photos_albums,
+ photos::photos_in_album,
+ photos::photo_set_flag,
+ photos::photo_play,
+ photos::photo_download,
note_table_add_row,
note_table_remove,
note_attachment_info,
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
new file mode 100644
index 0000000..fc8f7cf
--- /dev/null
+++ b/src-tauri/src/photos.rs
@@ -0,0 +1,337 @@
+//! Photos in the app: the library's commands, the pictures served to the window from a disk
+//! cache, and the download links Apple hands out (which expire) kept in memory only.
+//!
+//! A picture is fetched from Apple once, the first time it is drawn, and kept under the
+//! app's state directory by size; after that the grid is drawn from disk. A link older than
+//! LINK_LIFE, or one this run never saw, is asked of Apple again before a fetch.
+
+use crate::{Auth, Data, UiResult};
+use quince_core::photos::{Photo, View};
+use quince_icloud::photos::Links;
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+use tauri::{AppHandle, Manager, State};
+
+/// How long a download link from Apple is trusted before it is asked for again.
+const LINK_LIFE: Duration = Duration::from_secs(45 * 60);
+
+/// Every master's links seen this run, and when.
+static LINKS: Mutex<Option<HashMap<String, (Links, Instant)>>> = Mutex::new(None);
+
+/// Links a pass brought, kept for the pictures it will be asked for.
+pub fn remember(links: HashMap<String, Links>) {
+ let now = Instant::now();
+ let mut kept = LINKS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let map = kept.get_or_insert_with(HashMap::new);
+ for (master, l) in links {
+ map.insert(master, (l, now));
+ }
+}
+
+fn fresh_links(master: &str) -> Option<Links> {
+ let kept = LINKS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ kept.as_ref()?
+ .get(master)
+ .filter(|(_, at)| at.elapsed() < LINK_LIFE)
+ .map(|(l, _)| l.clone())
+}
+
+/// Which of a photo's pictures is wanted.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Size {
+ Thumb,
+ Medium,
+ Original,
+ Video,
+}
+
+impl Size {
+ fn name(self) -> &'static str {
+ match self {
+ Size::Thumb => "thumb",
+ Size::Medium => "medium",
+ Size::Original => "original",
+ Size::Video => "video",
+ }
+ }
+ fn pick(self, l: &Links) -> Option<String> {
+ match self {
+ Size::Thumb => l.thumb.clone(),
+ Size::Medium => l.medium.clone().or_else(|| l.thumb.clone()),
+ Size::Original => l.original.clone(),
+ Size::Video => l.video.clone(),
+ }
+ }
+}
+
+/// The photo and picture a `quince://` request asks for: `pic/<asset id>/<size>`, escaped as
+/// Tauri escapes it.
+pub fn requested(path: &str) -> Option<(String, Size)> {
+ let path = crate::percent_decode(path.trim_start_matches('/'));
+ let rest = path.strip_prefix("pic/")?;
+ let (id, size) = rest.rsplit_once('/')?;
+ let size = match size {
+ "thumb" => Size::Thumb,
+ "medium" => Size::Medium,
+ "original" => Size::Original,
+ "video" => Size::Video,
+ _ => return None,
+ };
+ // An asset id is a record name: letters, digits and dashes only, never a path.
+ if id.is_empty()
+ || !id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+ {
+ return None;
+ }
+ Some((id.to_string(), size))
+}
+
+fn cache_path(app: &AppHandle, id: &str, size: Size) -> PathBuf {
+ crate::state_dir(app)
+ .join("photos")
+ .join(size.name())
+ .join(id)
+}
+
+/// One picture of a photo: from the disk cache, or fetched from Apple once and kept.
+pub async fn picture(app: &AppHandle, id: &str, size: Size) -> Result<Vec<u8>, String> {
+ let path = cache_path(app, id, size);
+ if let Ok(bytes) = tokio::fs::read(&path).await {
+ return Ok(bytes);
+ }
+ let photo = {
+ let data = app.state::<Data>();
+ let library = data.0.lock().await;
+ library
+ .photo(id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?
+ };
+ let auth = app.state::<Auth>();
+ let (http, root, params) = crate::cloudkit_context(&auth).await?;
+ // A cached link first; a fresh one from Apple when it has none or Apple refuses the old.
+ let fetch = |url: String| {
+ let http = http.clone();
+ async move {
+ let r = http.get(&url).send().await.map_err(|e| e.to_string())?;
+ if !r.status().is_success() {
+ return Err(format!("Apple answered {}", r.status()));
+ }
+ r.bytes()
+ .await
+ .map(|b| b.to_vec())
+ .map_err(|e| e.to_string())
+ }
+ };
+ let cached = fresh_links(&photo.master).and_then(|l| size.pick(&l));
+ let bytes = match cached {
+ Some(url) => match fetch(url).await {
+ Ok(b) => b,
+ Err(_) => fetch(new_link(&http, &root, params, &photo, size).await?).await?,
+ },
+ None => fetch(new_link(&http, &root, params, &photo, size).await?).await?,
+ };
+ if let Some(dir) = path.parent() {
+ tokio::fs::create_dir_all(dir).await.ok();
+ }
+ // Written beside and moved into place, so a half-written picture is never served.
+ let partial = path.with_extension("part");
+ if tokio::fs::write(&partial, &bytes).await.is_ok() {
+ tokio::fs::rename(&partial, &path).await.ok();
+ }
+ Ok(bytes)
+}
+
+async fn new_link(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ photo: &Photo,
+ size: Size,
+) -> Result<String, String> {
+ let links = quince_icloud::photos::links(http, root, params, &photo.master)
+ .await
+ .map_err(|e| e.to_string())?
+ .ok_or("Apple no longer has that photo.")?;
+ remember(HashMap::from([(photo.master.clone(), links.clone())]));
+ size.pick(&links)
+ .ok_or_else(|| "That photo has no picture of that size.".into())
+}
+
+/// What a picture's bytes are, for the window to draw them.
+pub fn content_type(bytes: &[u8], size: Size) -> &'static str {
+ if size == Size::Video || bytes.get(4..8) == Some(b"ftyp") {
+ return "video/mp4";
+ }
+ crate::image_type(bytes)
+}
+
+/// A view's photos, newest first.
+#[tauri::command]
+pub async fn photos_list(view: View, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
+ data.0.lock().await.photos(view).map_err(|e| e.to_string())
+}
+
+/// The albums the person made, each with how many photos it holds.
+#[tauri::command]
+pub async fn photos_albums(
+ data: State<'_, Data>,
+) -> UiResult<Vec<(quince_core::photos::Album, usize)>> {
+ let library = data.0.lock().await;
+ let albums = library.albums().map_err(|e| e.to_string())?;
+ albums
+ .into_iter()
+ .map(|a| {
+ let n = library
+ .album_photos(&a.id)
+ .map_err(|e| e.to_string())?
+ .len();
+ Ok((a, n))
+ })
+ .collect()
+}
+
+/// One album's photos, in its order.
+#[tauri::command]
+pub async fn photos_in_album(album: String, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
+ data.0
+ .lock()
+ .await
+ .album_photos(&album)
+ .map_err(|e| e.to_string())
+}
+
+/// Favorite, Delete (to Recently Deleted, never for good) or Recover a photo, as icloud.com
+/// does it: the asset's one field updated against its change tag. The library takes Apple's
+/// answer at once, so every view shows it without waiting for the next pass.
+#[tauri::command]
+pub async fn photo_set_flag(
+ id: String,
+ flag: quince_icloud::photos::Flag,
+ on: bool,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Photo> {
+ let _one = crate::PHOTOS_PASS.lock().await;
+ let photo = data
+ .0
+ .lock()
+ .await
+ .photo(&id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?;
+ let (http, root, params) = crate::cloudkit_context(&auth).await?;
+ let answer = quince_icloud::photos::set_flag(
+ &http,
+ &root,
+ params,
+ &id,
+ photo.change_tag.as_deref(),
+ flag,
+ on,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ let mut updated = photo;
+ match flag {
+ quince_icloud::photos::Flag::Favorite => updated.favorite = on,
+ quince_icloud::photos::Flag::Hidden => updated.hidden = on,
+ quince_icloud::photos::Flag::Deleted => {
+ updated.deleted = on;
+ updated.deleted_at = on.then(|| jiff::Timestamp::now().as_second());
+ }
+ }
+ updated.change_tag = answer
+ .get("recordChangeTag")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ .or(updated.change_tag);
+ data.0
+ .lock()
+ .await
+ .put_photos(std::slice::from_ref(&updated))
+ .map_err(|e| e.to_string())?;
+ Ok(updated)
+}
+
+/// A video opened in this computer's own player. WebKitGTK plays nothing without GStreamer's
+/// codec plugins, which many systems (his among them) do not have, so a video is fetched once,
+/// kept beside the other pictures under its own name, and handed to the system's player.
+#[tauri::command]
+pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> UiResult<()> {
+ let photo = data
+ .0
+ .lock()
+ .await
+ .photo(&id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?;
+ let size = if photo.kind == quince_core::photos::Kind::Video {
+ Size::Original
+ } else {
+ Size::Video
+ };
+ let bytes = picture(&app, &id, size).await?;
+ let name = photo
+ .filename
+ .filter(|n| !n.contains('/') && !n.starts_with('.'))
+ .unwrap_or_else(|| format!("{id}.mp4"));
+ let dir = crate::state_dir(&app).join("photos").join("open").join(&id);
+ tokio::fs::create_dir_all(&dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ let path = dir.join(name);
+ if tokio::fs::metadata(&path).await.is_err() {
+ tokio::fs::write(&path, bytes)
+ .await
+ .map_err(|e| e.to_string())?;
+ }
+ use tauri_plugin_opener::OpenerExt;
+ app.opener()
+ .open_path(path.to_string_lossy(), None::<&str>)
+ .map_err(|e| format!("No app on this computer opens that video: {e}"))
+}
+
+/// How many photos each view holds.
+#[tauri::command]
+pub async fn photos_counts(data: State<'_, Data>) -> UiResult<Vec<(View, i64)>> {
+ data.0
+ .lock()
+ .await
+ .photo_counts()
+ .map_err(|e| e.to_string())
+}
+
+/// A photo's original saved to Downloads under its own name; answers where.
+#[tauri::command]
+pub async fn photo_download(id: String, app: AppHandle, data: State<'_, Data>) -> UiResult<String> {
+ let photo = data
+ .0
+ .lock()
+ .await
+ .photo(&id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?;
+ let bytes = picture(&app, &id, Size::Original).await?;
+ let dir = app
+ .path()
+ .download_dir()
+ .map_err(|_| "There is no Downloads folder to save to.")?;
+ let name = photo
+ .filename
+ .filter(|n| !n.contains('/') && !n.starts_with('.'))
+ .unwrap_or_else(|| format!("Photo {}", &id[..id.len().min(8)]));
+ let path = crate::free_path(&dir, &name);
+ tokio::fs::write(&path, bytes)
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(path.display().to_string())
+}
diff --git a/src-tauri/src/push.rs b/src-tauri/src/push.rs
index bcd4166..f830516 100644
--- a/src-tauri/src/push.rs
+++ b/src-tauri/src/push.rs
@@ -13,10 +13,12 @@ use std::time::{Duration, Instant};
use tauri::{Emitter, Manager};
use tokio::sync::{mpsc, Mutex};
-/// The containers one connection listens to, and the service each one is.
-const CONTAINERS: [(&str, &str); 2] = [
+/// The containers one connection listens to, and the service each one is. Photos measured
+/// live (2026-10-19): a change made elsewhere arrives 0.7 to 1.5 seconds after it is written.
+const CONTAINERS: [(&str, &str); 3] = [
("com.apple.notes", "notes"),
("com.apple.reminders", "reminders"),
+ ("com.apple.photos.cloud", "photos"),
];
/// How long one wait is left parked before it is parked afresh. Apple answers sooner when
@@ -268,6 +270,7 @@ mod tests {
fn each_container_is_its_service() {
assert_eq!(service_of("com.apple.notes"), Some("notes"));
assert_eq!(service_of("com.apple.reminders"), Some("reminders"));
- assert_eq!(service_of("com.apple.photos.cloud"), None);
+ assert_eq!(service_of("com.apple.photos.cloud"), Some("photos"));
+ assert_eq!(service_of("com.apple.clouddocs"), None);
}
}
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
index 0f56725..90333fb 100644
--- a/src-tauri/src/refresh.rs
+++ b/src-tauri/src/refresh.rs
@@ -66,12 +66,13 @@ pub struct Refresh {
const FULL_SYNC_EVERY: i64 = 24 * 60 * 60;
/// The services one pass covers, in the order a person would notice them going stale.
-const COVERED: [(&str, &str); 5] = [
+const COVERED: [(&str, &str); 6] = [
("calendar", "Calendar"),
("reminders", "Reminders"),
("notes", "Notes"),
("contacts", "Contacts"),
("drive", "iCloud Drive"),
+ ("photos", "Photos"),
];
/// The calendar window a background refresh keeps warm: the month behind, so last week is
@@ -290,6 +291,32 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
});
}
+ // Photos: the whole library through the change feed once, then only what changed — under
+ // half a second when nothing did. Fetched and stored as one: see `PHOTOS_PASS`.
+ if wanted("photos") {
+ reports.push(match ctx.cloudkit.as_deref() {
+ None => unavailable("photos", "Photos"),
+ Some(root) => {
+ let _one = crate::PHOTOS_PASS.lock().await;
+ let since = token(data, quince_icloud::photos::SERVICE).await;
+ let fetched = quince_icloud::photos::fetch(
+ &ctx.http,
+ root,
+ ctx.params.clone(),
+ since.as_deref(),
+ )
+ .await;
+ store("photos", "Photos", data, fetched, |library, f| {
+ let (_, links) = quince_icloud::photos::apply(library, f)?;
+ crate::photos::remember(links);
+ let n = library.photos(quince_core::photos::View::Library)?.len();
+ Ok(format!("{n} photo{}", plural(n)))
+ })
+ .await
+ }
+ });
+ }
+
let available: Vec<&str> = reports
.iter()
.filter(|r| r.outcome != Outcome::Unavailable)
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 94d5cb6..cae1876 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -17,6 +17,7 @@
"minHeight": 400,
"resizable": true,
"center": true,
+ "visible": false,
"theme": null
}
],
diff --git a/src/App.tsx b/src/App.tsx
index 1b79745..1636b9d 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -9,6 +9,20 @@ type Phase = "checking" | "signin" | "code" | "library";
export default function App() {
const [phase, setPhase] = useState<Phase>("checking");
+ // The window is shown once the first real screen (the library, or sign-in) has been drawn:
+ // never the session check before it, never a half-drawn frame (see window_ready, main.rs).
+ const [shown, setShown] = useState(false);
+ useEffect(() => {
+ if (shown || phase === "checking") return;
+ setShown(true);
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ import("@tauri-apps/api/core")
+ .then(({ invoke }) => invoke("window_ready"))
+ .catch(() => {});
+ }),
+ );
+ }, [phase, shown]);
// On launch, try the stored session before showing anything. This is the whole promise:
// a returning user should never see the sign-in screen.
diff --git a/src/components/AppIcon.tsx b/src/components/AppIcon.tsx
index 0348658..e4eecce 100644
--- a/src/components/AppIcon.tsx
+++ b/src/components/AppIcon.tsx
@@ -116,6 +116,29 @@ export function AppIcon({ app, size = 22 }: { app: string; size?: number }) {
</>
);
break;
+ case "photos":
+ // A picture in its frame: sky, the sun, two hills. Not Apple's pinwheel, which is theirs.
+ art = (
+ <>
+ <defs>
+ <linearGradient id={`${id}s`} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stopColor="#5ac8fa" />
+ <stop offset="1" stopColor="#a2e1ff" />
+ </linearGradient>
+ <clipPath id={`${id}c`}>
+ <rect x="3.4" y="4.6" width="17.2" height="14.8" rx="2.4" />
+ </clipPath>
+ </defs>
+ <g clipPath={`url(#${id}c)`}>
+ <rect x="3.4" y="4.6" width="17.2" height="14.8" fill={`url(#${id}s)`} />
+ <circle cx="15.9" cy="9" r="2.1" fill="#ffd60a" />
+ <path d="M3.4 17.2l5-5.6 4.2 4.4 2.4-2.6 5.6 5.8v.2H3.4z" fill="#34c759" />
+ <path d="M3.4 19.4l6.4-4.6 4.6 4.6z" fill="#248a3d" />
+ </g>
+ <rect x="3.4" y="4.6" width="17.2" height="14.8" rx="2.4" fill="none" stroke="#000" strokeOpacity="0.12" strokeWidth="0.4" />
+ </>
+ );
+ break;
default:
return <span style={s} aria-hidden="true" />;
}
diff --git a/src/components/UploadTray.tsx b/src/components/UploadTray.tsx
index b119fbb..044a23a 100644
--- a/src/components/UploadTray.tsx
+++ b/src/components/UploadTray.tsx
@@ -111,6 +111,23 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onD
return () => window.clearTimeout(t);
}, [uploads.length, active, anyFailed, onDismiss]);
+ // Away from the window, WebKit stops drawing while the upload goes on; coming back, the
+ // bars jump to where the upload has got to instead of replaying every step at once.
+ const [instant, setInstant] = useState(false);
+ useEffect(() => {
+ const back = () => {
+ if (document.visibilityState !== "visible") return;
+ setInstant(true);
+ requestAnimationFrame(() => requestAnimationFrame(() => setInstant(false)));
+ };
+ document.addEventListener("visibilitychange", back);
+ window.addEventListener("focus", back);
+ return () => {
+ document.removeEventListener("visibilitychange", back);
+ window.removeEventListener("focus", back);
+ };
+ }, []);
+
if (uploads.length === 0) return null;
const batches = [...new Set(uploads.filter((u) => !ended(u)).map((u) => u.batch))];
const heading = active
@@ -123,8 +140,9 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onD
? `${items[0].name} uploaded`
: `${files.length} uploaded`;
+
return (
- <section className="upload-tray" aria-label="Uploads" aria-live="polite">
+ <section className={`upload-tray${instant ? " is-instant" : ""}`} aria-label="Uploads" aria-live="polite">
<header className="upload-tray-head">
<span className="upload-tray-title">{heading}</span>
{active ? (
@@ -142,7 +160,7 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onD
</header>
{active && (
<div className={`upload-bar${allPlanned ? "" : " is-waiting"}`} aria-hidden="true">
- <span style={{ width: allPlanned ? `${percent}%` : undefined }} />
+ <span style={allPlanned ? { transform: `scaleX(${percent / 100})` } : undefined} />
</div>
)}
<ul className="upload-rows">
@@ -160,7 +178,7 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onD
<span className="upload-name">{item.name}</span>
{running && (item.folder ? planned.has(item.files[0]?.batch ?? "") : true) && (
<span className="upload-bar small" aria-hidden="true">
- <span style={{ width: `${p}%` }} />
+ <span style={{ transform: `scaleX(${p / 100})` }} />
</span>
)}
{!running && !item.folder && failed[0]?.error && <span className="upload-where">{failed[0].error}</span>}
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index fc78a08..ffe83e2 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -86,6 +86,18 @@ export const api = {
calendarEvents: (from: number, to: number) =>
invoke<CalendarEvent[]>("calendar_events", { from, to }),
calendarList: () => invoke<Calendar[]>("calendar_list"),
+ photosList: (view: PhotoView) => invoke<Photo[]>("photos_list", { view }),
+ photosCounts: () => invoke<[PhotoView, number][]>("photos_counts"),
+ /** The albums the person made, each with how many photos it holds. */
+ photosAlbums: () => invoke<[PhotoAlbum, number][]>("photos_albums"),
+ photosInAlbum: (album: string) => invoke<Photo[]>("photos_in_album", { album }),
+ /** A video (or a Live Photo's moving part) opened in this computer's own player. */
+ photoPlay: (id: string) => invoke<void>("photo_play", { id }),
+ /** Favorite, Delete (to Recently Deleted) or Recover; answers the photo as Apple now has it. */
+ photoSetFlag: (id: string, flag: "favorite" | "deleted" | "hidden", on: boolean) =>
+ invoke<Photo>("photo_set_flag", { id, flag, on }),
+ /** The original saved to Downloads; answers where. */
+ photoDownload: (id: string) => invoke<string>("photo_download", { id }),
/** New Calendar: Apple's next unused colour; a name already in use is refused. */
calendarCreate: (title: string) => invoke<string>("calendar_create", { title }),
calendarUpdate: (guid: string, change: { title?: string; colour?: string }) =>
@@ -190,7 +202,8 @@ export const api = {
/** These people as a vCard file in Downloads, written by Apple. Returns the path. */
contactsExport: (guids: string[], fileName: string) => invoke<string>("contacts_export", { guids, fileName }),
/** Everyone in a vCard file, added to Contacts. Returns [added, could not be read]. */
- contactsImport: (path: string) => invoke<[number, number]>("contacts_import", { path }),
+ /** vCard and CSV files, any number: [imported, could not be read]. */
+ contactsImport: (paths: string[]) => invoke<[number, number]>("contacts_import", { paths }),
/** The card that is this person's own, if they have said. */
contactMe: () => invoke<string | null>("contact_me"),
contactSetMe: (guid: string) => invoke<void>("contact_set_me", { guid }),
@@ -528,6 +541,36 @@ export function noteMediaSrc(id: string, part: "file" | "preview"): string {
return convertFileSrc(`note/${id}/${part}`, "quince");
}
+/** One of a photo's pictures, served from the disk cache (fetched from Apple once). */
+export function pictureSrc(id: string, size: "thumb" | "medium" | "original" | "video"): string {
+ return convertFileSrc(`pic/${id}/${size}`, "quince");
+}
+
+export type PhotoAlbum = { id: string; name: string; position: number; changeTag: string | null };
+
+export type PhotoView = "library" | "favorites" | "videos" | "screenshots" | "recents" | "recentlyDeleted";
+
+export type Photo = {
+ id: string;
+ master: string;
+ /** Unix seconds. */
+ takenAt: number;
+ addedAt: number | null;
+ kind: "image" | "video" | "live";
+ width: number;
+ height: number;
+ duration: number | null;
+ filename: string | null;
+ size: number | null;
+ uti: string | null;
+ favorite: boolean;
+ hidden: boolean;
+ deleted: boolean;
+ deletedAt: number | null;
+ subtype: number;
+ changeTag: string | null;
+};
+
/** The picture of the contact with this id, served by the backend. */
export function contactPhotoSrc(guid: string): string {
return convertFileSrc(`photo/${guid}`, "quince");
diff --git a/src/main.tsx b/src/main.tsx
index bf52638..5310445 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -6,6 +6,7 @@ import "./styles/app.css";
import "./styles/reminders.css";
import "./styles/calendar.css";
import "./styles/notes.css";
+import "./styles/photos.css";
import { applyTheme, storedTheme } from "./lib/theme";
// Before the first paint, so the window opens in the appearance chosen.
@@ -25,8 +26,20 @@ document.addEventListener("click", (e) => {
// Capturing, so a link whose own handler stops the click from spreading is covered too.
}, true);
+/*
+ * The engine's own menu (Back, Forward, Reload, Inspect Element) is not this app's: a reload
+ * from it flashed the whole window. Text fields keep their Cut, Copy and Paste; every menu the
+ * app draws itself has already taken its right-click.
+ */
+document.addEventListener("contextmenu", (e) => {
+ if (e.defaultPrevented) return;
+ const editable = (e.target as HTMLElement | null)?.closest?.("input, textarea, [contenteditable=''], [contenteditable='true'], [contenteditable='plaintext-only']");
+ if (!editable) e.preventDefault();
+});
+
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
index 4b69bff..2c6b90c 100644
--- a/src/screens/ContactsView.tsx
+++ b/src/screens/ContactsView.tsx
@@ -199,10 +199,16 @@ export function ContactsView() {
};
const importCards = async () => {
try {
- const chosen = await openFileDialog({ multiple: false, title: "Import vCard", filters: [{ name: "vCard", extensions: ["vcf", "vcard"] }] });
- if (!chosen || Array.isArray(chosen)) return;
+ // Any number of files at once, vCard or a CSV exported from Google Contacts or Outlook.
+ const chosen = await openFileDialog({
+ multiple: true,
+ title: "Import Contacts",
+ filters: [{ name: "Contacts", extensions: ["vcf", "vcard", "csv"] }],
+ });
+ const paths = !chosen ? [] : Array.isArray(chosen) ? chosen : [chosen];
+ if (paths.length === 0) return;
setBusy(true);
- const [added, failed] = await api.contactsImport(chosen);
+ const [added, failed] = await api.contactsImport(paths);
await Promise.all([read(search), readLists()]);
setDone(`${added} ${added === 1 ? "contact" : "contacts"} imported${failed ? `, ${failed} could not be read` : ""}.`);
} catch (e) {
@@ -523,7 +529,7 @@ export function ContactsView() {
at={moreMenu}
onClose={() => setMoreMenu(null)}
entries={[
- { label: "Import vCard\u2026", run: () => void importCards() },
+ { label: "Import Contacts\u2026", run: () => void importCards() },
{ label: openList ? `Export \u201c${openList.name}\u201d\u2026` : "Export All Contacts\u2026", run: () => void exportCards(sortedContacts(shown), openList?.name) },
]}
/>
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index ed102c2..b2e7df4 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -16,6 +16,7 @@ const loaders = {
notes: () => import("./NotesView").then((m) => ({ default: m.NotesView })),
contacts: () => import("./ContactsView").then((m) => ({ default: m.ContactsView })),
drivews: () => import("./DriveView").then((m) => ({ default: m.DriveView })),
+ photos: () => import("./PhotosView").then((m) => ({ default: m.PhotosView })),
settings: () => import("./SettingsView").then((m) => ({ default: m.SettingsView })),
};
const CalendarView = lazy(loaders.calendar);
@@ -23,6 +24,7 @@ const RemindersView = lazy(loaders.reminders);
const NotesView = lazy(loaders.notes);
const ContactsView = lazy(loaders.contacts);
const DriveView = lazy(loaders.drivews);
+const PhotosView = lazy(loaders.photos);
const SettingsView = lazy(loaders.settings);
import { ScreenBoundary } from "../components/ScreenBoundary";
import { AppIcon } from "../components/AppIcon";
@@ -39,6 +41,7 @@ const SCREENS: { key: string; name: string }[] = [
{ key: "reminders", name: "Reminders" },
{ key: "notes", name: "Notes" },
{ key: "drivews", name: "iCloud Drive" },
+ { key: "photos", name: "Photos" },
{ key: "calendar", name: "Calendar" },
{ key: "contacts", name: "Contacts" },
];
@@ -286,6 +289,8 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
<NotesView />
) : selected === "contacts" ? (
<ContactsView />
+ ) : selected === "photos" ? (
+ <PhotosView />
) : (
<DriveView />
)}
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 7d6746f..27a1937 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -527,8 +527,14 @@ export function NotesView() {
return;
}
const gone = open.guid;
+ // The note below opens in its place, or the one above at the end, as in Notes: the order
+ // is the list's as shown, pinned notes first.
+ const order = groupNotes(notes).flatMap((g) => g.notes.map((n) => n.guid));
+ const at = order.indexOf(gone);
+ const next = order[at + 1] ?? order[at - 1] ?? null;
+ setOpenGuid(next);
await write(() => api.noteDelete(gone), (rows) => rows.filter((n) => n.guid !== gone));
- }, [open, write]);
+ }, [open, write, notes]);
/** Out of Recently Deleted and back into Notes — Apple's "Notes" folder where there is one. */
const recover = useCallback(async () => {
@@ -892,7 +898,7 @@ export function NotesView() {
</button>
)}
{inTrash ? (
- <button className="quiet danger" onClick={() => void remove()} disabled={busy}>
+ <button className="quiet danger" onClick={() => void remove()}>
Delete Now
</button>
) : (
@@ -901,7 +907,6 @@ export function NotesView() {
aria-label="Delete"
title="Delete"
onClick={() => void remove()}
- disabled={busy}
>
<Trash2 size={17} strokeWidth={2} aria-hidden="true" />
</button>
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
new file mode 100644
index 0000000..7a07bbe
--- /dev/null
+++ b/src/screens/PhotosView.tsx
@@ -0,0 +1,347 @@
+/**
+ * Photos, as on a Mac: the library edge to edge, newest first, grouped by month, with a zoom
+ * for how many across; a photo opens on a dark stage with the arrows to go through them. Everything draws from the local library at once; thumbnails come
+ * from the disk cache and are fetched once.
+ */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { ChevronLeft, ChevronRight, Download, Heart, Info, Play, RotateCcw, Trash2, X } from "lucide-react";
+import { api, messageOf, pictureSrc, type Photo, type PhotoAlbum, type PhotoView } from "../lib/ipc";
+import { useSync } from "../lib/sync";
+import { Notice } from "../components/Notice";
+
+const VIEWS: { key: PhotoView; label: string }[] = [
+ { key: "library", label: "Library" },
+ { key: "favorites", label: "Favorites" },
+ { key: "recents", label: "Recents" },
+ { key: "videos", label: "Videos" },
+ { key: "screenshots", label: "Screenshots" },
+ { key: "recentlyDeleted", label: "Recently Deleted" },
+];
+
+/** How many across at each step of the zoom, as Photos steps it. */
+const ACROSS = [10, 7, 5, 3];
+
+const monthOf = (seconds: number) =>
+ new Date(seconds * 1000).toLocaleDateString(undefined, { month: "long", year: "numeric" });
+
+const clock = (s: number | null) => {
+ if (!s) return "";
+ const m = Math.floor(s / 60);
+ return `${m}:${String(Math.round(s % 60)).padStart(2, "0")}`;
+};
+
+export function PhotosView() {
+ const { revision } = useSync();
+ const [view, setView] = useState<PhotoView>("library");
+ /** An album open instead of a view. */
+ const [album, setAlbum] = useState<PhotoAlbum | null>(null);
+ const [albums, setAlbums] = useState<[PhotoAlbum, number][]>([]);
+ const [photos, setPhotos] = useState<Photo[] | null>(null);
+ const [counts, setCounts] = useState<Partial<Record<PhotoView, number>>>({});
+ const [error, setError] = useState<string | null>(null);
+ const [zoom, setZoom] = useState(1);
+ const [open, setOpen] = useState<number | null>(null);
+ const [info, setInfo] = useState(false);
+ const [saved, setSaved] = useState<string | null>(null);
+
+ const read = useCallback(async () => {
+ const [list, c, a] = await Promise.all([
+ album ? api.photosInAlbum(album.id) : api.photosList(view),
+ api.photosCounts(),
+ api.photosAlbums(),
+ ]);
+ setPhotos(list);
+ setCounts(Object.fromEntries(c));
+ setAlbums(a);
+ // An album deleted elsewhere is not left open, empty.
+ if (album && !a.some(([x]) => x.id === album.id)) setAlbum(null);
+ }, [view, album]);
+ useEffect(() => {
+ read().catch((e) => setError(messageOf(e)));
+ }, [read, revision]);
+
+ // Grouped by month, as the library reads; an album is one grid in its own order.
+ const months = useMemo(() => {
+ const out: { label: string; items: { photo: Photo; index: number }[] }[] = [];
+ if (album) return [{ label: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];
+ (photos ?? []).forEach((photo, index) => {
+ const label = monthOf(view === "recents" ? (photo.addedAt ?? photo.takenAt) : photo.takenAt);
+ const last = out[out.length - 1];
+ if (last && last.label === label) last.items.push({ photo, index });
+ else out.push({ label, items: [{ photo, index }] });
+ });
+ return out;
+ }, [photos, view, album]);
+
+ const shown = open !== null ? photos?.[open] ?? null : null;
+ const step = useCallback(
+ (by: number) => setOpen((at) => (at === null || !photos ? at : Math.max(0, Math.min(photos.length - 1, at + by)))),
+ [photos],
+ );
+
+ // The viewer's keys: arrows to go through, Escape to close, I for the details.
+ useEffect(() => {
+ if (open === null) return undefined;
+ const current = photos?.[open] ?? null;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "ArrowRight") step(1);
+ else if (e.key === "ArrowLeft") step(-1);
+ else if (e.key === "Escape") setOpen(null);
+ else if (e.key === " " && current?.kind === "video") void play(current);
+ else if (e.key.toLowerCase() === "i" && !e.metaKey && !e.ctrlKey) setInfo((v) => !v);
+ // As in Photos: "." favorites, Delete sends it to Recently Deleted.
+ else if (e.key === "." && current && view !== "recentlyDeleted") void change(current, "favorite", !current.favorite);
+ else if ((e.key === "Delete" || e.key === "Backspace") && current && view !== "recentlyDeleted") void change(current, "deleted", true);
+ else return;
+ e.preventDefault();
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ });
+
+ /**
+ * Favorite, Delete and Recover show at once, as on the phone; Apple's answer only matters if
+ * it refuses, which puts the photo back as it was and says why.
+ */
+ const change = async (p: Photo, flag: "favorite" | "deleted", on: boolean) => {
+ // Asked first, in icloud.com's words: a delete reaches every device.
+ if (
+ flag === "deleted" && on &&
+ !window.confirm("Delete this photo?\n\nIt will be deleted from iCloud Photos on all your devices. It stays in Recently Deleted for 30 days.")
+ ) {
+ return;
+ }
+ const before = photos;
+ const leaves = flag === "deleted" && (on ? view !== "recentlyDeleted" : view === "recentlyDeleted");
+ setPhotos((list) =>
+ leaves
+ ? (list ?? []).filter((x) => x.id !== p.id)
+ : (list ?? []).map((x) => (x.id === p.id ? { ...x, [flag]: on } : x)),
+ );
+ if (leaves) {
+ // The viewer goes on to the next photo, or the one before at the end, or closes.
+ setOpen((at) => {
+ if (at === null || !photos) return at;
+ const left = photos.length - 1;
+ return left === 0 ? null : Math.min(at, left - 1);
+ });
+ }
+ try {
+ await api.photoSetFlag(p.id, flag, on);
+ read().catch(() => {});
+ } catch (e) {
+ setPhotos(before);
+ setError(messageOf(e));
+ }
+ };
+
+ const play = async (p: Photo) => {
+ try {
+ await api.photoPlay(p.id);
+ } catch (e) {
+ setError(messageOf(e));
+ }
+ };
+
+ const download = async (p: Photo) => {
+ try {
+ const where = await api.photoDownload(p.id);
+ setSaved(`Saved to ${where}`);
+ } catch (e) {
+ setError(messageOf(e));
+ }
+ };
+
+ const title = album?.name ?? VIEWS.find((v) => v.key === view)?.label ?? "Photos";
+ const across = ACROSS[zoom];
+
+ return (
+ <div className="px">
+ <aside className="px-side" aria-label="Photos">
+ <p className="px-side-heading">Photos</p>
+ {VIEWS.map((v) => (
+ <button
+ key={v.key}
+ className="px-source"
+ aria-current={!album && view === v.key}
+ onClick={() => {
+ setView(v.key);
+ setAlbum(null);
+ setOpen(null);
+ }}
+ >
+ <span>{v.label}</span>
+ {counts[v.key] ? <span className="px-count">{counts[v.key]}</span> : null}
+ </button>
+ ))}
+ {albums.length > 0 && (
+ <>
+ <p className="px-side-heading">Albums</p>
+ {albums.map(([a, n]) => (
+ <button
+ key={a.id}
+ className="px-source"
+ aria-current={album?.id === a.id}
+ onClick={() => {
+ setAlbum(a);
+ setOpen(null);
+ }}
+ >
+ <span>{a.name}</span>
+ {n ? <span className="px-count">{n}</span> : null}
+ </button>
+ ))}
+ </>
+ )}
+ </aside>
+
+ <section className="px-main" aria-label={title}>
+ <header className="px-bar">
+ <h1>{title}</h1>
+ <span className="px-total">
+ {photos ? `${photos.length} ${photos.length === 1 ? "item" : "items"}` : ""}
+ </span>
+ <label className="px-zoom">
+ <span className="visually-hidden">Zoom</span>
+ <input
+ type="range"
+ min={0}
+ max={ACROSS.length - 1}
+ step={1}
+ value={zoom}
+ aria-label="Zoom"
+ onChange={(e) => setZoom(Number(e.target.value))}
+ />
+ </label>
+ </header>
+
+ {photos && photos.length === 0 && (
+ <p className="px-empty">
+ {album
+ ? "This album is empty. Photos added to it on any device show here."
+ : view === "recentlyDeleted"
+ ? "Nothing deleted. Photos you delete stay here for 30 days."
+ : view === "favorites"
+ ? "Mark a photo with the heart and it shows here."
+ : "No photos here yet."}
+ </p>
+ )}
+
+ <div className="px-scroll" style={{ "--across": across } as React.CSSProperties}>
+ {months.map((m) => (
+ <section key={m.label} className="px-month" aria-label={m.label}>
+ {m.label && <h2 className="px-month-title">{m.label}</h2>}
+ <div className="px-grid" role="list">
+ {m.items.map(({ photo, index }) => (
+ <button
+ key={photo.id}
+ role="listitem"
+ className="px-tile"
+ aria-label={`${photo.filename ?? "Photo"}, ${new Date(photo.takenAt * 1000).toLocaleString()}`}
+ onClick={() => setOpen(index)}
+ >
+ <img src={pictureSrc(photo.id, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />
+ {photo.kind === "video" && (
+ <span className="px-badge px-duration">
+ <Play size={10} strokeWidth={0} fill="currentColor" aria-hidden="true" />
+ {clock(photo.duration)}
+ </span>
+ )}
+ {photo.favorite && (
+ <Heart className="px-heart" size={13} strokeWidth={0} fill="currentColor" aria-label="Favorite" />
+ )}
+ </button>
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+
+ {shown && (
+ <div className="px-viewer" role="dialog" aria-label={shown.filename ?? "Photo"}>
+ <header className="px-viewer-bar">
+ <button className="px-icon" aria-label="Close" title="Close (Esc)" onClick={() => setOpen(null)}>
+ <X size={18} />
+ </button>
+ <div className="px-viewer-when">
+ <strong>{new Date(shown.takenAt * 1000).toLocaleDateString(undefined, { dateStyle: "long" })}</strong>
+ <span>{new Date(shown.takenAt * 1000).toLocaleTimeString(undefined, { timeStyle: "short" })}</span>
+ </div>
+ {view === "recentlyDeleted" && !album ? (
+ <button className="px-icon" aria-label="Recover" title="Recover" onClick={() => void change(shown, "deleted", false)}>
+ <RotateCcw size={17} />
+ </button>
+ ) : (
+ <>
+ <button
+ className={`px-icon${shown.favorite ? " is-favorite" : ""}`}
+ aria-label={shown.favorite ? "Unfavorite" : "Favorite"}
+ aria-pressed={shown.favorite}
+ title={shown.favorite ? "Unfavorite (.)" : "Favorite (.)"}
+ onClick={() => void change(shown, "favorite", !shown.favorite)}
+ >
+ <Heart size={17} fill={shown.favorite ? "currentColor" : "none"} />
+ </button>
+ <button className="px-icon" aria-label="Delete" title="Delete (Delete)" onClick={() => void change(shown, "deleted", true)}>
+ <Trash2 size={17} />
+ </button>
+ </>
+ )}
+ <button className="px-icon" aria-label="Download" title="Download the original" onClick={() => void download(shown)}>
+ <Download size={17} />
+ </button>
+ <button className="px-icon" aria-label="Info" aria-pressed={info} title="Info (I)" onClick={() => setInfo((v) => !v)}>
+ <Info size={17} />
+ </button>
+ </header>
+ <div className="px-stage">
+ {shown.kind === "video" ? (
+ // A still of the video, and Play opens it in this computer's own player: the
+ // window's engine plays nothing without codec plugins many systems lack.
+ <button className="px-video" aria-label="Play in your video player" onClick={() => void play(shown)}>
+ <img key={shown.id} src={pictureSrc(shown.id, "medium")} alt={shown.filename ?? ""} decoding="async" />
+ <span className="px-play" aria-hidden="true">
+ <Play size={28} strokeWidth={0} fill="currentColor" />
+ </span>
+ </button>
+ ) : (
+ <img key={shown.id} src={pictureSrc(shown.id, "medium")} alt={shown.filename ?? ""} decoding="async" />
+ )}
+ {open !== null && open > 0 && (
+ <button className="px-nav is-prev" aria-label="Previous" onClick={() => step(-1)}>
+ <ChevronLeft size={22} />
+ </button>
+ )}
+ {open !== null && photos && open < photos.length - 1 && (
+ <button className="px-nav is-next" aria-label="Next" onClick={() => step(1)}>
+ <ChevronRight size={22} />
+ </button>
+ )}
+ </div>
+ {info && (
+ <dl className="px-info">
+ <dt>Name</dt>
+ <dd>{shown.filename ?? "—"}</dd>
+ <dt>Taken</dt>
+ <dd>{new Date(shown.takenAt * 1000).toLocaleString()}</dd>
+ <dt>Size</dt>
+ <dd>
+ {shown.width} × {shown.height}
+ {shown.size ? ` · ${(shown.size / 1024 / 1024).toFixed(1)} MB` : ""}
+ </dd>
+ <dt>Kind</dt>
+ <dd>{shown.kind === "video" ? "Video" : shown.kind === "live" ? "Live Photo" : "Photo"}</dd>
+ </dl>
+ )}
+ </div>
+ )}
+ </section>
+ {error && <Notice message={error} onDismiss={() => setError(null)} />}
+ {saved && (
+ <p className="drive-saved px-saved" role="status" onClick={() => setSaved(null)}>
+ {saved}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/src/screens/RemindersView.tsx b/src/screens/RemindersView.tsx
index 2b1cda9..6f44edb 100644
--- a/src/screens/RemindersView.tsx
+++ b/src/screens/RemindersView.tsx
@@ -360,8 +360,58 @@ export function RemindersView() {
* The row therefore comes back unticked with a later date, which looks exactly like
* nothing happened, so the new date is called out for a moment.
*/
- const toggle = async (r: Reminder) => {
+ /**
+ * A ticked reminder leaves as on the phone: the circle fills at once, the row stays a
+ * moment (so a mistaken tick can be undone), then fades and goes, all on the screen's own
+ * clock, never waiting for Apple. Apple's answer only matters if it refuses, which brings
+ * the row back with the reason.
+ */
+ const [leaving, setLeaving] = useState<Set<string>>(() => new Set());
+ const [departed, setDeparted] = useState<Set<string>>(() => new Set());
+ const departure = useRef(new Map<string, number[]>());
+ const stay = (guid: string) => {
+ for (const t of departure.current.get(guid) ?? []) window.clearTimeout(t);
+ departure.current.delete(guid);
+ const without = (was: Set<string>) => {
+ if (!was.has(guid)) return was;
+ const next = new Set(was);
+ next.delete(guid);
+ return next;
+ };
+ setLeaving(without);
+ setDeparted(without);
+ };
+ const depart = (guid: string) => {
+ stay(guid);
+ departure.current.set(guid, [
+ window.setTimeout(() => setLeaving((was) => new Set(was).add(guid)), 900),
+ window.setTimeout(() => setDeparted((was) => new Set(was).add(guid)), 1200),
+ ]);
+ };
+ useEffect(() => {
+ const timers = departure.current;
+ return () => timers.forEach((ts) => ts.forEach((t) => window.clearTimeout(t)));
+ }, []);
+
+ /** Each reminder's ticks, sent to Apple one after another, in the order they were made. */
+ const ticks = useRef(new Map<string, Promise<unknown>>());
+ const toggle = (r: Reminder) => {
const wasOpen = !r.completedAt;
+ // Shown at once, every time, even while an earlier tick of this one is on its way.
+ if (repeatLabel(r) === null) {
+ setItems(patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null }));
+ }
+ // Only where completed reminders are hidden, and never for a repeating one, which rolls on.
+ if (wasOpen && !showDone && repeatLabel(r) === null) depart(r.guid);
+ else stay(r.guid);
+ const before = ticks.current.get(r.guid) ?? Promise.resolve();
+ const next = before.then(() => send(r, wasOpen));
+ ticks.current.set(r.guid, next);
+ void next.finally(() => {
+ if (ticks.current.get(r.guid) === next) ticks.current.delete(r.guid);
+ });
+ };
+ const send = async (r: Reminder, wasOpen: boolean) => {
const fresh = await write(
r,
() => api.reminderSetDone(r.guid, r.listGuid, wasOpen),
@@ -370,6 +420,7 @@ export function RemindersView() {
? patch(r.guid, { completedAt: wasOpen ? Math.floor(Date.now() / 1000) : null })
: undefined,
);
+ if (!fresh) stay(r.guid);
if (!fresh || !wasOpen || repeatLabel(r) === null) return;
const after = fresh.find((x) => x.guid === r.guid);
if (after && after.dueAt !== null && after.dueAt !== r.dueAt) {
@@ -621,21 +672,26 @@ export function RemindersView() {
* top level and wrong for what hangs off it: a subtask sorted away from its parent reads
* as an unrelated fragment. This re-threads them without re-sorting either level.
*/
+ // What is on screen: the list less any ticked reminder that has already left it.
+ const shownItems = useMemo(
+ () => (departed.size ? items.filter((r) => !departed.has(r.guid)) : items),
+ [items, departed],
+ );
const threaded = useMemo(() => {
const children = new Map<string, Reminder[]>();
- for (const r of items) {
+ for (const r of shownItems) {
if (!r.parentGuid) continue;
const bucket = children.get(r.parentGuid);
if (bucket) bucket.push(r);
else children.set(r.parentGuid, [r]);
}
- const known = new Set(items.map((r) => r.guid));
+ const known = new Set(shownItems.map((r) => r.guid));
const out: { reminder: Reminder; depth: number }[] = [];
// Open reminders first, in their list's own order; completed ones beneath them, the most
// recently completed first, as Reminders shows them. In the list's stored order they came
// out scattered among the open ones, in no order a person could follow.
- const open = items.filter((r) => !r.completedAt);
- const done = items
+ const open = shownItems.filter((r) => !r.completedAt);
+ const done = shownItems
.filter((r) => r.completedAt)
.sort((a, b) => (b.completedAt ?? 0) - (a.completedAt ?? 0));
for (const r of [...open, ...done]) {
@@ -648,7 +704,7 @@ export function RemindersView() {
}
}
return out;
- }, [items]);
+ }, [shownItems]);
/**
* The rows arranged the way Apple arranges them.
*
@@ -1110,7 +1166,7 @@ export function RemindersView() {
return (
<li
key={reminder.guid}
- className={`rx-row${reminder.completedAt ? " is-done" : ""}${
+ className={`rx-row${reminder.completedAt ? " is-done" : ""}${leaving.has(reminder.guid) ? " is-leaving" : ""}${
depth > 0 ? " is-subtask" : ""
}${isOpen ? " is-open" : ""}${dropBefore === reminder.guid ? " is-drop-before" : ""}${
dragging === reminder.guid ? " is-dragging" : ""
@@ -1182,7 +1238,6 @@ export function RemindersView() {
role="checkbox"
aria-checked={Boolean(reminder.completedAt)}
aria-label={reminder.title}
- disabled={busy.has(reminder.guid)}
style={{ "--tick": colourOf(home) } as React.CSSProperties}
onClick={() => toggle(reminder)}
/>
diff --git a/src/styles/app.css b/src/styles/app.css
index cc2a49b..3c900d4 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1723,13 +1723,19 @@
background: color-mix(in srgb, var(--text) 10%, transparent);
overflow: hidden;
}
+/* The fill grows by scale, on the compositor: a width animated here laid out the tray on
+ every step, and coming back to the window replayed every step at once as a glitch. */
.upload-bar > span {
display: block;
+ width: 100%;
height: 100%;
border-radius: inherit;
background: var(--accent);
- transition: width 200ms var(--ease);
+ transform-origin: left center;
+ transform: scaleX(0);
+ transition: transform 200ms var(--ease);
}
+.upload-tray.is-instant .upload-bar > span { transition: none; }
.upload-bar.small { height: 3px; margin: 4px 0 0; }
.upload-rows { margin: 0; padding: 0 6px 8px; list-style: none; overflow-y: auto; }
@@ -2055,4 +2061,5 @@
across instead of a number that would only shrink. */
.upload-bar.is-waiting > span { width: 30%; animation: upload-finding 1.2s var(--ease) infinite alternate; }
@keyframes upload-finding { from { transform: translateX(-10%); } to { transform: translateX(240%); } }
+.upload-bar.is-waiting > span { transform: none; }
@media (prefers-reduced-motion: reduce) { .upload-bar.is-waiting > span { animation: none; width: 100%; opacity: 0.4; } }
diff --git a/src/styles/photos.css b/src/styles/photos.css
new file mode 100644
index 0000000..2df1ca2
--- /dev/null
+++ b/src/styles/photos.css
@@ -0,0 +1,209 @@
+/* Photos: the photos are the design. Chrome stays quiet and solid (no live blur: WebKitGTK),
+ tiles meet with a hairline gap as on a Mac, and only what answers an action moves. */
+
+.px {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 216px minmax(0, 1fr);
+}
+
+/* ---- sidebar: the library's views, as Photos lists them ---------------------------------- */
+.px-side {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-height: 0;
+ padding: 4px 10px 10px;
+ border-right: 1px solid var(--separator);
+ overflow-y: auto;
+}
+.px-side-heading {
+ margin: 6px 8px 4px;
+ color: var(--text-3);
+ font-size: var(--t-11);
+ font-weight: 600;
+}
+.px-source {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ height: 30px;
+ padding: 0 10px;
+ border: 0;
+ border-radius: 7px;
+ background: none;
+ box-shadow: none;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ text-align: start;
+ cursor: default;
+}
+.px-source:hover { background: color-mix(in srgb, var(--text) 6%, transparent); }
+.px-source[aria-current="true"] { background: color-mix(in srgb, var(--text) 12%, transparent); }
+.px-source:focus-visible { outline: 3px solid var(--accent-ring); outline-offset: -1px; }
+.px-count { color: var(--text-3); font-variant-numeric: tabular-nums; font-size: var(--t-12, 12px); }
+
+/* ---- the library ------------------------------------------------------------------------- */
+.px-main { position: relative; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
+.px-bar {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ padding: 14px 18px 10px;
+}
+.px-bar h1 { margin: 0; font-size: var(--t-22, 22px); font-weight: 700; letter-spacing: -0.01em; }
+.px-total { color: var(--text-3); font-size: var(--t-13); font-variant-numeric: tabular-nums; }
+.px-zoom { margin-left: auto; align-self: center; }
+.px-zoom input { width: 120px; accent-color: var(--accent); }
+.px-empty { margin: 18vh auto 0; max-width: 36ch; color: var(--text-2); text-align: center; }
+
+.px-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 0 2px 24px; }
+/* A month off screen is not laid out or painted until it nears it: a library of thousands
+ scrolls as lightly as one of a hundred. */
+.px-month { content-visibility: auto; contain-intrinsic-size: auto 600px; }
+.px-month-title {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ margin: 0;
+ padding: 12px 16px 8px;
+ background: var(--bg);
+ font-size: var(--t-17, 17px);
+ font-weight: 700;
+ letter-spacing: -0.01em;
+}
+.px-grid {
+ display: grid;
+ grid-template-columns: repeat(var(--across, 7), minmax(0, 1fr));
+ gap: 2px;
+}
+.px-tile {
+ position: relative;
+ aspect-ratio: 1;
+ padding: 0;
+ border: 0;
+ border-radius: 0;
+ background: color-mix(in srgb, var(--text) 7%, transparent);
+ box-shadow: none;
+ overflow: hidden;
+ cursor: default;
+}
+.px-tile img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.px-tile:focus-visible { outline: 3px solid var(--accent); outline-offset: -3px; z-index: 1; }
+.px-badge {
+ position: absolute;
+ right: 6px;
+ bottom: 5px;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ color: #fff;
+ font-size: 11px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ text-shadow: 0 0 3px rgba(0, 0, 0, 0.6);
+}
+.px-heart { position: absolute; left: 6px; bottom: 6px; color: #fff; filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.6)); }
+
+/* ---- the viewer: a dark stage, the photo fitted to it -------------------------------------- */
+.px-viewer {
+ position: absolute;
+ inset: 0;
+ z-index: 5;
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ grid-template-columns: minmax(0, 1fr) auto;
+ background: #161618;
+ color: #f5f5f7;
+}
+.px-viewer-bar {
+ grid-column: 1 / -1;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 10px;
+}
+.px-viewer-when { flex: 1; display: flex; flex-direction: column; align-items: center; line-height: 1.25; }
+.px-viewer-when span { color: #a1a1a6; font-size: var(--t-11); }
+.px-icon {
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ padding: 0;
+ border: 0;
+ border-radius: 8px;
+ background: none;
+ box-shadow: none;
+ color: inherit;
+}
+.px-icon:hover, .px-icon[aria-pressed="true"] { background: rgba(255, 255, 255, 0.12); }
+.px-stage { position: relative; display: grid; place-items: center; min-height: 0; padding: 8px 56px 24px; }
+.px-stage img, .px-stage video { max-width: 100%; max-height: 100%; object-fit: contain; }
+.px-nav {
+ position: absolute;
+ top: 50%;
+ display: grid;
+ place-items: center;
+ width: 40px;
+ height: 40px;
+ margin-top: -20px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.1);
+ box-shadow: none;
+ color: #f5f5f7;
+}
+.px-nav:hover { background: rgba(255, 255, 255, 0.2); }
+.px-nav.is-prev { left: 10px; }
+.px-nav.is-next { right: 10px; }
+.px-info {
+ grid-row: 2;
+ grid-column: 2;
+ width: 260px;
+ margin: 0;
+ padding: 14px 16px;
+ border-left: 1px solid rgba(255, 255, 255, 0.1);
+ font-size: var(--t-13);
+ overflow-y: auto;
+}
+.px-info dt { margin-top: 10px; color: #a1a1a6; font-size: var(--t-11); }
+.px-info dd { margin: 2px 0 0; overflow-wrap: anywhere; }
+.px-saved {
+ position: absolute;
+ left: 232px;
+ bottom: 14px;
+ z-index: 6;
+ margin: 0;
+ padding: 7px 12px;
+ border-radius: 9px;
+ background: var(--glass-thick);
+ box-shadow: var(--glass-specular), var(--glass-lift);
+}
+.px-icon.is-favorite { color: #ff375f; }
+.px-video {
+ position: relative;
+ display: grid;
+ place-items: center;
+ max-width: 100%;
+ max-height: 100%;
+ padding: 0;
+ border: 0;
+ background: none;
+ box-shadow: none;
+}
+.px-video img { max-width: 100%; max-height: calc(100vh - 140px); object-fit: contain; }
+.px-play {
+ position: absolute;
+ display: grid;
+ place-items: center;
+ width: 64px;
+ height: 64px;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, 0.5);
+ color: #fff;
+}
+.px-video:hover .px-play { background: rgba(0, 0, 0, 0.65); }
diff --git a/src/styles/reminders.css b/src/styles/reminders.css
index 54ef6ae..5a19116 100644
--- a/src/styles/reminders.css
+++ b/src/styles/reminders.css
@@ -358,6 +358,11 @@
background: var(--separator);
}
.rx-row:last-child::after { display: none; }
+/* A ticked reminder on its way out, as on the phone: it fades and drifts up a little, on the
+ compositor only (opacity and transform), so nothing else is laid out while it goes. */
+.rx-row { transition: opacity 260ms var(--ease, ease), transform 260ms var(--ease, ease); }
+.rx-row.is-leaving { opacity: 0; transform: translateY(-4px); pointer-events: none; }
+@media (prefers-reduced-motion: reduce) { .rx-row { transition: none; } }
/* A row chosen from the keyboard: the selection Reminders draws, a rounded tint behind it, with
no outline drawn around the text. */
.rx-row:focus { outline: none; }