Cotton code
202 lines · 10.9 KB · KotlinRaw
package com.cottondb.android.platformimport android.app.AlarmManagerimport android.app.Notificationimport android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.BroadcastReceiverimport android.content.Intentimport android.net.Uriimport android.util.Logimport com.cottondb.android.MainActivityimport com.cottondb.android.Rimport com.cottondb.android.reminders.DesiredReminderimport com.cottondb.android.reminders.NotificationKindimport com.cottondb.android.reminders.ReminderCentreimport java.io.Fileimport java.io.FileOutputStreamimport java.nio.charset.StandardCharsetsimport java.nio.channels.FileChannelimport java.nio.file.Filesimport java.nio.file.StandardCopyOptionimport java.nio.file.StandardOpenOptionimport java.time.Instantimport java.util.concurrent.ConcurrentHashMapimport kotlinx.coroutines.launchimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.longimport kotlinx.serialization.json.put/** Inexact, idle-permitted, local reminder scheduling. It never requests exact-alarm access. */class AndroidReminderCentre private constructor(    private val ledger: ReminderLedger,    private val platform: ReminderPlatform,) : ReminderCentre {    constructor(context: Context) : this(        ReminderLedger(File(context.noBackupFilesDir, LEDGER_FILE)),        AndroidReminderPlatform(context.applicationContext),    )    override suspend fun heldIdentifiers(): List<String> = ledger.identifiers()    override suspend fun cancel(identifiers: List<String>) {        identifiers.distinct().forEach { identifier ->            ledger.transaction { transaction ->                check(transaction.remove(identifier)) { "The reminder ledger could not record cancellation." }                platform.cancel(identifier)            }        }    }    override suspend fun schedule(reminders: List<DesiredReminder>): Int {        var accepted = 0        for (reminder in reminders) {            val row = PendingReminder.from(reminder) ?: continue            // A failed durable write is a failed schedule: never leave an alarm            // that a restarted process cannot know to cancel.            val scheduled = ledger.transaction { transaction ->                if (!transaction.put(row)) return@transaction false                try {                    platform.schedule(row)                    true                } catch (_: RuntimeException) {                    check(transaction.remove(row.identifier)) { "The reminder ledger could not roll back scheduling." }                    false                }            }            if (scheduled) accepted += 1        }        return accepted    }    /** A fired alarm is stale unless its complete durable row still exists. */    fun deliver(identifier: String) {        ledger.transaction { transaction ->            val row = transaction.take(identifier) ?: return@transaction            try {                platform.post(row)            } catch (failure: RuntimeException) {                AndroidReminderRuntime.report("The reminder notification could not be posted.", failure)            }        }    }    /** Alarms vanish on reboot; clear the claim before the runtime reconciles. */    fun clearAfterBoot() = ledger.clear()    companion object {        private const val LEDGER_FILE = "reminders-pending-v1.json"        internal fun withBoundary(ledger: ReminderLedger, platform: ReminderPlatform) =            AndroidReminderCentre(ledger, platform)    }}class AndroidReminderReceiver : BroadcastReceiver() {    override fun onReceive(context: Context, intent: Intent) {        if (intent.action != ACTION_FIRE) return        val identifier = intent.data?.lastPathSegment?.takeIf(String::isNotBlank) ?: return        val pending = goAsync()        receiverScope.launch {            try {                AndroidReminderCentre(context.applicationContext).deliver(identifier)            } catch (failure: Exception) {                AndroidReminderRuntime.report("The reminder notification could not be delivered.", failure)            } finally {                pending.finish()            }        }    }    companion object {        const val ACTION_FIRE = "com.cottondb.cotton.REMINDER_FIRE"        private val receiverScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO)    }}/** Root registers these process callbacks when it owns the app runtime. */object AndroidReminderRuntime {    @Volatile var onError: ((String, Throwable?) -> Unit)? = null    fun report(message: String, failure: Throwable? = null) {        Log.e("CottonReminder", message, failure)        onError?.invoke(message, failure)    }}internal data class PendingReminder(    val identifier: String, val kind: String, val recordId: String, val atMillis: Long, val title: String, val body: String?,) {    companion object {        fun from(value: DesiredReminder): PendingReminder? = try {            PendingReminder(value.identifier, value.kind.wire, value.recordId, Instant.parse(value.at).toEpochMilli(), value.title, value.body)        } catch (_: Exception) { null }    }}/** Process- and file-locked atomically-written no-backup durable pending rows. */internal class ReminderLedger(private val file: File) {    private val lockFile = File(file.parentFile, "${file.name}.lock")    private val lockKey = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)    fun identifiers(): List<String> = transaction { it.identifiers() }    fun put(row: PendingReminder): Boolean = locked { rows -> rows[row.identifier] = row; write(rows) }    fun remove(identifier: String): Boolean = locked { rows -> rows.remove(identifier); write(rows) }    fun take(identifier: String): PendingReminder? = locked { rows ->        val row = rows.remove(identifier) ?: return@locked null        if (write(rows)) row else null    }    fun clear(): Boolean = transaction { it.clear() }    /** One centre operation, including its OS side effect, holds this file's process and OS lock. */    fun <T> transaction(block: (LedgerTransaction) -> T): T = locked { rows -> block(LedgerTransaction(rows)) }    private fun <T> locked(block: (MutableMap<String, PendingReminder>) -> T): T = synchronized(locks.computeIfAbsent(lockKey) { Any() }) {        file.parentFile?.mkdirs()        FileChannel.open(lockFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE).use { channel ->            channel.lock().use { block(read()) }        }    }    inner class LedgerTransaction internal constructor(private val rows: MutableMap<String, PendingReminder>) {        fun put(row: PendingReminder): Boolean { rows[row.identifier] = row; return write(rows) }        fun remove(identifier: String): Boolean { rows.remove(identifier); return write(rows) }        fun take(identifier: String): PendingReminder? { val row = rows.remove(identifier) ?: return null; return if (write(rows)) row else null }        fun identifiers(): List<String> = rows.keys.toList()        fun clear(): Boolean { rows.clear(); return write(rows) }    }    private fun read(): MutableMap<String, PendingReminder> {        if (!file.exists()) return linkedMapOf()        return runCatching {            Json.parseToJsonElement(file.readText()).jsonObject.mapValuesTo(linkedMapOf()) { (id, value) -> decode(id, value.jsonObject) }        }.getOrElse { throw IllegalStateException("The reminder ledger is unreadable.", it) }    }    private fun write(rows: Map<String, PendingReminder>): Boolean = runCatching {        val contents = buildJsonObject { rows.forEach { (id, row) -> put(id, encode(row)) } }.toString().toByteArray(StandardCharsets.UTF_8)        val tmp = File.createTempFile("${file.name}.", ".tmp", file.parentFile)        try { FileOutputStream(tmp).use { it.write(contents); it.fd.sync() }; Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } finally { tmp.delete() }    }.isSuccess    private fun encode(row: PendingReminder) = buildJsonObject { put("kind", row.kind); put("recordId", row.recordId); put("atMillis", row.atMillis); put("title", row.title); row.body?.let { put("body", it) } }    private fun decode(id: String, value: JsonObject) = PendingReminder(id, value["kind"]!!.jsonPrimitive.content, value["recordId"]!!.jsonPrimitive.content, value["atMillis"]!!.jsonPrimitive.long, value["title"]!!.jsonPrimitive.content, value["body"]?.jsonPrimitive?.contentOrNull)    companion object { private val locks = ConcurrentHashMap<String, Any>() }}internal interface ReminderPlatform { fun schedule(row: PendingReminder); fun cancel(identifier: String); fun post(row: PendingReminder) }private class AndroidReminderPlatform(private val context: Context) : ReminderPlatform {    private val alarms = context.getSystemService(AlarmManager::class.java)    private val notifications = context.getSystemService(NotificationManager::class.java)    override fun schedule(row: PendingReminder) { alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, row.atMillis, alarmIntent(row.identifier)) }    override fun cancel(identifier: String) { alarms.cancel(alarmIntent(identifier)); notifications.cancel(identifier, 0) }    override fun post(row: PendingReminder) { ensureChannels(); notifications.notify(row.identifier, 0, notification(row)) }    private fun alarmIntent(id: String) = PendingIntent.getBroadcast(context, 0, Intent(context, AndroidReminderReceiver::class.java).setAction(AndroidReminderReceiver.ACTION_FIRE).setData(identity(id)), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)    private fun notification(row: PendingReminder): Notification = Notification.Builder(context, CHANNEL).setSmallIcon(R.drawable.ic_launcher_monochrome).setContentTitle(row.title).setContentText(row.body).setAutoCancel(true).setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP).setData(identity(row.identifier)).putExtra("kind", row.kind).putExtra("id", row.recordId), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)).build()    private fun ensureChannels() { notifications.createNotificationChannel(NotificationChannel(CHANNEL, "Reminders", NotificationManager.IMPORTANCE_DEFAULT)) }    private fun identity(id: String): Uri = Uri.Builder().scheme("cotton-reminder").authority("pending").appendPath(id).build()    companion object { const val CHANNEL = "cotton-reminders" }}