Skip to content

Commit

Permalink
Migrate MMKV to dataStore
Browse files Browse the repository at this point in the history
  • Loading branch information
ismartcoding committed Jul 22, 2023
1 parent 120c89a commit 9520a7e
Show file tree
Hide file tree
Showing 31 changed files with 158 additions and 113 deletions.
13 changes: 0 additions & 13 deletions app/src/main/java/com/ismartcoding/plain/LocalStorage.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.ismartcoding.plain

import com.ismartcoding.lib.helpers.CryptoHelper
import com.ismartcoding.lib.helpers.StringHelper
import com.ismartcoding.lib.serialize.serialLazy
import com.ismartcoding.plain.features.audio.DPlaylistAudio
import com.ismartcoding.plain.features.audio.MediaPlayMode
Expand All @@ -10,10 +8,6 @@ import com.ismartcoding.plain.features.file.FileSortBy
import com.ismartcoding.plain.features.video.DVideo

object LocalStorage {
var clientId: String by serialLazy("")
var fileIdToken: String by serialLazy("") // use to generate file path to id or decrypt file id to path

var deviceSortBy: DeviceSortBy by serialLazy(DeviceSortBy.LAST_ACTIVE)
var audioPlayMode: MediaPlayMode by serialLazy(MediaPlayMode.REPEAT)
var audioPlaylist: List<DPlaylistAudio> by serialLazy(listOf())
var audioPlaying: DPlaylistAudio? by serialLazy(null)
Expand Down Expand Up @@ -91,11 +85,4 @@ object LocalStorage {
items.addAll(videos)
videoPlayerList = items
}

fun init() {
if (clientId.isEmpty()) {
clientId = StringHelper.shortUUID()
}
fileIdToken = CryptoHelper.generateAESKey()
}
}
10 changes: 4 additions & 6 deletions app/src/main/java/com/ismartcoding/plain/MainApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import com.ismartcoding.lib.logcat.DiskLogFormatStrategy
import com.ismartcoding.lib.logcat.LogCat
import com.ismartcoding.plain.data.enums.DarkTheme
import com.ismartcoding.plain.data.enums.PasswordType
import com.ismartcoding.plain.data.preference.ClientIdPreference
import com.ismartcoding.plain.data.preference.DarkThemePreference
import com.ismartcoding.plain.data.preference.KeyStorePasswordPreference
import com.ismartcoding.plain.data.preference.PasswordTypePreference
import com.ismartcoding.plain.features.AppEvents
import com.ismartcoding.plain.features.bluetooth.BluetoothEvents
Expand All @@ -19,14 +21,9 @@ import com.ismartcoding.plain.web.HttpServerManager
import com.ismartcoding.plain.workers.FeedFetchWorker
import com.tencent.mmkv.MMKV
import io.ktor.server.netty.NettyApplicationEngine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob

