Compare commits

..
3 Commits
8 changed files with 181 additions and 66 deletions
+14 -1
View File
@@ -27,12 +27,26 @@ android {
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"
) )
} }
} }
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
@@ -74,7 +88,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)
+14 -6
View File
@@ -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 * {
@@ -43,9 +48,9 @@
# 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.** { *; }
# ML Kit references optional google-http-client / joda-time paths that are # Optional compile-time-only references in Tink (androidx.security-crypto):
# absent from the Android artifact; the code paths are never exercised. # google-http-client / joda-time paths and JSR-305 annotations that are absent
# Generated by AGP in app/build/outputs/mapping/release/missing_rules.txt # 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.GenericUrl
-dontwarn com.google.api.client.http.HttpHeaders -dontwarn com.google.api.client.http.HttpHeaders
-dontwarn com.google.api.client.http.HttpRequest -dontwarn com.google.api.client.http.HttpRequest
@@ -54,4 +59,7 @@
-dontwarn com.google.api.client.http.HttpTransport -dontwarn com.google.api.client.http.HttpTransport
-dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder -dontwarn com.google.api.client.http.javanet.NetHttpTransport$Builder
-dontwarn com.google.api.client.http.javanet.NetHttpTransport -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 -dontwarn org.joda.time.Instant
@@ -69,16 +69,6 @@ private val licenseGroups = listOf(
url = "https://github.com/google/gson" url = "https://github.com/google/gson"
) )
) )
),
LicenseGroup(
license = "ML Kit Terms of Service",
licenseUrl = "https://developers.google.com/ml-kit/terms",
libraries = listOf(
LibraryLicense(
name = "ML Kit Barcode Scanning",
url = "https://developers.google.com/ml-kit"
)
)
) )
) )
@@ -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
@@ -36,10 +40,17 @@ 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)
@@ -59,34 +70,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)
val scanner = BarcodeScanning.getClient()
scanner.process(image)
.addOnSuccessListener { barcodes ->
val barcode = barcodes.firstOrNull { it.valueType == Barcode.TYPE_WIFI || it.rawValue?.startsWith("otpauth://") == true }
?: barcodes.firstOrNull()
val rawValue = barcode?.rawValue
if (rawValue != null && rawValue.startsWith("otpauth://")) { if (rawValue != null && rawValue.startsWith("otpauth://")) {
viewModel.addTokenFromUri(rawValue) viewModel.addTokenFromUri(rawValue)
} else { } else {
// Handle error: no valid QR code found // 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,6 +160,15 @@ fun AddTokenBottomSheet(
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) )
if (!hasCameraPermission) {
Text(
text = stringResource(R.string.camera_permission_hint),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.align(Alignment.Center).padding(16.dp)
)
}
if (showScanningText) { if (showScanningText) {
Surface( Surface(
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
@@ -171,8 +186,9 @@ fun AddTokenBottomSheet(
} }
} }
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 +271,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 {
// Ignored
}
.addOnCompleteListener {
imageProxy.close()
} }
} else { } else {
null
}
} catch (e: Exception) {
null
} finally {
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
} }
} }
@@ -31,6 +31,7 @@
<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="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>
@@ -31,6 +31,7 @@
<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="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>
+1
View File
@@ -31,6 +31,7 @@
<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="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>
-2
View File
@@ -13,7 +13,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"
@@ -46,7 +45,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" }