@capacitor/contacts 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,924 @@
1
+ package com.capacitorjs.plugins.contacts
2
+
3
+ import android.content.ContentProviderOperation
4
+ import android.content.ContentUris
5
+ import android.content.Context
6
+ import android.net.Uri
7
+ import android.provider.ContactsContract
8
+ import android.provider.ContactsContract.CommonDataKinds.Email
9
+ import android.provider.ContactsContract.CommonDataKinds.Event
10
+ import android.provider.ContactsContract.CommonDataKinds.GroupMembership
11
+ import android.provider.ContactsContract.CommonDataKinds.Im
12
+ import android.provider.ContactsContract.CommonDataKinds.Nickname
13
+ import android.provider.ContactsContract.CommonDataKinds.Note
14
+ import android.provider.ContactsContract.CommonDataKinds.Organization
15
+ import android.provider.ContactsContract.CommonDataKinds.Phone
16
+ import android.provider.ContactsContract.CommonDataKinds.Photo
17
+ import android.provider.ContactsContract.CommonDataKinds.StructuredName
18
+ import android.provider.ContactsContract.CommonDataKinds.StructuredPostal
19
+ import android.provider.ContactsContract.CommonDataKinds.Website
20
+ import android.provider.ContactsContract.Data
21
+ import android.util.Base64
22
+ import com.getcapacitor.JSArray
23
+ import com.getcapacitor.JSObject
24
+ import org.json.JSONObject
25
+ import java.text.SimpleDateFormat
26
+ import java.util.Date
27
+ import java.util.Locale
28
+
29
+ /**
30
+ * Pure business logic for reading, searching, saving and removing device
31
+ * contacts via [ContactsContract]. Holds no Capacitor bridge types; the bridge
32
+ * ([ContactsPlugin]) parses calls and delegates here.
33
+ */
34
+ class Contacts(private val context: Context) {
35
+
36
+ /** Marker value used by the legacy API to request every field. */
37
+ private val allFields = "*"
38
+
39
+ /**
40
+ * The text columns `find` may match per MIME type. Restricting the
41
+ * columns keeps the LIKE from string-matching numeric TYPE columns
42
+ * (e.g. a filter of "2" matching every TYPE_MOBILE phone row).
43
+ */
44
+ private val searchableColumnsByMimeType = mapOf(
45
+ StructuredName.CONTENT_ITEM_TYPE to listOf(
46
+ StructuredName.DISPLAY_NAME, StructuredName.GIVEN_NAME, StructuredName.FAMILY_NAME,
47
+ StructuredName.PREFIX, StructuredName.MIDDLE_NAME, StructuredName.SUFFIX
48
+ ),
49
+ Phone.CONTENT_ITEM_TYPE to listOf(Phone.NUMBER),
50
+ Email.CONTENT_ITEM_TYPE to listOf(Email.ADDRESS),
51
+ StructuredPostal.CONTENT_ITEM_TYPE to listOf(
52
+ StructuredPostal.FORMATTED_ADDRESS, StructuredPostal.STREET, StructuredPostal.CITY,
53
+ StructuredPostal.REGION, StructuredPostal.POSTCODE, StructuredPostal.COUNTRY
54
+ ),
55
+ Im.CONTENT_ITEM_TYPE to listOf(Im.DATA),
56
+ Organization.CONTENT_ITEM_TYPE to listOf(
57
+ Organization.COMPANY, Organization.TITLE, Organization.DEPARTMENT
58
+ ),
59
+ Website.CONTENT_ITEM_TYPE to listOf(Website.URL),
60
+ Nickname.CONTENT_ITEM_TYPE to listOf(Nickname.NAME),
61
+ Note.CONTENT_ITEM_TYPE to listOf(Note.NOTE),
62
+ Event.CONTENT_ITEM_TYPE to listOf(Event.START_DATE)
63
+ )
64
+
65
+ /** Reads a string field, treating JSON null as absent (never "null"). */
66
+ private fun JSONObject.stringOrNull(key: String): String? =
67
+ if (isNull(key)) null else optString(key)
68
+
69
+ private fun JSONObject.stringOrEmpty(key: String): String = stringOrNull(key) ?: ""
70
+
71
+ // ---------------------------------------------------------------------
72
+ // Search
73
+ // ---------------------------------------------------------------------
74
+
75
+ /**
76
+ * Searches the device contacts.
77
+ *
78
+ * @param fields fields to search against (`["*"]` for all).
79
+ * @param filter case-insensitive substring to match; empty returns all.
80
+ * @param multiple when false, at most one contact is returned.
81
+ * @param desiredFields if non-empty, limits the fields populated on results.
82
+ * @param hasPhoneNumber when true, only contacts with a phone number are kept.
83
+ */
84
+ fun search(
85
+ fields: List<String>,
86
+ filter: String,
87
+ multiple: Boolean,
88
+ desiredFields: List<String>,
89
+ hasPhoneNumber: Boolean
90
+ ): JSArray {
91
+ val populate = desiredFields.toSet()
92
+ val results = JSArray()
93
+ for (contactId in collectMatchingContactIds(fields, filter, hasPhoneNumber)) {
94
+ val contact = readContact(contactId, populate) ?: continue
95
+ results.put(contact)
96
+ if (!multiple) break
97
+ }
98
+ return results
99
+ }
100
+
101
+ /**
102
+ * Returns the ids of all contacts matching [filter] on the requested
103
+ * [fields], ordered by display name. Two provider queries total: one over
104
+ * the Data table for field values, one over the Contacts table for
105
+ * display-name matching, ordering and the [hasPhoneNumber] restriction.
106
+ */
107
+ private fun collectMatchingContactIds(
108
+ fields: List<String>,
109
+ filter: String,
110
+ hasPhoneNumber: Boolean
111
+ ): List<String> {
112
+ val searchAll = fields.isEmpty() || fields.contains(allFields)
113
+ val matchDisplayName = searchAll ||
114
+ fields.any { it == "displayName" || it == "name" || it == "formatted" }
115
+ val matchId = searchAll || fields.contains("id")
116
+ val dataMatches = if (filter.isEmpty()) {
117
+ emptySet()
118
+ } else {
119
+ queryDataMatches(fields, filter, searchAll, hasPhoneNumber)
120
+ }
121
+
122
+ val selection = if (hasPhoneNumber) "${ContactsContract.Contacts.HAS_PHONE_NUMBER} = 1" else null
123
+ val cursor = context.contentResolver.query(
124
+ ContactsContract.Contacts.CONTENT_URI,
125
+ arrayOf(ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY),
126
+ selection,
127
+ null,
128
+ ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
129
+ ) ?: return emptyList()
130
+
131
+ val needle = filter.lowercase(Locale.getDefault())
132
+ val ids = ArrayList<String>()
133
+ cursor.use {
134
+ while (it.moveToNext()) {
135
+ val id = it.getString(0) ?: continue
136
+ val matches = filter.isEmpty() ||
137
+ dataMatches.contains(id) ||
138
+ (matchId && id == filter) ||
139
+ (matchDisplayName &&
140
+ it.getString(1)?.lowercase(Locale.getDefault())?.contains(needle) == true)
141
+ if (matches) ids.add(id)
142
+ }
143
+ }
144
+ return ids
145
+ }
146
+
147
+ /** Single Data-table query for contacts whose field values contain [filter]. */
148
+ private fun queryDataMatches(
149
+ fields: List<String>,
150
+ filter: String,
151
+ searchAll: Boolean,
152
+ hasPhoneNumber: Boolean
153
+ ): Set<String> {
154
+ val mimeTypes = if (searchAll) {
155
+ searchableColumnsByMimeType.keys.toList()
156
+ } else {
157
+ fields.mapNotNull { fieldToMimeType(it) }.distinct()
158
+ }
159
+ if (mimeTypes.isEmpty()) return emptySet()
160
+
161
+ // Escape LIKE wildcards so user input is matched literally.
162
+ val escaped = filter.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
163
+ val pattern = "%$escaped%"
164
+
165
+ val clauses = StringBuilder("(")
166
+ val args = ArrayList<String>()
167
+ for (mime in mimeTypes) {
168
+ val columns = searchableColumnsByMimeType[mime] ?: continue
169
+ if (args.isNotEmpty()) clauses.append(" OR ")
170
+ clauses.append("(${Data.MIMETYPE} = ? AND (")
171
+ args.add(mime)
172
+ clauses.append(columns.joinToString(" OR ") { "$it LIKE ? ESCAPE '\\'" })
173
+ columns.forEach { _ -> args.add(pattern) }
174
+ clauses.append("))")
175
+ }
176
+ if (args.isEmpty()) return emptySet()
177
+ clauses.append(")")
178
+ if (hasPhoneNumber) {
179
+ clauses.append(" AND ${ContactsContract.Contacts.HAS_PHONE_NUMBER} = 1")
180
+ }
181
+
182
+ val ids = HashSet<String>()
183
+ context.contentResolver.query(
184
+ Data.CONTENT_URI,
185
+ arrayOf(Data.CONTACT_ID),
186
+ clauses.toString(),
187
+ args.toTypedArray(),
188
+ null
189
+ )?.use {
190
+ while (it.moveToNext()) {
191
+ it.getString(0)?.let(ids::add)
192
+ }
193
+ }
194
+ return ids
195
+ }
196
+
197
+ // ---------------------------------------------------------------------
198
+ // Read a single contact
199
+ // ---------------------------------------------------------------------
200
+
201
+ /** Returns the aggregated contact identified by [contactId], or null. */
202
+ fun getContactById(contactId: String, desiredFields: Set<String> = emptySet()): JSObject? =
203
+ readContact(contactId, desiredFields)
204
+
205
+ /** Returns the aggregated contact backing the given raw-contact id, or null. */
206
+ fun getContactByRawId(rawId: String, desiredFields: Set<String> = emptySet()): JSObject? {
207
+ val cursor = context.contentResolver.query(
208
+ ContactsContract.RawContacts.CONTENT_URI,
209
+ arrayOf(ContactsContract.RawContacts.CONTACT_ID),
210
+ "${ContactsContract.RawContacts._ID} = ?",
211
+ arrayOf(rawId),
212
+ null
213
+ ) ?: return null
214
+ cursor.use {
215
+ if (it.moveToFirst()) {
216
+ val contactId = it.getString(0) ?: return null
217
+ return readContact(contactId, desiredFields)
218
+ }
219
+ }
220
+ return null
221
+ }
222
+
223
+ private fun wants(field: String, desiredFields: Set<String>): Boolean =
224
+ desiredFields.isEmpty() || desiredFields.contains(field)
225
+
226
+ private fun readContact(contactId: String, desiredFields: Set<String>): JSObject? {
227
+ val contact = JSObject()
228
+ contact.put("id", contactId)
229
+ if (desiredFields.isEmpty()) {
230
+ rawIdForContact(contactId)?.let { contact.put("rawId", it) }
231
+ }
232
+
233
+ val phones = JSArray()
234
+ val emails = JSArray()
235
+ val addresses = JSArray()
236
+ val ims = JSArray()
237
+ val organizations = JSArray()
238
+ val urls = JSArray()
239
+ val photos = JSArray()
240
+ val categories = JSArray()
241
+ val name = JSObject()
242
+ var hasName = false
243
+
244
+ // Explicit projection: DATA1..DATA10 covers every field read below and
245
+ // keeps the photo BLOB (DATA15) out of the cursor window.
246
+ val cursor = context.contentResolver.query(
247
+ Data.CONTENT_URI,
248
+ arrayOf(
249
+ Data._ID, Data.MIMETYPE, Data.IS_SUPER_PRIMARY,
250
+ ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
251
+ Data.DATA1, Data.DATA2, Data.DATA3, Data.DATA4, Data.DATA5,
252
+ Data.DATA6, Data.DATA7, Data.DATA8, Data.DATA9, Data.DATA10
253
+ ),
254
+ "${Data.CONTACT_ID} = ?",
255
+ arrayOf(contactId),
256
+ null
257
+ ) ?: return null
258
+
259
+ var fallbackDisplayName: String? = null
260
+ cursor.use { c ->
261
+ // Column indices are stable per cursor; resolve each name once.
262
+ val colIdx = HashMap<String, Int>()
263
+ fun col(nameOfColumn: String) = colIdx.getOrPut(nameOfColumn) { c.getColumnIndex(nameOfColumn) }
264
+ fun str(nameOfColumn: String) = c.getString(col(nameOfColumn))
265
+ fun int(nameOfColumn: String) = c.getInt(col(nameOfColumn))
266
+
267
+ while (c.moveToNext()) {
268
+ val mime = str(Data.MIMETYPE) ?: continue
269
+ val dataId = str(Data._ID)
270
+ val pref = int(Data.IS_SUPER_PRIMARY) == 1
271
+ if (fallbackDisplayName == null) {
272
+ fallbackDisplayName = str(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
273
+ }
274
+ when (mime) {
275
+ StructuredName.CONTENT_ITEM_TYPE -> {
276
+ hasName = true
277
+ name.put("formatted", str(StructuredName.DISPLAY_NAME))
278
+ name.put("familyName", str(StructuredName.FAMILY_NAME))
279
+ name.put("givenName", str(StructuredName.GIVEN_NAME))
280
+ name.put("middleName", str(StructuredName.MIDDLE_NAME))
281
+ name.put("honorificPrefix", str(StructuredName.PREFIX))
282
+ name.put("honorificSuffix", str(StructuredName.SUFFIX))
283
+ contact.put("displayName", str(StructuredName.DISPLAY_NAME))
284
+ }
285
+
286
+ Phone.CONTENT_ITEM_TYPE -> phones.put(
287
+ field(
288
+ dataId,
289
+ str(Phone.NUMBER),
290
+ phoneLabel(int(Phone.TYPE), str(Phone.LABEL)),
291
+ pref
292
+ )
293
+ )
294
+
295
+ Email.CONTENT_ITEM_TYPE -> emails.put(
296
+ field(
297
+ dataId,
298
+ str(Email.ADDRESS),
299
+ emailLabel(int(Email.TYPE), str(Email.LABEL)),
300
+ pref
301
+ )
302
+ )
303
+
304
+ StructuredPostal.CONTENT_ITEM_TYPE -> {
305
+ val address = JSObject()
306
+ address.put("id", dataId)
307
+ address.put("pref", pref)
308
+ address.put("type", addressLabel(int(StructuredPostal.TYPE), str(StructuredPostal.LABEL)))
309
+ address.put("formatted", str(StructuredPostal.FORMATTED_ADDRESS))
310
+ address.put("streetAddress", str(StructuredPostal.STREET))
311
+ address.put("locality", str(StructuredPostal.CITY))
312
+ address.put("region", str(StructuredPostal.REGION))
313
+ address.put("postalCode", str(StructuredPostal.POSTCODE))
314
+ address.put("country", str(StructuredPostal.COUNTRY))
315
+ addresses.put(address)
316
+ }
317
+
318
+ Im.CONTENT_ITEM_TYPE -> ims.put(
319
+ field(
320
+ dataId,
321
+ str(Im.DATA),
322
+ imLabel(int(Im.PROTOCOL), str(Im.CUSTOM_PROTOCOL)),
323
+ pref
324
+ )
325
+ )
326
+
327
+ Organization.CONTENT_ITEM_TYPE -> {
328
+ val org = JSObject()
329
+ org.put("id", dataId)
330
+ org.put("pref", pref)
331
+ org.put("type", organizationLabel(int(Organization.TYPE), str(Organization.LABEL)))
332
+ org.put("name", str(Organization.COMPANY))
333
+ org.put("department", str(Organization.DEPARTMENT))
334
+ org.put("title", str(Organization.TITLE))
335
+ organizations.put(org)
336
+ }
337
+
338
+ Website.CONTENT_ITEM_TYPE -> urls.put(
339
+ field(
340
+ dataId,
341
+ str(Website.URL),
342
+ websiteLabel(int(Website.TYPE), str(Website.LABEL)),
343
+ pref
344
+ )
345
+ )
346
+
347
+ Nickname.CONTENT_ITEM_TYPE ->
348
+ contact.put("nickname", str(Nickname.NAME))
349
+
350
+ Note.CONTENT_ITEM_TYPE ->
351
+ contact.put("note", str(Note.NOTE))
352
+
353
+ Event.CONTENT_ITEM_TYPE -> {
354
+ if (int(Event.TYPE) == Event.TYPE_BIRTHDAY) {
355
+ parseBirthday(str(Event.START_DATE))?.let { ms ->
356
+ contact.put("birthday", ms)
357
+ }
358
+ }
359
+ }
360
+
361
+ Photo.CONTENT_ITEM_TYPE -> {
362
+ if (wants("photos", desiredFields) && photoRowHasData(dataId)) {
363
+ val photoUri = Uri.withAppendedPath(
364
+ ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId.toLong()),
365
+ ContactsContract.Contacts.Photo.CONTENT_DIRECTORY
366
+ )
367
+ photos.put(field(dataId, photoUri.toString(), "url", pref))
368
+ }
369
+ }
370
+
371
+ GroupMembership.CONTENT_ITEM_TYPE -> {
372
+ if (wants("categories", desiredFields)) {
373
+ groupTitle(str(GroupMembership.GROUP_ROW_ID))?.let { title ->
374
+ categories.put(field(dataId, title, null, false))
375
+ }
376
+ }
377
+ }
378
+ }
379
+ }
380
+ }
381
+
382
+ if (!contact.has("displayName") && fallbackDisplayName != null) {
383
+ contact.put("displayName", fallbackDisplayName)
384
+ }
385
+ if (hasName && wants("name", desiredFields)) contact.put("name", name)
386
+ if (phones.length() > 0 && wants("phoneNumbers", desiredFields)) contact.put("phoneNumbers", phones)
387
+ if (emails.length() > 0 && wants("emails", desiredFields)) contact.put("emails", emails)
388
+ if (addresses.length() > 0 && wants("addresses", desiredFields)) contact.put("addresses", addresses)
389
+ if (ims.length() > 0 && wants("ims", desiredFields)) contact.put("ims", ims)
390
+ if (organizations.length() > 0 && wants("organizations", desiredFields)) contact.put("organizations", organizations)
391
+ if (urls.length() > 0 && wants("urls", desiredFields)) contact.put("urls", urls)
392
+ if (photos.length() > 0 && wants("photos", desiredFields)) contact.put("photos", photos)
393
+ if (categories.length() > 0 && wants("categories", desiredFields)) contact.put("categories", categories)
394
+
395
+ if (desiredFields.isNotEmpty()) {
396
+ if (!desiredFields.contains("displayName")) contact.remove("displayName")
397
+ if (!desiredFields.contains("nickname")) contact.remove("nickname")
398
+ if (!desiredFields.contains("note")) contact.remove("note")
399
+ if (!desiredFields.contains("birthday")) contact.remove("birthday")
400
+ }
401
+ return contact
402
+ }
403
+
404
+ private fun field(id: String?, value: String?, type: String?, pref: Boolean): JSObject {
405
+ val f = JSObject()
406
+ if (id != null) f.put("id", id)
407
+ f.put("value", value ?: "")
408
+ f.put("type", type ?: "other")
409
+ f.put("pref", pref)
410
+ return f
411
+ }
412
+
413
+ // Maps TYPE_* constants to fixed English labels ("home", "work", ...).
414
+ // The platform's getTypeLabel returns text in the device language, so a
415
+ // contact saved and re-read under different languages would not match.
416
+
417
+ private fun phoneLabel(type: Int, custom: String?): String = when (type) {
418
+ Phone.TYPE_HOME -> "home"
419
+ Phone.TYPE_MOBILE -> "mobile"
420
+ Phone.TYPE_WORK -> "work"
421
+ Phone.TYPE_FAX_WORK -> "work fax"
422
+ Phone.TYPE_FAX_HOME -> "home fax"
423
+ Phone.TYPE_PAGER -> "pager"
424
+ Phone.TYPE_MAIN -> "main"
425
+ Phone.TYPE_CALLBACK -> "callback"
426
+ Phone.TYPE_CAR -> "car"
427
+ Phone.TYPE_COMPANY_MAIN -> "company main"
428
+ Phone.TYPE_OTHER_FAX -> "other fax"
429
+ Phone.TYPE_RADIO -> "radio"
430
+ Phone.TYPE_TELEX -> "telex"
431
+ Phone.TYPE_TTY_TDD -> "tty tdd"
432
+ Phone.TYPE_WORK_MOBILE -> "work mobile"
433
+ Phone.TYPE_WORK_PAGER -> "work pager"
434
+ Phone.TYPE_ASSISTANT -> "assistant"
435
+ Phone.TYPE_MMS -> "mms"
436
+ Phone.TYPE_ISDN -> "isdn"
437
+ Phone.TYPE_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
438
+ else -> "other"
439
+ }
440
+
441
+ private fun emailLabel(type: Int, custom: String?): String = when (type) {
442
+ Email.TYPE_HOME -> "home"
443
+ Email.TYPE_WORK -> "work"
444
+ Email.TYPE_MOBILE -> "mobile"
445
+ Email.TYPE_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
446
+ else -> "other"
447
+ }
448
+
449
+ private fun addressLabel(type: Int, custom: String?): String = when (type) {
450
+ StructuredPostal.TYPE_HOME -> "home"
451
+ StructuredPostal.TYPE_WORK -> "work"
452
+ StructuredPostal.TYPE_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
453
+ else -> "other"
454
+ }
455
+
456
+ private fun organizationLabel(type: Int, custom: String?): String = when (type) {
457
+ Organization.TYPE_WORK -> "work"
458
+ Organization.TYPE_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
459
+ else -> "other"
460
+ }
461
+
462
+ private fun imLabel(protocol: Int, custom: String?): String = when (protocol) {
463
+ Im.PROTOCOL_AIM -> "aim"
464
+ Im.PROTOCOL_MSN -> "msn"
465
+ Im.PROTOCOL_YAHOO -> "yahoo"
466
+ Im.PROTOCOL_SKYPE -> "skype"
467
+ Im.PROTOCOL_QQ -> "qq"
468
+ Im.PROTOCOL_GOOGLE_TALK -> "google talk"
469
+ Im.PROTOCOL_ICQ -> "icq"
470
+ Im.PROTOCOL_JABBER -> "jabber"
471
+ Im.PROTOCOL_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
472
+ else -> "other"
473
+ }
474
+
475
+ /** Website has no `getTypeLabel` helper, so map its TYPE_* constants manually. */
476
+ private fun websiteLabel(type: Int, custom: String?): String = when (type) {
477
+ Website.TYPE_HOMEPAGE -> "homepage"
478
+ Website.TYPE_BLOG -> "blog"
479
+ Website.TYPE_PROFILE -> "profile"
480
+ Website.TYPE_HOME -> "home"
481
+ Website.TYPE_WORK -> "work"
482
+ Website.TYPE_FTP -> "ftp"
483
+ Website.TYPE_CUSTOM -> custom?.lowercase(Locale.getDefault()) ?: "other"
484
+ else -> "other"
485
+ }
486
+
487
+ private fun rawIdForContact(contactId: String): String? {
488
+ val cursor = context.contentResolver.query(
489
+ ContactsContract.RawContacts.CONTENT_URI,
490
+ arrayOf(ContactsContract.RawContacts._ID),
491
+ "${ContactsContract.RawContacts.CONTACT_ID} = ?",
492
+ arrayOf(contactId),
493
+ null
494
+ ) ?: return null
495
+ cursor.use { if (it.moveToFirst()) return it.getString(0) }
496
+ return null
497
+ }
498
+
499
+ private fun groupTitle(groupRowId: String?): String? {
500
+ if (groupRowId == null) return null
501
+ val cursor = context.contentResolver.query(
502
+ ContactsContract.Groups.CONTENT_URI,
503
+ arrayOf(ContactsContract.Groups.TITLE),
504
+ "${ContactsContract.Groups._ID} = ?",
505
+ arrayOf(groupRowId),
506
+ null
507
+ ) ?: return null
508
+ cursor.use { if (it.moveToFirst()) return it.getString(0) }
509
+ return null
510
+ }
511
+
512
+ /** A contact can have a photo row with no image in it; those must not
513
+ * produce a photo entry. */
514
+ private fun photoRowHasData(dataId: String?): Boolean {
515
+ if (dataId == null) return false
516
+ return try {
517
+ val uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId.toLong())
518
+ context.contentResolver.openInputStream(uri)?.use { it.read() != -1 } ?: false
519
+ } catch (e: Exception) {
520
+ false
521
+ }
522
+ }
523
+
524
+ private fun parseBirthday(raw: String?): Long? {
525
+ if (raw.isNullOrEmpty()) return null
526
+ val formats = arrayOf("yyyy-MM-dd", "--MM-dd", "yyyyMMdd")
527
+ for (pattern in formats) {
528
+ try {
529
+ val date = SimpleDateFormat(pattern, Locale.US).parse(raw)
530
+ if (date != null) return date.time
531
+ } catch (_: Exception) {
532
+ }
533
+ }
534
+ return null
535
+ }
536
+
537
+ // ---------------------------------------------------------------------
538
+ // Save (insert or update)
539
+ // ---------------------------------------------------------------------
540
+
541
+ /**
542
+ * Inserts a new contact or updates the existing one identified by
543
+ * `contact.id`. Returns the affected raw-contact id.
544
+ *
545
+ * @throws ContactsException on failure.
546
+ */
547
+ fun save(contact: JSONObject): String {
548
+ val existingId = contact.stringOrNull("id")?.takeIf { it.isNotEmpty() }
549
+ return if (existingId == null) insert(contact) else update(existingId, contact)
550
+ }
551
+
552
+ private fun insert(contact: JSONObject): String {
553
+ val ops = ArrayList<ContentProviderOperation>()
554
+ val rawIndex = 0
555
+ // No ACCOUNT_TYPE/ACCOUNT_NAME values: absent columns let the provider
556
+ // pick the user's default account. Explicit nulls request a *local*
557
+ // contact, which Android 16+ rejects when the default account is a
558
+ // cloud account ("Cannot add contacts to local or SIM accounts").
559
+ ops.add(
560
+ ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
561
+ .withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
562
+ .build()
563
+ )
564
+ appendDataInserts(ops, rawIndex, contact)
565
+
566
+ try {
567
+ val results = context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)
568
+ val rawUri = results[0].uri ?: throw ContactsException(ContactsError.UNKNOWN)
569
+ return ContentUris.parseId(rawUri).toString()
570
+ } catch (e: ContactsException) {
571
+ throw e
572
+ } catch (e: Exception) {
573
+ throw ContactsException(ContactsError.IO_ERROR, e)
574
+ }
575
+ }
576
+
577
+ private fun update(contactId: String, contact: JSONObject): String {
578
+ val rawId = rawIdForContact(contactId)
579
+ ?: throw ContactsException(ContactsError.INVALID_ARGUMENT)
580
+ val ops = ArrayList<ContentProviderOperation>()
581
+
582
+ // Replace only the fields present in the payload; absent fields are
583
+ // left untouched.
584
+ val mimeTypeByWireKey = mapOf(
585
+ "name" to StructuredName.CONTENT_ITEM_TYPE,
586
+ "phoneNumbers" to Phone.CONTENT_ITEM_TYPE,
587
+ "emails" to Email.CONTENT_ITEM_TYPE,
588
+ "addresses" to StructuredPostal.CONTENT_ITEM_TYPE,
589
+ "ims" to Im.CONTENT_ITEM_TYPE,
590
+ "organizations" to Organization.CONTENT_ITEM_TYPE,
591
+ "urls" to Website.CONTENT_ITEM_TYPE,
592
+ "nickname" to Nickname.CONTENT_ITEM_TYPE,
593
+ "note" to Note.CONTENT_ITEM_TYPE,
594
+ "birthday" to Event.CONTENT_ITEM_TYPE,
595
+ "photos" to Photo.CONTENT_ITEM_TYPE
596
+ )
597
+ for ((key, mime) in mimeTypeByWireKey) {
598
+ if (!contact.has(key) || contact.isNull(key)) continue
599
+ // Only the birthday is managed among events; never delete the
600
+ // contact's anniversaries or other custom dates.
601
+ var selection = "${Data.RAW_CONTACT_ID} = ? AND ${Data.MIMETYPE} = ?"
602
+ if (key == "birthday") {
603
+ selection += " AND ${Event.TYPE} = ${Event.TYPE_BIRTHDAY}"
604
+ }
605
+ ops.add(
606
+ ContentProviderOperation.newDelete(Data.CONTENT_URI)
607
+ .withSelection(selection, arrayOf(rawId, mime))
608
+ .build()
609
+ )
610
+ }
611
+ appendDataInserts(ops, null, contact, rawId)
612
+
613
+ try {
614
+ context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)
615
+ return rawId
616
+ } catch (e: Exception) {
617
+ throw ContactsException(ContactsError.IO_ERROR, e)
618
+ }
619
+ }
620
+
621
+ /**
622
+ * Appends the data-row inserts for every field of [contact]. When
623
+ * [rawIndex] is non-null the rows back-reference an as-yet-uninserted raw
624
+ * contact (insert flow); otherwise they reference the existing [rawId]
625
+ * (update flow).
626
+ */
627
+ private fun appendDataInserts(
628
+ ops: ArrayList<ContentProviderOperation>,
629
+ rawIndex: Int?,
630
+ contact: JSONObject,
631
+ rawId: String? = null
632
+ ) {
633
+ fun newInsert(): ContentProviderOperation.Builder {
634
+ val builder = ContentProviderOperation.newInsert(Data.CONTENT_URI)
635
+ if (rawIndex != null) {
636
+ builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)
637
+ } else {
638
+ builder.withValue(Data.RAW_CONTACT_ID, rawId)
639
+ }
640
+ return builder
641
+ }
642
+
643
+ // Sets the row's TYPE column, adding LABEL only for custom types.
644
+ fun ContentProviderOperation.Builder.withType(
645
+ typed: TypedLabel,
646
+ typeColumn: String,
647
+ labelColumn: String
648
+ ): ContentProviderOperation.Builder {
649
+ withValue(typeColumn, typed.type)
650
+ if (typed.label != null) withValue(labelColumn, typed.label)
651
+ return this
652
+ }
653
+
654
+ contact.optJSONObject("name")?.let { name ->
655
+ ops.add(
656
+ newInsert()
657
+ .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
658
+ .withValue(StructuredName.DISPLAY_NAME, name.stringOrNull("formatted") ?: contact.stringOrEmpty("displayName"))
659
+ .withValue(StructuredName.FAMILY_NAME, name.stringOrEmpty("familyName"))
660
+ .withValue(StructuredName.GIVEN_NAME, name.stringOrEmpty("givenName"))
661
+ .withValue(StructuredName.MIDDLE_NAME, name.stringOrEmpty("middleName"))
662
+ .withValue(StructuredName.PREFIX, name.stringOrEmpty("honorificPrefix"))
663
+ .withValue(StructuredName.SUFFIX, name.stringOrEmpty("honorificSuffix"))
664
+ .build()
665
+ )
666
+ }
667
+
668
+ forEachField(contact, "phoneNumbers") { value, type, pref ->
669
+ newInsert()
670
+ .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
671
+ .withValue(Phone.NUMBER, value)
672
+ .withType(phoneType(type), Phone.TYPE, Phone.LABEL)
673
+ .withValue(Data.IS_SUPER_PRIMARY, if (pref) 1 else 0)
674
+ .build()
675
+ }.forEach { ops.add(it) }
676
+
677
+ forEachField(contact, "emails") { value, type, pref ->
678
+ newInsert()
679
+ .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
680
+ .withValue(Email.ADDRESS, value)
681
+ .withType(emailType(type), Email.TYPE, Email.LABEL)
682
+ .withValue(Data.IS_SUPER_PRIMARY, if (pref) 1 else 0)
683
+ .build()
684
+ }.forEach { ops.add(it) }
685
+
686
+ forEachField(contact, "ims") { value, type, pref ->
687
+ newInsert()
688
+ .withValue(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE)
689
+ .withValue(Im.DATA, value)
690
+ .withType(imProtocol(type), Im.PROTOCOL, Im.CUSTOM_PROTOCOL)
691
+ .withValue(Data.IS_SUPER_PRIMARY, if (pref) 1 else 0)
692
+ .build()
693
+ }.forEach { ops.add(it) }
694
+
695
+ forEachField(contact, "urls") { value, type, pref ->
696
+ newInsert()
697
+ .withValue(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE)
698
+ .withValue(Website.URL, value)
699
+ .withType(websiteType(type), Website.TYPE, Website.LABEL)
700
+ .withValue(Data.IS_SUPER_PRIMARY, if (pref) 1 else 0)
701
+ .build()
702
+ }.forEach { ops.add(it) }
703
+
704
+ contact.optJSONArray("addresses")?.let { arr ->
705
+ for (i in 0 until arr.length()) {
706
+ val a = arr.optJSONObject(i) ?: continue
707
+ ops.add(
708
+ newInsert()
709
+ .withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE)
710
+ .withType(addressType(a.stringOrEmpty("type")), StructuredPostal.TYPE, StructuredPostal.LABEL)
711
+ .withValue(StructuredPostal.FORMATTED_ADDRESS, a.stringOrEmpty("formatted"))
712
+ .withValue(StructuredPostal.STREET, a.stringOrEmpty("streetAddress"))
713
+ .withValue(StructuredPostal.CITY, a.stringOrEmpty("locality"))
714
+ .withValue(StructuredPostal.REGION, a.stringOrEmpty("region"))
715
+ .withValue(StructuredPostal.POSTCODE, a.stringOrEmpty("postalCode"))
716
+ .withValue(StructuredPostal.COUNTRY, a.stringOrEmpty("country"))
717
+ .withValue(Data.IS_SUPER_PRIMARY, if (a.optBoolean("pref")) 1 else 0)
718
+ .build()
719
+ )
720
+ }
721
+ }
722
+
723
+ contact.optJSONArray("organizations")?.let { arr ->
724
+ for (i in 0 until arr.length()) {
725
+ val o = arr.optJSONObject(i) ?: continue
726
+ ops.add(
727
+ newInsert()
728
+ .withValue(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
729
+ .withType(organizationType(o.stringOrEmpty("type")), Organization.TYPE, Organization.LABEL)
730
+ .withValue(Organization.COMPANY, o.stringOrEmpty("name"))
731
+ .withValue(Organization.DEPARTMENT, o.stringOrEmpty("department"))
732
+ .withValue(Organization.TITLE, o.stringOrEmpty("title"))
733
+ .withValue(Data.IS_SUPER_PRIMARY, if (o.optBoolean("pref")) 1 else 0)
734
+ .build()
735
+ )
736
+ }
737
+ }
738
+
739
+ contact.stringOrNull("nickname")?.takeIf { it.isNotEmpty() }?.let {
740
+ ops.add(
741
+ newInsert()
742
+ .withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
743
+ .withValue(Nickname.NAME, it)
744
+ .build()
745
+ )
746
+ }
747
+
748
+ contact.stringOrNull("note")?.takeIf { it.isNotEmpty() }?.let {
749
+ ops.add(
750
+ newInsert()
751
+ .withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE)
752
+ .withValue(Note.NOTE, it)
753
+ .build()
754
+ )
755
+ }
756
+
757
+ if (contact.opt("birthday") is Number) {
758
+ val ms = contact.optLong("birthday")
759
+ val formatted = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date(ms))
760
+ ops.add(
761
+ newInsert()
762
+ .withValue(Data.MIMETYPE, Event.CONTENT_ITEM_TYPE)
763
+ .withValue(Event.TYPE, Event.TYPE_BIRTHDAY)
764
+ .withValue(Event.START_DATE, formatted)
765
+ .build()
766
+ )
767
+ }
768
+
769
+ contact.optJSONArray("photos")?.let { arr ->
770
+ photoBytes(arr.optJSONObject(0))?.let { bytes ->
771
+ ops.add(
772
+ newInsert()
773
+ .withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE)
774
+ .withValue(Photo.PHOTO, bytes)
775
+ .build()
776
+ )
777
+ }
778
+ }
779
+ }
780
+
781
+ /**
782
+ * Decodes the first photo entry into image bytes: `base64` values are
783
+ * decoded directly; `url` values are read from local `file://` /
784
+ * `content://` URIs.
785
+ */
786
+ private fun photoBytes(photo: JSONObject?): ByteArray? {
787
+ val value = photo?.stringOrNull("value")
788
+ if (value.isNullOrEmpty()) return null
789
+ return try {
790
+ if ((photo.stringOrNull("type") ?: "url").lowercase(Locale.getDefault()) == "base64") {
791
+ Base64.decode(value, Base64.DEFAULT)
792
+ } else {
793
+ context.contentResolver.openInputStream(Uri.parse(value))?.use { it.readBytes() }
794
+ }
795
+ } catch (e: Exception) {
796
+ null
797
+ }
798
+ }
799
+
800
+ private fun forEachField(
801
+ contact: JSONObject,
802
+ key: String,
803
+ build: (value: String, type: String, pref: Boolean) -> ContentProviderOperation
804
+ ): List<ContentProviderOperation> {
805
+ val arr = contact.optJSONArray(key) ?: return emptyList()
806
+ val out = ArrayList<ContentProviderOperation>()
807
+ for (i in 0 until arr.length()) {
808
+ val f = arr.optJSONObject(i) ?: continue
809
+ val value = f.stringOrNull("value")
810
+ if (value.isNullOrEmpty()) continue
811
+ out.add(build(value, f.stringOrNull("type") ?: "other", f.optBoolean("pref")))
812
+ }
813
+ return out
814
+ }
815
+
816
+ // ---------------------------------------------------------------------
817
+ // Remove
818
+ // ---------------------------------------------------------------------
819
+
820
+ /**
821
+ * Removes the aggregated contact identified by [contactId]. Returns false
822
+ * when no contact has that id.
823
+ */
824
+ fun remove(contactId: String): Boolean {
825
+ val id = contactId.toLongOrNull() ?: return false
826
+ val uri: Uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id)
827
+ return context.contentResolver.delete(uri, null, null) > 0
828
+ }
829
+
830
+ // ---------------------------------------------------------------------
831
+ // Wire type <-> provider TYPE_* constant mapping
832
+ // ---------------------------------------------------------------------
833
+
834
+ /** A provider TYPE_* value plus the custom label when TYPE_CUSTOM. */
835
+ private data class TypedLabel(val type: Int, val label: String? = null)
836
+
837
+ private fun phoneType(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
838
+ "home" -> TypedLabel(Phone.TYPE_HOME)
839
+ "mobile", "cell" -> TypedLabel(Phone.TYPE_MOBILE)
840
+ "work" -> TypedLabel(Phone.TYPE_WORK)
841
+ "work fax" -> TypedLabel(Phone.TYPE_FAX_WORK)
842
+ "home fax" -> TypedLabel(Phone.TYPE_FAX_HOME)
843
+ "fax" -> TypedLabel(Phone.TYPE_FAX_WORK)
844
+ "pager" -> TypedLabel(Phone.TYPE_PAGER)
845
+ "main" -> TypedLabel(Phone.TYPE_MAIN)
846
+ "callback" -> TypedLabel(Phone.TYPE_CALLBACK)
847
+ "car" -> TypedLabel(Phone.TYPE_CAR)
848
+ "company main" -> TypedLabel(Phone.TYPE_COMPANY_MAIN)
849
+ "other fax" -> TypedLabel(Phone.TYPE_OTHER_FAX)
850
+ "radio" -> TypedLabel(Phone.TYPE_RADIO)
851
+ "telex" -> TypedLabel(Phone.TYPE_TELEX)
852
+ "tty tdd" -> TypedLabel(Phone.TYPE_TTY_TDD)
853
+ "work mobile" -> TypedLabel(Phone.TYPE_WORK_MOBILE)
854
+ "work pager" -> TypedLabel(Phone.TYPE_WORK_PAGER)
855
+ "assistant" -> TypedLabel(Phone.TYPE_ASSISTANT)
856
+ "mms" -> TypedLabel(Phone.TYPE_MMS)
857
+ "isdn" -> TypedLabel(Phone.TYPE_ISDN)
858
+ "other" -> TypedLabel(Phone.TYPE_OTHER)
859
+ else -> TypedLabel(Phone.TYPE_CUSTOM, type)
860
+ }
861
+
862
+ private fun emailType(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
863
+ "home" -> TypedLabel(Email.TYPE_HOME)
864
+ "work" -> TypedLabel(Email.TYPE_WORK)
865
+ "mobile" -> TypedLabel(Email.TYPE_MOBILE)
866
+ "other" -> TypedLabel(Email.TYPE_OTHER)
867
+ else -> TypedLabel(Email.TYPE_CUSTOM, type)
868
+ }
869
+
870
+ private fun addressType(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
871
+ "home" -> TypedLabel(StructuredPostal.TYPE_HOME)
872
+ "work" -> TypedLabel(StructuredPostal.TYPE_WORK)
873
+ "other" -> TypedLabel(StructuredPostal.TYPE_OTHER)
874
+ else -> TypedLabel(StructuredPostal.TYPE_CUSTOM, type)
875
+ }
876
+
877
+ private fun organizationType(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
878
+ "work" -> TypedLabel(Organization.TYPE_WORK)
879
+ "other" -> TypedLabel(Organization.TYPE_OTHER)
880
+ else -> TypedLabel(Organization.TYPE_CUSTOM, type)
881
+ }
882
+
883
+ private fun websiteType(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
884
+ "homepage" -> TypedLabel(Website.TYPE_HOMEPAGE)
885
+ "blog" -> TypedLabel(Website.TYPE_BLOG)
886
+ "profile" -> TypedLabel(Website.TYPE_PROFILE)
887
+ "home" -> TypedLabel(Website.TYPE_HOME)
888
+ "work" -> TypedLabel(Website.TYPE_WORK)
889
+ "ftp" -> TypedLabel(Website.TYPE_FTP)
890
+ "other" -> TypedLabel(Website.TYPE_OTHER)
891
+ else -> TypedLabel(Website.TYPE_CUSTOM, type)
892
+ }
893
+
894
+ private fun imProtocol(type: String): TypedLabel = when (type.lowercase(Locale.getDefault())) {
895
+ "aim" -> TypedLabel(Im.PROTOCOL_AIM)
896
+ "msn" -> TypedLabel(Im.PROTOCOL_MSN)
897
+ "yahoo" -> TypedLabel(Im.PROTOCOL_YAHOO)
898
+ "skype" -> TypedLabel(Im.PROTOCOL_SKYPE)
899
+ "qq" -> TypedLabel(Im.PROTOCOL_QQ)
900
+ "google talk", "gtalk" -> TypedLabel(Im.PROTOCOL_GOOGLE_TALK)
901
+ "icq" -> TypedLabel(Im.PROTOCOL_ICQ)
902
+ "jabber" -> TypedLabel(Im.PROTOCOL_JABBER)
903
+ else -> TypedLabel(Im.PROTOCOL_CUSTOM, type)
904
+ }
905
+
906
+ // ---------------------------------------------------------------------
907
+ // Field -> mimetype mapping (used for targeted filter searches)
908
+ // ---------------------------------------------------------------------
909
+
910
+ private fun fieldToMimeType(field: String): String? = when (field) {
911
+ "displayName", "name", "familyName", "givenName", "middleName",
912
+ "honorificPrefix", "honorificSuffix", "formatted" -> StructuredName.CONTENT_ITEM_TYPE
913
+ "phoneNumbers" -> Phone.CONTENT_ITEM_TYPE
914
+ "emails" -> Email.CONTENT_ITEM_TYPE
915
+ "addresses", "streetAddress", "locality", "region", "postalCode", "country" -> StructuredPostal.CONTENT_ITEM_TYPE
916
+ "ims" -> Im.CONTENT_ITEM_TYPE
917
+ "organizations", "department", "title" -> Organization.CONTENT_ITEM_TYPE
918
+ "urls" -> Website.CONTENT_ITEM_TYPE
919
+ "nickname" -> Nickname.CONTENT_ITEM_TYPE
920
+ "note" -> Note.CONTENT_ITEM_TYPE
921
+ "birthday" -> Event.CONTENT_ITEM_TYPE
922
+ else -> null
923
+ }
924
+ }