Cotton code
251 lines · 11.7 KB · KotlinRaw
package com.cottondb.android.platformimport android.app.AlarmManagerimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.content.pm.PackageManagerimport android.net.Uriimport android.os.Buildimport com.cottondb.android.MainActivityimport com.cottondb.android.day.alarms.Alarmimport com.cottondb.android.day.alarms.AlarmReconcileInputimport com.cottondb.android.day.alarms.AlarmReconcilePlanimport com.cottondb.android.day.alarms.AlarmScheduleimport com.cottondb.android.day.alarms.androidAlarmKeyimport com.cottondb.android.day.alarms.commitAcceptedSchedulesimport com.cottondb.android.day.alarms.reconcileAlarmsimport com.cottondb.android.reminders.NotificationPermissionimport com.cottondb.android.reminders.NotificationPrefsimport java.time.Clockimport java.time.ZoneIdsealed interface AlarmScheduleOutcome {    data class Applied(val scheduled: Int, val cancelled: Int, val firedOnce: List<String>) : AlarmScheduleOutcome    data class Partial(        val scheduled: Int,        val cancelled: Int,        val failed: Int,        val message: String,        val firedOnce: List<String>,    ) : AlarmScheduleOutcome    data class Refused(val message: String) : AlarmScheduleOutcome}/** Platform boundary so instrumentation tests can use a fake without creating real wake-up alarms. */interface ExactAlarmPlatform {    fun exactAlarmAllowed(): Boolean    fun held(key: String, entry: AndroidAlarmLedgerEntry): Boolean    fun schedule(schedule: AlarmSchedule): Boolean    fun cancel(key: String, entry: AndroidAlarmLedgerEntry?)}/** * Turns the core's one-shot plan into AlarmManager requests. Every platform call and ledger update * is serialized. A `FLAG_NO_CREATE` PendingIntent is only evidence that this backend still owns * its identity; Android offers no API that proves it remains scheduled. */class AndroidAlarmScheduler(    private val ledgerStore: AndroidAlarmLedgerStore,    private val platform: ExactAlarmPlatform,    private val clock: Clock,) {    fun reconcile(        alarms: List<Alarm>,        zoneId: ZoneId,        prefs: NotificationPrefs,        notificationPermission: NotificationPermission,    ): AlarmScheduleOutcome = ledgerStore.exclusive {        val boot = when (val value = ledgerStore.currentBootCount()) {            is BootCountRead.Available -> value.value            is BootCountRead.Unreadable -> return@exclusive AlarmScheduleOutcome.Refused(value.message)        }        var bootInvalidated = false        val snapshot = when (val read = ledgerStore.read()) {            AlarmLedgerRead.Missing -> AndroidAlarmLedgerSnapshot(boot, emptyMap())            is AlarmLedgerRead.Available -> {                if (read.snapshot.bootCount != boot) {                    bootInvalidated = true                    ledgerStore.invalidateForCurrentBoot().getOrElse { failure ->                        return@exclusive AlarmScheduleOutcome.Refused(                            failure.message ?: "Android alarm history could not be retained after restart.",                        )                    }                } else {                    read.snapshot                }            }            is AlarmLedgerRead.Unreadable -> return@exclusive AlarmScheduleOutcome.Refused(read.message)        }        val known = snapshot.entries.mapKeys { (id, _) -> androidAlarmKey(id) }        // A receiver has atomically recorded delivery before this pass. Its PendingIntent may        // still be discoverable even though the one-shot alarm fired, so delivery wins over that        // incomplete platform observation and lets core disable/re-arm exactly once.        val held = if (bootInvalidated) {            emptySet()        } else {            runCatching {                known.filter { (key, entry) -> !entry.delivered && platform.held(key, entry) }.keys            }.getOrElse { failure ->                return@exclusive AlarmScheduleOutcome.Refused(failure.message ?: "Android alarm state could not be read.")            }        }        val deliveryAllowed = prefs.enabled(com.cottondb.android.reminders.NotificationKind.Alarm) &&            notificationPermission == NotificationPermission.Granted        val canExact = runCatching { platform.exactAlarmAllowed() }.getOrElse { failure ->            return@exclusive AlarmScheduleOutcome.Refused(failure.message ?: "Android exact-alarm access could not be read.")        }        val canSchedule = deliveryAllowed && canExact        val plan = reconcileAlarms(            AlarmReconcileInput(                alarms = alarms,                actualHeldIds = held,                ledger = snapshot.coreLedger(),                canSchedule = canSchedule,                now = clock.instant(),                zoneId = zoneId,                deliveredIds = snapshot.entries.filterValues { it.delivered }.keys,            ),        )        apply(plan, snapshot, boot)    }    private fun apply(        plan: AlarmReconcilePlan,        prior: AndroidAlarmLedgerSnapshot,        boot: Int,    ): AlarmScheduleOutcome {        // A delivered request may retain its PendingIntent identity after AlarmManager consumed        // it. Retiring its ledger row must retire that identity too, even when it is not held.        val cancellations = (plan.cancel + prior.entries.keys.filterNot { it in plan.nextLedger }.map(::androidAlarmKey)).distinct()        val cancelFailure = runCatching {            cancellations.forEach { key -> platform.cancel(key, prior.entries[key.removePrefix("cotton:alarm:")]) }        }.exceptionOrNull()        if (cancelFailure != null) {            return AlarmScheduleOutcome.Refused(cancelFailure.message ?: "Android alarms could not be cancelled.")        }        val accepted = linkedSetOf<String>()        val failures = mutableListOf<String>()        plan.schedule.forEach { schedule ->            val attempt = runCatching {                prior.entries[schedule.id]?.let { old -> platform.cancel(schedule.key, old) }                platform.schedule(schedule)            }            if (attempt.getOrDefault(false)) {                accepted += schedule.id            } else {                failures += attempt.exceptionOrNull()?.message                    ?: "Alarm ${schedule.id} was declined by Android."            }        }        val committed = plan.commitAcceptedSchedules(accepted)        val updated = AndroidAlarmLedgerSnapshot(boot, prior.entries).withCoreLedger(committed)        val write = ledgerStore.write(updated)        if (write.isFailure) {            // Do not leave a request the receiver cannot authenticate in the durable ledger.            plan.schedule.filter { it.id in accepted }.forEach { schedule ->                platform.cancel(schedule.key, committed[schedule.id]?.let { entry ->                    AndroidAlarmLedgerEntry(entry.signature, entry.firesAt, delivered = false)                })            }            return AlarmScheduleOutcome.Refused(write.exceptionOrNull()?.message ?: "Alarm ledger could not be stored.")        }        return if (failures.isEmpty()) {            AlarmScheduleOutcome.Applied(accepted.size, cancellations.size, plan.firedOnce)        } else {            AlarmScheduleOutcome.Partial(                scheduled = accepted.size,                cancelled = cancellations.size,                failed = failures.size,                message = failures.joinToString(" "),                firedOnce = plan.firedOnce,            )        }    }}/** Production AlarmManager implementation. Root wires the receiver declaration separately. */internal class AndroidExactAlarmPlatform(private val context: Context) : ExactAlarmPlatform {    private val manager = context.getSystemService(AlarmManager::class.java)    override fun exactAlarmAllowed(): Boolean =        Build.VERSION.SDK_INT < Build.VERSION_CODES.S || manager.canScheduleExactAlarms()    override fun held(key: String, entry: AndroidAlarmLedgerEntry): Boolean =        pendingIntent(key, entry, PendingIntent.FLAG_NO_CREATE) != null    override fun schedule(schedule: AlarmSchedule): Boolean = runCatching {        val fireToken = alarmFireToken(schedule.signature, schedule.nextOccurrence.toEpochMilli())        val intent = receiverIntent(schedule.key, fireToken, schedule.nextOccurrence.toEpochMilli(), schedule.label, schedule.sound)        val operation = PendingIntent.getBroadcast(context, requestCode(schedule.key), intent, pendingFlags(PendingIntent.FLAG_UPDATE_CURRENT))        val show = PendingIntent.getActivity(            context,            requestCode("show:${schedule.key}"),            Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)                .setData(Uri.Builder().scheme("cotton").authority("alarm").appendPath(schedule.id).build())                .putExtra("kind", "alarm")                .putExtra("id", schedule.id),            pendingFlags(PendingIntent.FLAG_UPDATE_CURRENT),        )        manager.setAlarmClock(AlarmManager.AlarmClockInfo(schedule.nextOccurrence.toEpochMilli(), show), operation)        true    }.getOrDefault(false)    override fun cancel(key: String, entry: AndroidAlarmLedgerEntry?) {        entry ?: return        pendingIntent(key, entry, PendingIntent.FLAG_NO_CREATE)?.let { operation ->            manager.cancel(operation)            operation.cancel()        }    }    private fun pendingIntent(key: String, entry: AndroidAlarmLedgerEntry, extraFlags: Int): PendingIntent? = PendingIntent.getBroadcast(        context,        requestCode(key),        receiverIntent(key, alarmFireToken(entry.signature, requireNotNull(entry.firesAt)), entry.firesAt, null, null),        pendingFlags(extraFlags),    )    private fun receiverIntent(key: String, fireToken: String?, firesAt: Long?, label: String?, sound: Boolean?): Intent =        Intent(context, AndroidAlarmReceiver::class.java)            .setAction(ACTION_FIRE)            .setData(Uri.Builder().scheme("cotton").authority("alarm").appendPath(key).appendPath(fireToken.orEmpty()).build())            .putExtra(EXTRA_KEY, key)            .apply {                fireToken?.let { putExtra(EXTRA_FIRE_TOKEN, it) }                firesAt?.let { putExtra(EXTRA_FIRES_AT, it) }                label?.let { putExtra(EXTRA_LABEL, it) }                sound?.let { putExtra(EXTRA_SOUND, it) }            }    private fun pendingFlags(flag: Int): Int = flag or PendingIntent.FLAG_IMMUTABLE    private fun requestCode(key: String): Int = key.hashCode() and Int.MAX_VALUE    companion object {        const val ACTION_FIRE = "com.cottondb.android.action.FIRE_ALARM"        const val EXTRA_KEY = "alarmKey"        const val EXTRA_FIRE_TOKEN = "alarmFireToken"        const val EXTRA_FIRES_AT = "alarmFiresAt"        const val EXTRA_LABEL = "alarmLabel"        const val EXTRA_SOUND = "alarmSound"    }}fun alarmFireToken(signature: String, firesAt: Long): String = "$signature@$firesAt"/** Reads Android's current notification capability without ever prompting for it. */fun notificationPermission(context: Context, prefs: NotificationPrefs): NotificationPermission {    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {        if (context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {            return if (prefs.askedAt == null) NotificationPermission.Undetermined else NotificationPermission.Denied        }    }    return if (context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()) {        NotificationPermission.Granted    } else {        NotificationPermission.Denied    }}