Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Revert all auth plugin changes to match main

Amrithesh Kakkoth Ented07147e174fd
diff --git a/mobile/apps/auth/plugins/qr/android/build.gradle b/mobile/apps/auth/plugins/qr/android/build.gradle
index 77ca462dde..2e8cdb232a 100644
--- a/mobile/apps/auth/plugins/qr/android/build.gradle
+++ b/mobile/apps/auth/plugins/qr/android/build.gradle
@@ -50,7 +50,6 @@ android {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
implementation 'com.google.zxing:core:3.5.1'
- implementation 'androidx.exifinterface:exifinterface:1.3.7'
}
testOptions {
diff --git a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
index 7386f80649..44f97fa34a 100644
--- a/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
+++ b/mobile/apps/auth/plugins/qr/android/src/main/kotlin/io/ente/auth/ente_qr/EnteQrPlugin.kt
@@ -2,8 +2,6 @@ package io.ente.auth.ente_qr
import android.graphics.Bitmap
import android.graphics.BitmapFactory
-import android.graphics.Matrix
-import androidx.exifinterface.media.ExifInterface
import androidx.annotation.NonNull
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
@@ -12,7 +10,6 @@ import com.google.zxing.MultiFormatReader
import com.google.zxing.NotFoundException
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.Result as ZXingResult
-import com.google.zxing.common.GlobalHistogramBinarizer
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.multi.GenericMultipleBarcodeReader
import io.flutter.embedding.engine.plugins.FlutterPlugin
@@ -87,238 +84,192 @@ class EnteQrPlugin: FlutterPlugin, MethodCallHandler {
}
}
- /**
- * Load a bitmap and apply EXIF orientation so the image is upright
- * before QR detection.
- */
- private fun loadBitmapWithOrientation(imagePath: String): Bitmap? {
- val bitmap = BitmapFactory.decodeFile(imagePath) ?: return null
- return try {
- val exif = ExifInterface(imagePath)
- val orientation = exif.getAttributeInt(
- ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
- )
- val matrix = Matrix()
- when (orientation) {
- ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
- ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
- ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
- ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.preScale(-1f, 1f)
- ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.preScale(1f, -1f)
- else -> return bitmap
- }
- val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
- if (rotated !== bitmap) bitmap.recycle()
- rotated
- } catch (_: Exception) {
- bitmap
- }
- }
-
- private fun createDecodeHints(): HashMap<DecodeHintType, Any> {
- val hints = HashMap<DecodeHintType, Any>()
- hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)
- hints[DecodeHintType.TRY_HARDER] = true
- hints[DecodeHintType.ALSO_INVERTED] = true
- return hints
- }
-
- private fun getPixels(bitmap: Bitmap): IntArray {
- val width = bitmap.width
- val height = bitmap.height
- val pixels = IntArray(width * height)
- bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
- return pixels
- }
-
- // ── ZXing decode strategies ───────────────────────────────────────
- //
- // 1. HybridBinarizer at original resolution (fast, handles most cases)
- // 2. GlobalHistogramBinarizer at original resolution (uneven lighting)
- // 3. HybridBinarizer at half resolution (moirΓ©, noise)
-
- private fun zxingDecode(pixels: IntArray, width: Int, height: Int, hints: HashMap<DecodeHintType, Any>): ZXingResult? {
- val source = RGBLuminanceSource(width, height, pixels)
- val reader = MultiFormatReader()
- reader.setHints(hints)
-
- // Strategy 1: HybridBinarizer
- try {
- return reader.decode(BinaryBitmap(HybridBinarizer(source)))
- } catch (_: NotFoundException) {}
-
- // Strategy 2: GlobalHistogramBinarizer
- try {
- val source2 = RGBLuminanceSource(width, height, pixels)
- return reader.decode(BinaryBitmap(GlobalHistogramBinarizer(source2)))
- } catch (_: NotFoundException) {}
-
- return null
- }
-
- private fun zxingDecodeMultiple(pixels: IntArray, width: Int, height: Int, hints: HashMap<DecodeHintType, Any>): Array<ZXingResult>? {
- val source = RGBLuminanceSource(width, height, pixels)
- val reader = MultiFormatReader()
- reader.setHints(hints)
- val multiReader = GenericMultipleBarcodeReader(reader)
-
- // Strategy 1: HybridBinarizer
- try {
- return multiReader.decodeMultiple(BinaryBitmap(HybridBinarizer(source)), hints)
- } catch (_: NotFoundException) {}
-
- // Strategy 2: GlobalHistogramBinarizer
- try {
- val source2 = RGBLuminanceSource(width, height, pixels)
- return multiReader.decodeMultiple(BinaryBitmap(GlobalHistogramBinarizer(source2)), hints)
- } catch (_: NotFoundException) {}
-
- return null
- }
-
- // ── Main scan methods ─────────────────────────────────────────────
-
private fun scanQrCode(imagePath: String): Map<String, Any> {
try {
val file = File(imagePath)
if (!file.exists()) {
- return mapOf("success" to false, "error" to "Image file not found: $imagePath")
+ return mapOf(
+ "success" to false,
+ "error" to "Image file not found: $imagePath"
+ )
}
- val bitmap = loadBitmapWithOrientation(imagePath)
- ?: return mapOf("success" to false, "error" to "Unable to decode image file")
-
- try {
- val hints = createDecodeHints()
-
- // Try at original resolution
- val pixels = getPixels(bitmap)
- val result = zxingDecode(pixels, bitmap.width, bitmap.height, hints)
- if (result != null) {
- return mapOf("success" to true, "content" to result.text)
- }
+ var bitmap = BitmapFactory.decodeFile(imagePath)
+ if (bitmap == null) {
+ return mapOf(
+ "success" to false,
+ "error" to "Unable to decode image file"
+ )
+ }
- // Fallback: half resolution (helps with moirΓ©/noise)
- val halfW = bitmap.width / 2
- val halfH = bitmap.height / 2
- if (halfW > 0 && halfH > 0) {
- val halfBitmap = Bitmap.createScaledBitmap(bitmap, halfW, halfH, true)
- try {
- val halfPixels = getPixels(halfBitmap)
- val halfResult = zxingDecode(halfPixels, halfW, halfH, hints)
- if (halfResult != null) {
- return mapOf("success" to true, "content" to halfResult.text)
- }
- } finally {
- halfBitmap.recycle()
+ // Try multiple times with different image sizes like Aegis does
+ for (i in 0..2) {
+ if (i != 0) {
+ // Resize bitmap for subsequent attempts
+ val newWidth = bitmap.width / (i * 2)
+ val newHeight = bitmap.height / (i * 2)
+ if (newWidth > 0 && newHeight > 0) {
+ bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
}
}
- return mapOf("success" to false, "error" to "No QR code found in image")
- } finally {
- bitmap.recycle()
+ try {
+ val width = bitmap.width
+ val height = bitmap.height
+ val pixels = IntArray(width * height)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+
+ val source = RGBLuminanceSource(width, height, pixels)
+ val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
+
+ val reader = MultiFormatReader()
+ val hints = HashMap<DecodeHintType, Any>()
+ hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)
+ hints[DecodeHintType.TRY_HARDER] = true
+ hints[DecodeHintType.ALSO_INVERTED] = true
+ reader.setHints(hints)
+
+ val qrResult: ZXingResult = reader.decode(binaryBitmap)
+
+ return mapOf(
+ "success" to true,
+ "content" to qrResult.text
+ )
+ } catch (e: NotFoundException) {
+ // Continue to next iteration
+ continue
+ }
}
+
+ return mapOf(
+ "success" to false,
+ "error" to "No QR code found in image"
+ )
} catch (e: Exception) {
- return mapOf("success" to false, "error" to "Error scanning QR code: ${e.message}")
+ return mapOf(
+ "success" to false,
+ "error" to "Error scanning QR code: ${e.message}"
+ )
}
}
private fun scanAllQrCodes(imagePath: String): Map<String, Any> {
val file = File(imagePath)
if (!file.exists()) {
- return mapOf("success" to false, "error" to "Image file not found: $imagePath")
+ return mapOf(
+ "success" to false,
+ "error" to "Image file not found: $imagePath"
+ )
}
- val bitmap = loadBitmapWithOrientation(imagePath)
- ?: return mapOf("success" to false, "error" to "Unable to decode image file")
+ val origBitmap = BitmapFactory.decodeFile(imagePath)
+ ?: return mapOf(
+ "success" to false,
+ "error" to "Unable to decode image file"
+ )
+ var bitmap = origBitmap
try {
- val imgWidth = bitmap.width.toDouble()
- val imgHeight = bitmap.height.toDouble()
- val hints = createDecodeHints()
-
- // Try at original resolution
- val pixels = getPixels(bitmap)
- val results = zxingDecodeMultiple(pixels, bitmap.width, bitmap.height, hints)
- if (results != null && results.isNotEmpty()) {
- val detections = buildDetections(results, imgWidth, imgHeight, 1.0)
- if (detections.isNotEmpty()) {
- return mapOf("success" to true, "detections" to detections)
+ val origWidth = origBitmap.width.toDouble()
+ val origHeight = origBitmap.height.toDouble()
+
+ for (i in 0..2) {
+ if (i != 0) {
+ val newWidth = origBitmap.width / (i * 2)
+ val newHeight = origBitmap.height / (i * 2)
+ if (newWidth > 0 && newHeight > 0) {
+ if (bitmap !== origBitmap) bitmap.recycle()
+ bitmap = Bitmap.createScaledBitmap(origBitmap, newWidth, newHeight, true)
+ }
}
- }
- // Fallback: half resolution
- val halfW = bitmap.width / 2
- val halfH = bitmap.height / 2
- if (halfW > 0 && halfH > 0) {
- val halfBitmap = Bitmap.createScaledBitmap(bitmap, halfW, halfH, true)
try {
- val halfPixels = getPixels(halfBitmap)
- val halfResults = zxingDecodeMultiple(halfPixels, halfW, halfH, hints)
- if (halfResults != null && halfResults.isNotEmpty()) {
- val detections = buildDetections(halfResults, imgWidth, imgHeight, 2.0)
- if (detections.isNotEmpty()) {
- return mapOf("success" to true, "detections" to detections)
+ val width = bitmap.width
+ val height = bitmap.height
+ val pixels = IntArray(width * height)
+ bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
+
+ val source = RGBLuminanceSource(width, height, pixels)
+ val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
+
+ val reader = MultiFormatReader()
+ val hints = HashMap<DecodeHintType, Any>()
+ hints[DecodeHintType.POSSIBLE_FORMATS] = listOf(BarcodeFormat.QR_CODE)
+ hints[DecodeHintType.TRY_HARDER] = true
+ hints[DecodeHintType.ALSO_INVERTED] = true
+ reader.setHints(hints)
+
+ val multiReader = GenericMultipleBarcodeReader(reader)
+ val results: Array<ZXingResult> = multiReader.decodeMultiple(binaryBitmap, hints)
+
+ val detections = mutableListOf<Map<String, Any>>()
+ val scaleX = if (i == 0) 1.0 else (i * 2).toDouble()
+ val scaleY = if (i == 0) 1.0 else (i * 2).toDouble()
+
+ for (qrResult in results) {
+ val points = qrResult.resultPoints
+ if (points == null || points.isEmpty()) continue
+
+ var minX = Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE
+ var maxY = -Float.MAX_VALUE
+
+ for (point in points) {
+ if (point == null) continue
+ val px = point.x * scaleX.toFloat()
+ val py = point.y * scaleY.toFloat()
+ if (px < minX) minX = px
+ if (py < minY) minY = py
+ if (px > maxX) maxX = px
+ if (py > maxY) maxY = py
}
+
+ // Add padding around finder patterns (they mark corners, not edges)
+ val padX = (maxX - minX) * 0.15f
+ val padY = (maxY - minY) * 0.15f
+ minX = (minX - padX).coerceAtLeast(0f)
+ minY = (minY - padY).coerceAtLeast(0f)
+ maxX = (maxX + padX).coerceAtMost(origWidth.toFloat())
+ maxY = (maxY + padY).coerceAtMost(origHeight.toFloat())
+
+ detections.add(mapOf(
+ "content" to qrResult.text,
+ "x" to (minX / origWidth),
+ "y" to (minY / origHeight),
+ "width" to ((maxX - minX) / origWidth),
+ "height" to ((maxY - minY) / origHeight),
+ ))
+ }
+
+ if (detections.isNotEmpty()) {
+ if (bitmap !== origBitmap) bitmap.recycle()
+ origBitmap.recycle()
+ return mapOf(
+ "success" to true,
+ "detections" to detections
+ )
}
- } finally {
- halfBitmap.recycle()
+ } catch (e: NotFoundException) {
+ continue
}
}
- return mapOf("success" to false, "error" to "No QR code found in image")
- } catch (e: Exception) {
- return mapOf("success" to false, "error" to "Error scanning QR codes: ${e.message}")
- } finally {
- bitmap.recycle()
- }
- }
-
- private fun buildDetections(
- results: Array<ZXingResult>,
- imgWidth: Double,
- imgHeight: Double,
- scale: Double,
- ): List<Map<String, Any>> {
- val detections = mutableListOf<Map<String, Any>>()
-
- for (qrResult in results) {
- val points = qrResult.resultPoints
- if (points == null || points.isEmpty()) continue
-
- var minX = Float.MAX_VALUE
- var minY = Float.MAX_VALUE
- var maxX = -Float.MAX_VALUE
- var maxY = -Float.MAX_VALUE
-
- for (point in points) {
- if (point == null) continue
- val px = (point.x * scale).toFloat()
- val py = (point.y * scale).toFloat()
- if (px < minX) minX = px
- if (py < minY) minY = py
- if (px > maxX) maxX = px
- if (py > maxY) maxY = py
- }
+ if (bitmap !== origBitmap) bitmap.recycle()
+ origBitmap.recycle()
- // Add padding around finder patterns
- val padX = (maxX - minX) * 0.15f
- val padY = (maxY - minY) * 0.15f
- minX = (minX - padX).coerceAtLeast(0f)
- minY = (minY - padY).coerceAtLeast(0f)
- maxX = (maxX + padX).coerceAtMost(imgWidth.toFloat())
- maxY = (maxY + padY).coerceAtMost(imgHeight.toFloat())
-
- detections.add(mapOf(
- "content" to qrResult.text,
- "x" to (minX / imgWidth),
- "y" to (minY / imgHeight),
- "width" to ((maxX - minX) / imgWidth),
- "height" to ((maxY - minY) / imgHeight),
- ))
+ return mapOf(
+ "success" to false,
+ "error" to "No QR code found in image"
+ )
+ } catch (e: Exception) {
+ if (bitmap !== origBitmap) bitmap.recycle()
+ origBitmap.recycle()
+ return mapOf(
+ "success" to false,
+ "error" to "Error scanning QR codes: ${e.message}"
+ )
}
-
- return detections
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
diff --git a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
index b198b25719..f7c656fffd 100644
--- a/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
+++ b/mobile/apps/auth/plugins/qr/ios/Classes/EnteQrPlugin.swift
@@ -1,6 +1,5 @@
import Flutter
import UIKit
-import Vision
public class EnteQrPlugin: NSObject, FlutterPlugin {
private static let detectionQueue = DispatchQueue(label: "io.ente.qr.detection", qos: .userInitiated)
@@ -41,25 +40,10 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
result(FlutterMethodNotImplemented)
}
}
-
- private func detectBarcodes(in cgImage: CGImage) -> [VNBarcodeObservation] {
- let request = VNDetectBarcodesRequest()
- request.symbologies = [.qr]
-
- let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
- do {
- try handler.perform([request])
- } catch {
- return []
- }
-
- return request.results ?? []
- }
-
+
private func scanQrCode(from imagePath: String, result: @escaping FlutterResult) {
EnteQrPlugin.detectionQueue.async {
- guard let image = UIImage(contentsOfFile: imagePath),
- let cgImage = image.cgImage else {
+ guard let image = UIImage(contentsOfFile: imagePath) else {
DispatchQueue.main.async {
result([
"success": false,
@@ -69,14 +53,39 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
return
}
- let observations = self.detectBarcodes(in: cgImage)
+ guard let cgImage = image.cgImage else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to get CGImage from UIImage"
+ ])
+ }
+ return
+ }
+
+ let detector = CIDetector(ofType: CIDetectorTypeQRCode,
+ context: nil,
+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
- if let obs = observations.first,
- let payload = obs.payloadStringValue {
+ guard let qrDetector = detector else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to create QR code detector"
+ ])
+ }
+ return
+ }
+
+ let ciImage = CIImage(cgImage: cgImage)
+ let features = qrDetector.features(in: ciImage)
+
+ if let qrFeature = features.first as? CIQRCodeFeature,
+ let messageString = qrFeature.messageString {
DispatchQueue.main.async {
result([
"success": true,
- "content": payload
+ "content": messageString
])
}
} else {
@@ -92,8 +101,7 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
private func scanAllQrCodes(from imagePath: String, result: @escaping FlutterResult) {
EnteQrPlugin.detectionQueue.async {
- guard let image = UIImage(contentsOfFile: imagePath),
- let cgImage = image.cgImage else {
+ guard let image = UIImage(contentsOfFile: imagePath) else {
DispatchQueue.main.async {
result([
"success": false,
@@ -103,22 +111,72 @@ public class EnteQrPlugin: NSObject, FlutterPlugin {
return
}
- let observations = self.detectBarcodes(in: cgImage)
+ guard let cgImage = image.cgImage else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to get CGImage from UIImage"
+ ])
+ }
+ return
+ }
+
+ let detector = CIDetector(ofType: CIDetectorTypeQRCode,
+ context: nil,
+ options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
+
+ guard let qrDetector = detector else {
+ DispatchQueue.main.async {
+ result([
+ "success": false,
+ "error": "Unable to create QR code detector"
+ ])
+ }
+ return
+ }
+
+ let ciImage = CIImage(cgImage: cgImage)
+ let features = qrDetector.features(in: ciImage)
+
+ let imageWidth = CGFloat(cgImage.width)
+ let imageHeight = CGFloat(cgImage.height)
var detections: [[String: Any]] = []
- for obs in observations {
- guard let payload = obs.payloadStringValue else { continue }
+ for feature in features {
+ guard let qrFeature = feature as? CIQRCodeFeature,
+ let messageString = qrFeature.messageString else {
+ continue
+ }
+
+ // Core Image has origin at bottom-left with y-up.
+ // Convert to normalized [0,1] coords with origin top-left, y-down.
+ let minX = min(qrFeature.topLeft.x, qrFeature.bottomLeft.x)
+ let maxX = max(qrFeature.topRight.x, qrFeature.bottomRight.x)
+ // In CI coords, topLeft.y > bottomLeft.y (y goes up)
+ let minYci = min(qrFeature.bottomLeft.y, qrFeature.bottomRight.y)
+ let maxYci = max(qrFeature.topLeft.y, qrFeature.topRight.y)
+
+ // Add padding around finder patterns (matching Android's 15%)
+ let padX = (maxX - minX) * 0.15
+ let padY = (maxYci - minYci) * 0.15
+ let paddedMinX = max(minX - padX, 0)
+ let paddedMaxX = min(maxX + padX, imageWidth)
+ let paddedMinYci = max(minYci - padY, 0)
+ let paddedMaxYci = min(maxYci + padY, imageHeight)
+
+ // Flip y: top-left origin
+ let normX = paddedMinX / imageWidth
+ let normY = 1.0 - (paddedMaxYci / imageHeight)
+ let normW = (paddedMaxX - paddedMinX) / imageWidth
+ let normH = (paddedMaxYci - paddedMinYci) / imageHeight
- // Vision's boundingBox is normalized [0,1] with origin at bottom-left.
- // Convert to top-left origin (y-down) for Flutter.
- let box = obs.boundingBox
detections.append([
- "content": payload,
- "x": Double(box.origin.x),
- "y": Double(1.0 - box.origin.y - box.height),
- "width": Double(box.width),
- "height": Double(box.height),
+ "content": messageString,
+ "x": Double(normX),
+ "y": Double(normY),
+ "width": Double(normW),
+ "height": Double(normH),
])
}
diff --git a/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec b/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec
index 11df118b30..9c12badcec 100644
--- a/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec
+++ b/mobile/apps/auth/plugins/qr/ios/ente_qr.podspec
@@ -9,13 +9,13 @@ Pod::Spec.new do |s|
s.description = <<-DESC
A QR code reader plugin for Ente.
DESC
- s.homepage = 'https://ente.com'
+ s.homepage = 'https://ente.io'
s.license = { :file => '../LICENSE' }
- s.author = { 'Ente' => '[email protected]' }
+ s.author = { 'Ente' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
- s.platform = :ios, '12.0'
+ s.platform = :ios, '9.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }