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

Yashwanth Kamireddibbd83d671674
diff --git a/.uiverify/a11y.mjs b/.uiverify/a11y.mjs
index 1140033..67f7d6d 100644
--- a/.uiverify/a11y.mjs
+++ b/.uiverify/a11y.mjs
@@ -37,6 +37,9 @@ function installStub({ screen, services, twoFactor }) {
case "notes_in": return [];
case "notes_last_synced": return Math.floor(Date.now() / 1000);
case "notes_sync": return [0, 0];
+ case "contacts_list": return [];
+ case "contacts_last_synced": return Math.floor(Date.now() / 1000);
+ case "contacts_sync": return 0;
default: return null;
}
},
diff --git a/.uiverify/assert.mjs b/.uiverify/assert.mjs
index 8cf0be2..c884e08 100644
--- a/.uiverify/assert.mjs
+++ b/.uiverify/assert.mjs
@@ -25,6 +25,9 @@ await ctx.addInitScript(({ services }) => {
if (cmd === "notes_in") return [];
if (cmd === "notes_last_synced") return Math.floor(Date.now() / 1000);
if (cmd === "notes_sync") return [0, 0];
+ if (cmd === "contacts_list") return [];
+ if (cmd === "contacts_last_synced") return Math.floor(Date.now() / 1000);
+ if (cmd === "contacts_sync") return 0;
return null;
},
};
diff --git a/.uiverify/keyboard.mjs b/.uiverify/keyboard.mjs
index ed3bb16..c920255 100644
--- a/.uiverify/keyboard.mjs
+++ b/.uiverify/keyboard.mjs
@@ -36,6 +36,9 @@ function installStub({ screen, services, twoFactor }) {
case "notes_in": return [];
case "notes_last_synced": return Math.floor(Date.now() / 1000);
case "notes_sync": return [0, 0];
+ case "contacts_list": return [];
+ case "contacts_last_synced": return Math.floor(Date.now() / 1000);
+ case "contacts_sync": return 0;
default: return null;
}
},
diff --git a/.uiverify/shots.mjs b/.uiverify/shots.mjs
index b43b833..38e4cb1 100644
--- a/.uiverify/shots.mjs
+++ b/.uiverify/shots.mjs
@@ -19,7 +19,7 @@ const SERVICES = ["account","archivews","calendar","ckdatabasews","ckdeviceservi
value it needs must arrive through the single argument. */
/* Fixture events, so the agenda's rendering is verified without inventing rows in anyone's
real library. Times are unix seconds relative to now. */
-function installStub({ screen, services, twoFactor, calendarFixture, notesFixture }) {
+function installStub({ screen, services, twoFactor, calendarFixture, notesFixture, contactsFixture }) {
const HOUR = 3600, DAY = 86400;
const base = Math.floor(Date.now() / 1000 / DAY) * DAY + 9 * HOUR;
const events = !calendarFixture ? [] : [
@@ -63,6 +63,22 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
body: "These sources outline the fundamental principles and methodologies of **Software Testing Methodologies (CSEN3311)**, emphasizing its evolution from simple debugging to a structured, process-oriented discipline. The material details the **Software Testing Life Cycle (STLC)**, covering essential phases from initial planning and test design to execution and post-implementation review.",
locked: false, pinned: false, createdAt: null, modifiedAt: 1787800000, etag: null },
];
+ const contactList = !contactsFixture ? [] : [
+ { guid: "c1", firstName: "Zoya", lastName: "Ahuja", company: null, isCompany: false,
+ birthday: null, notes: null, etag: null,
+ methods: [{ kind: "phone", label: "mobile", value: "+91 90000 00001" },
+ { kind: "email", label: "home", value: "[email protected]" }] },
+ { guid: "c2", firstName: "Amma", lastName: null, company: null, isCompany: false,
+ birthday: null, notes: null, etag: null,
+ methods: [{ kind: "phone", label: null, value: "+91 98765 43210" }] },
+ { guid: "c3", firstName: null, lastName: null, company: "Northfield University",
+ isCompany: true, birthday: null, notes: null, etag: null,
+ methods: [{ kind: "phone", label: "work", value: "+91 891 284 0000" },
+ { kind: "url", label: null, value: "northfield.example" }] },
+ { guid: "c4", firstName: null, lastName: null, company: null, isCompany: false,
+ birthday: null, notes: null, etag: null,
+ methods: [{ kind: "phone", label: null, value: "+91 90000 11111" }] },
+ ];
const calendars = [
{ guid: "work", title: "Work", colour: "#cc73e1", ctag: null, sortOrder: 0, enabled: true },
{ guid: "home", title: "Home", colour: "#0088ff", ctag: null, sortOrder: 1, enabled: true },
@@ -94,6 +110,9 @@ function installStub({ screen, services, twoFactor, calendarFixture, notesFixtur
case "notes_in": return !notesFixture ? [] : noteList;
case "notes_last_synced": return Math.floor(Date.now() / 1000);
case "notes_sync": return [0, 0];
+ case "contacts_list": return !contactsFixture ? [] : contactList;
+ case "contacts_last_synced": return Math.floor(Date.now() / 1000) - 300;
+ case "contacts_sync": return contactList.length;
case "auth_two_factor_options": return twoFactor;
case "auth_resend_code": return null;
case "auth_send_sms": return null;
@@ -147,18 +166,25 @@ const shots = [
await p.waitForSelector(".note-rows .note-row");
await p.click('.note-row:has-text("These sources")');
} },
+ { name: "11-contacts", screen: "library", theme: "dark", contactsFixture: true,
+ viewport: { width: 1100, height: 820 },
+ act: async (p) => {
+ await p.click('.nav-item:has-text("Contacts")');
+ await p.waitForSelector(".contact-rows .contact-row");
+ await p.click('.contact-row:has-text("Zoya")');
+ } },
{ name: "04-library", screen: "library", theme: "light" },
{ name: "05-library-dark", screen: "library", theme: "dark" },
];
const browser = await chromium.launch();
-for (const { name, screen, theme, act, twoFactor = PUSHED, calendarFixture = false, notesFixture = false, viewport } of shots) {
+for (const { name, screen, theme, act, twoFactor = PUSHED, calendarFixture = false, notesFixture = false, contactsFixture = false, viewport } of shots) {
const ctx = await browser.newContext({
viewport: viewport ?? { width: 1040, height: 720 },
deviceScaleFactor: 2,
colorScheme: theme,
});
- await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor, calendarFixture, notesFixture });
+ await ctx.addInitScript(installStub, { screen, services: SERVICES, twoFactor, calendarFixture, notesFixture, contactsFixture });
const page = await ctx.newPage();
const errors = [];
page.on("console", (m) => m.type() === "error" && errors.push(m.text()));
diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rs
new file mode 100644
index 0000000..5bc55d1
--- /dev/null
+++ b/crates/quince-core/src/contacts.rs
@@ -0,0 +1,290 @@
+//! Contacts in the local library.
+
+use crate::{Library, Result};
+use rusqlite::params;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ContactMethod {
+ /// `phone`, `email`, `url`, `address`.
+ pub kind: String,
+ pub label: Option<String>,
+ pub value: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct Contact {
+ pub guid: String,
+ pub first_name: Option<String>,
+ pub last_name: Option<String>,
+ pub company: Option<String>,
+ pub is_company: bool,
+ pub birthday: Option<String>,
+ pub notes: Option<String>,
+ pub etag: Option<String>,
+ #[serde(default)]
+ pub methods: Vec<ContactMethod>,
+}
+
+impl Contact {
+ /// What to show, whichever name fields this contact happens to have.
+ ///
+ /// A contact with only a phone number still needs a label, so the fallback chain ends at
+ /// the first method rather than at an empty string.
+ #[must_use]
+ pub fn display_name(&self) -> String {
+ let full = [self.first_name.as_deref(), self.last_name.as_deref()]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" ");
+ if !full.trim().is_empty() {
+ return full;
+ }
+ if let Some(company) = self.company.as_deref().filter(|c| !c.trim().is_empty()) {
+ return company.to_string();
+ }
+ self.methods
+ .first()
+ .map_or_else(|| "No Name".to_string(), |m| m.value.clone())
+ }
+
+ /// Sorted on last name where there is one, which is how Apple orders the list.
+ fn sort_key(&self) -> String {
+ let key = [self.last_name.as_deref(), self.first_name.as_deref()]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(" ");
+ let key = if key.trim().is_empty() {
+ self.display_name()
+ } else {
+ key
+ };
+ key.to_lowercase()
+ }
+}
+
+fn now() -> i64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX))
+}
+
+impl Library {
+ /// Replace the address book, dropping anyone Apple no longer reports.
+ pub fn put_contacts(&mut self, contacts: &[Contact]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ {
+ let mut upsert = tx.prepare(
+ "INSERT INTO contacts (guid, first_name, last_name, company, is_company,
+ sort_name, birthday, notes, etag, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
+ ON CONFLICT(guid) DO UPDATE SET
+ first_name = excluded.first_name, last_name = excluded.last_name,
+ company = excluded.company, is_company = excluded.is_company,
+ sort_name = excluded.sort_name, birthday = excluded.birthday,
+ notes = excluded.notes, etag = excluded.etag,
+ updated_at = excluded.updated_at",
+ )?;
+ let mut clear = tx.prepare("DELETE FROM contact_methods WHERE contact_guid = ?1")?;
+ let mut add = tx.prepare(
+ "INSERT INTO contact_methods (contact_guid, kind, label, value, position)
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ )?;
+
+ let stamp = now();
+ for c in contacts {
+ upsert.execute(params![
+ c.guid,
+ c.first_name,
+ c.last_name,
+ c.company,
+ i64::from(c.is_company),
+ c.sort_key(),
+ c.birthday,
+ c.notes,
+ c.etag,
+ stamp
+ ])?;
+ // Methods are rewritten wholesale: a number removed on the phone must not
+ // linger here.
+ clear.execute(params![c.guid])?;
+ for (i, m) in c.methods.iter().enumerate() {
+ add.execute(params![
+ c.guid,
+ m.kind,
+ m.label,
+ m.value,
+ i64::try_from(i).unwrap_or(0)
+ ])?;
+ }
+ }
+
+ let keep: Vec<&str> = contacts.iter().map(|c| c.guid.as_str()).collect();
+ if keep.is_empty() {
+ tx.execute("DELETE FROM contacts", [])?;
+ } else {
+ let placeholders = vec!["?"; keep.len()].join(",");
+ tx.execute(
+ &format!("DELETE FROM contacts WHERE guid NOT IN ({placeholders})"),
+ rusqlite::params_from_iter(keep),
+ )?;
+ }
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
+ /// The address book in display order, optionally filtered.
+ ///
+ /// The filter matches names and any stored method, so searching a phone number finds the
+ /// person it belongs to.
+ pub fn contacts(&self, search: Option<&str>) -> Result<Vec<Contact>> {
+ let needle = search
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(|s| format!("%{}%", s.to_lowercase()));
+
+ let mut stmt = self.conn.prepare(
+ "SELECT c.guid, c.first_name, c.last_name, c.company, c.is_company,
+ c.birthday, c.notes, c.etag
+ FROM contacts c
+ WHERE ?1 IS NULL
+ OR lower(coalesce(c.first_name, '') || ' ' || coalesce(c.last_name, '')
+ || ' ' || coalesce(c.company, '')) LIKE ?1
+ OR EXISTS (SELECT 1 FROM contact_methods m
+ WHERE m.contact_guid = c.guid AND lower(m.value) LIKE ?1)
+ ORDER BY c.sort_name",
+ )?;
+ let rows = stmt.query_map(params![needle], |row| {
+ Ok(Contact {
+ guid: row.get(0)?,
+ first_name: row.get(1)?,
+ last_name: row.get(2)?,
+ company: row.get(3)?,
+ is_company: row.get::<_, i64>(4)? != 0,
+ birthday: row.get(5)?,
+ notes: row.get(6)?,
+ etag: row.get(7)?,
+ methods: Vec::new(),
+ })
+ })?;
+ let mut contacts = rows.collect::<rusqlite::Result<Vec<_>>>()?;
+
+ let mut methods = self.conn.prepare(
+ "SELECT kind, label, value FROM contact_methods
+ WHERE contact_guid = ?1 ORDER BY position",
+ )?;
+ for contact in &mut contacts {
+ let rows = methods.query_map(params![contact.guid], |row| {
+ Ok(ContactMethod {
+ kind: row.get(0)?,
+ label: row.get(1)?,
+ value: row.get(2)?,
+ })
+ })?;
+ contact.methods = rows.collect::<rusqlite::Result<Vec<_>>>()?;
+ }
+ Ok(contacts)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn contact(guid: &str, first: Option<&str>, last: Option<&str>) -> Contact {
+ Contact {
+ guid: guid.into(),
+ first_name: first.map(ToString::to_string),
+ last_name: last.map(ToString::to_string),
+ company: None,
+ is_company: false,
+ birthday: None,
+ notes: None,
+ etag: None,
+ methods: vec![ContactMethod {
+ kind: "phone".into(),
+ label: Some("mobile".into()),
+ value: format!("+91{guid}"),
+ }],
+ }
+ }
+
+ #[test]
+ fn contacts_sort_by_last_name_the_way_apple_does() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[
+ contact("1", Some("Aarav"), Some("Zutshi")),
+ contact("2", Some("Zoya"), Some("Ahuja")),
+ ])
+ .unwrap();
+ let names: Vec<String> = lib
+ .contacts(None)
+ .unwrap()
+ .iter()
+ .map(Contact::display_name)
+ .collect();
+ assert_eq!(names, vec!["Zoya Ahuja", "Aarav Zutshi"]);
+ }
+
+ /// A contact with only a phone number still needs something to show.
+ #[test]
+ fn a_nameless_contact_falls_back_to_its_first_method() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[contact("9", None, None)]).unwrap();
+ assert_eq!(lib.contacts(None).unwrap()[0].display_name(), "+919");
+ }
+
+ #[test]
+ fn searching_matches_a_phone_number_as_well_as_a_name() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[
+ contact("555", Some("Meera"), Some("Iyer")),
+ contact("777", Some("Rahul"), Some("Nair")),
+ ])
+ .unwrap();
+ assert_eq!(lib.contacts(Some("meera")).unwrap().len(), 1);
+ assert_eq!(
+ lib.contacts(Some("+91777")).unwrap()[0].display_name(),
+ "Rahul Nair"
+ );
+ assert_eq!(
+ lib.contacts(Some(" ")).unwrap().len(),
+ 2,
+ "a blank search is no filter"
+ );
+ }
+
+ /// A number removed on the phone must not linger here.
+ #[test]
+ fn methods_are_replaced_not_accumulated() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[contact("1", Some("Ada"), Some("Lovelace"))])
+ .unwrap();
+
+ let mut changed = contact("1", Some("Ada"), Some("Lovelace"));
+ changed.methods = vec![ContactMethod {
+ kind: "email".into(),
+ label: None,
+ value: "[email protected]".into(),
+ }];
+ lib.put_contacts(&[changed]).unwrap();
+
+ let stored = &lib.contacts(None).unwrap()[0];
+ assert_eq!(stored.methods.len(), 1);
+ assert_eq!(stored.methods[0].kind, "email");
+ }
+
+ #[test]
+ fn contacts_apple_stops_reporting_are_removed() {
+ let mut lib = Library::in_memory().unwrap();
+ lib.put_contacts(&[contact("1", Some("A"), None), contact("2", Some("B"), None)])
+ .unwrap();
+ lib.put_contacts(&[contact("1", Some("A"), None)]).unwrap();
+ assert_eq!(lib.contacts(None).unwrap().len(), 1);
+ }
+}
diff --git a/crates/quince-core/src/lib.rs b/crates/quince-core/src/lib.rs
index 8e6b0fd..eed20a4 100644
--- a/crates/quince-core/src/lib.rs
+++ b/crates/quince-core/src/lib.rs
@@ -5,6 +5,7 @@
//! it. That is the whole reason the app can be instant and work offline.
pub mod calendar;
+pub mod contacts;
pub mod notes;
pub mod reminders;
pub mod schema;
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index c28b1c5..d0281ee 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -115,4 +115,33 @@ pub const MIGRATIONS: &[&str] = &[
CREATE INDEX notes_by_folder ON notes (folder_guid, pinned DESC, modified_at DESC);
CREATE INDEX notes_by_modified ON notes (modified_at DESC);
"#,
+ // 5 — contacts, with their phone numbers and addresses normalised alongside.
+ r#"
+ CREATE TABLE contacts (
+ guid TEXT PRIMARY KEY,
+ first_name TEXT,
+ last_name TEXT,
+ company TEXT,
+ is_company INTEGER NOT NULL DEFAULT 0,
+ -- What to sort and search on, so neither depends on which name fields exist.
+ sort_name TEXT NOT NULL,
+ birthday TEXT,
+ notes TEXT,
+ etag TEXT,
+ updated_at INTEGER NOT NULL
+ ) STRICT;
+
+ CREATE INDEX contacts_by_name ON contacts (sort_name);
+
+ -- Phones, emails and the rest share a shape, so they share a table.
+ CREATE TABLE contact_methods (
+ contact_guid TEXT NOT NULL REFERENCES contacts(guid) ON DELETE CASCADE,
+ kind TEXT NOT NULL,
+ label TEXT,
+ value TEXT NOT NULL,
+ position INTEGER NOT NULL DEFAULT 0
+ ) STRICT;
+
+ CREATE INDEX contact_methods_by_contact ON contact_methods (contact_guid, kind, position);
+ "#,
];
diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rs
new file mode 100644
index 0000000..3458d0d
--- /dev/null
+++ b/crates/quince-icloud/src/contacts.rs
@@ -0,0 +1,160 @@
+//! Apple's contacts web service.
+//!
+//! Unlike reminders, this account's contacts still come from the legacy endpoint rather than
+//! CloudKit, so `/co/startup` is the whole of it.
+
+use crate::{Error, Result};
+use quince_core::contacts::{Contact, ContactMethod};
+use serde_json::Value;
+
+fn string(v: &Value, key: &str) -> Option<String> {
+ v.get(key)
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(ToString::to_string)
+}
+
+/// Read one of Apple's method arrays — phones, emails and the rest share a shape.
+///
+/// Apple names the value `field`, with an optional `label`. Entries with no value are
+/// skipped rather than stored as blanks.
+fn methods_from(v: &Value, key: &str, kind: &str) -> Vec<ContactMethod> {
+ v.get(key)
+ .and_then(Value::as_array)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(|entry| {
+ Some(ContactMethod {
+ kind: kind.to_string(),
+ label: string(entry, "label"),
+ value: string(entry, "field")?,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn contact_from(v: &Value) -> Option<Contact> {
+ let guid = string(v, "contactId")?;
+ let mut methods = methods_from(v, "phones", "phone");
+ methods.extend(methods_from(v, "emailAddresses", "email"));
+ methods.extend(methods_from(v, "urls", "url"));
+
+ Some(Contact {
+ guid,
+ first_name: string(v, "firstName"),
+ last_name: string(v, "lastName"),
+ company: string(v, "companyName"),
+ is_company: v.get("isCompany").and_then(Value::as_bool).unwrap_or(false),
+ birthday: string(v, "birthday"),
+ notes: string(v, "notes"),
+ etag: string(v, "etag"),
+ methods,
+ })
+}
+
+#[must_use]
+pub fn parse(body: &Value) -> Vec<Contact> {
+ body.get("contacts")
+ .and_then(Value::as_array)
+ .map(|arr| arr.iter().filter_map(contact_from).collect())
+ .unwrap_or_default()
+}
+
+/// Fetch the address book and reconcile it into the library.
+pub async fn sync(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ library: &mut quince_core::Library,
+) -> Result<usize> {
+ let mut query = params;
+ query.push(("clientVersion".into(), "2.1".into()));
+ query.push(("locale".into(), "en_US".into()));
+ query.push(("order".into(), "last,first".into()));
+
+ let url = format!("{}/co/startup", root.trim_end_matches('/'));
+ let response = http.get(url).query(&query).send().await?;
+ let status = response.status();
+ let text = response.text().await.unwrap_or_default();
+
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ return Err(Error::Protocol(format!(
+ "/co/startup returned {status}: {}",
+ text.chars().take(160).collect::<String>()
+ )));
+ }
+
+ let body: Value = serde_json::from_str(&text)
+ .map_err(|e| Error::Protocol(format!("/co/startup returned invalid JSON: {e}")))?;
+ let contacts = parse(&body);
+ library.put_contacts(&contacts)?;
+ library.mark_synced("contacts", None)?;
+ Ok(contacts.len())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_contact_is_read_with_its_methods() {
+ let contacts = parse(&json!({ "contacts": [{
+ "contactId": "abc",
+ "firstName": "Meera",
+ "lastName": "Iyer",
+ "phones": [{ "field": "+919000000001", "label": "MOBILE" }],
+ "emailAddresses": [{ "field": "[email protected]" }],
+ "etag": "e1"
+ }]}));
+ assert_eq!(contacts.len(), 1);
+ let c = &contacts[0];
+ assert_eq!(c.display_name(), "Meera Iyer");
+ assert_eq!(c.methods.len(), 2);
+ assert_eq!(c.methods[0].kind, "phone");
+ assert_eq!(c.methods[0].label.as_deref(), Some("MOBILE"));
+ assert_eq!(c.methods[1].kind, "email");
+ }
+
+ /// Most fields are optional — this account has contacts with only a first name and a
+ /// number — so absence must not lose the record.
+ #[test]
+ fn a_contact_with_almost_nothing_still_parses() {
+ let contacts = parse(&json!({ "contacts": [{
+ "contactId": "abc",
+ "firstName": "Amma",
+ "phones": [{ "field": "+919000000001" }]
+ }]}));
+ assert_eq!(contacts[0].display_name(), "Amma");
+ assert!(contacts[0].last_name.is_none());
+ assert!(contacts[0].methods[0].label.is_none());
+ }
+
+ #[test]
+ fn a_contact_without_an_id_is_skipped() {
+ assert!(parse(&json!({ "contacts": [{ "firstName": "Nobody" }] })).is_empty());
+ }
+
+ /// Blank values must not become empty rows in the detail view.
+ #[test]
+ fn blank_values_are_dropped() {
+ let contacts = parse(&json!({ "contacts": [{
+ "contactId": "abc", "firstName": " ", "lastName": "Iyer",
+ "phones": [{ "field": "" }, { "field": "+9111" }]
+ }]}));
+ assert!(contacts[0].first_name.is_none());
+ assert_eq!(contacts[0].methods.len(), 1);
+ }
+
+ #[test]
+ fn an_empty_body_is_an_empty_address_book() {
+ assert!(parse(&json!({})).is_empty());
+ }
+}
diff --git a/crates/quince-icloud/src/lib.rs b/crates/quince-icloud/src/lib.rs
index b1a8a3e..8ddff63 100644
--- a/crates/quince-icloud/src/lib.rs
+++ b/crates/quince-icloud/src/lib.rs
@@ -6,6 +6,7 @@
pub mod calendar;
pub mod ckdocument;
pub mod cloudkit;
+pub mod contacts;
pub mod notes;
pub mod reminders;
pub mod sync;
diff --git a/probe/src/main.rs b/probe/src/main.rs
index 101217d..0ff9757 100644
--- a/probe/src/main.rs
+++ b/probe/src/main.rs
@@ -708,6 +708,62 @@ async fn main() -> Result<()> {
}
}
+ // ---- what a contact record looks like ---------------------------------------
+ println!("\n\x1b[1m── Contacts: shape ──\x1b[0m");
+ if let Some(root) = session.service_url("contacts") {
+ let mut q = client.service_params();
+ q.push(("clientVersion".into(), "2.1".into()));
+ q.push(("locale".into(), "en_US".into()));
+ q.push(("order".into(), "last,first".into()));
+ if let Ok(r) = client
+ .http()
+ .get(format!("{}/co/startup", root.trim_end_matches('/')))
+ .query(&q)
+ .send()
+ .await
+ {
+ let status = r.status();
+ let text = r.text().await.unwrap_or_default();
+ let v: serde_json::Value =
+ serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
+ let contacts = v.get("contacts").and_then(|c| c.as_array());
+ println!(" {status}: {} contact(s)", contacts.map_or(0, Vec::len));
+ if let Some(first) = contacts.and_then(|c| c.first()) {
+ if let Some(obj) = first.as_object() {
+ let mut keys: Vec<String> = obj
+ .iter()
+ .map(|(k, val)| {
+ let kind = match val {
+ serde_json::Value::Array(a) => format!("array[{}]", a.len()),
+ serde_json::Value::String(_) => "string".into(),
+ serde_json::Value::Bool(_) => "bool".into(),
+ serde_json::Value::Number(_) => "number".into(),
+ serde_json::Value::Object(_) => "object".into(),
+ serde_json::Value::Null => "null".into(),
+ };
+ format!("{k}:{kind}")
+ })
+ .collect();
+ keys.sort();
+ println!(" fields: {}", keys.join(", "));
+ }
+ // Show the shape of the nested arrays, which is where phones and emails live.
+ for key in ["phones", "emailAddresses", "urls", "streetAddresses"] {
+ if let Some(entry) = first
+ .get(key)
+ .and_then(|a| a.as_array())
+ .and_then(|a| a.first())
+ {
+ println!(
+ " {key}[0]: {}",
+ serde_json::to_string(entry).unwrap_or_default()
+ );
+ }
+ }
+ }
+ }
+ }
+
// ---- CloudKit containers ----------------------------------------------------
// Apple's legacy /rd and /ca endpoints answer with a placeholder once data has been
// upgraded to the modern format. The real records live in CloudKit, so find out which
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index b022178..e791e45 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -3,6 +3,7 @@
use quince_auth::{Client, SignInOutcome, TwoFactorOptions};
use quince_core::calendar::{Calendar, Event};
+use quince_core::contacts::Contact;
use quince_core::notes::{Note, NoteFolder};
use quince_core::reminders::{Reminder, ReminderList};
use quince_core::Library;
@@ -413,6 +414,38 @@ async fn notes_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
library.last_synced("notes").map_err(|e| e.to_string())
}
+/// Refresh the address book. Contacts still come from the legacy endpoint, not CloudKit.
+#[tauri::command]
+async fn contacts_sync(auth: State<'_, Auth>, data: State<'_, Data>) -> UiResult<usize> {
+ let (http, root, params) = {
+ let client = auth.client.lock().await;
+ let root = client
+ .session()
+ .service_url("contacts")
+ .ok_or("Apple hasn't offered a contacts service for this account.")?;
+ (client.http().clone(), root, client.service_params())
+ };
+ let mut library = data.0.lock().await;
+ quince_icloud::contacts::sync(&http, &root, params, &mut library)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// The address book, optionally filtered by name or by any stored number or address.
+#[tauri::command]
+async fn contacts_list(search: Option<String>, data: State<'_, Data>) -> UiResult<Vec<Contact>> {
+ let library = data.0.lock().await;
+ library
+ .contacts(search.as_deref())
+ .map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+async fn contacts_last_synced(data: State<'_, Data>) -> UiResult<Option<i64>> {
+ let library = data.0.lock().await;
+ library.last_synced("contacts").map_err(|e| e.to_string())
+}
+
fn main() {
tauri::Builder::default()
.setup(|app| {
@@ -454,6 +487,9 @@ fn main() {
note_folders,
notes_in,
notes_last_synced,
+ contacts_sync,
+ contacts_list,
+ contacts_last_synced,
reminder_set_done,
])
.run(tauri::generate_context!())
diff --git a/src/App.tsx b/src/App.tsx
index 72c1594..c622d92 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -10,6 +10,7 @@ type Phase = "checking" | "signin" | "code" | "library";
const BACKGROUND_SYNCS = [
{ lastSynced: api.remindersLastSynced, sync: api.remindersSync },
{ lastSynced: api.notesLastSynced, sync: api.notesSync },
+ { lastSynced: api.contactsLastSynced, sync: api.contactsSync },
];
export default function App() {
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 3c35071..0fcce56 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -49,6 +49,10 @@ export const api = {
noteFolders: () => invoke<NoteFolder[]>("note_folders"),
notesIn: (folderGuid: string | null) => invoke<Note[]>("notes_in", { folderGuid }),
notesLastSynced: () => invoke<number | null>("notes_last_synced"),
+
+ contactsSync: () => invoke<number>("contacts_sync"),
+ contactsList: (search: string | null) => invoke<Contact[]>("contacts_list", { search }),
+ contactsLastSynced: () => invoke<number | null>("contacts_last_synced"),
};
/** Tauri rejects with a plain string from our commands; keep it readable either way. */
@@ -115,6 +119,28 @@ export type Note = {
etag: string | null;
};
+export type ContactMethod = { kind: string; label: string | null; value: string };
+
+export type Contact = {
+ guid: string;
+ firstName: string | null;
+ lastName: string | null;
+ company: string | null;
+ isCompany: boolean;
+ birthday: string | null;
+ notes: string | null;
+ etag: string | null;
+ methods: ContactMethod[];
+};
+
+/** What to show, whichever name fields a contact happens to have. */
+export function displayName(c: Contact): string {
+ const full = [c.firstName, c.lastName].filter(Boolean).join(" ").trim();
+ if (full) return full;
+ if (c.company?.trim()) return c.company;
+ return c.methods[0]?.value ?? "No Name";
+}
+
export function messageOf(e: unknown): string {
if (typeof e === "string") return e;
if (e instanceof Error) return e.message;
diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsx
new file mode 100644
index 0000000..94df938
--- /dev/null
+++ b/src/screens/ContactsView.tsx
@@ -0,0 +1,182 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { api, displayName, messageOf, type Contact } from "../lib/ipc";
+
+const KIND_LABEL: Record<string, string> = {
+ phone: "phone",
+ email: "email",
+ url: "link",
+ address: "address",
+};
+
+/** Initials for the avatar, from whichever name fields exist. */
+function initials(contact: Contact): string {
+ const name = displayName(contact).trim();
+ const parts = name.split(/\s+/).filter(Boolean);
+ if (parts.length === 0) return "?";
+ // A number-only contact has no useful initial, so show a glyph instead of a digit.
+ if (/^[+\d]/.test(parts[0])) return "#";
+ return parts
+ .slice(0, 2)
+ .map((p) => [...p][0]?.toUpperCase() ?? "")
+ .join("");
+}
+
+function relative(seconds: number | null): string {
+ if (seconds === null) return "never";
+ const ago = Math.max(0, Math.floor(Date.now() / 1000) - seconds);
+ if (ago < 60) return "just now";
+ if (ago < 3600) return `${Math.floor(ago / 60)} min ago`;
+ if (ago < 86_400) return `${Math.floor(ago / 3600)} h ago`;
+ return `${Math.floor(ago / 86_400)} d ago`;
+}
+
+export function ContactsView() {
+ const [contacts, setContacts] = useState<Contact[]>([]);
+ const [search, setSearch] = useState("");
+ const [openGuid, setOpenGuid] = useState<string | null>(null);
+ const [lastSynced, setLastSynced] = useState<number | null>(null);
+ const [syncing, setSyncing] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const read = useCallback(async (query: string) => {
+ const [found, synced] = await Promise.all([
+ api.contactsList(query.trim() || null),
+ api.contactsLastSynced(),
+ ]);
+ setContacts(Array.isArray(found) ? found : []);
+ setLastSynced(typeof synced === "number" ? synced : null);
+ setLoaded(true);
+ }, []);
+
+ const refreshRef = useRef<null | (() => Promise<void>)>(null);
+
+ const refresh = useCallback(async () => {
+ setSyncing(true);
+ setError(null);
+ try {
+ await api.contactsSync();
+ await read(search);
+ } catch (e) {
+ setError(messageOf(e));
+ } finally {
+ setSyncing(false);
+ }
+ }, [read, search]);
+ refreshRef.current = refresh;
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ await read(search);
+ if (cancelled) return;
+ if ((await api.contactsLastSynced()) === null) void refreshRef.current?.();
+ } catch (e) {
+ if (!cancelled) {
+ setError(messageOf(e));
+ setLoaded(true);
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // Re-reading on every keystroke is the point: the filter runs in SQLite.
+ }, [read, search]);
+
+ useEffect(() => {
+ if (contacts.length === 0) return setOpenGuid(null);
+ setOpenGuid((current) =>
+ current && contacts.some((c) => c.guid === current) ? current : contacts[0].guid
+ );
+ }, [contacts]);
+
+ const open = useMemo(
+ () => contacts.find((c) => c.guid === openGuid) ?? null,
+ [contacts, openGuid]
+ );
+
+ return (
+ <div className="contacts">
+ <section className="contacts-list" aria-label="Contacts">
+ <header className="cal-bar">
+ <div className="cal-nav">
+ <h1>Contacts</h1>
+ <span className="badge">{contacts.length}</span>
+ </div>
+ <div className="cal-actions">
+ <span className="badge">{relative(lastSynced)}</span>
+ <button className="quiet" onClick={refresh} disabled={syncing}>
+ {syncing ? "Refreshing…" : "Refresh"}
+ </button>
+ </div>
+ </header>
+
+ <input
+ className="contacts-search"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="Search"
+ aria-label="Search contacts"
+ type="search"
+ />
+
+ {error && <p className="error" role="alert">{error}</p>}
+
+ <ul className="contact-rows">
+ {contacts.map((contact) => (
+ <li key={contact.guid}>
+ <button
+ className="contact-row"
+ aria-current={openGuid === contact.guid}
+ onClick={() => setOpenGuid(contact.guid)}
+ >
+ <span className="avatar" aria-hidden="true">{initials(contact)}</span>
+ <span className="contact-row-name">{displayName(contact)}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+
+ {loaded && contacts.length === 0 && !error && (
+ <p className="cal-empty">{search ? "No matches." : "No contacts yet."}</p>
+ )}
+ </section>
+
+ <article className="contact-detail" aria-label="Contact">
+ {open ? (
+ <>
+ <span className="avatar large" aria-hidden="true">{initials(open)}</span>
+ <h2>{displayName(open)}</h2>
+ {open.company && !open.isCompany && <p className="contact-company">{open.company}</p>}
+
+ <dl className="contact-methods">
+ {open.methods.map((m, i) => (
+ <div key={`${m.kind}-${i}`}>
+ <dt>{m.label?.toLowerCase() || KIND_LABEL[m.kind] || m.kind}</dt>
+ <dd>
+ {m.kind === "email" ? (
+ <a href={`mailto:${m.value}`}>{m.value}</a>
+ ) : m.kind === "phone" ? (
+ <a href={`tel:${m.value}`}>{m.value}</a>
+ ) : (
+ m.value
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+
+ {open.methods.length === 0 && (
+ <p className="cal-empty">No phone numbers or addresses saved.</p>
+ )}
+ {open.notes && <p className="contact-notes">{open.notes}</p>}
+ </>
+ ) : (
+ loaded && <p className="cal-empty">Select a contact.</p>
+ )}
+ </article>
+ </div>
+ );
+}
diff --git a/src/screens/Library.tsx b/src/screens/Library.tsx
index c579647..07d1c42 100644
--- a/src/screens/Library.tsx
+++ b/src/screens/Library.tsx
@@ -3,6 +3,7 @@ import { api, messageOf } from "../lib/ipc";
import { CalendarView } from "./CalendarView";
import { RemindersView } from "./RemindersView";
import { NotesView } from "./NotesView";
+import { ContactsView } from "./ContactsView";
const NAMES: Record<string, string> = {
photos: "Photos",
@@ -42,7 +43,7 @@ const NAMES: Record<string, string> = {
/** Services with a real screen behind them. Opening on one of these beats opening on a
* placeholder, so selection prefers them. */
-const BUILT = new Set(["calendar", "reminders", "notes"]);
+const BUILT = new Set(["calendar", "reminders", "notes", "contacts"]);
/** What a person actually came for, in the order they'd look for it. */
const PRIMARY = [
@@ -156,6 +157,8 @@ export function Library({ onSignOut }: { onSignOut: () => void }) {
<RemindersView />
) : selected === "notes" ? (
<NotesView />
+ ) : selected === "contacts" ? (
+ <ContactsView />
) : (
<>
<div className="toolbar">
diff --git a/src/styles/app.css b/src/styles/app.css
index 7e054df..9c8ad99 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -797,3 +797,107 @@
.notes-folder-picker select:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: 1px; }
.content:has(.notes) { display: flex; flex-direction: column; overflow: hidden; }
+
+/* ---- contacts -------------------------------------------------------------------
+ Apple Contacts: a searchable list, then the person. */
+
+.contacts {
+ display: grid;
+ grid-template-columns: minmax(230px, 300px) minmax(0, 1fr);
+ height: 100%;
+ min-height: 0;
+}
+
+.contacts-list {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ min-width: 0;
+ border-right: 1px solid var(--separator);
+ padding: 0 14px 0 0;
+}
+
+.contacts-list .cal-bar { flex-direction: column; align-items: flex-start; gap: 4px; margin-bottom: 8px; }
+.contacts-list .cal-nav h1 { font-size: var(--t-17); }
+
+.contacts-search {
+ width: 100%;
+ font: inherit;
+ font-size: var(--t-13);
+ color: var(--text);
+ background: var(--field);
+ border: 1px solid var(--field-edge);
+ border-radius: var(--r-field);
+ padding: 5px 9px;
+ margin-bottom: 8px;
+ outline: none;
+}
+
+.contacts-search:focus { border-color: var(--gold); box-shadow: 0 0 0 3px var(--gold-ring); }
+.contacts-search::placeholder { color: var(--text-3); }
+
+.contact-rows { list-style: none; margin: 0; padding: 0; overflow-y: auto; min-height: 0; }
+
+.contact-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ border: 0;
+ background: none;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ text-align: left;
+ padding: 6px 9px;
+ border-radius: var(--r-field);
+ cursor: pointer;
+}
+
+.contact-row:hover { background: color-mix(in srgb, var(--text) 5%, transparent); }
+.contact-row[aria-current="true"] { background: var(--gold-tint); }
+.contact-row:focus-visible { outline: 3px solid var(--gold-ring); outline-offset: -1px; }
+.contact-row-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+.avatar {
+ width: 26px;
+ height: 26px;
+ border-radius: var(--r-pill);
+ background: color-mix(in srgb, var(--text) 12%, transparent);
+ color: var(--text-2);
+ font-size: var(--t-11);
+ font-weight: 600;
+ display: grid;
+ place-items: center;
+ flex: none;
+}
+
+.avatar.large {
+ width: 68px;
+ height: 68px;
+ font-size: var(--t-22);
+ margin-bottom: 12px;
+}
+
+.contact-detail { overflow-y: auto; min-height: 0; padding: 4px 32px 40px; }
+.contact-detail h2 { margin: 0 0 2px; font-size: var(--t-22); font-weight: 600; letter-spacing: -0.021em; }
+.contact-company { margin: 0 0 18px; color: var(--text-2); font-size: var(--t-13); }
+
+.contact-methods { margin: 18px 0 0; max-width: 46ch; }
+
+.contact-methods > div {
+ display: grid;
+ grid-template-columns: 92px 1fr;
+ gap: 12px;
+ padding: 8px 0;
+ border-top: 1px solid var(--separator);
+}
+
+.contact-methods dt { color: var(--text-2); font-size: var(--t-11); padding-top: 2px; }
+.contact-methods dd { margin: 0; font-size: var(--t-15); overflow-wrap: anywhere; }
+.contact-methods a { color: var(--gold); text-decoration: none; }
+.contact-methods a:hover { text-decoration: underline; }
+
+.contact-notes { margin-top: 20px; max-width: 60ch; color: var(--text-2); white-space: pre-wrap; }
+
+.content:has(.contacts) { display: flex; flex-direction: column; overflow: hidden; }