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.

Contacts: read the address book only when it changed

Yashwanth Kamireddidffb7f5502af
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
index dcc6163..2fd2073 100644
--- a/crates/quince-icloud/src/contacts.rs
+++ b/crates/quince-icloud/src/contacts.rs
@@ -174,12 +174,60 @@ pub fn parse(body: &Value) -> Vec<Contact> {
/// `syncToken` is how the service knows which version of the address book a change is based
/// on; `prefToken` carries the sort order the account is set to. Writing without them is
/// refused.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Tokens {
pub sync: String,
pub pref: String,
}
+impl Tokens {
+ /// As kept in the library's sync position for Contacts.
+ #[must_use]
+ pub fn stored(&self) -> String {
+ serde_json::to_string(self).unwrap_or_default()
+ }
+
+ /// From the library's sync position; `None` for anything else (a library from before
+ /// positions were kept), which reads the book whole.
+ #[must_use]
+ pub fn from_stored(s: &str) -> Option<Self> {
+ serde_json::from_str(s).ok()
+ }
+}
+
+/// What a Contacts pass found: the book read again, or Apple saying nothing changed since the
+/// tokens the library kept.
+pub enum Pass {
+ Read(AddressBook, Tokens),
+ Unchanged(Tokens),
+}
+
+/// A pass over Contacts that reads the book only when it changed. Apple's `/co/changeset`
+/// answers "unchanged" in a few hundred milliseconds; a change (or tokens too old) is answered
+/// 420, and only then is the whole book read — Apple sends no partial changes to read instead.
+/// `since` is `None` for a full read (the first, and the daily one).
+///
+/// # Errors
+/// When Apple cannot be reached or refuses.
+pub async fn pass(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ since: Option<Tokens>,
+) -> Result<Pass> {
+ if let Some(mut tokens) = since {
+ match changed(http, root, params.clone(), &mut tokens).await {
+ Ok(false) => return Ok(Pass::Unchanged(tokens)),
+ Ok(true) => {}
+ // A session gone is the caller's to mend; anything else, the book is read.
+ Err(Error::ReauthRequired) => return Err(Error::ReauthRequired),
+ Err(_) => {}
+ }
+ }
+ let (book, tokens) = fetch_book_with_tokens(http, root, params).await?;
+ Ok(Pass::Read(book, tokens))
+}
+
/// Read the address book along with the tokens a write will need.
///
/// The tokens come from the same response as the contacts, so asking for both at once is
@@ -1344,6 +1392,18 @@ pub fn apply(library: &mut quince_core::Library, book: AddressBook) -> Result<us
#[cfg(test)]
mod list_tests {
+ /// The tokens a pass keeps come back as they went in; anything else kept there (a library
+ /// from before) reads as none, so the book is read whole rather than trusted.
+ #[test]
+ fn kept_tokens_come_back_whole_or_not_at_all() {
+ let t = super::Tokens {
+ sync: "S1".into(),
+ pref: "P1".into(),
+ };
+ assert_eq!(super::Tokens::from_stored(&t.stored()), Some(t));
+ assert_eq!(super::Tokens::from_stored("an old position"), None);
+ }
+
/// The phone renamed the person while the form here was open on their notes: saving
/// writes the notes and keeps the phone's name — and Apple's numbers, untouched here —
/// against the version Apple holds now.
diff --git a/probe/examples/contacts_pass_live.rs b/probe/examples/contacts_pass_live.rs
new file mode 100644
index 0000000..777b83e
--- /dev/null
+++ b/probe/examples/contacts_pass_live.rs
@@ -0,0 +1,95 @@
+//! Live: a Contacts pass reads the book only when it changed. Unchanged, it is answered from
+//! /co/changeset alone; a throwaway card made, the next pass reads the book with it; deleted,
+//! the next pass reads it without. Prints counts and timings only.
+use anyhow::{anyhow, Result};
+use quince_core::contacts::{Contact, ContactMethod};
+use quince_icloud::contacts::{self, Pass, Tokens};
+use std::time::Instant;
+
+#[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("contacts")
+ .ok_or_else(|| anyhow!("no contacts"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let run = |since: Option<Tokens>| {
+ let (http, root, p) = (http.clone(), root.clone(), p.clone());
+ async move {
+ let t = Instant::now();
+ let r = contacts::pass(&http, &root, p, since).await?;
+ Ok::<_, anyhow::Error>((r, t.elapsed().as_millis()))
+ }
+ };
+ let say = |what: &str, r: &Pass, ms: u128| match r {
+ Pass::Read(b, _) => println!("{what}: read the book, {} cards, {ms} ms", b.contacts.len()),
+ Pass::Unchanged(_) => println!("{what}: unchanged, nothing read, {ms} ms"),
+ };
+ let (first, ms) = run(None).await?;
+ say("first pass", &first, ms);
+ let Pass::Read(book, tokens) = first else {
+ return Err(anyhow!("first pass must read"));
+ };
+ let before = book.contacts.len();
+ let (again, ms) = run(Some(tokens.clone())).await?;
+ say("nothing changed", &again, ms);
+ println!(
+ "{} skipped when unchanged",
+ if matches!(again, Pass::Unchanged(_)) {
+ "PASS"
+ } else {
+ "FAIL"
+ }
+ );
+ let tokens = match again {
+ Pass::Unchanged(t) | Pass::Read(_, t) => t,
+ };
+
+ let throwaway = Contact {
+ guid: String::new(),
+ first_name: Some("Quince mount test".into()),
+ middle_name: None,
+ last_name: Some(format!("{}", std::process::id())),
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ photo_url: None,
+ photo_signature: None,
+ photo_crop: None,
+ etag: None,
+ methods: vec![ContactMethod {
+ kind: "email".into(),
+ label: None,
+ value: "[email protected]".into(),
+ }],
+ };
+ let guid = contacts::create(&http, &root, p.clone(), &tokens, &throwaway).await?;
+ let (after, ms) = run(Some(tokens.clone())).await?;
+ say("after a card was made", &after, ms);
+ let ok = matches!(&after, Pass::Read(b, _) if b.contacts.len() == before + 1 && b.contacts.iter().any(|c| c.guid == guid));
+ println!(
+ "{} read again, with the new card",
+ if ok { "PASS" } else { "FAIL" }
+ );
+ let (tokens, made) = match after {
+ Pass::Read(b, t) => (t, b.contacts.into_iter().find(|c| c.guid == guid)),
+ Pass::Unchanged(t) => (t, None),
+ };
+ let made = made
+ .ok_or_else(|| anyhow!("throwaway not read back — delete it by hand: Quince mount test"))?;
+ contacts::delete(&http, &root, p.clone(), &tokens, &made).await?;
+ let (gone, ms) = run(Some(tokens)).await?;
+ say("after it was deleted", &gone, ms);
+ let ok = matches!(&gone, Pass::Read(b, _) if b.contacts.len() == before && !b.contacts.iter().any(|c| c.guid == guid));
+ println!(
+ "{} read again, without it",
+ if ok { "PASS" } else { "FAIL" }
+ );
+ Ok(())
+}
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
index 71fc121..4b5dc79 100644
--- a/src-tauri/src/refresh.rs
+++ b/src-tauri/src/refresh.rs
@@ -263,18 +263,41 @@ async fn run(client: &Arc<Mutex<Client>>, data: &Mutex<Library>, services: &[&st
reports.push(match ctx.contacts.as_deref() {
None => unavailable("contacts", "Contacts"),
Some(root) => {
- // Fetch and store as one, never across a save: see `CONTACTS_PASS`.
+ // Fetch and store as one, never across a save: see `CONTACTS_PASS`. The book
+ // is read only when Apple says it changed (contacts::pass).
let _one = crate::CONTACTS_PASS.lock().await;
+ let since = token(data, "contacts")
+ .await
+ .and_then(|t| quince_icloud::contacts::Tokens::from_stored(&t));
+ let full = since.is_none();
let fetched =
- quince_icloud::contacts::fetch(&ctx.http, root, ctx.params.clone()).await;
+ quince_icloud::contacts::pass(&ctx.http, root, ctx.params.clone(), since).await;
store(
"contacts",
"Contacts",
data,
ctx.account.as_deref(),
fetched,
- |library, people| {
- let count = quince_icloud::contacts::apply(library, people)?;
+ move |library, pass| {
+ use quince_icloud::contacts::Pass;
+ let count = match pass {
+ Pass::Read(book, tokens) => {
+ let n = quince_icloud::contacts::apply(library, book)?;
+ library.mark_synced("contacts", Some(&tokens.stored()))?;
+ n
+ }
+ Pass::Unchanged(tokens) => {
+ library.mark_synced("contacts", Some(&tokens.stored()))?;
+ let n: i64 = library
+ .conn()
+ .query_row("SELECT count(*) FROM contacts", [], |r| r.get(0))
+ .map_err(quince_core::Error::from)?;
+ usize::try_from(n).unwrap_or(0)
+ }
+ };
+ if full {
+ library.mark_full_sync("contacts")?;
+ }
Ok(format!("{count} contact{}", plural(count)))
},
)