64 lines · 2.6 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Contextimport android.content.SharedPreferencesimport com.cottondb.android.search.SEARCH_RECENTS_CAPimport com.cottondb.android.search.SearchRecentsStoreimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonPrimitive/** * Device-local search query history. The app manifest excludes its preferences from backup. * * Search queries are not vault values. This adapter never receives, reads, or saves a secret * payload, and it deliberately keeps no in-memory copy beyond SharedPreferences' own cache. */class AndroidSearchRecentsStore private constructor( private val preferences: SharedPreferences,) : SearchRecentsStore { constructor(context: Context, preferenceName: String = PREFERENCE_NAME) : this( context.applicationContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE), ) override fun load(): List<String> { val stored = try { preferences.getString(RECENTS_KEY, null) } catch (failure: Throwable) { throw SearchRecentsStoreException(failure) } ?: return emptyList() return try { val array = Json.parseToJsonElement(stored) as? JsonArray ?: throw IllegalArgumentException() require(array.size <= SEARCH_RECENTS_CAP) array.map { entry -> (entry as? JsonPrimitive)?.takeIf(JsonPrimitive::isString)?.content ?: throw IllegalArgumentException() }.also { values -> require(values.all(String::isNotBlank)) require(values.map { it.lowercase(java.util.Locale.ROOT) }.toSet().size == values.size) } } catch (failure: Throwable) { throw SearchRecentsStoreException(failure) } } override fun save(recents: List<String>) { require(recents.size <= SEARCH_RECENTS_CAP) { "Search recents exceed their maximum." } // apply() updates the process cache first and schedules disk work off the UI path. preferences.edit() .putString(RECENTS_KEY, JsonArray(recents.map(::JsonPrimitive)).toString()) .apply() } companion object { internal const val PREFERENCE_NAME = "search-recents-v1" internal const val RECENTS_KEY = "queries" }}/** Persisted content is deliberately not named: it can contain a person's search queries. */class SearchRecentsStoreException(cause: Throwable? = null) : IllegalStateException( "Saved search recents are unavailable.", cause,)