Cotton code
163 lines · 6.5 KB · KotlinRaw
package com.cottondb.android.keyboardimport android.content.Contextimport androidx.datastore.core.CorruptionExceptionimport androidx.datastore.core.DataStoreimport androidx.datastore.core.MultiProcessDataStoreFactoryimport androidx.datastore.core.Serializerimport java.io.Fileimport java.io.InputStreamimport java.io.OutputStreamimport java.nio.ByteBufferimport java.nio.charset.CharacterCodingExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.firstimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObject/** * A KeyboardChannelStore backed by one multiprocess DataStore per canonical file in this process. * The app's normal no-backup directory is credential encrypted; callers must not pass a * device-protected context because the channel can contain pending capture text. */class AndroidKeyboardChannelStore private constructor(    private val dataStore: DataStore<JsonObject>,) : KeyboardChannelStore {    override suspend fun read(): JsonObject = dataStore.data.first()    override suspend fun update(transform: (JsonObject) -> JsonObject): JsonObject =        dataStore.updateData { current ->            immutableJsonObject(transform(current))        }    companion object {        const val FILE_NAME = "keyboard-channel-v1.json"        private val lock = Any()        private val activeStores = mutableMapOf<String, ActiveStore>()        /**         * Opens the canonical credential-encrypted, no-backup channel. Repeated calls while the         * supplied scope is active receive the same DataStore, as required by DataStore.         */        fun open(context: Context, scope: CoroutineScope): KeyboardChannelStore {            require(!context.isDeviceProtectedStorage) {                "Keyboard channel must use credential-encrypted storage."            }            val applicationContext = context.applicationContext            require(!applicationContext.isDeviceProtectedStorage) {                "Keyboard channel application context must use credential-encrypted storage."            }            requireActiveScope(scope)            val directory = applicationContext.noBackupFilesDir.canonicalFile            val file = File(directory, FILE_NAME).canonicalFile            check(file.parentFile == directory) {                "Keyboard channel must remain directly inside the no-backup directory."            }            return synchronized(lock) {                activeStores[file.path]?.takeIf { it.scope.coroutineContext[Job]?.isActive != false }                    ?.store                    ?: createCanonicalStore(file, scope).also { created ->                        activeStores[file.path] = ActiveStore(scope, created)                        scope.coroutineContext[Job]?.invokeOnCompletion {                            synchronized(lock) {                                if (activeStores[file.path]?.store === created) {                                    activeStores.remove(file.path)                                }                            }                        }                    }            }        }        /**         * Injection seam for device tests. A test must use a unique file and cancel its scope         * before opening that file again, matching DataStore's one-active-instance rule.         */        internal fun openForTest(            file: File,            scope: CoroutineScope,            factory: KeyboardChannelDataStoreFactory = MultiProcessKeyboardChannelDataStoreFactory,        ): KeyboardChannelStore {            requireActiveScope(scope)            return AndroidKeyboardChannelStore(factory.create(file.canonicalFile, scope))        }        private fun createCanonicalStore(file: File, scope: CoroutineScope): KeyboardChannelStore =            AndroidKeyboardChannelStore(MultiProcessKeyboardChannelDataStoreFactory.create(file, scope))        private fun requireActiveScope(scope: CoroutineScope) {            val job = requireNotNull(scope.coroutineContext[Job]) {                "Keyboard channel scope must own a Job."            }            require(job.isActive) {                "Keyboard channel scope must be active."            }        }    }    private data class ActiveStore(        val scope: CoroutineScope,        val store: KeyboardChannelStore,    )}internal fun interface KeyboardChannelDataStoreFactory {    fun create(file: File, scope: CoroutineScope): DataStore<JsonObject>}internal object MultiProcessKeyboardChannelDataStoreFactory : KeyboardChannelDataStoreFactory {    override fun create(file: File, scope: CoroutineScope): DataStore<JsonObject> =        MultiProcessDataStoreFactory.create(            serializer = RawKeyboardChannelSerializer,            scope = scope,            produceFile = { file },        )}/** * JSON storage with no replacement corruption handler. An unreadable existing file is therefore * reported to the caller; it is never deleted or replaced with an empty outbox. */internal object RawKeyboardChannelSerializer : Serializer<JsonObject> {    override val defaultValue: JsonObject = JsonObject(emptyMap())    override suspend fun readFrom(input: InputStream): JsonObject {        val bytes = input.readBytes()        if (bytes.isEmpty()) {            throw CorruptionException("Keyboard channel is empty.")        }        val text = try {            Charsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString()        } catch (failure: CharacterCodingException) {            throw CorruptionException("Keyboard channel is not UTF-8.", failure)        }        val element = try {            Json.parseToJsonElement(text)        } catch (failure: Exception) {            throw CorruptionException("Keyboard channel is malformed JSON.", failure)        }        return (element as? JsonObject)?.let(::immutableJsonObject)            ?: throw CorruptionException("Keyboard channel root must be an object.")    }    override suspend fun writeTo(t: JsonObject, output: OutputStream) {        output.write(immutableJsonObject(t).toString().toByteArray(Charsets.UTF_8))    }}private fun immutableJsonObject(value: JsonObject): JsonObject =    JsonObject(value.mapValues { (_, element) -> immutableJsonElement(element) })private fun immutableJsonElement(value: JsonElement): JsonElement = when (value) {    is JsonObject -> immutableJsonObject(value)    is JsonArray -> JsonArray(value.map(::immutableJsonElement))    else -> value}