Compare commits

..
3 Commits
12 changed files with 772 additions and 165 deletions
@@ -3,25 +3,46 @@ package cn.airnan.a2fair.core.backup
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import cn.airnan.a2fair.crypto.CryptoManager import cn.airnan.a2fair.crypto.CryptoManager
import cn.airnan.a2fair.data.normalizeSecret
import cn.airnan.a2fair.data.entity.Group import cn.airnan.a2fair.data.entity.Group
import cn.airnan.a2fair.data.entity.Token import cn.airnan.a2fair.data.entity.Token
import cn.airnan.a2fair.data.repository.TokenRepository import cn.airnan.a2fair.data.repository.TokenRepository
import com.google.gson.Gson import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.security.SecureRandom import java.security.SecureRandom
import javax.crypto.AEADBadTagException
import javax.crypto.Cipher import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.PBEKeySpec import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec import javax.crypto.spec.SecretKeySpec
const val BACKUP_VERSION = 1
class EmptyBackupException : Exception("backup is empty")
class UnsupportedBackupVersionException :
Exception("backup version is newer than supported")
class WrongPasswordException : Exception("wrong backup password")
class InvalidBackupFileException : Exception("not a valid backup file")
data class BackupData( data class BackupData(
val version: Int = BACKUP_VERSION,
val groups: List<Group>, val groups: List<Group>,
val tokens: List<Token> val tokens: List<Token>
) )
data class ImportStats(
val groupsImported: Int,
val tokensImported: Int,
val tokensSkipped: Int
)
class BackupManager( class BackupManager(
private val context: Context, private val context: Context,
private val tokenRepository: TokenRepository, private val tokenRepository: TokenRepository,
@@ -29,9 +50,14 @@ class BackupManager(
) { ) {
private val gson = Gson() private val gson = Gson()
suspend fun getTokenCount(): Int = tokenRepository.getAllTokens().first().size
suspend fun exportData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) { suspend fun exportData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) {
try { try {
val tokens = tokenRepository.getAllTokens().first() val tokens = tokenRepository.getAllTokens().first()
if (tokens.isEmpty()) {
return@withContext Result.failure(EmptyBackupException())
}
val groups = tokenRepository.getAllGroups().first() val groups = tokenRepository.getAllGroups().first()
// Decrypt tokens before exporting // Decrypt tokens before exporting
@@ -42,7 +68,7 @@ class BackupManager(
) )
} }
val backupData = BackupData(groups, decryptedTokens) val backupData = BackupData(groups = groups, tokens = decryptedTokens)
val json = gson.toJson(backupData) val json = gson.toJson(backupData)
val jsonBytes = json.toByteArray(Charsets.UTF_8) val jsonBytes = json.toByteArray(Charsets.UTF_8)
@@ -74,50 +100,94 @@ class BackupManager(
} }
} }
suspend fun importData(uri: Uri, password: CharArray): Result<Unit> = withContext(Dispatchers.IO) { suspend fun importData(uri: Uri, password: CharArray): Result<ImportStats> = withContext(Dispatchers.IO) {
try { try {
val encryptedBytes = context.contentResolver.openInputStream(uri)?.use { input -> val encryptedBytes = context.contentResolver.openInputStream(uri)?.use { input ->
input.readBytes() input.readBytes()
} ?: return@withContext Result.failure(Exception("Could not open input stream")) } ?: return@withContext Result.failure(InvalidBackupFileException())
var offset = 0 val salt: ByteArray
val saltLength = encryptedBytes[offset++].toInt() val iv: ByteArray
val salt = encryptedBytes.copyOfRange(offset, offset + saltLength) val data: ByteArray
offset += saltLength try {
var offset = 0
val saltLength = encryptedBytes[offset++].toInt()
salt = encryptedBytes.copyOfRange(offset, offset + saltLength)
offset += saltLength
val ivLength = encryptedBytes[offset++].toInt() val ivLength = encryptedBytes[offset++].toInt()
val iv = encryptedBytes.copyOfRange(offset, offset + ivLength) iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
offset += ivLength offset += ivLength
val data = encryptedBytes.copyOfRange(offset, encryptedBytes.size) data = encryptedBytes.copyOfRange(offset, encryptedBytes.size)
} catch (e: IndexOutOfBoundsException) {
return@withContext Result.failure(InvalidBackupFileException())
}
// Derive key // Derive key
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
val spec = PBEKeySpec(password, salt, 10000, 256) val spec = PBEKeySpec(password, salt, 10000, 256)
val secretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES") val secretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
// Decrypt // Decrypt; a GCM tag mismatch means the password is wrong
val cipher = Cipher.getInstance("AES/GCM/NoPadding") val decryptedBytes = try {
val gcmSpec = GCMParameterSpec(128, iv) val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec) val gcmSpec = GCMParameterSpec(128, iv)
val decryptedBytes = cipher.doFinal(data) cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec)
cipher.doFinal(data)
} catch (e: AEADBadTagException) {
return@withContext Result.failure(WrongPasswordException())
}
val json = String(decryptedBytes, Charsets.UTF_8) val json = String(decryptedBytes, Charsets.UTF_8)
val backupData = gson.fromJson(json, BackupData::class.java) val backupData = try {
gson.fromJson(json, BackupData::class.java)
} catch (e: JsonSyntaxException) {
return@withContext Result.failure(InvalidBackupFileException())
}
// Merge logic (simple replace or merge) if (backupData.version > BACKUP_VERSION) {
// For now, let's just insert all if not exists, or replace. We'll do a simple insert. return@withContext Result.failure(UnsupportedBackupVersionException())
}
if (backupData.groups.isEmpty() && backupData.tokens.isEmpty()) {
return@withContext Result.failure(EmptyBackupException())
}
// Existing state for dedup and group name mapping
val existingSecrets = tokenRepository.getAllTokens().first()
.mapTo(mutableSetOf()) { it.secret.value.normalizeSecret() }
val groupNameToId = tokenRepository.getAllGroups().first()
.associate { it.name to it.id }
.toMutableMap()
// Restore groups, dedup by name, build old-id -> new-id mapping
val groupIdMapping = mutableMapOf<Long, Long>()
var groupsImported = 0
backupData.groups.forEach { group -> backupData.groups.forEach { group ->
// Ensure group doesn't duplicate by name? val targetId = groupNameToId[group.name] ?: run {
// For simplicity, insert directly, handle id mapping later if needed. val newId = tokenRepository.insertGroup(group.copy(id = 0))
tokenRepository.insertGroup(group.copy(id = 0)) groupNameToId[group.name] = newId
groupsImported++
newId
}
groupIdMapping[group.id] = targetId
} }
// Restore tokens: dedup by normalized secret, remap groupId
var tokensImported = 0
var tokensSkipped = 0
backupData.tokens.forEach { token -> backupData.tokens.forEach { token ->
tokenRepository.insertToken(token.copy(id = 0)) if (token.secret.value.normalizeSecret() in existingSecrets) {
tokensSkipped++
return@forEach
}
val remappedGroupId = token.groupId?.let { groupIdMapping[it] }
tokenRepository.insertToken(token.copy(id = 0, groupId = remappedGroupId))
existingSecrets.add(token.secret.value.normalizeSecret())
tokensImported++
} }
Result.success(Unit) Result.success(ImportStats(groupsImported, tokensImported, tokensSkipped))
} catch (e: Exception) { } catch (e: Exception) {
Result.failure(e) Result.failure(e)
} }
@@ -5,3 +5,8 @@ data class SecretString(val value: String) {
return "***" return "***"
} }
} }
/** Normalizes a base32 secret for comparison: uppercase, strip non-alphabet chars. */
fun String.normalizeSecret(): String {
return this.uppercase().replace(Regex("[^A-Z2-7]"), "")
}
@@ -41,11 +41,12 @@ data class AppLockSettings(
val isBiometricEnabled: Boolean = false, val isBiometricEnabled: Boolean = false,
val lockTrigger: AppLockTrigger = AppLockTrigger.DEFAULT val lockTrigger: AppLockTrigger = AppLockTrigger.DEFAULT
) { ) {
/** App locks when PIN is active or biometric unlock is enabled on its own. */
val isAppLockEnabled: Boolean val isAppLockEnabled: Boolean
get() = isPinEnabled && hasPinCode get() = (isPinEnabled && hasPinCode) || isBiometricEnabled
val canUseBiometric: Boolean val canUseBiometric: Boolean
get() = isAppLockEnabled && isBiometricEnabled get() = isBiometricEnabled
} }
class SettingsRepository(private val context: Context, private val cryptoManager: CryptoManager) { class SettingsRepository(private val context: Context, private val cryptoManager: CryptoManager) {
@@ -86,11 +87,10 @@ class SettingsRepository(private val context: Context, private val cryptoManager
storedLockTrigger storedLockTrigger
) { pinEnabled, decryptedPinCode, biometricEnabled, lockTrigger -> ) { pinEnabled, decryptedPinCode, biometricEnabled, lockTrigger ->
val hasPinCode = decryptedPinCode?.isValidPin() == true val hasPinCode = decryptedPinCode?.isValidPin() == true
val isAppLockEnabled = pinEnabled && hasPinCode
AppLockSettings( AppLockSettings(
isPinEnabled = isAppLockEnabled, isPinEnabled = pinEnabled && hasPinCode,
hasPinCode = hasPinCode, hasPinCode = hasPinCode,
isBiometricEnabled = isAppLockEnabled && biometricEnabled, isBiometricEnabled = biometricEnabled,
lockTrigger = lockTrigger lockTrigger = lockTrigger
) )
} }
@@ -110,19 +110,6 @@ class SettingsRepository(private val context: Context, private val cryptoManager
} }
} }
suspend fun setPinCode(pin: String?) {
require(pin == null || pin.isValidPin()) { "PIN must be exactly 6 digits." }
dataStore.edit { preferences ->
if (pin == null) {
preferences.remove(PreferencesKeys.PIN_CODE)
preferences[PreferencesKeys.PIN_ENABLED] = false
preferences[PreferencesKeys.BIOMETRIC_ENABLED] = false
} else {
preferences[PreferencesKeys.PIN_CODE] = cryptoManager.encrypt(pin)
}
}
}
suspend fun enablePin(pin: String) { suspend fun enablePin(pin: String) {
require(pin.isValidPin()) { "PIN must be exactly 6 digits." } require(pin.isValidPin()) { "PIN must be exactly 6 digits." }
dataStore.edit { preferences -> dataStore.edit { preferences ->
@@ -134,7 +121,6 @@ class SettingsRepository(private val context: Context, private val cryptoManager
suspend fun disablePin() { suspend fun disablePin() {
dataStore.edit { preferences -> dataStore.edit { preferences ->
preferences[PreferencesKeys.PIN_ENABLED] = false preferences[PreferencesKeys.PIN_ENABLED] = false
preferences[PreferencesKeys.BIOMETRIC_ENABLED] = false
preferences.remove(PreferencesKeys.PIN_CODE) preferences.remove(PreferencesKeys.PIN_CODE)
preferences[PreferencesKeys.FAILED_ATTEMPTS] = 0 preferences[PreferencesKeys.FAILED_ATTEMPTS] = 0
preferences[PreferencesKeys.LOCKOUT_END_TIME] = 0L preferences[PreferencesKeys.LOCKOUT_END_TIME] = 0L
@@ -147,9 +133,7 @@ class SettingsRepository(private val context: Context, private val cryptoManager
suspend fun setBiometricEnabled(enabled: Boolean) { suspend fun setBiometricEnabled(enabled: Boolean) {
dataStore.edit { preferences -> dataStore.edit { preferences ->
val hasPinCode = preferences[PreferencesKeys.PIN_CODE] != null preferences[PreferencesKeys.BIOMETRIC_ENABLED] = enabled
val isPinEnabled = preferences[PreferencesKeys.PIN_ENABLED] ?: false
preferences[PreferencesKeys.BIOMETRIC_ENABLED] = enabled && hasPinCode && isPinEnabled
} }
} }
@@ -163,6 +147,17 @@ class SettingsRepository(private val context: Context, private val cryptoManager
} }
} }
/** Display position of the Uncategorized pseudo-group; MAX_VALUE keeps it last. */
val uncategorizedOrder: Flow<Int> = dataStore.data.map { preferences ->
preferences[PreferencesKeys.UNCATEGORIZED_ORDER] ?: Int.MAX_VALUE
}
suspend fun setUncategorizedOrder(index: Int) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.UNCATEGORIZED_ORDER] = index
}
}
suspend fun getLastBackgroundTime(): Long { suspend fun getLastBackgroundTime(): Long {
return dataStore.data.map { it[PreferencesKeys.LAST_BACKGROUND_TIME] ?: 0L }.first() return dataStore.data.map { it[PreferencesKeys.LAST_BACKGROUND_TIME] ?: 0L }.first()
} }
@@ -266,5 +261,6 @@ class SettingsRepository(private val context: Context, private val cryptoManager
val DYNAMIC_COLOR = booleanPreferencesKey("dynamic_color") val DYNAMIC_COLOR = booleanPreferencesKey("dynamic_color")
val SEED_COLOR = intPreferencesKey("seed_color") val SEED_COLOR = intPreferencesKey("seed_color")
val LANGUAGE = intPreferencesKey("language") val LANGUAGE = intPreferencesKey("language")
val UNCATEGORIZED_ORDER = intPreferencesKey("uncategorized_order")
} }
} }
@@ -33,6 +33,7 @@ fun BackupScreen(
var confirmPassword by remember { mutableStateOf("") } var confirmPassword by remember { mutableStateOf("") }
var isExporting by remember { mutableStateOf(true) } var isExporting by remember { mutableStateOf(true) }
var showPasswordDialog by remember { mutableStateOf(false) } var showPasswordDialog by remember { mutableStateOf(false) }
var pendingImportUri by remember { mutableStateOf<Uri?>(null) }
val exportLauncher = rememberLauncherForActivityResult( val exportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/octet-stream") contract = ActivityResultContracts.CreateDocument("application/octet-stream")
@@ -40,6 +41,8 @@ fun BackupScreen(
if (uri != null && password.isNotEmpty()) { if (uri != null && password.isNotEmpty()) {
scope.launch { scope.launch {
val result = backupManager.exportData(uri, password.toCharArray()) val result = backupManager.exportData(uri, password.toCharArray())
password = ""
confirmPassword = ""
if (result.isSuccess) { if (result.isSuccess) {
Toast.makeText(context, context.getString(R.string.export_successful), Toast.LENGTH_SHORT).show() Toast.makeText(context, context.getString(R.string.export_successful), Toast.LENGTH_SHORT).show()
} else { } else {
@@ -52,15 +55,9 @@ fun BackupScreen(
val importLauncher = rememberLauncherForActivityResult( val importLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument() contract = ActivityResultContracts.OpenDocument()
) { uri: Uri? -> ) { uri: Uri? ->
if (uri != null && password.isNotEmpty()) { if (uri != null) {
scope.launch { pendingImportUri = uri
val result = backupManager.importData(uri, password.toCharArray()) showPasswordDialog = true
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()
}
}
} }
} }
@@ -95,8 +92,14 @@ fun BackupScreen(
) )
Button( Button(
onClick = { onClick = {
isExporting = true scope.launch {
showPasswordDialog = true if (backupManager.getTokenCount() == 0) {
Toast.makeText(context, context.getString(R.string.backup_empty_tokens), Toast.LENGTH_LONG).show()
} else {
isExporting = true
showPasswordDialog = true
}
}
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
@@ -117,7 +120,7 @@ fun BackupScreen(
Button( Button(
onClick = { onClick = {
isExporting = false isExporting = false
showPasswordDialog = true importLauncher.launch(arrayOf("application/octet-stream", "*/*"))
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
@@ -167,7 +170,35 @@ fun BackupScreen(
if (isExporting) { if (isExporting) {
exportLauncher.launch("a2fair_backup_${System.currentTimeMillis()}.bak") exportLauncher.launch("a2fair_backup_${System.currentTimeMillis()}.bak")
} else { } else {
importLauncher.launch(arrayOf("application/octet-stream", "*/*")) val uri = pendingImportUri
pendingImportUri = null
if (uri != null) {
scope.launch {
val result = backupManager.importData(uri, password.toCharArray())
val stats = result.getOrNull()
if (stats != null) {
Toast.makeText(
context,
context.getString(R.string.import_success_stats, stats.tokensImported, stats.tokensSkipped, stats.groupsImported),
Toast.LENGTH_LONG
).show()
} else {
val messageRes = when (result.exceptionOrNull()) {
is cn.airnan.a2fair.core.backup.EmptyBackupException -> R.string.import_empty_backup
is cn.airnan.a2fair.core.backup.UnsupportedBackupVersionException -> R.string.import_unsupported_version
is cn.airnan.a2fair.core.backup.WrongPasswordException -> R.string.import_wrong_password
is cn.airnan.a2fair.core.backup.InvalidBackupFileException -> R.string.import_invalid_file
else -> null
}
if (messageRes != null) {
Toast.makeText(context, context.getString(messageRes), Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context, context.getString(R.string.import_failed, result.exceptionOrNull()?.message ?: ""), Toast.LENGTH_LONG).show()
}
}
password = ""
}
}
} }
} }
}, },
@@ -180,6 +211,7 @@ fun BackupScreen(
TextButton( TextButton(
onClick = { onClick = {
showPasswordDialog = false showPasswordDialog = false
pendingImportUri = null
password = "" password = ""
confirmPassword = "" confirmPassword = ""
} }
@@ -34,6 +34,8 @@ fun LockScreen(
val pinCode by settingsRepo.pinCode.collectAsStateWithLifecycle(initialValue = null) val pinCode by settingsRepo.pinCode.collectAsStateWithLifecycle(initialValue = null)
val isBiometricEnabled = appLockSettings.canUseBiometric val isBiometricEnabled = appLockSettings.canUseBiometric
val hasPin = appLockSettings.isPinEnabled && pinCode != null
var biometricUnavailable by remember { mutableStateOf(false) }
val failedAttempts by settingsRepo.failedAttempts.collectAsStateWithLifecycle(initialValue = 0) val failedAttempts by settingsRepo.failedAttempts.collectAsStateWithLifecycle(initialValue = 0)
val lockoutEndTime by settingsRepo.lockoutEndTime.collectAsStateWithLifecycle(initialValue = 0L) val lockoutEndTime by settingsRepo.lockoutEndTime.collectAsStateWithLifecycle(initialValue = 0L)
@@ -66,15 +68,19 @@ fun LockScreen(
LaunchedEffect(isBiometricEnabled) { LaunchedEffect(isBiometricEnabled) {
if (isBiometricEnabled) { if (isBiometricEnabled) {
biometricAuthenticator.authenticate( if (biometricAuthenticator.getAvailability(BiometricAuthMode.AppConfirmation) != null) {
mode = BiometricAuthMode.AppConfirmation, biometricUnavailable = true
titleRes = R.string.unlock_2fair, } else {
subtitleRes = R.string.biometric_prompt_subtitle biometricAuthenticator.authenticate(
) { result -> mode = BiometricAuthMode.AppConfirmation,
when (result) { titleRes = R.string.unlock_2fair,
BiometricAuthResult.Success -> onUnlock() subtitleRes = R.string.biometric_prompt_subtitle
BiometricAuthResult.Failed -> errorMessage = biometricFailedMsg ) { result ->
else -> Unit when (result) {
BiometricAuthResult.Success -> onUnlock()
BiometricAuthResult.Failed -> errorMessage = biometricFailedMsg
else -> Unit
}
} }
} }
} }
@@ -119,69 +125,84 @@ fun LockScreen(
) )
Spacer(modifier = Modifier.height(32.dp)) Spacer(modifier = Modifier.height(32.dp))
if (isBiometricEnabled && biometricUnavailable) {
Text(
text = stringResource(R.string.biometric_unavailable_no_pin),
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodyMedium,
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
modifier = Modifier.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(24.dp))
}
Text( Text(
text = stringResource(R.string.enter_pin), text = if (hasPin) stringResource(R.string.enter_pin)
else stringResource(R.string.unlock_2fair),
style = MaterialTheme.typography.headlineSmall style = MaterialTheme.typography.headlineSmall
) )
Spacer(modifier = Modifier.height(16.dp))
PinIndicatorRow( if (hasPin) {
filledCount = enteredPin.length, Spacer(modifier = Modifier.height(16.dp))
isError = errorMessage != null || remainingLockOutTime > 0L,
isSuccess = isSuccess,
modifier = Modifier.fillMaxWidth(0.8f)
)
Spacer(modifier = Modifier.height(12.dp))
Text( PinIndicatorRow(
text = when { filledCount = enteredPin.length,
remainingLockOutTime > 0L -> stringResource(R.string.try_again_in, remainingLockOutTime) isError = errorMessage != null || remainingLockOutTime > 0L,
errorMessage != null -> errorMessage!! isSuccess = isSuccess,
enteredPin.isEmpty() -> pinHintMsg modifier = Modifier.fillMaxWidth(0.8f)
else -> stringResource(R.string.pin_digits_remaining, PIN_LENGTH - enteredPin.length) )
}, Spacer(modifier = Modifier.height(12.dp))
color = if (errorMessage != null || remainingLockOutTime > 0L) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(24.dp))
PinNumberPad( Text(
resetLabel = stringResource(R.string.clear_pin_input), text = when {
deleteLabel = stringResource(R.string.delete_digit), remainingLockOutTime > 0L -> stringResource(R.string.try_again_in, remainingLockOutTime)
onDigit = { digit -> errorMessage != null -> errorMessage!!
if (remainingLockOutTime > 0L || isSuccess || enteredPin.length >= PIN_LENGTH) { enteredPin.isEmpty() -> pinHintMsg
return@PinNumberPad else -> stringResource(R.string.pin_digits_remaining, PIN_LENGTH - enteredPin.length)
} },
val updatedPin = enteredPin + digit color = if (errorMessage != null || remainingLockOutTime > 0L) {
enteredPin = updatedPin MaterialTheme.colorScheme.error
errorMessage = null } else {
if (updatedPin.length == PIN_LENGTH) { MaterialTheme.colorScheme.onSurfaceVariant
submitPin(updatedPin) },
} style = MaterialTheme.typography.bodyMedium
}, )
onDelete = { Spacer(modifier = Modifier.height(24.dp))
if (remainingLockOutTime == 0L && enteredPin.isNotEmpty()) {
enteredPin = enteredPin.dropLast(1) PinNumberPad(
resetLabel = stringResource(R.string.clear_pin_input),
deleteLabel = stringResource(R.string.delete_digit),
onDigit = { digit ->
if (remainingLockOutTime > 0L || isSuccess || enteredPin.length >= PIN_LENGTH) {
return@PinNumberPad
}
val updatedPin = enteredPin + digit
enteredPin = updatedPin
errorMessage = null errorMessage = null
} if (updatedPin.length == PIN_LENGTH) {
}, submitPin(updatedPin)
onReset = { }
if (remainingLockOutTime == 0L && enteredPin.isNotEmpty()) { },
enteredPin = "" onDelete = {
errorMessage = null if (remainingLockOutTime == 0L && enteredPin.isNotEmpty()) {
} enteredPin = enteredPin.dropLast(1)
}, errorMessage = null
modifier = Modifier.fillMaxWidth(0.9f), }
isEnabled = remainingLockOutTime == 0L, },
isDeleteEnabled = enteredPin.isNotEmpty(), onReset = {
isResetEnabled = enteredPin.isNotEmpty() if (remainingLockOutTime == 0L && enteredPin.isNotEmpty()) {
) enteredPin = ""
errorMessage = null
}
},
modifier = Modifier.fillMaxWidth(0.9f),
isEnabled = remainingLockOutTime == 0L,
isDeleteEnabled = enteredPin.isNotEmpty(),
isResetEnabled = enteredPin.isNotEmpty()
)
}
if (isBiometricEnabled) { if (isBiometricEnabled && !biometricUnavailable) {
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
FilledTonalButton( FilledTonalButton(
onClick = { onClick = {
@@ -125,7 +125,6 @@ fun SecuritySettingsScreen(
} }
Switch( Switch(
checked = isBiometricEnabled, checked = isBiometricEnabled,
enabled = isPinEnabled,
onCheckedChange = { checked -> onCheckedChange = { checked ->
if (checked) { if (checked) {
biometricAuthenticator.authenticate( biometricAuthenticator.authenticate(
@@ -163,8 +162,25 @@ fun SecuritySettingsScreen(
BiometricAuthResult.Cancelled -> Unit BiometricAuthResult.Cancelled -> Unit
} }
} }
} else { } else if (isPinEnabled) {
// PIN available: confirm downgrade with PIN
verificationAction = SecurityVerificationAction.DisableBiometric verificationAction = SecurityVerificationAction.DisableBiometric
} else {
// No PIN: confirm downgrade with biometric itself
biometricAuthenticator.authenticate(
mode = BiometricAuthMode.BiometricOnly,
titleRes = R.string.disable_biometric_verification_title,
subtitleRes = R.string.enable_biometric_verification_desc
) { result ->
when (result) {
BiometricAuthResult.Success -> {
scope.launch {
settingsRepository.setBiometricEnabled(false)
}
}
else -> Unit
}
}
} }
} }
) )
@@ -172,7 +188,7 @@ fun SecuritySettingsScreen(
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
if (isPinEnabled) { if (isPinEnabled || isBiometricEnabled) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -135,6 +135,93 @@ fun TokenEditScreen(
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
// Group dropdown
val groups by viewModel.groups.collectAsStateWithLifecycle()
var groupExpanded by remember { mutableStateOf(false) }
var showNewGroupDialog by remember { mutableStateOf(false) }
val selectedGroupName = groups.firstOrNull { it.id == state.groupId }?.name
?: stringResource(R.string.uncategorized)
ExposedDropdownMenuBox(
expanded = groupExpanded,
onExpandedChange = { groupExpanded = it }
) {
OutlinedTextField(
value = selectedGroupName,
onValueChange = {},
readOnly = true,
label = { Text(stringResource(R.string.group_label)) },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = groupExpanded) },
modifier = Modifier.menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable).fillMaxWidth()
)
ExposedDropdownMenu(
expanded = groupExpanded,
onDismissRequest = { groupExpanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.uncategorized)) },
onClick = {
viewModel.updateGroupId(null)
groupExpanded = false
}
)
groups.forEach { group ->
DropdownMenuItem(
text = { Text(group.name) },
onClick = {
viewModel.updateGroupId(group.id)
groupExpanded = false
}
)
}
HorizontalDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.group_new)) },
onClick = {
groupExpanded = false
showNewGroupDialog = true
}
)
}
}
if (showNewGroupDialog) {
var newGroupName by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = { showNewGroupDialog = false },
title = { Text(stringResource(R.string.group_new)) },
text = {
OutlinedTextField(
value = newGroupName,
onValueChange = { newGroupName = it },
label = { Text(stringResource(R.string.group_name)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
enabled = newGroupName.isNotBlank(),
onClick = {
viewModel.createGroup(newGroupName) { id ->
viewModel.updateGroupId(id)
}
showNewGroupDialog = false
}
) {
Text(stringResource(R.string.save))
}
},
dismissButton = {
TextButton(onClick = { showNewGroupDialog = false }) {
Text(stringResource(R.string.cancel))
}
}
)
}
Spacer(modifier = Modifier.height(12.dp))
// Token Type dropdown // Token Type dropdown
ExposedDropdownMenuBox( ExposedDropdownMenuBox(
expanded = typeExpanded, expanded = typeExpanded,
@@ -9,6 +9,8 @@ import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
@@ -18,6 +20,9 @@ import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.DragIndicator
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.outlined.QrCode2 import androidx.compose.material.icons.outlined.QrCode2
@@ -33,11 +38,17 @@ import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.changedToUp
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.zIndex
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
@@ -66,6 +77,15 @@ fun TokensScreen(
val focusManager = LocalFocusManager.current val focusManager = LocalFocusManager.current
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
// Group & token drag-reorder state
var draggedGroupKey by remember { mutableStateOf<Long?>(null) } // real id; -1 = Uncategorized
var dragGroupTranslateY by remember { mutableFloatStateOf(0f) }
var draggedTokenId by remember { mutableStateOf<Long?>(null) }
var dragTokenTranslateY by remember { mutableFloatStateOf(0f) }
val cardHeights = remember { mutableMapOf<String, Int>() }
var renameTarget by remember { mutableStateOf<Group?>(null) }
var deleteTarget by remember { mutableStateOf<Group?>(null) }
LaunchedEffect(isSearchExpanded) { LaunchedEffect(isSearchExpanded) {
if (isSearchExpanded) { if (isSearchExpanded) {
searchFocusRequester.requestFocus() searchFocusRequester.requestFocus()
@@ -140,6 +160,7 @@ fun TokensScreen(
.fillMaxSize() .fillMaxSize()
.padding(padding) .padding(padding)
) { ) {
val latestUiState by rememberUpdatedState(uiState)
if (uiState.groupedTokens.isEmpty()) { if (uiState.groupedTokens.isEmpty()) {
if (uiState.searchQuery.isBlank()) { if (uiState.searchQuery.isBlank()) {
EmptyState( EmptyState(
@@ -165,29 +186,132 @@ fun TokensScreen(
) { ) {
uiState.groupedTokens.forEach { (group, tokens) -> uiState.groupedTokens.forEach { (group, tokens) ->
val groupId = group?.id val groupId = group?.id
val groupKey = groupId ?: -1L
val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L) val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L)
item(key = "group_${groupId ?: "unassigned"}") { item(key = "group_${groupId ?: "unassigned"}") {
Card( Card(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 6.dp), .padding(horizontal = 16.dp, vertical = 6.dp)
.zIndex(if (draggedGroupKey == groupKey) 1f else 0f)
.graphicsLayer {
if (draggedGroupKey == groupKey) translationY = dragGroupTranslateY
}
.onSizeChanged { cardHeights["g:$groupKey"] = it.height },
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp) elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
) { ) {
Column { Column {
GroupHeader( GroupHeader(
group = group, group = group,
isCollapsed = isCollapsed, isCollapsed = isCollapsed,
onToggle = { viewModel.toggleGroupCollapse(groupId) } onToggle = { viewModel.toggleGroupCollapse(groupId) },
onRename = { group?.let { renameTarget = it } },
onDelete = { group?.let { deleteTarget = it } },
dragModifier = Modifier.dragHandle(
key = groupKey,
onDragStart = {
draggedGroupKey = groupKey
dragGroupTranslateY = 0f
},
onDragDelta = { dy ->
dragGroupTranslateY += dy
// Swap with neighbour once dragged past its height
val keys = latestUiState.groupedTokens.keys.toList()
val index = keys.indexOfFirst { (it?.id ?: -1L) == groupKey }
if (index >= 0) {
if (dragGroupTranslateY > 0f && index < keys.lastIndex) {
val next = keys[index + 1]
val nextKey = next?.id ?: -1L
val nextHeight = cardHeights["g:$nextKey"] ?: 0
if (nextHeight > 0 && dragGroupTranslateY >= nextHeight) {
dragGroupTranslateY -= nextHeight
val newKeys = keys.toMutableList()
newKeys[index] = next
newKeys[index + 1] = group
viewModel.applyGroupOrder(newKeys)
}
} else if (dragGroupTranslateY < 0f && index > 0) {
val prev = keys[index - 1]
val prevKey = prev?.id ?: -1L
val prevHeight = cardHeights["g:$prevKey"] ?: 0
if (prevHeight > 0 && -dragGroupTranslateY >= prevHeight) {
dragGroupTranslateY += prevHeight
val newKeys = keys.toMutableList()
newKeys[index] = prev
newKeys[index - 1] = group
viewModel.applyGroupOrder(newKeys)
}
}
}
},
onDragEnd = {
draggedGroupKey = null
dragGroupTranslateY = 0f
}
)
) )
if (!isCollapsed) { if (!isCollapsed) {
tokens.forEachIndexed { index, token -> tokens.forEachIndexed { index, token ->
TokenCard( Box(
token = token, modifier = Modifier
onIncrement = { viewModel.incrementCounter(token) }, .zIndex(if (draggedTokenId == token.id) 1f else 0f)
onEdit = { onNavigateToTokenEdit(token.id) } .graphicsLayer {
) if (draggedTokenId == token.id) translationY = dragTokenTranslateY
}
.onSizeChanged { cardHeights["t:${token.id}"] = it.height }
) {
TokenCard(
token = token,
onIncrement = { viewModel.incrementCounter(token) },
onEdit = { onNavigateToTokenEdit(token.id) },
dragModifier = Modifier.dragHandle(
key = token.id,
onDragStart = {
draggedTokenId = token.id
dragTokenTranslateY = 0f
},
onDragDelta = { dy ->
dragTokenTranslateY += dy
// Reorder within the same group only
val groupTokens = latestUiState.groupedTokens[group]
if (groupTokens != null) {
val idx = groupTokens.indexOfFirst { it.id == token.id }
if (idx >= 0) {
if (idx < groupTokens.lastIndex && dragTokenTranslateY > 0f) {
val next = groupTokens[idx + 1]
val nextHeight = cardHeights["t:${next.id}"] ?: 0
if (nextHeight > 0 && dragTokenTranslateY >= nextHeight) {
dragTokenTranslateY -= nextHeight
val newOrder = groupTokens.toMutableList()
newOrder[idx] = next
newOrder[idx + 1] = token
viewModel.applyTokenOrder(newOrder)
}
} else if (idx > 0 && dragTokenTranslateY < 0f) {
val prev = groupTokens[idx - 1]
val prevHeight = cardHeights["t:${prev.id}"] ?: 0
if (prevHeight > 0 && -dragTokenTranslateY >= prevHeight) {
dragTokenTranslateY += prevHeight
val newOrder = groupTokens.toMutableList()
newOrder[idx] = prev
newOrder[idx - 1] = token
viewModel.applyTokenOrder(newOrder)
}
}
}
}
},
onDragEnd = {
draggedTokenId = null
dragTokenTranslateY = 0f
}
)
)
}
if (index < tokens.lastIndex) { if (index < tokens.lastIndex) {
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp)) HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
} }
@@ -211,6 +335,89 @@ fun TokensScreen(
} }
) )
} }
renameTarget?.let { target ->
var newName by remember(target.id) { mutableStateOf(target.name) }
AlertDialog(
onDismissRequest = { renameTarget = null },
title = { Text(stringResource(R.string.group_rename)) },
text = {
OutlinedTextField(
value = newName,
onValueChange = { newName = it },
label = { Text(stringResource(R.string.group_name)) },
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
},
confirmButton = {
TextButton(
enabled = newName.isNotBlank() && newName.trim() != target.name,
onClick = {
viewModel.renameGroup(target, newName)
renameTarget = null
}
) {
Text(stringResource(R.string.save))
}
},
dismissButton = {
TextButton(onClick = { renameTarget = null }) {
Text(stringResource(R.string.cancel))
}
}
)
}
deleteTarget?.let { target ->
AlertDialog(
onDismissRequest = { deleteTarget = null },
title = { Text(target.name) },
text = { Text(stringResource(R.string.group_delete_confirm)) },
confirmButton = {
TextButton(onClick = {
viewModel.deleteGroup(target)
deleteTarget = null
}) {
Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { deleteTarget = null }) {
Text(stringResource(R.string.cancel))
}
}
)
}
}
}
/**
* Drag handle: consumes the down event immediately so ancestor click/long-press
* (copy, detail drawer, collapse) never fires; drag deltas reported as cumulative dy.
*/
private fun Modifier.dragHandle(
key: Any?,
onDragStart: () -> Unit,
onDragDelta: (Float) -> Unit,
onDragEnd: () -> Unit
): Modifier = pointerInput(key) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
down.consume()
onDragStart()
try {
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull() ?: break
if (change.changedToUp()) break
val dy = change.positionChange().y
change.consume()
onDragDelta(dy)
}
} finally {
onDragEnd()
}
} }
} }
@@ -268,19 +475,33 @@ private fun EmptyState(
} }
} }
@OptIn(ExperimentalFoundationApi::class)
@Composable @Composable
fun GroupHeader( fun GroupHeader(
group: Group?, group: Group?,
isCollapsed: Boolean, isCollapsed: Boolean,
onToggle: () -> Unit onToggle: () -> Unit,
onRename: () -> Unit = {},
onDelete: () -> Unit = {},
dragModifier: Modifier = Modifier
) { ) {
var menuExpanded by remember { mutableStateOf(false) }
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable(onClick = onToggle) .combinedClickable(onClick = onToggle)
.padding(horizontal = 16.dp, vertical = 12.dp), .padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
if (group != null) {
Icon(
imageVector = Icons.Default.DragIndicator,
contentDescription = stringResource(R.string.drag_handle_desc),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = dragModifier
)
Spacer(modifier = Modifier.width(10.dp))
}
Text( Text(
text = group?.name ?: stringResource(R.string.uncategorized), text = group?.name ?: stringResource(R.string.uncategorized),
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
@@ -288,6 +509,34 @@ fun GroupHeader(
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.weight(1f) modifier = Modifier.weight(1f)
) )
Spacer(modifier = Modifier.width(4.dp))
Box {
IconButton(onClick = { menuExpanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = stringResource(R.string.rename)
)
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false }
) {
DropdownMenuItem(
text = { Text(stringResource(R.string.rename)) },
onClick = {
menuExpanded = false
onRename()
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
menuExpanded = false
onDelete()
}
)
}
}
Icon( Icon(
imageVector = if (isCollapsed) Icons.Default.ExpandMore else Icons.Default.ExpandLess, imageVector = if (isCollapsed) Icons.Default.ExpandMore else Icons.Default.ExpandLess,
contentDescription = stringResource(R.string.toggle_group) contentDescription = stringResource(R.string.toggle_group)
@@ -300,7 +549,8 @@ fun GroupHeader(
fun TokenCard( fun TokenCard(
token: Token, token: Token,
onIncrement: () -> Unit, onIncrement: () -> Unit,
onEdit: () -> Unit onEdit: () -> Unit,
dragModifier: Modifier = Modifier
) { ) {
val warningColor = Color(0xFFFF1744) val warningColor = Color(0xFFFF1744)
val otpPlaceholder = stringResource(R.string.otp_placeholder) val otpPlaceholder = stringResource(R.string.otp_placeholder)
@@ -393,6 +643,15 @@ fun TokenCard(
.padding(horizontal = 16.dp, vertical = 12.dp), .padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Icon(
imageVector = Icons.Default.DragIndicator,
contentDescription = stringResource(R.string.drag_handle_desc),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = dragModifier
)
Spacer(modifier = Modifier.width(12.dp))
TokenIcon(token) TokenIcon(token)
Spacer(modifier = Modifier.width(16.dp)) Spacer(modifier = Modifier.width(16.dp))
@@ -9,9 +9,11 @@ import cn.airnan.a2fair.A2FairApplication
import cn.airnan.a2fair.R import cn.airnan.a2fair.R
import cn.airnan.a2fair.core.OtpUriParser import cn.airnan.a2fair.core.OtpUriParser
import cn.airnan.a2fair.data.SecretString import cn.airnan.a2fair.data.SecretString
import cn.airnan.a2fair.data.normalizeSecret
import cn.airnan.a2fair.data.entity.HashAlgorithm import cn.airnan.a2fair.data.entity.HashAlgorithm
import cn.airnan.a2fair.data.entity.Token import cn.airnan.a2fair.data.entity.Token
import cn.airnan.a2fair.data.entity.TokenType import cn.airnan.a2fair.data.entity.TokenType
import cn.airnan.a2fair.data.repository.SettingsRepository
import cn.airnan.a2fair.data.repository.TokenRepository import cn.airnan.a2fair.data.repository.TokenRepository
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
@@ -34,6 +36,7 @@ data class AddTokenUiState(
val digits: Int = 6, val digits: Int = 6,
val period: Int = 30, val period: Int = 30,
val counter: Long = 0, val counter: Long = 0,
val groupId: Long? = null,
val isError: Boolean = false, val isError: Boolean = false,
val errorMessage: String? = null, val errorMessage: String? = null,
val isSuccess: Boolean = false, val isSuccess: Boolean = false,
@@ -49,7 +52,8 @@ data class TokensUiState(
class TokensViewModel( class TokensViewModel(
application: Application, application: Application,
private val tokenRepository: TokenRepository private val tokenRepository: TokenRepository,
private val settingsRepository: SettingsRepository
) : AndroidViewModel(application) { ) : AndroidViewModel(application) {
private val _searchQuery = MutableStateFlow("") private val _searchQuery = MutableStateFlow("")
@@ -59,8 +63,9 @@ class TokensViewModel(
tokenRepository.getAllTokens(), tokenRepository.getAllTokens(),
tokenRepository.getAllGroups(), tokenRepository.getAllGroups(),
_searchQuery, _searchQuery,
_collapsedGroups _collapsedGroups,
) { tokens, groups, query, collapsed -> settingsRepository.uncategorizedOrder
) { tokens, groups, query, collapsed, uncategorizedIndex ->
val filteredTokens = if (query.isBlank()) { val filteredTokens = if (query.isBlank()) {
tokens tokens
} else { } else {
@@ -74,12 +79,29 @@ class TokensViewModel(
val grouped = filteredTokens.groupBy { token -> val grouped = filteredTokens.groupBy { token ->
token.groupId?.let { groupMap[it] } token.groupId?.let { groupMap[it] }
}.toSortedMap(compareBy(nullsFirst()) { it?.sortOrder ?: Int.MAX_VALUE }) }.toMutableMap()
val sortedGrouped = grouped.mapValues { entry -> // Show groups even when they contain no tokens (except Uncategorized which only
entry.value.sortedWith(compareBy({ it.sortOrder }, { it.serviceName })) // appears when it has tokens)
groups.forEach { group ->
grouped.putIfAbsent(group, emptyList())
} }
// Display order: real groups by sortOrder, Uncategorized inserted at its stored index
val orderedKeys = buildList {
val unassigned: Group? = null
val real: MutableList<Group?> = groups.sortedBy { it.sortOrder }.toMutableList()
val idx = uncategorizedIndex.coerceIn(0, real.size)
real.add(idx, unassigned)
addAll(real)
}
val sortedGrouped = orderedKeys.mapNotNull { key -> grouped[key]?.let { key to it } }
.toMap(LinkedHashMap())
.mapValues { entry ->
entry.value.sortedWith(compareBy({ it.sortOrder }, { it.serviceName }))
}
TokensUiState( TokensUiState(
groupedTokens = sortedGrouped, groupedTokens = sortedGrouped,
searchQuery = query, searchQuery = query,
@@ -95,6 +117,59 @@ class TokensViewModel(
_searchQuery.value = query _searchQuery.value = query
} }
val groups: StateFlow<List<Group>> = tokenRepository.getAllGroups()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
fun createGroup(name: String, onCreated: (Long) -> Unit = {}) {
viewModelScope.launch {
val trimmed = name.trim()
if (trimmed.isEmpty()) return@launch
val maxSort = tokenRepository.getAllGroups().first().maxOfOrNull { it.sortOrder } ?: -1
val id = tokenRepository.insertGroup(Group(name = trimmed, sortOrder = maxSort + 1))
onCreated(id)
}
}
fun renameGroup(group: Group, newName: String) {
val trimmed = newName.trim()
if (trimmed.isEmpty() || trimmed == group.name) return
viewModelScope.launch {
tokenRepository.updateGroup(group.copy(name = trimmed))
}
}
fun deleteGroup(group: Group) {
viewModelScope.launch {
tokenRepository.deleteGroup(group)
}
}
/** Persists a new display order of groups; Uncategorized (null) position is stored separately. */
fun applyGroupOrder(ordered: List<Group?>) {
viewModelScope.launch {
ordered.filterNotNull().forEachIndexed { index, group ->
if (group.sortOrder != index) {
tokenRepository.updateGroup(group.copy(sortOrder = index))
}
}
val nullIndex = ordered.indexOfFirst { it == null }
if (nullIndex >= 0) {
settingsRepository.setUncategorizedOrder(nullIndex)
}
}
}
/** Persists a new display order of tokens within a group (renumbers sortOrder 0..n-1). */
fun applyTokenOrder(ordered: List<Token>) {
viewModelScope.launch {
ordered.forEachIndexed { index, token ->
if (token.sortOrder != index) {
tokenRepository.updateToken(token.copy(sortOrder = index))
}
}
}
}
fun toggleGroupCollapse(groupId: Long?) { fun toggleGroupCollapse(groupId: Long?) {
val id = groupId ?: -1L val id = groupId ?: -1L
_collapsedGroups.update { current -> _collapsedGroups.update { current ->
@@ -157,6 +232,10 @@ class TokensViewModel(
_addTokenState.update { it.copy(counter = counter) } _addTokenState.update { it.copy(counter = counter) }
} }
fun updateGroupId(groupId: Long?) {
_addTokenState.update { it.copy(groupId = groupId) }
}
fun resetAddState() { fun resetAddState() {
_addTokenState.value = AddTokenUiState() _addTokenState.value = AddTokenUiState()
editingTokenId = null editingTokenId = null
@@ -173,7 +252,8 @@ class TokensViewModel(
algorithm = token.algorithm, algorithm = token.algorithm,
digits = token.digits, digits = token.digits,
period = token.period, period = token.period,
counter = token.counter counter = token.counter,
groupId = token.groupId
) )
} }
@@ -196,7 +276,8 @@ class TokensViewModel(
algorithm = state.algorithm, algorithm = state.algorithm,
digits = state.digits, digits = state.digits,
period = state.period, period = state.period,
counter = state.counter counter = state.counter,
groupId = state.groupId
) )
tokenRepository.updateToken(updated) tokenRepository.updateToken(updated)
} }
@@ -234,7 +315,8 @@ class TokensViewModel(
algorithm = state.algorithm, algorithm = state.algorithm,
digits = state.digits, digits = state.digits,
period = state.period, period = state.period,
counter = state.counter counter = state.counter,
groupId = state.groupId
) )
saveToken(token) saveToken(token)
} catch (e: Exception) { } catch (e: Exception) {
@@ -242,10 +324,6 @@ class TokensViewModel(
} }
} }
private fun String.normalizeSecret(): String {
return this.uppercase().replace(Regex("[^A-Z2-7]"), "")
}
private fun saveToken(token: Token) { private fun saveToken(token: Token) {
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -265,6 +343,7 @@ class TokensViewModel(
digits = token.digits, digits = token.digits,
period = token.period, period = token.period,
counter = token.counter, counter = token.counter,
groupId = token.groupId,
isDuplicate = true, isDuplicate = true,
duplicateServiceName = duplicate.serviceName, duplicateServiceName = duplicate.serviceName,
isError = false, isError = false,
@@ -309,7 +388,7 @@ class TokensViewModel(
override fun <T : ViewModel> create(modelClass: Class<T>): T { override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(TokensViewModel::class.java)) { if (modelClass.isAssignableFrom(TokensViewModel::class.java)) {
val app = application as A2FairApplication val app = application as A2FairApplication
return TokensViewModel(application, app.tokenRepository) as T return TokensViewModel(application, app.tokenRepository, app.settingsRepository) as T
} }
throw IllegalArgumentException("Unknown ViewModel class") throw IllegalArgumentException("Unknown ViewModel class")
} }
@@ -32,6 +32,20 @@
<string name="add_token_title">添加令牌</string> <string name="add_token_title">添加令牌</string>
<string name="scanning_hint">扫描中…</string> <string name="scanning_hint">扫描中…</string>
<string name="camera_permission_hint">需要相机权限才能扫码</string> <string name="camera_permission_hint">需要相机权限才能扫码</string>
<string name="backup_empty_tokens">没有可备份的令牌,请先添加令牌</string>
<string name="import_empty_backup">备份文件中没有任何令牌或分组</string>
<string name="import_unsupported_version">该备份由更新版本的应用创建,请先升级应用</string>
<string name="import_wrong_password">密码不正确,请重新输入</string>
<string name="import_invalid_file">该文件不是有效的 2FAir 备份文件</string>
<string name="import_success_stats">已导入 %1$d 个令牌(跳过 %2$d 个重复),新增 %3$d 个分组</string>
<string name="group_label">分组</string>
<string name="group_new">新建分组…</string>
<string name="group_name">分组名称</string>
<string name="group_rename">重命名分组</string>
<string name="group_delete_confirm">删除该分组?组内令牌将移入未分组。</string>
<string name="rename">重命名</string>
<string name="drag_handle_desc">拖动排序</string>
<string name="biometric_unavailable_no_pin">生物识别不可用且未设置 PIN,请在系统设置中恢复指纹后再解锁应用</string>
<string name="account_name_required">账户名称(必填)</string> <string name="account_name_required">账户名称(必填)</string>
<string name="secret_key_required">密钥(必填)</string> <string name="secret_key_required">密钥(必填)</string>
<string name="issuer_optional">发行方(选填)</string> <string name="issuer_optional">发行方(选填)</string>
@@ -32,6 +32,20 @@
<string name="add_token_title">新增權杖</string> <string name="add_token_title">新增權杖</string>
<string name="scanning_hint">掃描中…</string> <string name="scanning_hint">掃描中…</string>
<string name="camera_permission_hint">需要相機權限才能掃碼</string> <string name="camera_permission_hint">需要相機權限才能掃碼</string>
<string name="backup_empty_tokens">沒有可備份的權杖,請先新增權杖</string>
<string name="import_empty_backup">備份檔案中沒有任何權杖或分組</string>
<string name="import_unsupported_version">該備份由更新版本的應用程式建立,請先升級應用程式</string>
<string name="import_wrong_password">密碼不正確,請重新輸入</string>
<string name="import_invalid_file">該檔案不是有效的 2FAir 備份檔案</string>
<string name="import_success_stats">已匯入 %1$d 個權杖(略過 %2$d 個重複),新增 %3$d 個分組</string>
<string name="group_label">分組</string>
<string name="group_new">新增分組…</string>
<string name="group_name">分組名稱</string>
<string name="group_rename">重新命名分組</string>
<string name="group_delete_confirm">刪除此分組?組內權杖將移入未分組。</string>
<string name="rename">重新命名</string>
<string name="drag_handle_desc">拖動排序</string>
<string name="biometric_unavailable_no_pin">生物辨識不可用且未設定 PIN,請在系統設定中恢復指紋後再解鎖應用程式</string>
<string name="account_name_required">帳戶名稱(必填)</string> <string name="account_name_required">帳戶名稱(必填)</string>
<string name="secret_key_required">金鑰(必填)</string> <string name="secret_key_required">金鑰(必填)</string>
<string name="issuer_optional">發行方(選填)</string> <string name="issuer_optional">發行方(選填)</string>
+14
View File
@@ -32,6 +32,20 @@
<string name="add_token_title">Add Token</string> <string name="add_token_title">Add Token</string>
<string name="scanning_hint">Scanning…</string> <string name="scanning_hint">Scanning…</string>
<string name="camera_permission_hint">Camera permission is required to scan QR codes.</string> <string name="camera_permission_hint">Camera permission is required to scan QR codes.</string>
<string name="backup_empty_tokens">No tokens to back up. Add a token first.</string>
<string name="import_empty_backup">This backup file contains no tokens or groups.</string>
<string name="import_unsupported_version">This backup was created by a newer app version. Please update the app.</string>
<string name="import_wrong_password">Password is incorrect. Please try again.</string>
<string name="import_invalid_file">This file is not a valid 2FAir backup.</string>
<string name="import_success_stats">Imported %1$d tokens (%2$d duplicates skipped), %3$d new groups.</string>
<string name="group_label">Group</string>
<string name="group_new">New group…</string>
<string name="group_name">Group name</string>
<string name="group_rename">Rename group</string>
<string name="group_delete_confirm">Delete this group? Its tokens will move to Uncategorized.</string>
<string name="rename">Rename</string>
<string name="drag_handle_desc">Drag to reorder</string>
<string name="biometric_unavailable_no_pin">Biometric unlock is unavailable and no PIN is set. Restore your fingerprint in system settings to unlock the app.</string>
<string name="account_name_required">Account Name (Required)</string> <string name="account_name_required">Account Name (Required)</string>
<string name="secret_key_required">Secret Key (Required)</string> <string name="secret_key_required">Secret Key (Required)</string>
<string name="issuer_optional">Issuer (Optional)</string> <string name="issuer_optional">Issuer (Optional)</string>