Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Photos: upload into the library, and albums you can make and change
Yashwanth Kamireddi52658169fe65
diff --git a/.uiverify/photos-albums.mjs b/.uiverify/photos-albums.mjsnew file mode 100644index 0000000..b8a52a1--- /dev/null+++ b/.uiverify/photos-albums.mjs@@ -0,0 +1,72 @@+// Photos albums: a new one from the sidebar's +, named in place, first in the list; a photo+// added from its right-click menu and from the viewer; taken out again in the album, staying+// in the library; renamed and deleted from the album's own right-click menu. Each shows at+// once and reaches iCloud.+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; });+page.on("dialog", (d) => void d.accept());+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 albumNames = () => page.locator(".px-side .px-source").evaluateAll((els) => els.map((e) => e.querySelector("span")?.textContent ?? "").slice(6));++await page.getByRole("button", { name: "New Album" }).click();+await page.getByLabel("Album name").fill("Beach");+await page.keyboard.press("Enter");+await page.waitForTimeout(250);+ok(JSON.stringify(await albumNames()) === JSON.stringify(["Beach", "Trips"]), `a new album is named in place and sorts first ${JSON.stringify(await albumNames())}`);+ok((await page.evaluate(() => window.__albumCalls.filter((c) => c.cmd === "photos_album_create").length)) === 1, "and is made once, not twice for Enter and the blur after it");++await page.locator(".px-tile").first().click({ button: "right" });+await page.locator(".row-menu").getByText("Add to Album").hover();+await page.waitForTimeout(200);+await page.locator(".row-menu").getByText("Beach", { exact: true }).click();+await page.waitForTimeout(250);+const add = await page.evaluate(() => window.__albumCalls.find((c) => c.cmd === "photos_album_add"));+ok(add && add.args.ids[0] === "p1", "right-click → Add to Album puts the photo in it");+ok(/1/.test(await page.locator(".px-source", { hasText: "Beach" }).innerText()), "and its count shows at once");++await page.locator(".px-tile").nth(1).click();+await page.getByRole("button", { name: "Add to Album" }).click();+await page.locator(".row-menu").getByText("Beach", { exact: true }).click();+await page.waitForTimeout(250);+ok((await page.evaluate(() => window.__albumCalls.filter((c) => c.cmd === "photos_album_add").length)) === 2, "the viewer's Add to Album does the same");+await page.keyboard.press("Escape");++await page.locator(".px-source", { hasText: "Beach" }).click();+await page.waitForTimeout(250);+ok((await page.locator(".px-tile").count()) === 2, "the album holds both");+await page.locator(".px-tile").first().click({ button: "right" });+ok((await page.locator(".row-menu").getByText("Delete", { exact: true }).count()) === 0, "in an album the menu offers Remove, not Delete");+await page.locator(".row-menu").getByText("Remove from Album").click();+await page.waitForTimeout(250);+ok((await page.locator(".px-tile").count()) === 1, "Remove from Album takes it out at once");+ok((await page.evaluate(() => window.__photos.filter((p) => !p.deleted).length)) === 5, "and the photo stays in the library");++await page.locator(".px-source", { hasText: "Beach" }).click({ button: "right" });+await page.locator(".row-menu").getByText("Rename Album").click();+await page.getByLabel("Album name").fill("Sea");+await page.keyboard.press("Enter");+await page.waitForTimeout(250);+ok((await page.locator(".px-bar h1").innerText()) === "Sea" && (await albumNames()).includes("Sea"), "Rename Album renames it in place and in the title");++await page.locator(".px-source", { hasText: "Sea" }).click({ button: "right" });+await page.locator(".row-menu").getByText("Delete Album").click();+await page.waitForTimeout(250);+ok(!(await albumNames()).includes("Sea") && (await page.locator(".px-bar h1").innerText()) === "Library", "Delete Album, once agreed, removes it and goes back to the library");++await page.evaluate(() => { window.__albumFail = true; });+await page.getByRole("button", { name: "New Album" }).click();+await page.getByLabel("Album name").fill("Nope");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+ok(!(await albumNames()).includes("Nope") && (await page.locator(".notice").count()) === 1, "an album iCloud refuses goes away again, and says why");+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos.mjs b/.uiverify/photos.mjsindex 7f6e372..fec6438 100644--- a/.uiverify/photos.mjs+++ b/.uiverify/photos.mjs@@ -90,5 +90,27 @@ 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()}`);++// Adding: the chosen photos go to the library, each shown in the tray as it goes; a file+// Photos can't take says why at once; Cancel stops the rest; a clean finish clears itself.+await page.evaluate(() => { window.__pick = ["/home/test/Pictures/beach.jpg", "/home/test/Pictures/notes.txt", "/home/test/Pictures/dog.heic"]; });+await page.getByRole("button", { name: "Add Photos" }).click();+await page.waitForTimeout(300);+ok(JSON.stringify(await page.evaluate(() => window.__photoUploads?.at(-1))) === JSON.stringify(["/home/test/Pictures/beach.jpg", "/home/test/Pictures/notes.txt", "/home/test/Pictures/dog.heic"]),+ "Add Photos sends the chosen files to the library");+ok((await page.locator(".upload-tray").count()) === 1 && /can’t add this kind/.test(await page.locator(".upload-tray").innerText()),+ "the tray shows the files, and why one can't be added");+await page.evaluate(() => window.__emit("quince://photo-upload", { id: "B1:0", batch: "B1", name: "beach.jpg", within: "", folder: false, error: null, state: "sending", sent: 500, total: 1000 }));+await page.waitForTimeout(100);+ok(/Uploading/.test(await page.locator(".upload-tray-title").innerText()), "a file on its way shows as uploading");+await page.locator(".upload-tray").getByRole("button", { name: "Cancel", exact: true }).click();+await page.waitForTimeout(200);+ok(JSON.stringify(await page.evaluate(() => window.__photoCancels?.at(-1))) === JSON.stringify({ ids: [], batch: "B1" }),+ "Cancel stops the batch through Photos, not Drive");+await page.evaluate(() => window.__emit("quince://photo-upload", { id: "B1:0", batch: "B1", name: "beach.jpg", within: "", folder: false, error: null, state: "cancelled", sent: 0, total: 1000 }));+await page.waitForTimeout(100);+ok(!/Uploading/.test(await page.locator(".upload-tray-title").innerText()), "once cancelled, nothing reads as still going");+await page.getByRole("button", { name: "Close uploads" }).click();+ok((await page.locator(".upload-tray").count()) === 0, "Done clears the tray");await b.close();process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 23f958d..fbff7dc 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -323,10 +323,31 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (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_albums": {+ const albums = (window.__albums ??= [{ id: "AL1", name: "Trips", position: 0, changeTag: null, items: ["p4", "p2"] }]);+ return albums.map(({ items, ...a }) => [a, items.length]);+ }case "photos_in_album": {const all = window.__photos ?? [];- return args.album === "AL1" ? all.filter((p) => p.id === "p4" || p.id === "p2") : [];+ const a = (window.__albums ?? [{ id: "AL1", items: ["p4", "p2"] }]).find((x) => x.id === args.album);+ return a ? a.items.map((id) => all.find((p) => p.id === id)).filter(Boolean) : [];+ }+ case "photos_album_create": case "photos_album_rename": case "photos_album_delete":+ case "photos_album_add": case "photos_album_remove": {+ (window.__albumCalls ??= []).push({ cmd, args });+ if (window.__albumFail) throw "iCloud didn’t accept that change.";+ const albums = (window.__albums ??= [{ id: "AL1", name: "Trips", position: 0, changeTag: null, items: ["p4", "p2"] }]);+ const find = (id) => albums.find((x) => x.id === id);+ if (cmd === "photos_album_create") {+ const made = { id: `AL${albums.length + 1}`, name: args.name, position: -1, changeTag: "t1" };+ albums.unshift({ ...made, items: [] });+ return made;+ }+ if (cmd === "photos_album_rename") find(args.id).name = args.name;+ if (cmd === "photos_album_delete") albums.splice(albums.indexOf(find(args.id)), 1);+ if (cmd === "photos_album_add") find(args.album).items.push(...args.ids.filter((i) => !find(args.album).items.includes(i)));+ if (cmd === "photos_album_remove") find(args.album).items = find(args.album).items.filter((i) => !args.ids.includes(i));+ return null;}case "photo_set_flag": {(window.__flags ??= []).push(args);@@ -340,6 +361,26 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}case "photo_play": (window.__plays ??= []).push(args); return null;case "photo_download": (window.__downloads ??= []).push(args); return `/home/test/Downloads/IMG_${args.id}.JPG`;+ // Each file is answered at once with where it stands; a test plays the rest in with __emit.+ case "photos_upload": {+ (window.__photoUploads ??= []).push(args.paths);+ const batch = `B${window.__photoUploads.length}`;+ const say = (e) => window.__emit?.("quince://photo-upload", { batch, within: "", sent: 0, total: 1000, folder: false, error: null, ...e });+ window.__photoLive = args.paths.map((path, i) => ({ id: `${batch}:${i}`, name: path.split("/").pop() }));+ setTimeout(() => {+ window.__photoLive.forEach((u) => say({ ...u, state: /\.txt$/.test(u.name) ? "failed" : "waiting",+ error: /\.txt$/.test(u.name) ? "Photos can’t add this kind of file." : null }));+ say({ ...window.__photoLive[0], state: "planned" });+ }, 0);+ return batch;+ }+ case "photos_upload_cancel": {+ (window.__photoCancels ??= []).push(args);+ for (const u of window.__photoLive ?? [])+ if (args.ids.includes(u.id) || (args.batch && u.id.startsWith(`${args.batch}:`)))+ window.__emit?.("quince://photo-upload", { ...u, batch: u.id.split(":")[0], within: "", sent: 0, total: 1000, folder: false, error: null, state: "cancelled" });+ return null;+ }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/check.sh b/check.shindex c032309..f29409d 100755--- a/check.sh+++ b/check.sh@@ -55,6 +55,7 @@ step "drive names" node .uiverify/drive-names.mjsstep "notes autoformat" node .uiverify/notes-autoformat.mjsstep "reminder ticks" node .uiverify/reminders-tick.mjsstep "photos" node .uiverify/photos.mjs+step "photo albums" node .uiverify/photos-albums.mjsstep "notes delete" node .uiverify/notes-delete.mjsstep "empty today" node .uiverify/reminders-empty.mjsstep "calendar keys" node .uiverify/calendar-keys.mjs@@ -93,6 +94,7 @@ step "webkit: drive names" env ENGINE=webkit node .uiverify/drive-names.mjsstep "webkit: autoformat" env ENGINE=webkit node .uiverify/notes-autoformat.mjsstep "webkit: ticks" env ENGINE=webkit node .uiverify/reminders-tick.mjsstep "webkit: photos" env ENGINE=webkit node .uiverify/photos.mjs+step "webkit: albums" env ENGINE=webkit node .uiverify/photos-albums.mjsstep "webkit: delete" env ENGINE=webkit node .uiverify/notes-delete.mjsstep "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjsstep "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjsdiff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rsindex 4f5e496..45bde1f 100644--- a/crates/quince-core/src/photos.rs+++ b/crates/quince-core/src/photos.rs@@ -80,6 +80,21 @@ pub struct Album {pub change_tag: Option<String>,}+/// A file on its way into Photos: waiting, sending, verifying (Apple making the photo), done,+/// failed (with why) or cancelled.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Upload {+ pub id: String,+ pub batch: String,+ pub path: String,+ pub name: String,+ pub state: String,+ pub error: Option<String>,+ pub asset: Option<String>,+ pub added_at: i64,+}+/// Which photos a view shows.#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]@@ -232,6 +247,65 @@ impl Library {Ok(out)}+ /// Files added to the upload queue, waiting.+ pub fn queue_uploads(&mut self, uploads: &[Upload]) -> Result<()> {+ let tx = self.conn.transaction()?;+ for u in uploads {+ tx.execute(+ "INSERT OR IGNORE INTO photo_uploads (id, batch, path, name, state, error, asset, added_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",+ params![u.id, u.batch, u.path, u.name, u.state, u.error, u.asset, u.added_at],+ )?;+ }+ tx.commit()?;+ Ok(())+ }++ /// An upload's state set, with why it failed or the photo it made.+ pub fn set_upload(+ &self,+ id: &str,+ state: &str,+ error: Option<&str>,+ asset: Option<&str>,+ ) -> Result<()> {+ self.conn.execute(+ "UPDATE photo_uploads SET state = ?2, error = ?3, asset = COALESCE(?4, asset) WHERE id = ?1",+ params![id, state, error, asset],+ )?;+ Ok(())+ }++ /// Uploads not yet finished, oldest first: what a launch resumes.+ pub fn unfinished_uploads(&self) -> Result<Vec<Upload>> {+ let mut stmt = self.conn.prepare(+ "SELECT id, batch, path, name, state, error, asset, added_at FROM photo_uploads+ WHERE state IN ('waiting', 'sending', 'verifying') ORDER BY added_at, id",+ )?;+ let rows = stmt.query_map([], |r| {+ Ok(Upload {+ id: r.get(0)?,+ batch: r.get(1)?,+ path: r.get(2)?,+ name: r.get(3)?,+ state: r.get(4)?,+ error: r.get(5)?,+ asset: r.get(6)?,+ added_at: r.get(7)?,+ })+ })?;+ Ok(rows.collect::<std::result::Result<_, _>>()?)+ }++ /// Finished uploads forgotten once their batch is: what the tray no longer shows.+ pub fn forget_finished_uploads(&self) -> Result<()> {+ self.conn.execute(+ "DELETE FROM photo_uploads WHERE state IN ('done', 'failed', 'cancelled')",+ [],+ )?;+ Ok(())+ }+/// The albums, replaced by `albums`.pub fn replace_albums(&mut self, albums: &[Album]) -> Result<()> {let tx = self.conn.transaction()?;@@ -295,6 +369,39 @@ impl Library {Ok(rows.collect::<std::result::Result<_, _>>()?)}+ /// One album added or changed, as Apple answered a write.+ pub fn put_album(&mut self, a: &Album) -> Result<()> {+ self.conn.execute(+ "INSERT INTO photo_albums (id, name, position, change_tag) VALUES (?1, ?2, ?3, ?4)+ ON CONFLICT(id) DO UPDATE SET name = excluded.name, position = excluded.position,+ change_tag = excluded.change_tag",+ params![a.id, a.name, a.position, a.change_tag],+ )?;+ Ok(())+ }++ /// An album gone, and which photos were in it with it. Apple leaves a deleted album's+ /// relation records standing, so they are dropped here.+ pub fn forget_album(&mut self, id: &str) -> Result<()> {+ let tx = self.conn.transaction()?;+ tx.execute("DELETE FROM photo_albums WHERE id = ?1", params![id])?;+ tx.execute(+ "DELETE FROM photo_album_items WHERE album = ?1",+ params![id],+ )?;+ tx.commit()?;+ Ok(())+ }++ /// Where the album's last photo sits, so what is added goes after it.+ pub fn album_last_position(&self, album: &str) -> Result<Option<i64>> {+ Ok(self.conn.query_row(+ "SELECT MAX(position) FROM photo_album_items WHERE album = ?1",+ params![album],+ |r| r.get(0),+ )?)+ }+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",diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 187e4d8..8f98087 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -413,4 +413,18 @@ pub const MIGRATIONS: &[&str] = &[PRIMARY KEY (album, asset)) STRICT;"#,+ // Photos uploads, kept until each is done: quitting halfway resumes where it stopped, and+ // a file is never thought sent until Apple has made the photo.+ r#"+ CREATE TABLE photo_uploads (+ id TEXT PRIMARY KEY,+ batch TEXT NOT NULL,+ path TEXT NOT NULL,+ name TEXT NOT NULL,+ state TEXT NOT NULL,+ error TEXT,+ asset TEXT,+ added_at INTEGER NOT NULL+ ) STRICT;+ "#,];diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rsindex b38d3a1..939d302 100644--- a/crates/quince-icloud/src/cloudkit.rs+++ b/crates/quince-icloud/src/cloudkit.rs@@ -923,6 +923,28 @@ impl ZoneClient<'_> {.await}+ /// Create a record CloudKit names itself, as icloud.com creates a Photos album: no+ /// `recordName` in the body. Answers the record made, its name with it.+ pub async fn create_record_unnamed(+ &self,+ zone: &str,+ record_type: &str,+ fields: Value,+ ) -> Result<Value> {+ let answer = self+ .modify(+ zone,+ json!({+ "operationType": "create",+ "record": { "recordType": record_type, "fields": fields },+ }),+ )+ .await?;+ answer.pointer("/records/0").cloned().ok_or_else(|| {+ Error::Protocol("CloudKit made the record but did not say what it is".into())+ })+ }+/// Remove a record outright.////// `forceDelete` is CloudKit's delete-regardless-of-change-tag. The alternative is todiff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rsindex 7cdef8c..8504797 100644--- a/crates/quince-icloud/src/lib.rs+++ b/crates/quince-icloud/src/lib.rs@@ -13,6 +13,7 @@ pub mod note_media;pub mod notes;pub mod occasions;pub mod photos;+pub mod photos_upload;pub mod push;pub mod reminders;pub mod sync;diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex ff1387a..86e75e0 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -195,6 +195,9 @@ pub fn apply(let mut gone: Vec<String> = Vec::new();let mut albums: Vec<Album> = Vec::new();let mut albums_seen = false;+ // Every album this pass speaks of: one deleted elsewhere arrives marked deleted, and has+ // to leave the list rather than stay as it was.+ let mut albums_touched: Vec<String> = Vec::new();// 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();@@ -230,6 +233,9 @@ pub fn apply(}Some("CPLAlbum") => {albums_seen = true;+ if let Some(id) = field::record_name(r) {+ albums_touched.push(id);+ }// 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@@ -280,7 +286,12 @@ pub fn apply(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.retain(|a| !albums_touched.contains(&a.id) && !gone.contains(&a.id));+ for id in albums_touched.iter().chain(&gone) {+ if !albums.iter().any(|b| &b.id == id) {+ library.forget_album(id)?;+ }+ }all.extend(albums);library.replace_albums(&all)?;}@@ -330,6 +341,155 @@ pub async fn set_flag(.await}+/// An album's name as Photos writes it: base64 of its UTF-8 bytes, untyped.+fn album_name(name: &str) -> String {+ base64::engine::general_purpose::STANDARD.encode(name.as_bytes())+}++/// Highest position an album or an album's item may take (`MAX_SAFE_INTEGER - 1024`).+pub const MAX_POSITION: i64 = 9_007_199_254_740_991 - 1024;+/// Gap between items added to an album, and the first item's position.+const ITEM_SPACING: i64 = 1024;++/// A new album, made as icloud.com makes one: CloudKit names it, it sorts first (two below+/// the first album there is), and its photos sort by date. Answers the album.+pub async fn create_album(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ name: &str,+ first_position: Option<i64>,+) -> Result<Album> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let position = first_position.map_or(MAX_POSITION, |p| (p - 2).max(0));+ let made = client+ .create_record_unnamed(+ ZONE,+ "CPLAlbum",+ serde_json::json!({+ "albumNameEnc": { "value": album_name(name) },+ "albumType": { "value": 0 },+ "isDeleted": { "value": 0 },+ "isExpunged": { "value": 0 },+ "position": { "value": position },+ "sortAscending": { "value": 1 },+ "sortType": { "value": 1 },+ }),+ )+ .await?;+ Ok(Album {+ id: field::record_name(&made).ok_or_else(|| {+ crate::Error::Protocol("CloudKit made the album without a name".into())+ })?,+ name: name.to_string(),+ position,+ change_tag: made+ .get("recordChangeTag")+ .and_then(Value::as_str)+ .map(str::to_string),+ })+}++/// An album renamed, against its change tag. Answers the new change tag.+pub async fn rename_album(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ album: &str,+ change_tag: Option<&str>,+ name: &str,+) -> Result<Option<String>> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let now = jiff::Timestamp::now().as_millisecond();+ let answer = client+ .update_record(+ ZONE,+ album,+ "CPLAlbum",+ change_tag,+ serde_json::json!({+ "albumNameEnc": { "value": album_name(name) },+ "userModificationDate": { "value": now },+ }),+ )+ .await?;+ Ok(answer+ .get("recordChangeTag")+ .and_then(Value::as_str)+ .map(str::to_string))+}++/// An album deleted, as Photos deletes one: marked deleted. Its photos stay in the library.+pub async fn delete_album(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ album: &str,+ change_tag: Option<&str>,+) -> Result<()> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ client+ .update_record(+ ZONE,+ album,+ "CPLAlbum",+ change_tag,+ serde_json::json!({ "isDeleted": { "value": 1 } }),+ )+ .await?;+ Ok(())+}++/// Photos put in an album, after what is there: a `CPLContainerRelation` each, named+/// `<asset>-IN-<album>`, 1024 apart. Answers each photo with the position it took.+pub async fn add_to_album(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ album: &str,+ assets: &[String],+ last_position: Option<i64>,+) -> Result<Vec<(String, i64)>> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ let mut at = last_position.unwrap_or(ITEM_SPACING);+ let mut added = Vec::new();+ for asset in assets {+ at = (at + ITEM_SPACING).min(MAX_POSITION);+ client+ .create_record(+ ZONE,+ &format!("{asset}-IN-{album}"),+ "CPLContainerRelation",+ serde_json::json!({+ "itemId": { "value": asset },+ "position": { "value": at },+ "containerId": { "value": album },+ }),+ )+ .await?;+ added.push((asset.clone(), at));+ }+ Ok(added)+}++/// Photos taken out of an album, as icloud.com takes them: their relation records removed+/// outright. The photos stay in the library.+pub async fn remove_from_album(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ album: &str,+ assets: &[String],+) -> Result<()> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ for asset in assets {+ client+ .delete_record(ZONE, &format!("{asset}-IN-{album}"))+ .await?;+ }+ Ok(())+}+/// The flags a photo carries that this app sets.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]#[serde(rename_all = "camelCase")]@@ -459,4 +619,55 @@ mod tests {apply(&mut lib, expunged).unwrap();assert!(lib.photo("A1").unwrap().is_none());}++ /// An album deleted on another device arrives marked deleted; it leaves the list, and+ /// its photos leave it with it (Apple leaves the relations standing), while a rename+ /// elsewhere is taken as it comes.+ #[test]+ fn an_album_deleted_elsewhere_goes() {+ let mut lib = quince_core::Library::in_memory().unwrap();+ let album = |name: &str, deleted: i64| {+ json!({"recordName": "AL", "recordType": "CPLAlbum", "fields": {+ "albumNameEnc": {"value": base64::engine::general_purpose::STANDARD.encode(name)},+ "albumType": {"value": 0}, "position": {"value": 5}, "isDeleted": {"value": deleted}}})+ };+ let relation = json!({"recordName": "A1-IN-AL", "recordType": "CPLContainerRelation", "fields": {"containerId": {"value": "AL"}, "itemId": {"value": "A1"}, "position": {"value": 1024}}});+ let pass = |records, incremental| PhotosFetch {+ records,+ token: Some("T".into()),+ incremental,+ complete: true,+ };+ apply(+ &mut lib,+ pass(+ vec![master(), asset(json!({})), album("Trips", 0), relation],+ false,+ ),+ )+ .unwrap();+ assert_eq!(lib.albums().unwrap()[0].name, "Trips");+ apply(&mut lib, pass(vec![album("Sea", 0)], true)).unwrap();+ assert_eq!(+ lib.albums().unwrap()[0].name,+ "Sea",+ "a rename elsewhere is taken"+ );+ apply(&mut lib, pass(vec![album("Sea", 1)], true)).unwrap();+ assert!(+ lib.albums().unwrap().is_empty(),+ "a deleted album leaves the list"+ );+ assert!(+ lib.album_photos("AL").unwrap().is_empty(),+ "and its photos with it"+ );+ assert_eq!(+ lib.photos(quince_core::photos::View::Library)+ .unwrap()+ .len(),+ 1,+ "the photos stay in the library"+ );+ }}diff --git a/crates/quince-icloud/src/photos_upload.rs b/crates/quince-icloud/src/photos_upload.rsnew file mode 100644index 0000000..c43cc5b--- /dev/null+++ b/crates/quince-icloud/src/photos_upload.rs@@ -0,0 +1,352 @@+//! Uploading to iCloud Photos, as icloud.com does it now (measured live 2026-10-19; the older+//! `uploadimagews …/upload` answers 410 Gone). Four steps on the `photosupload` service, each a+//! `POST {photosupload}/photosupload/<endpoint>?dsid=…` with a JSON body sent as text/plain:+//!+//! 1. `createUploadUrl` — where this file's bytes go;+//! 2. the bytes, sent there — answered with a receipt (`singleFile`), or `isDuplicate`;+//! 3. `putAsset` — the receipt made a photo: its asset and master names and a job id;+//! 4. `uploadStatus` — the job polled until Apple has made the photo (progress 100).+//!+//! A file is only ever read. A photo counts as uploaded once Apple's job says done, never on+//! the strength of a byte count. See docs/icloud-web/photos.md.++use crate::{Error, Result};+use serde_json::{json, Value};+use std::time::Duration;++/// What icloud.com checks before sending (photos3 constants): sizes and dimensions.+pub const MIN_BYTES: u64 = 125;+pub const MAX_BYTES: u64 = 524_288_000;+pub const MAX_SIDE: u32 = 20_480;+pub const MAX_AREA: u64 = 419_430_400;+pub const MAX_NAME: usize = 255;++/// The types icloud.com's current uploader takes, by extension.+const TYPES: [&str; 14] = [+ "jpg", "jpeg", "heic", "heif", "png", "gif", "tif", "tiff", "webp", "mov", "mp4", "m4v", "avi",+ "dng",+];++/// Why a file was not uploaded, in words a person can act on.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Refusal {+ /// The type Photos takes none of.+ Kind(String),+ TooSmall,+ TooLarge,+ NameTooLong,+ /// The photo is already in the library.+ Duplicate,+ /// iCloud is full.+ OverQuota,+}++impl Refusal {+ #[must_use]+ pub fn words(&self) -> String {+ match self {+ Refusal::Kind(ext) => format!("Photos doesn’t take .{ext} files."),+ Refusal::TooSmall => "That file is too small to be a photo.".into(),+ Refusal::TooLarge => "That file is larger than the 500 MB Photos takes.".into(),+ Refusal::NameTooLong => "That file’s name is longer than Photos takes.".into(),+ Refusal::Duplicate => "Already in your library.".into(),+ Refusal::OverQuota => "Your iCloud storage is full.".into(),+ }+ }+}++/// A file checked against Photos' limits before anything is sent; `None` when it may go.+#[must_use]+pub fn refusal(name: &str, size: u64) -> Option<Refusal> {+ let ext = name+ .rsplit_once('.')+ .map(|(_, e)| e.to_ascii_lowercase())+ .unwrap_or_default();+ if !TYPES.contains(&ext.as_str()) {+ return Some(Refusal::Kind(if ext.is_empty() { "?".into() } else { ext }));+ }+ if name.chars().count() > MAX_NAME {+ return Some(Refusal::NameTooLong);+ }+ if size < MIN_BYTES {+ return Some(Refusal::TooSmall);+ }+ if size > MAX_BYTES {+ return Some(Refusal::TooLarge);+ }+ None+}++/// Where an upload stands, for the window's tray.+#[derive(Debug, Clone, PartialEq)]+pub enum Stage {+ /// Bytes on their way: how many of how many.+ Sending(u64, u64),+ /// Apple has named the photo it is making: kept, so an upload resumed after a crash finds+ /// it rather than making a second copy.+ Named(Uploaded),+ /// Apple making the photo from them: 0 to 100.+ Processing(f64),+}++/// A finished upload: the photo Apple made.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Uploaded {+ pub asset: String,+ pub master: String,+}++/// How an upload ended, short of an error in the request itself.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Outcome {+ Uploaded(Uploaded),+ Refused(Refusal),+}++struct Service<'a> {+ http: &'a reqwest::Client,+ base: String,+ dsid: String,+}++impl Service<'_> {+ /// One call, retried as icloud.com retries it: up to three tries on a server error or+ /// throttling, the wait doubling from half a second, never past ten.+ async fn call(&self, endpoint: &str, body: &Value) -> Result<(u16, Value)> {+ let mut wait = Duration::from_millis(500);+ let mut last = None;+ for attempt in 1..=3 {+ let sent = self+ .http+ .post(format!("{}/photosupload/{endpoint}", self.base))+ .query(&[("dsid", &self.dsid)])+ .header("content-type", "text/plain;charset=UTF-8")+ .body(body.to_string())+ .send()+ .await;+ match sent {+ Ok(r) => {+ let status = r.status().as_u16();+ let text = r.text().await.unwrap_or_default();+ if status == 450 || status == 401 {+ return Err(Error::ReauthRequired);+ }+ if status == 429 || status >= 500 {+ last = Some(Error::Protocol(format!("{endpoint} answered {status}")));+ } else {+ let value = serde_json::from_str(&text).unwrap_or(Value::Null);+ if text.contains("QUOTA_EXCEEDED") {+ return Ok((507, value));+ }+ return Ok((status, value));+ }+ }+ Err(e) => last = Some(e.into()),+ }+ if attempt < 3 {+ tokio::time::sleep(wait).await;+ wait = (wait * 2).min(Duration::from_secs(10));+ }+ }+ Err(last.unwrap_or_else(|| Error::Protocol(format!("{endpoint} did not answer"))))+ }+}++/// One file uploaded to the library: checked, sent, made into a photo, and waited on until+/// Apple says it is there. `progress` hears each stage.+#[allow(clippy::too_many_arguments)]+pub async fn upload(+ http: &reqwest::Client,+ photosupload_root: &str,+ dsid: &str,+ path: &std::path::Path,+ name: &str,+ modified_ms: i64,+ time_zone: &str,+ offset_minutes: i64,+ import_group: &str,+ progress: std::sync::Arc<dyn Fn(Stage) + Send + Sync>,+) -> Result<Outcome> {+ let size = tokio::fs::metadata(path)+ .await+ .map_err(|e| Error::Protocol(format!("could not read {name}: {e}")))?+ .len();+ if let Some(r) = refusal(name, size) {+ return Ok(Outcome::Refused(r));+ }+ let service = Service {+ http,+ base: photosupload_root.trim_end_matches('/').to_string(),+ dsid: dsid.to_string(),+ };++ // 1. Where the bytes go.+ let key = uuid::Uuid::new_v4().to_string();+ let (status, answer) = service+ .call(+ "createUploadUrl",+ &json!({ "zoneName": crate::photos::ZONE, "assets": { &key: size } }),+ )+ .await?;+ if status == 507 {+ return Ok(Outcome::Refused(Refusal::OverQuota));+ }+ let url = answer+ .pointer(&format!("/uploadUrls/{key}"))+ .and_then(Value::as_str)+ .ok_or_else(|| Error::Protocol(format!("createUploadUrl gave no address ({status})")))?+ .to_string();++ // 2. The bytes, straight off disk in pieces and counted on the way past, never all in+ // memory: a video can be half a gigabyte.+ progress(Stage::Sending(0, size));+ let file = tokio::fs::File::open(path)+ .await+ .map_err(|e| Error::Protocol(format!("could not open {name}: {e}")))?;+ let counted = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));+ let stream = futures_util::stream::try_unfold(+ (file, counted, progress.clone()),+ move |(mut file, counted, progress)| async move {+ use tokio::io::AsyncReadExt;+ let mut buf = vec![0u8; 256 * 1024];+ let n = file.read(&mut buf).await?;+ if n == 0 {+ return Ok::<_, std::io::Error>(None);+ }+ buf.truncate(n);+ let so_far =+ counted.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed) + n as u64;+ progress(Stage::Sending(so_far, size));+ Ok(Some((buf, (file, counted, progress))))+ },+ );+ let sent = http+ .post(&url)+ .header("content-type", "text/plain")+ .header("content-length", size)+ .body(reqwest::Body::wrap_stream(stream))+ .send()+ .await?;+ let sent_status = sent.status();+ let text = sent.text().await.unwrap_or_default();+ if text.contains("QUOTA_EXCEEDED") {+ return Ok(Outcome::Refused(Refusal::OverQuota));+ }+ if !sent_status.is_success() {+ return Err(Error::Protocol(format!(+ "the upload answered {sent_status}"+ )));+ }+ let receipt: Value = serde_json::from_str(&text)+ .map_err(|e| Error::Protocol(format!("the upload's receipt was not JSON: {e}")))?;+ if receipt.get("isDuplicate").and_then(Value::as_bool) == Some(true) {+ return Ok(Outcome::Refused(Refusal::Duplicate));+ }+ let single = receipt+ .get("singleFile")+ .filter(|s| s.get("receipt").is_some())+ .ok_or_else(|| Error::Protocol("the upload gave no receipt".into()))?+ .clone();+ progress(Stage::Sending(size, size));++ // 3. The receipt made a photo.+ let (status, made) = service+ .call(+ "putAsset",+ &json!({+ "zoneName": crate::photos::ZONE,+ "localTimeZoneId": time_zone,+ "importGroup": import_group,+ "files": [{+ "fileName": name,+ "lastModDate": modified_ms,+ "timeZoneOffset": offset_minutes,+ "singleFileUploadRequest": single,+ }],+ }),+ )+ .await?;+ if status == 507 {+ return Ok(Outcome::Refused(Refusal::OverQuota));+ }+ let first = made.get(0).cloned().unwrap_or(Value::Null);+ let (Some(job), Some(asset), Some(master)) = (+ first.get("uploadJobId").and_then(Value::as_str),+ first.get("cplAsset").and_then(Value::as_str),+ first.get("cplMaster").and_then(Value::as_str),+ ) else {+ let said = first+ .pointer("/response/errorMessage")+ .and_then(Value::as_str)+ .unwrap_or("no photo was made");+ return Err(Error::Refused(format!(+ "iCloud didn’t take that photo: {said}"+ )));+ };++ progress(Stage::Named(Uploaded {+ asset: asset.to_string(),+ master: master.to_string(),+ }));++ // 4. Waited on until Apple says the photo is made: a second apart at first, then easing+ // off, for as long as the job is moving — a large video takes a while.+ progress(Stage::Processing(0.0));+ let mut wait = Duration::from_millis(800);+ let mut stalled = 0;+ let mut last = -1.0;+ loop {+ tokio::time::sleep(wait).await;+ let (_, status) = service+ .call("uploadStatus", &json!({ "uploadJobIds": [job] }))+ .await?;+ let state = status.get(job).cloned().unwrap_or(Value::Null);+ if let Some(code) = state.get("errorCode").and_then(Value::as_i64) {+ return Err(Error::Refused(format!(+ "iCloud couldn’t make that photo (error {code})."+ )));+ }+ let done = state.get("progress").and_then(Value::as_f64).unwrap_or(0.0);+ progress(Stage::Processing(done));+ if done >= 100.0 {+ return Ok(Outcome::Uploaded(Uploaded {+ asset: asset.to_string(),+ master: master.to_string(),+ }));+ }+ if done > last {+ last = done;+ stalled = 0;+ } else {+ stalled += 1;+ }+ // Five minutes without any movement is a job that will not finish.+ if stalled as u64 * wait.as_millis() as u64 > 300_000 {+ return Err(Error::Refused("iCloud stopped making that photo.".into()));+ }+ wait = (wait + Duration::from_millis(400)).min(Duration::from_secs(4));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Files Photos would refuse are refused here, with the reason, before anything is sent.+ #[test]+ fn files_are_checked_before_sending() {+ assert_eq!(refusal("IMG_0001.JPG", 2_000_000), None);+ assert_eq!(refusal("clip.mov", 80_000_000), None);+ assert_eq!(+ refusal("notes.txt", 2_000),+ Some(Refusal::Kind("txt".into()))+ );+ assert_eq!(refusal("noext", 2_000), Some(Refusal::Kind("?".into())));+ assert_eq!(refusal("a.jpg", 10), Some(Refusal::TooSmall));+ assert_eq!(refusal("a.jpg", MAX_BYTES + 1), Some(Refusal::TooLarge));+ assert_eq!(+ refusal(&format!("{}.jpg", "x".repeat(300)), 2_000),+ Some(Refusal::NameTooLong)+ );+ }+}diff --git a/probe/examples/photos_albums_roundtrip.rs b/probe/examples/photos_albums_roundtrip.rsnew file mode 100644index 0000000..b1ac3a9--- /dev/null+++ b/probe/examples/photos_albums_roundtrip.rs@@ -0,0 +1,107 @@+//! Live, on a throwaway album: Quince's album writes (quince_icloud::photos) end to end. Makes+//! "Quince probe album", puts two wallpapers in, takes one out, renames it, deletes it; each+//! step read back from Apple. The photos themselves are never touched.+use anyhow::{anyhow, Result};+use base64::Engine;+use quince_icloud::photos::{self, CONTAINER, ZONE};++#[tokio::main]+async fn main() -> Result<()> {+ let assets: Vec<String> = std::env::args().skip(1).collect();+ if assets.len() != 2 {+ return Err(anyhow!("two asset ids"));+ }+ 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 ck = 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, &ck, CONTAINER, p.clone());+ let name_of = |r: &serde_json::Value| {+ r.pointer("/fields/albumNameEnc/value")+ .and_then(|v| v.as_str())+ .and_then(|v| base64::engine::general_purpose::STANDARD.decode(v).ok())+ .map(|b| String::from_utf8_lossy(&b).into_owned())+ };++ let album = photos::create_album(&http, &ck, p.clone(), "Quince probe album", None).await?;+ let made = zc+ .lookup_record(ZONE, &album.id)+ .await?+ .ok_or_else(|| anyhow!("album not there"))?;+ println!(+ "created {} name={:?} position={:?}",+ album.id,+ name_of(&made),+ made.pointer("/fields/position/value")+ );++ let added = photos::add_to_album(&http, &ck, p.clone(), &album.id, &assets, None).await?;+ println!("added {added:?}");+ for a in &assets {+ let r = zc+ .lookup_record(ZONE, &format!("{a}-IN-{}", album.id))+ .await?;+ println!(+ " relation {a}: {}",+ r.map_or("MISSING".into(), |r| r["fields"].to_string())+ );+ }++ photos::remove_from_album(&http, &ck, p.clone(), &album.id, &assets[..1]).await?;+ let gone = zc+ .lookup_record(ZONE, &format!("{}-IN-{}", assets[0], album.id))+ .await?;+ println!(+ "removed first: relation now {}",+ if gone.is_none() {+ "gone"+ } else {+ "STILL THERE"+ }+ );+ let photo = zc.lookup_record(ZONE, &assets[0]).await?;+ println!(+ " the photo itself: {}",+ photo.map_or("MISSING".into(), |r| format!(+ "isDeleted={:?}",+ r.pointer("/fields/isDeleted/value")+ ))+ );++ let tag = photos::rename_album(+ &http,+ &ck,+ p.clone(),+ &album.id,+ album.change_tag.as_deref(),+ "Quince probe — renamed ✓",+ )+ .await?;+ let renamed = zc+ .lookup_record(ZONE, &album.id)+ .await?+ .ok_or_else(|| anyhow!("album gone"))?;+ println!("renamed: {:?}", name_of(&renamed));++ photos::delete_album(&http, &ck, p.clone(), &album.id, tag.as_deref()).await?;+ let deleted = zc.lookup_record(ZONE, &album.id).await?;+ println!(+ "deleted: isDeleted={:?}",+ deleted.and_then(|r| r.pointer("/fields/isDeleted/value").cloned())+ );+ // What the album's one remaining photo relation becomes once the album is deleted.+ let left = zc+ .lookup_record(ZONE, &format!("{}-IN-{}", assets[1], album.id))+ .await?;+ println!(+ " remaining relation after delete: {}",+ left.map_or("gone".into(), |r| r["fields"].to_string())+ );+ Ok(())+}diff --git a/probe/examples/photos_upload_quince.rs b/probe/examples/photos_upload_quince.rsnew file mode 100644index 0000000..6599e62--- /dev/null+++ b/probe/examples/photos_upload_quince.rs@@ -0,0 +1,78 @@+//! Live: Quince's own uploader (quince_icloud::photos_upload) sends the small test JPEG, with+//! its progress printed; the photo is confirmed in the library and then sent to Recently+//! Deleted. Run twice in a row, the second must say it is already in the library.+use anyhow::{anyhow, Result};+use quince_icloud::photos::Flag;+use quince_icloud::photos_upload::{Outcome, Stage};+#[tokio::main]+async fn main() -> Result<()> {+ let path = std::path::PathBuf::from(+ 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 name = path.file_name().unwrap().to_string_lossy().to_string();+ let t = std::time::Instant::now();+ let progress: std::sync::Arc<dyn Fn(Stage) + Send + Sync> =+ std::sync::Arc::new(move |s| println!(" {:>6.2}s {s:?}", t.elapsed().as_secs_f64()));+ let outcome = quince_icloud::photos_upload::upload(+ &http,+ &up,+ &dsid,+ &path,+ &name,+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)?+ .as_millis() as i64,+ "Asia/Kolkata",+ -330,+ &uuid::Uuid::new_v4().to_string(),+ progress,+ )+ .await?;+ println!("outcome: {outcome:?}");+ if let Outcome::Uploaded(u) = outcome {+ let zc = quince_icloud::cloudkit::ZoneClient::new(+ &http,+ &ck,+ "com.apple.photos.cloud",+ p.clone(),+ );+ let rec = zc+ .lookup_record("PrimarySync", &u.asset)+ .await?+ .ok_or_else(|| anyhow!("not in the library"))?;+ println!("in the library: yes");+ quince_icloud::photos::set_flag(+ &http,+ &ck,+ p,+ &u.asset,+ rec["recordChangeTag"].as_str(),+ Flag::Deleted,+ true,+ )+ .await?;+ println!("sent to Recently Deleted");+ }+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 10f9a63..44344c5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -3699,6 +3699,8 @@ fn main() {eprintln!("no tray on this desktop, so closing the window quits: {e}");}show_when_ready(app.handle());+ // Photos uploads a quit left half done carry on.+ photos::work(app.handle().clone());Ok(())}).invoke_handler(tauri::generate_handler![@@ -3759,6 +3761,13 @@ fn main() {photos::photos_in_album,photos::photo_set_flag,photos::photo_play,+ photos::photos_upload,+ photos::photos_upload_cancel,+ photos::photos_album_create,+ photos::photos_album_rename,+ photos::photos_album_delete,+ photos::photos_album_add,+ photos::photos_album_remove,photos::photo_download,note_table_add_row,note_table_remove,diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex fc8f7cf..d3b16a3 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -209,6 +209,176 @@ pub async fn photos_in_album(album: String, data: State<'_, Data>) -> UiResult<V.map_err(|e| e.to_string())}+/// A new album, first in the list as Photos puts one. Answers it as Apple made it.+#[tauri::command]+pub async fn photos_album_create(+ name: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<quince_core::photos::Album> {+ let name = name.trim();+ if name.is_empty() {+ return Err("An album needs a name.".into());+ }+ let _one = crate::PHOTOS_PASS.lock().await;+ let first = data+ .0+ .lock()+ .await+ .albums()+ .map_err(|e| e.to_string())?+ .iter()+ .map(|a| a.position)+ .min();+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ let album = quince_icloud::photos::create_album(&http, &root, params, name, first)+ .await+ .map_err(|e| e.to_string())?;+ data.0+ .lock()+ .await+ .put_album(&album)+ .map_err(|e| e.to_string())?;+ Ok(album)+}++/// An album renamed, against the change tag last seen.+#[tauri::command]+pub async fn photos_album_rename(+ id: String,+ name: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let name = name.trim();+ if name.is_empty() {+ return Err("An album needs a name.".into());+ }+ let _one = crate::PHOTOS_PASS.lock().await;+ let mut album = album_of(&data, &id).await?;+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ let tag = quince_icloud::photos::rename_album(+ &http,+ &root,+ params,+ &id,+ album.change_tag.as_deref(),+ name,+ )+ .await+ .map_err(|e| e.to_string())?;+ album.name = name.to_string();+ album.change_tag = tag.or(album.change_tag);+ data.0+ .lock()+ .await+ .put_album(&album)+ .map_err(|e| e.to_string())+}++/// An album deleted. Its photos stay in the library.+#[tauri::command]+pub async fn photos_album_delete(+ id: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let _one = crate::PHOTOS_PASS.lock().await;+ let album = album_of(&data, &id).await?;+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ quince_icloud::photos::delete_album(&http, &root, params, &id, album.change_tag.as_deref())+ .await+ .map_err(|e| e.to_string())?;+ data.0+ .lock()+ .await+ .forget_album(&id)+ .map_err(|e| e.to_string())+}++/// Photos put in an album after what is there. One already in it is not added twice.+#[tauri::command]+pub async fn photos_album_add(+ album: String,+ ids: Vec<String>,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let _one = crate::PHOTOS_PASS.lock().await;+ album_of(&data, &album).await?;+ let (fresh, last) = {+ let library = data.0.lock().await;+ let inside: std::collections::HashSet<String> = library+ .album_photos(&album)+ .map_err(|e| e.to_string())?+ .into_iter()+ .map(|p| p.id)+ .collect();+ let fresh: Vec<String> = ids.into_iter().filter(|i| !inside.contains(i)).collect();+ let last = library+ .album_last_position(&album)+ .map_err(|e| e.to_string())?;+ (fresh, last)+ };+ if fresh.is_empty() {+ return Ok(());+ }+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ let added =+ quince_icloud::photos::add_to_album(&http, &root, params, &album, &fresh, last).await;+ // What went in before a failure is in the album on Apple; the library says so too.+ let placed = match &added {+ Ok(a) => a.clone(),+ Err(_) => Vec::new(),+ };+ data.0+ .lock()+ .await+ .put_album_items(+ &placed+ .into_iter()+ .map(|(asset, at)| (album.clone(), asset, at))+ .collect::<Vec<_>>(),+ )+ .map_err(|e| e.to_string())?;+ added.map(|_| ()).map_err(|e| e.to_string())+}++/// Photos taken out of an album. They stay in the library.+#[tauri::command]+pub async fn photos_album_remove(+ album: String,+ ids: Vec<String>,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let _one = crate::PHOTOS_PASS.lock().await;+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ quince_icloud::photos::remove_from_album(&http, &root, params, &album, &ids)+ .await+ .map_err(|e| e.to_string())?;+ data.0+ .lock()+ .await+ .forget_album_items(+ &ids.into_iter()+ .map(|i| (album.clone(), i))+ .collect::<Vec<_>>(),+ )+ .map_err(|e| e.to_string())+}++async fn album_of(data: &State<'_, Data>, id: &str) -> UiResult<quince_core::photos::Album> {+ data.0+ .lock()+ .await+ .albums()+ .map_err(|e| e.to_string())?+ .into_iter()+ .find(|a| a.id == id)+ .ok_or_else(|| "That album is no longer there.".into())+}+/// 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.@@ -300,9 +470,11 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui.map_err(|e| format!("No app on this computer opens that video: {e}"))}-/// How many photos each view holds.+/// How many photos each view holds. Asked after every sync, which is also when an upload queue+/// paused for a session coming back starts again.#[tauri::command]-pub async fn photos_counts(data: State<'_, Data>) -> UiResult<Vec<(View, i64)>> {+pub async fn photos_counts(app: AppHandle, data: State<'_, Data>) -> UiResult<Vec<(View, i64)>> {+ work(app);data.0.lock().await@@ -335,3 +507,433 @@ pub async fn photo_download(id: String, app: AppHandle, data: State<'_, Data>) -.map_err(|e| e.to_string())?;Ok(path.display().to_string())}++/// Where Photos uploads tell the window how they are going: the same shape Drive's tray reads.+pub const PHOTO_UPLOAD: &str = "quince://photo-upload";++#[derive(Clone, serde::Serialize)]+struct UploadEvent {+ id: String,+ batch: String,+ name: String,+ within: String,+ sent: u64,+ total: u64,+ state: &'static str,+ folder: bool,+ error: Option<String>,+}++fn say(+ app: &AppHandle,+ u: &quince_core::photos::Upload,+ state: &'static str,+ sent: u64,+ total: u64,+ error: Option<String>,+) {+ use tauri::Emitter;+ app.emit(+ PHOTO_UPLOAD,+ UploadEvent {+ id: u.id.clone(),+ batch: u.batch.clone(),+ name: u.name.clone(),+ within: String::new(),+ sent,+ total,+ state,+ folder: false,+ error,+ },+ )+ .ok();+}++/// One worker at a time drains the queue, as icloud.com uploads one file at a time.+static WORKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+/// Batches, and single uploads, asked to stop.+static CANCELLED: Mutex<Vec<String>> = Mutex::new(Vec::new());+/// The upload on its way, so Cancel can stop it mid-file rather than after it lands.+static CURRENT: Mutex<Option<(String, String, futures_util::future::AbortHandle)>> =+ Mutex::new(None);++fn cancelled(u: &quince_core::photos::Upload) -> bool {+ CANCELLED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .iter()+ .any(|b| *b == u.batch || *b == u.id)+}++/// Files (and the photos and videos inside folders) added to Photos. Each is checked against+/// Photos' limits first; a file Photos would refuse is answered at once with why, and never+/// sent. Answers the batch, whose progress comes as `quince://photo-upload` events.+#[tauri::command]+pub async fn photos_upload(+ paths: Vec<String>,+ app: AppHandle,+ data: State<'_, Data>,+) -> UiResult<String> {+ let batch = uuid::Uuid::new_v4().to_string();+ let mut files = Vec::new();+ for p in paths {+ let path = PathBuf::from(&p);+ if path.is_dir() {+ let mut stack = vec![path];+ while let Some(dir) = stack.pop() {+ let Ok(mut entries) = tokio::fs::read_dir(&dir).await else {+ continue;+ };+ while let Ok(Some(e)) = entries.next_entry().await {+ let p = e.path();+ if p.is_dir() {+ stack.push(p);+ } else {+ files.push(p);+ }+ }+ }+ } else {+ files.push(path);+ }+ }+ files.sort();+ let now = jiff::Timestamp::now().as_second();+ let mut queued = Vec::new();+ for path in files {+ let name = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ let size = tokio::fs::metadata(&path)+ .await+ .map(|m| m.len())+ .unwrap_or(0);+ let mut u = quince_core::photos::Upload {+ id: uuid::Uuid::new_v4().to_string(),+ batch: batch.clone(),+ path: path.to_string_lossy().into_owned(),+ name: name.clone(),+ state: "waiting".into(),+ error: None,+ asset: None,+ added_at: now,+ };+ if let Some(r) = quince_icloud::photos_upload::refusal(&name, size) {+ u.state = "failed".into();+ u.error = Some(r.words());+ }+ queued.push((u, size));+ }+ if queued.is_empty() {+ return Err("There are no photos or videos there to add.".into());+ }+ data.0+ .lock()+ .await+ .queue_uploads(&queued.iter().map(|(u, _)| u.clone()).collect::<Vec<_>>())+ .map_err(|e| e.to_string())?;+ for (u, size) in &queued {+ say(+ &app,+ u,+ if u.state == "failed" {+ "failed"+ } else {+ "waiting"+ },+ 0,+ *size,+ u.error.clone(),+ );+ }+ if let Some((u, _)) = queued.first() {+ say(&app, u, "planned", 0, 0, None);+ }+ work(app);+ Ok(batch)+}++/// Stop uploads, by id or a whole batch: what is waiting is not sent, and the file on its way+/// is abandoned mid-send. A photo Apple has already made stays (it is in the library, and can+/// be deleted there).+#[tauri::command]+pub async fn photos_upload_cancel(+ ids: Vec<String>,+ batch: Option<String>,+ app: AppHandle,+ data: State<'_, Data>,+) -> UiResult<()> {+ let wanted = |id: &str, b: &str| ids.iter().any(|i| i == id) || batch.as_deref() == Some(b);+ CANCELLED+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .extend(ids.iter().cloned().chain(batch.clone()));+ if let Some((id, b, handle)) = CURRENT+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ {+ if wanted(id, b) {+ handle.abort();+ }+ }+ let library = data.0.lock().await;+ for u in library.unfinished_uploads().map_err(|e| e.to_string())? {+ if wanted(&u.id, &u.batch) && u.state == "waiting" {+ library+ .set_upload(&u.id, "cancelled", None, None)+ .map_err(|e| e.to_string())?;+ say(&app, &u, "cancelled", 0, 0, None);+ }+ }+ Ok(())+}++/// The queue drained, one file at a time; started on demand and at launch to resume what a+/// quit left half done.+pub fn work(app: AppHandle) {+ if WORKING.swap(true, std::sync::atomic::Ordering::SeqCst) {+ return;+ }+ tauri::async_runtime::spawn(async move {+ loop {+ let next = {+ let data = app.state::<Data>();+ let library = data.0.lock().await;+ library+ .unfinished_uploads()+ .ok()+ .and_then(|u| u.into_iter().next())+ };+ let Some(u) = next else { break };+ if !one(&app, u).await {+ break;+ }+ }+ WORKING.store(false, std::sync::atomic::Ordering::SeqCst);+ });+}++/// One upload, to its end. False when the queue must pause (the session lapsed).+async fn one(app: &AppHandle, u: quince_core::photos::Upload) -> bool {+ let set = |state: &str, error: Option<&str>, asset: Option<&str>| {+ let data = app.state::<Data>();+ let (id, state, error, asset) = (+ u.id.clone(),+ state.to_string(),+ error.map(str::to_string),+ asset.map(str::to_string),+ );+ async move {+ data.0+ .lock()+ .await+ .set_upload(&id, &state, error.as_deref(), asset.as_deref())+ .ok();+ }+ };+ if cancelled(&u) {+ set("cancelled", None, None).await;+ say(app, &u, "cancelled", 0, 0, None);+ return true;+ }+ let auth = app.state::<Auth>();+ let (http, ck, params, upload_root) = {+ let client = auth.client.lock().await;+ let s = client.session();+ (+ client.http().clone(),+ s.service_url("ckdatabasews"),+ client.service_params(),+ s.service_url("photosupload"),+ )+ };+ // Not signed in yet (a launch resumes before the session is back): the queue waits, and+ // is started again by the next sync.+ let (Some(ck), Some(upload_root)) = (ck, upload_root) else {+ return false;+ };+ // Resumed after a quit: a photo Apple had already named is not made twice.+ if let Some(asset) = u.asset.as_deref() {+ let zc = quince_icloud::cloudkit::ZoneClient::new(+ &http,+ &ck,+ quince_icloud::photos::CONTAINER,+ params.clone(),+ );+ if matches!(+ zc.lookup_record(quince_icloud::photos::ZONE, asset).await,+ Ok(Some(_))+ ) {+ set("done", None, Some(asset)).await;+ say(app, &u, "done", 1, 1, None);+ refresh_photos(app).await;+ return true;+ }+ }+ let path = PathBuf::from(&u.path);+ let Ok(meta) = tokio::fs::metadata(&path).await else {+ set("failed", Some("That file is no longer there."), None).await;+ say(+ app,+ &u,+ "failed",+ 0,+ 0,+ Some("That file is no longer there.".into()),+ );+ return true;+ };+ let size = meta.len();+ let modified = meta+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(0));+ let zone = jiff::tz::TimeZone::system();+ let zone_name = zone.iana_name().unwrap_or("UTC").to_string();+ let offset = -i64::from(jiff::Zoned::now().offset().seconds()) / 60;+ let dsid = params+ .iter()+ .find(|(k, _)| k == "dsid")+ .map(|(_, v)| v.clone())+ .unwrap_or_default();+ set("sending", None, None).await;+ say(app, &u, "sending", 0, size, None);++ let mut attempt = 0;+ loop {+ attempt += 1;+ // Cancelled while waiting to try again.+ if attempt > 1 && cancelled(&u) {+ set("cancelled", None, None).await;+ say(app, &u, "cancelled", 0, size, None);+ return true;+ }+ let app2 = app.clone();+ let u2 = u.clone();+ let last = std::sync::Arc::new(Mutex::new(Instant::now() - Duration::from_secs(1)));+ let progress: std::sync::Arc<dyn Fn(quince_icloud::photos_upload::Stage) + Send + Sync> =+ std::sync::Arc::new(move |stage| {+ use quince_icloud::photos_upload::Stage;+ match stage {+ Stage::Sending(sent, total) => {+ // A few times a second at most: every piece would flood the window.+ let mut at = last+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if sent == total || at.elapsed() > Duration::from_millis(120) {+ *at = Instant::now();+ say(&app2, &u2, "sending", sent, total, None);+ }+ }+ Stage::Named(made) => {+ let (app3, id) = (app2.clone(), u2.id.clone());+ tauri::async_runtime::spawn(async move {+ let data = app3.state::<Data>();+ data.0+ .lock()+ .await+ .set_upload(&id, "verifying", None, Some(&made.asset))+ .ok();+ });+ }+ Stage::Processing(done) => {+ say(+ &app2,+ &u2,+ "verifying",+ (done.clamp(0.0, 100.0) as u64) * size / 100,+ size,+ None,+ );+ }+ }+ });+ let (handle, registration) = futures_util::future::AbortHandle::new_pair();+ *CURRENT+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) =+ Some((u.id.clone(), u.batch.clone(), handle));+ let result = futures_util::future::Abortable::new(+ quince_icloud::photos_upload::upload(+ &http,+ &upload_root,+ &dsid,+ &path,+ &u.name,+ modified,+ &zone_name,+ offset,+ &u.batch,+ progress,+ ),+ registration,+ )+ .await;+ CURRENT+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take();+ let Ok(result) = result else {+ set("cancelled", None, None).await;+ say(app, &u, "cancelled", 0, size, None);+ // Apple may already have made it; the library shows what is true.+ refresh_photos(app).await;+ return true;+ };+ use quince_icloud::photos_upload::{Outcome, Refusal};+ match result {+ Ok(Outcome::Uploaded(made)) => {+ set("done", None, Some(&made.asset)).await;+ say(app, &u, "done", size, size, None);+ refresh_photos(app).await;+ return true;+ }+ Ok(Outcome::Refused(Refusal::Duplicate)) => {+ set("done", Some("Already in your library."), None).await;+ say(app, &u, "done", size, size, None);+ return true;+ }+ Ok(Outcome::Refused(r)) => {+ set("failed", Some(&r.words()), None).await;+ say(app, &u, "failed", 0, size, Some(r.words()));+ return true;+ }+ Err(quince_icloud::Error::ReauthRequired) => {+ // Not a failure of this file: the queue waits for the session to come back.+ set("waiting", None, None).await;+ say(+ app,+ &u,+ "waiting",+ 0,+ size,+ Some("Waiting for iCloud to sign back in.".into()),+ );+ return false;+ }+ Err(e) if attempt < 3 && !cancelled(&u) => {+ eprintln!("photos upload of {}: try {attempt} failed: {e}", u.name);+ tokio::time::sleep(Duration::from_secs(2 * attempt)).await;+ }+ Err(e) => {+ let words = e.to_string();+ set("failed", Some(&words), None).await;+ say(app, &u, "failed", 0, size, Some(words));+ return true;+ }+ }+ }+}++async fn refresh_photos(app: &AppHandle) {+ use tauri::Emitter;+ let auth = app.state::<Auth>();+ let data = app.state::<Data>();+ crate::refresh::some(&auth.client, &data.0, &["photos"]).await;+ app.emit(crate::SYNCED, crate::refresh::status(&data.0).await)+ .ok();+}diff --git a/src/components/UploadTray.tsx b/src/components/UploadTray.tsxindex 044a23a..62e8dd9 100644--- a/src/components/UploadTray.tsx+++ b/src/components/UploadTray.tsx@@ -80,7 +80,16 @@ function measure(item: Item, planned: boolean) {* opens to show what in it did not upload, and why. When everything has gone up cleanly the* tray steps aside on its own; anything that failed keeps it until it is read.*/-export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onDismiss: () => void }) {+export function UploadTray({+ uploads,+ onDismiss,+ cancel = api.driveUploadCancel,+}: {+ uploads: UploadEvent[];+ onDismiss: () => void;+ /** Stops uploads by id, or a whole batch; Drive's unless the screen says otherwise. */+ cancel?: (ids: string[], batch?: string) => Promise<void>;+}) {const [open, setOpen] = useState<string | null>(null);const items = group(uploads);const planned = new Set(uploads.filter((u) => u.state === "planned").map((u) => u.batch));@@ -148,7 +157,7 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onD{active ? (<span className="upload-tray-actions">{allPlanned && <span className="upload-tray-percent">{percent}%</span>}- <button className="upload-tray-close" onClick={() => batches.forEach((b) => void api.driveUploadCancel([], b))}>+ <button className="upload-tray-close" onClick={() => batches.forEach((b) => void cancel([], b))}>Cancel</button></span>@@ -202,7 +211,7 @@ export function UploadTray({ uploads, onDismiss }: { uploads: UploadEvent[]; onDclassName="upload-stop"aria-label={`Cancel ${item.name}`}title="Cancel"- onClick={() => void api.driveUploadCancel(stoppable.map((u) => u.id))}+ onClick={() => void cancel(stoppable.map((u) => u.id))}>✕</button>diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex ffe83e2..d803fcd 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -33,6 +33,7 @@ export type Refresh = {/** Emitted by the backend whenever a refresh finishes, background ones included. *//** Where each uploading file's progress is announced. */export const UPLOAD = "quince://upload";+export const PHOTO_UPLOAD = "quince://photo-upload";/** One file's upload, as it moves. */export type UploadEvent = {@@ -98,6 +99,16 @@ export const api = {invoke<Photo>("photo_set_flag", { id, flag, on }),/** The original saved to Downloads; answers where. */photoDownload: (id: string) => invoke<string>("photo_download", { id }),+ /** Photos and videos (or folders of them) into the library. Answers the batch; progress+ * arrives as PHOTO_UPLOAD events, in the same shape as Drive's. */+ photosUpload: (paths: string[]) => invoke<string>("photos_upload", { paths }),+ photosAlbumCreate: (name: string) => invoke<PhotoAlbum>("photos_album_create", { name }),+ photosAlbumRename: (id: string, name: string) => invoke<void>("photos_album_rename", { id, name }),+ photosAlbumDelete: (id: string) => invoke<void>("photos_album_delete", { id }),+ photosAlbumAdd: (album: string, ids: string[]) => invoke<void>("photos_album_add", { album, ids }),+ photosAlbumRemove: (album: string, ids: string[]) => invoke<void>("photos_album_remove", { album, ids }),+ photosUploadCancel: (ids: string[], batch?: string) =>+ invoke<void>("photos_upload_cancel", { ids, batch: batch ?? null }),/** 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 }) =>diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 7a07bbe..654da3f 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -3,11 +3,25 @@* 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { listen } from "@tauri-apps/api/event";+import { getCurrentWebview } from "@tauri-apps/api/webview";+import { open as openFileDialog } from "@tauri-apps/plugin-dialog";+import { ChevronLeft, ChevronRight, CopyMinus, CopyPlus, Download, Heart, Info, Play, Plus, RotateCcw, Trash2, X } from "lucide-react";+import {+ api,+ messageOf,+ pictureSrc,+ PHOTO_UPLOAD,+ type Photo,+ type PhotoAlbum,+ type PhotoView,+ type UploadEvent,+} from "../lib/ipc";import { useSync } from "../lib/sync";import { Notice } from "../components/Notice";+import { UploadTray } from "../components/UploadTray";+import { RowMenu, type MenuEntry } from "../components/RowMenu";const VIEWS: { key: PhotoView; label: string }[] = [{ key: "library", label: "Library" },@@ -24,6 +38,9 @@ const ACROSS = [10, 7, 5, 3];const monthOf = (seconds: number) =>new Date(seconds * 1000).toLocaleDateString(undefined, { month: "long", year: "numeric" });+/** What Photos takes, as icloud.com's picker offers it. */+const KINDS = ["jpg", "jpeg", "heic", "heif", "png", "gif", "tif", "tiff", "webp", "dng", "mov", "mp4", "m4v", "avi"];+const clock = (s: number | null) => {if (!s) return "";const m = Math.floor(s / 60);@@ -43,6 +60,11 @@ export function PhotosView() {const [open, setOpen] = useState<number | null>(null);const [info, setInfo] = useState(false);const [saved, setSaved] = useState<string | null>(null);+ const [uploads, setUploads] = useState<Map<string, UploadEvent>>(new Map());+ const [dropping, setDropping] = useState(false);+ const [menu, setMenu] = useState<{ at: { x: number; y: number; alignRight: boolean }; entries: MenuEntry[] } | null>(null);+ /** An album being named in the sidebar: a new one (with the photos to put in it), or a rename. */+ const [naming, setNaming] = useState<{ id: string | null; then: string[]; draft: string } | null>(null);const read = useCallback(async () => {const [list, c, a] = await Promise.all([@@ -91,6 +113,7 @@ export function PhotosView() {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 && album) void removeFrom([current]);else if ((e.key === "Delete" || e.key === "Backspace") && current && view !== "recentlyDeleted") void change(current, "deleted", true);else return;e.preventDefault();@@ -135,6 +158,151 @@ export function PhotosView() {}};+ /*+ * Albums, as Photos keeps them: every change shows at once and goes to iCloud behind it; a+ * refusal puts the list back and says why. A new album sorts first, as Photos puts it.+ */+ const createAlbum = async (name: string, then: string[]) => {+ const before = albums;+ const temp: PhotoAlbum = { id: `new:${Date.now()}`, name, position: -1, changeTag: null };+ setAlbums((list) => [[temp, then.length], ...list]);+ try {+ const made = await api.photosAlbumCreate(name);+ setAlbums((list) => list.map((x) => (x[0].id === temp.id ? [made, x[1]] : x)));+ if (then.length) await api.photosAlbumAdd(made.id, then);+ read().catch(() => {});+ } catch (e) {+ setAlbums(before);+ setError(messageOf(e));+ }+ };++ const renameAlbum = async (a: PhotoAlbum, name: string) => {+ if (name === a.name) return;+ const before = albums;+ setAlbums((list) => list.map((x) => (x[0].id === a.id ? [{ ...x[0], name }, x[1]] : x)));+ if (album?.id === a.id) setAlbum({ ...a, name });+ try {+ await api.photosAlbumRename(a.id, name);+ } catch (e) {+ setAlbums(before);+ if (album?.id === a.id) setAlbum(a);+ setError(messageOf(e));+ }+ };++ const deleteAlbum = async (a: PhotoAlbum) => {+ if (!window.confirm(`Delete the album “${a.name}”?\n\nThe photos in it stay in your library.`)) return;+ const before = albums;+ setAlbums((list) => list.filter((x) => x[0].id !== a.id));+ if (album?.id === a.id) setAlbum(null);+ try {+ await api.photosAlbumDelete(a.id);+ } catch (e) {+ setAlbums(before);+ setError(messageOf(e));+ }+ };++ const addTo = async (a: PhotoAlbum, ids: string[]) => {+ const before = albums;+ setAlbums((list) => list.map((x) => (x[0].id === a.id ? [x[0], x[1] + ids.length] : x)));+ try {+ await api.photosAlbumAdd(a.id, ids);+ setSaved(ids.length === 1 ? `Added to ${a.name}` : `${ids.length} added to ${a.name}`);+ read().catch(() => {});+ } catch (e) {+ setAlbums(before);+ setError(messageOf(e));+ }+ };++ /** Out of the album open; the photos stay in the library. */+ const removeFrom = async (gone: Photo[]) => {+ if (!album) return;+ const n = gone.length;+ if (!window.confirm(`Remove ${n === 1 ? "this photo" : `${n} photos`} from the album?\n\n${n === 1 ? "It stays" : "They stay"} in your library.`)) return;+ const before = photos;+ const ids = new Set(gone.map((p) => p.id));+ setPhotos((list) => (list ?? []).filter((x) => !ids.has(x.id)));+ setAlbums((list) => list.map((x) => (x[0].id === album.id ? [x[0], Math.max(0, x[1] - n)] : x)));+ setOpen((at) => {+ if (at === null || !photos) return at;+ const left = photos.length - n;+ return left <= 0 ? null : Math.min(at, left - 1);+ });+ try {+ await api.photosAlbumRemove(album.id, [...ids]);+ read().catch(() => {});+ } catch (e) {+ setPhotos(before);+ setError(messageOf(e));+ }+ };++ const albumEntries = (ids: string[]): MenuEntry[] => [+ ...albums.filter(([a]) => a.id !== album?.id && !a.id.startsWith("new:")).map(([a]) => ({ label: a.name, run: () => void addTo(a, ids) })),+ ...(albums.length ? [null] : []),+ { label: "New Album…", run: () => setNaming({ id: null, then: ids, draft: "" }) },+ ];++ const photoMenu = (p: Photo, at: { x: number; y: number; alignRight: boolean }) => {+ const entries: MenuEntry[] =+ view === "recentlyDeleted" && !album+ ? [{ label: "Recover", run: () => void change(p, "deleted", false) }]+ : [+ { label: p.favorite ? "Unfavorite" : "Favorite", run: () => void change(p, "favorite", !p.favorite) },+ { label: "Download", run: () => void download(p) },+ null,+ { label: "Add to Album", submenu: albumEntries([p.id]) },+ null,+ album+ ? { label: "Remove from Album", danger: true, run: () => void removeFrom([p]) }+ : { label: "Delete", danger: true, run: () => void change(p, "deleted", true) },+ ];+ setMenu({ at, entries });+ };++ // Enter submits and closes the field, and closing it blurs it, which would submit again+ // with the same name still in hand: one album per name typed.+ const namedOnce = useRef(false);+ useEffect(() => {+ if (naming) namedOnce.current = false;+ }, [naming === null]); // eslint-disable-line react-hooks/exhaustive-deps+ const finishNaming = () => {+ if (!naming || namedOnce.current) return;+ namedOnce.current = true;+ const name = naming.draft.trim();+ setNaming(null);+ if (!name) return;+ if (naming.id === null) void createAlbum(name, naming.then);+ else {+ const a = albums.find(([x]) => x.id === naming.id)?.[0];+ if (a) void renameAlbum(a, name);+ }+ };++ const nameField = (+ <input+ className="px-source px-naming"+ aria-label="Album name"+ autoFocus+ value={naming?.draft ?? ""}+ placeholder="Untitled Album"+ onChange={(e) => setNaming((n) => (n ? { ...n, draft: e.target.value } : n))}+ onKeyDown={(e) => {+ if (e.key === "Enter") finishNaming();+ else if (e.key === "Escape") {+ namedOnce.current = true;+ setNaming(null);+ }+ e.stopPropagation();+ }}+ onBlur={finishNaming}+ onFocus={(e) => e.currentTarget.select()}+ />+ );+const play = async (p: Photo) => {try {await api.photoPlay(p.id);@@ -152,11 +320,94 @@ export function PhotosView() {}};+ // Uploads report as they go; a finished one never goes back, as events can pass each other.+ // The library itself is redrawn by the sync each landed photo starts.+ useEffect(() => {+ let stop: (() => void) | undefined;+ let cancelled = false;+ listen<UploadEvent>(PHOTO_UPLOAD, (event) => {+ const u = event.payload;+ setUploads((was) => {+ const before = was.get(u.id);+ if (before && (before.state === "done" || before.state === "failed" || before.state === "cancelled")) return was;+ return new Map(was).set(u.id, u);+ });+ })+ .then((unlisten) => {+ const quietly = () => {+ try {+ void Promise.resolve(unlisten() as unknown).catch(() => {});+ } catch {+ // Nothing was listening.+ }+ };+ if (cancelled) quietly();+ else stop = quietly;+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ stop?.();+ };+ }, []);+ const dismissUploads = useCallback(() => setUploads(new Map()), []);++ const add = useCallback(async (paths: string[]) => {+ if (paths.length === 0) return;+ try {+ await api.photosUpload(paths);+ } catch (e) {+ setError(messageOf(e));+ }+ }, []);++ const choose = async () => {+ try {+ const chosen = await openFileDialog({+ multiple: true,+ title: "Add to iCloud Photos",+ filters: [{ name: "Photos and Videos", extensions: KINDS }],+ });+ if (chosen) await add(Array.isArray(chosen) ? chosen : [chosen]);+ } catch (e) {+ setError(messageOf(e));+ }+ };++ // Photos and videos dropped on the window go into the library. Outside the app shell there+ // is no webview to ask; the button still works.+ useEffect(() => {+ let stop: (() => void) | undefined;+ let cancelled = false;+ try {+ void getCurrentWebview()+ .onDragDropEvent((event) => {+ if (event.payload.type === "over") setDropping(true);+ else if (event.payload.type === "leave") setDropping(false);+ else if (event.payload.type === "drop") {+ setDropping(false);+ void add(event.payload.paths);+ }+ })+ .then((unlisten) => {+ if (cancelled) unlisten();+ else stop = unlisten;+ })+ .catch(() => {});+ } catch {+ // No drag and drop here.+ }+ return () => {+ cancelled = true;+ stop?.();+ };+ }, [add]);+const title = album?.name ?? VIEWS.find((v) => v.key === view)?.label ?? "Photos";const across = ACROSS[zoom];return (- <div className="px">+ <div className={`px${dropping ? " is-dropping" : ""}`}><aside className="px-side" aria-label="Photos"><p className="px-side-heading">Photos</p>{VIEWS.map((v) => (@@ -174,24 +425,43 @@ export function PhotosView() {{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>- ))}- </>+ <div className="px-side-row">+ <p className="px-side-heading">Albums</p>+ <button className="px-side-add" aria-label="New Album" title="New Album" onClick={() => setNaming({ id: null, then: [], draft: "" })}>+ <Plus size={14} strokeWidth={2} aria-hidden="true" />+ </button>+ </div>+ {naming?.id === null && nameField}+ {albums.map(([a, n]) =>+ naming?.id === a.id ? (+ <span key={a.id}>{nameField}</span>+ ) : (+ <button+ key={a.id}+ className="px-source"+ aria-current={album?.id === a.id}+ onClick={() => {+ setAlbum(a);+ setOpen(null);+ }}+ onDoubleClick={() => setNaming({ id: a.id, then: [], draft: a.name })}+ onContextMenu={(e) => {+ e.preventDefault();+ if (a.id.startsWith("new:")) return;+ setMenu({+ at: { x: e.clientX, y: e.clientY, alignRight: false },+ entries: [+ { label: "Rename Album", run: () => setNaming({ id: a.id, then: [], draft: a.name }) },+ null,+ { label: "Delete Album", danger: true, run: () => void deleteAlbum(a) },+ ],+ });+ }}+ >+ <span>{a.name}</span>+ {n ? <span className="px-count">{n}</span> : null}+ </button>+ ),)}</aside>@@ -213,6 +483,9 @@ export function PhotosView() {onChange={(e) => setZoom(Number(e.target.value))}/></label>+ <button className="px-add" onClick={() => void choose()} title="Add photos and videos" aria-label="Add Photos">+ <Plus size={16} strokeWidth={2} aria-hidden="true" />+ </button></header>{photos && photos.length === 0 && (@@ -239,6 +512,10 @@ export function PhotosView() {className="px-tile"aria-label={`${photo.filename ?? "Photo"}, ${new Date(photo.takenAt * 1000).toLocaleString()}`}onClick={() => setOpen(index)}+ onContextMenu={(e) => {+ e.preventDefault();+ photoMenu(photo, { x: e.clientX, y: e.clientY, alignRight: false });+ }}><img src={pictureSrc(photo.id, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />{photo.kind === "video" && (@@ -282,9 +559,27 @@ export function PhotosView() {><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+ className="px-icon"+ aria-label="Add to Album"+ aria-haspopup="menu"+ title="Add to Album"+ onClick={(e) => {+ const r = e.currentTarget.getBoundingClientRect();+ setMenu({ at: { x: r.right, y: r.bottom + 4, alignRight: true }, entries: albumEntries([shown.id]) });+ }}+ >+ <CopyPlus size={17} /></button>+ {album ? (+ <button className="px-icon" aria-label="Remove from Album" title="Remove from Album (Delete)" onClick={() => void removeFrom([shown])}>+ <CopyMinus size={17} />+ </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)}>@@ -342,6 +637,8 @@ export function PhotosView() {{saved}</p>)}+ {menu && <RowMenu at={menu.at} entries={menu.entries} onClose={() => setMenu(null)} />}+ <UploadTray uploads={[...uploads.values()]} onDismiss={dismissUploads} cancel={api.photosUploadCancel} /></div>);}diff --git a/src/styles/photos.css b/src/styles/photos.cssindex 2df1ca2..f36cf65 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -43,6 +43,33 @@.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-side-row { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; }+.px-side-row .px-side-heading { margin-bottom: 4px; }+.px-side-add {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ margin-right: 4px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--text-3);+ opacity: 0;+ transition: opacity 120ms ease;+}+/* As in Finder and Photos: the + shows when the sidebar is pointed at or the keys reach it. */+.px-side:hover .px-side-add,+.px-side-add:focus-visible { opacity: 1; }+.px-side-add:hover { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); }+.px-naming {+ width: 100%;+ font: inherit;+ outline: 2px solid var(--accent-ring);+ outline-offset: -2px;+ background: var(--surface, transparent);+ cursor: text;+}.px-count { color: var(--text-3); font-variant-numeric: tabular-nums; font-size: var(--t-12, 12px); }/* ---- the library ------------------------------------------------------------------------- */@@ -57,6 +84,40 @@.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-add {+ align-self: center;+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: var(--text-2);+ cursor: default;+}+.px-add:hover { background: color-mix(in srgb, currentColor 9%, transparent); color: var(--text); }+.px-add:active { transform: scale(0.94); }+.px-add:focus-visible { outline: 2px solid var(--accent-ring); outline-offset: 1px; }++/* A drop into the library: the whole window answers, as Photos does. No live blur — WebKitGTK+ repaints it every frame the pointer moves. */+.px { position: relative; }+.px.is-dropping::after {+ content: "Add to Library";+ position: absolute;+ inset: 8px;+ z-index: 3;+ display: grid;+ place-items: center;+ border-radius: var(--r-plateau);+ border: 2px dashed var(--accent-ring);+ background: color-mix(in srgb, var(--accent-tint) 80%, transparent);+ color: var(--accent-strong);+ font-size: var(--t-13);+ font-weight: 600;+ pointer-events: none;+}.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; }