|
| 1 | +@preconcurrency import Contacts |
| 2 | +import Foundation |
| 3 | + |
| 4 | +public struct ContactMatch: Equatable, Sendable { |
| 5 | + public let name: String |
| 6 | + public let handle: String |
| 7 | + |
| 8 | + public init(name: String, handle: String) { |
| 9 | + self.name = name |
| 10 | + self.handle = handle |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +public protocol ContactResolving: Sendable { |
| 15 | + var contactsUnavailable: Bool { get } |
| 16 | + |
| 17 | + func displayName(for handle: String) -> String? |
| 18 | + func displayNames(for handles: [String]) -> [String: String] |
| 19 | + func searchByName(_ query: String) -> [ContactMatch] |
| 20 | +} |
| 21 | + |
| 22 | +public final class NoOpContactResolver: ContactResolving, Sendable { |
| 23 | + public let contactsUnavailable: Bool |
| 24 | + |
| 25 | + public init(contactsUnavailable: Bool = false) { |
| 26 | + self.contactsUnavailable = contactsUnavailable |
| 27 | + } |
| 28 | + |
| 29 | + public func displayName(for handle: String) -> String? { nil } |
| 30 | + public func displayNames(for handles: [String]) -> [String: String] { [:] } |
| 31 | + public func searchByName(_ query: String) -> [ContactMatch] { [] } |
| 32 | +} |
| 33 | + |
| 34 | +public final class ContactResolver: ContactResolving, @unchecked Sendable { |
| 35 | + private let phoneToName: [String: String] |
| 36 | + private let emailToName: [String: String] |
| 37 | + private let contacts: [ContactRecord] |
| 38 | + private let normalizer = PhoneNumberNormalizer() |
| 39 | + private let region: String |
| 40 | + |
| 41 | + public let contactsUnavailable: Bool |
| 42 | + |
| 43 | + private init( |
| 44 | + phoneToName: [String: String], |
| 45 | + emailToName: [String: String], |
| 46 | + contacts: [ContactRecord], |
| 47 | + region: String |
| 48 | + ) { |
| 49 | + self.phoneToName = phoneToName |
| 50 | + self.emailToName = emailToName |
| 51 | + self.contacts = contacts |
| 52 | + self.region = region |
| 53 | + self.contactsUnavailable = false |
| 54 | + } |
| 55 | + |
| 56 | + public static func create(region: String = "US") async -> any ContactResolving { |
| 57 | + let store = CNContactStore() |
| 58 | + switch CNContactStore.authorizationStatus(for: .contacts) { |
| 59 | + case .authorized: |
| 60 | + return load(store: store, region: region) |
| 61 | + case .notDetermined: |
| 62 | + let granted = await requestAccess(store: store) |
| 63 | + return granted |
| 64 | + ? load(store: store, region: region) : NoOpContactResolver(contactsUnavailable: true) |
| 65 | + case .denied, .restricted: |
| 66 | + return NoOpContactResolver(contactsUnavailable: true) |
| 67 | + @unknown default: |
| 68 | + return NoOpContactResolver(contactsUnavailable: true) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + public func displayName(for handle: String) -> String? { |
| 73 | + let lookup = normalizedLookupHandle(handle) |
| 74 | + if lookup.contains("@") { |
| 75 | + return emailToName[lookup.lowercased()] |
| 76 | + } |
| 77 | + return phoneToName[normalizer.normalize(lookup, region: region)] |
| 78 | + } |
| 79 | + |
| 80 | + public func displayNames(for handles: [String]) -> [String: String] { |
| 81 | + var resolved: [String: String] = [:] |
| 82 | + for handle in handles { |
| 83 | + if let name = displayName(for: handle) { |
| 84 | + resolved[handle] = name |
| 85 | + } |
| 86 | + } |
| 87 | + return resolved |
| 88 | + } |
| 89 | + |
| 90 | + public func searchByName(_ query: String) -> [ContactMatch] { |
| 91 | + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() |
| 92 | + guard !normalizedQuery.isEmpty else { return [] } |
| 93 | + |
| 94 | + var matches: [ContactMatch] = [] |
| 95 | + for contact in contacts where contact.name.lowercased().contains(normalizedQuery) { |
| 96 | + if let phone = contact.phones.first { |
| 97 | + matches.append(ContactMatch(name: contact.name, handle: phone)) |
| 98 | + } else if let email = contact.emails.first { |
| 99 | + matches.append(ContactMatch(name: contact.name, handle: email)) |
| 100 | + } |
| 101 | + } |
| 102 | + return matches |
| 103 | + } |
| 104 | + |
| 105 | + private static func requestAccess(store: CNContactStore) async -> Bool { |
| 106 | + await withCheckedContinuation { continuation in |
| 107 | + store.requestAccess(for: .contacts) { granted, _ in |
| 108 | + continuation.resume(returning: granted) |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private static func load(store: CNContactStore, region: String) -> any ContactResolving { |
| 114 | + let keysToFetch: [CNKeyDescriptor] = [ |
| 115 | + CNContactGivenNameKey as CNKeyDescriptor, |
| 116 | + CNContactFamilyNameKey as CNKeyDescriptor, |
| 117 | + CNContactNicknameKey as CNKeyDescriptor, |
| 118 | + CNContactPhoneNumbersKey as CNKeyDescriptor, |
| 119 | + CNContactEmailAddressesKey as CNKeyDescriptor, |
| 120 | + ] |
| 121 | + let request = CNContactFetchRequest(keysToFetch: keysToFetch) |
| 122 | + let normalizer = PhoneNumberNormalizer() |
| 123 | + var phoneToName: [String: String] = [:] |
| 124 | + var emailToName: [String: String] = [:] |
| 125 | + var contacts: [ContactRecord] = [] |
| 126 | + |
| 127 | + do { |
| 128 | + try store.enumerateContacts(with: request) { contact, _ in |
| 129 | + guard let name = displayName(for: contact) else { return } |
| 130 | + var phones: [String] = [] |
| 131 | + var emails: [String] = [] |
| 132 | + |
| 133 | + for number in contact.phoneNumbers { |
| 134 | + let normalized = normalizer.normalize(number.value.stringValue, region: region) |
| 135 | + phones.append(normalized) |
| 136 | + phoneToName[normalized] = phoneToName[normalized] ?? name |
| 137 | + } |
| 138 | + for email in contact.emailAddresses { |
| 139 | + let normalized = String(email.value).lowercased() |
| 140 | + emails.append(normalized) |
| 141 | + emailToName[normalized] = emailToName[normalized] ?? name |
| 142 | + } |
| 143 | + |
| 144 | + if !phones.isEmpty || !emails.isEmpty { |
| 145 | + contacts.append(ContactRecord(name: name, phones: phones, emails: emails)) |
| 146 | + } |
| 147 | + } |
| 148 | + } catch { |
| 149 | + return NoOpContactResolver(contactsUnavailable: true) |
| 150 | + } |
| 151 | + |
| 152 | + return ContactResolver( |
| 153 | + phoneToName: phoneToName, |
| 154 | + emailToName: emailToName, |
| 155 | + contacts: contacts, |
| 156 | + region: region |
| 157 | + ) |
| 158 | + } |
| 159 | + |
| 160 | + private static func displayName(for contact: CNContact) -> String? { |
| 161 | + if !contact.nickname.isEmpty { |
| 162 | + return contact.nickname |
| 163 | + } |
| 164 | + let name = [contact.givenName, contact.familyName] |
| 165 | + .filter { !$0.isEmpty } |
| 166 | + .joined(separator: " ") |
| 167 | + return name.isEmpty ? nil : name |
| 168 | + } |
| 169 | + |
| 170 | + private func normalizedLookupHandle(_ handle: String) -> String { |
| 171 | + let trimmed = handle.trimmingCharacters(in: .whitespacesAndNewlines) |
| 172 | + for prefix in ["iMessage;-;", "iMessage;+;", "SMS;-;", "SMS;+;", "any;-;", "any;+;"] |
| 173 | + where trimmed.hasPrefix(prefix) { |
| 174 | + return String(trimmed.dropFirst(prefix.count)) |
| 175 | + } |
| 176 | + return trimmed |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +private struct ContactRecord: Sendable { |
| 181 | + let name: String |
| 182 | + let phones: [String] |
| 183 | + let emails: [String] |
| 184 | +} |
0 commit comments