package com.cottondb.android.platform import android.app.AlarmManager import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.BroadcastReceiver import android.content.Intent import android.net.Uri import android.util.Log import com.cottondb.android.MainActivity import com.cottondb.android.R import com.cottondb.android.reminders.DesiredReminder import com.cottondb.android.reminders.NotificationKind import com.cottondb.android.reminders.ReminderCentre import java.io.File import java.io.FileOutputStream import java.nio.charset.StandardCharsets import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.time.Instant import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long import 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 = ledger.identifiers() override suspend fun cancel(identifiers: List) { 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): 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 = 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 transaction(block: (LedgerTransaction) -> T): T = locked { rows -> block(LedgerTransaction(rows)) } private fun locked(block: (MutableMap) -> 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) { 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 = rows.keys.toList() fun clear(): Boolean { rows.clear(); return write(rows) } } private fun read(): MutableMap { 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): 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() } } 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" } }