0.0.1版本
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package cn.airnan.a2fair
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import cn.airnan.a2fair.core.backup.BackupManager
|
||||
import cn.airnan.a2fair.core.security.AppLockManager
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
import cn.airnan.a2fair.data.AppDatabase
|
||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||
import cn.airnan.a2fair.data.repository.TokenRepository
|
||||
import cn.airnan.a2fair.data.repository.dataStore
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.util.Locale
|
||||
|
||||
class A2FairApplication : Application() {
|
||||
|
||||
lateinit var cryptoManager: CryptoManager
|
||||
private set
|
||||
|
||||
lateinit var database: AppDatabase
|
||||
private set
|
||||
|
||||
lateinit var tokenRepository: TokenRepository
|
||||
private set
|
||||
|
||||
lateinit var settingsRepository: SettingsRepository
|
||||
private set
|
||||
|
||||
lateinit var appLockManager: AppLockManager
|
||||
private set
|
||||
|
||||
lateinit var backupManager: BackupManager
|
||||
private set
|
||||
|
||||
override fun attachBaseContext(base: Context) {
|
||||
val languageCode = try {
|
||||
runBlocking { base.dataStore.data.first() }[intPreferencesKey("language")] ?: 0
|
||||
} catch (_: Exception) {
|
||||
0
|
||||
}
|
||||
val locale = codeToLocale(languageCode) ?: return super.attachBaseContext(base)
|
||||
Locale.setDefault(locale)
|
||||
val config = Configuration(base.resources.configuration)
|
||||
config.setLocale(locale)
|
||||
val wrappedContext = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
base.createConfigurationContext(config)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
base.resources.updateConfiguration(config, base.resources.displayMetrics)
|
||||
base
|
||||
}
|
||||
super.attachBaseContext(wrappedContext)
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
cryptoManager = CryptoManager()
|
||||
database = AppDatabase.getDatabase(this, cryptoManager)
|
||||
tokenRepository = TokenRepository(database.tokenDao(), database.groupDao())
|
||||
settingsRepository = SettingsRepository(this, cryptoManager)
|
||||
|
||||
appLockManager = AppLockManager(settingsRepository)
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(appLockManager)
|
||||
|
||||
backupManager = BackupManager(this, tokenRepository, cryptoManager)
|
||||
}
|
||||
}
|
||||
|
||||
fun codeToLocale(code: Int): Locale? = when (code) {
|
||||
1 -> Locale.SIMPLIFIED_CHINESE // zh-CN
|
||||
2 -> Locale.TRADITIONAL_CHINESE // zh-TW
|
||||
3 -> Locale.ENGLISH
|
||||
else -> null // 0: System, use default
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package cn.airnan.a2fair
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import cn.airnan.a2fair.data.repository.dataStore
|
||||
import cn.airnan.a2fair.ui.navigation.AppNavigation
|
||||
import cn.airnan.a2fair.ui.settings.security.LockScreen
|
||||
import cn.airnan.a2fair.ui.theme._2FAirTheme
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.util.Locale
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
val languageCode = try {
|
||||
runBlocking { newBase.dataStore.data.first() }[intPreferencesKey("language")] ?: 0
|
||||
} catch (_: Exception) {
|
||||
0
|
||||
}
|
||||
val locale = codeToLocale(languageCode)
|
||||
val wrappedContext = if (locale != null) {
|
||||
val config = Configuration(newBase.resources.configuration)
|
||||
config.setLocale(locale)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
newBase.createConfigurationContext(config)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
newBase.resources.updateConfiguration(config, newBase.resources.displayMetrics)
|
||||
newBase
|
||||
}
|
||||
} else {
|
||||
newBase
|
||||
}
|
||||
super.attachBaseContext(wrappedContext)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
val app = application as A2FairApplication
|
||||
val settingsRepo = app.settingsRepository
|
||||
val appLockManager = app.appLockManager
|
||||
|
||||
val themeMode by settingsRepo.themeMode.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val dynamicColor by settingsRepo.dynamicColor.collectAsStateWithLifecycle(initialValue = true)
|
||||
val seedColor by settingsRepo.seedColor.collectAsStateWithLifecycle(initialValue = 0xFF6750A4.toInt())
|
||||
val isFlagSecureEnabled by settingsRepo.isFlagSecureEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val isLocked by appLockManager.isLocked.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(isFlagSecureEnabled) {
|
||||
if (isFlagSecureEnabled) {
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||
} else {
|
||||
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
settingsRepo.languageChangeEvent.collect {
|
||||
this@MainActivity.recreate()
|
||||
}
|
||||
}
|
||||
|
||||
_2FAirTheme(
|
||||
themeMode = themeMode,
|
||||
dynamicColor = dynamicColor,
|
||||
seedColor = seedColor
|
||||
) {
|
||||
if (isLocked) {
|
||||
LockScreen(
|
||||
onUnlock = { appLockManager.unlock() },
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
} else {
|
||||
AppNavigation()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cn.airnan.a2fair.core
|
||||
|
||||
object NativeLib {
|
||||
init {
|
||||
System.loadLibrary("a2fair")
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a Base32 encoded string to byte array
|
||||
*/
|
||||
external fun base32Decode(encoded: String): ByteArray
|
||||
|
||||
/**
|
||||
* Encode a byte array to Base32 string
|
||||
*/
|
||||
external fun base32Encode(data: ByteArray): String
|
||||
|
||||
/**
|
||||
* Generate HOTP code
|
||||
*/
|
||||
external fun generateHOTP(secret: ByteArray, counter: Long, digits: Int, algo: Int): String
|
||||
|
||||
/**
|
||||
* Generate TOTP code
|
||||
*/
|
||||
external fun generateTOTP(secret: ByteArray, time: Long, period: Int, digits: Int, algo: Int): String
|
||||
|
||||
/**
|
||||
* Generate Steam TOTP code
|
||||
*/
|
||||
external fun generateSteam(secret: ByteArray, time: Long): String
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package cn.airnan.a2fair.core
|
||||
|
||||
import android.net.Uri
|
||||
import cn.airnan.a2fair.data.SecretString
|
||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
|
||||
object OtpUriParser {
|
||||
|
||||
class ParseException(message: String) : Exception(message)
|
||||
|
||||
fun parse(uriString: String): Token {
|
||||
val uri = Uri.parse(uriString)
|
||||
|
||||
if (uri.scheme != "otpauth") {
|
||||
throw ParseException("Invalid scheme: ${uri.scheme}")
|
||||
}
|
||||
|
||||
val typeStr = uri.authority ?: throw ParseException("Missing token type")
|
||||
val tokenType = when (typeStr.lowercase()) {
|
||||
"totp" -> TokenType.TOTP
|
||||
"hotp" -> TokenType.HOTP
|
||||
"steam" -> TokenType.STEAM
|
||||
else -> throw ParseException("Unsupported token type: $typeStr")
|
||||
}
|
||||
|
||||
// Path is usually /issuer:account or /account
|
||||
val path = uri.path?.removePrefix("/") ?: throw ParseException("Missing path/label")
|
||||
if (path.isEmpty()) {
|
||||
throw ParseException("Missing path/label")
|
||||
}
|
||||
|
||||
val labelDecoded = Uri.decode(path)
|
||||
val colonIndex = labelDecoded.indexOf(':')
|
||||
|
||||
var issuer = uri.getQueryParameter("issuer") ?: ""
|
||||
var serviceName = labelDecoded
|
||||
|
||||
if (colonIndex != -1) {
|
||||
val labelIssuer = labelDecoded.substring(0, colonIndex).trim()
|
||||
val labelAccount = labelDecoded.substring(colonIndex + 1).trim()
|
||||
|
||||
if (issuer.isEmpty()) {
|
||||
issuer = labelIssuer
|
||||
}
|
||||
serviceName = labelAccount
|
||||
}
|
||||
|
||||
val secret = uri.getQueryParameter("secret") ?: throw ParseException("Missing secret")
|
||||
if (secret.isEmpty()) {
|
||||
throw ParseException("Secret is empty")
|
||||
}
|
||||
|
||||
val algorithmStr = uri.getQueryParameter("algorithm") ?: "SHA1"
|
||||
val algorithm = when (algorithmStr.uppercase()) {
|
||||
"SHA1" -> HashAlgorithm.SHA1
|
||||
"SHA256" -> HashAlgorithm.SHA256
|
||||
"SHA512" -> HashAlgorithm.SHA512
|
||||
else -> throw ParseException("Unsupported algorithm: $algorithmStr")
|
||||
}
|
||||
|
||||
val digitsStr = uri.getQueryParameter("digits") ?: "6"
|
||||
val digits = digitsStr.toIntOrNull() ?: throw ParseException("Invalid digits: $digitsStr")
|
||||
|
||||
val periodStr = uri.getQueryParameter("period") ?: "30"
|
||||
val period = periodStr.toIntOrNull() ?: throw ParseException("Invalid period: $periodStr")
|
||||
|
||||
val counterStr = uri.getQueryParameter("counter") ?: "0"
|
||||
val counter = counterStr.toLongOrNull() ?: throw ParseException("Invalid counter: $counterStr")
|
||||
|
||||
if (tokenType == TokenType.HOTP && !uri.queryParameterNames.contains("counter")) {
|
||||
throw ParseException("HOTP requires a counter")
|
||||
}
|
||||
|
||||
return Token(
|
||||
issuer = issuer,
|
||||
serviceName = serviceName,
|
||||
secret = SecretString(secret),
|
||||
tokenType = tokenType,
|
||||
algorithm = algorithm,
|
||||
digits = digits,
|
||||
period = period,
|
||||
counter = counter
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package cn.airnan.a2fair.core.backup
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.repository.TokenRepository
|
||||
import com.google.gson.Gson
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.security.SecureRandom
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
data class BackupData(
|
||||
val groups: List<Group>,
|
||||
val tokens: List<Token>
|
||||
)
|
||||
|
||||
class BackupManager(
|
||||
private val context: Context,
|
||||
private val tokenRepository: TokenRepository,
|
||||
private val cryptoManager: CryptoManager
|
||||
) {
|
||||
private val gson = Gson()
|
||||
|
||||
suspend fun exportData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val tokens = tokenRepository.getAllTokens().first()
|
||||
val groups = tokenRepository.getAllGroups().first()
|
||||
|
||||
// Decrypt tokens before exporting
|
||||
val decryptedTokens = tokens.map { token ->
|
||||
token.copy(
|
||||
secret = cn.airnan.a2fair.data.SecretString(token.secret.value) // Actually the secret in entity is plain when loaded from DB because of TypeConverter, wait, Room's TypeConverter encrypts on save, decrypts on load.
|
||||
// So token.secret is already decrypted!
|
||||
)
|
||||
}
|
||||
|
||||
val backupData = BackupData(groups, decryptedTokens)
|
||||
val json = gson.toJson(backupData)
|
||||
val jsonBytes = json.toByteArray(Charsets.UTF_8)
|
||||
|
||||
// Generate salt and derive key
|
||||
val salt = ByteArray(16)
|
||||
SecureRandom().nextBytes(salt)
|
||||
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
val spec = PBEKeySpec(password, salt, 10000, 256)
|
||||
val secretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
|
||||
|
||||
// Encrypt data
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey)
|
||||
val iv = cipher.iv
|
||||
val encryptedData = cipher.doFinal(jsonBytes)
|
||||
|
||||
// Write to file: format = [SALT_LENGTH (1)] + [SALT] + [IV_LENGTH (1)] + [IV] + [DATA]
|
||||
context.contentResolver.openOutputStream(uri)?.use { output ->
|
||||
output.write(salt.size)
|
||||
output.write(salt)
|
||||
output.write(iv.size)
|
||||
output.write(iv)
|
||||
output.write(encryptedData)
|
||||
} ?: return@withContext Result.failure(Exception("Could not open output stream"))
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun importData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val encryptedBytes = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
input.readBytes()
|
||||
} ?: return@withContext Result.failure(Exception("Could not open input stream"))
|
||||
|
||||
var offset = 0
|
||||
val saltLength = encryptedBytes[offset++].toInt()
|
||||
val salt = encryptedBytes.copyOfRange(offset, offset + saltLength)
|
||||
offset += saltLength
|
||||
|
||||
val ivLength = encryptedBytes[offset++].toInt()
|
||||
val iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
|
||||
offset += ivLength
|
||||
|
||||
val data = encryptedBytes.copyOfRange(offset, encryptedBytes.size)
|
||||
|
||||
// Derive key
|
||||
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
|
||||
val spec = PBEKeySpec(password, salt, 10000, 256)
|
||||
val secretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
|
||||
|
||||
// Decrypt
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
val gcmSpec = GCMParameterSpec(128, iv)
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec)
|
||||
val decryptedBytes = cipher.doFinal(data)
|
||||
|
||||
val json = String(decryptedBytes, Charsets.UTF_8)
|
||||
val backupData = gson.fromJson(json, BackupData::class.java)
|
||||
|
||||
// Merge logic (simple replace or merge)
|
||||
// For now, let's just insert all if not exists, or replace. We'll do a simple insert.
|
||||
backupData.groups.forEach { group ->
|
||||
// Ensure group doesn't duplicate by name?
|
||||
// For simplicity, insert directly, handle id mapping later if needed.
|
||||
tokenRepository.insertGroup(group.copy(id = 0))
|
||||
}
|
||||
|
||||
backupData.tokens.forEach { token ->
|
||||
tokenRepository.insertToken(token.copy(id = 0))
|
||||
}
|
||||
|
||||
Result.success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cn.airnan.a2fair.core.security
|
||||
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class AppLockManager(private val settingsRepository: SettingsRepository) : DefaultLifecycleObserver {
|
||||
private val _isLocked = MutableStateFlow(false)
|
||||
val isLocked: StateFlow<Boolean> = _isLocked.asStateFlow()
|
||||
|
||||
private val scope = CoroutineScope(Dispatchers.Main)
|
||||
|
||||
fun lock() {
|
||||
scope.launch {
|
||||
val isPinEnabled = settingsRepository.isPinEnabled.first()
|
||||
if (isPinEnabled) {
|
||||
_isLocked.value = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun unlock() {
|
||||
_isLocked.value = false
|
||||
}
|
||||
|
||||
override fun onStop(owner: LifecycleOwner) {
|
||||
super.onStop(owner)
|
||||
lock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package cn.airnan.a2fair.crypto
|
||||
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class CryptoManager {
|
||||
|
||||
private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply {
|
||||
load(null)
|
||||
}
|
||||
|
||||
private fun getSecretKey(): SecretKey {
|
||||
val existingKey = keyStore.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry
|
||||
return existingKey?.secretKey ?: createSecretKey()
|
||||
}
|
||||
|
||||
private fun createSecretKey(): SecretKey {
|
||||
val keyGenerator = KeyGenerator.getInstance(
|
||||
KeyProperties.KEY_ALGORITHM_AES,
|
||||
"AndroidKeyStore"
|
||||
)
|
||||
val spec = KeyGenParameterSpec.Builder(
|
||||
ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.build()
|
||||
|
||||
keyGenerator.init(spec)
|
||||
return keyGenerator.generateKey()
|
||||
}
|
||||
|
||||
fun encrypt(unencryptedString: String): String {
|
||||
if (unencryptedString.isBlank()) return unencryptedString
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey())
|
||||
val iv = cipher.iv
|
||||
val encryptedBytes = cipher.doFinal(unencryptedString.toByteArray(Charsets.UTF_8))
|
||||
|
||||
val combined = ByteArray(iv.size + encryptedBytes.size)
|
||||
System.arraycopy(iv, 0, combined, 0, iv.size)
|
||||
System.arraycopy(encryptedBytes, 0, combined, iv.size, encryptedBytes.size)
|
||||
|
||||
return Base64.encodeToString(combined, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
fun decrypt(encryptedString: String): String {
|
||||
if (encryptedString.isBlank()) return encryptedString
|
||||
return try {
|
||||
val combined = Base64.decode(encryptedString, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
|
||||
// For AES-GCM, IV length is 12 bytes
|
||||
val iv = combined.copyOfRange(0, 12)
|
||||
val encryptedBytes = combined.copyOfRange(12, combined.size)
|
||||
|
||||
val spec = GCMParameterSpec(128, iv)
|
||||
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec)
|
||||
|
||||
val decryptedBytes = cipher.doFinal(encryptedBytes)
|
||||
String(decryptedBytes, Charsets.UTF_8)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val ALIAS = "a2fair_secret_key"
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package cn.airnan.a2fair.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
import cn.airnan.a2fair.data.dao.GroupDao
|
||||
import cn.airnan.a2fair.data.dao.TokenDao
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
|
||||
@Database(entities = [Group::class, Token::class], version = 1, exportSchema = false)
|
||||
@TypeConverters(SecretTypeConverter::class, EnumConverters::class)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun groupDao(): GroupDao
|
||||
abstract fun tokenDao(): TokenDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
private var INSTANCE: AppDatabase? = null
|
||||
|
||||
fun getDatabase(context: Context, cryptoManager: CryptoManager): AppDatabase {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
val instance = Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AppDatabase::class.java,
|
||||
"a2fair_database"
|
||||
)
|
||||
.addTypeConverter(SecretTypeConverter(cryptoManager))
|
||||
.build()
|
||||
INSTANCE = instance
|
||||
instance
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cn.airnan.a2fair.data
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
|
||||
class EnumConverters {
|
||||
|
||||
@TypeConverter
|
||||
fun fromTokenType(value: TokenType): String {
|
||||
return value.name
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun toTokenType(value: String): TokenType {
|
||||
return try {
|
||||
TokenType.valueOf(value)
|
||||
} catch (e: Exception) {
|
||||
TokenType.TOTP
|
||||
}
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun fromHashAlgorithm(value: HashAlgorithm): String {
|
||||
return value.name
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun toHashAlgorithm(value: String): HashAlgorithm {
|
||||
return try {
|
||||
HashAlgorithm.valueOf(value)
|
||||
} catch (e: Exception) {
|
||||
HashAlgorithm.SHA1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package cn.airnan.a2fair.data
|
||||
|
||||
data class SecretString(val value: String) {
|
||||
override fun toString(): String {
|
||||
return "***"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.airnan.a2fair.data
|
||||
|
||||
import androidx.room.ProvidedTypeConverter
|
||||
import androidx.room.TypeConverter
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
|
||||
@ProvidedTypeConverter
|
||||
class SecretTypeConverter(private val cryptoManager: CryptoManager) {
|
||||
|
||||
@TypeConverter
|
||||
fun fromSecretString(secretString: SecretString?): String? {
|
||||
if (secretString == null) return null
|
||||
return cryptoManager.encrypt(secretString.value)
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun toSecretString(encryptedString: String?): SecretString? {
|
||||
if (encryptedString == null) return null
|
||||
return SecretString(cryptoManager.decrypt(encryptedString))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.airnan.a2fair.data.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface GroupDao {
|
||||
@Query("SELECT * FROM groups ORDER BY sortOrder ASC")
|
||||
fun getAllGroups(): Flow<List<Group>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
fun insertGroup(group: Group): Long
|
||||
|
||||
@Update
|
||||
fun updateGroup(group: Group): Int
|
||||
|
||||
@Delete
|
||||
fun deleteGroup(group: Group): Int
|
||||
|
||||
@Query("SELECT * FROM groups WHERE id = :id LIMIT 1")
|
||||
fun getGroupById(id: Long): Group?
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package cn.airnan.a2fair.data.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface TokenDao {
|
||||
@Query("SELECT * FROM tokens ORDER BY sortOrder ASC")
|
||||
fun getAllTokens(): Flow<List<Token>>
|
||||
|
||||
@Query("SELECT * FROM tokens WHERE groupId = :groupId ORDER BY sortOrder ASC")
|
||||
fun getTokensByGroupId(groupId: Long): Flow<List<Token>>
|
||||
|
||||
@Query("SELECT * FROM tokens WHERE groupId IS NULL ORDER BY sortOrder ASC")
|
||||
fun getUncategorizedTokens(): Flow<List<Token>>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
fun insertToken(token: Token): Long
|
||||
|
||||
@Update
|
||||
fun updateToken(token: Token): Int
|
||||
|
||||
@Delete
|
||||
fun deleteToken(token: Token): Int
|
||||
|
||||
@Query("SELECT * FROM tokens WHERE id = :id LIMIT 1")
|
||||
fun getTokenById(id: Long): Token?
|
||||
|
||||
@Query("UPDATE tokens SET counter = :counter WHERE id = :id")
|
||||
fun updateCounter(id: Long, counter: Long): Int
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package cn.airnan.a2fair.data.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
@Entity(tableName = "groups")
|
||||
data class Group(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
val name: String,
|
||||
val sortOrder: Int = 0
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
package cn.airnan.a2fair.data.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
enum class TokenType {
|
||||
TOTP, HOTP, STEAM
|
||||
}
|
||||
|
||||
enum class HashAlgorithm {
|
||||
SHA1, SHA256, SHA512
|
||||
}
|
||||
|
||||
@Entity(
|
||||
tableName = "tokens",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = Group::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["groupId"],
|
||||
onDelete = ForeignKey.SET_NULL
|
||||
)
|
||||
],
|
||||
indices = [Index("groupId")]
|
||||
)
|
||||
data class Token(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
val issuer: String = "",
|
||||
val serviceName: String,
|
||||
val secret: cn.airnan.a2fair.data.SecretString, // will be encrypted
|
||||
val tokenType: TokenType = TokenType.TOTP,
|
||||
val algorithm: HashAlgorithm = HashAlgorithm.SHA1,
|
||||
val digits: Int = 6,
|
||||
val period: Int = 30,
|
||||
val counter: Long = 0,
|
||||
val groupId: Long? = null,
|
||||
val icon: String? = null,
|
||||
val sortOrder: Int = 0
|
||||
)
|
||||
@@ -0,0 +1,153 @@
|
||||
package cn.airnan.a2fair.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import cn.airnan.a2fair.crypto.CryptoManager
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
|
||||
|
||||
class SettingsRepository(private val context: Context, private val cryptoManager: CryptoManager) {
|
||||
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
val isPinEnabled: Flow<Boolean> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.PIN_ENABLED] ?: false
|
||||
}
|
||||
|
||||
suspend fun setPinEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.PIN_ENABLED] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
val pinCode: Flow<String?> = dataStore.data.map { preferences ->
|
||||
val encryptedPin = preferences[PreferencesKeys.PIN_CODE]
|
||||
if (encryptedPin != null) {
|
||||
try {
|
||||
cryptoManager.decrypt(encryptedPin)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setPinCode(pin: String?) {
|
||||
dataStore.edit { preferences ->
|
||||
if (pin == null) {
|
||||
preferences.remove(PreferencesKeys.PIN_CODE)
|
||||
} else {
|
||||
preferences[PreferencesKeys.PIN_CODE] = cryptoManager.encrypt(pin)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val isBiometricEnabled: Flow<Boolean> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.BIOMETRIC_ENABLED] ?: false
|
||||
}
|
||||
|
||||
suspend fun setBiometricEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.BIOMETRIC_ENABLED] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
val isFlagSecureEnabled: Flow<Boolean> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.FLAG_SECURE_ENABLED] ?: false
|
||||
}
|
||||
|
||||
suspend fun setFlagSecureEnabled(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.FLAG_SECURE_ENABLED] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
val failedAttempts: Flow<Int> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.FAILED_ATTEMPTS] ?: 0
|
||||
}
|
||||
|
||||
suspend fun setFailedAttempts(attempts: Int) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.FAILED_ATTEMPTS] = attempts
|
||||
}
|
||||
}
|
||||
|
||||
val lockoutEndTime: Flow<Long> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.LOCKOUT_END_TIME] ?: 0L
|
||||
}
|
||||
|
||||
suspend fun setLockoutEndTime(time: Long) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.LOCKOUT_END_TIME] = time
|
||||
}
|
||||
}
|
||||
|
||||
val themeMode: Flow<Int> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.THEME_MODE] ?: 0 // 0: System, 1: Light, 2: Dark
|
||||
}
|
||||
|
||||
suspend fun setThemeMode(mode: Int) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.THEME_MODE] = mode
|
||||
}
|
||||
}
|
||||
|
||||
val dynamicColor: Flow<Boolean> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.DYNAMIC_COLOR] ?: true
|
||||
}
|
||||
|
||||
suspend fun setDynamicColor(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.DYNAMIC_COLOR] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
val seedColor: Flow<Int> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.SEED_COLOR] ?: 0xFF6750A4.toInt() // Default to Material You purple
|
||||
}
|
||||
|
||||
suspend fun setSeedColor(color: Int) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.SEED_COLOR] = color
|
||||
}
|
||||
}
|
||||
|
||||
val language: Flow<Int> = dataStore.data.map { preferences ->
|
||||
preferences[PreferencesKeys.LANGUAGE] ?: 0 // 0: System, 1: zh-CN, 2: zh-TW, 3: en
|
||||
}
|
||||
|
||||
private val _languageChangeEvent = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||
val languageChangeEvent: SharedFlow<Unit> = _languageChangeEvent
|
||||
|
||||
suspend fun setLanguage(code: Int) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[PreferencesKeys.LANGUAGE] = code
|
||||
}
|
||||
_languageChangeEvent.emit(Unit)
|
||||
}
|
||||
|
||||
private object PreferencesKeys {
|
||||
val PIN_ENABLED = booleanPreferencesKey("pin_enabled")
|
||||
val PIN_CODE = stringPreferencesKey("pin_code")
|
||||
val BIOMETRIC_ENABLED = booleanPreferencesKey("biometric_enabled")
|
||||
val FLAG_SECURE_ENABLED = booleanPreferencesKey("flag_secure_enabled")
|
||||
val FAILED_ATTEMPTS = intPreferencesKey("failed_attempts")
|
||||
val LOCKOUT_END_TIME = longPreferencesKey("lockout_end_time")
|
||||
val THEME_MODE = intPreferencesKey("theme_mode")
|
||||
val DYNAMIC_COLOR = booleanPreferencesKey("dynamic_color")
|
||||
val SEED_COLOR = intPreferencesKey("seed_color")
|
||||
val LANGUAGE = intPreferencesKey("language")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cn.airnan.a2fair.data.repository
|
||||
|
||||
import cn.airnan.a2fair.data.dao.GroupDao
|
||||
import cn.airnan.a2fair.data.dao.TokenDao
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class TokenRepository(
|
||||
private val tokenDao: TokenDao,
|
||||
private val groupDao: GroupDao
|
||||
) {
|
||||
// Group
|
||||
fun getAllGroups(): Flow<List<Group>> = groupDao.getAllGroups()
|
||||
suspend fun getGroupById(id: Long): Group? = withContext(Dispatchers.IO) { groupDao.getGroupById(id) }
|
||||
suspend fun insertGroup(group: Group): Long = withContext(Dispatchers.IO) { groupDao.insertGroup(group) }
|
||||
suspend fun updateGroup(group: Group) { withContext(Dispatchers.IO) { groupDao.updateGroup(group) } }
|
||||
suspend fun deleteGroup(group: Group) { withContext(Dispatchers.IO) { groupDao.deleteGroup(group) } }
|
||||
|
||||
// Token
|
||||
fun getAllTokens(): Flow<List<Token>> = tokenDao.getAllTokens()
|
||||
fun getTokensByGroupId(groupId: Long): Flow<List<Token>> = tokenDao.getTokensByGroupId(groupId)
|
||||
fun getUncategorizedTokens(): Flow<List<Token>> = tokenDao.getUncategorizedTokens()
|
||||
suspend fun getTokenById(id: Long): Token? = withContext(Dispatchers.IO) { tokenDao.getTokenById(id) }
|
||||
suspend fun insertToken(token: Token): Long = withContext(Dispatchers.IO) { tokenDao.insertToken(token) }
|
||||
suspend fun updateToken(token: Token) { withContext(Dispatchers.IO) { tokenDao.updateToken(token) } }
|
||||
suspend fun deleteToken(token: Token) { withContext(Dispatchers.IO) { tokenDao.deleteToken(token) } }
|
||||
suspend fun updateCounter(id: Long, counter: Long) { withContext(Dispatchers.IO) { tokenDao.updateCounter(id, counter) } }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cn.airnan.a2fair.ui.navigation
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Shield
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import cn.airnan.a2fair.R
|
||||
|
||||
enum class TopLevelDestination(
|
||||
val route: String,
|
||||
val icon: ImageVector,
|
||||
@StringRes val titleTextId: Int
|
||||
) {
|
||||
TOKENS(
|
||||
route = "tokens",
|
||||
icon = Icons.Outlined.Shield,
|
||||
titleTextId = R.string.tokens
|
||||
),
|
||||
SETTINGS(
|
||||
route = "settings",
|
||||
icon = Icons.Default.Settings,
|
||||
titleTextId = R.string.settings
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package cn.airnan.a2fair.ui.navigation
|
||||
|
||||
import androidx.compose.animation.EnterTransition
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.slideInHorizontally
|
||||
import androidx.compose.animation.slideOutHorizontally
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.NavigationBar
|
||||
import androidx.compose.material3.NavigationBarItem
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.ui.settings.SettingsScreen
|
||||
import cn.airnan.a2fair.ui.settings.security.PinSetupScreen
|
||||
import cn.airnan.a2fair.ui.settings.security.SecuritySettingsScreen
|
||||
import cn.airnan.a2fair.ui.tokens.TokensScreen
|
||||
|
||||
@Composable
|
||||
fun AppNavigation(
|
||||
appState: AppState = rememberAppState()
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as A2FairApplication
|
||||
val animDuration = context.resources.getInteger(android.R.integer.config_shortAnimTime)
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets(0, 0, 0, 0),
|
||||
bottomBar = {
|
||||
AppBottomBar(
|
||||
destinations = appState.topLevelDestinations,
|
||||
onNavigateToDestination = appState::navigateToTopLevelDestination,
|
||||
currentDestination = appState.currentTopLevelDestination
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
NavHost(
|
||||
navController = appState.navController,
|
||||
startDestination = TopLevelDestination.TOKENS.route,
|
||||
modifier = Modifier.padding(padding)
|
||||
) {
|
||||
composable(
|
||||
route = TopLevelDestination.TOKENS.route,
|
||||
enterTransition = { EnterTransition.None },
|
||||
exitTransition = { ExitTransition.None }
|
||||
) {
|
||||
TokensScreen()
|
||||
}
|
||||
composable(
|
||||
route = TopLevelDestination.SETTINGS.route,
|
||||
enterTransition = { EnterTransition.None },
|
||||
exitTransition = { ExitTransition.None }
|
||||
) {
|
||||
SettingsScreen(
|
||||
onNavigateToSecurity = { appState.navController.navigate("security") },
|
||||
onNavigateToBackup = { appState.navController.navigate("backup") },
|
||||
onNavigateToTheme = { appState.navController.navigate("theme") },
|
||||
onNavigateToLanguage = { appState.navController.navigate("language") },
|
||||
onNavigateToAbout = { appState.navController.navigate("about") }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "security",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
SecuritySettingsScreen(
|
||||
settingsRepository = app.settingsRepository,
|
||||
onNavigateBack = { appState.navController.popBackStack() },
|
||||
onNavigateToPinSetup = { appState.navController.navigate("pin_setup") }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "pin_setup",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
PinSetupScreen(
|
||||
settingsRepository = app.settingsRepository,
|
||||
onNavigateBack = { appState.navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "backup",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
cn.airnan.a2fair.ui.settings.backup.BackupScreen(
|
||||
backupManager = app.backupManager,
|
||||
onNavigateBack = { appState.navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "theme",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
cn.airnan.a2fair.ui.settings.ThemeSettingsScreen(
|
||||
onNavigateBack = { appState.navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "about",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
cn.airnan.a2fair.ui.settings.AboutScreen(
|
||||
onNavigateBack = { appState.navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = "language",
|
||||
enterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
},
|
||||
exitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popEnterTransition = {
|
||||
slideInHorizontally(initialOffsetX = { -it / 3 }, animationSpec = tween(animDuration))
|
||||
},
|
||||
popExitTransition = {
|
||||
slideOutHorizontally(targetOffsetX = { it }, animationSpec = tween(animDuration))
|
||||
}
|
||||
) {
|
||||
cn.airnan.a2fair.ui.settings.LanguageSettingsScreen(
|
||||
onNavigateBack = { appState.navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppBottomBar(
|
||||
destinations: List<TopLevelDestination>,
|
||||
onNavigateToDestination: (TopLevelDestination) -> Unit,
|
||||
currentDestination: TopLevelDestination?
|
||||
) {
|
||||
NavigationBar {
|
||||
destinations.forEach { destination ->
|
||||
val selected = currentDestination == destination
|
||||
NavigationBarItem(
|
||||
selected = selected,
|
||||
onClick = { onNavigateToDestination(destination) },
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = destination.icon,
|
||||
contentDescription = stringResource(id = destination.titleTextId)
|
||||
)
|
||||
},
|
||||
label = {
|
||||
Text(text = stringResource(id = destination.titleTextId))
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cn.airnan.a2fair.ui.navigation
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.navigation.NavDestination
|
||||
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||
import androidx.navigation.NavHostController
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
|
||||
@Composable
|
||||
fun rememberAppState(
|
||||
navController: NavHostController = rememberNavController()
|
||||
): AppState {
|
||||
return remember(navController) {
|
||||
AppState(navController)
|
||||
}
|
||||
}
|
||||
|
||||
@Stable
|
||||
class AppState(
|
||||
val navController: NavHostController
|
||||
) {
|
||||
val currentDestination: NavDestination?
|
||||
@Composable get() = navController.currentBackStackEntryAsState().value?.destination
|
||||
|
||||
val currentTopLevelDestination: TopLevelDestination?
|
||||
@Composable get() {
|
||||
val route = currentDestination?.route
|
||||
return TopLevelDestination.values().find { it.route == route }
|
||||
}
|
||||
|
||||
val topLevelDestinations: List<TopLevelDestination> = TopLevelDestination.values().toList()
|
||||
|
||||
fun navigateToTopLevelDestination(topLevelDestination: TopLevelDestination) {
|
||||
navController.navigate(topLevelDestination.route) {
|
||||
popUpTo(navController.graph.findStartDestination().id) {
|
||||
saveState = true
|
||||
}
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package cn.airnan.a2fair.ui.settings
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cn.airnan.a2fair.BuildConfig
|
||||
import cn.airnan.a2fair.R
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AboutScreen(
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.about)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(48.dp))
|
||||
|
||||
// Use app icon (assuming ic_launcher is available)
|
||||
Image(
|
||||
painter = painterResource(id = R.mipmap.ic_launcher),
|
||||
contentDescription = stringResource(R.string.app_icon),
|
||||
modifier = Modifier.size(100.dp)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.app_name),
|
||||
style = MaterialTheme.typography.headlineMedium
|
||||
)
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.version_format, BuildConfig.VERSION_NAME),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(48.dp))
|
||||
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.source_code)) },
|
||||
supportingContent = { Text(stringResource(R.string.view_on_github)) },
|
||||
modifier = Modifier.clickable {
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/"))
|
||||
context.startActivity(intent)
|
||||
}
|
||||
)
|
||||
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.open_source_licenses)) },
|
||||
modifier = Modifier.clickable {
|
||||
// TODO: Implement license viewer or navigation
|
||||
}
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.copyright),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 24.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package cn.airnan.a2fair.ui.settings
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.R
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun LanguageSettingsScreen(
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as A2FairApplication
|
||||
val viewModel: SettingsViewModel = viewModel(
|
||||
factory = SettingsViewModel.Factory(app)
|
||||
)
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
|
||||
fun changeLanguage(code: Int) {
|
||||
if (code != uiState.language) {
|
||||
viewModel.setLanguage(code)
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.language)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
) {
|
||||
LanguageOption(
|
||||
title = stringResource(R.string.lang_follow_system),
|
||||
selected = uiState.language == 0,
|
||||
onClick = { changeLanguage(0) }
|
||||
)
|
||||
LanguageOption(
|
||||
title = stringResource(R.string.lang_zh_cn),
|
||||
selected = uiState.language == 1,
|
||||
onClick = { changeLanguage(1) }
|
||||
)
|
||||
LanguageOption(
|
||||
title = stringResource(R.string.lang_zh_tw),
|
||||
selected = uiState.language == 2,
|
||||
onClick = { changeLanguage(2) }
|
||||
)
|
||||
LanguageOption(
|
||||
title = stringResource(R.string.lang_en),
|
||||
selected = uiState.language == 3,
|
||||
onClick = { changeLanguage(3) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LanguageOption(
|
||||
title: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
androidx.compose.material3.ListItem(
|
||||
headlineContent = {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.bodyLarge
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
RadioButton(selected = selected, onClick = onClick)
|
||||
},
|
||||
modifier = Modifier.clickable(onClick = onClick)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package cn.airnan.a2fair.ui.settings
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ColorLens
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.SettingsBackupRestore
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import cn.airnan.a2fair.BuildConfig
|
||||
import cn.airnan.a2fair.R
|
||||
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
onNavigateToSecurity: () -> Unit,
|
||||
onNavigateToBackup: () -> Unit,
|
||||
onNavigateToTheme: () -> Unit,
|
||||
onNavigateToLanguage: () -> Unit,
|
||||
onNavigateToAbout: () -> Unit
|
||||
) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) }
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.security)) },
|
||||
leadingContent = { Icon(Icons.Default.Lock, contentDescription = null) },
|
||||
modifier = Modifier.clickable { onNavigateToSecurity() }
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.backup_restore)) },
|
||||
leadingContent = { Icon(Icons.Default.SettingsBackupRestore, contentDescription = null) },
|
||||
modifier = Modifier.clickable { onNavigateToBackup() }
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.theme)) },
|
||||
leadingContent = { Icon(Icons.Default.ColorLens, contentDescription = null) },
|
||||
modifier = Modifier.clickable { onNavigateToTheme() }
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.language)) },
|
||||
leadingContent = { Icon(Icons.Default.Language, contentDescription = null) },
|
||||
modifier = Modifier.clickable { onNavigateToLanguage() }
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.about)) },
|
||||
leadingContent = { Icon(Icons.Default.Info, contentDescription = null) },
|
||||
trailingContent = {
|
||||
Text(
|
||||
text = "v${BuildConfig.VERSION_NAME}",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
},
|
||||
modifier = Modifier.clickable { onNavigateToAbout() }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package cn.airnan.a2fair.ui.settings
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
|
||||
data class SettingsUiState(
|
||||
val themeMode: Int = 0,
|
||||
val dynamicColor: Boolean = true,
|
||||
val seedColor: Int = 0xFF6750A4.toInt(),
|
||||
val language: Int = 0
|
||||
)
|
||||
|
||||
class SettingsViewModel(
|
||||
application: Application,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) : AndroidViewModel(application) {
|
||||
|
||||
val uiState: StateFlow<SettingsUiState> = combine(
|
||||
settingsRepository.themeMode,
|
||||
settingsRepository.dynamicColor,
|
||||
settingsRepository.seedColor,
|
||||
settingsRepository.language
|
||||
) { themeMode, dynamicColor, seedColor, language ->
|
||||
SettingsUiState(
|
||||
themeMode = themeMode,
|
||||
dynamicColor = dynamicColor,
|
||||
seedColor = seedColor,
|
||||
language = language
|
||||
)
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = SettingsUiState()
|
||||
)
|
||||
|
||||
fun setThemeMode(mode: Int) {
|
||||
viewModelScope.launch {
|
||||
settingsRepository.setThemeMode(mode)
|
||||
}
|
||||
}
|
||||
|
||||
fun setDynamicColor(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
settingsRepository.setDynamicColor(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
fun setSeedColor(color: Int) {
|
||||
viewModelScope.launch {
|
||||
settingsRepository.setSeedColor(color)
|
||||
}
|
||||
}
|
||||
|
||||
fun setLanguage(code: Int) {
|
||||
viewModelScope.launch {
|
||||
settingsRepository.setLanguage(code)
|
||||
}
|
||||
}
|
||||
|
||||
class Factory(private val application: Application) : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||
if (modelClass.isAssignableFrom(SettingsViewModel::class.java)) {
|
||||
val app = application as A2FairApplication
|
||||
return SettingsViewModel(application, app.settingsRepository) as T
|
||||
}
|
||||
throw IllegalArgumentException("Unknown ViewModel class")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package cn.airnan.a2fair.ui.settings
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.R
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ThemeSettingsScreen(
|
||||
onNavigateBack: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as A2FairApplication
|
||||
val viewModel: SettingsViewModel = viewModel(
|
||||
factory = SettingsViewModel.Factory(app)
|
||||
)
|
||||
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.theme_settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.theme_mode),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(16.dp),
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
horizontalArrangement = Arrangement.SpaceEvenly
|
||||
) {
|
||||
ThemeModeItem(
|
||||
title = stringResource(R.string.system),
|
||||
selected = uiState.themeMode == 0,
|
||||
onClick = { viewModel.setThemeMode(0) }
|
||||
)
|
||||
ThemeModeItem(
|
||||
title = stringResource(R.string.light),
|
||||
selected = uiState.themeMode == 1,
|
||||
onClick = { viewModel.setThemeMode(1) }
|
||||
)
|
||||
ThemeModeItem(
|
||||
title = stringResource(R.string.dark),
|
||||
selected = uiState.themeMode == 2,
|
||||
onClick = { viewModel.setThemeMode(2) }
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.color_palette),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(16.dp),
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.dynamic_color)) },
|
||||
supportingContent = { Text(stringResource(R.string.dynamic_color_desc)) },
|
||||
trailingContent = {
|
||||
Switch(
|
||||
checked = uiState.dynamicColor,
|
||||
onCheckedChange = { viewModel.setDynamicColor(it) }
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
if (!uiState.dynamicColor) {
|
||||
Text(
|
||||
text = stringResource(R.string.seed_color),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
)
|
||||
|
||||
val colors = listOf(
|
||||
0xFF6750A4, // Default Purple
|
||||
0xFF4CAF50, // Green
|
||||
0xFF2196F3, // Blue
|
||||
0xFFFF9800, // Light Blue
|
||||
0xFFE91E63, // Orange
|
||||
0xFFF44336, // Pink
|
||||
0xFF9C27B0, // Deep Purple
|
||||
0xFF795548 // Purple
|
||||
)
|
||||
|
||||
LazyRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp)
|
||||
) {
|
||||
items(colors) { colorInt ->
|
||||
val color = Color(colorInt)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(end = 8.dp)
|
||||
.size(48.dp)
|
||||
.clip(CircleShape)
|
||||
.background(color)
|
||||
.border(
|
||||
width = if (uiState.seedColor == colorInt.toInt()) 3.dp else 0.dp,
|
||||
color = if (uiState.seedColor == colorInt.toInt()) MaterialTheme.colorScheme.onSurface else Color.Transparent,
|
||||
shape = CircleShape
|
||||
)
|
||||
.clickable { viewModel.setSeedColor(colorInt.toInt()) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ThemeModeItem(title: String, selected: Boolean, onClick: () -> Unit) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.clickable(onClick = onClick)
|
||||
.border(
|
||||
width = if (selected) 2.dp else 1.dp,
|
||||
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
|
||||
shape = MaterialTheme.shapes.medium
|
||||
)
|
||||
.padding(vertical = 12.dp, horizontal = 24.dp)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package cn.airnan.a2fair.ui.settings.backup
|
||||
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.core.backup.BackupManager
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun BackupScreen(
|
||||
backupManager: BackupManager,
|
||||
onNavigateBack: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
var password by remember { mutableStateOf("") }
|
||||
var confirmPassword by remember { mutableStateOf("") }
|
||||
var isExporting by remember { mutableStateOf(true) }
|
||||
var showPasswordDialog by remember { mutableStateOf(false) }
|
||||
|
||||
val exportLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("application/octet-stream")
|
||||
) { uri: Uri? ->
|
||||
if (uri != null && password.isNotEmpty()) {
|
||||
scope.launch {
|
||||
val result = backupManager.exportData(uri, password.toCharArray())
|
||||
if (result.isSuccess) {
|
||||
Toast.makeText(context, context.getString(R.string.export_successful), Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.export_failed, result.exceptionOrNull()?.message ?: ""), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val importLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocument()
|
||||
) { uri: Uri? ->
|
||||
if (uri != null && password.isNotEmpty()) {
|
||||
scope.launch {
|
||||
val result = backupManager.importData(uri, password.toCharArray())
|
||||
if (result.isSuccess) {
|
||||
Toast.makeText(context, context.getString(R.string.import_successful), Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
Toast.makeText(context, context.getString(R.string.import_failed, result.exceptionOrNull()?.message ?: ""), Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.backup_restore)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
modifier = modifier
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.export_data),
|
||||
style = MaterialTheme.typography.titleLarge
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.export_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
isExporting = true
|
||||
showPasswordDialog = true
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(stringResource(R.string.export_to_file))
|
||||
}
|
||||
|
||||
Divider(modifier = Modifier.padding(vertical = 16.dp))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.import_data),
|
||||
style = MaterialTheme.typography.titleLarge
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.import_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
isExporting = false
|
||||
showPasswordDialog = true
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(stringResource(R.string.import_from_file))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showPasswordDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = {
|
||||
showPasswordDialog = false
|
||||
password = ""
|
||||
confirmPassword = ""
|
||||
},
|
||||
title = { Text(if (isExporting) stringResource(R.string.set_backup_password) else stringResource(R.string.enter_backup_password)) },
|
||||
text = {
|
||||
Column {
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text(stringResource(R.string.password)) },
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
if (isExporting) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = confirmPassword,
|
||||
onValueChange = { confirmPassword = it },
|
||||
label = { Text(stringResource(R.string.confirm_password)) },
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
isError = password != confirmPassword && confirmPassword.isNotEmpty()
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
if (password.isNotEmpty() && (!isExporting || password == confirmPassword)) {
|
||||
showPasswordDialog = false
|
||||
if (isExporting) {
|
||||
exportLauncher.launch("a2fair_backup_${System.currentTimeMillis()}.bak")
|
||||
} else {
|
||||
importLauncher.launch(arrayOf("application/octet-stream", "*/*"))
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = password.isNotEmpty() && (!isExporting || password == confirmPassword)
|
||||
) {
|
||||
Text(if (isExporting) stringResource(R.string.export_btn) else stringResource(R.string.import_btn))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showPasswordDialog = false
|
||||
password = ""
|
||||
confirmPassword = ""
|
||||
}
|
||||
) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package cn.airnan.a2fair.ui.settings.security
|
||||
|
||||
import android.widget.Toast
|
||||
import androidx.biometric.BiometricManager
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Fingerprint
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.R
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
fun LockScreen(
|
||||
onUnlock: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as A2FairApplication
|
||||
val settingsRepo = app.settingsRepository
|
||||
|
||||
val isBiometricEnabled by settingsRepo.isBiometricEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val pinCode by settingsRepo.pinCode.collectAsStateWithLifecycle(initialValue = null)
|
||||
|
||||
val failedAttempts by settingsRepo.failedAttempts.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val lockoutEndTime by settingsRepo.lockoutEndTime.collectAsStateWithLifecycle(initialValue = 0L)
|
||||
|
||||
var enteredPin by remember { mutableStateOf("") }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
val incorrectPinMsg = stringResource(R.string.incorrect_pin)
|
||||
var remainingLockOutTime by remember { mutableStateOf(0L) }
|
||||
|
||||
val scope = rememberCoroutineScope()
|
||||
val biometricFailedMsg = stringResource(R.string.biometric_failed)
|
||||
|
||||
LaunchedEffect(lockoutEndTime) {
|
||||
while (true) {
|
||||
val now = System.currentTimeMillis()
|
||||
if (now < lockoutEndTime) {
|
||||
remainingLockOutTime = (lockoutEndTime - now) / 1000
|
||||
} else {
|
||||
remainingLockOutTime = 0L
|
||||
if (failedAttempts >= 5) {
|
||||
settingsRepo.setFailedAttempts(0)
|
||||
}
|
||||
break
|
||||
}
|
||||
kotlinx.coroutines.delay(1000)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto prompt biometric if enabled
|
||||
LaunchedEffect(isBiometricEnabled) {
|
||||
if (isBiometricEnabled) {
|
||||
showBiometricPrompt(context as FragmentActivity, onUnlock, onFailed = {
|
||||
errorMessage = biometricFailedMsg
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Surface(modifier = modifier) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Lock,
|
||||
contentDescription = stringResource(R.string.lock_icon),
|
||||
modifier = Modifier.size(64.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.enter_pin),
|
||||
style = MaterialTheme.typography.headlineSmall
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = enteredPin,
|
||||
onValueChange = {
|
||||
enteredPin = it
|
||||
errorMessage = null
|
||||
},
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
isError = errorMessage != null,
|
||||
modifier = Modifier.fillMaxWidth(0.8f)
|
||||
)
|
||||
|
||||
if (errorMessage != null) {
|
||||
Text(
|
||||
text = errorMessage!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 4.dp)
|
||||
)
|
||||
}
|
||||
|
||||
if (remainingLockOutTime > 0) {
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.try_again_in, remainingLockOutTime),
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(top = 8.dp)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(0.8f),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
if (isBiometricEnabled && remainingLockOutTime == 0L) {
|
||||
IconButton(onClick = {
|
||||
showBiometricPrompt(context as FragmentActivity, onUnlock, onFailed = {
|
||||
errorMessage = biometricFailedMsg
|
||||
})
|
||||
}) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Fingerprint,
|
||||
contentDescription = stringResource(R.string.use_biometric),
|
||||
modifier = Modifier.size(48.dp)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Spacer(modifier = Modifier.width(48.dp))
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (pinCode != null && enteredPin == pinCode) {
|
||||
scope.launch {
|
||||
settingsRepo.setFailedAttempts(0)
|
||||
settingsRepo.setLockoutEndTime(0L)
|
||||
}
|
||||
onUnlock()
|
||||
} else {
|
||||
val newAttempts = failedAttempts + 1
|
||||
errorMessage = incorrectPinMsg
|
||||
enteredPin = ""
|
||||
scope.launch {
|
||||
settingsRepo.setFailedAttempts(newAttempts)
|
||||
if (newAttempts >= 5) {
|
||||
val lockoutTime = System.currentTimeMillis() + 30000L // 30s lockout
|
||||
settingsRepo.setLockoutEndTime(lockoutTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = remainingLockOutTime == 0L && enteredPin.isNotEmpty()
|
||||
) {
|
||||
Text(stringResource(R.string.unlock))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showBiometricPrompt(
|
||||
activity: FragmentActivity,
|
||||
onSuccess: () -> Unit,
|
||||
onFailed: () -> Unit
|
||||
) {
|
||||
val biometricManager = BiometricManager.from(activity)
|
||||
if (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL) != BiometricManager.BIOMETRIC_SUCCESS) {
|
||||
return
|
||||
}
|
||||
|
||||
val executor = ContextCompat.getMainExecutor(activity)
|
||||
val biometricPrompt = BiometricPrompt(activity, executor,
|
||||
object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
||||
super.onAuthenticationError(errorCode, errString)
|
||||
onFailed()
|
||||
}
|
||||
|
||||
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||
super.onAuthenticationSucceeded(result)
|
||||
onSuccess()
|
||||
}
|
||||
|
||||
override fun onAuthenticationFailed() {
|
||||
super.onAuthenticationFailed()
|
||||
onFailed()
|
||||
}
|
||||
})
|
||||
|
||||
val promptInfo = BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle(activity.getString(R.string.unlock_2fair))
|
||||
.setSubtitle(activity.getString(R.string.biometric_prompt_subtitle))
|
||||
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG or BiometricManager.Authenticators.DEVICE_CREDENTIAL)
|
||||
.build()
|
||||
|
||||
biometricPrompt.authenticate(promptInfo)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package cn.airnan.a2fair.ui.settings.security
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PinSetupScreen(
|
||||
settingsRepository: SettingsRepository,
|
||||
onNavigateBack: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
var step by remember { mutableStateOf(1) }
|
||||
var pin by remember { mutableStateOf("") }
|
||||
var confirmPin by remember { mutableStateOf("") }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val pinTooShortMsg = stringResource(R.string.pin_too_short)
|
||||
val pinsDoNotMatchMsg = stringResource(R.string.pins_do_not_match)
|
||||
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.set_pin)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
modifier = modifier
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Text(
|
||||
text = if (step == 1) stringResource(R.string.enter_new_pin) else stringResource(R.string.confirm_pin),
|
||||
style = MaterialTheme.typography.titleLarge
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = if (step == 1) pin else confirmPin,
|
||||
onValueChange = {
|
||||
if (step == 1) {
|
||||
pin = it
|
||||
} else {
|
||||
confirmPin = it
|
||||
}
|
||||
errorMessage = null
|
||||
},
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
singleLine = true,
|
||||
isError = errorMessage != null,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
|
||||
if (errorMessage != null) {
|
||||
Text(
|
||||
text = errorMessage!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 4.dp)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (step == 1) {
|
||||
if (pin.length < 4) {
|
||||
errorMessage = pinTooShortMsg
|
||||
} else {
|
||||
step = 2
|
||||
}
|
||||
} else {
|
||||
if (pin == confirmPin) {
|
||||
scope.launch {
|
||||
settingsRepository.setPinCode(pin)
|
||||
settingsRepository.setPinEnabled(true)
|
||||
onNavigateBack()
|
||||
}
|
||||
} else {
|
||||
errorMessage = pinsDoNotMatchMsg
|
||||
confirmPin = ""
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(if (step == 1) stringResource(R.string.next) else stringResource(R.string.confirm))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package cn.airnan.a2fair.ui.settings.security
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SecuritySettingsScreen(
|
||||
settingsRepository: SettingsRepository,
|
||||
onNavigateBack: () -> Unit,
|
||||
onNavigateToPinSetup: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val isPinEnabled by settingsRepository.isPinEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val isBiometricEnabled by settingsRepository.isBiometricEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val isFlagSecureEnabled by settingsRepository.isFlagSecureEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.security)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
modifier = modifier
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(stringResource(R.string.app_lock_pin), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(R.string.app_lock_pin_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = isPinEnabled,
|
||||
onCheckedChange = { checked ->
|
||||
if (checked) {
|
||||
onNavigateToPinSetup()
|
||||
} else {
|
||||
scope.launch {
|
||||
settingsRepository.setPinEnabled(false)
|
||||
settingsRepository.setPinCode(null)
|
||||
settingsRepository.setBiometricEnabled(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
if (isPinEnabled) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(stringResource(R.string.biometric_unlock), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(R.string.biometric_unlock_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = isBiometricEnabled,
|
||||
onCheckedChange = { checked ->
|
||||
scope.launch {
|
||||
settingsRepository.setBiometricEnabled(checked)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(stringResource(R.string.block_screenshots), style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
stringResource(R.string.block_screenshots_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = isFlagSecureEnabled,
|
||||
onCheckedChange = { checked ->
|
||||
scope.launch {
|
||||
settingsRepository.setFlagSecureEnabled(checked)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package cn.airnan.a2fair.ui.theme
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.core.view.WindowCompat
|
||||
import com.google.android.material.color.utilities.Hct
|
||||
import com.google.android.material.color.utilities.Scheme
|
||||
import com.google.android.material.color.utilities.TonalPalette
|
||||
|
||||
@Composable
|
||||
private fun colorSchemeFromSeed(seedColor: Int, darkTheme: Boolean): ColorScheme {
|
||||
val hct = Hct.fromInt(seedColor)
|
||||
val scheme = if (darkTheme) Scheme.dark(seedColor) else Scheme.light(seedColor)
|
||||
|
||||
// 中性调色板(与种子色相同色相,极低色度)
|
||||
val neutralPalette = TonalPalette.fromHueAndChroma(hct.hue, 4.0)
|
||||
val surfaceContainerLowest = Color(neutralPalette.tone(if (darkTheme) 6 else 100))
|
||||
val surfaceContainerLow = Color(neutralPalette.tone(if (darkTheme) 10 else 96))
|
||||
val surfaceContainer = Color(neutralPalette.tone(if (darkTheme) 12 else 94))
|
||||
val surfaceContainerHigh = Color(neutralPalette.tone(if (darkTheme) 17 else 92))
|
||||
val surfaceContainerHighest = Color(neutralPalette.tone(if (darkTheme) 22 else 90))
|
||||
|
||||
return if (darkTheme) {
|
||||
darkColorScheme(
|
||||
primary = Color(scheme.primary),
|
||||
onPrimary = Color(scheme.onPrimary),
|
||||
primaryContainer = Color(scheme.primaryContainer),
|
||||
onPrimaryContainer = Color(scheme.onPrimaryContainer),
|
||||
secondary = Color(scheme.secondary),
|
||||
onSecondary = Color(scheme.onSecondary),
|
||||
secondaryContainer = Color(scheme.secondaryContainer),
|
||||
onSecondaryContainer = Color(scheme.onSecondaryContainer),
|
||||
tertiary = Color(scheme.tertiary),
|
||||
onTertiary = Color(scheme.onTertiary),
|
||||
tertiaryContainer = Color(scheme.tertiaryContainer),
|
||||
onTertiaryContainer = Color(scheme.onTertiaryContainer),
|
||||
error = Color(scheme.error),
|
||||
onError = Color(scheme.onError),
|
||||
errorContainer = Color(scheme.errorContainer),
|
||||
onErrorContainer = Color(scheme.onErrorContainer),
|
||||
background = Color(scheme.background),
|
||||
onBackground = Color(scheme.onBackground),
|
||||
surface = Color(scheme.surface),
|
||||
onSurface = Color(scheme.onSurface),
|
||||
surfaceVariant = Color(scheme.surfaceVariant),
|
||||
onSurfaceVariant = Color(scheme.onSurfaceVariant),
|
||||
surfaceContainerLowest = surfaceContainerLowest,
|
||||
surfaceContainerLow = surfaceContainerLow,
|
||||
surfaceContainer = surfaceContainer,
|
||||
surfaceContainerHigh = surfaceContainerHigh,
|
||||
surfaceContainerHighest = surfaceContainerHighest,
|
||||
outline = Color(scheme.outline),
|
||||
outlineVariant = Color(scheme.outlineVariant),
|
||||
inverseSurface = Color(scheme.inverseSurface),
|
||||
inverseOnSurface = Color(scheme.inverseOnSurface),
|
||||
inversePrimary = Color(scheme.inversePrimary),
|
||||
surfaceTint = Color(scheme.primary),
|
||||
)
|
||||
} else {
|
||||
lightColorScheme(
|
||||
primary = Color(scheme.primary),
|
||||
onPrimary = Color(scheme.onPrimary),
|
||||
primaryContainer = Color(scheme.primaryContainer),
|
||||
onPrimaryContainer = Color(scheme.onPrimaryContainer),
|
||||
secondary = Color(scheme.secondary),
|
||||
onSecondary = Color(scheme.onSecondary),
|
||||
secondaryContainer = Color(scheme.secondaryContainer),
|
||||
onSecondaryContainer = Color(scheme.onSecondaryContainer),
|
||||
tertiary = Color(scheme.tertiary),
|
||||
onTertiary = Color(scheme.onTertiary),
|
||||
tertiaryContainer = Color(scheme.tertiaryContainer),
|
||||
onTertiaryContainer = Color(scheme.onTertiaryContainer),
|
||||
error = Color(scheme.error),
|
||||
onError = Color(scheme.onError),
|
||||
errorContainer = Color(scheme.errorContainer),
|
||||
onErrorContainer = Color(scheme.onErrorContainer),
|
||||
background = Color(scheme.background),
|
||||
onBackground = Color(scheme.onBackground),
|
||||
surface = Color(scheme.surface),
|
||||
onSurface = Color(scheme.onSurface),
|
||||
surfaceVariant = Color(scheme.surfaceVariant),
|
||||
onSurfaceVariant = Color(scheme.onSurfaceVariant),
|
||||
surfaceContainerLowest = surfaceContainerLowest,
|
||||
surfaceContainerLow = surfaceContainerLow,
|
||||
surfaceContainer = surfaceContainer,
|
||||
surfaceContainerHigh = surfaceContainerHigh,
|
||||
surfaceContainerHighest = surfaceContainerHighest,
|
||||
outline = Color(scheme.outline),
|
||||
outlineVariant = Color(scheme.outlineVariant),
|
||||
inverseSurface = Color(scheme.inverseSurface),
|
||||
inverseOnSurface = Color(scheme.inverseOnSurface),
|
||||
inversePrimary = Color(scheme.inversePrimary),
|
||||
surfaceTint = Color(scheme.primary),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
tailrec fun Context.findActivity(): Activity? = when (this) {
|
||||
is Activity -> this
|
||||
is ContextWrapper -> baseContext.findActivity()
|
||||
else -> null
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun _2FAirTheme(
|
||||
themeMode: Int = 0, // 0: System, 1: Light, 2: Dark
|
||||
dynamicColor: Boolean = true,
|
||||
seedColor: Int = 0xFF6750A4.toInt(),
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val darkTheme = when (themeMode) {
|
||||
1 -> false
|
||||
2 -> true
|
||||
else -> isSystemInDarkTheme()
|
||||
}
|
||||
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
else -> colorSchemeFromSeed(seedColor, darkTheme)
|
||||
}
|
||||
|
||||
val view = LocalView.current
|
||||
if (!view.isInEditMode) {
|
||||
SideEffect {
|
||||
val window = view.context.findActivity()?.window
|
||||
if (window != null) {
|
||||
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
|
||||
WindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = !darkTheme
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = Typography,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package cn.airnan.a2fair.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
// Set of Material typography styles to start with
|
||||
val Typography = Typography(
|
||||
bodyLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
/* Other default text styles to override
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 22.sp,
|
||||
lineHeight = 28.sp,
|
||||
letterSpacing = 0.sp
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
*/
|
||||
)
|
||||
@@ -0,0 +1,406 @@
|
||||
package cn.airnan.a2fair.ui.tokens
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageAnalysis
|
||||
import androidx.camera.core.ImageProxy
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.content.ContextCompat
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
import com.google.mlkit.vision.barcode.BarcodeScanning
|
||||
import com.google.mlkit.vision.barcode.common.Barcode
|
||||
import com.google.mlkit.vision.common.InputImage
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.MultiFormatReader
|
||||
import com.google.zxing.NotFoundException
|
||||
import com.google.zxing.PlanarYUVLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddTokenBottomSheet(
|
||||
viewModel: TokensViewModel,
|
||||
onDismissRequest: () -> Unit
|
||||
) {
|
||||
val state by viewModel.addTokenState.collectAsState()
|
||||
val context = LocalContext.current
|
||||
var showManualEntry by remember { mutableStateOf(false) }
|
||||
var showCameraScanner by remember { mutableStateOf(false) }
|
||||
|
||||
val photoPickerLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.PickVisualMedia()
|
||||
) { uri: Uri? ->
|
||||
if (uri != null) {
|
||||
try {
|
||||
val image = InputImage.fromFilePath(context, uri)
|
||||
val scanner = BarcodeScanning.getClient()
|
||||
scanner.process(image)
|
||||
.addOnSuccessListener { barcodes ->
|
||||
val barcode = barcodes.firstOrNull { it.valueType == Barcode.TYPE_WIFI || it.rawValue?.startsWith("otpauth://") == true }
|
||||
?: barcodes.firstOrNull()
|
||||
val rawValue = barcode?.rawValue
|
||||
if (rawValue != null && rawValue.startsWith("otpauth://")) {
|
||||
viewModel.addTokenFromUri(rawValue)
|
||||
} else {
|
||||
// Handle error: no valid QR code found
|
||||
}
|
||||
}
|
||||
.addOnFailureListener {
|
||||
// Handle error
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { isGranted ->
|
||||
if (isGranted) {
|
||||
showCameraScanner = true
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(state.isSuccess) {
|
||||
if (state.isSuccess) {
|
||||
viewModel.resetAddState()
|
||||
onDismissRequest()
|
||||
}
|
||||
}
|
||||
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = {
|
||||
viewModel.resetAddState()
|
||||
onDismissRequest()
|
||||
}
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = if (showManualEntry) stringResource(R.string.enter_details_manually) else stringResource(R.string.add_token_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(bottom = 16.dp)
|
||||
)
|
||||
|
||||
if (state.isError) {
|
||||
Text(
|
||||
text = state.errorMessage ?: stringResource(R.string.unknown_error),
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(bottom = 8.dp)
|
||||
)
|
||||
}
|
||||
|
||||
if (!showManualEntry) {
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.scan_qr_code)) },
|
||||
leadingContent = { Icon(Icons.Default.QrCodeScanner, contentDescription = null) },
|
||||
modifier = Modifier.clickable {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
|
||||
showCameraScanner = true
|
||||
} else {
|
||||
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
||||
}
|
||||
}
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.import_from_image)) },
|
||||
leadingContent = { Icon(Icons.Default.Image, contentDescription = null) },
|
||||
modifier = Modifier.clickable {
|
||||
photoPickerLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
|
||||
}
|
||||
)
|
||||
ListItem(
|
||||
headlineContent = { Text(stringResource(R.string.enter_manually)) },
|
||||
leadingContent = { Icon(Icons.Default.Keyboard, contentDescription = null) },
|
||||
modifier = Modifier.clickable { showManualEntry = true }
|
||||
)
|
||||
Spacer(modifier = Modifier.height(32.dp))
|
||||
} else {
|
||||
ManualEntryForm(
|
||||
state = state,
|
||||
viewModel = viewModel,
|
||||
onCancel = { showManualEntry = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showCameraScanner) {
|
||||
CameraScannerDialog(
|
||||
onScan = { uri ->
|
||||
showCameraScanner = false
|
||||
viewModel.addTokenFromUri(uri)
|
||||
},
|
||||
onDismissRequest = { showCameraScanner = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ManualEntryForm(
|
||||
state: AddTokenUiState,
|
||||
viewModel: TokensViewModel,
|
||||
onCancel: () -> Unit
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = state.accountName,
|
||||
onValueChange = viewModel::updateAccountName,
|
||||
label = { Text(stringResource(R.string.account_name_required)) },
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = state.secret,
|
||||
onValueChange = viewModel::updateSecret,
|
||||
label = { Text(stringResource(R.string.secret_key_required)) },
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = state.issuer,
|
||||
onValueChange = viewModel::updateIssuer,
|
||||
label = { Text(stringResource(R.string.issuer_optional)) },
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
// Type selection
|
||||
var expandedType by remember { mutableStateOf(false) }
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expandedType,
|
||||
onExpandedChange = { expandedType = !expandedType },
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = state.tokenType.name,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text(stringResource(R.string.type_label)) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedType) },
|
||||
modifier = Modifier.menuAnchor().fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expandedType,
|
||||
onDismissRequest = { expandedType = false }
|
||||
) {
|
||||
TokenType.entries.forEach { type ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(type.name) },
|
||||
onClick = {
|
||||
viewModel.updateTokenType(type)
|
||||
expandedType = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Advanced options could be hidden behind a toggle, but for simplicity we show them
|
||||
var expandedAlgorithm by remember { mutableStateOf(false) }
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expandedAlgorithm,
|
||||
onExpandedChange = { expandedAlgorithm = !expandedAlgorithm },
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = state.algorithm.name,
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text(stringResource(R.string.algorithm_label)) },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedAlgorithm) },
|
||||
modifier = Modifier.menuAnchor().fillMaxWidth()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expandedAlgorithm,
|
||||
onDismissRequest = { expandedAlgorithm = false }
|
||||
) {
|
||||
HashAlgorithm.entries.forEach { alg ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(alg.name) },
|
||||
onClick = {
|
||||
viewModel.updateAlgorithm(alg)
|
||||
expandedAlgorithm = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedTextField(
|
||||
value = state.digits.toString(),
|
||||
onValueChange = { it.toIntOrNull()?.let { d -> viewModel.updateDigits(d) } },
|
||||
label = { Text(stringResource(R.string.digits_label)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
|
||||
if (state.tokenType == TokenType.HOTP) {
|
||||
OutlinedTextField(
|
||||
value = state.counter.toString(),
|
||||
onValueChange = { it.toLongOrNull()?.let { c -> viewModel.updateCounter(c) } },
|
||||
label = { Text(stringResource(R.string.counter_label)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
value = state.period.toString(),
|
||||
onValueChange = { it.toIntOrNull()?.let { p -> viewModel.updatePeriod(p) } },
|
||||
label = { Text(stringResource(R.string.period_label)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 32.dp),
|
||||
horizontalArrangement = Arrangement.End
|
||||
) {
|
||||
TextButton(onClick = onCancel) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Button(onClick = viewModel::addTokenManually) {
|
||||
Text(stringResource(R.string.add))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CameraScannerDialog(
|
||||
onScan: (String) -> Unit,
|
||||
onDismissRequest: () -> Unit
|
||||
) {
|
||||
Dialog(
|
||||
onDismissRequest = onDismissRequest,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
CameraPreview(onScan = onScan)
|
||||
IconButton(
|
||||
onClick = onDismissRequest,
|
||||
modifier = Modifier.align(Alignment.TopStart).padding(16.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = stringResource(R.string.close), tint = MaterialTheme.colorScheme.onSurface)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CameraPreview(onScan: (String) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
var previewView by remember { mutableStateOf<PreviewView?>(null) }
|
||||
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
PreviewView(ctx).also {
|
||||
previewView = it
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
|
||||
LaunchedEffect(previewView) {
|
||||
val pv = previewView ?: return@LaunchedEffect
|
||||
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
|
||||
cameraProviderFuture.addListener({
|
||||
val cameraProvider = cameraProviderFuture.get()
|
||||
val preview = Preview.Builder().build().also {
|
||||
it.setSurfaceProvider(pv.surfaceProvider)
|
||||
}
|
||||
val imageAnalyzer = ImageAnalysis.Builder()
|
||||
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||
.build()
|
||||
.also {
|
||||
it.setAnalyzer(Executors.newSingleThreadExecutor(), ZxingAnalyzer(onScan))
|
||||
}
|
||||
|
||||
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
|
||||
try {
|
||||
cameraProvider.unbindAll()
|
||||
cameraProvider.bindToLifecycle(
|
||||
lifecycleOwner, cameraSelector, preview, imageAnalyzer
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}, ContextCompat.getMainExecutor(context))
|
||||
}
|
||||
}
|
||||
|
||||
class ZxingAnalyzer(private val onScan: (String) -> Unit) : ImageAnalysis.Analyzer {
|
||||
private val reader = MultiFormatReader()
|
||||
|
||||
override fun analyze(image: ImageProxy) {
|
||||
val buffer = image.planes[0].buffer
|
||||
val data = ByteArray(buffer.capacity())
|
||||
buffer.get(data)
|
||||
|
||||
val source = PlanarYUVLuminanceSource(
|
||||
data,
|
||||
image.width,
|
||||
image.height,
|
||||
0,
|
||||
0,
|
||||
image.width,
|
||||
image.height,
|
||||
false
|
||||
)
|
||||
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
|
||||
|
||||
try {
|
||||
val result = reader.decode(binaryBitmap)
|
||||
val text = result.text
|
||||
if (text.startsWith("otpauth://")) {
|
||||
onScan(text)
|
||||
}
|
||||
} catch (e: NotFoundException) {
|
||||
// No barcode found
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package cn.airnan.a2fair.ui.tokens
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.core.NativeLib
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun TokensScreen() {
|
||||
val context = LocalContext.current
|
||||
val app = context.applicationContext as A2FairApplication
|
||||
val viewModel: TokensViewModel = viewModel(
|
||||
factory = TokensViewModel.Factory(app)
|
||||
)
|
||||
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
var showAddBottomSheet by remember { mutableStateOf(false) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.tokens)) },
|
||||
actions = {
|
||||
// Optional action icons
|
||||
}
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
FloatingActionButton(onClick = { showAddBottomSheet = true }) {
|
||||
Icon(Icons.Default.Add, contentDescription = stringResource(R.string.add_token))
|
||||
}
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
) {
|
||||
// Search Bar
|
||||
OutlinedTextField(
|
||||
value = uiState.searchQuery,
|
||||
onValueChange = { viewModel.updateSearchQuery(it) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
placeholder = { Text(stringResource(R.string.search_tokens)) },
|
||||
leadingIcon = { Icon(Icons.Default.Search, contentDescription = stringResource(R.string.search)) },
|
||||
singleLine = true,
|
||||
shape = MaterialTheme.shapes.large
|
||||
)
|
||||
|
||||
// Token List
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(bottom = 80.dp)
|
||||
) {
|
||||
uiState.groupedTokens.forEach { (group, tokens) ->
|
||||
val groupId = group?.id
|
||||
val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L)
|
||||
|
||||
item(key = "group_${groupId ?: "unassigned"}") {
|
||||
GroupHeader(
|
||||
group = group,
|
||||
isCollapsed = isCollapsed,
|
||||
onToggle = { viewModel.toggleGroupCollapse(groupId) }
|
||||
)
|
||||
}
|
||||
|
||||
if (!isCollapsed) {
|
||||
items(tokens, key = { it.id }) { token ->
|
||||
TokenCard(
|
||||
token = token,
|
||||
onIncrement = { viewModel.incrementCounter(token) },
|
||||
onDelete = { viewModel.deleteToken(token) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showAddBottomSheet) {
|
||||
AddTokenBottomSheet(
|
||||
viewModel = viewModel,
|
||||
onDismissRequest = { showAddBottomSheet = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun GroupHeader(
|
||||
group: Group?,
|
||||
isCollapsed: Boolean,
|
||||
onToggle: () -> Unit
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onToggle)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = group?.name ?: stringResource(R.string.uncategorized),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
Icon(
|
||||
imageVector = if (isCollapsed) Icons.Default.ExpandMore else Icons.Default.ExpandLess,
|
||||
contentDescription = stringResource(R.string.toggle_group)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun TokenCard(
|
||||
token: Token,
|
||||
onIncrement: () -> Unit,
|
||||
onDelete: () -> Unit
|
||||
) {
|
||||
val otpPlaceholder = stringResource(R.string.otp_placeholder)
|
||||
val errorText = stringResource(R.string.error)
|
||||
var currentCode by remember { mutableStateOf(otpPlaceholder) }
|
||||
var progress by remember { mutableStateOf(1f) }
|
||||
var remainingSeconds by remember { mutableStateOf(0) }
|
||||
var showMenu by remember { mutableStateOf(false) }
|
||||
val context = LocalContext.current
|
||||
|
||||
val secretBytes = remember(token.secret.value) {
|
||||
try {
|
||||
NativeLib.base32Decode(token.secret.value)
|
||||
} catch (e: Exception) {
|
||||
ByteArray(0)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(token, secretBytes) {
|
||||
if (secretBytes.isEmpty()) {
|
||||
currentCode = errorText
|
||||
return@LaunchedEffect
|
||||
}
|
||||
while (true) {
|
||||
val now = System.currentTimeMillis()
|
||||
when (token.tokenType) {
|
||||
TokenType.TOTP -> {
|
||||
val periodMs = token.period * 1000L
|
||||
val time = now / 1000L
|
||||
currentCode = NativeLib.generateTOTP(
|
||||
secretBytes,
|
||||
time,
|
||||
token.period,
|
||||
token.digits,
|
||||
token.algorithm.ordinal
|
||||
)
|
||||
val remaining = periodMs - (now % periodMs)
|
||||
progress = remaining.toFloat() / periodMs.toFloat()
|
||||
remainingSeconds = (remaining / 1000L).toInt()
|
||||
}
|
||||
TokenType.STEAM -> {
|
||||
val time = now / 1000L
|
||||
currentCode = NativeLib.generateSteam(
|
||||
secretBytes,
|
||||
time
|
||||
)
|
||||
val periodMs = 30000L
|
||||
val remaining = periodMs - (now % periodMs)
|
||||
progress = remaining.toFloat() / periodMs.toFloat()
|
||||
remainingSeconds = (remaining / 1000L).toInt()
|
||||
}
|
||||
TokenType.HOTP -> {
|
||||
currentCode = NativeLib.generateHOTP(
|
||||
secretBytes,
|
||||
token.counter,
|
||||
token.digits,
|
||||
token.algorithm.ordinal
|
||||
)
|
||||
progress = 1f
|
||||
}
|
||||
}
|
||||
delay(100)
|
||||
}
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp)
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
copyToClipboard(context, currentCode, token.serviceName)
|
||||
},
|
||||
onLongClick = { showMenu = true }
|
||||
),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
|
||||
) {
|
||||
Box {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
TokenIcon(token)
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = token.serviceName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
if (token.issuer.isNotBlank()) {
|
||||
Text(
|
||||
text = token.issuer,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = formatCode(currentCode),
|
||||
style = MaterialTheme.typography.headlineSmall.copy(
|
||||
letterSpacing = 2.sp,
|
||||
fontFeatureSettings = "tnum"
|
||||
),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
if (token.tokenType == TokenType.HOTP) {
|
||||
IconButton(onClick = onIncrement) {
|
||||
Icon(Icons.Default.Refresh, contentDescription = stringResource(R.string.refresh_hotp))
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier.size(44.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
progress = { progress },
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = if (progress < 0.15f) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary,
|
||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
strokeWidth = 3.dp,
|
||||
)
|
||||
Text(
|
||||
text = "$remainingSeconds",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = if (progress < 0.15f) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DropdownMenu(
|
||||
expanded = showMenu,
|
||||
onDismissRequest = { showMenu = false }
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.copy_code)) },
|
||||
onClick = {
|
||||
showMenu = false
|
||||
copyToClipboard(context, currentCode, token.serviceName)
|
||||
},
|
||||
leadingIcon = { Icon(Icons.Default.ContentCopy, contentDescription = null) }
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.edit)) },
|
||||
onClick = {
|
||||
showMenu = false
|
||||
},
|
||||
leadingIcon = { Icon(Icons.Default.Edit, contentDescription = null) }
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.delete)) },
|
||||
onClick = {
|
||||
showMenu = false
|
||||
onDelete()
|
||||
},
|
||||
leadingIcon = { Icon(Icons.Default.Delete, contentDescription = null) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun TokenIcon(token: Token) {
|
||||
val letter = token.issuer.takeIf { it.isNotBlank() }?.firstOrNull()?.uppercaseChar()
|
||||
?: token.serviceName.firstOrNull()?.uppercaseChar()
|
||||
?: '?'
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.primaryContainer),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(
|
||||
text = letter.toString(),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatCode(code: String): String {
|
||||
if (code.length == 6) {
|
||||
return "${code.substring(0, 3)} ${code.substring(3)}"
|
||||
}
|
||||
if (code.length == 8) {
|
||||
return "${code.substring(0, 4)} ${code.substring(4)}"
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
private fun copyToClipboard(context: Context, code: String, label: String) {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = ClipData.newPlainText("OTP Code", code)
|
||||
clipboard.setPrimaryClip(clip)
|
||||
Toast.makeText(context, context.getString(R.string.code_copied, label), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package cn.airnan.a2fair.ui.tokens
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import cn.airnan.a2fair.A2FairApplication
|
||||
import cn.airnan.a2fair.R
|
||||
import cn.airnan.a2fair.core.OtpUriParser
|
||||
import cn.airnan.a2fair.data.SecretString
|
||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||
import cn.airnan.a2fair.data.entity.Token
|
||||
import cn.airnan.a2fair.data.entity.TokenType
|
||||
import cn.airnan.a2fair.data.repository.TokenRepository
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
import cn.airnan.a2fair.data.entity.Group
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
|
||||
data class AddTokenUiState(
|
||||
val issuer: String = "",
|
||||
val accountName: String = "",
|
||||
val secret: String = "",
|
||||
val tokenType: TokenType = TokenType.TOTP,
|
||||
val algorithm: HashAlgorithm = HashAlgorithm.SHA1,
|
||||
val digits: Int = 6,
|
||||
val period: Int = 30,
|
||||
val counter: Long = 0,
|
||||
val isError: Boolean = false,
|
||||
val errorMessage: String? = null,
|
||||
val isSuccess: Boolean = false
|
||||
)
|
||||
|
||||
data class TokensUiState(
|
||||
val groupedTokens: Map<Group?, List<Token>> = emptyMap(),
|
||||
val searchQuery: String = "",
|
||||
val collapsedGroups: Set<Long> = emptySet()
|
||||
)
|
||||
|
||||
class TokensViewModel(
|
||||
application: Application,
|
||||
private val tokenRepository: TokenRepository
|
||||
) : AndroidViewModel(application) {
|
||||
|
||||
private val _searchQuery = MutableStateFlow("")
|
||||
private val _collapsedGroups = MutableStateFlow<Set<Long>>(emptySet())
|
||||
|
||||
val uiState: StateFlow<TokensUiState> = combine(
|
||||
tokenRepository.getAllTokens(),
|
||||
tokenRepository.getAllGroups(),
|
||||
_searchQuery,
|
||||
_collapsedGroups
|
||||
) { tokens, groups, query, collapsed ->
|
||||
val filteredTokens = if (query.isBlank()) {
|
||||
tokens
|
||||
} else {
|
||||
tokens.filter {
|
||||
it.issuer.contains(query, ignoreCase = true) ||
|
||||
it.serviceName.contains(query, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
val groupMap = groups.associateBy { it.id }
|
||||
|
||||
val grouped = filteredTokens.groupBy { token ->
|
||||
token.groupId?.let { groupMap[it] }
|
||||
}.toSortedMap(compareBy(nullsFirst()) { it?.sortOrder ?: Int.MAX_VALUE })
|
||||
|
||||
val sortedGrouped = grouped.mapValues { entry ->
|
||||
entry.value.sortedWith(compareBy({ it.sortOrder }, { it.serviceName }))
|
||||
}
|
||||
|
||||
TokensUiState(
|
||||
groupedTokens = sortedGrouped,
|
||||
searchQuery = query,
|
||||
collapsedGroups = collapsed
|
||||
)
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = TokensUiState()
|
||||
)
|
||||
|
||||
fun updateSearchQuery(query: String) {
|
||||
_searchQuery.value = query
|
||||
}
|
||||
|
||||
fun toggleGroupCollapse(groupId: Long?) {
|
||||
val id = groupId ?: -1L
|
||||
_collapsedGroups.update { current ->
|
||||
if (current.contains(id)) {
|
||||
current - id
|
||||
} else {
|
||||
current + id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteToken(token: Token) {
|
||||
viewModelScope.launch {
|
||||
tokenRepository.deleteToken(token)
|
||||
}
|
||||
}
|
||||
|
||||
fun incrementCounter(token: Token) {
|
||||
viewModelScope.launch {
|
||||
tokenRepository.updateCounter(token.id, token.counter + 1)
|
||||
}
|
||||
}
|
||||
|
||||
private val _addTokenState = MutableStateFlow(AddTokenUiState())
|
||||
val addTokenState: StateFlow<AddTokenUiState> = _addTokenState.asStateFlow()
|
||||
|
||||
fun updateIssuer(issuer: String) {
|
||||
_addTokenState.update { it.copy(issuer = issuer) }
|
||||
}
|
||||
|
||||
fun updateAccountName(accountName: String) {
|
||||
_addTokenState.update { it.copy(accountName = accountName) }
|
||||
}
|
||||
|
||||
fun updateSecret(secret: String) {
|
||||
// Strip spaces
|
||||
_addTokenState.update { it.copy(secret = secret.replace(" ", "")) }
|
||||
}
|
||||
|
||||
fun updateTokenType(type: TokenType) {
|
||||
_addTokenState.update { it.copy(tokenType = type) }
|
||||
}
|
||||
|
||||
fun updateAlgorithm(algorithm: HashAlgorithm) {
|
||||
_addTokenState.update { it.copy(algorithm = algorithm) }
|
||||
}
|
||||
|
||||
fun updateDigits(digits: Int) {
|
||||
_addTokenState.update { it.copy(digits = digits) }
|
||||
}
|
||||
|
||||
fun updatePeriod(period: Int) {
|
||||
_addTokenState.update { it.copy(period = period) }
|
||||
}
|
||||
|
||||
fun updateCounter(counter: Long) {
|
||||
_addTokenState.update { it.copy(counter = counter) }
|
||||
}
|
||||
|
||||
fun resetAddState() {
|
||||
_addTokenState.value = AddTokenUiState()
|
||||
}
|
||||
|
||||
fun addTokenFromUri(uriString: String) {
|
||||
try {
|
||||
val token = OtpUriParser.parse(uriString)
|
||||
saveToken(token)
|
||||
} catch (e: Exception) {
|
||||
_addTokenState.update { it.copy(isError = true, errorMessage = getApplication<Application>().getString(R.string.failed_parse_qr, e.message ?: "")) }
|
||||
}
|
||||
}
|
||||
|
||||
fun addTokenManually() {
|
||||
val state = _addTokenState.value
|
||||
if (state.secret.isBlank() || state.accountName.isBlank()) {
|
||||
_addTokenState.update { it.copy(isError = true, errorMessage = getApplication<Application>().getString(R.string.secret_and_account_required)) }
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val token = Token(
|
||||
issuer = state.issuer,
|
||||
serviceName = state.accountName,
|
||||
secret = SecretString(state.secret),
|
||||
tokenType = state.tokenType,
|
||||
algorithm = state.algorithm,
|
||||
digits = state.digits,
|
||||
period = state.period,
|
||||
counter = state.counter
|
||||
)
|
||||
saveToken(token)
|
||||
} catch (e: Exception) {
|
||||
_addTokenState.update { it.copy(isError = true, errorMessage = e.message) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveToken(token: Token) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
tokenRepository.insertToken(token)
|
||||
_addTokenState.update { it.copy(isSuccess = true, isError = false, errorMessage = null) }
|
||||
} catch (e: Exception) {
|
||||
_addTokenState.update { it.copy(isError = true, errorMessage = getApplication<Application>().getString(R.string.failed_save_token, e.message ?: "")) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearError() {
|
||||
_addTokenState.update { it.copy(isError = false, errorMessage = null) }
|
||||
}
|
||||
|
||||
class Factory(private val application: Application) : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
||||
if (modelClass.isAssignableFrom(TokensViewModel::class.java)) {
|
||||
val app = application as A2FairApplication
|
||||
return TokensViewModel(application, app.tokenRepository) as T
|
||||
}
|
||||
throw IllegalArgumentException("Unknown ViewModel class")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user