class MainApp : Application() {
var httpServer: NettyApplicationEngine? = null
var httpServerError: String = ""
val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

override fun onCreate() {
super.onCreate()
Expand All @@ -37,7 +34,8 @@ class MainApp : Application() {

MMKV.initialize(this)

LocalStorage.init()
ClientIdPreference.ensureValue(this)
KeyStorePasswordPreference.ensureValue(this)

BRV.modelId = BR.m

Expand Down
9 changes: 7 additions & 2 deletions app/src/main/java/com/ismartcoding/plain/TempData.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package com.ismartcoding.plain

import com.ismartcoding.lib.helpers.CryptoHelper

object TempData {
var demoMode = false
var selectedBoxId = ""
var endictShowWord = true
var endictShowTranslation = true
var endictShowWord = true
var endictShowTranslation = true
var clientId = ""
var keyStorePassword = ""
val fileIdToken = CryptoHelper.generateAESKey() // use to generate file path to id or decrypt file id to path
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.ismartcoding.lib.helpers.PhoneHelper
import com.ismartcoding.lib.logcat.LogCat
import com.ismartcoding.plain.LocalStorage
import com.ismartcoding.plain.MainApp
import com.ismartcoding.plain.TempData
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.*
Expand Down Expand Up @@ -71,7 +72,7 @@ object HttpClientManager {
LogCat.d("[Request] $requestBodyStr")
val response = chain.proceed(
request.newBuilder()
.addHeader("c-id", LocalStorage.clientId)
.addHeader("c-id", TempData.clientId)
.addHeader("c-platform", "android")
.addHeader("c-name", Base64.encodeToString(PhoneHelper.getDeviceName(MainApp.instance).toByteArray(), Base64.NO_WRAP))
.addHeader("c-version", MainApp.getAppVersion())
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/com/ismartcoding/plain/data/Interfaces.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.ismartcoding.plain.data

import android.content.Context

interface ISelectOption {
fun isSelected(): Boolean
fun isSelected(context: Context): Boolean
fun getText(): String
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package com.ismartcoding.plain.data.preference

import android.content.Context
import androidx.datastore.preferences.core.Preferences
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import com.ismartcoding.lib.helpers.CoroutinesHelper.coIO

abstract class BasePreference<T> {
abstract val default: T
Expand All @@ -18,12 +16,12 @@ abstract class BasePreference<T> {
return context.dataStore.get(key) ?: default
}

fun put(context: Context, scope: CoroutineScope, value: T) {
scope.launch(Dispatchers.IO) {
fun put(context: Context, value: T) {
coIO {
context.dataStore.put(
key,
value
)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import com.ismartcoding.lib.logcat.LogCat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.io.IOException

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

suspend fun <T> DataStore<Preferences>.put(key: Preferences.Key<T>, value: T) {
this.edit {
withContext(Dispatchers.IO) {
it[key] = value
}
it[key] = value
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import com.ismartcoding.lib.helpers.JsonHelper.jsonEncode
import com.ismartcoding.lib.logcat.LogCat
import com.ismartcoding.lib.helpers.StringHelper
import com.ismartcoding.plain.TempData
import com.ismartcoding.plain.data.enums.DarkTheme
import com.ismartcoding.plain.data.enums.Language
import com.ismartcoding.plain.data.enums.PasswordType
import com.ismartcoding.plain.features.Permission
import com.ismartcoding.plain.features.device.DeviceSortBy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
Expand All @@ -27,8 +29,8 @@ object PasswordTypePreference : BasePreference<Int>() {
override val default = PasswordType.RANDOM.value
override val key = intPreferencesKey("password_type")

fun put(context: Context, scope: CoroutineScope, value: PasswordType) {
put(context, scope, value.value)
fun put(context: Context, value: PasswordType) {
put(context, value.value)
}
}

Expand All @@ -46,14 +48,14 @@ object ApiPermissionsPreference : BasePreference<Set<String>>() {
override val default = setOf<String>()
override val key = stringSetPreferencesKey("api_permissions")

fun put(context: Context, scope: CoroutineScope, permission: Permission, enable: Boolean) {
fun put(context: Context, permission: Permission, enable: Boolean) {
val permissions = get(context).toMutableSet()
if (enable) {
permissions.add(permission.name)
} else {
permissions.remove(permission.name)
}
put(context, scope, permissions)
put(context, permissions)
}
}

Expand All @@ -72,8 +74,8 @@ object DarkThemePreference : BasePreference<Int>() {
override val default = DarkTheme.UseDeviceTheme.value
override val key = intPreferencesKey("dark_theme")

fun put(context: Context, scope: CoroutineScope, value: DarkTheme) {
put(context, scope, value.value)
fun put(context: Context, value: DarkTheme) {
put(context, value.value)
setDarkMode(value)
}

Expand All @@ -82,9 +84,11 @@ object DarkThemePreference : BasePreference<Int>() {
DarkTheme.ON -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}

DarkTheme.OFF -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}

else -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
Expand Down Expand Up @@ -149,7 +153,47 @@ object ExchangeRatePreference : BasePreference<String>() {
return Json.decodeFromString(str)
}

fun put(context: Context, scope: CoroutineScope, value: ExchangeConfig) {
put(context, scope, jsonEncode(value))
fun put(context: Context, value: ExchangeConfig) {
put(context, jsonEncode(value))
}
}
}

object ClientIdPreference : BasePreference<String>() {
override val default = ""
override val key = stringPreferencesKey("client_id")

fun ensureValue(context: Context) {
TempData.clientId = get(context)
if (TempData.clientId.isEmpty()) {
TempData.clientId = StringHelper.shortUUID()
put(context, TempData.clientId)
}
}
}

object KeyStorePasswordPreference : BasePreference<String>() {
override val default = ""
override val key = stringPreferencesKey("key_store_password")

fun ensureValue(context: Context) {
TempData.keyStorePassword = get(context)
if (TempData.keyStorePassword.isEmpty()) {
TempData.keyStorePassword = StringHelper.shortUUID()
put(context, TempData.keyStorePassword)
}
}
}

object DeviceSortByPreference : BasePreference<Int>() {
override val default = DeviceSortBy.LAST_ACTIVE.ordinal
override val key = intPreferencesKey("device_sort_by")

fun put(context: Context, value: DeviceSortBy) {
put(context, value.ordinal)
}

fun getValue(context: Context): DeviceSortBy {
val value = get(context)
return DeviceSortBy.values().find { it.ordinal == value } ?: DeviceSortBy.LAST_ACTIVE
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import com.ismartcoding.plain.LocalStorage
import com.ismartcoding.plain.MainApp
import com.ismartcoding.lib.helpers.PhoneHelper
import com.ismartcoding.plain.TempData
import org.json.JSONObject

data class BleAuthData(val password: String) {
Expand Down Expand Up @@ -31,7 +32,7 @@ data class BleRequestData(val headers: MutableMap<String, String> = mutableMapOf
fun create(context: Context): BleRequestData {
val data = BleRequestData()
data.headers.run {
this["c-id"] = LocalStorage.clientId
this["c-id"] = TempData.clientId
this["c-platform"] = "android"
this["c-name"] = PhoneHelper.getDeviceName(context)
this["c-version"] = MainApp.getAppVersion()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.ismartcoding.plain.features.device

import com.ismartcoding.plain.LocalStorage
import android.content.Context
import com.ismartcoding.plain.R
import com.ismartcoding.plain.data.ISelectOption
import com.ismartcoding.plain.data.preference.DeviceSortByPreference
import com.ismartcoding.plain.features.locale.LocaleHelper.getString

enum class DeviceSortBy : ISelectOption {
Expand All @@ -17,7 +18,7 @@ enum class DeviceSortBy : ISelectOption {
}
}

override fun isSelected(): Boolean {
return LocalStorage.deviceSortBy == this
override fun isSelected(context: Context): Boolean {
return DeviceSortByPreference.getValue(context) == this
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.ismartcoding.plain.features.feed

import android.content.Context
import com.ismartcoding.plain.LocalStorage
import com.ismartcoding.plain.data.ISelectOption
import com.ismartcoding.plain.helpers.FormatHelper

class FeedAutoRefreshInterval(val value: Int) : ISelectOption {
override fun isSelected(): Boolean {
override fun isSelected(context: Context): Boolean {
return value == LocalStorage.feedAutoRefreshInterval
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import com.ismartcoding.lib.extensions.hasPermission
import com.ismartcoding.lib.helpers.CryptoHelper
import com.ismartcoding.lib.isRPlus
import com.ismartcoding.plain.LocalStorage
import com.ismartcoding.plain.TempData
import java.io.*


Expand Down Expand Up @@ -40,12 +41,12 @@ object FileHelper {
if (path.startsWith("https://", true) || path.startsWith("http://", true)) {
return path
}
return Base64.encodeToString(CryptoHelper.aesEncrypt(LocalStorage.fileIdToken, path), Base64.NO_WRAP)
return Base64.encodeToString(CryptoHelper.aesEncrypt(TempData.fileIdToken, path), Base64.NO_WRAP)
}

fun getFilePath(id: String): String {
val bytes = Base64.decode(id, Base64.NO_WRAP)
return CryptoHelper.aesDecrypt(LocalStorage.fileIdToken, bytes)?.decodeToString() ?: ""
return CryptoHelper.aesDecrypt(TempData.fileIdToken, bytes)?.decodeToString() ?: ""
}

fun rename(filePath: String, newName: String): File? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ object ScreenHelper {
}

fun saveTimeout(value: Int) {
SystemScreenTimeoutPreference.put(MainApp.instance, MainApp.instance.ioScope, value)
SystemScreenTimeoutPreference.put(MainApp.instance, value)
}

fun saveOn(value: Boolean) {
KeepScreenOnPreference.put(MainApp.instance, MainApp.instance.ioScope, value)
KeepScreenOnPreference.put(MainApp.instance, value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class ServiceStopBroadcastReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {
if (intent.action == "com.ismartcoding.plain.action.stop_http_server") {
WebPreference.put(MainApp.instance, MainApp.instance.ioScope, false)
WebPreference.put(MainApp.instance, false)
sendEvent(HttpServerEnabledEvent(false))
HttpServerService.instance?.stop()
HttpServerService.instance = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ class HttpServerService : LifecycleService() {
if (MainApp.instance.httpServer == null) {
MainApp.instance.httpServer = HttpServerManager.createHttpServer(MainApp.instance)
MainApp.instance.httpServer?.start(wait = true)
MainApp.instance.httpServerError = ""
HttpServerManager.httpServerError = ""
}
} catch (ex: Exception) {
ex.printStackTrace()
MainApp.instance.httpServer = null
MainApp.instance.httpServerError = ex.toString()
HttpServerManager.httpServerError = ex.toString()
LogCat.e(ex.toString())
}
}
Expand Down
Loading

0 comments on commit 9520a7e

Please sign in to comment.