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
The Shared Library, beside the personal one
Yashwanth Kamireddi0b8bf4cf0140
diff --git a/.uiverify/photos-library-switcher.mjs b/.uiverify/photos-library-switcher.mjsnew file mode 100644index 0000000..1ab731e--- /dev/null+++ b/.uiverify/photos-library-switcher.mjs@@ -0,0 +1,51 @@+// The Shared Library switcher, as Photos has it: under the Photos heading, only for an account+// with a Shared Library; Both Libraries, Personal Library or Shared Library, each showing only+// its own photos in the grid, kept as chosen.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";+const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };++async function open(withShared) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });+ await ctx.addInitScript((shared) => {+ window.__hasShared = shared;+ // p2 and p4 are the Shared Library's.+ window.__photoExtra = shared ? { p2: { zone: "SharedSync-1" }, p4: { zone: "SharedSync-1" } } : {};+ }, withShared);+ const page = await ctx.newPage();+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });+ await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });+ await openScreen(page, "Photos");+ await page.waitForFunction(() => document.querySelectorAll(".px-tile").length > 0);+ return { ctx, page };+}+const tiles = (page) => page.evaluate(() => [...document.querySelectorAll(".px-tile[data-id]")].map((t) => t.dataset.id).sort().join(","));++{+ const { ctx, page } = await open(false);+ ok((await page.locator(".px-library").count()) === 0, "no Shared Library: no switcher");+ await ctx.close();+}+{+ const { ctx, page } = await open(true);+ const sw = page.locator(".px-library .picker-button");+ ok((await sw.count()) === 1 && /Both Libraries/.test(await sw.innerText()), "with one: the switcher, on Both Libraries");+ const both = await tiles(page);+ ok(both.includes("p2") && both.includes("p1"), `Both shows every photo ${both}`);+ for (const [label, want, gone] of [["Personal Library", "p1", "p2"], ["Shared Library", "p2", "p1"]]) {+ await sw.click();+ await page.getByRole("menuitemradio", { name: label }).or(page.getByRole("option", { name: label })).or(page.getByRole("menuitem", { name: label })).first().click();+ await page.waitForFunction((g) => !document.querySelector(`.px-tile[data-id="${g}"]`), gone, { timeout: 3000 }).catch(() => {});+ const now = await tiles(page);+ ok(now.includes(want) && !now.includes(gone), `${label} shows only its own ${now}`);+ ok(new RegExp(label).test(await sw.innerText()) && (await page.evaluate(() => window.__library)) === (label.startsWith("Personal") ? "personal" : "shared"), `${label} is kept as chosen`);+ }+ await page.screenshot({ path: "/tmp/library-switcher.png" });+ await ctx.close();+}+await b.close();+console.log(failures ? `${failures} FAILED` : "all passed");+process.exit(failures ? 1 : 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 6038a03..8ead838 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -657,7 +657,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteP("p1", 1792500000, { favorite: true }), P("p2", 1792400000, { keywords: ["beach"], latitude: 17.7653751, longitude: 83.357605 }), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),P("p4", 1789900000, { addedAt: 1792700000 }), P("p5", 1789800000, { rating: 5 }), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000, expungeAt: Math.floor(Date.now() / 1000) + 2 * 86400 + 600 }),]);- const live = all.filter((p) => !p.deleted && !p.hidden);+ // The library switcher, as the library keeps it: a photo with a `zone` is the Shared+ // Library's.+ const inLibrary = (p) => (window.__library === "personal" ? !p.zone : window.__library === "shared" ? !!p.zone : true);+ const live = all.filter((p) => !p.deleted && !p.hidden && inLibrary(p));const views = {library: live, recents: live, favorites: live.filter((p) => p.favorite), videos: live.filter((p) => p.kind === "video"),screenshots: live.filter((p) => p.subtype === 3), panoramas: live.filter((p) => p.subtype === 1), portrait: live.filter((p) => p.rendered === 8), recentlyDeleted: all.filter((p) => p.deleted),@@ -754,6 +757,9 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note// Shared albums as the library keeps them (`__shared`), and each one's photos by zone// (`__sharedPhotos`), made like the library's.case "photos_shared_albums": return [...(window.__shared ??= [])];+ // The library switcher: a Shared Library when `__hasShared`; the choice kept in `__library`.+ case "photos_library": return { showing: window.__library ?? "both", hasShared: !!window.__hasShared };+ case "photos_set_library": window.__library = args.which; return null;case "photos_burst": {// Three shots; the library's own photo is the chosen one, in the middle.const pick = (window.__photos ?? []).find((p) => p.burst === args.burst);diff --git a/check.sh b/check.shindex bf12cf0..f0e01d2 100755--- a/check.sh+++ b/check.sh@@ -80,6 +80,7 @@ step "download options" node .uiverify/photos-download.mjsstep "adjust date" node .uiverify/photos-date.mjsstep "photo search" node .uiverify/photos-search.mjsstep "full quality" node .uiverify/photos-quality.mjs+step "library switcher" node .uiverify/photos-library-switcher.mjsstep "notes delete" node .uiverify/notes-delete.mjsstep "empty today" node .uiverify/reminders-empty.mjsstep "calendar keys" node .uiverify/calendar-keys.mjsdiff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rsindex b30a0a1..50e0f20 100644--- a/crates/quince-core/src/photos.rs+++ b/crates/quince-core/src/photos.rs@@ -290,6 +290,31 @@ pub(crate) struct MonthsKept {months: Vec<PhotoMonth>,}+/// Which photo library the views show, as Photos' library switcher chooses: both (the+/// default), the personal library alone, or the Shared Library alone. Kept in the library's+/// state, so it stays as chosen.+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum PhotoLibrary {+ #[default]+ Both,+ Personal,+ Shared,+}++impl PhotoLibrary {+ const KEY: &'static str = "photos.library";++ /// The condition on `photos` that keeps a view to this library.+ fn clause(self) -> &'static str {+ match self {+ Self::Both => "1",+ Self::Personal => "zone IS NULL",+ Self::Shared => "zone IS NOT NULL",+ }+ }+}+impl Library {/// Photos written or replaced, by asset id.pub fn put_photos(&mut self, photos: &[Photo]) -> Result<()> {@@ -399,7 +424,7 @@ impl Library {/// A view's photos, newest first.pub fn photos(&self, view: View) -> Result<Vec<Photo>> {- let (filter, order) = Self::view_query(view);+ let (filter, order) = self.view_query_in(view)?;let bursts = if view == View::RecentlyDeleted {"1"} else {@@ -464,6 +489,34 @@ impl Library {self.with_bursts(rows.collect::<std::result::Result<_, _>>()?)}+ /// The library the views show, as last chosen.+ pub fn photo_library(&self) -> Result<PhotoLibrary> {+ Ok(match self.state(PhotoLibrary::KEY)?.as_deref() {+ Some("personal") => PhotoLibrary::Personal,+ Some("shared") => PhotoLibrary::Shared,+ _ => PhotoLibrary::Both,+ })+ }++ /// The library the views show from now on.+ pub fn set_photo_library(&mut self, which: PhotoLibrary) -> Result<()> {+ let value = match which {+ PhotoLibrary::Both => "both",+ PhotoLibrary::Personal => "personal",+ PhotoLibrary::Shared => "shared",+ };+ self.set_state(PhotoLibrary::KEY, value)+ }++ /// Which photos a view holds of the library chosen (`photo_library`), and in what order.+ fn view_query_in(&self, view: View) -> Result<(String, &'static str)> {+ let (filter, order) = Self::view_query(view);+ Ok((+ format!("{filter} AND {}", self.photo_library()?.clause()),+ order,+ ))+ }+/// Which photos a view holds, and in what order.fn view_query(view: View) -> (&'static str, &'static str) {match view {@@ -541,6 +594,10 @@ impl Library {/// How many photos each view holds.pub fn photo_counts(&self) -> Result<Vec<(View, i64)>> {+ // One library of two: the kept counts are of both, so these are counted.+ if self.photo_library()? != PhotoLibrary::Both {+ return self.counted(true);+ }// Kept by the photos' own triggers (migration 50): read, never counted. Less, for the// views that show a burst once, the burst's other photos — counted over the bursts'// own index, which holds bursts only.@@ -569,6 +626,12 @@ impl Library {/// How many photos each view holds, each counted over the library: what the kept counts/// ([`Library::photo_counts`]) must always agree with.pub fn photo_counts_counted(&self) -> Result<Vec<(View, i64)>> {+ self.counted(false)+ }++ /// Each view counted over the library: of both libraries, or (`chosen`) of the one the+ /// views show.+ fn counted(&self, chosen: bool) -> Result<Vec<(View, i64)>> {let mut out = Vec::new();for view in [View::Library,@@ -583,7 +646,11 @@ impl Library {] {// Counted where the rows are: a library of twenty thousand is not read seven times// over to say how many each view holds.- let (filter, _) = Self::view_query(view);+ let filter = if chosen {+ self.view_query_in(view)?.0+ } else {+ Self::view_query(view).0.to_string()+ };let bursts = if view == View::RecentlyDeleted {"1"} else {@@ -954,7 +1021,7 @@ struct Query {}impl Library {- fn source_query(source: &Source, order: Option<Order>) -> Query {+ fn source_query(&self, source: &Source, order: Option<Order>) -> Result<Query> {const TAKEN: &str = "taken_at";const ADDED: &str = "COALESCE(added_at, taken_at)";let plain = |filter: String, order: String, key, params, keyset| Query {@@ -966,9 +1033,9 @@ impl Library {params,keyset,};- match source {+ Ok(match source {Source::View(view) => {- let (filter, own) = Self::view_query(*view);+ let (filter, own) = self.view_query_in(*view)?;let bursts = if *view == View::RecentlyDeleted {"1"} else {@@ -1024,7 +1091,7 @@ impl Library {vec![burst.clone()],Some(false),),- }+ })}/// Every photo a source shows, as a grid lays them out (see [`PhotoIndex`]).@@ -1040,7 +1107,7 @@ impl Library {}return Ok(out);}- let q = Self::source_query(source, order);+ let q = self.source_query(source, order)?;let mut stmt = self.conn.prepare(&format!("SELECT {p}id, {key}, {p}kind, {p}favorite, {p}rating, {p}taken_at FROM {from}WHERE {filter} ORDER BY {order}",@@ -1088,7 +1155,7 @@ impl Library {});return Ok(all.into_iter().skip(from).take(limit.min(5_000)).collect());}- let q = Self::source_query(source, order);+ let q = self.source_query(source, order)?;let columns = COLUMNS.split(", ").map(|c| format!("{}{}", q.pre, c.trim()))@@ -1292,7 +1359,7 @@ impl Library {fn months_worked_out(&self) -> Result<Vec<PhotoMonth>> {use jiff::{civil::Date, Span, Timestamp};- let (filter, _) = Self::view_query(View::Library);+ let (filter, _) = self.view_query_in(View::Library)?;let shown = format!("{filter} AND {ONE_PER_BURST} AND taken_at >= ?1 AND taken_at < ?2");let (first, last): (Option<i64>, Option<i64>) = self.conn.query_row(&format!("SELECT MIN(taken_at), MAX(taken_at) FROM photos WHERE {filter}"),@@ -1412,127 +1479,204 @@ pub struct PhotoMonth {/// whose master is in the next page, or a master whose asset is) are held until it comes.const WALK_TABLES: &str = "CREATE TABLE IF NOT EXISTS photo_walk (+ zone TEXT NOT NULL DEFAULT '',kind TEXT NOT NULL,id TEXT NOT NULL,- PRIMARY KEY (kind, id)+ PRIMARY KEY (zone, kind, id)) STRICT, WITHOUT ROWID;CREATE TABLE IF NOT EXISTS photo_walk_held (- id TEXT PRIMARY KEY,- record TEXT NOT NULL+ zone TEXT NOT NULL DEFAULT '',+ id TEXT NOT NULL,+ record TEXT NOT NULL,+ UNIQUE (zone, id)) STRICT;";+/// Which library a whole read is of, as the walk tables key it: `''` for the personal library,+/// or a Shared Library's zone.+fn walk_key(zone: Option<&str>) -> &str {+ zone.unwrap_or("")+}+impl Library {fn walk_tables(&self) -> Result<()> {self.conn.execute_batch(WALK_TABLES)?;Ok(())}- /// A whole read starting from the beginning: anything an earlier one noted or held is- /// dropped.- pub fn begin_photo_walk(&mut self) -> Result<()> {+ /// A whole read of one library (`zone`: none, the personal one) starting from the+ /// beginning: anything an earlier read of it noted or held is dropped.+ pub fn begin_photo_walk(&mut self, zone: Option<&str>) -> Result<()> {self.walk_tables()?;+ let key = walk_key(zone);+ self.conn+ .execute("DELETE FROM photo_walk WHERE zone = ?1", params![key])?;self.conn- .execute_batch("DELETE FROM photo_walk; DELETE FROM photo_walk_held;")?;+ .execute("DELETE FROM photo_walk_held WHERE zone = ?1", params![key])?;Ok(())}- /// Where the whole read underway carries on from, if one is.- pub fn photo_walk_cursor(&self) -> Result<Option<String>> {+ /// Where the whole read of one library underway carries on from, if one is.+ pub fn photo_walk_cursor(&self, zone: Option<&str>) -> Result<Option<String>> {self.walk_tables()?;Ok(self.conn- .query_row("SELECT id FROM photo_walk WHERE kind = 'cursor'", [], |r| {- r.get(0)- })+ .query_row(+ "SELECT id FROM photo_walk WHERE zone = ?1 AND kind = 'cursor'",+ params![walk_key(zone)],+ |r| r.get(0),+ ).optional()?)}- /// The whole read underway, forgotten without letting anything go.- pub fn forget_photo_walk(&mut self) -> Result<()> {+ /// The whole read of one library underway, forgotten without letting anything go.+ pub fn forget_photo_walk(&mut self, zone: Option<&str>) -> Result<()> {self.walk_tables()?;- self.conn.execute("DELETE FROM photo_walk", [])?;+ self.conn.execute(+ "DELETE FROM photo_walk WHERE zone = ?1",+ params![walk_key(zone)],+ )?;Ok(())}- /// What a pass of the whole read stored, and where the next pass carries on from (none:- /// the read starts over).+ /// What a pass of one library's whole read stored, and where the next pass carries on+ /// from (none: the read starts over).pub fn note_photo_walk(&mut self,+ zone: Option<&str>,photos: &[String],albums: &[String],items: &[(String, String)],cursor: Option<&str>,) -> Result<()> {self.walk_tables()?;+ let key = walk_key(zone);let tx = self.conn.savepoint()?;{- let mut stmt =- tx.prepare("INSERT OR IGNORE INTO photo_walk (kind, id) VALUES (?1, ?2)")?;+ let mut stmt = tx+ .prepare("INSERT OR IGNORE INTO photo_walk (zone, kind, id) VALUES (?1, ?2, ?3)")?;for id in photos {- stmt.execute(params!["photo", id])?;+ stmt.execute(params![key, "photo", id])?;}for id in albums {- stmt.execute(params!["album", id])?;+ stmt.execute(params![key, "album", id])?;}for (album, asset) in items {- stmt.execute(params!["item", format!("{album}\u{1f}{asset}")])?;+ stmt.execute(params![key, "item", format!("{album}\u{1f}{asset}")])?;}}- tx.execute("DELETE FROM photo_walk WHERE kind = 'cursor'", [])?;+ tx.execute(+ "DELETE FROM photo_walk WHERE zone = ?1 AND kind = 'cursor'",+ params![key],+ )?;if let Some(cursor) = cursor {tx.execute(- "INSERT INTO photo_walk (kind, id) VALUES ('cursor', ?1)",- params![cursor],+ "INSERT INTO photo_walk (zone, kind, id) VALUES (?1, 'cursor', ?2)",+ params![key, cursor],)?;}tx.commit()?;Ok(())}- /// The whole read reached the end: every photo, album and album's photo it never saw is- /// gone from iCloud, and goes here.- pub fn finish_photo_walk(&mut self) -> Result<()> {+ /// One library's whole read reached the end: every photo of that library it never saw is+ /// gone from iCloud, and goes here — never another library's. Albums are the personal+ /// library's alone (a Shared Library has none of its own), so only its read lets them go.+ pub fn finish_photo_walk(&mut self, zone: Option<&str>) -> Result<()> {self.walk_tables()?;+ let key = walk_key(zone);let tx = self.conn.savepoint()?;- tx.execute_batch(+ tx.execute("DELETE FROM photos- WHERE id NOT IN (SELECT id FROM photo_walk WHERE kind = 'photo');- DELETE FROM photo_albums- WHERE id NOT IN (SELECT id FROM photo_walk WHERE kind = 'album');- DELETE FROM photo_album_items- WHERE album || char(31) || asset- NOT IN (SELECT id FROM photo_walk WHERE kind = 'item');- DELETE FROM photo_walk;",+ WHERE zone IS ?1+ AND id NOT IN (SELECT id FROM photo_walk WHERE zone = ?2 AND kind = 'photo')",+ params![zone, key],)?;+ if zone.is_none() {+ tx.execute_batch(+ "DELETE FROM photo_albums+ WHERE id NOT IN (SELECT id FROM photo_walk WHERE zone = '' AND kind = 'album');+ DELETE FROM photo_album_items+ WHERE album || char(31) || asset+ NOT IN (SELECT id FROM photo_walk WHERE zone = '' AND kind = 'item');",+ )?;+ }+ tx.execute("DELETE FROM photo_walk WHERE zone = ?1", params![key])?;tx.commit()?;Ok(())}- /// Records held from an unfinished pass, as JSON, for the next pass to read first.- pub fn photo_walk_held(&self) -> Result<Vec<String>> {+ /// Records held from an unfinished pass of one library, as JSON, for its next pass to read+ /// first.+ pub fn photo_walk_held(&self, zone: Option<&str>) -> Result<Vec<String>> {self.walk_tables()?;let mut stmt = self.conn- .prepare("SELECT record FROM photo_walk_held ORDER BY rowid")?;- let rows = stmt.query_map([], |r| r.get(0))?;+ .prepare("SELECT record FROM photo_walk_held WHERE zone = ?1 ORDER BY rowid")?;+ let rows = stmt.query_map(params![walk_key(zone)], |r| r.get(0))?;Ok(rows.collect::<std::result::Result<_, _>>()?)}- /// The records held for the next pass, by record name, in place of those held before.- pub fn hold_for_photo_walk(&mut self, records: &[(String, String)]) -> Result<()> {+ /// The records held for one library's next pass, by record name, in place of those held+ /// before.+ pub fn hold_for_photo_walk(+ &mut self,+ zone: Option<&str>,+ records: &[(String, String)],+ ) -> Result<()> {self.walk_tables()?;+ let key = walk_key(zone);let tx = self.conn.savepoint()?;- tx.execute("DELETE FROM photo_walk_held", [])?;+ tx.execute("DELETE FROM photo_walk_held WHERE zone = ?1", params![key])?;for (id, record) in records {tx.execute(- "INSERT OR REPLACE INTO photo_walk_held (id, record) VALUES (?1, ?2)",- params![id, record],+ "INSERT OR REPLACE INTO photo_walk_held (zone, id, record) VALUES (?1, ?2, ?3)",+ params![key, id, record],)?;}tx.commit()?;Ok(())}++ /// Photos of one library written or replaced (`zone`: none, the personal library). A photo+ /// already kept takes the zone it now arrives from.+ pub fn put_photos_in(&mut self, zone: Option<&str>, photos: &[Photo]) -> Result<()> {+ self.put_photos(photos)?;+ if zone.is_some() {+ let tx = self.conn.savepoint()?;+ {+ let mut stmt =+ tx.prepare("UPDATE photos SET zone = ?1 WHERE id = ?2 AND zone IS NOT ?1")?;+ for p in photos {+ stmt.execute(params![zone, p.id])?;+ }+ }+ tx.commit()?;+ } else {+ let tx = self.conn.savepoint()?;+ {+ let mut stmt =+ tx.prepare("UPDATE photos SET zone = NULL WHERE id = ?1 AND zone IS NOT NULL")?;+ for p in photos {+ stmt.execute(params![p.id])?;+ }+ }+ tx.commit()?;+ }+ Ok(())+ }++ /// The library a photo is in: none for the personal library, else its Shared Library's+ /// zone. What every write to it is addressed to.+ pub fn photo_zone(&self, id: &str) -> Result<Option<String>> {+ Ok(self+ .conn+ .query_row("SELECT zone FROM photos WHERE id = ?1", params![id], |r| {+ r.get::<_, Option<String>>(0)+ })+ .optional()?+ .flatten())+ }}#[cfg(test)]@@ -1573,6 +1717,111 @@ mod tests {}}+ /// Two libraries read side by side: a whole read of the personal library that reaches its+ /// end lets go of the personal photos it never saw, and none of the Shared Library's; the+ /// Shared Library's own read lets go only of its own. Each read keeps its own place.+ #[test]+ fn a_whole_read_of_one_library_never_lets_go_of_the_others() {+ let mut lib = Library::in_memory().unwrap();+ let shared = Some("SharedSync-1");+ lib.put_photos_in(None, &[photo("mine", 1), photo("mine-gone", 2)])+ .unwrap();+ lib.put_photos_in(shared, &[photo("family", 3), photo("family-gone", 4)])+ .unwrap();+ assert_eq!(lib.photo_zone("family").unwrap().as_deref(), shared);+ assert_eq!(lib.photo_zone("mine").unwrap(), None);++ // Both reads underway at once, each where it got to.+ lib.begin_photo_walk(None).unwrap();+ lib.begin_photo_walk(shared).unwrap();+ lib.note_photo_walk(None, &["mine".into()], &[], &[], Some("p-1"))+ .unwrap();+ lib.note_photo_walk(shared, &["family".into()], &[], &[], Some("s-1"))+ .unwrap();+ assert_eq!(lib.photo_walk_cursor(None).unwrap().as_deref(), Some("p-1"));+ assert_eq!(+ lib.photo_walk_cursor(shared).unwrap().as_deref(),+ Some("s-1")+ );+ lib.hold_for_photo_walk(shared, &[("x".into(), "{}".into())])+ .unwrap();+ assert!(lib.photo_walk_held(None).unwrap().is_empty());+ assert_eq!(lib.photo_walk_held(shared).unwrap().len(), 1);++ lib.finish_photo_walk(None).unwrap();+ let ids = lib.photo_ids().unwrap();+ assert!(ids.contains("mine") && !ids.contains("mine-gone"));+ assert!(+ ids.contains("family") && ids.contains("family-gone"),+ "the personal read let go of Shared Library photos"+ );+ assert_eq!(+ lib.photo_walk_cursor(shared).unwrap().as_deref(),+ Some("s-1")+ );++ lib.finish_photo_walk(shared).unwrap();+ let ids = lib.photo_ids().unwrap();+ assert!(ids.contains("family") && !ids.contains("family-gone"));+ assert!(ids.contains("mine"));+ }++ /// The library switcher: Both shows every photo; Personal and Shared each show only their+ /// own in the views, their counts and the months; it stays as chosen.+ #[test]+ fn the_library_switcher_keeps_each_library_to_itself() {+ let mut lib = Library::in_memory().unwrap();+ lib.put_photos_in(None, &[photo("mine", 1_700_000_000)])+ .unwrap();+ lib.put_photos_in(Some("SharedSync-1"), &[photo("ours", 1_600_000_000)])+ .unwrap();+ let shown = |lib: &Library| {+ let mut ids = lib+ .photo_index(&Source::View(View::Library), None)+ .unwrap()+ .ids;+ ids.sort();+ ids+ };+ let library_count = |lib: &Library| {+ lib.photo_counts()+ .unwrap()+ .into_iter()+ .find(|(v, _)| *v == View::Library)+ .unwrap()+ .1+ };+ assert_eq!(lib.photo_library().unwrap(), PhotoLibrary::Both);+ assert_eq!(shown(&lib), vec!["mine", "ours"]);+ assert_eq!(library_count(&lib), 2);+ lib.set_photo_library(PhotoLibrary::Personal).unwrap();+ assert_eq!(shown(&lib), vec!["mine"]);+ assert_eq!(library_count(&lib), 1);+ assert_eq!(lib.photo_months().unwrap().len(), 1);+ lib.set_photo_library(PhotoLibrary::Shared).unwrap();+ assert_eq!(shown(&lib), vec!["ours"]);+ assert_eq!(lib.photos(View::Library).unwrap().len(), 1);+ assert_eq!(lib.photo_library().unwrap(), PhotoLibrary::Shared);+ }++ /// A write's own update of a photo (`put_photos`) keeps the library it is in; a pass that+ /// brings it from another library moves it there.+ #[test]+ fn a_photo_keeps_its_library_until_a_pass_says_otherwise() {+ let mut lib = Library::in_memory().unwrap();+ lib.put_photos_in(Some("SharedSync-1"), &[photo("a", 1)])+ .unwrap();+ let mut favorite = photo("a", 1);+ favorite.favorite = true;+ lib.put_photos(&[favorite]).unwrap();+ assert_eq!(+ lib.photo_zone("a").unwrap().as_deref(),+ Some("SharedSync-1")+ );+ lib.put_photos_in(None, &[photo("a", 1)]).unwrap();+ assert_eq!(lib.photo_zone("a").unwrap(), None);+ }+/// A burst shows as its chosen photo in every view and count, carrying how many it holds;/// all of it is there to look through; with its chosen photo gone it shows whole.#[test]diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 7357159..2033ab3 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -922,6 +922,49 @@ pub const MIGRATIONS: &[&str] = &[CREATE INDEX shared_album_photos_by_taken ON shared_album_photos (zone, taken_at DESC, id);CREATE INDEX shared_album_photos_by_id ON shared_album_photos (id);"#,+ // 52 — the Shared Library (iOS 16+): a second photo library, shared with family, in a+ // `SharedSync-<id>` zone beside the personal one. Its photos are the library's own rows,+ // each marked with the zone it lives in (none: the personal library, so no existing row is+ // rewritten); where each Shared Library is in Apple's databases is kept beside them. A whole+ // read is noted per zone, so finishing one library's read lets go only of that library's+ // photos it never saw, never the other's.+ r#"+ ALTER TABLE photos ADD COLUMN zone TEXT;+ CREATE INDEX photos_by_zone ON photos (zone) WHERE zone IS NOT NULL;+ CREATE TABLE shared_libraries (+ zone TEXT PRIMARY KEY,+ database TEXT NOT NULL,+ owner TEXT,+ title TEXT+ ) STRICT;+ CREATE TABLE IF NOT EXISTS photo_walk (+ kind TEXT NOT NULL,+ id TEXT NOT NULL,+ PRIMARY KEY (kind, id)+ ) STRICT, WITHOUT ROWID;+ CREATE TABLE photo_walk_by_zone (+ zone TEXT NOT NULL DEFAULT '',+ kind TEXT NOT NULL,+ id TEXT NOT NULL,+ PRIMARY KEY (zone, kind, id)+ ) STRICT, WITHOUT ROWID;+ INSERT INTO photo_walk_by_zone (kind, id) SELECT kind, id FROM photo_walk;+ DROP TABLE photo_walk;+ ALTER TABLE photo_walk_by_zone RENAME TO photo_walk;+ CREATE TABLE IF NOT EXISTS photo_walk_held (+ id TEXT PRIMARY KEY,+ record TEXT NOT NULL+ ) STRICT;+ CREATE TABLE photo_walk_held_by_zone (+ zone TEXT NOT NULL DEFAULT '',+ id TEXT NOT NULL,+ record TEXT NOT NULL,+ UNIQUE (zone, id)+ ) STRICT;+ INSERT INTO photo_walk_held_by_zone (id, record) SELECT id, record FROM photo_walk_held ORDER BY rowid;+ DROP TABLE photo_walk_held;+ ALTER TABLE photo_walk_held_by_zone RENAME TO photo_walk_held;+ "#,];/// Migrations that need more than SQL, run in the same transaction as the one numbered.diff --git a/crates/quince-core/src/shared.rs b/crates/quince-core/src/shared.rsindex 206f0a7..ef04b3c 100644--- a/crates/quince-core/src/shared.rs+++ b/crates/quince-core/src/shared.rs@@ -206,8 +206,167 @@ impl Library {}}+/// A Shared Library (iOS 16+): the family photo library this account owns or was invited to,+/// in a `SharedSync-<id>` zone. Its photos are the library's own rows, marked with this zone.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SharedLibrary {+ pub zone: String,+ /// `private` when this account set it up, `shared` when it joined someone else's.+ pub database: String,+ /// The account that owns it, for one this account joined.+ pub owner: Option<String>,+ pub title: Option<String>,+}++impl Library {+ /// A Shared Library as Apple lists it now.+ pub fn put_shared_library(&mut self, library: &SharedLibrary) -> Result<()> {+ self.conn.execute(+ "INSERT INTO shared_libraries (zone, database, owner, title) VALUES (?1, ?2, ?3, ?4)+ ON CONFLICT(zone) DO UPDATE SET database = excluded.database,+ owner = excluded.owner, title = excluded.title",+ params![library.zone, library.database, library.owner, library.title],+ )?;+ Ok(())+ }++ /// Only these Shared Libraries are left: one this account left or that was ended goes,+ /// with its photos and its read's place, so none of them lingers in the grid.+ pub fn keep_shared_libraries(&mut self, kept: &[&str]) -> Result<()> {+ let list = crate::id_list(kept);+ let tx = self.conn.savepoint()?;+ let gone: Vec<String> = {+ let mut stmt = tx.prepare(+ "SELECT zone FROM shared_libraries WHERE zone NOT IN (SELECT value FROM json_each(?1))",+ )?;+ let rows = stmt.query_map(params![list], |r| r.get(0))?;+ rows.collect::<std::result::Result<_, _>>()?+ };+ for zone in &gone {+ tx.execute("DELETE FROM photos WHERE zone = ?1", params![zone])?;+ tx.execute(+ "DELETE FROM sync_state WHERE service = ?1",+ params![format!("photos:{zone}")],+ )?;+ tx.execute(+ "DELETE FROM shared_libraries WHERE zone = ?1",+ params![zone],+ )?;+ }+ tx.commit()?;+ Ok(())+ }++ /// Every Shared Library this account is in.+ pub fn shared_libraries(&self) -> Result<Vec<SharedLibrary>> {+ let mut stmt = self.conn.prepare(+ "SELECT zone, database, owner, title FROM shared_libraries ORDER BY database, zone",+ )?;+ let rows = stmt.query_map([], |r| {+ Ok(SharedLibrary {+ zone: r.get(0)?,+ database: r.get(1)?,+ owner: r.get(2)?,+ title: r.get(3)?,+ })+ })?;+ Ok(rows.collect::<std::result::Result<_, _>>()?)+ }++ /// Where a photo of a Shared Library lives in Apple's databases: none for a photo of the+ /// personal library (or one not kept).+ pub fn shared_library_of(&self, photo: &str) -> Result<Option<SharedLibrary>> {+ Ok(self+ .conn+ .query_row(+ "SELECT l.zone, l.database, l.owner, l.title+ FROM photos p JOIN shared_libraries l ON l.zone = p.zone+ WHERE p.id = ?1",+ params![photo],+ |r| {+ Ok(SharedLibrary {+ zone: r.get(0)?,+ database: r.get(1)?,+ owner: r.get(2)?,+ title: r.get(3)?,+ })+ },+ )+ .optional()?)+ }+}+#[cfg(test)]mod tests {++ /// A Shared Library left or ended goes with its photos and its place in the change feed;+ /// the personal library's photos and the libraries kept stay.+ #[test]+ fn leaving_a_shared_library_lets_go_of_its_photos() {+ use crate::photos::{Kind, Photo};+ let shot = |id: &str| Photo {+ id: id.into(),+ master: format!("m-{id}"),+ taken_at: 1,+ added_at: None,+ kind: Kind::Image,+ width: 1,+ height: 1,+ duration: None,+ filename: None,+ size: None,+ uti: None,+ favorite: false,+ hidden: false,+ deleted: false,+ deleted_at: None,+ expunge_at: None,+ title: None,+ caption: None,+ rating: 0,+ keywords: Vec::new(),+ latitude: None,+ longitude: None,+ rendered: 0,+ subtype: 0,+ burst: None,+ burst_pick: false,+ burst_count: 0,+ live_size: None,+ change_tag: None,+ };+ let mut lib = Library::in_memory().unwrap();+ for zone in ["SharedSync-A", "SharedSync-B"] {+ lib.put_shared_library(&SharedLibrary {+ zone: zone.into(),+ database: "shared".into(),+ owner: Some("_owner".into()),+ title: None,+ })+ .unwrap();+ }+ lib.put_photos_in(None, &[shot("mine")]).unwrap();+ lib.put_photos_in(Some("SharedSync-A"), &[shot("a")])+ .unwrap();+ lib.put_photos_in(Some("SharedSync-B"), &[shot("b")])+ .unwrap();+ lib.mark_synced("photos:SharedSync-A", Some("t")).unwrap();+ assert_eq!(+ lib.shared_library_of("a")+ .unwrap()+ .map(|l| l.zone)+ .as_deref(),+ Some("SharedSync-A")+ );+ assert_eq!(lib.shared_library_of("mine").unwrap(), None);++ lib.keep_shared_libraries(&["SharedSync-B"]).unwrap();+ let ids = lib.photo_ids().unwrap();+ assert!(ids.contains("mine") && ids.contains("b") && !ids.contains("a"));+ assert_eq!(lib.sync_token("photos:SharedSync-A").unwrap(), None);+ assert_eq!(lib.shared_libraries().unwrap().len(), 1);+ }use super::*;use crate::photos::{Kind, View};diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex 44b04ca..1b3371e 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -7,7 +7,7 @@//! 273 records in eight seconds, and a pass from the token with nothing new is under half a//! second. See docs/icloud-web/photos.md.-use crate::cloudkit::{field, ZoneClient};+use crate::cloudkit::{field, Database, ZoneClient};use crate::Result;use base64::Engine;use quince_core::photos::{Album, Kind, Photo};@@ -89,6 +89,47 @@ pub struct PhotosFetch {/// a whole read from the beginning, and what it never sees is gone.pub incremental: bool,pub complete: bool,+ /// The library read: none for the personal one, else a Shared Library's zone.+ pub zone: Option<String>,+}++/// Where a library's progress is kept in the library's sync state: `photos` for the personal+/// library, `photos:<zone>` for a Shared Library.+#[must_use]+pub fn service_of(zone: Option<&str>) -> String {+ zone.map_or_else(|| SERVICE.to_string(), |z| format!("{SERVICE}:{z}"))+}++/// The zones Shared Libraries live in: `SharedSync-<id>`.+pub const SHARED_LIBRARY_PREFIX: &str = "SharedSync-";++/// Every Shared Library this account set up (its own database) or joined (the shared one,+/// with its owner): a `SharedSync-*` zone in either.+///+/// # Errors+/// When Apple cannot be reached or refuses the question.+pub async fn shared_libraries(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+) -> Result<Vec<crate::shared_collections::Place>> {+ let mut out = Vec::new();+ for database in [Database::Private, Database::Shared] {+ let ids = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params.clone())+ .in_database(database)+ .zone_ids()+ .await?;+ out.extend(+ ids.into_iter()+ .filter(|(name, _)| name.starts_with(SHARED_LIBRARY_PREFIX))+ .map(|(zone, owner)| crate::shared_collections::Place {+ database,+ zone,+ owner,+ }),+ );+ }+ Ok(out)}/// How many pages of the change feed one fetch reads (500 records each). A library larger@@ -101,6 +142,33 @@ const PASS_PAGES: usize = 10;/// hundred pages a refresh has always gone through, ten at a time.pub const PASS_ROUNDS: usize = 10;+/// A client for one library: the personal one (`place` none), or a Shared Library where+/// [`shared_libraries`] found it — in the shared database, under its owner, for one joined.+fn client_in<'a>(+ http: &'a reqwest::Client,+ ckdatabasews_root: &'a str,+ params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,+) -> ZoneClient<'a> {+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ match place {+ None => client,+ Some(p) => client.in_database(p.database).owned_by(p.owner.clone()),+ }+}++/// The zone a library's records are in: a Shared Library's own, or the personal library's as+/// [`library_zone`] finds it.+async fn zone_in(+ client: &ZoneClient<'_>,+ place: Option<&crate::shared_collections::Place>,+) -> String {+ match place {+ Some(p) => p.zone.clone(),+ None => library_zone(client).await,+ }+}+/// One pass of the change feed from `since` (or from the start).////// A `since` that Apple will not read any more (an expired or malformed change token) is@@ -112,9 +180,26 @@ pub async fn fetch(params: Vec<(String, String)>,since: Option<&str>,) -> Result<PhotosFetch> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);+ fetch_in(http, ckdatabasews_root, params, None, since).await+}++/// [`fetch`] of one library: `place` none for the personal library, else a Shared Library+/// where [`shared_libraries`] found it.+///+/// # Errors+/// When Apple cannot be reached or refuses the read.+pub async fn fetch_in(+ http: &reqwest::Client,+ ckdatabasews_root: &str,+ params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,+ since: Option<&str>,+) -> Result<PhotosFetch> {+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;+ let shared = place.map(|p| p.zone.clone());if let Some(from) = since.map(str::trim).filter(|t| !t.is_empty()) {- match walk(&client, Some(from)).await {+ match walk(&client, &zone, Some(from)).await {Ok((records, token, complete)) => {return Ok(PhotosFetch {records,@@ -122,6 +207,7 @@ pub async fn fetch(from: Some(from.to_string()),incremental: true,complete,+ zone: shared,})}Err(e) if refused_token(&e) => {@@ -130,13 +216,14 @@ pub async fn fetch(Err(e) => return Err(e),}}- let (records, token, complete) = walk(&client, None).await?;+ let (records, token, complete) = walk(&client, &zone, None).await?;Ok(PhotosFetch {records,token,from: None,incremental: false,complete,+ zone: shared,})}@@ -214,13 +301,13 @@ fn refused_token(e: &crate::Error) -> bool {/// the feed was read to its end.async fn walk(client: &ZoneClient<'_>,+ zone: &str,since: Option<&str>,) -> Result<(Vec<Value>, Option<String>, bool)> {- let zone = library_zone(client).await;let mut records = Vec::new();let mut token = since.map(str::to_string);for page_no in 0..PASS_PAGES {- let page = client.changes(&zone, token.as_deref()).await?;+ let page = client.changes(zone, token.as_deref()).await?;// A token answered with no position at all was not taken: an expired one can come// back as the zone's error code alone, which reads as an empty zone.if page_no == 0 && since.is_some() && page.sync_token.is_none() {@@ -552,21 +639,23 @@ fn apply_whole(from,incremental,complete,+ zone,} = fetched;+ let zone = zone.as_deref();let walking = if incremental {- let carrying_on = from.is_some() && library.photo_walk_cursor()? == from;+ let carrying_on = from.is_some() && library.photo_walk_cursor(zone)? == from;if !carrying_on {- library.forget_photo_walk()?;+ library.forget_photo_walk(zone)?;}carrying_on} else {- library.begin_photo_walk()?;- library.mark_full_sync(SERVICE)?;+ library.begin_photo_walk(zone)?;+ library.mark_full_sync(&service_of(zone))?;true};// What the last pass held back comes first, so this pass's own records win over it.let records: Vec<Value> = library- .photo_walk_held()?+ .photo_walk_held(zone)?.iter().filter_map(|r| serde_json::from_str(r).ok()).chain(fresh)@@ -722,7 +811,7 @@ fn apply_whole(}}let changed = photos.len() + gone.len();- library.put_photos(&photos)?;+ library.put_photos_in(zone, &photos)?;library.forget_photos(&gone)?;library.put_album_items(&in_albums)?;library.forget_album_items(&out_of_albums)?;@@ -748,9 +837,9 @@ fn apply_whole(.map(|(album, asset, _)| (album.clone(), asset.clone())).collect();let carry_on_from = if complete { None } else { token.as_deref() };- library.note_photo_walk(&seen, &album_ids, &items, carry_on_from)?;+ library.note_photo_walk(zone, &seen, &album_ids, &items, carry_on_from)?;if complete {- library.finish_photo_walk()?;+ library.finish_photo_walk(zone)?;library.forget_orphan_albums()?;}}@@ -768,9 +857,9 @@ fn apply_whole(}}}- library.hold_for_photo_walk(&held)?;+ library.hold_for_photo_walk(zone, &held)?;// Unfinished, this is where the next pass carries on from, so each pass gets further.- library.mark_synced(SERVICE, token.as_deref())?;+ library.mark_synced(&service_of(zone), token.as_deref())?;Ok((changed, links))}@@ -778,19 +867,21 @@ fn apply_whole(/// field, against the asset's change tag. Favorite is `isFavorite`; Delete (to Recently/// Deleted, never for good) is `isDeleted: 1`; Recover is `isDeleted: 0`; Hide is `isHidden`./// Answers the asset as Apple now holds it.+#[allow(clippy::too_many_arguments)]pub async fn set_flag(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,asset: &str,change_tag: Option<&str>,flag: Flag,on: bool,) -> Result<Value> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;if flag == Flag::Expunged && on {- return expunge_checked(&client, asset)+ return expunge_checked(&client, &zone, asset).await.map_err(crate::Error::Refused);}@@ -817,9 +908,10 @@ pub async fn set_flag(/// is kept: the plain update resent the delete over that recovery when its change tag moved.async fn expunge_checked(client: &ZoneClient<'_>,+ zone: &str,asset: &str,) -> std::result::Result<Value, String> {- let zone = library_zone(client).await;+ let zone = zone.to_string();let current = client.lookup_record(&zone, asset).await@@ -856,19 +948,20 @@ pub async fn set_flags(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,assets: &[(String, Option<String>)],flag: Flag,on: bool,) -> Result<Vec<std::result::Result<Value, String>>> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;if flag == Flag::Expunged && on {// Eight at a time: a full Recently Deleted empties quickly, each photo still checked.let mut out = Vec::with_capacity(assets.len());for batch in assets.chunks(8) {let mut pending = Vec::with_capacity(batch.len());for (id, _) in batch {- pending.push(expunge_checked(&client, id));+ pending.push(expunge_checked(&client, &zone, id));}out.extend(futures_util::future::join_all(pending).await);}@@ -900,6 +993,7 @@ pub async fn set_title_and_caption(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,asset: &str,title: Option<&str>,caption: Option<&str>,@@ -924,8 +1018,8 @@ pub async fn set_title_and_caption(return Ok(None);}let fields = Value::Object(fields);- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;client.edit_record(&zone, asset, "CPLAsset", |_| Some(fields.clone())).await@@ -937,12 +1031,13 @@ pub async fn set_rating(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,asset: &str,change_tag: Option<&str>,rating: i64,) -> Result<Value> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;client.update_record(&zone,@@ -960,6 +1055,7 @@ pub async fn set_keywords(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,asset: &str,base: &[String],wanted: &[String],@@ -979,8 +1075,8 @@ pub async fn set_keywords(.cloned().collect();let result = std::sync::Mutex::new(Vec::new());- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;let written = client.edit_record(&zone, asset, "CPLAsset", |current| {let mut words: Vec<String> = keywords_of(current)@@ -1020,12 +1116,13 @@ pub async fn set_date(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,asset: &str,change_tag: Option<&str>,millis: i64,) -> Result<Value> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;client.update_record(&zone,@@ -1404,11 +1501,12 @@ pub async fn links(http: &reqwest::Client,ckdatabasews_root: &str,params: Vec<(String, String)>,+ place: Option<&crate::shared_collections::Place>,master: &str,asset: &str,) -> Result<Option<Links>> {- let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);- let zone = library_zone(&client).await;+ let client = client_in(http, ckdatabasews_root, params, place);+ let zone = zone_in(&client, place).await;let Some(m) = client.lookup_record(&zone, master).await? else {return Ok(None);};@@ -1549,6 +1647,59 @@ mod tests {/// photo already known; an expunged asset goes./// A pass that fails as it stores its position — its last write, standing in for a crash/// part way — stores none of the photos it had already put in.+ /// A Shared Library read whole stores its photos marked with its zone and keeps its own+ /// place; the personal library's whole read that follows, seeing none of them, lets go of+ /// none of them; and the Shared Library's photo is the same photo the personal parser makes.+ #[test]+ fn a_shared_library_pass_is_its_own() {+ let mut lib = quince_core::Library::in_memory().unwrap();+ let mut shared_master = master();+ shared_master["recordName"] = json!("M2");+ let mut shared_asset = asset(json!({}));+ shared_asset["recordName"] = json!("A2");+ shared_asset["fields"]["masterRef"] = json!({"value": {"recordName": "M2"}});+ apply(+ &mut lib,+ PhotosFetch {+ records: vec![shared_master, shared_asset],+ token: Some("S1".into()),+ from: None,+ incremental: false,+ complete: true,+ zone: Some("SharedSync-X".into()),+ },+ )+ .unwrap();+ apply(+ &mut lib,+ PhotosFetch {+ records: vec![master(), asset(json!({}))],+ token: Some("P1".into()),+ from: None,+ incremental: false,+ complete: true,+ zone: None,+ },+ )+ .unwrap();+ assert_eq!(+ lib.photo_zone("A2").unwrap().as_deref(),+ Some("SharedSync-X")+ );+ assert_eq!(lib.photo_zone("A1").unwrap(), None);+ assert_eq!(+ lib.sync_token("photos:SharedSync-X").unwrap().as_deref(),+ Some("S1")+ );+ assert_eq!(lib.sync_token(SERVICE).unwrap().as_deref(), Some("P1"));+ let a1 = lib.photo("A1").unwrap().unwrap();+ let a2 = lib.photo("A2").unwrap().unwrap();+ assert_eq!(+ (a1.taken_at, a1.kind, a1.width),+ (a2.taken_at, a2.kind, a2.width)+ );+ }+#[test]fn a_pass_that_fails_part_way_stores_none_of_itself() {let mut lib = quince_core::Library::in_memory().unwrap();@@ -1566,6 +1717,7 @@ mod tests {from: None,incremental: false,complete: true,+ zone: None,};assert!(apply(&mut lib, pass).is_err());assert!(lib@@ -1589,6 +1741,7 @@ mod tests {from: None,incremental: false,complete: true,+ zone: None,};apply(&mut lib, full).unwrap();assert_eq!(@@ -1603,6 +1756,7 @@ mod tests {from: None,incremental: true,complete: true,+ zone: None,};apply(&mut lib, change).unwrap();assert!(lib@@ -1624,6 +1778,7 @@ mod tests {from: None,incremental: true,complete: true,+ zone: None,};apply(&mut lib, expunged).unwrap();assert!(lib.photo("A1").unwrap().is_none());@@ -1647,6 +1802,7 @@ mod tests {from: None,incremental,complete: true,+ zone: None,};apply(&mut lib,@@ -1692,6 +1848,7 @@ mod tests {from: None,incremental,complete: true,+ zone: None,};apply(&mut lib,@@ -1725,6 +1882,7 @@ mod tests {from: None,incremental,complete: true,+ zone: None,};apply(&mut lib,@@ -1845,6 +2003,7 @@ mod tests {from: None,incremental,complete: true,+ zone: None,};apply(&mut lib,@@ -1958,6 +2117,7 @@ mod tests {&http,&server.uri(),vec![],+ None,&[("KEPT".into(), Some("k1".into())),("GONE".into(), Some("g1".into())),@@ -2021,6 +2181,7 @@ mod tests {from: None,incremental: false,complete: true,+ zone: None,};apply(&mut lib,@@ -2040,6 +2201,7 @@ mod tests {from: None,incremental: false,complete: false,+ zone: None,};apply(&mut lib, first).unwrap();assert_eq!(@@ -2059,6 +2221,7 @@ mod tests {from: Some("C1".into()),incremental: true,complete: true,+ zone: None,};apply(&mut lib, second).unwrap();assert_eq!(@@ -2079,6 +2242,7 @@ mod tests {from: Some("T1".into()),incremental: true,complete: true,+ zone: None,};apply(&mut lib, after).unwrap();assert_eq!(ids(&lib), ["A1", "A2", "A3"]);@@ -2095,6 +2259,7 @@ mod tests {from: None,incremental: false,complete: true,+ zone: None,};apply(&mut lib, whole).unwrap();let part = PhotosFetch {@@ -2103,6 +2268,7 @@ mod tests {from: Some("T0".into()),incremental: true,complete: false,+ zone: None,};apply(&mut lib, part).unwrap();assert_eq!(lib.sync_token(SERVICE).unwrap().as_deref(), Some("C1"));@@ -2112,6 +2278,7 @@ mod tests {from: Some("C1".into()),incremental: true,complete: true,+ zone: None,};apply(&mut lib, rest).unwrap();assert_eq!(ids(&lib), ["A1", "A2"], "nothing pruned");@@ -2225,6 +2392,7 @@ mod tests {from: None,incremental: false,complete: true,+ zone: None,};apply(&mut lib, had).unwrap();let (changed, _) = apply(&mut lib, fetched).unwrap();diff --git a/probe/examples/heic_check.rs b/probe/examples/heic_check.rsindex 39a541b..d498afd 100644--- a/probe/examples/heic_check.rs+++ b/probe/examples/heic_check.rs@@ -14,7 +14,7 @@ async fn main() -> Result<()> {.service_url("ckdatabasews").ok_or_else(|| anyhow!("no ck"))?;let (http, p) = (client.http().clone(), client.service_params());- let links = quince_icloud::photos::links(&http, &root, p, master, master)+ let links = quince_icloud::photos::links(&http, &root, p, None, master, master).await?.ok_or_else(|| anyhow!("no links"))?;let url = links.original.ok_or_else(|| anyhow!("no original"))?;diff --git a/probe/examples/photos_date_roundtrip.rs b/probe/examples/photos_date_roundtrip.rsindex 05164c7..c5122d6 100644--- a/probe/examples/photos_date_roundtrip.rs+++ b/probe/examples/photos_date_roundtrip.rs@@ -29,7 +29,7 @@ async fn main() -> Result<()> {let was = date(&before).ok_or_else(|| anyhow!("no date"))?;println!("before: {was}");let tag = before.get("recordChangeTag").and_then(|t| t.as_str());- photos::set_date(&http, &ck, p.clone(), &asset, tag, was + 86_400_000).await?;+ photos::set_date(&http, &ck, p.clone(), None, &asset, tag, was + 86_400_000).await?;let now = zc.lookup_record(&zone, &asset).await?.unwrap();println!("moved: {:?} (a day later: {})",@@ -37,7 +37,7 @@ async fn main() -> Result<()> {date(&now) == Some(was + 86_400_000));let tag = now.get("recordChangeTag").and_then(|t| t.as_str());- photos::set_date(&http, &ck, p.clone(), &asset, tag, was).await?;+ photos::set_date(&http, &ck, p.clone(), None, &asset, tag, was).await?;let back = zc.lookup_record(&zone, &asset).await?.unwrap();println!("back: {:?} (as it was: {})",diff --git a/probe/examples/photos_expunge.rs b/probe/examples/photos_expunge.rsindex 9c1f3bc..8f931c4 100644--- a/probe/examples/photos_expunge.rs+++ b/probe/examples/photos_expunge.rs@@ -47,7 +47,17 @@ async fn main() -> Result<()> {continue;}let tag = a.get("recordChangeTag").and_then(|t| t.as_str());- photos::set_flag(&http, &ck, p.clone(), &asset, tag, Flag::Expunged, true).await?;+ photos::set_flag(+ &http,+ &ck,+ p.clone(),+ None,+ &asset,+ tag,+ Flag::Expunged,+ true,+ )+ .await?;let after = zc.lookup_record(&zone, &asset).await?;println!("{asset} ({name}): after = {}",diff --git a/probe/examples/photos_flags_batch_live.rs b/probe/examples/photos_flags_batch_live.rsindex 3c83964..42390a9 100644--- a/probe/examples/photos_flags_batch_live.rs+++ b/probe/examples/photos_flags_batch_live.rs@@ -115,7 +115,8 @@ async fn main() -> Result<()> {let assets = tags(stale.clone()).await?;let t = std::time::Instant::now();let out =- quince_icloud::photos::set_flags(&http, &root, p.clone(), &assets, flag, on).await?;+ quince_icloud::photos::set_flags(&http, &root, p.clone(), None, &assets, flag, on)+ .await?;let refused: Vec<_> = out.iter().filter_map(|r| r.as_ref().err()).collect();println!("{flag:?}={on}{}: one batch in {:?}, refused {refused:?}",diff --git a/probe/examples/photos_flags_live.rs b/probe/examples/photos_flags_live.rsindex 8e83e16..be1c92a 100644--- a/probe/examples/photos_flags_live.rs+++ b/probe/examples/photos_flags_live.rs@@ -59,6 +59,7 @@ async fn main() -> Result<()> {&http,&root,p.clone(),+ None,&photo.id,tag.as_deref(),flag,diff --git a/probe/examples/photos_folder_add_live.rs b/probe/examples/photos_folder_add_live.rsindex ba89307..24dbeb9 100644--- a/probe/examples/photos_folder_add_live.rs+++ b/probe/examples/photos_folder_add_live.rs@@ -145,6 +145,7 @@ impl Remote for Photos {&c.http,&c.ck,c.params.clone(),+ None,&asset,rec["recordChangeTag"].as_str(),Flag::Deleted,diff --git a/probe/examples/photos_heavy_roundtrip.rs b/probe/examples/photos_heavy_roundtrip.rsindex e56f093..8898f99 100644--- a/probe/examples/photos_heavy_roundtrip.rs+++ b/probe/examples/photos_heavy_roundtrip.rs@@ -110,7 +110,17 @@ async fn main() -> Result<()> {);// Gone for good: to Recently Deleted, then expunged.let tag = asset.get("recordChangeTag").and_then(|x| x.as_str());- let deleted = set_flag(&http, &ck, p.clone(), &u.asset, tag, Flag::Deleted, true).await?;+ let deleted = set_flag(+ &http,+ &ck,+ p.clone(),+ None,+ &u.asset,+ tag,+ Flag::Deleted,+ true,+ )+ .await?;let tag = deleted.get("recordChangeTag").and_then(|x| x.as_str())@@ -125,6 +135,7 @@ async fn main() -> Result<()> {&http,&ck,p,+ None,&u.asset,tag.as_deref(),Flag::Expunged,diff --git a/probe/examples/photos_hide_roundtrip.rs b/probe/examples/photos_hide_roundtrip.rsindex d0863c8..c4c203d 100644--- a/probe/examples/photos_hide_roundtrip.rs+++ b/probe/examples/photos_hide_roundtrip.rs@@ -32,6 +32,7 @@ async fn main() -> Result<()> {&http,&ck,p.clone(),+ None,&asset,tag.as_deref(),Flag::Hidden,@@ -53,6 +54,7 @@ async fn main() -> Result<()> {&http,&ck,p.clone(),+ None,&asset,tag.as_deref(),Flag::Hidden,diff --git a/probe/examples/photos_keywords_roundtrip.rs b/probe/examples/photos_keywords_roundtrip.rsindex db7e533..7e0730f 100644--- a/probe/examples/photos_keywords_roundtrip.rs+++ b/probe/examples/photos_keywords_roundtrip.rs@@ -40,10 +40,10 @@ async fn main() -> Result<()> {.ok_or_else(|| anyhow!("gone"))?;println!("before: {:?}", words(&before));let wanted: Vec<String> = vec!["spring".into(), "quince test ✿".into()];- photos::set_keywords(&http, &ck, p.clone(), &asset, &[], &wanted).await?;+ photos::set_keywords(&http, &ck, p.clone(), None, &asset, &[], &wanted).await?;let now = zc.lookup_record(&zone, &asset).await?.unwrap();println!("set: {:?}", words(&now));- photos::set_keywords(&http, &ck, p.clone(), &asset, &wanted, &[]).await?;+ photos::set_keywords(&http, &ck, p.clone(), None, &asset, &wanted, &[]).await?;let back = zc.lookup_record(&zone, &asset).await?.unwrap();println!("clear: {:?}", words(&back));Ok(())diff --git a/probe/examples/photos_push_live.rs b/probe/examples/photos_push_live.rsindex dee04aa..f5ae9f2 100644--- a/probe/examples/photos_push_live.rs+++ b/probe/examples/photos_push_live.rs@@ -57,6 +57,7 @@ async fn main() -> Result<()> {&http,&ck,p.clone(),+ None,&photo.id,tag.as_deref(),Flag::Favorite,diff --git a/probe/examples/photos_rating_roundtrip.rs b/probe/examples/photos_rating_roundtrip.rsindex 9de4b1c..842e77e 100644--- a/probe/examples/photos_rating_roundtrip.rs+++ b/probe/examples/photos_rating_roundtrip.rs@@ -25,11 +25,11 @@ async fn main() -> Result<()> {.ok_or_else(|| anyhow!("gone"))?;println!("before: {:?}", rating(&before));let tag = before.get("recordChangeTag").and_then(|t| t.as_str());- photos::set_rating(&http, &ck, p.clone(), &asset, tag, 3).await?;+ photos::set_rating(&http, &ck, p.clone(), None, &asset, tag, 3).await?;let now = zc.lookup_record(&zone, &asset).await?.unwrap();println!("set: {:?}", rating(&now));let tag = now.get("recordChangeTag").and_then(|t| t.as_str());- photos::set_rating(&http, &ck, p.clone(), &asset, tag, 0).await?;+ photos::set_rating(&http, &ck, p.clone(), None, &asset, tag, 0).await?;let back = zc.lookup_record(&zone, &asset).await?.unwrap();println!("clear: {:?}", rating(&back));Ok(())diff --git a/probe/examples/photos_text_roundtrip.rs b/probe/examples/photos_text_roundtrip.rsindex 6725281..cfabb2b 100644--- a/probe/examples/photos_text_roundtrip.rs+++ b/probe/examples/photos_text_roundtrip.rs@@ -48,6 +48,7 @@ async fn main() -> Result<()> {&http,&ck,p.clone(),+ None,&asset,Some("Spring bloom"),Some("Quince test — a caption ✿"),@@ -55,7 +56,7 @@ async fn main() -> Result<()> {.await?;let now = zc.lookup_record(&zone, &asset).await?.unwrap();println!("set: {}", show(&now));- photos::set_title_and_caption(&http, &ck, p.clone(), &asset, Some(""), Some("")).await?;+ photos::set_title_and_caption(&http, &ck, p.clone(), None, &asset, Some(""), Some("")).await?;let back = zc.lookup_record(&zone, &asset).await?.unwrap();println!("clear: {}", show(&back));Ok(())diff --git a/probe/examples/photos_upload_live.rs b/probe/examples/photos_upload_live.rsindex c7250e9..1d646f3 100644--- a/probe/examples/photos_upload_live.rs+++ b/probe/examples/photos_upload_live.rs@@ -73,6 +73,7 @@ async fn main() -> Result<()> {&http,&ck,p,+ None,&name,a["recordChangeTag"].as_str(),Flag::Deleted,diff --git a/probe/examples/photos_upload_quince.rs b/probe/examples/photos_upload_quince.rsindex 3c76c86..e9a6b5f 100644--- a/probe/examples/photos_upload_quince.rs+++ b/probe/examples/photos_upload_quince.rs@@ -74,6 +74,7 @@ async fn main() -> Result<()> {&http,&ck,p,+ None,&u.asset,rec["recordChangeTag"].as_str(),Flag::Deleted,diff --git a/probe/examples/photos_upload_v2.rs b/probe/examples/photos_upload_v2.rsindex 88deaa6..7f936f8 100644--- a/probe/examples/photos_upload_v2.rs+++ b/probe/examples/photos_upload_v2.rs@@ -110,6 +110,7 @@ async fn main() -> Result<()> {&http,&ck,p,+ None,&asset,a["recordChangeTag"].as_str(),Flag::Deleted,diff --git a/probe/examples/shared_library_read.rs b/probe/examples/shared_library_read.rsnew file mode 100644index 0000000..856fef0--- /dev/null+++ b/probe/examples/shared_library_read.rs@@ -0,0 +1,68 @@+//! Read-only: every Shared Library this account owns or joined, read whole through the app's+//! own engine (fetch_in + apply) into a library in memory — nothing written to iCloud or to the+//! app's library. Prints how many photos each holds and the kinds of the first few.+use anyhow::{anyhow, Result};++#[tokio::main]+async fn main() -> Result<()> {+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;+ let p = client.service_params();+ let http = client.http().clone();+ let places = quince_icloud::photos::shared_libraries(&http, &root, p.clone()).await?;+ println!(+ "{} Shared Librar{}",+ places.len(),+ if places.len() == 1 { "y" } else { "ies" }+ );+ let mut lib = quince_core::Library::in_memory()?;+ for place in &places {+ let mut since = None;+ let mut rounds = 0;+ loop {+ rounds += 1;+ let f = quince_icloud::photos::fetch_in(+ &http,+ &root,+ p.clone(),+ Some(place),+ since.as_deref(),+ )+ .await?;+ let done = f.complete;+ since = f.token.clone();+ quince_icloud::photos::apply(&mut lib, f)?;+ if done || rounds > 50 {+ break;+ }+ }+ let ids = lib.photo_ids()?;+ let in_zone = ids+ .iter()+ .filter(|id| lib.photo_zone(id).ok().flatten().as_deref() == Some(place.zone.as_str()))+ .count();+ println!(+ "{} ({}): {in_zone} photo(s) in {rounds} round(s), token kept: {}",+ &place.zone[..place.zone.len().min(20)],+ if place.owned() { "owned" } else { "joined" },+ lib.sync_token(&quince_icloud::photos::service_of(Some(&place.zone)))?+ .is_some()+ );+ for id in ids.iter().take(3) {+ if let Some(ph) = lib.photo(id)? {+ println!(+ " {:?} {}x{} taken {}",+ ph.kind, ph.width, ph.height, ph.taken_at+ );+ }+ }+ }+ Ok(())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex e676573..8265130 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -7307,6 +7307,8 @@ fn main() {photos::photos_set_flag,photos::photos_burst,photos::photos_shared_albums,+ photos::photos_library,+ photos::photos_set_library,photos::photos_unlock_hidden,photos::photos_lock_hidden,photos::photos_hello_available,diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex 08aaf38..7c34f86 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -491,13 +491,26 @@ async fn any_photo(id: &str,) -> Result<Option<(Photo, Option<quince_core::shared::SharedPlace>)>, String> {let data = app.state::<Data>();- if let Some(p) = data+ if let Some(found) = data.0- .read(|l| l.photo(id))+ .read(|l| {+ let Some(p) = l.photo(id)? else {+ return Ok(None);+ };+ // A Shared Library's photo is asked of its own zone, as a shared album's is.+ let place = l+ .shared_library_of(id)?+ .map(|s| quince_core::shared::SharedPlace {+ zone: s.zone,+ database: s.database,+ owner: s.owner,+ });+ Ok(Some((p, place)))+ }).await.map_err(|e| e.to_string())?{- return Ok(Some((p, None)));+ return Ok(Some(found));}Ok(data.0@@ -507,6 +520,27 @@ async fn any_photo(.map(|(p, place)| (p, Some(place))))}+/// Where a photo's library is in Apple's databases, for a write to it: none for the personal+/// library, else its Shared Library's zone (in the shared database, under its owner, for one+/// this account joined).+fn library_place(+ library: &quince_core::Library,+ id: &str,+) -> Result<Option<quince_icloud::shared_collections::Place>, String> {+ Ok(library+ .shared_library_of(id)+ .map_err(|e| e.to_string())?+ .map(|s| quince_icloud::shared_collections::Place {+ database: if s.database == "shared" {+ quince_icloud::cloudkit::Database::Shared+ } else {+ quince_icloud::cloudkit::Database::Private+ },+ zone: s.zone,+ owner: s.owner,+ }))+}+/// Whether a photo's original is HEIC (or another HEIF).async fn is_heic(app: &AppHandle, id: &str) -> bool {any_photo(app, id)@@ -1041,7 +1075,9 @@ async fn new_link().await}- None => quince_icloud::photos::links(http, root, params, &photo.master, &photo.id).await,+ None => {+ quince_icloud::photos::links(http, root, params, None, &photo.master, &photo.id).await+ }}.map_err(|e| e.to_string())?.ok_or("Apple no longer has that photo.")?;@@ -1421,6 +1457,41 @@ pub async fn photos_shared_albums(.map_err(|e| e.to_string())}+/// Which library the views show (Both, Personal or Shared), and whether there is a Shared+/// Library to choose: the switcher shows only when there is.+#[derive(serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct LibraryChoice {+ pub showing: quince_core::photos::PhotoLibrary,+ pub has_shared: bool,+}++#[tauri::command]+pub async fn photos_library(data: State<'_, Data>) -> UiResult<LibraryChoice> {+ data.0+ .read(|l| {+ Ok(LibraryChoice {+ showing: l.photo_library()?,+ has_shared: !l.shared_libraries()?.is_empty(),+ })+ })+ .await+ .map_err(|e: quince_core::Error| e.to_string())+}++/// The library the views show from now on, as Photos' library switcher sets it.+#[tauri::command]+pub async fn photos_set_library(+ which: quince_core::photos::PhotoLibrary,+ data: State<'_, Data>,+) -> UiResult<()> {+ data.0+ .lock()+ .await+ .set_photo_library(which)+ .map_err(|e| e.to_string())+}+/// Every photo of one burst, in the order they were shot — what "View all" shows.#[tauri::command]pub async fn photos_burst(burst: String, data: State<'_, Data>) -> UiResult<Vec<Photo>> {@@ -1700,11 +1771,13 @@ pub async fn photo_set_flag(if flag == quince_icloud::photos::Flag::Expunged && (!on || !photo.deleted) {return Err("Only a photo in Recently Deleted can be deleted for good.".into());}+ let place = library_place(&*data.0.lock().await, &id)?;let (http, root, params) = crate::cloudkit_context(&auth).await?;let answer = quince_icloud::photos::set_flag(&http,&root,params,+ place.as_ref(),&id,photo.change_tag.as_deref(),flag,@@ -1811,14 +1884,73 @@ pub async fn photos_set_flag(// Then to Apple, with no sync pass between the two.let _one = crate::PHOTOS_PASS.lock().await;let sent = async {+ // A selection can hold photos of both libraries: each library's are sent to its own+ // zone, and the answers put back in the order the photos were given.+ let places = {+ let library = data.0.lock().await;+ before+ .iter()+ .map(|p| library_place(&library, &p.id))+ .collect::<Result<Vec<_>, String>>()?+ };let (http, root, params) = crate::cloudkit_context(&auth).await?;- let assets: Vec<(String, Option<String>)> = before- .iter()- .map(|p| (p.id.clone(), p.change_tag.clone()))- .collect();- quince_icloud::photos::set_flags(&http, &root, params, &assets, flag, on)+ let mut answers: Vec<Option<Result<serde_json::Value, String>>> =+ (0..before.len()).map(|_| None).collect();+ let mut zones: Vec<Option<&quince_icloud::shared_collections::Place>> = Vec::new();+ for place in &places {+ if !zones+ .iter()+ .any(|z| z.map(|z| &z.zone) == place.as_ref().map(|p| &p.zone))+ {+ zones.push(place.as_ref());+ }+ }+ for zone in zones {+ let wanted: Vec<usize> = (0..before.len())+ .filter(|&i| places[i].as_ref().map(|p| &p.zone) == zone.map(|z| &z.zone))+ .collect();+ let assets: Vec<(String, Option<String>)> = wanted+ .iter()+ .map(|&i| (before[i].id.clone(), before[i].change_tag.clone()))+ .collect();+ // One library's batch failing leaves the other's answers as Apple gave them: only+ // this library's photos are said not to have gone.+ match quince_icloud::photos::set_flags(+ &http,+ &root,+ params.clone(),+ zone,+ &assets,+ flag,+ on,+ ).await- .map_err(|e| e.to_string())+ {+ Ok(got) => {+ for (&i, answer) in wanted.iter().zip(got) {+ answers[i] = Some(answer);+ }+ }+ Err(e)+ if places+ .iter()+ .all(|p| p.as_ref().map(|p| &p.zone) == zone.map(|z| &z.zone)) =>+ {+ return Err(e.to_string());+ }+ Err(e) => {+ for &i in &wanted {+ answers[i] = Some(Err(e.to_string()));+ }+ }+ }+ }+ Ok::<_, String>(+ answers+ .into_iter()+ .map(|a| a.unwrap_or_else(|| Err("Not sent.".into())))+ .collect::<Vec<_>>(),+ )}.await;let answers = match sent {@@ -1928,11 +2060,13 @@ pub async fn photo_set_text(// Only what was changed here goes: the other field may have been changed on another device.let title_changed = photo.title.as_deref().unwrap_or("") != title;let caption_changed = photo.caption.as_deref().unwrap_or("") != caption;+ let place = library_place(&*data.0.lock().await, &id)?;let (http, root, params) = crate::cloudkit_context(&auth).await?;let answer = quince_icloud::photos::set_title_and_caption(&http,&root,params,+ place.as_ref(),&id,title_changed.then_some(title.as_str()),caption_changed.then_some(caption.as_str()),@@ -1980,11 +2114,13 @@ pub async fn photo_set_rating(.photo(&id).map_err(|e| e.to_string())?.ok_or("That photo is no longer in the library.")?;+ let place = library_place(&*data.0.lock().await, &id)?;let (http, root, params) = crate::cloudkit_context(&auth).await?;let answer = quince_icloud::photos::set_rating(&http,&root,params,+ place.as_ref(),&id,photo.change_tag.as_deref(),rating,@@ -2119,11 +2255,19 @@ pub async fn photo_set_keywords(.photo(&id).map_err(|e| e.to_string())?.ok_or("That photo is no longer in the library.")?;+ let place = library_place(&*data.0.lock().await, &id)?;let (http, root, params) = crate::cloudkit_context(&auth).await?;- let (answer, kept) =- quince_icloud::photos::set_keywords(&http, &root, params, &id, &photo.keywords, &words)- .await- .map_err(|e| e.to_string())?;+ let (answer, kept) = quince_icloud::photos::set_keywords(+ &http,+ &root,+ params,+ place.as_ref(),+ &id,+ &photo.keywords,+ &words,+ )+ .await+ .map_err(|e| e.to_string())?;// Apple's list now: this change, and any word another device added meanwhile.photo.keywords = kept;photo.change_tag = answer@@ -2160,11 +2304,13 @@ pub async fn photo_set_date(.photo(&id).map_err(|e| e.to_string())?.ok_or("That photo is no longer in the library.")?;+ let place = library_place(&*data.0.lock().await, &id)?;let (http, root, params) = crate::cloudkit_context(&auth).await?;let answer = quince_icloud::photos::set_date(&http,&root,params,+ place.as_ref(),&id,photo.change_tag.as_deref(),taken_at * 1000,@@ -2440,6 +2586,26 @@ pub async fn photo_download(.photo_to_view(&id).map_err(|e| e.to_string())?.ok_or("That photo is no longer in the library.")?;+ // Asked of the zone the photo lives in: its Shared Library's, its shared album's, or the+ // personal library's.+ let place = {+ let library = data.0.lock().await;+ match library_place(&library, &id)? {+ Some(p) => Some(p),+ None => library+ .shared_photo(&id)+ .map_err(|e| e.to_string())?+ .map(|(_, s)| quince_icloud::shared_collections::Place {+ database: if s.database == "shared" {+ quince_icloud::cloudkit::Database::Shared+ } else {+ quince_icloud::cloudkit::Database::Private+ },+ zone: s.zone,+ owner: s.owner,+ }),+ }+ };let (http, root, params) = crate::cloudkit_context(&auth).await?;let zc = quince_icloud::cloudkit::ZoneClient::new(&http,@@ -2447,7 +2613,16 @@ pub async fn photo_download(quince_icloud::photos::CONTAINER,params,);- let zone = quince_icloud::photos::library_zone(&zc).await;+ let (zc, zone) = match &place {+ Some(p) => (+ zc.in_database(p.database).owned_by(p.owner.clone()),+ p.zone.clone(),+ ),+ None => {+ let zone = quince_icloud::photos::library_zone(&zc).await;+ (zc, zone)+ }+ };let asset = zc.lookup_record(&zone, &id).awaitdiff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rsindex b82e98c..790d0af 100644--- a/src-tauri/src/refresh.rs+++ b/src-tauri/src/refresh.rs@@ -645,6 +645,14 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])report.changed = true;report.items = None;}+ // The Shared Library's photos are the library's own rows: what+ // changed redraws Photos whole, as the albums' do.+ if report.outcome == Outcome::Ok+ && shared_library_pass(&ctx, root, data).await+ {+ report.changed = true;+ report.items = None;+ }break report;}}@@ -951,6 +959,94 @@ async fn shared_albums_pass(ctx: &Context, root: &str, data: &LibraryLock) -> bo.map_or(true, |after| after.len() != before.len())}+/// The Shared Libraries (family photo libraries) after the personal one: each read through its+/// own change feed, from its own place, a few pages per refresh as the personal library is.+/// Its photos join the library's own rows, marked with its zone. A library this account left+/// or that was ended goes with its photos — but only when Apple's list of them was read: a+/// list that failed lets nothing go. Answers whether anything changed.+async fn shared_library_pass(ctx: &Context, root: &str, data: &LibraryLock) -> bool {+ use quince_icloud::photos::{apply, fetch_in, service_of, shared_libraries, PASS_ROUNDS};+ let found = match shared_libraries(&ctx.http, root, ctx.params.clone()).await {+ Ok(found) => found,+ Err(e) => {+ quiet!("shared library: couldn't list them ({e})");+ return false;+ }+ };+ let same_account = |library: &Library| {+ let owner = library.state(crate::ACCOUNT_KEY).ok().flatten();+ ctx.account.is_some() && owner.as_deref() == ctx.account.as_deref()+ };+ let mut changed = false;+ {+ let mut library = data.lock_for_pass().await;+ if !same_account(&library) {+ return false;+ }+ let before = library.shared_libraries().unwrap_or_default().len();+ let zones: Vec<&str> = found.iter().map(|p| p.zone.as_str()).collect();+ let kept = tokio::task::block_in_place(|| {+ library.atomically(|library| {+ for place in &found {+ library.put_shared_library(&quince_core::shared::SharedLibrary {+ zone: place.zone.clone(),+ database: if place.owned() { "private" } else { "shared" }.into(),+ owner: place.owner.clone(),+ title: None,+ })?;+ }+ library.keep_shared_libraries(&zones)+ })+ });+ if let Err(e) = kept {+ quiet!("shared library: couldn't store the list ({e})");+ return false;+ }+ changed |= before != found.len();+ }+ for place in &found {+ let service = service_of(Some(&place.zone));+ for _ in 0..PASS_ROUNDS {+ let since = data.read(|l| l.sync_token(&service)).await.ok().flatten();+ let fetched = match fetch_in(+ &ctx.http,+ root,+ ctx.params.clone(),+ Some(place),+ since.as_deref(),+ )+ .await+ {+ Ok(f) => f,+ Err(e) => {+ quiet!("shared library: couldn't read {} ({e})", place.zone);+ break;+ }+ };+ let more = !fetched.complete;+ let brought = fetched.records.len();+ let mut library = data.lock_for_pass().await;+ if !same_account(&library) {+ return changed;+ }+ match tokio::task::block_in_place(|| apply(&mut library, fetched)) {+ Ok((n, links)) => {+ changed |= n > 0;+ crate::photos::remember(links);+ }+ Err(e) => {+ quiet!("shared library: couldn't store {} ({e})", place.zone);+ break;+ }+ }+ if !more || brought == 0 {+ break;+ }+ }+ }+ changed+}+/// What every pass writes whatever came back: where it got to, and when.const BOOKKEEPING: &[&str] = &["sync_state"];diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex ddba761..bc78d9a 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -292,6 +292,11 @@ export const api = {/** What the window shows pictures at, so the app makes them before they are shown. */photosPrepare: (shown: { cell: number; fit: boolean; stageW: number; stageH: number; dpr: number; view?: PhotoView | null }) =>invoke<void>("photos_prepare", { shown }),+ /** Which photo library the views show (the library switcher), and whether a Shared Library+ * exists to choose. */+ photosLibrary: () => invoke<{ showing: PhotoLibrary; hasShared: boolean }>("photos_library"),+ /** The library the views show from now on. */+ photosSetLibrary: (which: PhotoLibrary) => invoke<void>("photos_set_library", { which }),/** Shared albums, made or joined, newest first — from Apple each time. */photosSharedAlbums: () => invoke<SharedAlbum[]>("photos_shared_albums"),/** The Hidden album unlocked with the Apple ID password; refused with why (wrong, or a wait). */@@ -936,6 +941,9 @@ export type PhotoAlbum = {};/** Where a grid's photos come from (quince-core photos::Source). */+/** Photos' library switcher: both libraries, the personal one, or the Shared Library. */+export type PhotoLibrary = "both" | "personal" | "shared";+export type PhotoSource = { view: PhotoView } | { album: string } | { query: string } | { burst: string } | { shared: string };/** How a sortable view is sorted; null keeps the source's own order. */export type PhotoOrder = { by: "taken" | "added"; oldest: boolean };diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 147b05f..44be649 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -19,6 +19,7 @@ import {type PhotoAlbum,type PhotoMonth,type PhotoOrder,+ type PhotoLibrary,type PhotoSource,type PhotoView,type UploadEvent,@@ -49,6 +50,13 @@ import { PAGE, PhotoList, PhotoStore } from "./photos/list";import { Periods, monthName, type Level, type Place } from "./photos/Periods";import { same } from "../lib/same";+/** The library switcher's choices, named as Photos names them. */+const LIBRARIES = [+ { value: "both", label: "Both Libraries" },+ { value: "personal", label: "Personal Library" },+ { value: "shared", label: "Shared Library" },+];+/** The sidebar, in Photos' order, each with the symbol Photos gives it. */const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [{ key: "library", label: "Library", Icon: Images },@@ -805,6 +813,9 @@ export function PhotosView() {*/const [inBurst, setInBurst] = useState<{ from: string; count: number } | null>(null);const [counts, setCounts] = useState<Partial<Record<PhotoView, number>>>({});+ /** The library switcher: which library the views show, and whether there is a Shared+ * Library to choose (the switcher shows only then). */+ const [library, setLibrary] = useState<{ showing: PhotoLibrary; hasShared: boolean }>({ showing: "both", hasShared: false });const [error, setError] = useState<string | null>(null);useErrorToast(error, () => setError(null));const [zoom, setZoom] = useState(1);@@ -982,7 +993,7 @@ export function PhotosView() {() => {},);}- const [read, c, a] = await Promise.all([index, api.photosCounts(), api.photosAlbums()]);+ const [read, c, a, l] = await Promise.all([index, api.photosCounts(), api.photosAlbums(), api.photosLibrary().catch(() => null)]);indexed = true;if (mine !== reads.current) return;const next = new PhotoList(read, store);@@ -1032,9 +1043,10 @@ export function PhotosView() {const counted = Object.fromEntries(c);setCounts((was) => (same(was, counted) ? was : counted));setAlbums((was) => (same(was, a) ? was : a));+ if (l) setLibrary((was) => (was.showing === l.showing && was.hasShared === l.hasShared ? was : l));// An album deleted elsewhere is not left open, empty.if (album && !album.shared && !a.some(([x]) => x.id === album.id)) setAlbum(null);- }, [view, album, searching, want?.by, want?.oldest, hiddenOpen]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [view, album, searching, want?.by, want?.oldest, hiddenOpen, library.showing]); // eslint-disable-line react-hooks/exhaustive-deps// A pass that lands while another screen is in front is read when this one comes back, once,// not at every landing: a screen out of sight is still mounted (lib/screen), and each pass// lands a service at a time.@@ -3246,6 +3258,23 @@ export function PhotosView() {</div><aside className="px-side" aria-label="Photos"><p className="side-heading px-side-heading">Photos</p>+ {/* Photos' library switcher, only for an account with a Shared Library: the views,+ their counts and the months then show the library chosen. */}+ {library.hasShared && (+ <Picker+ className="px-library"+ label="Library"+ value={library.showing}+ options={LIBRARIES}+ onChange={(v) => {+ const which = v as PhotoLibrary;+ api.photosSetLibrary(which).then(+ () => setLibrary((was) => ({ ...was, showing: which })),+ (e) => setError(String(e)),+ );+ }}+ />+ )}{VIEWS.map(source)}{/* Collections, as icloud.com lists them: Albums and Media Types open to what theyhold, then Rated, Hidden and Recently Deleted. */}diff --git a/src/styles/photos.css b/src/styles/photos.cssindex 84b7963..483fea0 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -30,6 +30,9 @@.px-side-gap { margin-top: var(--source-gap); }.px-side-row { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; }.px-side-row .px-side-heading { margin-bottom: 4px; }+/* The library switcher, under the Photos heading, as wide as a row. */+.px-library { display: flex; margin: 0 0 6px; }+.px-library .picker-button { flex: 1; justify-content: space-between; }/* ---- the library ------------------------------------------------------------------------- */.px-main { position: relative; display: flex; flex-direction: column; min-width: 0; min-height: 0; }