12package com.peachpasswords.sync34import android.content.Context5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.channels.awaitClose9import kotlinx.coroutines.flow.Flow10import kotlinx.coroutines.flow.callbackFlow11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import javax.inject.Inject14import javax.inject.Singleton151617181920212223242526272829303132333435363738@Singleton39class PairedDeviceStore @Inject constructor(40 @ApplicationContext context: Context,41) {42 private val masterKey = MasterKey.Builder(context)43 .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)44 .build()4546 private val prefs = EncryptedSharedPreferences.create(47 context,48 PREFS_FILE,49 masterKey,50 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,51 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,52 )5354 private val listSerializer = ListSerializer(PairedDevice.serializer())5556 fun getAll(): List<PairedDevice> {57 val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()58 return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())59 }6061 fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }6263 64 fun upsert(device: PairedDevice) {65 val next = getAll().filterNot { it.deviceId == device.deviceId } + device66 persist(next)67 }6869 fun remove(id: String) {70 persist(getAll().filterNot { it.deviceId == id })71 }7273 fun clear() {74 prefs.edit().remove(KEY_DEVICES).apply()75 }7677 78798081 fun updateLastSeen(id: String, ip: String? = null) {82 val current = get(id) ?: return83 if (ip == null) return84 upsert(current.copy(lastKnownIp = ip))85 }8687 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {88 val current = get(id) ?: return89 upsert(current.copy(lastSyncedAt = at))90 }9192 9394959697 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {98 trySend(getAll())99 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->100 if (key == KEY_DEVICES || key == null) trySend(getAll())101 }102 prefs.registerOnSharedPreferenceChangeListener(listener)103 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }104 }105106 private fun persist(devices: List<PairedDevice>) {107 prefs.edit()108 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))109 .apply()110 }111112 private companion object {113 const val PREFS_FILE = "peach_paired_devices"114 const val KEY_DEVICES = "paired_devices"115 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }116 }117}