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 as iOS 27 keeps them: CloudKit shared-collection zones, private and shared databases

Yashwanth Kamireddia5563303ca3b
diff --git a/crates/quince-icloud/src/cloudkit.rs b/crates/quince-icloud/src/cloudkit.rs
index d41b323..ee8f18e 100644
--- a/crates/quince-icloud/src/cloudkit.rs
+++ b/crates/quince-icloud/src/cloudkit.rs
@@ -25,6 +25,29 @@ pub struct ZoneClient<'a> {
base: String,
container: String,
params: Vec<(String, String)>,
+ /// Which of the container's databases: the account's own, or what others share with it.
+ database: Database,
+ /// Whose zone it is, for a zone another account owns (one shared with this one): CloudKit
+ /// finds a shared zone only by its name and its owner together.
+ owner: Option<String>,
+}
+
+/// A CloudKit container's databases this client reads.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Database {
+ /// The account's own records.
+ Private,
+ /// Zones other accounts have shared with this one (an album someone invited you to).
+ Shared,
+}
+
+impl Database {
+ fn path(self) -> &'static str {
+ match self {
+ Self::Private => "private",
+ Self::Shared => "shared",
+ }
+ }
}
/// One page of zone changes.
@@ -128,7 +151,43 @@ impl<'a> ZoneClient<'a> {
base: ckdatabasews_root.trim_end_matches('/').to_string(),
container: container.to_string(),
params,
+ database: Database::Private,
+ owner: None,
+ }
+ }
+
+ /// The same client, reading `database`.
+ #[must_use]
+ pub fn in_database(mut self, database: Database) -> Self {
+ self.database = database;
+ self
+ }
+
+ /// The same client, for zones `owner` owns (a zone shared with this account).
+ #[must_use]
+ pub fn owned_by(mut self, owner: Option<String>) -> Self {
+ self.owner = owner;
+ self
+ }
+
+ /// A zone as CloudKit names it in a request: its name, and its owner where it is someone
+ /// else's.
+ fn zone_id(&self, zone: &str) -> Value {
+ let mut id = json!({ "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" });
+ if let Some(owner) = &self.owner {
+ id["ownerRecordName"] = json!(owner);
}
+ id
+ }
+
+ /// The address of one of the database's operations (`records/lookup`, `zones/list` …).
+ fn url(&self, operation: &str) -> String {
+ format!(
+ "{}/database/1/{}/production/{}/{operation}",
+ self.base,
+ self.container,
+ self.database.path()
+ )
}
fn query(&self) -> Vec<(String, String)> {
@@ -198,7 +257,7 @@ impl<'a> ZoneClient<'a> {
pub async fn changes(&self, zone: &str, sync_token: Option<&str>) -> Result<Page> {
let mut zone_body = json!({
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
"maxChanges": PAGE_SIZE,
});
// An empty string is not a cursor — Apple answers one with a 500. Absent means
@@ -208,10 +267,7 @@ impl<'a> ZoneClient<'a> {
}
// Note: no `desiredKeys`. Sending an empty list asks Apple for no fields at all.
- let url = format!(
- "{}/database/1/{}/production/private/changes/zone",
- self.base, self.container
- );
+ let url = self.url("changes/zone");
let mut tries = 0;
loop {
tries += 1;
@@ -548,6 +604,32 @@ mod token_tests {
#[cfg(test)]
mod tests {
+
+ /// A zone another account owns is asked for in the shared database, by its name and its
+ /// owner together; the account's own zones, in the private one, by name alone.
+ #[test]
+ fn a_shared_zone_is_named_with_its_owner_in_the_shared_database() {
+ let http = reqwest::Client::new();
+ let own = ZoneClient::new(&http, "https://ck.example/", "c", vec![]);
+ assert_eq!(
+ own.url("zones/list"),
+ "https://ck.example/database/1/c/production/private/zones/list"
+ );
+ assert!(own.zone_id("Z").get("ownerRecordName").is_none());
+ let theirs = ZoneClient::new(&http, "https://ck.example/", "c", vec![])
+ .in_database(Database::Shared)
+ .owned_by(Some("_owner".into()));
+ assert_eq!(
+ theirs.url("records/lookup"),
+ "https://ck.example/database/1/c/production/shared/records/lookup"
+ );
+ assert_eq!(theirs.zone_id("Z")["ownerRecordName"], "_owner");
+ assert_ne!(
+ own.scope(),
+ theirs.scope(),
+ "what is learnt of one is never taken for the other"
+ );
+ }
use super::*;
use wiremock::matchers::{method, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -945,12 +1027,9 @@ impl ZoneClient<'_> {
pub async fn records_query(&self, zone: &str, query: Value) -> Result<Vec<Value>> {
let body = json!({
"query": query,
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
});
- let url = format!(
- "{}/database/1/{}/production/private/records/query",
- self.base, self.container
- );
+ let url = self.url("records/query");
let (status, text) = self.post_json(&url, &body).await?;
if status.as_u16() == 450 {
return Err(Error::ReauthRequired);
@@ -992,13 +1071,10 @@ impl ZoneClient<'_> {
async fn modify_once(&self, zone: &str, operation: &Value) -> Result<Value> {
let body = json!({
"operations": [operation],
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
});
- let url = format!(
- "{}/database/1/{}/production/private/records/modify",
- self.base, self.container
- );
+ let url = self.url("records/modify");
let (status, text) = self.post_json(&url, &body).await?;
if status.as_u16() == 450 {
@@ -1319,13 +1395,10 @@ impl ZoneClient<'_> {
.collect();
let body = json!({
"operations": operations,
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
"atomic": false,
});
- let url = format!(
- "{}/database/1/{}/production/private/records/modify",
- self.base, self.container
- );
+ let url = self.url("records/modify");
let (status, text) = self.post_json(&url, &body).await?;
if status.as_u16() == 450 {
return Err(Error::ReauthRequired);
@@ -1383,13 +1456,10 @@ impl ZoneClient<'_> {
zone: &str,
names: &[&str],
) -> Result<std::collections::HashMap<String, String>> {
- let url = format!(
- "{}/database/1/{}/production/private/records/lookup",
- self.base, self.container
- );
+ let url = self.url("records/lookup");
let body = json!({
"records": names.iter().map(|n| json!({ "recordName": n })).collect::<Vec<_>>(),
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
});
let (status, text) = self.post_json(&url, &body).await?;
if status.as_u16() == 450 {
@@ -1418,10 +1488,7 @@ impl ZoneClient<'_> {
/// The names of the container's private zones Apple could read (`zones/list`). An entry it
/// could not fetch still names its zone but carries `serverErrorCode`, and is left out.
pub async fn zone_names(&self) -> Result<Vec<String>> {
- let url = format!(
- "{}/database/1/{}/production/private/zones/list",
- self.base, self.container
- );
+ let url = self.url("zones/list");
let (status, text) = self.post_json(&url, &json!({})).await?;
if status.as_u16() == 450 || status.as_u16() == 401 {
return Err(Error::ReauthRequired);
@@ -1443,6 +1510,40 @@ impl ZoneClient<'_> {
.collect())
}
+ /// Every zone in the database Apple could read (`zones/list`), as its name and — in the
+ /// shared database, where zones belong to other accounts — its owner.
+ pub async fn zone_ids(&self) -> Result<Vec<(String, Option<String>)>> {
+ let (status, text) = self.post_json(&self.url("zones/list"), &json!({})).await?;
+ if status.as_u16() == 450 || status.as_u16() == 401 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ return Err(Error::Protocol(format!(
+ "CloudKit couldn't list its zones ({status})"
+ )));
+ }
+ let parsed: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
+ let shared = self.database == Database::Shared;
+ Ok(parsed
+ .get("zones")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|z| {
+ z.get("serverErrorCode").is_none() && z.get("deleted") != Some(&json!(true))
+ })
+ .filter_map(|z| {
+ let name = z.pointer("/zoneID/zoneName")?.as_str()?.to_string();
+ let owner = z
+ .pointer("/zoneID/ownerRecordName")
+ .and_then(Value::as_str)
+ .filter(|_| shared)
+ .map(str::to_string);
+ Some((name, owner))
+ })
+ .collect())
+ }
+
/// Who this client reads for: the database, the container and the account (`dsid`), so
/// something learnt of one account is never taken for another's.
#[must_use]
@@ -1452,17 +1553,20 @@ impl ZoneClient<'_> {
.iter()
.find(|(k, _)| k == "dsid")
.map_or("", |(_, v)| v.as_str());
- format!("{}|{}|{dsid}", self.base, self.container)
+ format!(
+ "{}|{}|{}|{}|{dsid}",
+ self.base,
+ self.container,
+ self.database.path(),
+ self.owner.as_deref().unwrap_or("")
+ )
}
pub async fn lookup_record(&self, zone: &str, record_name: &str) -> Result<Option<Value>> {
- let url = format!(
- "{}/database/1/{}/production/private/records/lookup",
- self.base, self.container
- );
+ let url = self.url("records/lookup");
let body = json!({
"records": [{ "recordName": record_name }],
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
});
let (status, text) = self.post_json(&url, &body).await?;
if status.as_u16() == 450 {
@@ -1496,7 +1600,7 @@ impl ZoneClient<'_> {
"value": {
"action": "VALIDATE",
"recordName": record_name,
- "zoneID": { "zoneName": zone, "zoneType": "REGULAR_CUSTOM_ZONE" },
+ "zoneID": self.zone_id(zone),
}
})
}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index 87b5a0a..84928f3 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -33,6 +33,7 @@ pub mod photos_upload;
pub mod push;
pub mod reminders;
pub mod shared_albums;
+pub mod shared_collections;
pub mod sync;
pub mod table;
pub mod topotext;
diff --git a/crates/quince-icloud/src/shared_collections.rs b/crates/quince-icloud/src/shared_collections.rs
new file mode 100644
index 0000000..9bf38f9
--- /dev/null
+++ b/crates/quince-icloud/src/shared_collections.rs
@@ -0,0 +1,241 @@
+//! Shared Albums as Apple keeps them since iOS 27: "shared collections", each a CloudKit zone
+//! of its own in Photos' container (`SharedCollection-<UUID>`), holding the same photo records
+//! as the library (a `CPLAsset` and its `CPLMaster` per photo) and a `cloudkit.share` naming
+//! the album — its title, when it expires, how it may be viewed. An album this account made is
+//! in its private database; one it was invited to is in the shared database, in a zone the
+//! other account owns. The older `sharedstreams` service (`shared_albums`) knows none of them:
+//! it answers an empty list for an album icloud.com shows. Mapped live 2026-11-05 (see
+//! docs/icloud-web/photos.md).
+//!
+//! An album is small (Apple caps one at a few thousand photos), so it is read whole whenever
+//! its change feed says it changed: what Apple has now is what the album holds, nothing kept
+//! from an older read can linger, and no half-read album is ever shown.
+
+use crate::cloudkit::{field, Database, ZoneClient};
+use crate::photos::{links_with_edit, photo_of, Links, CONTAINER};
+use crate::Result;
+use quince_core::photos::Photo;
+use serde_json::Value;
+use std::collections::HashMap;
+
+/// The zones of the new Shared Albums are named so.
+pub const ZONE_PREFIX: &str = "SharedCollection-";
+
+/// Where one shared album lives.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Place {
+ pub database: Database,
+ pub zone: String,
+ /// The account that owns it, for one shared with this account.
+ pub owner: Option<String>,
+}
+
+impl Place {
+ /// Made by this account (in its own database), rather than joined.
+ #[must_use]
+ pub fn owned(&self) -> bool {
+ self.database == Database::Private
+ }
+}
+
+/// A shared album, as its `cloudkit.share` describes it.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct About {
+ pub title: Option<String>,
+ /// When Apple ends the album, unix seconds ("Expires November 19").
+ pub expires_at: Option<i64>,
+}
+
+/// One whole read of a shared album.
+pub struct Read {
+ pub about: About,
+ pub photos: Vec<Photo>,
+ /// Every photo's picture links, by master, as the library keeps them for its own photos.
+ pub links: HashMap<String, Links>,
+ /// Where the album's change feed stands now: asked next time whether anything changed.
+ pub token: Option<String>,
+}
+
+fn client<'a>(
+ http: &'a reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ place: &Place,
+) -> ZoneClient<'a> {
+ ZoneClient::new(http, ckdatabasews_root, CONTAINER, params)
+ .in_database(place.database)
+ .owned_by(place.owner.clone())
+}
+
+/// Every shared album this account made or was invited to.
+pub async fn places(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+) -> Result<Vec<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(ZONE_PREFIX))
+ .map(|(zone, owner)| Place {
+ database,
+ zone,
+ owner,
+ }),
+ );
+ }
+ Ok(out)
+}
+
+/// Whether the album changed since `token`, and the token to keep. With no token held, or one
+/// Apple no longer takes, it has (it is to be read whole).
+pub async fn changed(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ place: &Place,
+ token: Option<&str>,
+) -> Result<bool> {
+ let Some(token) = token.filter(|t| !t.is_empty()) else {
+ return Ok(true);
+ };
+ match client(http, ckdatabasews_root, params, place)
+ .changes(&place.zone, Some(token))
+ .await
+ {
+ Ok(page) => Ok(!page.records.is_empty() || page.more_coming),
+ Err(crate::Error::ReauthRequired) => Err(crate::Error::ReauthRequired),
+ // A cursor Apple refuses (expired) or anything odd about it: read whole, which is
+ // always right.
+ Err(_) => Ok(true),
+ }
+}
+
+/// The album read whole: what it is called, every photo in it, and their links.
+pub async fn read(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ place: &Place,
+) -> Result<Read> {
+ let walk = client(http, ckdatabasews_root, params, place)
+ .all_records(&place.zone, None)
+ .await?;
+ let (about, photos, links) = parse(&walk.records);
+ Ok(Read {
+ about,
+ photos,
+ links,
+ token: walk.token,
+ })
+}
+
+/// 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.
+#[must_use]
+pub fn parse(records: &[Value]) -> (About, Vec<Photo>, HashMap<String, Links>) {
+ let live = || {
+ records
+ .iter()
+ .filter(|r| r.get("deleted").and_then(Value::as_bool) != Some(true))
+ };
+ let masters: HashMap<String, &Value> = live()
+ .filter(|r| field::record_type(r).as_deref() == Some("CPLMaster"))
+ .filter_map(|r| Some((field::record_name(r)?, r)))
+ .collect();
+ let mut about = About::default();
+ let mut photos = Vec::new();
+ let mut links = HashMap::new();
+ for r in live() {
+ match field::record_type(r).as_deref() {
+ Some("cloudkit.share") => {
+ about.title = field::string(r, "cloudkit.title").filter(|t| !t.trim().is_empty());
+ about.expires_at = field::timestamp_seconds(r, "expiryDate");
+ }
+ Some("CPLAsset") => {
+ let Some(master) = field::reference(r, "masterRef").and_then(|m| masters.get(&m))
+ else {
+ continue;
+ };
+ if let Some(photo) = photo_of(r, master) {
+ links.insert(photo.master.clone(), links_with_edit(Some(r), master));
+ photos.push(photo);
+ }
+ }
+ _ => {}
+ }
+ }
+ // Newest first, as an album shows them; ties by id so the order is the same every read.
+ photos.sort_by(|a, b| b.taken_at.cmp(&a.taken_at).then(a.id.cmp(&b.id)));
+ (about, photos, links)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use base64::Engine;
+ use serde_json::json;
+
+ fn master(name: &str) -> Value {
+ json!({"recordName": name, "recordType": "CPLMaster", "fields": {
+ "itemType": {"value": "public.jpeg"},
+ "filenameEnc": {"value": base64::engine::general_purpose::STANDARD.encode(format!("{name}.JPG"))},
+ "resOriginalWidth": {"value": 1200}, "resOriginalHeight": {"value": 2600},
+ "resJPEGThumbRes": {"value": {"downloadURL": "https://cvws.example/thumb/${f}"}},
+ "resOriginalRes": {"value": {"downloadURL": "https://cvws.example/orig/${f}"}}
+ }})
+ }
+
+ fn asset(name: &str, master: &str, taken_ms: i64) -> Value {
+ json!({"recordName": name, "recordType": "CPLAsset", "fields": {
+ "masterRef": {"value": {"recordName": master}},
+ "assetDate": {"value": taken_ms}
+ }})
+ }
+
+ /// What Apple sent for his "Wallpapers" album, cut down: the share names it and says when
+ /// it ends; each asset with its master is a photo with links; newest first.
+ #[test]
+ fn an_albums_records_are_its_title_expiry_and_photos() {
+ let records = vec![
+ json!({"recordName": "share", "recordType": "cloudkit.share", "fields": {
+ "cloudkit.title": {"value": "Wallpapers"},
+ "expiryDate": {"value": 1_795_498_444_000_i64}
+ }}),
+ master("M1"),
+ asset("A1", "M1", 1_790_000_000_000),
+ master("M2"),
+ asset("A2", "M2", 1_791_000_000_000),
+ json!({"recordName": "q", "recordType": "CPLSharedCollectionQuota", "fields": {}}),
+ ];
+ let (about, photos, links) = parse(&records);
+ assert_eq!(about.title.as_deref(), Some("Wallpapers"));
+ assert_eq!(about.expires_at, Some(1_795_498_444));
+ let ids: Vec<&str> = photos.iter().map(|p| p.id.as_str()).collect();
+ assert_eq!(ids, ["A2", "A1"], "newest first");
+ assert!(links["M1"].thumb.is_some() && links["M1"].original.is_some());
+ }
+
+ /// An asset whose master hasn't come (or was deleted), a deleted asset, and a master with
+ /// no asset are no photos: an album never shows a photo it can't draw.
+ #[test]
+ fn only_whole_photos_are_shown() {
+ let mut gone = asset("A3", "M3", 1);
+ gone["deleted"] = json!(true);
+ let records = vec![
+ asset("A1", "M-missing", 1),
+ master("M3"),
+ gone,
+ master("M4"),
+ ];
+ let (about, photos, _) = parse(&records);
+ assert!(photos.is_empty(), "{photos:?}");
+ assert_eq!(about, About::default());
+ }
+}
diff --git a/probe/examples/photos_zones_all.rs b/probe/examples/photos_zones_all.rs
new file mode 100644
index 0000000..ff3b06f
--- /dev/null
+++ b/probe/examples/photos_zones_all.rs
@@ -0,0 +1,92 @@
+//! Read-only: every Photos zone in the private and shared databases, as icloud.com lists them
+//! with and without `excludeSCZones` (shared-collection zones: the new Shared Albums), and the
+//! records of the first shared-collection zone, shown as names, types and short values.
+use anyhow::{anyhow, Result};
+use serde_json::{json, Value};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ let p = client.service_params();
+ let http = client.http().clone();
+ let mut sc: Vec<(String, Value)> = Vec::new();
+ for db in ["private", "shared"] {
+ for exclude in [true, false] {
+ let url = format!(
+ "{}/database/1/com.apple.photos.cloud/production/{db}/zones/list",
+ root.trim_end_matches('/')
+ );
+ let mut q = p.clone();
+ if exclude {
+ q.push(("excludeSCZones".into(), "true".into()));
+ }
+ let r = http
+ .get(&url)
+ .query(&q)
+ .header("X-Apple-Internal-IncludeCMMZones", "true")
+ .send()
+ .await?;
+ let status = r.status();
+ let v: Value = serde_json::from_str(&r.text().await?).unwrap_or(Value::Null);
+ println!("── {db} excludeSCZones={exclude}: {status}");
+ for z in v["zones"].as_array().into_iter().flatten() {
+ let id = &z["zoneID"];
+ let name = id["zoneName"].as_str().unwrap_or("?");
+ println!(
+ " {name} owner={} type={}",
+ id["ownerRecordName"]
+ .as_str()
+ .map(|s| &s[..s.len().min(10)])
+ .unwrap_or("-"),
+ id["zoneType"]
+ );
+ if !exclude
+ && !name.starts_with("PrimarySync")
+ && !name.starts_with("CMM")
+ && !sc.iter().any(|(_, i)| i == id)
+ {
+ sc.push((db.to_string(), id.clone()));
+ }
+ }
+ }
+ }
+ for (db, zone) in sc.iter().take(3) {
+ let url = format!(
+ "{}/database/1/com.apple.photos.cloud/production/{db}/changes/zone",
+ root.trim_end_matches('/')
+ );
+ let body = json!({ "zones": [{ "zoneID": zone, "resultsLimit": 20 }] });
+ let r = http
+ .post(&url)
+ .query(&p)
+ .header("content-type", "text/plain")
+ .body(body.to_string())
+ .send()
+ .await?;
+ println!("── records in {} ({db}): {}", zone["zoneName"], r.status());
+ let v: Value = serde_json::from_str(&r.text().await?).unwrap_or(Value::Null);
+ for z in v["zones"].as_array().into_iter().flatten() {
+ for rec in z["records"].as_array().into_iter().flatten() {
+ let fields: Vec<String> = rec["fields"]
+ .as_object()
+ .map(|m| {
+ m.iter()
+ .map(|(k, f)| format!("{k}:{}", f["type"].as_str().unwrap_or("?")))
+ .collect()
+ })
+ .unwrap_or_default();
+ println!(" {} [{}]", rec["recordType"], fields.join(", "));
+ }
+ println!(" moreComing={}", z["moreComing"]);
+ }
+ }
+ Ok(())
+}
diff --git a/probe/examples/shared_album_contents.rs b/probe/examples/shared_album_contents.rs
new file mode 100644
index 0000000..f12cecd
--- /dev/null
+++ b/probe/examples/shared_album_contents.rs
@@ -0,0 +1,112 @@
+//! Read-only: what Apple answers for the photos in each shared album (sharedstreams webgetassets,
+//! webgetassetcount, webasseturls), printed as structure — key names, types and short values — so
+//! the shapes can be mapped. Nothing is written.
+use anyhow::{anyhow, Result};
+use serde_json::{json, Value};
+
+fn shape(v: &Value, depth: usize, out: &mut String) {
+ let pad = " ".repeat(depth);
+ match v {
+ Value::Object(m) => {
+ for (k, x) in m {
+ match x {
+ Value::Object(_) | Value::Array(_) => {
+ out.push_str(&format!("{pad}{k}:\n"));
+ shape(x, depth + 1, out);
+ }
+ _ => {
+ let s = x.to_string();
+ out.push_str(&format!(
+ "{pad}{k}: {}\n",
+ s.chars().take(60).collect::<String>()
+ ));
+ }
+ }
+ }
+ }
+ Value::Array(a) => {
+ out.push_str(&format!("{pad}[{} items] first:\n", a.len()));
+ if let Some(first) = a.first() {
+ shape(first, depth + 1, out);
+ }
+ }
+ other => out.push_str(&format!(
+ "{pad}{}\n",
+ other.to_string().chars().take(60).collect::<String>()
+ )),
+ }
+}
+
+#[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("sharedstreams")
+ .ok_or_else(|| anyhow!("no sharedstreams"))?;
+ let p = client.service_params();
+ let dsid = p
+ .iter()
+ .find(|(k, _)| k == "dsid")
+ .map(|(_, v)| v.clone())
+ .ok_or_else(|| anyhow!("no dsid"))?;
+ let http = client.http().clone();
+ let call = |base: String, endpoint: &'static str, body: Value| {
+ let (http, p) = (http.clone(), p.clone());
+ async move {
+ let url = format!("{}/{endpoint}", base.trim_end_matches('/'));
+ let r = http
+ .post(&url)
+ .query(&p)
+ .header("content-type", "text/plain;charset=UTF-8")
+ .body(body.to_string())
+ .send()
+ .await?;
+ let status = r.status();
+ let text = r.text().await?;
+ println!("── {endpoint}: {status}");
+ Ok::<Value, anyhow::Error>(
+ serde_json::from_str(&text)
+ .unwrap_or(Value::String(text.chars().take(300).collect())),
+ )
+ }
+ };
+ let base = format!("{}/{dsid}/sharedstreams", root.trim_end_matches('/'));
+ let list = call(base.clone(), "webgetalbumslist", json!({})).await?;
+ let mut s = String::new();
+ shape(&list, 0, &mut s);
+ println!("{s}");
+ for a in list["albums"].as_array().into_iter().flatten() {
+ let guid = a["albumguid"].as_str().unwrap_or_default().to_string();
+ let ctag = a["albumctag"].clone();
+ let at = a["albumlocation"]
+ .as_str()
+ .map(|l| format!("{}{dsid}/sharedstreams", l))
+ .unwrap_or(base.clone());
+ let count = call(at.clone(), "webgetassetcount", json!({ "albumguid": guid })).await?;
+ println!("{count}");
+ let assets = call(
+ at.clone(),
+ "webgetassets",
+ json!({ "albumguid": guid, "offset": "0", "limit": "3", "albumctag": ctag }),
+ )
+ .await?;
+ let mut s = String::new();
+ shape(&assets, 0, &mut s);
+ println!("{s}");
+ let stream = call(
+ at.clone(),
+ "webstream",
+ json!({ "albumguid": guid, "streamCtag": Value::Null }),
+ )
+ .await?;
+ let mut s = String::new();
+ shape(&stream, 0, &mut s);
+ println!("{}", s.lines().take(80).collect::<Vec<_>>().join("\n"));
+ }
+ Ok(())
+}
diff --git a/probe/examples/shared_collections_read.rs b/probe/examples/shared_collections_read.rs
new file mode 100644
index 0000000..67d8195
--- /dev/null
+++ b/probe/examples/shared_collections_read.rs
@@ -0,0 +1,49 @@
+//! Read-only: the account's shared albums through quince_icloud::shared_collections — every
+//! album found, its title and expiry, how many photos it holds and whether each has links.
+use anyhow::{anyhow, Result};
+use quince_icloud::shared_collections::{changed, places, read};
+
+#[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 found = places(&http, &root, p.clone()).await?;
+ println!("{} shared album(s)", found.len());
+ for place in &found {
+ let r = read(&http, &root, p.clone(), place).await?;
+ println!(
+ "{:?} owned={} title={:?} expires={:?} photos={} with_thumbs={} with_originals={}",
+ place.database,
+ place.owned(),
+ r.about.title,
+ r.about
+ .expires_at
+ .and_then(|s| jiff::Timestamp::from_second(s).ok())
+ .map(|t| t.to_string()),
+ r.photos.len(),
+ r.photos
+ .iter()
+ .filter(|p| r.links.get(&p.master).is_some_and(|l| l.thumb.is_some()))
+ .count(),
+ r.photos
+ .iter()
+ .filter(|p| r.links.get(&p.master).is_some_and(|l| l.original.is_some()))
+ .count(),
+ );
+ for p in r.photos.iter().take(3) {
+ println!(" {:?} {}x{} {:?}", p.kind, p.width, p.height, p.filename);
+ }
+ let again = changed(&http, &root, p.clone(), place, r.token.as_deref()).await?;
+ println!(" changed since this read: {again}");
+ }
+ Ok(())
+}