Compare commits
27
Commits
252bb1c02b
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f9ce7aed8 | ||
|
|
5dae8385a0 | ||
|
|
ed290f3d7d | ||
|
|
69b83a2f20 | ||
|
|
fbd5d5bd2c | ||
|
|
315db320a7 | ||
|
|
d317ede90d | ||
|
|
c326b11163 | ||
|
|
76990f2c41 | ||
|
|
b03501f227 | ||
|
|
01c619e925 | ||
|
|
d3459e69c1 | ||
|
|
d26264c867 | ||
|
|
74aa93abcd | ||
|
|
e10e296efa | ||
|
|
a676bef14a | ||
|
|
19384b9547 | ||
|
|
e0bd974f59 | ||
|
|
666542ce17 | ||
|
|
cfe26fd5d3 | ||
|
|
9ee6cfdfee | ||
|
|
f5735956c8 | ||
|
|
3aa6da26a9 | ||
|
|
32ba07651b | ||
|
|
6689cda4b2 | ||
|
|
1caf879d27 | ||
|
|
86cd6fb3dc |
@@ -16,6 +16,8 @@ captures/
|
|||||||
.cxx/
|
.cxx/
|
||||||
*.apk
|
*.apk
|
||||||
output.json
|
output.json
|
||||||
|
output-metadata.json
|
||||||
|
app/release/
|
||||||
|
|
||||||
# IntelliJ
|
# IntelliJ
|
||||||
*.iml
|
*.iml
|
||||||
@@ -27,6 +29,7 @@ render.experimental.xml
|
|||||||
# Keystore files
|
# Keystore files
|
||||||
*.jks
|
*.jks
|
||||||
*.keystore
|
*.keystore
|
||||||
|
keystore.properties
|
||||||
|
|
||||||
# Google Services (e.g. APIs or Firebase)
|
# Google Services (e.g. APIs or Firebase)
|
||||||
google-services.json
|
google-services.json
|
||||||
|
|||||||
@@ -1,3 +1,151 @@
|
|||||||
# 2FAir
|
# 2FAir
|
||||||
|
|
||||||
2FA令牌管理器
|
2FA 令牌管理器(两步验证 / 身份验证器),Android 原生应用。
|
||||||
|
|
||||||
|
当前版本:0.0.1
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
### 令牌
|
||||||
|
- 支持 **TOTP / HOTP / Steam** 三种令牌类型
|
||||||
|
- 算法支持 **SHA-1 / SHA-256 / SHA-512**,位数、周期、计数器均可配置
|
||||||
|
- 三种添加方式:**扫描二维码**(CameraX + ZXing 实时识别)、**从相册图片导入**、**手动输入**
|
||||||
|
- 标准 `otpauth://` URI 解析与生成;令牌详情可查看二维码、复制密钥,便于迁移
|
||||||
|
- 复制验证码;HOTP 支持手动刷新计数器
|
||||||
|
- 按密钥(归一化后)检测重复令牌,可选强制添加
|
||||||
|
- 搜索令牌(发行方 / 账户名)
|
||||||
|
- 分组管理:新建 / 重命名 / 删除分组、拖拽排序、折叠展开;分组删除后令牌移入「未分组」
|
||||||
|
- 令牌与分组均支持拖拽排序
|
||||||
|
|
||||||
|
### 安全
|
||||||
|
- 密钥加密存储:AndroidKeyStore 生成的 AES-GCM 密钥,通过 Room `TypeConverter` 在落库 / 读取时透明加解密,数据库文件中不存明文密钥
|
||||||
|
- 应用锁:
|
||||||
|
- 6 位数字 PIN(Keystore 加密后存于 DataStore,非明文)
|
||||||
|
- 生物识别解锁(指纹 / 面部,`BiometricPrompt`)
|
||||||
|
- 锁定时机可选:立即 / 1 分钟 / 3 分钟 / 5 分钟;后台时间持久化,进程被杀后恢复仍会正确上锁
|
||||||
|
- PIN 连续输错 5 次锁定 30 秒
|
||||||
|
- 「禁止截屏」开关(`FLAG_SECURE`,防截屏 / 录屏)
|
||||||
|
- `SecretString` 重写 `toString()`,避免密钥意外进入日志
|
||||||
|
|
||||||
|
### 备份与恢复
|
||||||
|
- 导出 / 导入加密备份文件,支持跨设备迁移
|
||||||
|
- 加密方案:PBKDF2-HMAC-SHA256(10 000 次迭代、16 字节随机盐、256 位密钥)+ AES-GCM(128 位 tag)
|
||||||
|
- 文件格式:`[salt 长度(1B)][salt][IV 长度(1B)][IV][密文]`
|
||||||
|
- 备份带版本号,导入新版本备份会提示先升级应用
|
||||||
|
- 导入按名称合并分组、按归一化密钥去重令牌,并自动重映射分组 ID
|
||||||
|
|
||||||
|
### 应用内更新
|
||||||
|
- 基于 Gitea Release 实现:启动时静默检测(每进程一次,失败不打扰),关于页可手动检测
|
||||||
|
- 发现新版本弹窗展示更新内容,确认后应用内下载(按设备 ABI 自动选择 arm64-v8a / armeabi-v7a / x86_64 安装包)并拉起系统安装器
|
||||||
|
- 首次安装前会引导开启「安装未知应用」权限
|
||||||
|
|
||||||
|
### 界面与个性化
|
||||||
|
- Jetpack Compose + Material 3,edge-to-edge
|
||||||
|
- 主题模式:跟随系统 / 浅色 / 深色
|
||||||
|
- 动态取色(Material You,Android 12+)与自定义主题色
|
||||||
|
- 应用内语言切换:跟随系统 / 简体中文 / 繁體中文 / English
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
| 类别 | 选型 |
|
||||||
|
|---|---|
|
||||||
|
| 语言 | Kotlin 2.2.10 + C++17(NDK) |
|
||||||
|
| UI | Jetpack Compose(BOM 2026.02.01)、Material 3、Navigation Compose、reorderable |
|
||||||
|
| 数据 | Room 2.6.1(KSP)、DataStore Preferences |
|
||||||
|
| 扫码 | CameraX 1.4.0 + ZXing Core 3.5.3 |
|
||||||
|
| 安全 | AndroidKeyStore(AES-GCM)、androidx.biometric、security-crypto |
|
||||||
|
| 序列化 | Gson(备份 JSON) |
|
||||||
|
| 构建 | Gradle 9.4.1、AGP 9.2.1、JDK 17 toolchain(foojay 自动下载)、CMake 3.22.1 |
|
||||||
|
|
||||||
|
OTP 核心算法(HMAC、SHA-1/256/512、Base32、HOTP/TOTP/Steam)在 `app/src/main/cpp` 以 C++ 自行实现,无第三方依赖,通过 JNI(`NativeLib`)调用。
|
||||||
|
|
||||||
|
## 系统要求
|
||||||
|
|
||||||
|
- Android 7.0(API 24)及以上
|
||||||
|
- 生物识别解锁需要设备具备对应硬件并已录入生物信息
|
||||||
|
|
||||||
|
## 构建
|
||||||
|
|
||||||
|
环境要求:
|
||||||
|
- JDK 17(Gradle toolchain 会按 `gradle/gradle-daemon-jvm.properties` 自动下载)
|
||||||
|
- Android SDK(compileSdk 37)
|
||||||
|
- NDK + CMake 3.22.1(仓库提供 `mise.toml`,执行 `mise install` 可获得对应版本 cmake / ninja)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Debug 构建
|
||||||
|
./gradlew assembleDebug
|
||||||
|
|
||||||
|
# Release 构建(R8 混淆 + 资源收缩,按 ABI 拆分 APK)
|
||||||
|
./gradlew assembleRelease
|
||||||
|
```
|
||||||
|
|
||||||
|
Release 产物按 `arm64-v8a / armeabi-v7a / x86_64` 拆分;资源仅保留 `en / zh-rCN / zh-rTW`。
|
||||||
|
|
||||||
|
### 手动发版
|
||||||
|
|
||||||
|
CI 服务器无需编译,Release 由本地构建后上传:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 一次性创建签名密钥(密钥库与 keystore.properties 均已 gitignore)
|
||||||
|
keytool -genkeypair -v -keystore release.keystore -alias a2fair -keyalg RSA -keysize 4096 -validity 10000
|
||||||
|
cat > keystore.properties <<'EOF'
|
||||||
|
storeFile=release.keystore
|
||||||
|
storePassword=密钥库口令
|
||||||
|
keyAlias=a2fair
|
||||||
|
keyPassword=密钥口令
|
||||||
|
EOF
|
||||||
|
|
||||||
|
# 2. 本地构建已签名 Release
|
||||||
|
./gradlew assembleRelease
|
||||||
|
|
||||||
|
# 3. 打标签推送,在 Gitea 网页(或 API)创建 Release 并附上 APK
|
||||||
|
git tag vX.Y.Z && git push origin vX.Y.Z
|
||||||
|
```
|
||||||
|
|
||||||
|
产物在 `app/build/outputs/apk/release/`,命名规范 `2fair-<版本>-<abi>.apk`(如 `2fair-0.1.0-arm64-v8a.apk`),文件名自带 ABI 子串,符合应用内更新择包约定。绝大多数设备用 `arm64-v8a`。
|
||||||
|
|
||||||
|
应用内更新依赖发版约定:
|
||||||
|
|
||||||
|
- **递增 `versionCode`**(否则系统拒绝覆盖安装),tag 与 `versionName` 对应(如 `v0.0.2` ↔ `0.0.2`,`V` 前缀大小写均可)
|
||||||
|
- 三个 APK 附件名需包含 ABI 子串(`arm64-v8a` / `armeabi-v7a` / `x86_64`),更新器按设备 ABI 择包
|
||||||
|
- 更新检测走 `releases/latest` 接口,仅认最新非草稿、非预发布版本
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
app/src/main/
|
||||||
|
├── cpp/ # NDK 原生代码:OTP/HMAC/SHA/Base32
|
||||||
|
│ ├── otp.{h,cpp} # HOTP / TOTP / Steam 生成
|
||||||
|
│ ├── hmac.{h,cpp} # HMAC
|
||||||
|
│ ├── sha1/sha256/sha512 # 哈希实现
|
||||||
|
│ └── base32.{h,cpp} # Base32 编解码
|
||||||
|
├── java/cn/airnan/a2fair/
|
||||||
|
│ ├── MainActivity.kt # 锁屏 / 主界面切换、主题、语言、FLAG_SECURE
|
||||||
|
│ ├── A2FairApplication.kt # 全局依赖组装(Crypto/DB/Repo/AppLock/Backup)
|
||||||
|
│ ├── core/
|
||||||
|
│ │ ├── OtpUriParser.kt # otpauth:// 解析
|
||||||
|
│ │ ├── OtpUriBuilder.kt # otpauth:// 生成
|
||||||
|
│ │ ├── NativeLib.kt # JNI 绑定
|
||||||
|
│ │ ├── security/ # AppLockManager(锁定时机/生命周期)、PinPolicy
|
||||||
|
│ │ └── backup/ # BackupManager(加密导出/导入/去重/合并)
|
||||||
|
│ ├── crypto/CryptoManager.kt # AndroidKeyStore AES-GCM 加解密
|
||||||
|
│ ├── data/
|
||||||
|
│ │ ├── entity/ # Token、Group(Room 实体)
|
||||||
|
│ │ ├── dao/ # TokenDao、GroupDao
|
||||||
|
│ │ ├── repository/ # TokenRepository、SettingsRepository
|
||||||
|
│ │ └── SecretString.kt # 密钥包装 + Base32 归一化
|
||||||
|
│ └── ui/
|
||||||
|
│ ├── tokens/ # 令牌列表 / 详情 / 编辑 / 添加(扫码、图片、手动)
|
||||||
|
│ ├── settings/ # 设置、安全(PIN/生物识别/锁屏)、备份、主题、语言、关于、开源许可
|
||||||
|
│ ├── navigation/ # 导航
|
||||||
|
│ └── theme/ # Material 3 主题
|
||||||
|
└── res/ # 文案(en / zh-rCN / zh-rTW)、图标
|
||||||
|
```
|
||||||
|
|
||||||
|
## 源代码
|
||||||
|
|
||||||
|
<https://git.airnan.cn/wangairnan/2FAir>
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
[AGPL-3.0](LICENSE)
|
||||||
|
|||||||
+64
-4
@@ -1,19 +1,33 @@
|
|||||||
|
import com.android.build.api.variant.FilterConfiguration
|
||||||
|
import java.util.Properties
|
||||||
|
|
||||||
|
// 版本单点维护:defaultConfig 与 APK 命名共用
|
||||||
|
val appVersionCode = 2
|
||||||
|
val appVersionName = "0.1.0"
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
alias(libs.plugins.kotlin.compose)
|
alias(libs.plugins.kotlin.compose)
|
||||||
alias(libs.plugins.ksp)
|
alias(libs.plugins.ksp)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 本地发布签名:根目录 keystore.properties(不入库)指向密钥库,存在则 release 自动签名
|
||||||
|
val keystorePropertiesFile = rootProject.file("keystore.properties")
|
||||||
|
val keystoreProperties = Properties().apply {
|
||||||
|
if (keystorePropertiesFile.exists()) keystorePropertiesFile.inputStream().use { load(it) }
|
||||||
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "cn.airnan.a2fair"
|
namespace = "cn.airnan.a2fair"
|
||||||
compileSdk = 35
|
compileSdk = 37
|
||||||
|
compileSdkMinor = 0
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "cn.airnan.a2fair"
|
applicationId = "cn.airnan.a2fair"
|
||||||
minSdk = 24
|
minSdk = 24
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = appVersionCode
|
||||||
versionName = "0.0.1"
|
versionName = appVersionName
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|
||||||
@@ -24,15 +38,43 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
if (keystorePropertiesFile.exists()) {
|
||||||
|
create("release") {
|
||||||
|
storeFile = rootProject.file(keystoreProperties.getProperty("storeFile"))
|
||||||
|
storePassword = keystoreProperties.getProperty("storePassword")
|
||||||
|
keyAlias = keystoreProperties.getProperty("keyAlias")
|
||||||
|
keyPassword = keystoreProperties.getProperty("keyPassword")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
isMinifyEnabled = true
|
isMinifyEnabled = true
|
||||||
|
isShrinkResources = true
|
||||||
proguardFiles(
|
proguardFiles(
|
||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro"
|
"proguard-rules.pro"
|
||||||
)
|
)
|
||||||
|
if (keystorePropertiesFile.exists()) {
|
||||||
|
signingConfig = signingConfigs.getByName("release")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
splits {
|
||||||
|
abi {
|
||||||
|
isEnable = true
|
||||||
|
reset()
|
||||||
|
include("arm64-v8a", "armeabi-v7a", "x86_64")
|
||||||
|
isUniversalApk = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
androidResources {
|
||||||
|
localeFilters += listOf("en", "zh-rCN", "zh-rTW")
|
||||||
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility = JavaVersion.VERSION_17
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
targetCompatibility = JavaVersion.VERSION_17
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
@@ -50,8 +92,27 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// APK 命名规范:2fair-<版本>-<abi>.apk(非 release 附构建类型,如 2fair-0.1.0-debug-arm64-v8a.apk)
|
||||||
|
androidComponents {
|
||||||
|
onVariants { variant ->
|
||||||
|
val buildType = variant.buildType
|
||||||
|
variant.outputs.forEach { output ->
|
||||||
|
val abi = output.filters
|
||||||
|
.firstOrNull { it.filterType == FilterConfiguration.FilterType.ABI }?.identifier
|
||||||
|
val fileName = buildString {
|
||||||
|
append("2fair-").append(appVersionName)
|
||||||
|
abi?.let { append('-').append(it) }
|
||||||
|
if (buildType != "release") append('-').append(buildType)
|
||||||
|
append(".apk")
|
||||||
|
}
|
||||||
|
output.outputFileName.set(fileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(platform(libs.androidx.compose.bom))
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
|
implementation(libs.reorderable)
|
||||||
implementation(libs.androidx.activity.compose)
|
implementation(libs.androidx.activity.compose)
|
||||||
implementation(libs.androidx.compose.material3)
|
implementation(libs.androidx.compose.material3)
|
||||||
implementation("androidx.compose.material:material-icons-extended")
|
implementation("androidx.compose.material:material-icons-extended")
|
||||||
@@ -74,7 +135,6 @@ dependencies {
|
|||||||
implementation(libs.androidx.camera.view)
|
implementation(libs.androidx.camera.view)
|
||||||
|
|
||||||
implementation(libs.zxing.core)
|
implementation(libs.zxing.core)
|
||||||
implementation(libs.mlkit.barcode.scanning)
|
|
||||||
|
|
||||||
implementation(libs.androidx.datastore.preferences)
|
implementation(libs.androidx.datastore.preferences)
|
||||||
|
|
||||||
|
|||||||
Vendored
+25
-4
@@ -21,15 +21,20 @@
|
|||||||
#-renamesourcefileattribute SourceFile
|
#-renamesourcefileattribute SourceFile
|
||||||
|
|
||||||
# Room
|
# Room
|
||||||
-keep class * extends androidx.room.RoomDatabase
|
# Room instantiates its generated *_Impl classes reflectively; R8 full mode
|
||||||
|
# (AGP 9 default) strips the no-arg constructor unless explicitly kept.
|
||||||
|
-keep class * extends androidx.room.RoomDatabase { <init>(); }
|
||||||
-dontwarn androidx.room.paging.**
|
-dontwarn androidx.room.paging.**
|
||||||
-keep @androidx.room.Entity class *
|
-keep @androidx.room.Entity class *
|
||||||
-keep class * {
|
-keep class * {
|
||||||
@androidx.room.PrimaryKey <fields>;
|
@androidx.room.PrimaryKey <fields>;
|
||||||
}
|
}
|
||||||
|
|
||||||
# CameraX
|
# Gson reflection: BackupManager serializes these models and the field names
|
||||||
-keep class androidx.camera.core.** { *; }
|
# are the on-disk JSON schema of backup files. Without keeps R8 renames the
|
||||||
|
# fields and backups silently change format between build types.
|
||||||
|
-keep class cn.airnan.a2fair.data.entity.Token { <fields>; }
|
||||||
|
-keep class cn.airnan.a2fair.core.backup.BackupData { <fields>; }
|
||||||
|
|
||||||
# JNI
|
# JNI
|
||||||
-keepclasseswithmembernames class * {
|
-keepclasseswithmembernames class * {
|
||||||
@@ -41,4 +46,20 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
# Base32 and algorithms (in case of reflection or specific needs)
|
# Base32 and algorithms (in case of reflection or specific needs)
|
||||||
-keep class cn.airnan.a2fair.core.algorithm.** { *; }
|
-keep class cn.airnan.a2fair.core.algorithm.** { *; }
|
||||||
|
|
||||||
|
# Optional compile-time-only references in Tink (androidx.security-crypto):
|
||||||
|
# google-http-client / joda-time paths and JSR-305 annotations that are absent
|
||||||
|
# at runtime. Generated by AGP in app/build/outputs/mapping/release/missing_rules.txt
|
||||||
|
-dontwarn com.google.api.client.http.GenericUrl
|
||||||
|
-dontwarn com.google.api.client.http.HttpHeaders
|
||||||
|
-dontwarn com.google.api.client.http.HttpRequest
|
||||||
|
-dontwarn com.google.api.client.http.HttpRequestFactory
|
||||||
|
-dontwarn com.google.api.client.http.HttpResponse
|
||||||
|
-dontwarn com.google.api.client.http.HttpTransport
|
||||||
|
-dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder
|
||||||
|
-dontwarn com.google.api.client.http.javanet.NetHttpTransport
|
||||||
|
-dontwarn javax.annotation.Nullable
|
||||||
|
-dontwarn javax.annotation.concurrent.GuardedBy
|
||||||
|
-dontwarn javax.annotation.concurrent.ThreadSafe
|
||||||
|
-dontwarn org.joda.time.Instant
|
||||||
@@ -5,6 +5,8 @@
|
|||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
||||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:name=".A2FairApplication"
|
android:name=".A2FairApplication"
|
||||||
@@ -15,7 +17,17 @@
|
|||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
android:theme="@style/Theme._2FAir">
|
android:theme="@style/Theme._2FAir">
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import android.os.Build
|
|||||||
import androidx.lifecycle.ProcessLifecycleOwner
|
import androidx.lifecycle.ProcessLifecycleOwner
|
||||||
import cn.airnan.a2fair.core.backup.BackupManager
|
import cn.airnan.a2fair.core.backup.BackupManager
|
||||||
import cn.airnan.a2fair.core.security.AppLockManager
|
import cn.airnan.a2fair.core.security.AppLockManager
|
||||||
|
import cn.airnan.a2fair.core.update.UpdateManager
|
||||||
import cn.airnan.a2fair.crypto.CryptoManager
|
import cn.airnan.a2fair.crypto.CryptoManager
|
||||||
import cn.airnan.a2fair.data.AppDatabase
|
import cn.airnan.a2fair.data.AppDatabase
|
||||||
import cn.airnan.a2fair.data.repository.SettingsRepository
|
import cn.airnan.a2fair.data.repository.SettingsRepository
|
||||||
@@ -37,6 +38,8 @@ class A2FairApplication : Application() {
|
|||||||
lateinit var backupManager: BackupManager
|
lateinit var backupManager: BackupManager
|
||||||
private set
|
private set
|
||||||
|
|
||||||
|
val updateManager: UpdateManager by lazy { UpdateManager(this) }
|
||||||
|
|
||||||
override fun attachBaseContext(base: Context) {
|
override fun attachBaseContext(base: Context) {
|
||||||
val languageCode = try {
|
val languageCode = try {
|
||||||
runBlocking { base.dataStore.data.first() }[intPreferencesKey("language")] ?: 0
|
runBlocking { base.dataStore.data.first() }[intPreferencesKey("language")] ?: 0
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import cn.airnan.a2fair.data.repository.dataStore
|
|||||||
import cn.airnan.a2fair.ui.navigation.AppNavigation
|
import cn.airnan.a2fair.ui.navigation.AppNavigation
|
||||||
import cn.airnan.a2fair.ui.settings.security.LockScreen
|
import cn.airnan.a2fair.ui.settings.security.LockScreen
|
||||||
import cn.airnan.a2fair.ui.theme._2FAirTheme
|
import cn.airnan.a2fair.ui.theme._2FAirTheme
|
||||||
|
import cn.airnan.a2fair.ui.update.UpdateDialog
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
@@ -65,9 +66,11 @@ class MainActivity : FragmentActivity() {
|
|||||||
val seedColor by settingsRepo.seedColor.collectAsStateWithLifecycle(initialValue = 0xFF6750A4.toInt())
|
val seedColor by settingsRepo.seedColor.collectAsStateWithLifecycle(initialValue = 0xFF6750A4.toInt())
|
||||||
val isFlagSecureEnabled by settingsRepo.isFlagSecureEnabled.collectAsStateWithLifecycle(initialValue = false)
|
val isFlagSecureEnabled by settingsRepo.isFlagSecureEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||||
val isLocked by appLockManager.isLocked.collectAsStateWithLifecycle()
|
val isLocked by appLockManager.isLocked.collectAsStateWithLifecycle()
|
||||||
|
val updateState by app.updateManager.state.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
appLockManager.checkInitialLockState()
|
appLockManager.checkInitialLockState()
|
||||||
|
app.updateManager.silentCheck()
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(isFlagSecureEnabled) {
|
LaunchedEffect(isFlagSecureEnabled) {
|
||||||
@@ -114,6 +117,18 @@ class MainActivity : FragmentActivity() {
|
|||||||
AppNavigation()
|
AppNavigation()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新弹窗锁屏期间不展示,解锁后可见;下载中弹窗不可随手关(需显式取消)
|
||||||
|
if (!isLocked) {
|
||||||
|
UpdateDialog(
|
||||||
|
state = updateState,
|
||||||
|
onDismiss = { app.updateManager.dismiss() },
|
||||||
|
onDownload = { app.updateManager.download(it) },
|
||||||
|
onCancelDownload = { app.updateManager.cancelDownload() },
|
||||||
|
onInstall = { app.updateManager.installReady(it) },
|
||||||
|
onRetryDownload = { app.updateManager.download(it) }
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,11 +50,16 @@ 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
|
||||||
val decryptedTokens = tokens.map { token ->
|
val decryptedTokens = tokens.map { token ->
|
||||||
token.copy(
|
token.copy(
|
||||||
@@ -41,8 +67,8 @@ class BackupManager(
|
|||||||
// So token.secret is already decrypted!
|
// So token.secret is already decrypted!
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
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 ivLength = encryptedBytes[offset++].toInt()
|
val saltLength = encryptedBytes[offset++].toInt()
|
||||||
val iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
|
salt = encryptedBytes.copyOfRange(offset, offset + saltLength)
|
||||||
offset += ivLength
|
offset += saltLength
|
||||||
|
|
||||||
val data = encryptedBytes.copyOfRange(offset, encryptedBytes.size)
|
val ivLength = encryptedBytes[offset++].toInt()
|
||||||
|
iv = encryptedBytes.copyOfRange(offset, offset + ivLength)
|
||||||
|
offset += ivLength
|
||||||
|
|
||||||
|
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)
|
||||||
// Merge logic (simple replace or merge)
|
} catch (e: JsonSyntaxException) {
|
||||||
// For now, let's just insert all if not exists, or replace. We'll do a simple insert.
|
return@withContext Result.failure(InvalidBackupFileException())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (backupData.version > BACKUP_VERSION) {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,256 @@
|
|||||||
|
package cn.airnan.a2fair.core.update
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.provider.Settings
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import cn.airnan.a2fair.BuildConfig
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import kotlin.coroutines.coroutineContext
|
||||||
|
|
||||||
|
/** Gitea Release 摘要(应用内更新用) */
|
||||||
|
data class UpdateInfo(
|
||||||
|
val tagName: String,
|
||||||
|
/** tag 去掉 v/V 前缀后的版本号,如 "V0.0.2" -> "0.0.2" */
|
||||||
|
val version: String,
|
||||||
|
val changelog: String,
|
||||||
|
val assetName: String,
|
||||||
|
val downloadUrl: String,
|
||||||
|
val sizeBytes: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
sealed interface UpdateState {
|
||||||
|
data object Checking : UpdateState
|
||||||
|
data object UpToDate : UpdateState
|
||||||
|
data class Available(val info: UpdateInfo) : UpdateState
|
||||||
|
data class CheckError(val message: String) : UpdateState
|
||||||
|
/** progress 取值 0..100;-1 表示响应无 Content-Length,进度未知 */
|
||||||
|
data class Downloading(val info: UpdateInfo, val progress: Int) : UpdateState
|
||||||
|
data class DownloadFailed(val info: UpdateInfo, val message: String) : UpdateState
|
||||||
|
data class ReadyToInstall(val info: UpdateInfo, val file: File) : UpdateState
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于 Gitea Release 的应用内更新:
|
||||||
|
* - 启动时静默检测(每进程一次),仅在发现新版本时弹窗
|
||||||
|
* - 关于页手动检测,结果回写到 [state]
|
||||||
|
* - 确认更新后按设备 ABI 择包下载,经 FileProvider 拉起系统安装器
|
||||||
|
*/
|
||||||
|
class UpdateManager(private val context: Context) {
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
private val silentChecked = AtomicBoolean(false)
|
||||||
|
private var checkJob: Job? = null
|
||||||
|
private var downloadJob: Job? = null
|
||||||
|
|
||||||
|
private val _state = MutableStateFlow<UpdateState?>(null)
|
||||||
|
val state: StateFlow<UpdateState?> = _state.asStateFlow()
|
||||||
|
|
||||||
|
/** 启动静默检测:失败与已是最新均不打扰 UI */
|
||||||
|
fun silentCheck() {
|
||||||
|
if (!silentChecked.compareAndSet(false, true)) return
|
||||||
|
scope.launch {
|
||||||
|
delay(SILENT_CHECK_DELAY_MS)
|
||||||
|
check(silent = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关于页手动检测 */
|
||||||
|
fun manualCheck() {
|
||||||
|
if (_state.value is UpdateState.Downloading) return
|
||||||
|
checkJob?.cancel()
|
||||||
|
checkJob = scope.launch { check(silent = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun download(info: UpdateInfo) {
|
||||||
|
if (_state.value is UpdateState.Downloading) return
|
||||||
|
downloadJob?.cancel()
|
||||||
|
downloadJob = scope.launch {
|
||||||
|
try {
|
||||||
|
val file = downloadApk(info) { progress ->
|
||||||
|
_state.value = UpdateState.Downloading(info, progress)
|
||||||
|
}
|
||||||
|
_state.value = UpdateState.ReadyToInstall(info, file)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||||
|
_state.value = UpdateState.DownloadFailed(info, e.message ?: "unknown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancelDownload() {
|
||||||
|
downloadJob?.cancel()
|
||||||
|
downloadJob = null
|
||||||
|
_state.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关闭弹窗;下载中不允许直接关(必须显式取消) */
|
||||||
|
fun dismiss() {
|
||||||
|
if (_state.value is UpdateState.Downloading) return
|
||||||
|
_state.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 安装已下载的 APK;缺少「安装未知应用」权限时先引导授权 */
|
||||||
|
fun installReady(ready: UpdateState.ReadyToInstall) {
|
||||||
|
if (canInstallNow()) {
|
||||||
|
install(ready.file)
|
||||||
|
} else {
|
||||||
|
requestInstallPermission()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun canInstallNow(): Boolean =
|
||||||
|
Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
|
||||||
|
context.packageManager.canRequestPackageInstalls()
|
||||||
|
|
||||||
|
private fun requestInstallPermission() {
|
||||||
|
val intent = Intent(
|
||||||
|
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
|
||||||
|
Uri.parse("package:${context.packageName}")
|
||||||
|
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun install(file: File) {
|
||||||
|
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW)
|
||||||
|
.setDataAndType(uri, "application/vnd.android.package-archive")
|
||||||
|
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun check(silent: Boolean) {
|
||||||
|
if (!silent) _state.value = UpdateState.Checking
|
||||||
|
try {
|
||||||
|
val info = fetchLatestRelease()
|
||||||
|
when {
|
||||||
|
info == null -> if (!silent) _state.value = UpdateState.UpToDate
|
||||||
|
isNewer(info.version, BuildConfig.VERSION_NAME) ->
|
||||||
|
_state.value = UpdateState.Available(info)
|
||||||
|
!silent -> _state.value = UpdateState.UpToDate
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (!silent) _state.value = UpdateState.CheckError(e.message ?: "unknown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fetchLatestRelease(): UpdateInfo? {
|
||||||
|
val conn = openConnection("$API_BASE/releases/latest")
|
||||||
|
val code = conn.responseCode
|
||||||
|
if (code == HttpURLConnection.HTTP_NOT_FOUND) return null // 仓库尚无 release
|
||||||
|
if (code != HttpURLConnection.HTTP_OK) throw IOException("HTTP $code")
|
||||||
|
val body = conn.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
|
||||||
|
|
||||||
|
val json = JSONObject(body)
|
||||||
|
val tagName = json.optString("tag_name").trim()
|
||||||
|
if (tagName.isEmpty()) return null
|
||||||
|
val asset = pickAsset(json.optJSONArray("assets")) ?: return null // 没有可用 APK 附件
|
||||||
|
|
||||||
|
return UpdateInfo(
|
||||||
|
tagName = tagName,
|
||||||
|
version = if (tagName.startsWith("v") || tagName.startsWith("V")) tagName.substring(1) else tagName,
|
||||||
|
changelog = json.optString("body"),
|
||||||
|
assetName = asset.optString("name"),
|
||||||
|
downloadUrl = asset.optString("browser_download_url"),
|
||||||
|
sizeBytes = asset.optLong("size", -1L)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按 Build.SUPPORTED_ABIS 优先级择包,兜底 arm64-v8a,再兜底第一个 .apk */
|
||||||
|
private fun pickAsset(assets: JSONArray?): JSONObject? {
|
||||||
|
if (assets == null) return null
|
||||||
|
val apks = (0 until assets.length())
|
||||||
|
.map { assets.getJSONObject(it) }
|
||||||
|
.filter { it.optString("name").endsWith(".apk", ignoreCase = true) }
|
||||||
|
if (apks.isEmpty()) return null
|
||||||
|
for (abi in Build.SUPPORTED_ABIS) {
|
||||||
|
apks.firstOrNull { it.optString("name").contains(abi, ignoreCase = true) }
|
||||||
|
?.let { return it }
|
||||||
|
}
|
||||||
|
return apks.firstOrNull { it.optString("name").contains("arm64-v8a", ignoreCase = true) }
|
||||||
|
?: apks.first()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun downloadApk(info: UpdateInfo, onProgress: (Int) -> Unit): File {
|
||||||
|
val dir = File(context.filesDir, "updates").apply { mkdirs() }
|
||||||
|
val tmp = File(dir, "${info.version}.apk.part")
|
||||||
|
val target = File(dir, "${info.version}.apk")
|
||||||
|
target.delete()
|
||||||
|
|
||||||
|
val conn = openConnection(info.downloadUrl)
|
||||||
|
val code = conn.responseCode
|
||||||
|
if (code != HttpURLConnection.HTTP_OK) throw IOException("HTTP $code")
|
||||||
|
val total = conn.contentLengthLong
|
||||||
|
var written = 0L
|
||||||
|
var lastPercent = -1
|
||||||
|
val activeContext = coroutineContext
|
||||||
|
|
||||||
|
conn.inputStream.use { input ->
|
||||||
|
tmp.outputStream().use { output ->
|
||||||
|
val buffer = ByteArray(64 * 1024)
|
||||||
|
while (true) {
|
||||||
|
activeContext.ensureActive()
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n == -1) break
|
||||||
|
output.write(buffer, 0, n)
|
||||||
|
written += n
|
||||||
|
if (total > 0) {
|
||||||
|
val percent = (written * 100 / total).toInt()
|
||||||
|
if (percent != lastPercent) {
|
||||||
|
lastPercent = percent
|
||||||
|
onProgress(percent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (total > 0 && written != total) throw IOException("truncated download")
|
||||||
|
if (!tmp.renameTo(target)) throw IOException("rename failed")
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openConnection(url: String): HttpURLConnection =
|
||||||
|
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||||
|
connectTimeout = 10_000
|
||||||
|
readTimeout = 20_000
|
||||||
|
instanceFollowRedirects = true
|
||||||
|
setRequestProperty("Accept", "*/*")
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val API_BASE = "https://git.airnan.cn/api/v1/repos/wangairnan/2FAir"
|
||||||
|
private const val SILENT_CHECK_DELAY_MS = 3_000L
|
||||||
|
|
||||||
|
/** 语义化比较:v 前缀可有可无,缺失段补 0,比较失败即不更新 */
|
||||||
|
fun isNewer(remote: String, current: String): Boolean {
|
||||||
|
fun parse(v: String) = v.split('.')
|
||||||
|
.map { seg -> seg.takeWhile(Char::isDigit).toIntOrNull() ?: 0 }
|
||||||
|
val r = parse(remote)
|
||||||
|
val c = parse(current)
|
||||||
|
for (i in 0 until maxOf(r.size, c.size)) {
|
||||||
|
val a = r.getOrElse(i) { 0 }
|
||||||
|
val b = c.getOrElse(i) { 0 }
|
||||||
|
if (a != b) return a > b
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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]"), "")
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,4 +34,7 @@ interface TokenDao {
|
|||||||
|
|
||||||
@Query("UPDATE tokens SET counter = :counter WHERE id = :id")
|
@Query("UPDATE tokens SET counter = :counter WHERE id = :id")
|
||||||
fun updateCounter(id: Long, counter: Long): Int
|
fun updateCounter(id: Long, counter: Long): Int
|
||||||
|
|
||||||
|
@Query("UPDATE tokens SET groupId = :targetGroupId WHERE groupId IS NULL")
|
||||||
|
fun reassignUncategorizedTokens(targetGroupId: Long)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,4 +28,5 @@ class TokenRepository(
|
|||||||
suspend fun updateToken(token: Token) { withContext(Dispatchers.IO) { tokenDao.updateToken(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 deleteToken(token: Token) { withContext(Dispatchers.IO) { tokenDao.deleteToken(token) } }
|
||||||
suspend fun updateCounter(id: Long, counter: Long) { withContext(Dispatchers.IO) { tokenDao.updateCounter(id, counter) } }
|
suspend fun updateCounter(id: Long, counter: Long) { withContext(Dispatchers.IO) { tokenDao.updateCounter(id, counter) } }
|
||||||
|
suspend fun reassignUncategorizedTokens(targetGroupId: Long) { withContext(Dispatchers.IO) { tokenDao.reassignUncategorizedTokens(targetGroupId) } }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -216,6 +216,26 @@ fun AppNavigation(
|
|||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
cn.airnan.a2fair.ui.settings.AboutScreen(
|
cn.airnan.a2fair.ui.settings.AboutScreen(
|
||||||
|
onNavigateBack = { appState.navController.popBackStack() },
|
||||||
|
onNavigateToLicenses = { appState.navController.navigate("licenses") }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
composable(
|
||||||
|
route = "licenses",
|
||||||
|
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.OpenSourceLicensesScreen(
|
||||||
onNavigateBack = { appState.navController.popBackStack() }
|
onNavigateBack = { appState.navController.popBackStack() }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import androidx.compose.material3.Scaffold
|
|||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
@@ -28,15 +29,34 @@ import androidx.compose.ui.platform.LocalContext
|
|||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.viewinterop.AndroidView
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import cn.airnan.a2fair.A2FairApplication
|
||||||
import cn.airnan.a2fair.BuildConfig
|
import cn.airnan.a2fair.BuildConfig
|
||||||
import cn.airnan.a2fair.R
|
import cn.airnan.a2fair.R
|
||||||
|
import cn.airnan.a2fair.core.update.UpdateState
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun AboutScreen(
|
fun AboutScreen(
|
||||||
onNavigateBack: () -> Unit
|
onNavigateBack: () -> Unit,
|
||||||
|
onNavigateToLicenses: () -> Unit = {}
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
val app = context.applicationContext as A2FairApplication
|
||||||
|
val updateState by app.updateManager.state.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val updateStatusText = when (val s = updateState) {
|
||||||
|
null -> stringResource(R.string.check_update_desc)
|
||||||
|
UpdateState.Checking -> stringResource(R.string.update_checking)
|
||||||
|
UpdateState.UpToDate -> stringResource(R.string.update_up_to_date)
|
||||||
|
is UpdateState.Available -> stringResource(R.string.update_available_title, s.info.version)
|
||||||
|
is UpdateState.CheckError -> stringResource(R.string.update_check_failed, s.message)
|
||||||
|
is UpdateState.Downloading ->
|
||||||
|
if (s.progress >= 0) stringResource(R.string.update_download_progress, s.progress)
|
||||||
|
else stringResource(R.string.update_downloading)
|
||||||
|
is UpdateState.DownloadFailed -> stringResource(R.string.update_download_failed, s.message)
|
||||||
|
is UpdateState.ReadyToInstall -> stringResource(R.string.update_ready_title)
|
||||||
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
@@ -86,20 +106,34 @@ fun AboutScreen(
|
|||||||
Spacer(modifier = Modifier.height(48.dp))
|
Spacer(modifier = Modifier.height(48.dp))
|
||||||
|
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text(stringResource(R.string.source_code)) },
|
headlineContent = { Text(stringResource(R.string.author_homepage)) },
|
||||||
supportingContent = { Text(stringResource(R.string.view_on_github)) },
|
supportingContent = { Text(stringResource(R.string.author_handle)) },
|
||||||
modifier = Modifier.clickable {
|
modifier = Modifier.clickable {
|
||||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/"))
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://airnan.cn"))
|
||||||
context.startActivity(intent)
|
context.startActivity(intent)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
ListItem(
|
ListItem(
|
||||||
headlineContent = { Text(stringResource(R.string.open_source_licenses)) },
|
headlineContent = { Text(stringResource(R.string.source_code)) },
|
||||||
|
supportingContent = { Text(stringResource(R.string.view_on_gitea)) },
|
||||||
modifier = Modifier.clickable {
|
modifier = Modifier.clickable {
|
||||||
// TODO: Implement license viewer or navigation
|
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://git.airnan.cn/wangairnan/2FAir"))
|
||||||
|
context.startActivity(intent)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(stringResource(R.string.check_update)) },
|
||||||
|
supportingContent = { Text(updateStatusText) },
|
||||||
|
modifier = Modifier.clickable { app.updateManager.manualCheck() }
|
||||||
|
)
|
||||||
|
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(stringResource(R.string.open_source_licenses)) },
|
||||||
|
supportingContent = { Text(stringResource(R.string.licenses_desc)) },
|
||||||
|
modifier = Modifier.clickable { onNavigateToLicenses() }
|
||||||
|
)
|
||||||
|
|
||||||
Spacer(modifier = Modifier.weight(1f))
|
Spacer(modifier = Modifier.weight(1f))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package cn.airnan.a2fair.ui.settings
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.ArrowBack
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
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.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cn.airnan.a2fair.R
|
||||||
|
|
||||||
|
private data class LibraryLicense(
|
||||||
|
val name: String,
|
||||||
|
val url: String
|
||||||
|
)
|
||||||
|
|
||||||
|
private data class LicenseGroup(
|
||||||
|
val license: String,
|
||||||
|
val licenseUrl: String,
|
||||||
|
val libraries: List<LibraryLicense>
|
||||||
|
)
|
||||||
|
|
||||||
|
private val APACHE_2_0_URL = "https://www.apache.org/licenses/LICENSE-2.0"
|
||||||
|
|
||||||
|
private val licenseGroups = listOf(
|
||||||
|
LicenseGroup(
|
||||||
|
license = "Apache License 2.0",
|
||||||
|
licenseUrl = APACHE_2_0_URL,
|
||||||
|
libraries = listOf(
|
||||||
|
LibraryLicense(
|
||||||
|
name = "AndroidX & Jetpack Compose",
|
||||||
|
url = "https://developer.android.com/jetpack"
|
||||||
|
),
|
||||||
|
LibraryLicense(
|
||||||
|
name = "Material Components for Android",
|
||||||
|
url = "https://github.com/material-components/material-components-android"
|
||||||
|
),
|
||||||
|
LibraryLicense(
|
||||||
|
name = "Kotlin & Coroutines",
|
||||||
|
url = "https://github.com/JetBrains/kotlin"
|
||||||
|
),
|
||||||
|
LibraryLicense(
|
||||||
|
name = "KSP (Kotlin Symbol Processing)",
|
||||||
|
url = "https://github.com/google/ksp"
|
||||||
|
),
|
||||||
|
LibraryLicense(
|
||||||
|
name = "ZXing Core",
|
||||||
|
url = "https://github.com/zxing/zxing"
|
||||||
|
),
|
||||||
|
LibraryLicense(
|
||||||
|
name = "Gson",
|
||||||
|
url = "https://github.com/google/gson"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun OpenSourceLicensesScreen(
|
||||||
|
onNavigateBack: () -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val openUrl: (String) -> Unit = { url ->
|
||||||
|
context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text(stringResource(R.string.open_source_licenses)) },
|
||||||
|
navigationIcon = {
|
||||||
|
IconButton(onClick = onNavigateBack) {
|
||||||
|
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
) { padding ->
|
||||||
|
LazyColumn(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(padding)
|
||||||
|
) {
|
||||||
|
item {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.licenses_desc),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.padding(start = 16.dp, top = 8.dp, end = 16.dp, bottom = 8.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
licenseGroups.forEach { group ->
|
||||||
|
item(key = "license_${group.license}") {
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(group.license) },
|
||||||
|
supportingContent = { Text(group.licenseUrl, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
modifier = Modifier.clickable { openUrl(group.licenseUrl) }
|
||||||
|
)
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
items(group.libraries, key = { "lib_${group.license}_${it.name}" }) { library ->
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text(library.name) },
|
||||||
|
supportingContent = { Text(library.url, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||||
|
modifier = Modifier.clickable { openUrl(library.url) }
|
||||||
|
)
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
package cn.airnan.a2fair.ui.settings
|
package cn.airnan.a2fair.ui.settings
|
||||||
|
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
@@ -11,11 +10,12 @@ import androidx.compose.material.icons.filled.Info
|
|||||||
import androidx.compose.material.icons.filled.Lock
|
import androidx.compose.material.icons.filled.Lock
|
||||||
import androidx.compose.material.icons.filled.SettingsBackupRestore
|
import androidx.compose.material.icons.filled.SettingsBackupRestore
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.ListItem
|
import androidx.compose.material3.ListItem
|
||||||
|
import androidx.compose.material3.MediumFlexibleTopAppBar
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TopAppBar
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
@@ -25,7 +25,7 @@ import cn.airnan.a2fair.R
|
|||||||
import androidx.compose.material.icons.filled.Language
|
import androidx.compose.material.icons.filled.Language
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun SettingsScreen(
|
fun SettingsScreen(
|
||||||
onNavigateToSecurity: () -> Unit,
|
onNavigateToSecurity: () -> Unit,
|
||||||
@@ -36,7 +36,7 @@ fun SettingsScreen(
|
|||||||
) {
|
) {
|
||||||
Scaffold(
|
Scaffold(
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
MediumFlexibleTopAppBar(
|
||||||
title = { Text(stringResource(R.string.settings)) }
|
title = { Text(stringResource(R.string.settings)) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -178,8 +209,9 @@ fun BackupScreen(
|
|||||||
},
|
},
|
||||||
dismissButton = {
|
dismissButton = {
|
||||||
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()
|
||||||
|
|||||||
@@ -6,7 +6,10 @@ import android.content.ContextWrapper
|
|||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.material3.ColorScheme
|
import androidx.compose.material3.ColorScheme
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
|
||||||
|
import androidx.compose.material3.MaterialExpressiveTheme
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.MotionScheme
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.dynamicDarkColorScheme
|
import androidx.compose.material3.dynamicDarkColorScheme
|
||||||
import androidx.compose.material3.dynamicLightColorScheme
|
import androidx.compose.material3.dynamicLightColorScheme
|
||||||
@@ -115,6 +118,7 @@ tailrec fun Context.findActivity(): Activity? = when (this) {
|
|||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun _2FAirTheme(
|
fun _2FAirTheme(
|
||||||
themeMode: Int = 0, // 0: System, 1: Light, 2: Dark
|
themeMode: Int = 0, // 0: System, 1: Light, 2: Dark
|
||||||
@@ -147,8 +151,9 @@ fun _2FAirTheme(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MaterialTheme(
|
MaterialExpressiveTheme(
|
||||||
colorScheme = colorScheme,
|
colorScheme = colorScheme,
|
||||||
|
motionScheme = MotionScheme.expressive(),
|
||||||
typography = Typography,
|
typography = Typography,
|
||||||
content = content
|
content = content
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
package cn.airnan.a2fair.ui.tokens
|
package cn.airnan.a2fair.ui.tokens
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.graphics.ImageFormat
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.PickVisualMediaRequest
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
@@ -17,9 +21,11 @@ import androidx.compose.foundation.rememberScrollState
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.*
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material.icons.outlined.PhotoCamera
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
@@ -36,13 +42,20 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
|||||||
import cn.airnan.a2fair.R
|
import cn.airnan.a2fair.R
|
||||||
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
import cn.airnan.a2fair.data.entity.HashAlgorithm
|
||||||
import cn.airnan.a2fair.data.entity.TokenType
|
import cn.airnan.a2fair.data.entity.TokenType
|
||||||
import com.google.mlkit.vision.barcode.BarcodeScanning
|
import com.google.zxing.BarcodeFormat
|
||||||
import com.google.mlkit.vision.barcode.common.Barcode
|
import com.google.zxing.BinaryBitmap
|
||||||
import com.google.mlkit.vision.common.InputImage
|
import com.google.zxing.DecodeHintType
|
||||||
|
import com.google.zxing.LuminanceSource
|
||||||
|
import com.google.zxing.MultiFormatReader
|
||||||
|
import com.google.zxing.NotFoundException
|
||||||
|
import com.google.zxing.PlanarYUVLuminanceSource
|
||||||
|
import com.google.zxing.RGBLuminanceSource
|
||||||
|
import com.google.zxing.common.HybridBinarizer
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import java.nio.ByteBuffer
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun AddTokenBottomSheet(
|
fun AddTokenBottomSheet(
|
||||||
viewModel: TokensViewModel,
|
viewModel: TokensViewModel,
|
||||||
@@ -59,34 +72,29 @@ fun AddTokenBottomSheet(
|
|||||||
contract = ActivityResultContracts.PickVisualMedia()
|
contract = ActivityResultContracts.PickVisualMedia()
|
||||||
) { uri: Uri? ->
|
) { uri: Uri? ->
|
||||||
if (uri != null) {
|
if (uri != null) {
|
||||||
try {
|
val rawValue = decodeQrFromUri(context, uri)
|
||||||
val image = InputImage.fromFilePath(context, uri)
|
if (rawValue != null && rawValue.startsWith("otpauth://")) {
|
||||||
val scanner = BarcodeScanning.getClient()
|
viewModel.addTokenFromUri(rawValue)
|
||||||
scanner.process(image)
|
} else {
|
||||||
.addOnSuccessListener { barcodes ->
|
// Handle error: no valid QR code found
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var hasCameraPermission by remember { mutableStateOf(false) }
|
||||||
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
val cameraPermissionLauncher = rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.RequestPermission()
|
contract = ActivityResultContracts.RequestPermission()
|
||||||
) { _ ->
|
) { granted ->
|
||||||
// Permission result - camera will auto-start when preview composable is shown
|
hasCameraPermission = granted
|
||||||
// if permission was granted, we just re-compose so PreviewView binds
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
hasCameraPermission = ContextCompat.checkSelfPermission(
|
||||||
|
context, Manifest.permission.CAMERA
|
||||||
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!hasCameraPermission) {
|
||||||
|
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(state.isSuccess) {
|
LaunchedEffect(state.isSuccess) {
|
||||||
@@ -154,25 +162,59 @@ fun AddTokenBottomSheet(
|
|||||||
modifier = Modifier.fillMaxSize()
|
modifier = Modifier.fillMaxSize()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (!hasCameraPermission) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
modifier = Modifier.align(Alignment.Center).padding(16.dp)
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(56.dp)
|
||||||
|
.clip(MaterialShapes.Cookie9Sided.toShape())
|
||||||
|
.background(MaterialTheme.colorScheme.primaryContainer),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Outlined.PhotoCamera,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(10.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.camera_permission_hint),
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (showScanningText) {
|
if (showScanningText) {
|
||||||
Surface(
|
Surface(
|
||||||
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
|
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
|
||||||
modifier = Modifier.align(Alignment.BottomCenter).padding(8.dp),
|
modifier = Modifier.align(Alignment.BottomCenter).padding(8.dp),
|
||||||
shape = RoundedCornerShape(8.dp)
|
shape = RoundedCornerShape(8.dp)
|
||||||
) {
|
) {
|
||||||
Text(
|
Row(
|
||||||
text = stringResource(R.string.scanning_hint),
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||||
style = MaterialTheme.typography.labelMedium,
|
) {
|
||||||
color = MaterialTheme.colorScheme.onSurface
|
LoadingIndicator(modifier = Modifier.size(20.dp))
|
||||||
)
|
Spacer(modifier = Modifier.width(8.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.scanning_hint),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(previewView) {
|
LaunchedEffect(previewView, hasCameraPermission) {
|
||||||
val pv = previewView ?: return@LaunchedEffect
|
val pv = previewView ?: return@LaunchedEffect
|
||||||
|
if (!hasCameraPermission) return@LaunchedEffect
|
||||||
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
|
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
|
||||||
cameraProviderFuture.addListener({
|
cameraProviderFuture.addListener({
|
||||||
val cameraProvider = cameraProviderFuture.get()
|
val cameraProvider = cameraProviderFuture.get()
|
||||||
@@ -255,37 +297,124 @@ fun AddTokenBottomSheet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ZxingAnalyzer(private val onScan: (String) -> Unit) : ImageAnalysis.Analyzer {
|
class ZxingAnalyzer(private val onScan: (String) -> Unit) : ImageAnalysis.Analyzer {
|
||||||
private val scanner = BarcodeScanning.getClient()
|
private val reader = MultiFormatReader().apply {
|
||||||
|
setHints(
|
||||||
|
mapOf(
|
||||||
|
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE, BarcodeFormat.AZTEC),
|
||||||
|
DecodeHintType.TRY_HARDER to true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
@Volatile
|
@Volatile
|
||||||
private var scanned = false
|
private var scanned = false
|
||||||
|
|
||||||
@androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)
|
|
||||||
override fun analyze(imageProxy: ImageProxy) {
|
override fun analyze(imageProxy: ImageProxy) {
|
||||||
if (scanned) {
|
if (scanned) {
|
||||||
imageProxy.close()
|
imageProxy.close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val mediaImage = imageProxy.image
|
val text = try {
|
||||||
if (mediaImage != null) {
|
val source = luminanceSource(imageProxy)
|
||||||
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
|
if (source != null) {
|
||||||
scanner.process(image)
|
try {
|
||||||
.addOnSuccessListener { barcodes ->
|
reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text
|
||||||
val barcode = barcodes.firstOrNull { it.valueType == Barcode.TYPE_WIFI || it.rawValue?.startsWith("otpauth://") == true }
|
} catch (e: NotFoundException) {
|
||||||
?: barcodes.firstOrNull()
|
null
|
||||||
val rawValue = barcode?.rawValue
|
} finally {
|
||||||
if (rawValue != null && rawValue.startsWith("otpauth://")) {
|
reader.reset()
|
||||||
scanned = true
|
|
||||||
onScan(rawValue)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.addOnFailureListener {
|
} else {
|
||||||
// Ignored
|
null
|
||||||
}
|
}
|
||||||
.addOnCompleteListener {
|
} catch (e: Exception) {
|
||||||
imageProxy.close()
|
null
|
||||||
}
|
} finally {
|
||||||
} else {
|
|
||||||
imageProxy.close()
|
imageProxy.close()
|
||||||
}
|
}
|
||||||
|
if (text != null && text.startsWith("otpauth://")) {
|
||||||
|
scanned = true
|
||||||
|
onScan(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun luminanceSource(proxy: ImageProxy): LuminanceSource? {
|
||||||
|
if (proxy.format != ImageFormat.YUV_420_888) return null
|
||||||
|
val plane = proxy.planes[0]
|
||||||
|
val yPlane = extractYPlane(
|
||||||
|
plane.buffer, proxy.width, proxy.height, plane.rowStride, plane.pixelStride,
|
||||||
|
proxy.imageInfo.rotationDegrees
|
||||||
|
)
|
||||||
|
return PlanarYUVLuminanceSource(yPlane.data, yPlane.width, yPlane.height, 0, 0, yPlane.width, yPlane.height, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class YPlane(val data: ByteArray, val width: Int, val height: Int)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compacts the camera Y plane (dropping row/pixel padding) and rotates it by
|
||||||
|
* [rotationDegrees] into display orientation. PlanarYUVLuminanceSource itself
|
||||||
|
* cannot rotate (it throws UnsupportedOperationException), so the raw bytes
|
||||||
|
* are re-indexed here. Output dimensions are swapped for 90/270.
|
||||||
|
*/
|
||||||
|
internal fun extractYPlane(
|
||||||
|
buffer: ByteBuffer,
|
||||||
|
width: Int,
|
||||||
|
height: Int,
|
||||||
|
rowStride: Int,
|
||||||
|
pixelStride: Int,
|
||||||
|
rotationDegrees: Int
|
||||||
|
): YPlane {
|
||||||
|
val rotation = ((rotationDegrees % 360) + 360) % 360
|
||||||
|
val rotated = rotation == 90 || rotation == 270
|
||||||
|
val outWidth = if (rotated) height else width
|
||||||
|
val outHeight = if (rotated) width else height
|
||||||
|
val out = ByteArray(outWidth * outHeight)
|
||||||
|
for (y in 0 until height) {
|
||||||
|
val rowStart = y * rowStride
|
||||||
|
for (x in 0 until width) {
|
||||||
|
val v = buffer.get(rowStart + x * pixelStride)
|
||||||
|
when (rotation) {
|
||||||
|
90 -> out[(width - 1 - x) * height + y] = v
|
||||||
|
180 -> out[(height - 1 - y) * width + (width - 1 - x)] = v
|
||||||
|
270 -> out[x * height + (height - 1 - y)] = v
|
||||||
|
else -> out[y * width + x] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return YPlane(out, outWidth, outHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeQrFromUri(context: Context, uri: Uri): String? {
|
||||||
|
return try {
|
||||||
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
|
context.contentResolver.openInputStream(uri)?.use {
|
||||||
|
BitmapFactory.decodeStream(it, null, bounds)
|
||||||
|
}
|
||||||
|
var sampleSize = 1
|
||||||
|
while (maxOf(bounds.outWidth, bounds.outHeight) / sampleSize > 1536) sampleSize *= 2
|
||||||
|
val options = BitmapFactory.Options().apply { inSampleSize = sampleSize }
|
||||||
|
val bitmap = context.contentResolver.openInputStream(uri)?.use {
|
||||||
|
BitmapFactory.decodeStream(it, null, options)
|
||||||
|
} ?: return null
|
||||||
|
val pixels = IntArray(bitmap.width * bitmap.height)
|
||||||
|
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
|
||||||
|
bitmap.recycle()
|
||||||
|
val reader = MultiFormatReader().apply {
|
||||||
|
setHints(
|
||||||
|
mapOf(
|
||||||
|
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE, BarcodeFormat.AZTEC),
|
||||||
|
DecodeHintType.TRY_HARDER to true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
reader.decodeWithState(BinaryBitmap(HybridBinarizer(RGBLuminanceSource(bitmap.width, bitmap.height, pixels)))).text
|
||||||
|
} catch (e: NotFoundException) {
|
||||||
|
null
|
||||||
|
} finally {
|
||||||
|
reader.reset()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ import androidx.compose.runtime.*
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
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.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -24,7 +26,7 @@ import cn.airnan.a2fair.data.entity.Token
|
|||||||
import cn.airnan.a2fair.data.entity.TokenType
|
import cn.airnan.a2fair.data.entity.TokenType
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun TokenDetailSheet(
|
fun TokenDetailSheet(
|
||||||
token: Token,
|
token: Token,
|
||||||
@@ -154,12 +156,14 @@ fun TokenDetailSheet(
|
|||||||
modifier = Modifier.size(44.dp),
|
modifier = Modifier.size(44.dp),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
CircularProgressIndicator(
|
val ringStroke = Stroke(width = with(LocalDensity.current) { 3.dp.toPx() })
|
||||||
|
CircularWavyProgressIndicator(
|
||||||
progress = { progress },
|
progress = { progress },
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.size(44.dp),
|
||||||
color = if (showNextPreview) warningColor else MaterialTheme.colorScheme.primary,
|
color = if (showNextPreview) warningColor else MaterialTheme.colorScheme.primary,
|
||||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
trackColor = MaterialTheme.colorScheme.outlineVariant,
|
||||||
strokeWidth = 3.dp,
|
stroke = ringStroke,
|
||||||
|
trackStroke = ringStroke,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "$remainingSeconds",
|
text = "$remainingSeconds",
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -6,33 +6,49 @@ import android.content.Context
|
|||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
|
import androidx.compose.foundation.LocalIndication
|
||||||
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.interaction.MutableInteractionSource
|
||||||
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
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
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.SearchOff
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.*
|
import androidx.compose.runtime.*
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.shadow
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
import androidx.compose.ui.focus.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
import androidx.compose.ui.focus.onFocusChanged
|
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.vector.ImageVector
|
||||||
|
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||||
|
import androidx.compose.ui.input.nestedscroll.nestedScroll
|
||||||
|
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.platform.LocalHapticFeedback
|
||||||
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.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
@@ -41,9 +57,13 @@ import cn.airnan.a2fair.R
|
|||||||
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.entity.TokenType
|
import cn.airnan.a2fair.data.entity.TokenType
|
||||||
|
import kotlin.math.abs
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
import sh.calvin.reorderable.ReorderableColumn
|
||||||
|
import sh.calvin.reorderable.ReorderableItem
|
||||||
|
import sh.calvin.reorderable.rememberReorderableLazyListState
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun TokensScreen(
|
fun TokensScreen(
|
||||||
viewModel: TokensViewModel,
|
viewModel: TokensViewModel,
|
||||||
@@ -55,6 +75,15 @@ fun TokensScreen(
|
|||||||
var searchFieldHasFocus by remember { mutableStateOf(false) }
|
var searchFieldHasFocus by remember { mutableStateOf(false) }
|
||||||
val searchFocusRequester = remember { FocusRequester() }
|
val searchFocusRequester = remember { FocusRequester() }
|
||||||
val focusManager = LocalFocusManager.current
|
val focusManager = LocalFocusManager.current
|
||||||
|
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
|
||||||
|
|
||||||
|
// Group drag-reorder state: pending local order while dragging, persisted on release
|
||||||
|
val hapticFeedback = LocalHapticFeedback.current
|
||||||
|
var pendingGroupOrder by remember { mutableStateOf<List<Group?>?>(null) }
|
||||||
|
val lazyListState = rememberLazyListState()
|
||||||
|
var renameTarget by remember { mutableStateOf<Group?>(null) }
|
||||||
|
var deleteTarget by remember { mutableStateOf<Group?>(null) }
|
||||||
|
var renameUncategorized by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
LaunchedEffect(isSearchExpanded) {
|
LaunchedEffect(isSearchExpanded) {
|
||||||
if (isSearchExpanded) {
|
if (isSearchExpanded) {
|
||||||
@@ -63,68 +92,56 @@ fun TokensScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
Scaffold(
|
Scaffold(
|
||||||
|
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
if (isSearchExpanded) {
|
||||||
title = {
|
TopAppBar(
|
||||||
Row(
|
title = {
|
||||||
modifier = Modifier.fillMaxWidth(),
|
Surface(
|
||||||
verticalAlignment = Alignment.CenterVertically
|
shape = MaterialTheme.shapes.large,
|
||||||
) {
|
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||||
AnimatedVisibility(visible = !isSearchExpanded) {
|
|
||||||
Text(stringResource(R.string.tokens))
|
|
||||||
}
|
|
||||||
AnimatedVisibility(
|
|
||||||
visible = isSearchExpanded,
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.weight(1f)
|
.fillMaxWidth()
|
||||||
.padding(end = 16.dp)
|
.padding(end = 16.dp)
|
||||||
) {
|
) {
|
||||||
Surface(
|
TextField(
|
||||||
shape = MaterialTheme.shapes.large,
|
value = uiState.searchQuery,
|
||||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
onValueChange = { viewModel.updateSearchQuery(it) },
|
||||||
modifier = Modifier.fillMaxWidth()
|
modifier = Modifier
|
||||||
) {
|
.fillMaxWidth()
|
||||||
TextField(
|
.focusRequester(searchFocusRequester)
|
||||||
value = uiState.searchQuery,
|
.onFocusChanged { focusState ->
|
||||||
onValueChange = { viewModel.updateSearchQuery(it) },
|
if (searchFieldHasFocus && !focusState.isFocused) {
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.focusRequester(searchFocusRequester)
|
|
||||||
.onFocusChanged { focusState ->
|
|
||||||
if (searchFieldHasFocus && !focusState.isFocused) {
|
|
||||||
isSearchExpanded = false
|
|
||||||
}
|
|
||||||
searchFieldHasFocus = focusState.isFocused
|
|
||||||
},
|
|
||||||
placeholder = { Text(stringResource(R.string.search_tokens)) },
|
|
||||||
leadingIcon = { Icon(Icons.Default.Search, contentDescription = stringResource(R.string.search)) },
|
|
||||||
trailingIcon = {
|
|
||||||
IconButton(onClick = {
|
|
||||||
viewModel.updateSearchQuery("")
|
|
||||||
focusManager.clearFocus(force = true)
|
|
||||||
isSearchExpanded = false
|
isSearchExpanded = false
|
||||||
}) {
|
|
||||||
Icon(Icons.Default.Close, contentDescription = "Clear search")
|
|
||||||
}
|
}
|
||||||
|
searchFieldHasFocus = focusState.isFocused
|
||||||
},
|
},
|
||||||
singleLine = true,
|
placeholder = { Text(stringResource(R.string.search_tokens)) },
|
||||||
colors = TextFieldDefaults.colors(
|
leadingIcon = { Icon(Icons.Default.Search, contentDescription = stringResource(R.string.search)) },
|
||||||
unfocusedIndicatorColor = Color.Transparent,
|
trailingIcon = {
|
||||||
focusedIndicatorColor = Color.Transparent
|
IconButton(onClick = {
|
||||||
)
|
viewModel.updateSearchQuery("")
|
||||||
|
focusManager.clearFocus(force = true)
|
||||||
|
isSearchExpanded = false
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Close, contentDescription = "Clear search")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
singleLine = true,
|
||||||
|
colors = TextFieldDefaults.colors(
|
||||||
|
unfocusedIndicatorColor = Color.Transparent,
|
||||||
|
focusedIndicatorColor = Color.Transparent
|
||||||
)
|
)
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
)
|
||||||
actions = {
|
} else {
|
||||||
AnimatedVisibility(visible = !isSearchExpanded) {
|
MediumFlexibleTopAppBar(
|
||||||
IconButton(onClick = { isSearchExpanded = true }) {
|
title = { Text(stringResource(R.string.app_name)) },
|
||||||
Icon(Icons.Default.Search, contentDescription = stringResource(R.string.search))
|
scrollBehavior = scrollBehavior
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
)
|
|
||||||
},
|
},
|
||||||
floatingActionButton = {
|
floatingActionButton = {
|
||||||
FloatingActionButton(onClick = { showAddBottomSheet = true }) {
|
FloatingActionButton(onClick = { showAddBottomSheet = true }) {
|
||||||
@@ -137,38 +154,140 @@ fun TokensScreen(
|
|||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(padding)
|
.padding(padding)
|
||||||
) {
|
) {
|
||||||
// Token List
|
if (!isSearchExpanded) {
|
||||||
LazyColumn(
|
Surface(
|
||||||
modifier = Modifier.fillMaxSize(),
|
shape = MaterialTheme.shapes.extraLarge,
|
||||||
contentPadding = PaddingValues(bottom = 80.dp)
|
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||||
) {
|
modifier = Modifier
|
||||||
uiState.groupedTokens.forEach { (group, tokens) ->
|
.fillMaxWidth()
|
||||||
val groupId = group?.id
|
.padding(horizontal = 16.dp, vertical = 4.dp)
|
||||||
val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L)
|
.clickable { isSearchExpanded = true }
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Default.Search,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.width(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.search_tokens),
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val latestUiState by rememberUpdatedState(uiState)
|
||||||
|
if (uiState.groupedTokens.isEmpty()) {
|
||||||
|
if (uiState.searchQuery.isBlank()) {
|
||||||
|
EmptyState(
|
||||||
|
icon = Icons.Outlined.QrCode2,
|
||||||
|
title = stringResource(R.string.empty_tokens_title),
|
||||||
|
hint = stringResource(R.string.empty_tokens_hint),
|
||||||
|
actionLabel = stringResource(R.string.add_token),
|
||||||
|
onActionClick = { showAddBottomSheet = true }
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
EmptyState(
|
||||||
|
icon = Icons.Outlined.SearchOff,
|
||||||
|
title = stringResource(R.string.empty_search_title),
|
||||||
|
hint = stringResource(R.string.empty_search_hint),
|
||||||
|
iconShape = MaterialShapes.Sunny.toShape()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Token List
|
||||||
|
val displayGroups =
|
||||||
|
(pendingGroupOrder ?: latestUiState.groupedTokens.keys.toList())
|
||||||
|
.mapNotNull { key -> latestUiState.groupedTokens[key]?.let { key to it } }
|
||||||
|
|
||||||
item(key = "group_${groupId ?: "unassigned"}") {
|
val reorderableLazyListState =
|
||||||
Card(
|
rememberReorderableLazyListState(lazyListState) { from, to ->
|
||||||
modifier = Modifier
|
val keys = pendingGroupOrder ?: latestUiState.groupedTokens.keys.toList()
|
||||||
.fillMaxWidth()
|
val fromIndex = keys.indexOfFirst { groupItemKey(it) == from.key }
|
||||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
val toIndex = keys.indexOfFirst { groupItemKey(it) == to.key }
|
||||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
|
if (fromIndex in keys.indices && toIndex in keys.indices) {
|
||||||
) {
|
pendingGroupOrder =
|
||||||
Column {
|
keys.toMutableList().apply { add(toIndex, removeAt(fromIndex)) }
|
||||||
GroupHeader(
|
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
|
||||||
group = group,
|
}
|
||||||
isCollapsed = isCollapsed,
|
}
|
||||||
onToggle = { viewModel.toggleGroupCollapse(groupId) }
|
|
||||||
|
LazyColumn(
|
||||||
|
state = lazyListState,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(bottom = 80.dp),
|
||||||
|
) {
|
||||||
|
items(displayGroups, key = { groupItemKey(it.first) }) { (group, tokens) ->
|
||||||
|
val groupId = group?.id
|
||||||
|
val isCollapsed = uiState.collapsedGroups.contains(groupId ?: -1L)
|
||||||
|
|
||||||
|
ReorderableItem(reorderableLazyListState, groupItemKey(group)) { groupDragging ->
|
||||||
|
val groupDragScope = this
|
||||||
|
val groupInteractionSource = remember { MutableInteractionSource() }
|
||||||
|
Card(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(
|
||||||
|
defaultElevation = if (groupDragging) 6.dp else 0.dp
|
||||||
)
|
)
|
||||||
|
) {
|
||||||
|
Column {
|
||||||
|
GroupHeader(
|
||||||
|
group = group,
|
||||||
|
isCollapsed = isCollapsed,
|
||||||
|
onToggle = { viewModel.toggleGroupCollapse(groupId) },
|
||||||
|
onRename = { renameTarget = group; renameUncategorized = group == null },
|
||||||
|
onDelete = { group?.let { deleteTarget = it } },
|
||||||
|
dragModifier = with(groupDragScope) {
|
||||||
|
Modifier.draggableHandle(
|
||||||
|
interactionSource = groupInteractionSource,
|
||||||
|
onDragStarted = {
|
||||||
|
hapticFeedback.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate)
|
||||||
|
},
|
||||||
|
onDragStopped = {
|
||||||
|
pendingGroupOrder?.let { viewModel.applyGroupOrder(it) }
|
||||||
|
pendingGroupOrder = null
|
||||||
|
}
|
||||||
|
)
|
||||||
|
},
|
||||||
|
interactionSource = groupInteractionSource
|
||||||
|
)
|
||||||
|
|
||||||
if (!isCollapsed) {
|
if (!isCollapsed) {
|
||||||
tokens.forEachIndexed { index, token ->
|
ReorderableColumn(
|
||||||
TokenCard(
|
list = tokens,
|
||||||
token = token,
|
onMove = {
|
||||||
onIncrement = { viewModel.incrementCounter(token) },
|
hapticFeedback.performHapticFeedback(HapticFeedbackType.SegmentFrequentTick)
|
||||||
onEdit = { onNavigateToTokenEdit(token.id) }
|
},
|
||||||
)
|
onSettle = { from, to ->
|
||||||
if (index < tokens.lastIndex) {
|
val newOrder = tokens.toMutableList().apply { add(to, removeAt(from)) }
|
||||||
HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
|
viewModel.applyTokenOrder(newOrder)
|
||||||
|
},
|
||||||
|
) { index, token, tokenDragging ->
|
||||||
|
key(token.id) {
|
||||||
|
ReorderableItem {
|
||||||
|
val tokenDragScope = this
|
||||||
|
val rowInteractionSource = remember { MutableInteractionSource() }
|
||||||
|
TokenCard(
|
||||||
|
token = token,
|
||||||
|
onIncrement = { viewModel.incrementCounter(token) },
|
||||||
|
onEdit = { onNavigateToTokenEdit(token.id) },
|
||||||
|
isDragging = tokenDragging,
|
||||||
|
interactionSource = rowInteractionSource,
|
||||||
|
dragModifier = with(tokenDragScope) {
|
||||||
|
Modifier.draggableHandle(
|
||||||
|
interactionSource = rowInteractionSource
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -189,29 +308,186 @@ fun TokensScreen(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (renameUncategorized || renameTarget != null) {
|
||||||
|
val target = renameTarget
|
||||||
|
val currentName = target?.name ?: stringResource(R.string.uncategorized)
|
||||||
|
var newName by remember(renameTarget?.id, currentName) { mutableStateOf(currentName) }
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { renameTarget = null; renameUncategorized = false },
|
||||||
|
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() != currentName,
|
||||||
|
onClick = {
|
||||||
|
viewModel.renameGroup(target, newName)
|
||||||
|
renameTarget = null
|
||||||
|
renameUncategorized = false
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.save))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { renameTarget = null; renameUncategorized = false }) {
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||||
|
@Composable
|
||||||
|
private fun EmptyState(
|
||||||
|
icon: ImageVector,
|
||||||
|
title: String,
|
||||||
|
hint: String,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
iconShape: Shape = MaterialShapes.Cookie9Sided.toShape(),
|
||||||
|
actionLabel: String? = null,
|
||||||
|
onActionClick: (() -> Unit)? = null
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(horizontal = 32.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(96.dp)
|
||||||
|
.clip(iconShape)
|
||||||
|
.background(MaterialTheme.colorScheme.primaryContainer),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = icon,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(44.dp),
|
||||||
|
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
Text(
|
||||||
|
text = title,
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.SemiBold
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(6.dp))
|
||||||
|
Text(
|
||||||
|
text = hint,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
textAlign = TextAlign.Center
|
||||||
|
)
|
||||||
|
if (actionLabel != null && onActionClick != null) {
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
FilledTonalButton(onClick = onActionClick) {
|
||||||
|
Text(actionLabel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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,
|
||||||
|
interactionSource: MutableInteractionSource? = null
|
||||||
) {
|
) {
|
||||||
|
var menuExpanded by remember { mutableStateOf(false) }
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.clickable(onClick = onToggle)
|
.combinedClickable(
|
||||||
|
interactionSource = interactionSource,
|
||||||
|
indication = LocalIndication.current,
|
||||||
|
onClick = onToggle
|
||||||
|
)
|
||||||
.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(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.copy(fontWeight = FontWeight.Bold),
|
||||||
fontWeight = FontWeight.Bold,
|
|
||||||
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()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
// 未分组是伪分组(groupId IS NULL),不可删除,仅真实分组显示删除项
|
||||||
|
if (group != null) {
|
||||||
|
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)
|
||||||
@@ -219,12 +495,15 @@ fun GroupHeader(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun TokenCard(
|
fun TokenCard(
|
||||||
token: Token,
|
token: Token,
|
||||||
onIncrement: () -> Unit,
|
onIncrement: () -> Unit,
|
||||||
onEdit: () -> Unit
|
onEdit: () -> Unit,
|
||||||
|
dragModifier: Modifier = Modifier,
|
||||||
|
isDragging: Boolean = false,
|
||||||
|
interactionSource: MutableInteractionSource? = null
|
||||||
) {
|
) {
|
||||||
val warningColor = Color(0xFFFF1744)
|
val warningColor = Color(0xFFFF1744)
|
||||||
val otpPlaceholder = stringResource(R.string.otp_placeholder)
|
val otpPlaceholder = stringResource(R.string.otp_placeholder)
|
||||||
@@ -308,7 +587,15 @@ fun TokenCard(
|
|||||||
Row(
|
Row(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
.then(
|
||||||
|
if (isDragging) Modifier
|
||||||
|
.shadow(elevation = 8.dp)
|
||||||
|
.background(MaterialTheme.colorScheme.surface)
|
||||||
|
else Modifier
|
||||||
|
)
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
|
interactionSource = interactionSource,
|
||||||
|
indication = LocalIndication.current,
|
||||||
onClick = {
|
onClick = {
|
||||||
copyToClipboard(context, currentCode, token.serviceName)
|
copyToClipboard(context, currentCode, token.serviceName)
|
||||||
},
|
},
|
||||||
@@ -317,10 +604,19 @@ 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))
|
||||||
|
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
text = token.serviceName,
|
text = token.serviceName,
|
||||||
@@ -367,12 +663,11 @@ fun TokenCard(
|
|||||||
modifier = Modifier.size(44.dp),
|
modifier = Modifier.size(44.dp),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
CircularProgressIndicator(
|
CircularWavyProgressIndicator(
|
||||||
progress = { progress },
|
progress = { progress },
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.size(44.dp),
|
||||||
color = if (showNextPreview) warningColor else MaterialTheme.colorScheme.primary,
|
color = if (showNextPreview) warningColor else MaterialTheme.colorScheme.primary,
|
||||||
trackColor = MaterialTheme.colorScheme.surfaceVariant,
|
trackColor = MaterialTheme.colorScheme.outlineVariant,
|
||||||
strokeWidth = 3.dp,
|
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "$remainingSeconds",
|
text = "$remainingSeconds",
|
||||||
@@ -397,16 +692,26 @@ fun TokenCard(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun TokenIcon(token: Token) {
|
fun TokenIcon(token: Token) {
|
||||||
val letter = token.issuer.takeIf { it.isNotBlank() }?.firstOrNull()?.uppercaseChar()
|
val letter = token.issuer.takeIf { it.isNotBlank() }?.firstOrNull()?.uppercaseChar()
|
||||||
?: token.serviceName.firstOrNull()?.uppercaseChar()
|
?: token.serviceName.firstOrNull()?.uppercaseChar()
|
||||||
?: '?'
|
?: '?'
|
||||||
|
|
||||||
|
// Deterministic per-token shape: keep 4 understated options, no randomness between recompositions
|
||||||
|
val shapes = listOf(
|
||||||
|
MaterialShapes.Circle,
|
||||||
|
MaterialShapes.Cookie9Sided,
|
||||||
|
MaterialShapes.Pill,
|
||||||
|
MaterialShapes.Sunny,
|
||||||
|
)
|
||||||
|
val shape = shapes[abs(token.issuer.hashCode() * 31 + token.serviceName.hashCode()) % shapes.size]
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(48.dp)
|
.size(48.dp)
|
||||||
.clip(CircleShape)
|
.clip(shape.toShape())
|
||||||
.background(MaterialTheme.colorScheme.primaryContainer),
|
.background(MaterialTheme.colorScheme.primaryContainer),
|
||||||
contentAlignment = Alignment.Center
|
contentAlignment = Alignment.Center
|
||||||
) {
|
) {
|
||||||
@@ -435,3 +740,5 @@ private fun copyToClipboard(context: Context, code: String, label: String) {
|
|||||||
clipboard.setPrimaryClip(clip)
|
clipboard.setPrimaryClip(clip)
|
||||||
Toast.makeText(context, context.getString(R.string.code_copied, label), Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, context.getString(R.string.code_copied, label), Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun groupItemKey(group: Group?): String = "group_${group?.id ?: "unassigned"}"
|
||||||
|
|||||||
@@ -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 {
|
||||||
@@ -71,15 +76,32 @@ class TokensViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val groupMap = groups.associateBy { it.id }
|
val groupMap = groups.associateBy { it.id }
|
||||||
|
|
||||||
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,93 @@ 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()) return
|
||||||
|
if (group == null) {
|
||||||
|
// 未分组重命名 = 物化为真实组;改回默认名视为无操作
|
||||||
|
if (trimmed == getApplication<Application>().getString(R.string.uncategorized)) return
|
||||||
|
materializeUncategorized(trimmed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (trimmed == group.name) return
|
||||||
|
viewModelScope.launch {
|
||||||
|
tokenRepository.updateGroup(group.copy(name = trimmed))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteGroup(group: Group) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
tokenRepository.deleteGroup(group)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 物化未分组(重命名触发):建同名真实分组(已存在同名组则并入),
|
||||||
|
* 全部 groupId 为 NULL 的令牌转入,新分组继承未分组的显示位置,
|
||||||
|
* 伪分组位置重置回默认(列表末尾)。未分组不支持删除,物化仅由重命名进入。
|
||||||
|
*/
|
||||||
|
private fun materializeUncategorized(name: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val hasUncategorized = tokenRepository.getAllTokens().first().any { it.groupId == null }
|
||||||
|
if (!hasUncategorized) return@launch
|
||||||
|
|
||||||
|
val groups = tokenRepository.getAllGroups().first()
|
||||||
|
val existing = groups.firstOrNull { it.name == name }
|
||||||
|
val targetId = existing?.id ?: run {
|
||||||
|
val sorted = groups.sortedBy { it.sortOrder }
|
||||||
|
val newGroup = Group(name = name, sortOrder = 0)
|
||||||
|
val newId = tokenRepository.insertGroup(newGroup)
|
||||||
|
val insertIdx = settingsRepository.uncategorizedOrder.first().coerceIn(0, sorted.size)
|
||||||
|
sorted.toMutableList()
|
||||||
|
.apply { add(insertIdx, newGroup.copy(id = newId)) }
|
||||||
|
.forEachIndexed { index, g -> tokenRepository.updateGroup(g.copy(sortOrder = index)) }
|
||||||
|
newId
|
||||||
|
}
|
||||||
|
tokenRepository.reassignUncategorizedTokens(targetId)
|
||||||
|
settingsRepository.setUncategorizedOrder(Int.MAX_VALUE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 +266,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 +286,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 +310,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 +349,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 +358,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 +377,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 +422,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")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package cn.airnan.a2fair.ui.update
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cn.airnan.a2fair.R
|
||||||
|
import cn.airnan.a2fair.core.update.UpdateInfo
|
||||||
|
import cn.airnan.a2fair.core.update.UpdateState
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun UpdateDialog(
|
||||||
|
state: UpdateState?,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onDownload: (UpdateInfo) -> Unit,
|
||||||
|
onCancelDownload: () -> Unit,
|
||||||
|
onInstall: (UpdateState.ReadyToInstall) -> Unit,
|
||||||
|
onRetryDownload: (UpdateInfo) -> Unit
|
||||||
|
) {
|
||||||
|
when (state) {
|
||||||
|
is UpdateState.Available -> AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.update_available_title, state.info.version)) },
|
||||||
|
text = {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.heightIn(max = 300.dp)
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
) {
|
||||||
|
if (state.info.changelog.isNotBlank()) {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.update_changelog),
|
||||||
|
style = MaterialTheme.typography.titleSmall
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
text = state.info.changelog,
|
||||||
|
style = MaterialTheme.typography.bodySmall
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = { onDownload(state.info) }) {
|
||||||
|
Text(stringResource(R.string.update_download))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text(stringResource(R.string.update_later))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
is UpdateState.Downloading -> AlertDialog(
|
||||||
|
onDismissRequest = onCancelDownload,
|
||||||
|
title = { Text(stringResource(R.string.update_downloading)) },
|
||||||
|
text = {
|
||||||
|
Column {
|
||||||
|
if (state.progress >= 0) {
|
||||||
|
LinearProgressIndicator(
|
||||||
|
progress = { state.progress / 100f },
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.update_download_progress, state.progress),
|
||||||
|
style = MaterialTheme.typography.bodySmall
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onCancelDownload) {
|
||||||
|
Text(stringResource(R.string.update_cancel_download))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
is UpdateState.ReadyToInstall -> AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.update_ready_title)) },
|
||||||
|
text = { Text(stringResource(R.string.update_ready_message)) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = { onInstall(state) }) {
|
||||||
|
Text(stringResource(R.string.update_install))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text(stringResource(R.string.update_later))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
is UpdateState.DownloadFailed -> AlertDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
title = { Text(stringResource(R.string.update_download_failed_title)) },
|
||||||
|
text = { Text(stringResource(R.string.update_download_failed, state.message)) },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = { onRetryDownload(state.info) }) {
|
||||||
|
Text(stringResource(R.string.update_retry))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = onDismiss) {
|
||||||
|
Text(stringResource(R.string.cancel))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,10 @@
|
|||||||
<string name="edit">编辑</string>
|
<string name="edit">编辑</string>
|
||||||
<string name="delete">删除</string>
|
<string name="delete">删除</string>
|
||||||
<string name="code_copied">已复制 %s 的验证码</string>
|
<string name="code_copied">已复制 %s 的验证码</string>
|
||||||
|
<string name="empty_tokens_title">还没有令牌</string>
|
||||||
|
<string name="empty_tokens_hint">扫描二维码或手动输入,添加你的第一个两步验证令牌。</string>
|
||||||
|
<string name="empty_search_title">未找到匹配的令牌</string>
|
||||||
|
<string name="empty_search_hint">换个关键词试试</string>
|
||||||
|
|
||||||
<!-- Add Token -->
|
<!-- Add Token -->
|
||||||
<string name="scan_qr_code">扫描二维码</string>
|
<string name="scan_qr_code">扫描二维码</string>
|
||||||
@@ -27,6 +31,21 @@
|
|||||||
<string name="enter_details_manually">手动输入详情</string>
|
<string name="enter_details_manually">手动输入详情</string>
|
||||||
<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="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>
|
||||||
@@ -63,6 +82,8 @@
|
|||||||
<string name="backup_restore">备份与恢复</string>
|
<string name="backup_restore">备份与恢复</string>
|
||||||
<string name="theme">主题</string>
|
<string name="theme">主题</string>
|
||||||
<string name="about">关于</string>
|
<string name="about">关于</string>
|
||||||
|
<string name="author_homepage">作者主页</string>
|
||||||
|
<string name="author_handle">@码农阿楠</string>
|
||||||
|
|
||||||
<!-- Security Settings -->
|
<!-- Security Settings -->
|
||||||
<string name="app_lock_pin">应用锁 PIN 码</string>
|
<string name="app_lock_pin">应用锁 PIN 码</string>
|
||||||
@@ -143,12 +164,33 @@
|
|||||||
<string name="dynamic_color_desc">使用壁纸提取的颜色(Android 12+)</string>
|
<string name="dynamic_color_desc">使用壁纸提取的颜色(Android 12+)</string>
|
||||||
<string name="seed_color">主题色</string>
|
<string name="seed_color">主题色</string>
|
||||||
|
|
||||||
|
<!-- Update -->
|
||||||
|
<string name="check_update">检查更新</string>
|
||||||
|
<string name="check_update_desc">从 Gitea Release 检查并安装新版本</string>
|
||||||
|
<string name="update_checking">正在检查更新…</string>
|
||||||
|
<string name="update_up_to_date">当前已是最新版本</string>
|
||||||
|
<string name="update_available_title">发现新版本 v%s</string>
|
||||||
|
<string name="update_changelog">更新内容</string>
|
||||||
|
<string name="update_download">下载更新</string>
|
||||||
|
<string name="update_later">以后再说</string>
|
||||||
|
<string name="update_downloading">正在下载更新…</string>
|
||||||
|
<string name="update_download_progress">正在下载 %1$d%%</string>
|
||||||
|
<string name="update_cancel_download">取消下载</string>
|
||||||
|
<string name="update_download_failed_title">下载失败</string>
|
||||||
|
<string name="update_download_failed">下载失败:%s</string>
|
||||||
|
<string name="update_retry">重试</string>
|
||||||
|
<string name="update_ready_title">安装包下载完成</string>
|
||||||
|
<string name="update_ready_message">安装包已下载,是否立即安装?</string>
|
||||||
|
<string name="update_install">立即安装</string>
|
||||||
|
<string name="update_check_failed">检查更新失败:%s</string>
|
||||||
|
|
||||||
<!-- About -->
|
<!-- About -->
|
||||||
<string name="back">返回</string>
|
<string name="back">返回</string>
|
||||||
<string name="app_icon">应用图标</string>
|
<string name="app_icon">应用图标</string>
|
||||||
<string name="version_format">版本 %s</string>
|
<string name="version_format">版本 %s</string>
|
||||||
<string name="source_code">源代码</string>
|
<string name="source_code">源代码</string>
|
||||||
<string name="view_on_github">在 GitHub 上查看</string>
|
<string name="view_on_gitea">在作者的 Gitea 上查看</string>
|
||||||
|
<string name="licenses_desc">本应用使用了以下开源项目。</string>
|
||||||
<string name="open_source_licenses">开源许可</string>
|
<string name="open_source_licenses">开源许可</string>
|
||||||
<string name="copyright">© 2026 2FAir</string>
|
<string name="copyright">© 2026 2FAir</string>
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,10 @@
|
|||||||
<string name="edit">編輯</string>
|
<string name="edit">編輯</string>
|
||||||
<string name="delete">刪除</string>
|
<string name="delete">刪除</string>
|
||||||
<string name="code_copied">已複製 %s 的驗證碼</string>
|
<string name="code_copied">已複製 %s 的驗證碼</string>
|
||||||
|
<string name="empty_tokens_title">還沒有權杖</string>
|
||||||
|
<string name="empty_tokens_hint">掃描 QR 碼或手動輸入,新增你的第一個兩步驟驗證權杖。</string>
|
||||||
|
<string name="empty_search_title">未找到符合的權杖</string>
|
||||||
|
<string name="empty_search_hint">換個關鍵字試試</string>
|
||||||
|
|
||||||
<!-- Add Token -->
|
<!-- Add Token -->
|
||||||
<string name="scan_qr_code">掃描 QR 碼</string>
|
<string name="scan_qr_code">掃描 QR 碼</string>
|
||||||
@@ -27,6 +31,21 @@
|
|||||||
<string name="enter_details_manually">手動輸入詳情</string>
|
<string name="enter_details_manually">手動輸入詳情</string>
|
||||||
<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="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>
|
||||||
@@ -143,12 +162,33 @@
|
|||||||
<string name="dynamic_color_desc">使用桌布提取的顏色(Android 12+)</string>
|
<string name="dynamic_color_desc">使用桌布提取的顏色(Android 12+)</string>
|
||||||
<string name="seed_color">主題色</string>
|
<string name="seed_color">主題色</string>
|
||||||
|
|
||||||
|
<!-- Update -->
|
||||||
|
<string name="check_update">檢查更新</string>
|
||||||
|
<string name="check_update_desc">從 Gitea Release 檢查並安裝新版本</string>
|
||||||
|
<string name="update_checking">正在檢查更新…</string>
|
||||||
|
<string name="update_up_to_date">目前已是最新版本</string>
|
||||||
|
<string name="update_available_title">發現新版本 v%s</string>
|
||||||
|
<string name="update_changelog">更新內容</string>
|
||||||
|
<string name="update_download">下載更新</string>
|
||||||
|
<string name="update_later">稍後再說</string>
|
||||||
|
<string name="update_downloading">正在下載更新…</string>
|
||||||
|
<string name="update_download_progress">正在下載 %1$d%%</string>
|
||||||
|
<string name="update_cancel_download">取消下載</string>
|
||||||
|
<string name="update_download_failed_title">下載失敗</string>
|
||||||
|
<string name="update_download_failed">下載失敗:%s</string>
|
||||||
|
<string name="update_retry">重試</string>
|
||||||
|
<string name="update_ready_title">安裝套件下載完成</string>
|
||||||
|
<string name="update_ready_message">安裝套件已下載,是否立即安裝?</string>
|
||||||
|
<string name="update_install">立即安裝</string>
|
||||||
|
<string name="update_check_failed">檢查更新失敗:%s</string>
|
||||||
|
|
||||||
<!-- About -->
|
<!-- About -->
|
||||||
<string name="back">返回</string>
|
<string name="back">返回</string>
|
||||||
<string name="app_icon">應用程式圖示</string>
|
<string name="app_icon">應用程式圖示</string>
|
||||||
<string name="version_format">版本 %s</string>
|
<string name="version_format">版本 %s</string>
|
||||||
<string name="source_code">原始碼</string>
|
<string name="source_code">原始碼</string>
|
||||||
<string name="view_on_github">在 GitHub 上檢視</string>
|
<string name="view_on_gitea">在作者的 Gitea 上檢視</string>
|
||||||
|
<string name="licenses_desc">本應用程式使用了以下開放原始碼專案。</string>
|
||||||
<string name="open_source_licenses">開放原始碼授權</string>
|
<string name="open_source_licenses">開放原始碼授權</string>
|
||||||
<string name="copyright">© 2026 2FAir</string>
|
<string name="copyright">© 2026 2FAir</string>
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,10 @@
|
|||||||
<string name="edit">Edit</string>
|
<string name="edit">Edit</string>
|
||||||
<string name="delete">Delete</string>
|
<string name="delete">Delete</string>
|
||||||
<string name="code_copied">Code for %s copied</string>
|
<string name="code_copied">Code for %s copied</string>
|
||||||
|
<string name="empty_tokens_title">No tokens yet</string>
|
||||||
|
<string name="empty_tokens_hint">Scan a QR code or enter one manually to add your first 2FA token.</string>
|
||||||
|
<string name="empty_search_title">No matching tokens</string>
|
||||||
|
<string name="empty_search_hint">Try a different keyword</string>
|
||||||
|
|
||||||
<!-- Add Token -->
|
<!-- Add Token -->
|
||||||
<string name="scan_qr_code">Scan QR Code</string>
|
<string name="scan_qr_code">Scan QR Code</string>
|
||||||
@@ -27,6 +31,21 @@
|
|||||||
<string name="enter_details_manually">Enter Details Manually</string>
|
<string name="enter_details_manually">Enter Details Manually</string>
|
||||||
<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="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>
|
||||||
@@ -63,6 +82,8 @@
|
|||||||
<string name="backup_restore">Backup & Restore</string>
|
<string name="backup_restore">Backup & Restore</string>
|
||||||
<string name="theme">Theme</string>
|
<string name="theme">Theme</string>
|
||||||
<string name="about">About</string>
|
<string name="about">About</string>
|
||||||
|
<string name="author_homepage">Author homepage</string>
|
||||||
|
<string name="author_handle">@Airnan</string>
|
||||||
|
|
||||||
<!-- Security Settings -->
|
<!-- Security Settings -->
|
||||||
<string name="app_lock_pin">App Lock PIN</string>
|
<string name="app_lock_pin">App Lock PIN</string>
|
||||||
@@ -143,12 +164,33 @@
|
|||||||
<string name="dynamic_color_desc">Use colors extracted from wallpaper (Android 12+)</string>
|
<string name="dynamic_color_desc">Use colors extracted from wallpaper (Android 12+)</string>
|
||||||
<string name="seed_color">Seed Color</string>
|
<string name="seed_color">Seed Color</string>
|
||||||
|
|
||||||
|
<!-- Update -->
|
||||||
|
<string name="check_update">Check for updates</string>
|
||||||
|
<string name="check_update_desc">Check and install new versions from Gitea releases</string>
|
||||||
|
<string name="update_checking">Checking for updates…</string>
|
||||||
|
<string name="update_up_to_date">You are on the latest version</string>
|
||||||
|
<string name="update_available_title">Update available: v%s</string>
|
||||||
|
<string name="update_changelog">What\'s new</string>
|
||||||
|
<string name="update_download">Download update</string>
|
||||||
|
<string name="update_later">Later</string>
|
||||||
|
<string name="update_downloading">Downloading update…</string>
|
||||||
|
<string name="update_download_progress">Downloading %1$d%%</string>
|
||||||
|
<string name="update_cancel_download">Cancel download</string>
|
||||||
|
<string name="update_download_failed_title">Download failed</string>
|
||||||
|
<string name="update_download_failed">Download failed: %s</string>
|
||||||
|
<string name="update_retry">Retry</string>
|
||||||
|
<string name="update_ready_title">Update downloaded</string>
|
||||||
|
<string name="update_ready_message">The update package is ready. Install it now?</string>
|
||||||
|
<string name="update_install">Install now</string>
|
||||||
|
<string name="update_check_failed">Update check failed: %s</string>
|
||||||
|
|
||||||
<!-- About -->
|
<!-- About -->
|
||||||
<string name="back">Back</string>
|
<string name="back">Back</string>
|
||||||
<string name="app_icon">App Icon</string>
|
<string name="app_icon">App Icon</string>
|
||||||
<string name="version_format">Version %s</string>
|
<string name="version_format">Version %s</string>
|
||||||
<string name="source_code">Source Code</string>
|
<string name="source_code">Source Code</string>
|
||||||
<string name="view_on_github">View on GitHub</string>
|
<string name="view_on_gitea">View on author\'s Gitea</string>
|
||||||
|
<string name="licenses_desc">This app is built with the help of the following open source projects.</string>
|
||||||
<string name="open_source_licenses">Open Source Licenses</string>
|
<string name="open_source_licenses">Open Source Licenses</string>
|
||||||
<string name="copyright">© 2026 2FAir</string>
|
<string name="copyright">© 2026 2FAir</string>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<!-- 应用内更新下载的安装包目录 -->
|
||||||
|
<files-path name="updates" path="updates/" />
|
||||||
|
</paths>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- 仅放行本机回环明文流量,供 adb reverse + 本地 mock server 联调更新流程;正式更新走 https -->
|
||||||
|
<network-security-config>
|
||||||
|
<domain-config cleartextTrafficPermitted="true">
|
||||||
|
<domain includeSubdomains="false">localhost</domain>
|
||||||
|
<domain includeSubdomains="false">127.0.0.1</domain>
|
||||||
|
</domain-config>
|
||||||
|
</network-security-config>
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
[versions]
|
[versions]
|
||||||
agp = "9.2.1"
|
agp = "9.2.1"
|
||||||
|
reorderable = "3.1.0"
|
||||||
coreKtx = "1.15.0"
|
coreKtx = "1.15.0"
|
||||||
junit = "4.13.2"
|
junit = "4.13.2"
|
||||||
junitVersion = "1.3.0"
|
junitVersion = "1.3.0"
|
||||||
@@ -13,7 +14,6 @@ navigationCompose = "2.8.5"
|
|||||||
room = "2.6.1"
|
room = "2.6.1"
|
||||||
cameraX = "1.4.0"
|
cameraX = "1.4.0"
|
||||||
zxing = "3.5.3"
|
zxing = "3.5.3"
|
||||||
mlKitBarcode = "17.3.0"
|
|
||||||
dataStore = "1.1.2"
|
dataStore = "1.1.2"
|
||||||
biometric = "1.1.0"
|
biometric = "1.1.0"
|
||||||
securityCrypto = "1.1.0-alpha06"
|
securityCrypto = "1.1.0-alpha06"
|
||||||
@@ -36,7 +36,8 @@ androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-toolin
|
|||||||
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||||
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
||||||
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
|
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
|
||||||
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version = "1.5.0-beta01" }
|
||||||
|
reorderable = { module = "sh.calvin.reorderable:reorderable", version.ref = "reorderable" }
|
||||||
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
||||||
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
|
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
|
||||||
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
|
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
|
||||||
@@ -46,7 +47,6 @@ androidx-camera-camera2 = { group = "androidx.camera", name = "camera-camera2",
|
|||||||
androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "cameraX" }
|
androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "cameraX" }
|
||||||
androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "cameraX" }
|
androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "cameraX" }
|
||||||
zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" }
|
zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" }
|
||||||
mlkit-barcode-scanning = { group = "com.google.mlkit", name = "barcode-scanning", version.ref = "mlKitBarcode" }
|
|
||||||
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "dataStore" }
|
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "dataStore" }
|
||||||
androidx-biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" }
|
androidx-biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" }
|
||||||
androidx-security-crypto = { group = "androidx.security", name = "security-crypto-ktx", version.ref = "securityCrypto" }
|
androidx-security-crypto = { group = "androidx.security", name = "security-crypto-ktx", version.ref = "securityCrypto" }
|
||||||
|
|||||||
Reference in New Issue
Block a user