Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Contacts show the addresses, profiles and middle names they always had
Yashwanth Kamireddied92ef7d176f
diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rsindex 5bc55d1..f7ce16b 100644--- a/crates/quince-core/src/contacts.rs+++ b/crates/quince-core/src/contacts.rs@@ -18,6 +18,9 @@ pub struct ContactMethod {pub struct Contact {pub guid: String,pub first_name: Option<String>,+ /// Apple keeps one, and four people in a real address book have one.+ #[serde(default)]+ pub middle_name: Option<String>,pub last_name: Option<String>,pub company: Option<String>,pub is_company: bool,@@ -35,11 +38,15 @@ impl Contact {/// 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(" ");+ let full = [+ self.first_name.as_deref(),+ self.middle_name.as_deref(),+ self.last_name.as_deref(),+ ]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>()+ .join(" ");if !full.trim().is_empty() {return full;}@@ -79,11 +86,12 @@ impl Library {let tx = self.conn.transaction()?;{let mut upsert = tx.prepare(- "INSERT INTO contacts (guid, first_name, last_name, company, is_company,+ "INSERT INTO contacts (guid, first_name, middle_name, last_name, company, is_company,sort_name, birthday, notes, etag, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)ON CONFLICT(guid) DO UPDATE SET- first_name = excluded.first_name, last_name = excluded.last_name,+ first_name = excluded.first_name, middle_name = excluded.middle_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,@@ -100,6 +108,7 @@ impl Library {upsert.execute(params![c.guid,c.first_name,+ c.middle_name,c.last_name,c.company,i64::from(c.is_company),@@ -149,11 +158,12 @@ impl Library {.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,+ "SELECT c.guid, c.first_name, c.middle_name, c.last_name, c.company, c.is_company,c.birthday, c.notes, c.etagFROM contacts cWHERE ?1 IS NULL- OR lower(coalesce(c.first_name, '') || ' ' || coalesce(c.last_name, '')+ OR lower(coalesce(c.first_name, '') || ' ' || coalesce(c.middle_name, '')+ || ' ' || coalesce(c.last_name, '')|| ' ' || coalesce(c.company, '')) LIKE ?1OR EXISTS (SELECT 1 FROM contact_methods mWHERE m.contact_guid = c.guid AND lower(m.value) LIKE ?1)@@ -163,12 +173,13 @@ impl Library {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)?,+ middle_name: row.get(2)?,+ last_name: row.get(3)?,+ company: row.get(4)?,+ is_company: row.get::<_, i64>(5)? != 0,+ birthday: row.get(6)?,+ notes: row.get(7)?,+ etag: row.get(8)?,methods: Vec::new(),})})?;@@ -200,6 +211,7 @@ mod tests {Contact {guid: guid.into(),first_name: first.map(ToString::to_string),+ middle_name: None,last_name: last.map(ToString::to_string),company: None,is_company: false,diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rsindex 8d327bf..cd8bb1e 100644--- a/crates/quince-core/src/schema.rs+++ b/crates/quince-core/src/schema.rs@@ -206,4 +206,11 @@ pub const MIGRATIONS: &[&str] = &[ALTER TABLE reminders ADD COLUMN parent_guid TEXT;CREATE INDEX reminders_by_parent ON reminders (parent_guid);"#,+ // 12 — a contact's middle name.+ //+ // Apple keeps one and four people in a real address book have one; without it they were+ // shown under a name that was not quite theirs.+ r#"+ ALTER TABLE contacts ADD COLUMN middle_name TEXT;+ "#,];diff --git a/crates/quince-icloud/src/contacts.rs b/crates/quince-icloud/src/contacts.rsindex bd4e7d1..c6edaf0 100644--- a/crates/quince-icloud/src/contacts.rs+++ b/crates/quince-icloud/src/contacts.rs@@ -37,15 +37,86 @@ fn methods_from(v: &Value, key: &str, kind: &str) -> Vec<ContactMethod> {.unwrap_or_default()}+/// Apple's postal address: a structured object, not a string.+///+/// Flattened into the lines a person would write on an envelope, in the order they would+/// write them. Reading it as a string — which is what every other method array holds —+/// simply skipped it, so the one contact with an address showed none.+fn address_from(entry: &Value) -> Option<String> {+ let field = entry.get("field")?;+ if let Some(text) = field.as_str() {+ return Some(text.trim().to_string()).filter(|s| !s.is_empty());+ }++ let part = |key: &str| string(field, key);+ let mut lines: Vec<String> = Vec::new();+ if let Some(street) = part("street") {+ lines.extend(street.lines().map(str::trim).map(ToString::to_string));+ }+ // City, state and postcode share a line, as they do on an envelope.+ let locality: Vec<String> = ["city", "state", "postalCode"]+ .iter()+ .filter_map(|k| part(k))+ .collect();+ if !locality.is_empty() {+ lines.push(locality.join(" "));+ }+ if let Some(country) = part("country") {+ lines.push(country);+ }++ (!lines.is_empty()).then(|| lines.join("\n"))+}+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"));+ // A postal address nests its parts rather than holding a string.+ methods.extend(+ v.get("streetAddresses")+ .and_then(Value::as_array)+ .map(|entries| {+ entries+ .iter()+ .filter_map(|entry| {+ Some(ContactMethod {+ kind: "address".into(),+ label: string(entry, "label"),+ value: address_from(entry)?,+ })+ })+ .collect::<Vec<_>>()+ })+ .unwrap_or_default(),+ );++ // A profile carries both an encoded handle and the readable one a person typed. The+ // readable one is the point; `x-apple:%2B91%2090000` is not an answer to "who is this".+ methods.extend(+ v.get("profiles")+ .and_then(Value::as_array)+ .map(|entries| {+ entries+ .iter()+ .filter_map(|entry| {+ Some(ContactMethod {+ kind: "profile".into(),+ label: string(entry, "label"),+ value: string(entry, "user").or_else(|| string(entry, "field"))?,+ })+ })+ .collect::<Vec<_>>()+ })+ .unwrap_or_default(),+ );+Some(Contact {guid,first_name: string(v, "firstName"),+ middle_name: string(v, "middleName"),last_name: string(v, "lastName"),company: string(v, "companyName"),is_company: v.get("isCompany").and_then(Value::as_bool).unwrap_or(false),@@ -429,6 +500,7 @@ mod write_tests {Contact {guid: "C1".into(),first_name: Some("Ada".into()),+ middle_name: None,last_name: Some("Lovelace".into()),company: None,is_company: false,@@ -657,3 +729,106 @@ mod write_tests {assert!(matches!(err, Error::Conflict), "got {err:?}");}}++#[cfg(test)]+mod shape_tests {+ use super::*;+ use serde_json::json;++ /// A postal address nests its parts rather than holding a string, so reading it the way+ /// every other method array is read skipped it entirely — the one contact with an+ /// address showed none.+ #[test]+ fn a_postal_address_reads_as_the_lines_it_would_be_written_on() {+ let contacts = parse(&json!({+ "contacts": [{+ "contactId": "C1",+ "firstName": "Asha",+ "streetAddresses": [{+ "label": "HOME",+ "field": {+ "street": "12 Example Street\nSpringfield",+ "city": "Springfield",+ "state": "ST",+ "postalCode": "123456",+ "country": "India"+ }+ }]+ }]+ }));+ let address = contacts[0]+ .methods+ .iter()+ .find(|m| m.kind == "address")+ .expect("the address is read");+ assert_eq!(+ address.value,+ "12 Example Street\nSpringfield\nSpringfield ST 123456\nIndia"+ );+ assert_eq!(address.label.as_deref(), Some("HOME"));+ }++ /// Town, county and postcode belong on one line; a missing part must not leave a gap.+ #[test]+ fn a_partial_address_leaves_no_holes() {+ let contacts = parse(&json!({+ "contacts": [{+ "contactId": "C1",+ "streetAddresses": [{ "field": { "city": "Springfield", "country": "India" } }]+ }]+ }));+ assert_eq!(contacts[0].methods[0].value, "Springfield\nIndia");+ }++ /// A profile carries an encoded handle and the readable one a person typed. Showing+ /// `x-apple:%2B91...` answers nothing.+ #[test]+ fn a_profile_shows_what_a_person_typed_not_the_encoding() {+ let contacts = parse(&json!({+ "contacts": [{+ "contactId": "C1",+ "profiles": [{+ "field": "x-apple:+91%2090000%2000003",+ "user": "+91 90000 00003"+ }]+ }]+ }));+ assert_eq!(contacts[0].methods[0].kind, "profile");+ assert_eq!(contacts[0].methods[0].value, "+91 90000 00003");+ }++ /// Apple keeps a middle name, and a person with one is not shown under a name that is+ /// only nearly theirs.+ #[test]+ fn a_middle_name_is_part_of_the_name() {+ let contacts = parse(&json!({+ "contacts": [{+ "contactId": "C1",+ "firstName": "Asha",+ "middleName": "Devi",+ "lastName": "Rao"+ }]+ }));+ assert_eq!(contacts[0].display_name(), "Asha Devi Rao");+ }++ /// An address that really is a plain string still reads.+ #[test]+ fn an_address_given_as_a_string_still_reads() {+ let contacts = parse(&json!({+ "contacts": [{+ "contactId": "C1",+ "streetAddresses": [{ "field": "12 Somewhere Lane" }]+ }]+ }));+ assert_eq!(contacts[0].methods[0].value, "12 Somewhere Lane");+ }++ #[test]+ fn an_empty_address_is_left_out_rather_than_shown_blank() {+ let contacts = parse(&json!({+ "contacts": [{ "contactId": "C1", "streetAddresses": [{ "field": {} }] }]+ }));+ assert!(contacts[0].methods.is_empty());+ }+}diff --git a/probe/src/main.rs b/probe/src/main.rsindex 3f1abff..dfed185 100644--- a/probe/src/main.rs+++ b/probe/src/main.rs@@ -1754,6 +1754,7 @@ async fn main() -> Result<()> {let draft = quince_core::contacts::Contact {guid: String::new(),first_name: Some("Quince".into()),+ middle_name: None,last_name: Some("Write Test".into()),company: None,is_company: false,diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex d5916ee..8df8fd8 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -233,6 +233,7 @@ export type ContactMethod = { kind: string; label: string | null; value: stringexport type Contact = {guid: string;firstName: string | null;+ middleName: string | null;lastName: string | null;company: string | null;isCompany: boolean;@@ -244,7 +245,7 @@ export type Contact = {/** 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();+ const full = [c.firstName, c.middleName, c.lastName].filter(Boolean).join(" ").trim();if (full) return full;if (c.company?.trim()) return c.company;return c.methods[0]?.value ?? "No Name";diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex dca3e2a..96d9886 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -19,6 +19,7 @@ const KINDS = [const blank = (): Contact => ({guid: "",firstName: null,+ middleName: null,lastName: null,company: null,isCompany: false,@@ -33,8 +34,14 @@ const KIND_LABEL: Record<string, string> = {email: "email",url: "link",address: "address",+ profile: "profile",};+/** What this app can safely write back. Apple stores an address as a structured thing and a+ * profile as an encoded handle; editing either as one line here would mangle it, so they+ * are shown and left alone rather than half-supported. */+const EDITABLE_KINDS = new Set(["phone", "email", "url"]);+/** Initials for the avatar, from whichever name fields exist. */function initials(contact: Contact): string {const name = displayName(contact).trim();@@ -227,7 +234,16 @@ export function ContactsView() {</div><ul className="contact-method-rows">- {draft.methods.map((m, index) => (+ {draft.methods.map((m, index) =>+ !EDITABLE_KINDS.has(m.kind) ? (+ // Shown so it is not a surprise that it exists, but not offered for+ // editing — this app cannot write a structured address back safely.+ <li key={index} className="contact-method-fixed">+ <span>{KIND_LABEL[m.kind] ?? m.kind}</span>+ <span className="contact-address">{m.value}</span>+ <span className="badge">edited on an Apple device</span>+ </li>+ ) : (<li key={index}><Pickerlabel={`Kind of detail ${index + 1}`}@@ -264,7 +280,8 @@ export function ContactsView() {✕</button></li>- ))}+ ),+ )}</ul><button@@ -328,6 +345,9 @@ export function ContactsView() {<a href={`mailto:${m.value}`}>{m.value}</a>) : m.kind === "phone" ? (<a href={`tel:${m.value}`}>{m.value}</a>+ ) : m.kind === "address" ? (+ // A postal address is several lines and stays that way.+ <span className="contact-address">{m.value}</span>) : (m.value)}diff --git a/src/styles/app.css b/src/styles/app.cssindex 59227eb..9fb8870 100644--- a/src/styles/app.css+++ b/src/styles/app.css@@ -1255,6 +1255,20 @@ textarea.note-text:disabled {.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; }++/* A postal address is several lines and reads as several lines. */+.contact-address { white-space: pre-line; }++/* A detail this app can show but not safely write: present, plainly not editable. */+.contact-method-fixed {+ display: grid;+ grid-template-columns: 96px minmax(0, 1fr) auto;+ gap: 6px;+ align-items: start;+ font-size: var(--t-13);+ color: var(--text-2);+ padding: 4px 0;+}.contact-methods a { color: var(--gold); text-decoration: none; }.contact-methods a:hover { text-decoration: underline; }