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: captions, typed in Info and kept on every device
Yashwanth Kamireddi34766e1a0f9a
diff --git a/.uiverify/photos-caption.mjs b/.uiverify/photos-caption.mjsnew file mode 100644index 0000000..f7a4ac5--- /dev/null+++ b/.uiverify/photos-caption.mjs@@ -0,0 +1,45 @@+// A caption, as Photos' Info has one: typed in place, saved on Return, kept when the photo is+// opened again; the keys typed into it are words (an "f" does not favorite); Escape puts it+// back and leaves the photo open.+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++; };++await page.locator(".px-tile").nth(1).dblclick();+await page.waitForTimeout(600);+await page.keyboard.press("i");+const field = page.getByLabel("Caption");+ok((await field.getAttribute("placeholder")) === "Add a Caption", "Info offers Add a Caption");+await field.click();+await page.keyboard.type("Ferry at half five, fish and hills");+ok((await page.evaluate(() => (window.__flags ?? []).length)) === 0 && (await page.locator(".px-viewer").count()) === 1,+ "the letters typed are words, not the photo's keys");+await page.keyboard.press("Enter");+await page.waitForTimeout(200);+ok(JSON.stringify(await page.evaluate(() => window.__captions?.at(-1))) === JSON.stringify({ id: "p2", caption: "Ferry at half five, fish and hills" }),+ "Return saves it to iCloud");+await page.keyboard.press("Escape");+await page.waitForTimeout(650);+await page.locator(".px-tile").nth(1).dblclick();+await page.waitForTimeout(600);+// Info stays open from one photo to the next, as in Photos.+ok((await page.locator(".px-info").count()) === 1, "Info is still open on the next photo opened");+ok((await page.getByLabel("Caption").inputValue()) === "Ferry at half five, fish and hills", "and it is there when the photo is opened again");+await page.getByLabel("Caption").click();+await page.keyboard.type(" — not this");+await page.keyboard.press("Escape");+await page.waitForTimeout(200);+ok((await page.getByLabel("Caption").inputValue()) === "Ferry at half five, fish and hills" && (await page.locator(".px-viewer").count()) === 1,+ "Escape puts it back and keeps the photo open");+ok((await page.evaluate(() => window.__captions.length)) === 1, "and sends nothing");+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex bb65199..0b675e9 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -362,6 +362,12 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}return p;}+ case "photo_set_caption": {+ (window.__captions ??= []).push(args);+ const p = (window.__photos ?? []).find((x) => x.id === args.id);+ if (p) p.caption = args.caption || 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`;// Each file is answered at once with where it stands; a test plays the rest in with __emit.diff --git a/check.sh b/check.shindex b039ba7..988e88c 100755--- a/check.sh+++ b/check.sh@@ -61,6 +61,7 @@ step "photos drag" node .uiverify/photos-drag.mjsstep "photos keys" node .uiverify/photos-keys.mjsstep "photos sort" node .uiverify/photos-sort.mjsstep "slideshow" node .uiverify/photos-show.mjs+step "photo captions" node .uiverify/photos-caption.mjsstep "notes delete" node .uiverify/notes-delete.mjsstep "empty today" node .uiverify/reminders-empty.mjsstep "calendar keys" node .uiverify/calendar-keys.mjs@@ -105,6 +106,7 @@ step "webkit: drag" env ENGINE=webkit node .uiverify/photos-drag.mjsstep "webkit: keys" env ENGINE=webkit node .uiverify/photos-keys.mjsstep "webkit: sort" env ENGINE=webkit node .uiverify/photos-sort.mjsstep "webkit: slideshow" env ENGINE=webkit node .uiverify/photos-show.mjs+step "webkit: captions" env ENGINE=webkit node .uiverify/photos-caption.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 4a832c3..75a039f 100644--- a/crates/quince-core/src/photos.rs+++ b/crates/quince-core/src/photos.rs@@ -67,6 +67,9 @@ pub struct Photo {/// In Recently Deleted: when Apple deletes it for good, unix seconds (`dateExpunged`).#[serde(default)]pub expunge_at: Option<i64>,+ /// The caption typed for it in Photos (`captionEnc`).+ #[serde(default)]+ pub caption: Option<String>,/// Photos' subtype: 1 and 3 mark screenshots and the like (`assetSubtypeV2`).pub subtype: i64,/// The asset's change tag, for writing back to it.@@ -114,7 +117,7 @@ pub enum View {}const COLUMNS: &str = "id, master, taken_at, added_at, kind, width, height, duration, filename, \- size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag, expunge_at";+ size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag, expunge_at, caption";fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {Ok(Photo {@@ -136,6 +139,7 @@ fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {subtype: r.get(15)?,change_tag: r.get(16)?,expunge_at: r.get(17)?,+ caption: r.get(18)?,})}@@ -147,8 +151,8 @@ impl Library {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, expunge_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)+ subtype, change_tag, expunge_at, caption)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19)ON CONFLICT(id) DO UPDATE SETmaster = excluded.master, taken_at = excluded.taken_at,added_at = excluded.added_at, kind = excluded.kind, width = excluded.width,@@ -157,7 +161,7 @@ impl Library {favorite = excluded.favorite, hidden = excluded.hidden,deleted = excluded.deleted, deleted_at = excluded.deleted_at,subtype = excluded.subtype, change_tag = excluded.change_tag,- expunge_at = excluded.expunge_at",+ expunge_at = excluded.expunge_at, caption = excluded.caption",)?;for p in photos {stmt.execute(params![@@ -178,7 +182,8 @@ impl Library {p.deleted_at,p.subtype,p.change_tag,- p.expunge_at+ p.expunge_at,+ p.caption])?;}}@@ -488,6 +493,7 @@ mod tests {subtype: 0,change_tag: None,expunge_at: None,+ caption: None,}}diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 06252c2..488e668 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -445,4 +445,10 @@ pub const MIGRATIONS: &[&str] = &[ALTER TABLE photos ADD COLUMN expunge_at INTEGER;UPDATE sync_state SET token = NULL WHERE service = 'photos';"#,+ // A photo's caption, as typed in Photos on any device; Photos is read again so every+ // photo has its own.+ r#"+ ALTER TABLE photos ADD COLUMN caption TEXT;+ UPDATE sync_state SET token = NULL WHERE service = 'photos';+ "#,];diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex a858de9..6591755 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -158,6 +158,7 @@ pub fn photo_of(asset: &Value, master: &Value) -> Option<Photo> {.filter(|&d| d == 1).and(millis(asset, "recordModificationDate")),subtype: field::int(asset, "assetSubtypeV2").unwrap_or(0),+ caption: decoded(asset, "captionEnc"),expunge_at: (field::int(asset, "isDeleted") == Some(1)).then(|| millis(asset, "dateExpunged")).flatten(),@@ -183,6 +184,7 @@ fn with_asset(mut p: Photo, asset: &Value) -> Photo {} else {None};+ p.caption = decoded(asset, "captionEnc");p.expunge_at = if p.deleted {millis(asset, "dateExpunged").or(p.expunge_at)} else {@@ -365,6 +367,28 @@ pub async fn set_flag(.await}+/// A photo's caption set, as icloud.com sets it: `captionEnc`, base64 of its UTF-8 bytes,+/// against the asset's change tag. An empty caption clears it. Answers the asset as it now is.+pub async fn set_caption(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ asset: &str,+ change_tag: Option<&str>,+ caption: &str,+) -> Result<Value> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ client+ .update_record(+ ZONE,+ asset,+ "CPLAsset",+ change_tag,+ serde_json::json!({ "captionEnc": { "value": album_name(caption) } }),+ )+ .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())diff --git a/probe/examples/photos_caption_roundtrip.rs b/probe/examples/photos_caption_roundtrip.rsnew file mode 100644index 0000000..1983745--- /dev/null+++ b/probe/examples/photos_caption_roundtrip.rs@@ -0,0 +1,58 @@+//! Live, on a wallpaper he named as a throwaway: a caption set through Quince's own+//! set_caption, read back from Apple, then cleared. Leaves the photo as it was.+use anyhow::{anyhow, Result};+use base64::Engine;+use quince_icloud::photos::{self, CONTAINER, ZONE};++#[tokio::main]+async fn main() -> Result<()> {+ let asset = std::env::args().nth(1).ok_or_else(|| anyhow!("asset id"))?;+ 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 caption = |r: &serde_json::Value| {+ r.pointer("/fields/captionEnc/value")+ .and_then(|v| v.as_str())+ .map(|v| {+ String::from_utf8_lossy(+ &base64::engine::general_purpose::STANDARD+ .decode(v)+ .unwrap_or_default(),+ )+ .into_owned()+ })+ };+ let before = zc+ .lookup_record(ZONE, &asset)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ println!("before: {:?}", caption(&before));+ let tag = before.get("recordChangeTag").and_then(|t| t.as_str());+ let after = photos::set_caption(+ &http,+ &ck,+ p.clone(),+ &asset,+ tag,+ "Spring bloom — Quince test ✿",+ )+ .await?;+ let now = zc.lookup_record(ZONE, &asset).await?.unwrap();+ println!("set: {:?}", caption(&now));+ let tag = after+ .get("recordChangeTag")+ .and_then(|t| t.as_str())+ .or_else(|| now.get("recordChangeTag").and_then(|t| t.as_str()));+ photos::set_caption(&http, &ck, p.clone(), &asset, tag, "").await?;+ let back = zc.lookup_record(ZONE, &asset).await?.unwrap();+ println!("clear: {:?}", caption(&back));+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 44344c5..5e7d7ad 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -3768,6 +3768,7 @@ fn main() {photos::photos_album_delete,photos::photos_album_add,photos::photos_album_remove,+ photos::photo_set_caption,photos::photo_download,note_table_add_row,note_table_remove,diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex e0a7034..830976a 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -457,6 +457,48 @@ pub async fn photo_set_flag(Ok(updated)}+/// A photo's caption, as typed in its Info: Apple's answer taken at once. Empty clears it.+#[tauri::command]+pub async fn photo_set_caption(+ id: String,+ caption: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<Photo> {+ let _one = crate::PHOTOS_PASS.lock().await;+ let mut photo = data+ .0+ .lock()+ .await+ .photo(&id)+ .map_err(|e| e.to_string())?+ .ok_or("That photo is no longer in the library.")?;+ let caption = caption.trim().to_string();+ let (http, root, params) = crate::cloudkit_context(&auth).await?;+ let answer = quince_icloud::photos::set_caption(+ &http,+ &root,+ params,+ &id,+ photo.change_tag.as_deref(),+ &caption,+ )+ .await+ .map_err(|e| e.to_string())?;+ photo.caption = (!caption.is_empty()).then_some(caption);+ photo.change_tag = answer+ .get("recordChangeTag")+ .and_then(serde_json::Value::as_str)+ .map(str::to_string)+ .or(photo.change_tag);+ data.0+ .lock()+ .await+ .put_photos(std::slice::from_ref(&photo))+ .map_err(|e| e.to_string())?;+ Ok(photo)+}+/// 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.diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex ef7fbb1..e4efad1 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -99,6 +99,7 @@ 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 }),+ photoSetCaption: (id: string, caption: string) => invoke<Photo>("photo_set_caption", { id, caption }),/** 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 }),@@ -580,6 +581,8 @@ export type Photo = {deletedAt: number | null;/** In Recently Deleted: when Apple deletes it for good, unix seconds. */expungeAt?: number | null;+ /** The caption typed for it in Photos. */+ caption?: string | null;subtype: number;changeTag: string | null;};diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex da45291..977d95b 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -502,6 +502,8 @@ export function PhotosView() {if (open === null) return undefined;const current = photos?.[open] ?? null;const onKey = (e: KeyboardEvent) => {+ // Keys typed into a field — the caption — are words, not commands.+ if ((e.target as HTMLElement | null)?.closest?.("input, textarea, [contenteditable]")) return;if (e.key === "ArrowRight") step(1);else if (e.key === "ArrowLeft") step(-1);else if (e.key === "Escape" && lensRef.current.k > 1) unzoom();@@ -997,6 +999,19 @@ export function PhotosView() {/>);+ const caption = async (p: Photo, words: string) => {+ const next = words.trim();+ if (next === (p.caption ?? "")) return;+ const before = photos;+ setPhotos((all) => (all ?? []).map((x) => (x.id === p.id ? { ...x, caption: next || null } : x)));+ try {+ await api.photoSetCaption(p.id, next);+ } catch (e) {+ setPhotos(before);+ setError(messageOf(e));+ }+ };+const play = async (p: Photo) => {try {await api.photoPlay(p.id);@@ -1472,6 +1487,28 @@ export function PhotosView() {</div>{info && (<dl className="px-info">+ {/* As in Photos' Info: the caption first, typed in place, and kept on every+ device; Return or leaving the field saves it, Escape puts it back. */}+ <dd className="px-caption-row">+ <input+ key={shown.id}+ className="px-caption"+ aria-label="Caption"+ placeholder="Add a Caption"+ defaultValue={shown.caption ?? ""}+ maxLength={2000}+ readOnly={view === "recentlyDeleted"}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.currentTarget.blur();+ else if (e.key === "Escape") {+ e.currentTarget.value = shown.caption ?? "";+ e.currentTarget.blur();+ e.stopPropagation();+ }+ }}+ onBlur={(e) => void caption(shown, e.currentTarget.value)}+ />+ </dd><dt>Name</dt><dd>{shown.filename ?? "—"}</dd><dt>Taken</dt>diff --git a/src/styles/photos.css b/src/styles/photos.cssindex f9011a2..630e747 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -439,3 +439,22 @@.px-show-bar .px-cap { color: #fff; }.px-show-bar .px-cap:hover { background: rgba(255, 255, 255, 0.14); }.px-show-count { padding: 0 10px; font-size: var(--t-13); font-variant-numeric: tabular-nums; color: rgba(255, 255, 255, 0.75); }++/* The caption, typed in place at the head of Info, as Photos has it. */+.px-caption-row { margin: 0 0 4px; }+.px-caption {+ padding: 6px 8px;+ margin: 0 -8px;+ width: calc(100% + 16px);+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: var(--t-15, 15px);+ font-weight: 600;+ outline: none;+}+.px-caption::placeholder { color: var(--text-3); font-weight: 500; }+.px-caption:hover:not(:read-only) { background: color-mix(in srgb, var(--text) 6%, transparent); }+.px-caption:focus { background: var(--field, transparent); box-shadow: 0 0 0 2px var(--accent-ring); }