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: names, number search, merging notes and duplicates
Yashwanth Kamireddi25cf25d36bb1
diff --git a/crates/quince-core/src/contacts.rs b/crates/quince-core/src/contacts.rsindex bf6b721..7ae3433 100644--- a/crates/quince-core/src/contacts.rs+++ b/crates/quince-core/src/contacts.rs@@ -361,6 +361,15 @@ impl Contact {/// the first method rather than at an empty string.#[must_use]pub fn display_name(&self) -> String {+ // A company's card goes by the company, whoever is named on it, as Contacts shows it.+ if let Some(company) = self+ .company+ .as_deref()+ .map(str::trim)+ .filter(|c| self.is_company && !c.is_empty())+ {+ return company.to_string();+ }let full = [self.first_name.as_deref(),self.middle_name.as_deref(),@@ -941,11 +950,28 @@ impl Contact {.filter(|m| m.kind == "phone").map(|m| digits(&m.value)).collect();+ // A whole number typed or pasted (its words together: "+91 98765 43210") is found+ // however the card writes it — with or without the country code or a trunk 0 — by its+ // last digits, as numbers are told apart when merging.+ let typed: String = words+ .iter()+ .filter(|w| looks_like_number(w))+ .map(|w| digits(w))+ .collect();+ let whole_number = typed.len() >= 7+ && numbers.iter().any(|n| {+ let tail = |d: &str| d[d.len().saturating_sub(10)..].to_string();+ n.contains(&typed)+ || (n.len() >= 7 && {+ let (a, b) = (tail(n), tail(&typed));+ a.ends_with(&b) || b.ends_with(&a)+ })+ });words.iter().all(|w| {text.contains(w.as_str())|| (looks_like_number(w) && {let d = digits(w);- numbers.iter().any(|n| n.contains(&d))+ whole_number || numbers.iter().any(|n| n.contains(&d))})})}@@ -977,6 +1003,46 @@ mod tests {}}+ /// A company's card goes by the company, whoever is named on it — as Contacts lists it,+ /// and as an export names it.+ #[test]+ fn a_company_card_goes_by_the_company() {+ let mut card = contact("1", Some("Ravi"), Some("Menon"));+ card.company = Some("Bluepine Logistics".into());+ assert_eq!(card.display_name(), "Ravi Menon");+ card.is_company = true;+ assert_eq!(card.display_name(), "Bluepine Logistics");+ card.company = Some(" ".into());+ assert_eq!(card.display_name(), "Ravi Menon");+ }++ /// A number searched as it is pasted from elsewhere — with its country code, or a trunk+ /// 0 — finds the card that holds it written the other way.+ #[test]+ fn a_number_is_found_with_or_without_its_country_code() {+ let mut lib = Library::in_memory().unwrap();+ let mut local = contact("1", Some("Asha"), None);+ local.methods[0].value = "98765 43210".into();+ let mut intl = contact("2", Some("Bela"), None);+ intl.methods[0].value = "+44 7700 900123".into();+ lib.put_contacts(&[local, intl]).unwrap();+ let found = |q: &str| -> Vec<String> {+ lib.contacts(Some(q))+ .unwrap()+ .into_iter()+ .map(|c| c.guid)+ .collect()+ };+ assert_eq!(found("+91 98765 43210"), ["1"]);+ assert_eq!(found("+919876543210"), ["1"]);+ assert_eq!(found("098765 43210"), ["1"]);+ assert_eq!(found("07700 900123"), ["2"]);+ assert_eq!(found("7700"), ["2"]);+ // Part of a number still finds only what holds that part.+ assert_eq!(found("98765"), ["1"]);+ assert!(found("+91 12345 67890").is_empty());+ }+/// Warming the picture cache asks only who has a picture and which: the same people the/// whole cards say have one, with the same signatures.#[test]diff --git a/crates/quince-core/src/contacts_merge.rs b/crates/quince-core/src/contacts_merge.rsindex 509b77b..e08fb0f 100644--- a/crates/quince-core/src/contacts_merge.rs+++ b/crates/quince-core/src/contacts_merge.rs@@ -77,6 +77,24 @@ fn name_key(c: &Contact) -> Option<String> {(folded.chars().count() >= 2).then_some(folded)}+/// Whether two names could be one person's: either has none, or each word of the shorter is+/// the start of a word of the longer ("A R", "Asha R" and "Asha Rao"; never "Ravi Rao").+fn same_person(a: &Option<String>, b: &Option<String>) -> bool {+ let (Some(a), Some(b)) = (a, b) else {+ return true;+ };+ let (a, b): (Vec<&str>, Vec<&str>) = (a.split(' ').collect(), b.split(' ').collect());+ let (short, long) = if a.len() <= b.len() { (a, b) } else { (b, a) };+ let mut used = vec![false; long.len()];+ short.iter().all(|w| {+ let found = long+ .iter()+ .enumerate()+ .find(|(k, l)| !used[*k] && (l.starts_with(w) || w.starts_with(*l)));+ found.map(|(k, _)| used[k] = true).is_some()+ })+}+/// Cards that look like one person, and what they have in common.#[derive(Debug, Clone, Serialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]@@ -100,6 +118,7 @@ pub fn find_duplicates(book: &[Contact]) -> Vec<Duplicates> {}i}+ let names: Vec<Option<String>> = book.iter().map(name_key).collect();// Each key, the first card that had it and why it counts.let mut first: HashMap<String, usize> = HashMap::new();let mut shared: HashMap<String, Vec<usize>> = HashMap::new();@@ -129,6 +148,10 @@ pub fn find_duplicates(book: &[Contact]) -> Vec<Duplicates> {for key in keys {shared.entry(key.clone()).or_default().push(i);match first.get(&key) {+ // A number or an address shared by two people named differently is a home's+ // landline or an office's switchboard, not one person: Merge All made Mom and+ // Dad one card.+ Some(&j) if !key.starts_with("name:") && !same_person(&names[i], &names[j]) => {}Some(&j) => {let (a, b) = (root(&mut parent, i), root(&mut parent, j));if a != b {@@ -218,15 +241,21 @@ fn filled(v: &Option<String>) -> bool {/// merging the merged card again adds nothing.#[must_use]pub fn joined_notes<'a>(notes: impl IntoIterator<Item = Option<&'a str>>) -> Option<String> {+ // Kept paragraph by paragraph, a paragraph dropped only when it is there already whole:+ // matched as text anywhere, "peanuts" was lost beside "Allergic to peanuts".let mut out = String::new();- for n in notes.into_iter().flatten().map(str::trim) {- if n.is_empty() || out.contains(n) {- continue;- }- if !out.is_empty() {- out.push_str("\n\n");+ let mut seen: Vec<String> = Vec::new();+ for n in notes.into_iter().flatten() {+ for p in n.split("\n\n").map(str::trim).filter(|p| !p.is_empty()) {+ if seen.iter().any(|s| s == p) {+ continue;+ }+ if !out.is_empty() {+ out.push_str("\n\n");+ }+ out.push_str(p);+ seen.push(p.to_string());}- out.push_str(n);}(!out.is_empty()).then_some(out)}@@ -324,6 +353,30 @@ mod tests {use super::*;use crate::contacts::ContactDetails;+ /// A note is dropped only when it is already there whole, not when its words happen to+ /// appear inside another card's note: "peanuts" was lost beside "Allergic to peanuts".+ #[test]+ fn a_note_inside_another_is_kept_and_a_merged_note_adds_nothing_again() {+ assert_eq!(+ joined_notes([Some("Allergic to peanuts and shellfish"), Some("peanuts")]).as_deref(),+ Some("Allergic to peanuts and shellfish\n\npeanuts")+ );+ assert_eq!(+ joined_notes([Some("Mom's friend"), Some("Mom")]).as_deref(),+ Some("Mom's friend\n\nMom")+ );+ // Merged again with either card: nothing more.+ let once = joined_notes([Some("Gate code 4410"), Some("Lives upstairs")]).unwrap();+ assert_eq!(+ joined_notes([Some(once.as_str()), Some("Lives upstairs")]),+ Some(once.clone())+ );+ assert_eq!(+ joined_notes([Some("Gate code 4410"), Some(once.as_str())]),+ Some(once)+ );+ }+fn person(guid: &str, first: &str, last: &str, methods: &[(&str, &str, &str)]) -> Card {Card {contact: Contact {@@ -416,6 +469,24 @@ mod tests {assert_eq!(found[0].guids, ["A", "B", "C"]);}+ /// People who share a home's landline or an office's number are not one person: only a+ /// card with no name, or one whose name could be theirs, joins them by it.+ #[test]+ fn people_who_share_a_landline_are_not_duplicates() {+ let book: Vec<Contact> = [+ person("A", "Asha", "Rao", &[("phone", "HOME", "+1 555 010 0100")]),+ person("B", "Ravi", "Rao", &[("phone", "HOME", "555 010 0100")]),+ person("C", "", "", &[("phone", "", "(555) 010-0100")]),+ person("D", "Asha", "R", &[("phone", "", "555-010-0100")]),+ ]+ .into_iter()+ .map(|c| c.contact)+ .collect();+ let found = find_duplicates(&book);+ assert_eq!(found.len(), 1, "{found:?}");+ assert_eq!(found[0].guids, ["A", "C", "D"]);+ }+#[test]fn a_card_with_nothing_to_go_on_is_never_a_duplicate() {let book: Vec<Contact> = [person("A", "", "", &[]), person("B", "", "", &[])]