package com.cottondb.android.platform import android.Manifest import android.content.ContentResolver import android.content.Context import android.content.pm.PackageManager import android.os.CancellationSignal import android.os.OperationCanceledException import android.provider.ContactsContract import android.util.AtomicFile import android.provider.Settings import com.cottondb.android.day.people.ContactsAccess import com.cottondb.android.day.people.ContactsSource import com.cottondb.android.day.people.DeviceContact import com.cottondb.android.day.people.DeviceContactBirthday import java.io.File import java.util.UUID import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ensureActive import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext /** Records whether this installation has made an explicit READ_CONTACTS request. */ interface ContactsPermissionMemory { fun requestedBefore(): Boolean fun recordRequestStarted() fun recordResult(granted: Boolean) } interface ContactsPermissionChecker { fun granted(): Boolean } class AndroidContactsPermissionChecker(context: Context) : ContactsPermissionChecker { private val application = context.applicationContext override fun granted(): Boolean = application.checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED } class AndroidContactsPermissionMemory(context: Context) : ContactsPermissionMemory { private val preferences = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE) override fun requestedBefore(): Boolean = preferences.getBoolean(REQUESTED, false) override fun recordRequestStarted() { preferences.edit().putBoolean(REQUESTED, true).apply() } override fun recordResult(granted: Boolean) { // A result, including refusal, is proof that this was not a first visit. preferences.edit().putBoolean(REQUESTED, true).apply() } private companion object { const val FILE = "contacts-permission-v1" const val REQUESTED = "requested" } } /** Synchronous Android provider boundary, isolated so tests never query a real address book. */ interface AndroidContactsDirectory { /** Must close every cursor before it returns; [signal] is cancelled with the calling coroutine. */ fun read(signal: CancellationSignal): List } /** * Namespace identity per physical Android device before appending its lookup key. Rust's unique * `device_contact_id` index is workspace-wide, so the raw numeric `Contacts._ID` would collide * between two Android devices. `LOOKUP_KEY` survives contact aggregation better than that row id. */ interface AndroidContactIdentity { fun deviceContactId(lookupKey: String): String } class AndroidContactIdentityNamespace private constructor( private val androidId: () -> String?, private val file: File, ) : AndroidContactIdentity { constructor(context: Context) : this( androidId = { Settings.Secure.getString(context.applicationContext.contentResolver, Settings.Secure.ANDROID_ID) }, file = File(context.applicationContext.noBackupFilesDir, FILE_NAME), ) internal constructor(androidId: () -> String?, file: File, testOnly: Unit = Unit) : this(androidId, file) private val atomic = AtomicFile(file) private val lock = locks.computeIfAbsent(file.canonicalPath) { ReentrantLock() } @Volatile private var cached: String? = null override fun deviceContactId(lookupKey: String): String { val stableLookupKey = lookupKey.trim().takeIf(String::isNotEmpty) ?: throw IllegalArgumentException("An Android contact needs a lookup key.") return "android:${namespace()}:$stableLookupKey" } /** Resolved once and cached, so one provider read never reopens preferences per contact. */ private fun namespace(): String = cached ?: lock.withLock { cached ?: (androidId()?.trim()?.takeIf(String::isNotEmpty) ?: loadOrCreateFallback()).also { cached = it } } private fun loadOrCreateFallback(): String { if (!file.exists() && !File(file.path + ".bak").exists()) return writeNewNamespace() val existing = runCatching { atomic.openRead().bufferedReader(Charsets.UTF_8).use { it.readText().trim() } } .getOrElse { throw IllegalStateException("Android contact namespace could not be read.", it) } return existing.takeIf(String::isNotBlank) ?: throw IllegalStateException("Android contact namespace is malformed.") } private fun writeNewNamespace(): String { val parent = requireNotNull(file.parentFile) { "Android contact namespace has no parent." } require(parent.exists() || parent.mkdirs()) { "Android contact namespace directory could not be created." } val value = UUID.randomUUID().toString() val stream = atomic.startWrite() try { stream.write(value.toByteArray(Charsets.UTF_8)) stream.flush() atomic.finishWrite(stream) return value } catch (failure: Throwable) { atomic.failWrite(stream) throw IllegalStateException("Android contact namespace could not be saved.", failure) } } private companion object { const val FILE_NAME = "contacts-device-identity-v1" val locks = ConcurrentHashMap() } } /** * Permission-free construction; permission prompting is owned by the Activity Result seam. * The source checks permission again before querying, because a grant can be revoked while the * import screen remains open. */ class AndroidContactsSource( context: Context, private val permissionMemory: ContactsPermissionMemory = AndroidContactsPermissionMemory(context), private val permissionChecker: ContactsPermissionChecker = AndroidContactsPermissionChecker(context), private val directory: AndroidContactsDirectory = AndroidContactsContractDirectory( context.applicationContext.contentResolver, AndroidContactIdentityNamespace(context.applicationContext), ), private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO, ) : ContactsSource { override suspend fun currentAccess(): ContactsAccess = when { permissionChecker.granted() -> ContactsAccess.Authorized permissionMemory.requestedBefore() -> ContactsAccess.Denied else -> ContactsAccess.NotDetermined } override suspend fun readContacts(): List { if (currentAccess() != ContactsAccess.Authorized) { throw SecurityException("READ_CONTACTS is not granted.") } return withContext(ioDispatcher) { val signal = CancellationSignal() try { suspendCancellableCoroutine { continuation -> continuation.invokeOnCancellation { signal.cancel() } try { val contacts = directory.read(signal) if (continuation.isActive) continuation.resume(contacts) { _, _, _ -> } } catch (cancelled: OperationCanceledException) { if (signal.isCanceled) continuation.cancel(CancellationException("Contacts query was cancelled.").also { it.initCause(cancelled) }) else continuation.resumeWith(Result.failure(cancelled)) } catch (failure: Throwable) { continuation.resumeWith(Result.failure(failure)) } } } finally { signal.cancel() } } } } /** The real resolver reader. It asks only for fields Cotton's import contract carries. */ class AndroidContactsContractDirectory( private val resolver: ContentResolver, private val identity: AndroidContactIdentity, ) : AndroidContactsDirectory { override fun read(signal: CancellationSignal): List { val factsByContact = linkedMapOf() (resolver.query( ContactsContract.Data.CONTENT_URI, DATA_PROJECTION, "${ContactsContract.Data.MIMETYPE} IN (${MIME_TYPES.joinToString(",") { "?" }})", MIME_TYPES, null, signal, ) ?: throw IllegalStateException("Android contacts data query returned no cursor.")).use { cursor -> val contactId = cursor.getColumnIndexOrThrow(ContactsContract.Data.CONTACT_ID) val mimeType = cursor.getColumnIndexOrThrow(ContactsContract.Data.MIMETYPE) val data1 = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA1) val data4 = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA4) val data7 = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA7) val data2 = cursor.getColumnIndexOrThrow(ContactsContract.Data.DATA2) while (cursor.moveToNext()) { if (signal.isCanceled) throw CancellationException("Contacts query was cancelled.") val facts = factsByContact.getOrPut(cursor.getLong(contactId)) { MutableContactFacts() } when (cursor.getString(mimeType)) { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE -> facts.phones.add(cursor.getString(data1)) ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE -> facts.emails.add(cursor.getString(data1)) ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE -> { facts.org = facts.org ?: cleaned(cursor.getString(data1)) facts.roleTitle = facts.roleTitle ?: cleaned(cursor.getString(data4)) } ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE -> { facts.city = facts.city ?: cleaned(cursor.getString(data7)) } ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE -> { if (cursor.getInt(data2) == ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) { facts.birthday = facts.birthday ?: parseAndroidBirthday(cursor.getString(data1)) } } } } } return buildList { (resolver.query( ContactsContract.Contacts.CONTENT_URI, CONTACT_PROJECTION, null, null, "${ContactsContract.Contacts.SORT_KEY_PRIMARY} ASC", signal, ) ?: throw IllegalStateException("Android contacts query returned no cursor.")).use { cursor -> val rowId = cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID) val lookupKey = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY) val primaryName = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY) val fallbackName = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME) while (cursor.moveToNext()) { if (signal.isCanceled) throw CancellationException("Contacts query was cancelled.") val name = cleaned(cursor.getString(primaryName)) ?: cleaned(cursor.getString(fallbackName)) ?: continue val lookup = cleaned(cursor.getString(lookupKey)) ?: continue val facts = factsByContact[cursor.getLong(rowId)] ?: MutableContactFacts() add(DeviceContact( id = identity.deviceContactId(lookup), fullName = name, phones = facts.phones.values(), emails = facts.emails.values(), org = facts.org, roleTitle = facts.roleTitle, city = facts.city, birthday = facts.birthday, )) } } } } private class MutableContactFacts { val phones = OrderedText() val emails = OrderedText() var org: String? = null var roleTitle: String? = null var city: String? = null var birthday: DeviceContactBirthday? = null } private class OrderedText { private val values = mutableListOf() fun add(value: String?) { val cleaned = cleaned(value) ?: return if (cleaned !in values) values += cleaned } fun values(): List = values.toList() } private companion object { val CONTACT_PROJECTION = arrayOf( ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.DISPLAY_NAME, ) val DATA_PROJECTION = arrayOf( ContactsContract.Data.CONTACT_ID, ContactsContract.Data.MIMETYPE, ContactsContract.Data.DATA1, ContactsContract.Data.DATA2, ContactsContract.Data.DATA4, ContactsContract.Data.DATA7, ) val MIME_TYPES = arrayOf( ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, ) } } private fun cleaned(value: String?): String? = value?.trim()?.takeIf(String::isNotEmpty) /** Android Event.START_DATE carries either yyyy-MM-dd or --MM-dd. Invalid partial dates are absent. */ internal fun parseAndroidBirthday(value: String?): DeviceContactBirthday? { val text = value?.trim() ?: return null val (year, monthText, dayText) = if (text.startsWith("--")) { val parts = text.removePrefix("--").split('-') if (parts.size != 2) return null Triple(null, parts[0], parts[1]) } else { val parts = text.split('-') if (parts.size != 3 || parts[0].length != 4 || !parts[0].all(Char::isDigit)) return null val parsedYear = parts[0].toIntOrNull()?.takeIf { it > 0 } ?: return null Triple(parsedYear.takeUnless { it == 1604 }, parts[1], parts[2]) } val month = monthText.toIntOrNull() ?: return null val day = dayText.toIntOrNull() ?: return null if (runCatching { java.time.LocalDate.of(year ?: 2000, month, day) }.isFailure) return null return DeviceContactBirthday(month, day, year) }