Cotton code
131 lines · 6.3 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport android.util.AtomicFileimport com.cottondb.android.reminders.NotificationCategoryimport com.cottondb.android.reminders.NotificationPrefsimport java.io.Fileimport java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.locks.ReentrantLockimport kotlin.concurrent.withLockimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.intOrNullimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitive/** * Device-local notification preferences, kept outside backup alongside the local scheduler. * * Calls are synchronous by design: callers choose their IO dispatcher. Every instance for the * same file shares one lock, so a foreground setting change cannot race a reminder pass in a * recreated process. A missing file is the only case that returns defaults; damaged persisted * preferences are refused so notification choices are never silently changed. */class NotificationPrefsStore private constructor(private val file: File) : NotificationPrefsPersistence {    constructor(context: Context) : this(File(context.noBackupFilesDir, FILE_NAME))    internal constructor(file: File, testOnly: Unit = Unit) : this(file)    private val atomicFile = AtomicFile(file)    private val lock = locks.computeIfAbsent(file.canonicalPath) { ReentrantLock() }    override fun load(): NotificationPrefs = lock.withLock {        if (!file.exists() && !File(file.path + BACKUP_SUFFIX).exists()) return NotificationPrefs()        val text = try {            atomicFile.openRead().bufferedReader(Charsets.UTF_8).use { it.readText() }        } catch (failure: Throwable) {            throw NotificationPrefsPersistenceException("Notification preferences could not be read.", failure)        }        if (text.isEmpty() || text.length > MAX_BYTES) {            throw NotificationPrefsPersistenceException("Notification preferences have an invalid size.")        }        try {            parse(text)        } catch (failure: NotificationPrefsPersistenceException) {            throw failure        } catch (failure: Throwable) {            throw NotificationPrefsPersistenceException("Notification preferences are malformed.", failure)        }    }    override fun save(prefs: NotificationPrefs) = lock.withLock {        val parent = file.parentFile            ?: throw NotificationPrefsPersistenceException("Notification preferences have no parent directory.")        if (!parent.exists() && !parent.mkdirs()) {            throw NotificationPrefsPersistenceException("Notification preferences directory could not be created.")        }        val stream = try {            atomicFile.startWrite()        } catch (failure: Throwable) {            throw NotificationPrefsPersistenceException("Notification preferences could not be opened for writing.", failure)        }        try {            stream.write(serialize(prefs).toByteArray(Charsets.UTF_8))            stream.flush()            // AtomicFile closes only after it has committed the replacement.            atomicFile.finishWrite(stream)        } catch (failure: Throwable) {            atomicFile.failWrite(stream)            throw NotificationPrefsPersistenceException("Notification preferences could not be saved.", failure)        }    }    private fun parse(text: String): NotificationPrefs {        val root = Json.parseToJsonElement(text).jsonObject        require(root.keys == ROOT_KEYS || root.keys == ROOT_KEYS_WITHOUT_ASKED_AT) {            "Notification preferences have unknown or missing fields."        }        val enabled = root.requiredBoolean("enabled")        val categoriesObject = root["categories"]?.jsonObject            ?: throw NotificationPrefsPersistenceException("Notification preference categories are missing.")        require(categoriesObject.keys == NotificationCategory.entries.mapTo(linkedSetOf()) { it.wire }) {            "Notification preference categories are incomplete or unknown."        }        val categories = NotificationCategory.entries.associateWith { category ->            categoriesObject.requiredBoolean(category.wire)        }        val moodHour = root.requiredInt("moodHour")        val askedAt = when (val value = root["askedAt"]) {            null, JsonNull -> null            is JsonPrimitive -> value.takeIf(JsonPrimitive::isString)?.content                ?: throw NotificationPrefsPersistenceException("Notification preference askedAt must be a string or null.")            else -> throw NotificationPrefsPersistenceException("Notification preference askedAt must be a string or null.")        }        return try {            NotificationPrefs(enabled, categories, moodHour, askedAt)        } catch (failure: IllegalArgumentException) {            throw NotificationPrefsPersistenceException("Notification preferences are invalid.", failure)        }    }    private fun serialize(prefs: NotificationPrefs): String = prefs.toJson().toString()    private fun JsonObject.requiredBoolean(key: String): Boolean =        (this[key] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull            ?: throw NotificationPrefsPersistenceException("Notification preference $key must be a boolean.")    private fun JsonObject.requiredInt(key: String): Int =        (this[key] as? JsonPrimitive)?.takeIf { !it.isString }?.intOrNull            ?: throw NotificationPrefsPersistenceException("Notification preference $key must be an integer.")    private companion object {        const val FILE_NAME = "notification-prefs.json"        const val BACKUP_SUFFIX = ".bak"        const val MAX_BYTES = 64 * 1024        val ROOT_KEYS = setOf("enabled", "categories", "moodHour", "askedAt")        val ROOT_KEYS_WITHOUT_ASKED_AT = ROOT_KEYS - "askedAt"        val locks = ConcurrentHashMap<String, ReentrantLock>()    }}/** The small persistence seam used by the reminder pass and notification settings UI. */interface NotificationPrefsPersistence {    fun load(): NotificationPrefs    fun save(prefs: NotificationPrefs)}class NotificationPrefsPersistenceException(message: String, cause: Throwable? = null) : IllegalStateException(message, cause)