Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Shared Albums open: synced from Apple's shared collections, a card each with its cover and expiry, its photos in the grid to view, copy and save

Yashwanth Kamireddi0c899d241bd5
diff --git a/.uiverify/photos-shared.mjs b/.uiverify/photos-shared.mjs
index a6681e9..d8c8993 100644
--- a/.uiverify/photos-shared.mjs
+++ b/.uiverify/photos-shared.mjs
@@ -1,12 +1,22 @@
-// Sharing, as icloud.com lists it: Shared Albums from Apple's own service — empty, a new one
-// named in a sheet and on the page at once, deleted from its menu after asking; a refusal puts
-// things back and says why.
+// Shared Albums, as iOS 27 keeps them and icloud.com lists them: a card each with its newest
+// photo, its name, "Created by You" or "Shared with You", and when it expires; a card opens the
+// album in the grid. A shared album is looked at, copied and saved — never edited from here:
+// no Favorite, Hide, Delete or Remove in its menus or viewer, and Delete does nothing.
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 });
-await ctx.addInitScript(() => { window.__shared = [{ guid: "J1", name: "Family", createdAt: 1790000000, owned: false, public: false, contributions: true }]; });
+await ctx.addInitScript(() => {
+ const P = (id, takenAt) => ({ id, master: `m${id}`, takenAt, addedAt: takenAt, kind: "image", width: 1200, height: 2600, duration: null,
+ filename: `IMG_${id}.JPG`, size: null, uti: "public.jpeg", favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null });
+ // 19 November 2026, 12:00 UTC: "Expires November 19" wherever the test runs.
+ window.__shared = [
+ { zone: "SharedCollection-W", database: "private", owner: null, title: "Wallpapers", expiresAt: 1795089600, count: 2, cover: "s2" },
+ { zone: "SharedCollection-F", database: "shared", owner: "_other", title: "Family", expiresAt: null, count: 1, cover: "s3" },
+ ];
+ window.__sharedPhotos = { "SharedCollection-W": [P("s2", 1792600000), P("s1", 1792500000)], "SharedCollection-F": [P("s3", 1792000000)] };
+});
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" });
@@ -19,40 +29,45 @@ const cards = () => page.locator(".px-albums-page .px-card").allInnerTexts();
await page.locator(".px-source", { hasText: "Shared Albums" }).click();
await page.waitForTimeout(300);
ok((await page.locator(".px-albums-page h1").innerText()) === "Shared Albums" && (await page.locator(".px-tile:visible").count()) === 0, "Sharing → Shared Albums opens its page in place of the photos");
-ok((await page.locator(".px-source", { hasText: "Library" }).getAttribute("aria-current")) !== "true" && (await page.locator(".px-source", { hasText: "Shared Albums" }).getAttribute("aria-current")) === "true",
- "and the sidebar marks it, not the view before");
-ok(/Family[\s\S]*Shared with you/.test((await cards()).join()), `an album shared with this account says so ${JSON.stringify(await cards())}`);
+ok((await page.locator(".px-albums-head .px-span").innerText()) === "2 Shared Albums", "with how many there are");
+const [w, f] = await cards();
+ok(/Wallpapers[\s\S]*Created by You[\s\S]*Expires November 19/.test(w ?? ""), `one of yours: its name, made by you, when it ends ${JSON.stringify(w)}`);
+ok(/Family[\s\S]*Shared with You/.test(f ?? "") && !/Expires/.test(f ?? ""), `one shared with you says so ${JSON.stringify(f)}`);
+ok((await page.locator(".px-albums-page .px-card img").first().getAttribute("src"))?.includes("s2"), "each card shows its newest photo");
+ok((await page.getByRole("button", { name: "New Shared Album" }).count()) === 0, "no New Shared Album: making one isn't possible from here yet");
-await page.getByRole("button", { name: "New Shared Album" }).first().click();
-await page.waitForTimeout(200);
-await page.getByLabel("Album Name").fill("Beach Trip");
-await page.keyboard.press("Enter");
-await page.waitForTimeout(250);
-ok(/Beach Trip[\s\S]*Shared by you/.test((await cards())[0] ?? "") && (await page.getByRole("dialog", { name: "New Shared Album" }).count()) === 0, "a new one, named in a sheet, is on the page at once — shared by you");
-ok(await page.evaluate(() => window.__shared.some((a) => a.name === "Beach Trip")), "and made at Apple");
+// Opened: its photos in the grid, under its name.
+await page.locator(".px-albums-page .px-card", { hasText: "Wallpapers" }).click();
+await page.waitForTimeout(350);
+ok((await page.locator(".px-bar h1").innerText()) === "Wallpapers" && (await page.locator(".px-tile").count()) === 2, "a card opens the album: its photos, under its name");
+const albumAfterSync = async () => { await page.evaluate(() => window.__emit?.("quince://synced", { services: [{ service: "photos", label: "Photos", outcome: "ok", detail: null, lastSyncedAt: Math.floor(Date.now() / 1000) }], asOf: Math.floor(Date.now() / 1000), tookMs: 10, changed: ["photos"] })); await page.waitForTimeout(300); };
+await albumAfterSync();
+ok((await page.locator(".px-bar h1").innerText()) === "Wallpapers", "and stays open when a sync lands (it is in no album list of yours)");
-// Deleted from its menu, after asking.
-await page.locator(".px-albums-page .px-card", { hasText: "Beach Trip" }).click({ button: "right" });
-await page.locator(".row-menu").getByText("Delete Shared Album").click();
-ok(/everyone it is shared with/.test(await page.locator(".confirm").innerText()), "deleting asks first, saying it goes for everyone");
-await page.locator(".confirm .confirm-answer").click();
+// Looked at, never edited.
+await page.locator(".px-tile").first().click({ button: "right" });
+const menu = await page.locator(".row-menu").innerText();
+ok(/Download/.test(menu) && /Copy/.test(menu) && !/Favorite|Hide|Delete|Remove|Add to Album/.test(menu), `its menu saves and copies, and edits nothing ${JSON.stringify(menu)}`);
+await page.keyboard.press("Escape");
+await page.locator(".px-tile").first().click();
+await page.keyboard.press("Delete");
await page.waitForTimeout(250);
-ok(!(await cards()).join().includes("Beach Trip") && !(await page.evaluate(() => window.__shared.some((a) => a.name === "Beach Trip"))), "and it is gone, here and at Apple");
-// One shared with this account cannot be deleted from here.
-await page.locator(".px-albums-page .px-card", { hasText: "Family" }).click({ button: "right" });
-ok((await page.locator(".row-menu").getByText("Delete Shared Album").count()) === 0, "one shared with you offers no delete — only its owner can");
+ok((await page.locator(".confirm").count()) === 0 && (await page.locator(".px-tile").count()) === 2, "Delete does nothing in a shared album");
+await page.locator(".px-tile").first().dblclick();
+await page.waitForTimeout(400);
+const buttons = await page.locator(".px-viewer button[aria-label]").evaluateAll((els) => els.map((e) => e.getAttribute("aria-label")));
+ok(buttons.includes("Download") && !buttons.some((l) => /Favorite|Delete|Remove/.test(l ?? "")), `the viewer offers Download, not Favorite or Delete ${JSON.stringify(buttons)}`);
await page.keyboard.press("Escape");
+await page.waitForTimeout(250);
-// Apple refuses: the new one goes again, and the reason is said.
-await page.evaluate(() => { window.__sharedFail = true; });
-await page.getByRole("button", { name: "New Shared Album" }).first().click();
-await page.getByLabel("Album Name").fill("Nope");
-await page.keyboard.press("Enter");
+// No albums: said plainly.
+await page.evaluate(() => { window.__shared = []; });
+await page.locator(".px-source", { hasText: "Library" }).click();
+await page.waitForTimeout(250);
+await page.locator(".px-source", { hasText: "Shared Albums" }).click();
await page.waitForTimeout(300);
-ok(!(await cards()).join().includes("Nope") && /refused/.test(await page.locator(".toast.is-error").innerText().catch(() => "")), "a refusal takes it back and says why");
-await page.evaluate(() => { window.__sharedFail = false; });
+ok(/Albums you share from your iPhone/.test(await page.locator(".px-albums-page").innerText()), "with none, the page says where they come from");
-// Back to the library.
await page.locator(".px-source", { hasText: "Library" }).click();
await page.waitForTimeout(300);
ok((await page.locator(".px-albums-page").count()) === 0 && (await page.locator(".px-tile:visible").count()) > 0, "Library brings the photos back");
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 7c636a6..ddeef9c 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -671,6 +671,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
let list = src.view ? await self("photos_list", { view: src.view })
: src.album ? await self("photos_in_album", { album: src.album })
: src.query ? await self("photos_search", { query: src.query })
+ : src.shared ? (window.__sharedPhotos?.[src.shared] ?? []).map((p) => ({ ...p }))
: await self("photos_burst", { burst: src.burst });
const sortable = src.view && src.view !== "rated" && src.view !== "recentlyDeleted";
const order = sortable ? args.order : null;
@@ -717,26 +718,19 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
case "photos_get": {
(window.__gets ??= []).push(args.ids.length);
- const all = window.__photos ?? [];
+ // Shared albums' photos too: the backend finds a shared photo by its id as well.
+ const all = [...(window.__photos ?? []), ...Object.values(window.__sharedPhotos ?? {}).flat()];
const burst = window.__burstShots ?? [];
// Made once per fixture: rebuilt per call, the stub's own work showed as the grid's.
- if (window.__byIdOf?.all !== all || window.__byIdOf?.burst !== burst) window.__byIdOf = { all, burst, map: new Map([...burst, ...all].map((p) => [p.id, p])) };
+ const src = window.__photos, shared = window.__sharedPhotos;
+ if (window.__byIdOf?.src !== src || window.__byIdOf?.shared !== shared || window.__byIdOf?.burst !== burst) window.__byIdOf = { src, shared, burst, map: new Map([...burst, ...all].map((p) => [p.id, p])) };
const byId = window.__byIdOf.map;
return args.ids.map((id) => byId.get(id)).filter(Boolean).map((p) => ({ ...p }));
}
case "photos_prepare": (window.__prepared ??= []).push(args.shown); return null;
+ // 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 ??= [])];
- case "photos_shared_create": {
- if (window.__sharedFail) throw "Shared Albums refused that (503).";
- const guid = `S-${(window.__shared ??= []).length + 1}`;
- window.__shared.unshift({ guid, name: args.name, createdAt: 1792500000, owned: true, public: false, contributions: true });
- return guid;
- }
- case "photos_shared_delete": {
- if (window.__sharedFail) throw "Shared Albums refused that (503).";
- window.__shared = (window.__shared ?? []).filter((a) => a.guid !== args.guid);
- 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/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index 59f50b5..a647efb 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -883,7 +883,8 @@ impl Library {
}
}
-/// Where the photos a grid shows come from: a view, an album, a search, or one burst.
+/// Where the photos a grid shows come from: a view, an album, a search, one burst, or a shared
+/// album (by its zone; kept apart from the library, see `shared`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum Source {
@@ -891,6 +892,7 @@ pub enum Source {
Album(String),
Query(String),
Burst(String),
+ Shared(String),
}
/// How a view the person can sort is sorted: by when taken or when added, newest or oldest
@@ -994,6 +996,8 @@ impl Library {
keyset,
)
}
+ // Read from its own table (`photo_index`, `photo_page`); asked here, nothing.
+ Source::Shared(_) => plain("0".into(), "id".into(), TAKEN, Vec::new(), None),
Source::Album(album) => Query {
from: "photo_album_items i JOIN photos p ON p.id = i.asset",
pre: "p.",
@@ -1025,6 +1029,17 @@ impl Library {
/// Every photo a source shows, as a grid lays them out (see [`PhotoIndex`]).
pub fn photo_index(&self, source: &Source, order: Option<Order>) -> Result<PhotoIndex> {
+ if let Source::Shared(zone) = source {
+ let mut out = PhotoIndex::default();
+ for p in self.shared_album_photos(zone)? {
+ out.first = Some(out.first.map_or(p.taken_at, |f| f.min(p.taken_at)));
+ out.last = Some(out.last.map_or(p.taken_at, |l| l.max(p.taken_at)));
+ out.marks.push(mark(p.kind.as_str(), p.favorite, p.rating));
+ out.keys.push(p.taken_at);
+ out.ids.push(p.id);
+ }
+ return Ok(out);
+ }
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}
@@ -1063,6 +1078,16 @@ impl Library {
after: Option<&After>,
limit: usize,
) -> Result<Vec<Photo>> {
+ // A shared album is small, and walked to the photo named, as an album is.
+ if let Source::Shared(zone) = source {
+ let all = self.shared_album_photos(zone)?;
+ let from = after.map_or(0, |a| {
+ all.iter()
+ .position(|p| p.id == a.id)
+ .map_or(all.len(), |i| i + 1)
+ });
+ return Ok(all.into_iter().skip(from).take(limit.min(5_000)).collect());
+ }
let q = Self::source_query(source, order);
let columns = COLUMNS
.split(", ")
diff --git a/crates/quince-core/src/shared.rs b/crates/quince-core/src/shared.rs
index b5a8879..acea9c8 100644
--- a/crates/quince-core/src/shared.rs
+++ b/crates/quince-core/src/shared.rs
@@ -150,6 +150,14 @@ impl Library {
.collect()
}
+ /// A photo to look at, copy or save: the library's own, or one in a shared album.
+ pub fn photo_to_view(&self, id: &str) -> Result<Option<Photo>> {
+ if let Some(p) = self.photo(id)? {
+ return Ok(Some(p));
+ }
+ Ok(self.shared_photo(id)?.map(|(p, _)| p))
+ }
+
/// A shared photo by its id, and where it lives: for its pictures.
pub fn shared_photo(&self, id: &str) -> Result<Option<(Photo, SharedPlace)>> {
let row: Option<(String, String, String, Option<String>)> = self
diff --git a/crates/quince-icloud/src/shared_collections.rs b/crates/quince-icloud/src/shared_collections.rs
index 9bf38f9..43b62ac 100644
--- a/crates/quince-icloud/src/shared_collections.rs
+++ b/crates/quince-icloud/src/shared_collections.rs
@@ -135,6 +135,27 @@ pub async fn read(
})
}
+/// One shared photo's links, read from its album now: for a picture whose kept link expired.
+pub async fn links(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ place: &Place,
+ master: &str,
+ asset: &str,
+) -> Result<Option<Links>> {
+ let client = client(http, ckdatabasews_root, params, place);
+ let Some(m) = client.lookup_record(&place.zone, master).await? else {
+ return Ok(None);
+ };
+ let a = client
+ .lookup_record(&place.zone, asset)
+ .await
+ .ok()
+ .flatten();
+ Ok(Some(links_with_edit(a.as_ref(), &m)))
+}
+
/// An album's records as its title, expiry, photos and their links. A photo's asset without
/// its master (or a master without an asset) is no photo yet, and is left out; deleted records
/// are simply absent from a whole read.
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index bf8c0c0..8538310 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -7306,8 +7306,6 @@ fn main() {
photos::photos_set_flag,
photos::photos_burst,
photos::photos_shared_albums,
- photos::photos_shared_create,
- photos::photos_shared_delete,
photos::photos_prepare,
photos::photos_index,
photos::photos_months,
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 0cd76b4..b435592 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -374,16 +374,37 @@ pub async fn cached(app: &AppHandle, id: &str, size: Size) -> Result<PathBuf, St
from_apple(app, id, size, path).await
}
-/// Whether a photo's original is HEIC (or another HEIF).
-async fn is_heic(app: &AppHandle, id: &str) -> bool {
+/// A photo whose pictures are asked for: the library's own, or one in a shared album (with
+/// where that album lives, to ask Apple for its links). Read beside a sync pass, never behind
+/// it (see `LibraryLock::read`).
+async fn any_photo(
+ app: &AppHandle,
+ id: &str,
+) -> Result<Option<(Photo, Option<quince_core::shared::SharedPlace>)>, String> {
let data = app.state::<Data>();
- // Read beside a sync pass, never behind it (see `LibraryLock::read`).
- data.0
+ if let Some(p) = data
+ .0
.read(|l| l.photo(id))
+ .await
+ .map_err(|e| e.to_string())?
+ {
+ return Ok(Some((p, None)));
+ }
+ Ok(data
+ .0
+ .read(|l| l.shared_photo(id))
+ .await
+ .map_err(|e| e.to_string())?
+ .map(|(p, place)| (p, Some(place))))
+}
+
+/// Whether a photo's original is HEIC (or another HEIF).
+async fn is_heic(app: &AppHandle, id: &str) -> bool {
+ any_photo(app, id)
.await
.ok()
.flatten()
- .and_then(|p| p.uti)
+ .and_then(|(p, _)| p.uti)
.is_some_and(|u| {
let u = u.to_ascii_lowercase();
u.contains("heic") || u.contains("heif")
@@ -434,16 +455,11 @@ async fn from_apple(
if tokio::fs::metadata(&path).await.is_ok() {
return Ok(path);
}
- let photo = {
- let data = app.state::<Data>();
- // Beside a sync pass on a reader: a picture asked for never waits behind a pass's
- // store, which holds the writer for seconds on a large library.
- data.0
- .read(|l| l.photo(id))
- .await
- .map_err(|e| e.to_string())?
- .ok_or("That photo is no longer in the library.")?
- };
+ // Beside a sync pass on a reader: a picture asked for never waits behind a pass's store,
+ // which holds the writer for seconds on a large library.
+ let (photo, shared) = any_photo(app, id)
+ .await?
+ .ok_or("That photo is no longer in the library.")?;
let auth = app.state::<Auth>();
let (http, root, params) = crate::cloudkit_context(&auth).await?;
// A cached link first; a fresh one from Apple when it has none or Apple refuses the old.
@@ -459,7 +475,8 @@ async fn from_apple(
Some(url) => fetch(url).await.unwrap_or(false),
None => false,
};
- if !done && !fetch(new_link(&http, &root, params, &photo, size).await?).await? {
+ if !done && !fetch(new_link(&http, &root, params, &photo, shared.as_ref(), size).await?).await?
+ {
return Err("Apple did not send that picture.".into());
}
// Held for whoever asked, and the cache checked against its cap soon after (a thumbnail is
@@ -859,12 +876,35 @@ async fn new_link(
root: &str,
params: Vec<(String, String)>,
photo: &Photo,
+ shared: Option<&quince_core::shared::SharedPlace>,
size: Size,
) -> Result<String, String> {
- let links = quince_icloud::photos::links(http, root, params, &photo.master, &photo.id)
- .await
- .map_err(|e| e.to_string())?
- .ok_or("Apple no longer has that photo.")?;
+ let links = match shared {
+ // A shared album's photo is asked of its album, where Apple keeps it.
+ Some(place) => {
+ let place = quince_icloud::shared_collections::Place {
+ database: if place.database == "shared" {
+ quince_icloud::cloudkit::Database::Shared
+ } else {
+ quince_icloud::cloudkit::Database::Private
+ },
+ zone: place.zone.clone(),
+ owner: place.owner.clone(),
+ };
+ quince_icloud::shared_collections::links(
+ http,
+ root,
+ params,
+ &place,
+ &photo.master,
+ &photo.id,
+ )
+ .await
+ }
+ None => quince_icloud::photos::links(http, root, params, &photo.master, &photo.id).await,
+ }
+ .map_err(|e| e.to_string())?
+ .ok_or("Apple no longer has that photo.")?;
remember(HashMap::from([(photo.master.clone(), links.clone())]));
size.pick(&links)
.ok_or_else(|| "That photo has no picture of that size.".into())
@@ -995,14 +1035,9 @@ pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String>
{
return Ok(Film::Growing(g));
}
- let photo = {
- let data = app.state::<Data>();
- data.0
- .read(|l| l.photo(id))
- .await
- .map_err(|e| e.to_string())?
- .ok_or("That photo is no longer in the library.")?
- };
+ let (photo, shared) = any_photo(app, id)
+ .await?
+ .ok_or("That photo is no longer in the library.")?;
let auth = app.state::<Auth>();
let (http, root, params) = crate::cloudkit_context(&auth).await?;
let ask = |url: String| {
@@ -1014,7 +1049,7 @@ pub async fn film(app: &AppHandle, id: &str, size: Size) -> Result<Film, String>
None => None,
};
if response.is_none() {
- let url = new_link(&http, &root, params, &photo, size).await?;
+ let url = new_link(&http, &root, params, &photo, shared.as_ref(), size).await?;
response = Some(ask(url).await?).filter(|r| r.status().is_success());
}
let response = response.ok_or("Apple did not send that film.")?;
@@ -1231,59 +1266,16 @@ pub async fn photos_get(ids: Vec<String>, data: State<'_, Data>) -> UiResult<Vec
.map_err(|e| e.to_string())
}
-/// The Shared Albums service for the signed-in account: its client, address and params.
-async fn shared_streams(
- auth: &State<'_, Auth>,
-) -> Result<(reqwest::Client, String, Vec<(String, String)>), String> {
- let client = auth.client.lock().await;
- let root = client
- .session()
- .service_url("sharedstreams")
- .ok_or("Apple hasn't offered Shared Albums for this account.")?;
- Ok((client.http().clone(), root, client.service_params()))
-}
-
-/// Every shared album the account has, made or joined, newest first — read from Apple each time
-/// (there are few, and a list kept here would go stale as people are invited and leave).
+/// Every shared album the account made or was invited to, with its photo count and cover: as
+/// the last sync found them (each album is read again whenever Apple says it changed).
#[tauri::command]
pub async fn photos_shared_albums(
- auth: State<'_, Auth>,
-) -> UiResult<Vec<quince_icloud::shared_albums::SharedAlbum>> {
- let (http, root, params) = shared_streams(&auth).await?;
- let s = quince_icloud::shared_albums::SharedStreams {
- http: &http,
- root: &root,
- params: &params,
- };
- s.list().await.map_err(|e| e.to_string())
-}
-
-/// A new shared album, named; answers its id.
-#[tauri::command]
-pub async fn photos_shared_create(name: String, auth: State<'_, Auth>) -> UiResult<String> {
- let name = name.trim();
- if name.is_empty() {
- return Err("A shared album needs a name.".into());
- }
- let (http, root, params) = shared_streams(&auth).await?;
- let s = quince_icloud::shared_albums::SharedStreams {
- http: &http,
- root: &root,
- params: &params,
- };
- s.create(name).await.map_err(|e| e.to_string())
-}
-
-/// A shared album deleted, for everyone it was shared with.
-#[tauri::command]
-pub async fn photos_shared_delete(guid: String, auth: State<'_, Auth>) -> UiResult<()> {
- let (http, root, params) = shared_streams(&auth).await?;
- let s = quince_icloud::shared_albums::SharedStreams {
- http: &http,
- root: &root,
- params: &params,
- };
- s.delete(&guid).await.map_err(|e| e.to_string())
+ data: State<'_, Data>,
+) -> UiResult<Vec<quince_core::shared::SharedAlbum>> {
+ data.0
+ .read(quince_core::Library::shared_albums)
+ .await
+ .map_err(|e| e.to_string())
}
/// Every photo of one burst, in the order they were shot — what "View all" shows.
@@ -1904,7 +1896,7 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui
.0
.lock()
.await
- .photo(&id)
+ .photo_to_view(&id)
.map_err(|e| e.to_string())?
.ok_or("That photo is no longer in the library.")?;
let size = if photo.kind == quince_core::photos::Kind::Video {
@@ -2118,7 +2110,7 @@ pub async fn photo_copy(
.0
.lock()
.await
- .photo(&id)
+ .photo_to_view(&id)
.map_err(|e| e.to_string())?
.ok_or("That photo is no longer in the library.")?;
if photo.kind == quince_core::photos::Kind::Video {
@@ -2302,7 +2294,7 @@ pub async fn photo_download(
.0
.lock()
.await
- .photo(&id)
+ .photo_to_view(&id)
.map_err(|e| e.to_string())?
.ok_or("That photo is no longer in the library.")?;
let (http, root, params) = crate::cloudkit_context(&auth).await?;
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
index b3821eb..b82e98c 100644
--- a/src-tauri/src/refresh.rs
+++ b/src-tauri/src/refresh.rs
@@ -636,6 +636,15 @@ async fn run(client: &Arc<Mutex<Client>>, data: &LibraryLock, services: &[&str])
{
report.changed = changed;
report.items = if changed { items } else { None };
+ // Shared Albums after the library, on a pass that went well: what
+ // changed there redraws Photos whole (it has no rows of its own in
+ // the library's change tracking).
+ if report.outcome == Outcome::Ok
+ && shared_albums_pass(&ctx, root, data).await
+ {
+ report.changed = true;
+ report.items = None;
+ }
break report;
}
}
@@ -869,6 +878,79 @@ async fn token(data: &LibraryLock, service: &str) -> Option<String> {
.flatten()
}
+/// Shared Albums (iOS 27's shared collections): every album found, each read whole when its
+/// change feed says it changed, and any no longer there let go of. Answers whether anything
+/// was stored. Quiet on failure — the library's own pass speaks for Photos — and a failure
+/// leaves every album as it was: nothing is let go of unless Apple's whole list was read.
+async fn shared_albums_pass(ctx: &Context, root: &str, data: &LibraryLock) -> bool {
+ use quince_icloud::shared_collections::{changed, places, read};
+ let found = match places(&ctx.http, root, ctx.params.clone()).await {
+ Ok(found) => found,
+ Err(e) => {
+ quiet!("shared albums: couldn't list them ({e})");
+ return false;
+ }
+ };
+ let mut reads = Vec::new();
+ for place in &found {
+ let token = data
+ .read(|l| l.shared_album_token(&place.zone))
+ .await
+ .ok()
+ .flatten();
+ match changed(&ctx.http, root, ctx.params.clone(), place, token.as_deref()).await {
+ Ok(false) => continue,
+ Ok(true) => {}
+ Err(e) => {
+ quiet!("shared albums: {} ({e})", place.zone);
+ continue;
+ }
+ }
+ match read(&ctx.http, root, ctx.params.clone(), place).await {
+ Ok(r) => reads.push((place.clone(), r)),
+ Err(e) => quiet!("shared albums: couldn't read {} ({e})", place.zone),
+ }
+ }
+ let mut library = data.lock_for_pass().await;
+ // Read for an account that is no longer the library's: dropped, as `store` drops it.
+ let owner = library.state(crate::ACCOUNT_KEY).ok().flatten();
+ if ctx.account.is_none() || owner.as_deref() != ctx.account.as_deref() {
+ return false;
+ }
+ let before = library.shared_albums().unwrap_or_default();
+ let zones: Vec<&str> = found.iter().map(|p| p.zone.as_str()).collect();
+ let mut links = std::collections::HashMap::new();
+ let stored = tokio::task::block_in_place(|| {
+ library.atomically(|library| {
+ for (place, r) in &reads {
+ let album = quince_core::shared::SharedAlbum {
+ zone: place.zone.clone(),
+ database: if place.owned() { "private" } else { "shared" }.into(),
+ owner: place.owner.clone(),
+ title: r.about.title.clone(),
+ expires_at: r.about.expires_at,
+ count: 0,
+ cover: None,
+ };
+ library.put_shared_album(&album, &r.photos, r.token.as_deref())?;
+ }
+ library.keep_shared_albums(&zones)
+ })
+ });
+ if let Err(e) = stored {
+ quiet!("shared albums: couldn't store them ({e})");
+ return false;
+ }
+ for (_, r) in reads.iter_mut() {
+ links.extend(std::mem::take(&mut r.links));
+ }
+ crate::photos::remember(links);
+ !reads.is_empty()
+ || library
+ .shared_albums()
+ .map_or(true, |after| after.len() != before.len())
+}
+
/// 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.ts
index 961978c..e924a6f 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -294,8 +294,6 @@ export const api = {
invoke<void>("photos_prepare", { shown }),
/** Shared albums, made or joined, newest first — from Apple each time. */
photosSharedAlbums: () => invoke<SharedAlbum[]>("photos_shared_albums"),
- photosSharedCreate: (name: string) => invoke<string>("photos_shared_create", { name }),
- photosSharedDelete: (guid: string) => invoke<void>("photos_shared_delete", { guid }),
/** Every photo of one burst, in the order they were shot. */
photosBurst: (burst: string) => invoke<Photo[]>("photos_burst", { burst }),
/** Favorite, Delete (to Recently Deleted) or Recover; answers the photo as Apple now has it. */
@@ -903,15 +901,19 @@ export function pictureVersion(master: string): string {
return h.toString(36);
}
-/** A shared album (Apple's sharedstreams service). */
+/** A shared album, as the last sync found it (iOS 27's shared collections). */
export type SharedAlbum = {
- guid: string;
- name: string;
- createdAt: number | null;
- /** Made by this account, as against one it was invited to. */
- owned: boolean;
- public: boolean;
- contributions: boolean;
+ /** Its zone in Apple's Photos: what it is known by. */
+ zone: string;
+ /** `private`: made by this account; `shared`: one it was invited to. */
+ database: "private" | "shared";
+ owner: string | null;
+ title: string | null;
+ /** When Apple ends it, unix seconds. */
+ expiresAt: number | null;
+ count: number;
+ /** Its newest photo, for its picture. */
+ cover: string | null;
};
export type PhotoAlbum = {
@@ -921,12 +923,14 @@ export type PhotoAlbum = {
changeTag: string | null;
/** A folder of albums, not an album of photos. */
folder?: boolean;
+ /** A shared album, by its zone: read from it, and looked at only (nothing in it is edited). */
+ shared?: string;
/** The folder it sits in; none at the top. */
parent?: string | null;
};
/** Where a grid's photos come from (quince-core photos::Source). */
-export type PhotoSource = { view: PhotoView } | { album: string } | { query: string } | { burst: string };
+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 };
/** A grid's layout before its photos (quince-core photos::PhotoIndex). */
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index 9f40093..e85b736 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -901,6 +901,8 @@ export function PhotosView() {
// All, Hidden's Unhide or an album's Remove, from the view it was typed over.
const place: PhotoView = drawn.query ? "library" : view;
const inAlbum = drawn.query ? null : album;
+ /** A shared album open: its photos are looked at, copied and saved, never edited here. */
+ const viewOnly = !drawn.query && !!album?.shared;
const [sorts, setSorts] = useState(readSorts);
/**
* The Hidden album is locked, as in Photos: shown only once asked for, and locked again when
@@ -959,7 +961,7 @@ export function PhotosView() {
setDrawn({ view, album, query: searching });
return;
}
- const source: PhotoSource = searching ? { query: searching } : album ? { album: album.id } : { view };
+ const source: PhotoSource = searching ? { query: searching } : album?.shared ? { shared: album.shared } : album ? { album: album.id } : { view };
const order: PhotoOrder | null = want;
const d = drawnNow.current;
const again = photosNow.current !== null && d.view === view && d.album?.id === album?.id && d.query === searching;
@@ -1030,7 +1032,7 @@ export function PhotosView() {
setCounts((was) => (same(was, counted) ? was : counted));
setAlbums((was) => (same(was, a) ? was : a));
// An album deleted elsewhere is not left open, empty.
- if (album && !a.some(([x]) => x.id === album.id)) setAlbum(null);
+ 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
// 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
@@ -1705,7 +1707,7 @@ export function PhotosView() {
const change = (p: Photo, flag: Flag, on: boolean) => changeAll([p.id], flag, on);
/** A flag set on photos by id — what is here changes at once, the rest when it is read. */
const changeAll = async (list: string[], flag: Flag, on: boolean) => {
- if (list.length === 0) return;
+ if (list.length === 0 || viewOnly) return;
const n = list.length;
// Asked first, in icloud.com's words: a delete reaches every device.
if (
@@ -1864,7 +1866,7 @@ export function PhotosView() {
/** Out of the album open; the photos stay in the library. */
const removeFrom = async (gone: string[]) => {
- if (!album) return;
+ if (!album || viewOnly) return;
const n = gone.length;
const sure = await ask({
title: `Remove ${n === 1 ? "this photo" : `${n} photos`} from the album?`,
@@ -2058,7 +2060,7 @@ export function PhotosView() {
else setChosen(new Set([list[to]]));
anchor.current = to;
reach(to);
- } else if ((e.key === "Delete" || e.key === "Backspace") && selected.length) {
+ } else if ((e.key === "Delete" || e.key === "Backspace") && selected.length && !viewOnly) {
if (inAlbum) void removeFrom(selected);
else if (place !== "recentlyDeleted") void changeAll(selected, "deleted", true);
else void changeAll(selected, "expunged", true);
@@ -2226,8 +2228,14 @@ export function PhotosView() {
const plain = anyPlain(group);
setMenu({
at,
- entries:
- place === "recentlyDeleted" && !inAlbum
+ entries: viewOnly
+ ? [
+ { label: `Download ${n} Items`, run: () => void downloadAs(group, "originals") },
+ { label: "More Download Options", run: () => void store.load(group).then(setOptions, (e) => setError(messageOf(e))) },
+ null,
+ { label: "Start Slideshow", run: () => startShow(p) },
+ ]
+ : place === "recentlyDeleted" && !inAlbum
? [
{ label: `Recover ${n} Items`, run: () => void changeAll(group, "deleted", false) },
null,
@@ -2252,8 +2260,14 @@ export function PhotosView() {
});
return;
}
- const entries: MenuEntry[] =
- place === "recentlyDeleted" && !inAlbum
+ const entries: MenuEntry[] = viewOnly
+ ? [
+ ...(p.kind !== "video" ? [{ label: "Copy", run: () => void copy([p.id]) }] : []),
+ { label: "Download", run: () => void download(p) },
+ { label: "More Download Options", run: () => setOptions([p]) },
+ { label: "Start Slideshow", run: () => startShow(p) },
+ ]
+ : place === "recentlyDeleted" && !inAlbum
? [
{ label: "Recover", run: () => void change(p, "deleted", false) },
null,
@@ -3278,7 +3292,18 @@ export function PhotosView() {
</aside>
<section className="px-main" aria-label={sharedPage ? "Shared Albums" : albumsPage ? "Albums" : title} data-page={albumsPage || sharedPage ? "albums" : undefined}>
- {sharedPage && <SharedAlbums ask={ask} onError={(m) => setError(m)} />}
+ {sharedPage && (
+ <SharedAlbums
+ onError={(m) => setError(m)}
+ onOpen={(a) => {
+ setAlbum({ id: `shared:${a.zone}`, name: a.title ?? "Shared Album", position: 0, changeTag: null, shared: a.zone });
+ setAlbumsPage(false);
+ setSharedPage(false);
+ endSearch();
+ setOpen(null);
+ }}
+ />
+ )}
{albumsPage && !sharedPage && (
<div className="px-albums-page">
{(() => {
@@ -3701,6 +3726,10 @@ export function PhotosView() {
<Trash2 size={17} />
</button>
</>
+ ) : viewOnly ? (
+ <button className="px-full-btn" aria-label="Download" title="Download the original" onClick={() => void download(shown)}>
+ <Download size={17} />
+ </button>
) : (
<>
<button
@@ -3758,7 +3787,7 @@ export function PhotosView() {
</div>
{when}
<div className="toolbar-group">
- {place === "recentlyDeleted" && !inAlbum ? (
+ {viewOnly ? null : place === "recentlyDeleted" && !inAlbum ? (
<>
<button className="tool px-cap" aria-label="Recover" title="Recover" onClick={() => void change(shown, "deleted", false)}>
<RotateCcw size={17} />
diff --git a/src/screens/photos/SharedAlbums.tsx b/src/screens/photos/SharedAlbums.tsx
index 9de97af..03c7ef2 100644
--- a/src/screens/photos/SharedAlbums.tsx
+++ b/src/screens/photos/SharedAlbums.tsx
@@ -1,157 +1,69 @@
/**
- * Shared Albums, as icloud.com's Sharing section lists them: each a card — made by this account
- * ("Shared by you") or joined ("Shared with you") — read from Apple's own service each time the
- * page opens. A new one is named in a sheet and is on the page at once, then confirmed by Apple
- * (or taken back, with Apple's reason); one of this account's is deleted from its menu, asked
- * first, for everyone it was shared with.
+ * Shared Albums, as icloud.com's Sharing section lists them: a card each, with its newest photo,
+ * its name, who made it ("Created by You", or one it was invited to) and when Apple ends it.
+ * Read from the library, which each sync keeps as Apple has them (iOS 27's shared collections);
+ * a card opens the album in the grid, to look through, copy and save. Making albums, adding to
+ * them and comments come once Apple's ways of writing them are mapped.
*/
import { EmptyState } from "../../components/EmptyState";
import { PaneTitle } from "../../components/PaneTitle";
-import { useEffect, useRef, useState } from "react";
-import { useModalFocus } from "../../lib/focus";
-import { Plus, Users } from "lucide-react";
-import { api, type SharedAlbum } from "../../lib/ipc";
-import { Portal } from "../../components/Portal";
-import { RowMenu, type MenuEntry } from "../../components/RowMenu";
-import type { Question } from "../../components/Confirm";
+import { useEffect, useState } from "react";
+import { Users } from "lucide-react";
+import { api, pictureSrc, type SharedAlbum } from "../../lib/ipc";
+import { useRevision } from "../../lib/sync";
-export function SharedAlbums({ ask, onError }: { ask: (q: Question) => Promise<boolean>; onError: (message: string) => void }) {
+/** When an album ends, as icloud.com says it: "Expires November 19". */
+function expiry(at: number | null): string | null {
+ if (!at) return null;
+ return `Expires ${new Date(at * 1000).toLocaleDateString(undefined, { month: "long", day: "numeric" })}`;
+}
+
+export function SharedAlbums({ onError, onOpen }: { onError: (message: string) => void; onOpen: (album: SharedAlbum) => void }) {
const [albums, setAlbums] = useState<SharedAlbum[] | null>(null);
- const [naming, setNaming] = useState(false);
- const [menu, setMenu] = useState<{ at: { x: number; y: number; alignRight: boolean }; entries: MenuEntry[] } | null>(null);
+ // Read again whenever a sync changed Photos: an album new, changed or gone redraws the page.
+ const revision = useRevision("photos");
- const read = () =>
+ useEffect(() => {
api.photosSharedAlbums().then(setAlbums, (e) => {
- setAlbums([]);
+ setAlbums((was) => was ?? []);
onError(String(e));
});
- useEffect(() => {
- void read();
- }, []); // eslint-disable-line react-hooks/exhaustive-deps
-
- const create = async (name: string) => {
- setNaming(false);
- const temp: SharedAlbum = { guid: `new:${Date.now()}`, name, createdAt: Math.floor(Date.now() / 1000), owned: true, public: false, contributions: true };
- setAlbums((list) => [temp, ...(list ?? [])]);
- try {
- const guid = await api.photosSharedCreate(name);
- setAlbums((list) => (list ?? []).map((a) => (a.guid === temp.guid ? { ...a, guid } : a)));
- } catch (e) {
- setAlbums((list) => (list ?? []).filter((a) => a.guid !== temp.guid));
- onError(String(e));
- }
- };
- const remove = async (a: SharedAlbum) => {
- const sure = await ask({
- title: `Delete the shared album “${a.name}”?`,
- body: "It will be deleted from iCloud for everyone it is shared with, along with its photos and comments.",
- action: "Delete",
- danger: true,
- symbol: "trash",
- });
- if (!sure) return;
- const before = albums;
- setAlbums((list) => (list ?? []).filter((x) => x.guid !== a.guid));
- try {
- await api.photosSharedDelete(a.guid);
- } catch (e) {
- setAlbums(before);
- onError(String(e));
- }
- };
+ }, [revision]); // eslint-disable-line react-hooks/exhaustive-deps
const n = albums?.length ?? 0;
return (
<div className="px-albums-page">
<header className="px-albums-head">
- <PaneTitle className="px-heading" countClassName="px-span" count={albums === null ? "\u00a0" : n === 1 ? "1 Item" : `${n} Items`}>
+ <PaneTitle className="px-heading" countClassName="px-span" count={albums === null ? " " : n === 1 ? "1 Shared Album" : `${n} Shared Albums`}>
Shared Albums
</PaneTitle>
- <div className="toolbar-group">
- <button className="tool px-cap" aria-label="New Shared Album" title="New Shared Album" onClick={() => setNaming(true)}>
- <Plus size={16} strokeWidth={2} aria-hidden="true" />
- </button>
- </div>
</header>
{albums !== null && n === 0 ? (
- <EmptyState className="px-empty px-shared-empty" icon={<Users size={28} strokeWidth={1.6} />} action={{ label: "New Shared Album", run: () => setNaming(true) }}>
- Share photos with the people you choose.
+ <EmptyState className="px-empty px-shared-empty" icon={<Users size={28} strokeWidth={1.6} />}>
+ Albums you share from your iPhone, and ones you're invited to, show here.
</EmptyState>
) : (
<div className="px-cards" role="list" aria-busy={albums === null}>
- {(albums ?? []).map((a) => (
- <div
- key={a.guid}
- role="listitem"
- className="px-card"
- aria-label={a.name}
- onContextMenu={(e) => {
- e.preventDefault();
- setMenu({
- at: { x: e.clientX, y: e.clientY, alignRight: false },
- entries: a.owned ? [{ label: "Delete Shared Album", danger: true, run: () => void remove(a) }] : [{ label: "Shared with you — only its owner can delete it" }],
- });
- }}
- >
- <span className="px-card-pic">
- <Users size={34} strokeWidth={1.6} aria-hidden="true" />
- </span>
- <span className="px-card-name">{a.name}</span>
- <span className="px-card-count">
- {a.owned ? "Shared by you" : "Shared with you"}
- {a.createdAt ? ` · ${new Date(a.createdAt * 1000).toLocaleDateString(undefined, { dateStyle: "medium" })}` : ""}
- </span>
- </div>
- ))}
+ {(albums ?? []).map((a) => {
+ const name = a.title ?? "Shared Album";
+ const ends = expiry(a.expiresAt);
+ return (
+ <button key={a.zone} type="button" role="listitem" className="px-card" aria-label={name} onClick={() => onOpen(a)}>
+ <span className="px-card-pic">
+ {a.cover ? (
+ <img src={pictureSrc(a.cover, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />
+ ) : (
+ <Users size={34} strokeWidth={1.6} aria-hidden="true" />
+ )}
+ </span>
+ <span className="px-card-name">{name}</span>
+ <span className="px-card-count">{a.database === "private" ? "Created by You" : "Shared with You"}</span>
+ {ends && <span className="px-card-count">{ends}</span>}
+ </button>
+ );
+ })}
</div>
)}
- {naming && <NameSheet onCancel={() => setNaming(false)} onCreate={(name) => void create(name)} />}
- {menu && <RowMenu at={menu.at} entries={menu.entries} onClose={() => setMenu(null)} />}
</div>
);
}
-
-/** The name for a new shared album, asked in a sheet: Return makes it, Escape leaves it. */
-function NameSheet({ onCancel, onCreate }: { onCancel: () => void; onCreate: (name: string) => void }) {
- const sheetRef = useRef<HTMLFormElement | null>(null);
- useModalFocus(sheetRef);
- const [name, setName] = useState("");
- const field = useRef<HTMLInputElement | null>(null);
- useEffect(() => field.current?.focus(), []);
- const go = () => name.trim() && onCreate(name.trim());
- return (
- <Portal>
- <div className="modal-veil" onClick={onCancel}>
- <form
- ref={sheetRef}
- className="modal-sheet confirm"
- role="dialog"
- aria-modal="true"
- aria-label="New Shared Album"
- onClick={(e) => e.stopPropagation()}
- onSubmit={(e) => {
- e.preventDefault();
- go();
- }}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- e.stopPropagation();
- onCancel();
- }
- }}
- >
- <h2>New Shared Album</h2>
- <input ref={field} className="field px-shared-name" placeholder="Album Name" aria-label="Album Name" value={name} onChange={(e) => setName(e.target.value)} />
- <div className="confirm-actions">
- <button type="button" className="quiet" onClick={onCancel}>
- Cancel
- </button>
- <button type="submit" className="primary confirm-answer" disabled={!name.trim()}>
- Create
- </button>
- </div>
- </form>
- </div>
- </Portal>
- );
-}