Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
215 lines
8.7 KiB
Swift
215 lines
8.7 KiB
Swift
import Contacts
|
|
import Foundation
|
|
import OpenClawKit
|
|
|
|
final class ContactsService: ContactsServicing {
|
|
private let authorizationStatus: @Sendable () -> CNAuthorizationStatus
|
|
|
|
init(
|
|
authorizationStatus: @escaping @Sendable () -> CNAuthorizationStatus = {
|
|
CNContactStore.authorizationStatus(for: .contacts)
|
|
})
|
|
{
|
|
self.authorizationStatus = authorizationStatus
|
|
}
|
|
|
|
private static var payloadKeys: [CNKeyDescriptor] {
|
|
[
|
|
CNContactIdentifierKey as CNKeyDescriptor,
|
|
CNContactGivenNameKey as CNKeyDescriptor,
|
|
CNContactFamilyNameKey as CNKeyDescriptor,
|
|
CNContactOrganizationNameKey as CNKeyDescriptor,
|
|
CNContactPhoneNumbersKey as CNKeyDescriptor,
|
|
CNContactEmailAddressesKey as CNKeyDescriptor,
|
|
// CNContactFormatter requires more keys than payload(from:) accesses directly.
|
|
// Fetch its declared key set; formatting a partial contact otherwise raises an
|
|
// Objective-C CNContactPropertyNotFetchedException and crashes the app.
|
|
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
|
|
]
|
|
}
|
|
|
|
func search(params: OpenClawContactsSearchParams) async throws -> OpenClawContactsSearchPayload {
|
|
let store = try self.authorizedStore()
|
|
|
|
let limit = max(1, min(params.limit ?? 25, 200))
|
|
|
|
var contacts: [CNContact] = []
|
|
if let query = params.query?.trimmingCharacters(in: .whitespacesAndNewlines), !query.isEmpty {
|
|
let predicate = CNContact.predicateForContacts(matchingName: query)
|
|
contacts = try store.unifiedContacts(matching: predicate, keysToFetch: Self.payloadKeys)
|
|
} else {
|
|
let request = CNContactFetchRequest(keysToFetch: Self.payloadKeys)
|
|
try store.enumerateContacts(with: request) { contact, stop in
|
|
contacts.append(contact)
|
|
if contacts.count >= limit {
|
|
stop.pointee = true
|
|
}
|
|
}
|
|
}
|
|
|
|
let sliced = Array(contacts.prefix(limit))
|
|
let payload = sliced.map { Self.payload(from: $0) }
|
|
|
|
return OpenClawContactsSearchPayload(contacts: payload)
|
|
}
|
|
|
|
func add(params: OpenClawContactsAddParams) async throws -> OpenClawContactsAddPayload {
|
|
let store = try self.authorizedStore()
|
|
|
|
let givenName = params.givenName?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let familyName = params.familyName?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let organizationName = params.organizationName?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let displayName = params.displayName?.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let phoneNumbers = Self.normalizeStrings(params.phoneNumbers)
|
|
let emails = Self.normalizeStrings(params.emails, lowercased: true)
|
|
|
|
let hasName = !(givenName ?? "").isEmpty || !(familyName ?? "").isEmpty || !(displayName ?? "").isEmpty
|
|
let hasOrg = !(organizationName ?? "").isEmpty
|
|
let hasDetails = !phoneNumbers.isEmpty || !emails.isEmpty
|
|
guard hasName || hasOrg || hasDetails else {
|
|
throw NSError(domain: "Contacts", code: 2, userInfo: [
|
|
NSLocalizedDescriptionKey: "CONTACTS_INVALID: include a name, organization, phone, or email",
|
|
])
|
|
}
|
|
|
|
if !phoneNumbers.isEmpty || !emails.isEmpty {
|
|
if let existing = try Self.findExistingContact(
|
|
store: store,
|
|
phoneNumbers: phoneNumbers,
|
|
emails: emails)
|
|
{
|
|
return OpenClawContactsAddPayload(contact: Self.payload(from: existing))
|
|
}
|
|
}
|
|
|
|
let contact = CNMutableContact()
|
|
contact.givenName = givenName ?? ""
|
|
contact.familyName = familyName ?? ""
|
|
contact.organizationName = organizationName ?? ""
|
|
if contact.givenName.isEmpty, contact.familyName.isEmpty, let displayName {
|
|
contact.givenName = displayName
|
|
}
|
|
contact.phoneNumbers = phoneNumbers.map {
|
|
CNLabeledValue(label: CNLabelPhoneNumberMobile, value: CNPhoneNumber(stringValue: $0))
|
|
}
|
|
contact.emailAddresses = emails.map {
|
|
CNLabeledValue(label: CNLabelHome, value: $0 as NSString)
|
|
}
|
|
|
|
let save = CNSaveRequest()
|
|
save.add(contact, toContainerWithIdentifier: nil)
|
|
try store.execute(save)
|
|
|
|
let persisted: CNContact = if !contact.identifier.isEmpty {
|
|
try store.unifiedContact(
|
|
withIdentifier: contact.identifier,
|
|
keysToFetch: Self.payloadKeys)
|
|
} else {
|
|
contact
|
|
}
|
|
|
|
return OpenClawContactsAddPayload(contact: Self.payload(from: persisted))
|
|
}
|
|
|
|
private static func ensureAuthorization(status: CNAuthorizationStatus) -> Bool {
|
|
switch status {
|
|
case .authorized, .limited:
|
|
return true
|
|
case .notDetermined:
|
|
return false
|
|
case .restricted, .denied:
|
|
return false
|
|
@unknown default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
private func authorizedStore() throws -> CNContactStore {
|
|
let status = self.authorizationStatus()
|
|
let authorized = Self.ensureAuthorization(status: status)
|
|
guard authorized else {
|
|
throw NSError(domain: "Contacts", code: 1, userInfo: [
|
|
NSLocalizedDescriptionKey: "CONTACTS_PERMISSION_REQUIRED: grant Contacts permission",
|
|
])
|
|
}
|
|
return CNContactStore()
|
|
}
|
|
|
|
private static func normalizeStrings(_ values: [String]?, lowercased: Bool = false) -> [String] {
|
|
(values ?? [])
|
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
.filter { !$0.isEmpty }
|
|
.map { lowercased ? $0.lowercased() : $0 }
|
|
}
|
|
|
|
private static func findExistingContact(
|
|
store: CNContactStore,
|
|
phoneNumbers: [String],
|
|
emails: [String]) throws -> CNContact?
|
|
{
|
|
if phoneNumbers.isEmpty, emails.isEmpty {
|
|
return nil
|
|
}
|
|
|
|
var matches: [CNContact] = []
|
|
|
|
for phone in phoneNumbers {
|
|
let predicate = CNContact.predicateForContacts(matching: CNPhoneNumber(stringValue: phone))
|
|
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: Self.payloadKeys)
|
|
matches.append(contentsOf: contacts)
|
|
}
|
|
|
|
for email in emails {
|
|
let predicate = CNContact.predicateForContacts(matchingEmailAddress: email)
|
|
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: Self.payloadKeys)
|
|
matches.append(contentsOf: contacts)
|
|
}
|
|
|
|
return Self.matchContacts(contacts: matches, phoneNumbers: phoneNumbers, emails: emails)
|
|
}
|
|
|
|
private static func matchContacts(
|
|
contacts: [CNContact],
|
|
phoneNumbers: [String],
|
|
emails: [String]) -> CNContact?
|
|
{
|
|
let normalizedPhones = Set(phoneNumbers.map { self.normalizePhone($0) }.filter { !$0.isEmpty })
|
|
let normalizedEmails = Set(emails.map { $0.lowercased() }.filter { !$0.isEmpty })
|
|
var seen = Set<String>()
|
|
|
|
for contact in contacts {
|
|
guard seen.insert(contact.identifier).inserted else { continue }
|
|
let contactPhones = Set(contact.phoneNumbers.map { self.normalizePhone($0.value.stringValue) })
|
|
let contactEmails = Set(contact.emailAddresses.map { String($0.value).lowercased() })
|
|
|
|
if !normalizedPhones.isEmpty, !contactPhones.isDisjoint(with: normalizedPhones) {
|
|
return contact
|
|
}
|
|
if !normalizedEmails.isEmpty, !contactEmails.isDisjoint(with: normalizedEmails) {
|
|
return contact
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
private static func normalizePhone(_ phone: String) -> String {
|
|
let trimmed = phone.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
let digits = trimmed.unicodeScalars.filter { CharacterSet.decimalDigits.contains($0) }
|
|
let normalized = String(String.UnicodeScalarView(digits))
|
|
return normalized.isEmpty ? trimmed : normalized
|
|
}
|
|
|
|
private static func payload(from contact: CNContact) -> OpenClawContactPayload {
|
|
OpenClawContactPayload(
|
|
identifier: contact.identifier,
|
|
displayName: CNContactFormatter.string(from: contact, style: .fullName)
|
|
?? "\(contact.givenName) \(contact.familyName)".trimmingCharacters(in: .whitespacesAndNewlines),
|
|
givenName: contact.givenName,
|
|
familyName: contact.familyName,
|
|
organizationName: contact.organizationName,
|
|
phoneNumbers: contact.phoneNumbers.map(\.value.stringValue),
|
|
emails: contact.emailAddresses.map { String($0.value) })
|
|
}
|
|
}
|