Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Consoles: QR provider enhancements and iOS cookie improvements (#1207)

Michael Rademakera13a5a57dda1
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/service/BleProvider.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/service/BleProvider.kt
index d7f833a8f..a072b964a 100644
--- a/console/android/ORLib/src/main/java/io/openremote/orlib/service/BleProvider.kt
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/service/BleProvider.kt
@@ -180,6 +180,13 @@ class BleProvider(val context: Context) {
"Successfully disconnected from $deviceAddress"
)
gatt.close()
+ bleCallback.accept(
+ hashMapOf(
+ "action" to "CONNECT_TO_DEVICE",
+ "provider" to "ble",
+ "success" to false,
+ )
+ )
}
} else {
bleCallback.accept(
@@ -218,7 +225,6 @@ class BleProvider(val context: Context) {
}
if (characteristic.isWritable()) {
- gatt?.setCharacteristicNotification(characteristic, true)
deviceCharacteristics.find { it.characteristic.uuid == characteristic.uuid }?.isWritable =
true
}
@@ -306,11 +312,11 @@ class BleProvider(val context: Context) {
"action" to "CONNECT_TO_DEVICE",
"provider" to "ble",
"success" to true,
- "data" to hashMapOf("attributes" to deviceCharacteristics.map {
- createAttributeMap(
- it
- )
- })
+// "data" to hashMapOf("attributes" to deviceCharacteristics.map {
+// createAttributeMap(
+// it
+// )
+// })
)
)
}
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt
index 7861780ed..2fce24a16 100644
--- a/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/service/QrScannerProvider.kt
@@ -76,8 +76,15 @@ class QrScannerProvider(val context: Context) {
)
}
- fun startScanner(activity: Activity) {
+ fun startScanner(activity: Activity, callback: ScannerCallback?) {
val intent = Intent(activity, QrScannerActivity::class.java)
activity.startActivityForResult(intent, REQUEST_SCAN_QR)
+ callback?.accept(
+ hashMapOf(
+ "action" to "SCAN_QR",
+ "provider" to "qr",
+ "success" to true
+ )
+ )
}
}
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/ui/OrMainActivity.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/OrMainActivity.kt
index bf2df6dab..3e8ca5f5e 100644
--- a/console/android/ORLib/src/main/java/io/openremote/orlib/ui/OrMainActivity.kt
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/OrMainActivity.kt
@@ -510,13 +510,23 @@ open class OrMainActivity : Activity() {
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == QrScannerProvider.REQUEST_SCAN_QR) {
- val qrResult = data?.getStringExtra("result")
+ val response = when (resultCode) {
+ RESULT_OK -> {
+ val qrResult = data?.getStringExtra("result")
+
+ hashMapOf(
+ "action" to "SCAN_RESULT",
+ "provider" to "qr",
+ "data" to hashMapOf("result" to qrResult)
+ )
+ }
- val response = hashMapOf(
- "action" to "SCAN_QR",
- "provider" to "qr",
- "data" to hashMapOf("result" to qrResult)
- )
+ else -> hashMapOf(
+ "action" to "SCAN_RESULT",
+ "provider" to "qr",
+ "data" to hashMapOf("result" to "FAILED")
+ )
+ }
notifyClient(response)
}
}
@@ -845,7 +855,12 @@ open class OrMainActivity : Activity() {
}
action.equals("SCAN_QR", ignoreCase = true) -> {
- qrScannerProvider?.startScanner(this@OrMainActivity)
+ qrScannerProvider?.startScanner(this@OrMainActivity, object :
+ QrScannerProvider.ScannerCallback {
+ override fun accept(responseData: Map<String, Any>) {
+ notifyClient(responseData)
+ }
+ })
}
}
}
diff --git a/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt
index ff57a0fbf..dd1c1f42e 100644
--- a/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt
+++ b/console/android/ORLib/src/main/java/io/openremote/orlib/ui/QrScannerActivity.kt
@@ -2,12 +2,12 @@ package io.openremote.orlib.ui
import android.Manifest
import android.annotation.SuppressLint
-import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.SurfaceHolder
import android.view.SurfaceView
+import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
@@ -18,7 +18,6 @@ import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
import io.openremote.orlib.R
import io.openremote.orlib.databinding.ActivityOrQrScannerBinding
-import io.openremote.orlib.service.QrScannerProvider
import java.io.IOException
class QrScannerActivity : AppCompatActivity() {
@@ -36,6 +35,15 @@ class QrScannerActivity : AppCompatActivity() {
supportActionBar!!.title = "Scan QR Code"
initViews()
initialiseDetectorsAndSources()
+
+ onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() {
+ val data = Intent()
+ data.putExtra("result", "CANCELED")
+ setResult(RESULT_OK, data)
+ finish()
+ }
+ })
}
private fun initViews() {
@@ -146,4 +154,4 @@ class QrScannerActivity : AppCompatActivity() {
companion object {
private const val REQUEST_CAMERA_PERMISSION = 201
}
-}
\ No newline at end of file
+}
diff --git a/console/iOS/ORLib/ORLib/ConsoleProviders/QrScannerProvider.swift b/console/iOS/ORLib/ORLib/ConsoleProviders/QrScannerProvider.swift
index f686bd088..ec306b6c3 100644
--- a/console/iOS/ORLib/ORLib/ConsoleProviders/QrScannerProvider.swift
+++ b/console/iOS/ORLib/ORLib/ConsoleProviders/QrScannerProvider.swift
@@ -113,7 +113,7 @@ public class QrScannerProvider: NSObject {
]
}
- public func startScanner(currentViewController: UIViewController, callback:@escaping ([String: Any]) -> Void) {
+ public func startScanner(currentViewController: UIViewController, startScanCallback:@escaping ([String: Any]) -> Void, scannedCallback:@escaping ([String: Any]) -> Void) {
let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
switch cameraAuthorizationStatus {
@@ -122,7 +122,14 @@ public class QrScannerProvider: NSObject {
scanner!.delegate = self
self.scanner?.modalPresentationStyle = .fullScreen
currentViewController.present(scanner!, animated: true, completion: nil)
- scannedCallback = callback
+ self.scannedCallback = scannedCallback
+ startScanCallback(
+ [
+ DefaultsKey.actionKey: Actions.scanQr,
+ DefaultsKey.providerKey: Providers.qr,
+ DefaultsKey.successKey: true,
+ ]
+ )
default:
AVCaptureDevice.requestAccess(for: .video, completionHandler: { granted in
if granted {
@@ -131,9 +138,23 @@ public class QrScannerProvider: NSObject {
self.scanner!.delegate = self
self.scanner?.modalPresentationStyle = .fullScreen
currentViewController.present(self.scanner!, animated: true, completion: nil)
- self.scannedCallback = callback
+ self.scannedCallback = scannedCallback
+ startScanCallback(
+ [
+ DefaultsKey.actionKey: Actions.scanQr,
+ DefaultsKey.providerKey: Providers.qr,
+ DefaultsKey.successKey: true,
+ ]
+ )
}
} else {
+ startScanCallback(
+ [
+ DefaultsKey.actionKey: Actions.scanQr,
+ DefaultsKey.providerKey: Providers.qr,
+ DefaultsKey.successKey: false,
+ ]
+ )
let alertController = UIAlertController(title: "Camera permission needed", message: "In order to scan QR codes, access to the camera is needed. Would you like to enable it now?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Yes", style: .default, handler: {alertAction in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
@@ -160,9 +181,9 @@ extension QrScannerProvider: QrScannerDelegate {
scanner?.dismiss(animated: true) {
self.scannedCallback?(
[
- DefaultsKey.actionKey: Actions.scanQr,
+ DefaultsKey.actionKey: Actions.scanResult,
DefaultsKey.providerKey: Providers.qr,
- DefaultsKey.dataKey: ["result": codeContents]
+ DefaultsKey.dataKey: ["result": codeContents ?? "CANCELED"]
]
)
self.scannedCallback = nil
diff --git a/console/iOS/ORLib/ORLib/UI/ORViewController.swift b/console/iOS/ORLib/ORLib/UI/ORViewController.swift
index 4f92c360e..809284bc5 100644
--- a/console/iOS/ORLib/ORLib/UI/ORViewController.swift
+++ b/console/iOS/ORLib/ORLib/UI/ORViewController.swift
@@ -284,9 +284,12 @@ extension ORViewcontroller: WKScriptMessageHandler {
sendData(data: disableData)
}
case Actions.scanQr:
- qrProvider?.startScanner(currentViewController: self) { scannedData in
+ qrProvider?.startScanner(currentViewController: self, startScanCallback: { startScanData in
+ self.sendData(data: startScanData)
+ }, scannedCallback:
+ { scannedData in
self.sendData(data: scannedData)
- }
+ })
default:
print("Wrong action \(action) for \(provider)")
}
@@ -388,12 +391,18 @@ extension ORViewcontroller: WKNavigationDelegate {
if response.statusCode != 200 && response.statusCode != 204 {
decisionHandler(.cancel)
+ if 400...499 ~= response.statusCode {
+ if let baseUrl = self.baseUrl {
+ webView.clearCookies(for: baseUrl, completion: nil)
+ }
+ }
+
handleError(errorCode: response.statusCode, description: "Error in request", failingUrl: response.url?.absoluteString ?? "", isForMainFrame: true)
return
}
}
if let baseUrl = self.baseUrl {
- webView.writeCookiesToStorage(for: baseUrl){
+ webView.writeCookiesToStorage(for: baseUrl) {
decisionHandler(.allow)
}
} else {
diff --git a/console/iOS/ORLib/ORLib/UI/QrScannerViewController.swift b/console/iOS/ORLib/ORLib/UI/QrScannerViewController.swift
index 5187b3e92..24c4c49d1 100644
--- a/console/iOS/ORLib/ORLib/UI/QrScannerViewController.swift
+++ b/console/iOS/ORLib/ORLib/UI/QrScannerViewController.swift
@@ -63,7 +63,9 @@ public class QrScannerViewController: UIViewController, AVCaptureMetadataOutputO
subView.layer.addSublayer(previewLayer)
view.addSubview(subView)
- captureSession.startRunning()
+ DispatchQueue.global(qos: .background).async {
+ self.captureSession.startRunning()
+ }
let cancelButton = UIButton(type: .close)
cancelButton.layer.cornerRadius = 25
@@ -93,7 +95,9 @@ public class QrScannerViewController: UIViewController, AVCaptureMetadataOutputO
super.viewWillAppear(animated)
if (captureSession?.isRunning == false) {
- captureSession.startRunning()
+ DispatchQueue.global(qos: .background).async {
+ self.captureSession.startRunning()
+ }
}
}
diff --git a/console/iOS/ORLib/ORLib/Utils/Constants.swift b/console/iOS/ORLib/ORLib/Utils/Constants.swift
index e383f7c7d..50d500ca1 100644
--- a/console/iOS/ORLib/ORLib/Utils/Constants.swift
+++ b/console/iOS/ORLib/ORLib/Utils/Constants.swift
@@ -60,6 +60,7 @@ public enum Actions {
public static let store = "STORE"
public static let retrieve = "RETRIEVE"
public static let scanQr = "SCAN_QR"
+ public static let scanResult = "SCAN_RESULT"
public static let scanBleDevices = "SCAN_BLE_DEVICES"
public static let connectToBleDevice = "CONNECT_TO_DEVICE"
public static let sendToBleDevice = "SEND_TO_DEVICE"
diff --git a/console/iOS/ORLib/ORLib/Utils/WKWebView+Utils.swift b/console/iOS/ORLib/ORLib/Utils/WKWebView+Utils.swift
index a768c6520..da8c9a3d5 100644
--- a/console/iOS/ORLib/ORLib/Utils/WKWebView+Utils.swift
+++ b/console/iOS/ORLib/ORLib/Utils/WKWebView+Utils.swift
@@ -1,63 +1,83 @@
import WebKit
extension WKWebView {
-
-enum PrefKey {
- static let cookie = "cookies"
-}
-
-func writeCookiesToStorage(for domain: String, completion: @escaping () -> ()) {
- fetchInMemoryCookies(for: domain) { data in
- UserDefaults.standard.setValue(data, forKey: PrefKey.cookie + domain)
- completion();
+
+ enum PrefKey {
+ static let cookie = "cookies"
}
-}
-
-
- func loadCookiesFromStorage(for domain: String, completion: @escaping () -> ()) {
- if let storedCookie = UserDefaults.standard.dictionary(forKey: (PrefKey.cookie + domain)){
- fetchInMemoryCookies(for: domain) { freshCookie in
-
- let mergedCookie = storedCookie.merging(freshCookie) { (_, new) in new }
-
- for (_, cookieConfig) in mergedCookie {
- let cookie = cookieConfig as! Dictionary<String, Any>
-
- var expire : Any? = nil
-
- if let expireTime = cookie["Expires"] as? Double{
- expire = Date(timeIntervalSinceNow: expireTime)
+
+ func writeCookiesToStorage(for domain: String, completion: (() -> (Void))?) {
+ fetchInMemoryCookies(for: domain) { cookies in
+ UserDefaults.standard.set(cookies, forKey: PrefKey.cookie + domain)
+ completion?();
+ }
+ }
+
+ func clearCookies(for domain: String, completion: (() -> (Void))?) {
+ WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
+ records.forEach { record in
+ WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
+ print("[WebCacheCleaner] Record \(record) deleted")
+ }
+ }
+ WKWebsiteDataStore.default().httpCookieStore.getAllCookies { (cookies) in
+ for cookie in cookies {
+ if domain.contains(cookie.domain) {
+ self.configuration.websiteDataStore.httpCookieStore.delete(cookie)
}
-
- let newCookie = HTTPCookie(properties: [
- .domain: cookie["Domain"] as Any,
- .path: cookie["Path"] as Any,
- .name: cookie["Name"] as Any,
- .value: cookie["Value"] as Any,
- .secure: cookie["Secure"] as Any,
- .expires: expire as Any
- ])
-
- self.configuration.websiteDataStore.httpCookieStore.setCookie(newCookie!)
}
-
- completion()
}
-
+ UserDefaults.standard.removeObject(forKey: PrefKey.cookie + domain)
+ UserDefaults.standard.synchronize()
+ completion?();
}
- else{
- completion()
+
+
+ func loadCookiesFromStorage(for domain: String, completion: (() -> (Void))?) {
+ if let storedCookies = UserDefaults.standard.dictionary(forKey: (PrefKey.cookie + domain)){
+ fetchInMemoryCookies(for: domain) { freshCookies in
+
+ let mergedCookie = storedCookies.merging(freshCookies) { (_, new) in new }
+
+ for (_, cookieConfig) in mergedCookie {
+ let cookie = cookieConfig as! Dictionary<String, Any>
+
+ var expire : Any? = nil
+
+ if let expireTime = cookie["Expires"] as? Double{
+ expire = Date(timeIntervalSinceNow: expireTime)
+ }
+
+ let newCookie = HTTPCookie(properties: [
+ .domain: cookie["Domain"] as Any,
+ .path: cookie["Path"] as Any,
+ .name: cookie["Name"] as Any,
+ .value: cookie["Value"] as Any,
+ .secure: cookie["Secure"] as Any,
+ .expires: expire as Any
+ ])
+
+ self.configuration.websiteDataStore.httpCookieStore.setCookie(newCookie!)
+ }
+
+ completion?()
+ }
+
+ }
+ else{
+ completion?()
+ }
}
-}
-
-func fetchInMemoryCookies(for domain: String, completion: @escaping ([String: Any]) -> ()) {
- var cookieDict = [String: AnyObject]()
- WKWebsiteDataStore.default().httpCookieStore.getAllCookies { (cookies) in
- for cookie in cookies {
- if domain.contains(cookie.domain) {
- cookieDict[cookie.name] = cookie.properties as AnyObject?
+
+ func fetchInMemoryCookies(for domain: String, completion: (([String: Any]) -> (Void))?) {
+ var cookieDict = [String: AnyObject]()
+ WKWebsiteDataStore.default().httpCookieStore.getAllCookies { (cookies) in
+ for cookie in cookies {
+ if domain.contains(cookie.domain) {
+ cookieDict[cookie.name] = cookie.properties as AnyObject?
+ }
}
+ completion?(cookieDict)
}
- completion(cookieDict)
}
-}}
+}
diff --git a/ui/component/core/src/console.ts b/ui/component/core/src/console.ts
index c4476b124..2697492f2 100644
--- a/ui/component/core/src/console.ts
+++ b/ui/component/core/src/console.ts
@@ -6,9 +6,12 @@ import {Deferred} from "./util";
// No ES6 module support in platform lib
let platform = require('platform');
-export interface ProviderMessage {
+export interface ProviderAction {
provider: string;
action: string;
+}
+
+export interface ProviderMessage extends ProviderAction{
data?: any;
[x: string]: any;
}
@@ -39,6 +42,7 @@ export class Console {
protected _initialised: boolean = false;
protected _initialiseInProgress: boolean = false;
protected _pendingProviderPromises: { [name: string]: [Deferred<any>, number] } = {};
+ protected _providerMessageListeners: { [name: string]: (msg: ProviderMessage) => void } = {};
protected _pendingProviderEnables: string[] = [];
protected _enableCompleteCallback: (() => void) | null;
protected _registrationTimer: number | null = null;
@@ -367,6 +371,14 @@ export class Console {
}
}
+ public addProviderMessageListener(providerAction: ProviderAction, listener: (msg: ProviderMessage) => void) {
+ this._providerMessageListeners[providerAction.provider + providerAction.action] = listener;
+ }
+
+ public removeProviderMessageListener(providerAction: ProviderAction) {
+ delete this._providerMessageListeners[providerAction.provider + providerAction.action];
+ }
+
protected _postNativeShellMessage(jsonMessage: any) {
if (this.shellAndroid) {
// @ts-ignore
@@ -508,6 +520,11 @@ export class Console {
delete this._pendingProviderPromises[name + action];
deferredAndTimeout[0].resolve(msgJson);
}
+
+ let listener = this._providerMessageListeners[name + action];
+ if (listener) {
+ listener(msgJson);
+ }
}
protected _callCompletedCallback() {