@regulaforensics/cordova-plugin-document-reader-api 9.11.937-rc → 9.11.938-rc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,324 @@
1
+ import DocumentReader
2
+
3
+ let docReader = DocReader.shared
4
+
5
+ let completionEvent = "completion"
6
+ let databaseProgressEvent = "database_progress"
7
+ let rfidOnProgressEvent = "rfidOnProgressCompletion"
8
+ let rfidOnChipDetectedEvent = "rfidOnChipDetectedEvent"
9
+ let rfidOnRetryReadChipEvent = "rfidOnRetryReadChipEvent"
10
+ let paCertificateCompletionEvent = "pa_certificate_completion"
11
+ let taCertificateCompletionEvent = "ta_certificate_completion"
12
+ let taSignatureCompletionEvent = "ta_signature_completion"
13
+ let aaChallengeCompletionEvent = "aaChallengeCompletionEvent"
14
+ let paceProtocolCompletionEvent = "paceProtocolCompletionEvent"
15
+ let caProtocolCompletionEvent = "caProtocolCompletionEvent"
16
+ let videoEncoderCompletionEvent = "video_encoder_completion"
17
+ let onCustomButtonTappedEvent = "onCustomButtonTappedEvent"
18
+
19
+ func methodCall(_ method: String, _ callback: @escaping Callback) {
20
+ switch method {
21
+ case("getDocumentReaderIsReady"): callback(docReader.isDocumentReaderIsReady)
22
+ case("getDocumentReaderStatus"): callback(docReader.documentReaderStatus)
23
+ case("getRfidSessionStatus"): callback(docReader.rfidSessionStatus)
24
+ case("setRfidSessionStatus"): docReader.rfidSessionStatus = argsNullable(0)
25
+ case("getTag"): callback(docReader.tag)
26
+ case("setTag"): docReader.tag = argsNullable(0)
27
+ case("getTenant"): callback(docReader.tenant)
28
+ case("setTenant"): docReader.tenant = argsNullable(0)
29
+ case("getEnv"): callback(docReader.env)
30
+ case("setEnv"): docReader.env = argsNullable(0)
31
+ case("getLocale"): callback(docReader.languageLocaleCode)
32
+ case("setLocale"): docReader.languageLocaleCode = argsNullable(0)
33
+ case("getFunctionality"): callback(docReader.functionality.encode())
34
+ case("setFunctionality"): docReader.functionality.update(args(0))
35
+ case("getProcessParams"): callback(docReader.processParams.encode())
36
+ case("setProcessParams"): docReader.processParams.update(args(0))
37
+ case("getCustomization"): callback(docReader.customization.encode())
38
+ case("setCustomization"): docReader.customization.update(args(0))
39
+ case("getRfidScenario"): callback(docReader.rfidScenario.encode())
40
+ case("setRfidScenario"): docReader.rfidScenario.update(args(0))
41
+ case("resetConfiguration"):
42
+ docReader.functionality = Functionality()
43
+ docReader.processParams = ProcessParams()
44
+ docReader.customization = Customization()
45
+ docReader.rfidScenario = RFIDScenario()
46
+ docReader.functionality.recordScanningProcessDelegate = recordScanningProcessDelegate
47
+ docReader.customization.actionDelegate = actionDelegate
48
+ case("initialize"), ("initializeReader"), ("initializeReaderWithBleDeviceConfig"):
49
+ let config = args(0) as [String: Any]
50
+ docReader.initializeReader(
51
+ config: config["useBleDevice"] as? Bool == true || method == "initializeReaderWithBleDeviceConfig"
52
+ ? DocReader.BleConfig.decode(config, bluetooth)
53
+ : DocReader.Config.decode(config)!,
54
+ completion: { success, error in
55
+ if success {
56
+ docReader.rfidDelegate = rfidDelegate
57
+ docReader.functionality.recordScanningProcessDelegate = recordScanningProcessDelegate
58
+ docReader.customization.actionDelegate = actionDelegate
59
+ }
60
+ callback(generateSuccessCompletion(success, error))
61
+ })
62
+ case("deinitializeReader"): docReader.deinitializeReader()
63
+ case("prepareDatabase"):
64
+ docReader.databaseFetchDelegate = databaseFetchDelegate
65
+ docReader.prepareDatabase(databaseID: args(0), progressHandler: nil, completion: { callback(generateSuccessCompletion($0, $1)) })
66
+ case("runAutoUpdate"):
67
+ docReader.databaseFetchDelegate = databaseFetchDelegate
68
+ docReader.runAutoUpdate(databaseID: args(0), progressHandler: nil, completion: { callback(generateSuccessCompletion($0, $1)) })
69
+ case("removeDatabase"): docReader.removeDatabase { success, _ in callback(success) }
70
+ case("cancelDBUpdate"): docReader.cancelDBUpdate(); callback(true)
71
+ case("checkDatabaseUpdate"): docReader.checkDatabaseUpdate(databaseID: args(0), completion: { callback($0?.encode()) })
72
+ case("scan"), ("startScanner"): let config = DocReader.ScannerConfig.decode(args(0))!
73
+ withPresenter { docReader.startScanner(presenter: $0, config: config, completion: completion) }
74
+ case("recognize"): let config = DocReader.RecognizeConfig.decode(args(0))!
75
+ withPresenter { docReader.recognizeImage(fromPresenter: $0, config: config, completion: completion) }
76
+ case("startNewPage"): docReader.startNewPage()
77
+ case("stopScanner"): DispatchQueue.main.async { docReader.stopScanner(nil) }
78
+ case("startRFIDReader"):
79
+ rfidReaderRequest = args(0)
80
+ withPresenter { docReader.startRFIDReader(fromPresenter: $0, completion: completion) }
81
+ case("readRFID"):
82
+ rfidReaderRequest = args(0)
83
+ docReader.readRFID({ _, notification in
84
+ if let notification { sendEvent(rfidOnProgressEvent, notification.encode()) }
85
+ }, completion: { action, results, error, _ in
86
+ sendEvent(completionEvent, generateCompletion(action.encode(), results, error))
87
+ })
88
+ case("stopRFIDReader"): docReader.stopRFIDReader(nil)
89
+ case("providePACertificates"): paCertificateCompletion?((argsNullable(0) as [Any]?)?.compactMap(PKDCertificate.decode))
90
+ case("provideTACertificates"): taCertificateCompletion?((argsNullable(0) as [Any]?)?.compactMap(PKDCertificate.decode))
91
+ case("provideTASignature"): taSignatureCompletion?(Data.decode(argsNullable(0)))
92
+ case("provideAAChallenge"): aaChallengeCompletion?(argsNullable(0))
93
+ case("selectPACEProtocol"): paceProtocolCompletion?(RGLRFIDAccessControlPACE.decode(argsNullable(0)))
94
+ case("selectCAProtocol"): caProtocolCompletion?(RGLRFIDAccessControlCA.decode(argsNullable(0)))
95
+ case("setTCCParams"): docReader.setTCCParams(TCCParams.decode(args(0))!, completion: { callback(generateSuccessCompletion($0, $1)) })
96
+ case("addPKDCertificates"): docReader.addPKDCertificates(certificates: (args(0) as [Any]).compactMap(PKDCertificate.decode))
97
+ case("clearPKDCertificates"): docReader.clearPKDCertificates()
98
+ case("startNewSession"): docReader.startNewSession()
99
+ case("connectBluetoothDevice"):
100
+ if bluetooth.state == .connected {
101
+ print("REGULA: Bluetooth device already connected, returning false")
102
+ callback(false)
103
+ return
104
+ }
105
+ bluetooth.delegate = bluetoothDelegate
106
+ bluetoothCallback = callback
107
+ bluetooth.connect(withDeviceName: args(0))
108
+ case("startReadMDl"):
109
+ let type = eMDLDeviceEngagement(rawValue: args(0))!
110
+ let retrieval = DocReader.DataRetrieval.decode(args(1))!
111
+ withPresenter { docReader.startReadMDL(fromPresenter: $0, engagementType: type, dataRetrieval: retrieval,
112
+ completion: { callback(generateCompletion($0.encode(), $1, $2)) }) }
113
+ case("startEngageDevice"): let type = eMDLDeviceEngagement(rawValue: args(0))!
114
+ withPresenter { docReader.startEngageDevice(fromPresenter: $0, type: type,
115
+ completion: { callback(generateDeviceEngagementCompletion($0, $1)) }) }
116
+ case("engageDeviceNFC"):
117
+ withPresenter { docReader.engageDeviceNFC($0, completion: { callback(generateDeviceEngagementCompletion($0, $1)) }) }
118
+ case("engageDeviceData"): docReader.engageDeviceData(args(0), completion: { callback(generateDeviceEngagementCompletion($0, $1)) })
119
+ case("startRetrieveData"): docReader.startRetrieveData(
120
+ DocReader.DeviceEngagement.decode(args(1))!, dataRetrieval: DocReader.DataRetrieval.decode(args(0))!,
121
+ completion: { callback(generateCompletion($0.encode(), $1, $2)) })
122
+ case("retrieveDataNFC"): docReader.retrieveDataNFC(DocReader.DataRetrieval.decode(args(0))!,
123
+ completion: { callback(generateCompletion($0.encode(), $1, $2)) })
124
+ case("retrieveDataBLE"): docReader.retrieveDataBLE(
125
+ DocReader.DeviceEngagement.decode(args(1))!, dataRetrieval: DocReader.DataRetrieval.decode(args(0))!,
126
+ completion: { callback(generateCompletion($0.encode(), $1, $2)) })
127
+ case("setLocalizationDictionary"): let localization = argsNullable(0) as [String: String?]?
128
+ docReader.localizationHandler = { localization?[$0] ?? nil }
129
+ case("getLicense"): callback(docReader.license?.encode())
130
+ case("getAvailableScenarios"): callback(docReader.availableScenarios.map { $0.encode() })
131
+ case("getIsRFIDAvailableForUse"): callback(docReader.isRFIDAvailableForUse)
132
+ case("isAuthenticatorRFIDAvailableForUse"): callback(docReader.isAuthenticatorRFIDAvailableForUse)
133
+ case("isAuthenticatorAvailableForUse"): callback(docReader.isAuthenticatorAvailableForUse)
134
+ case("getDocReaderVersion"): callback(docReader.version?.encode())
135
+ case("getDocReaderDocumentsDatabase"): callback(docReader.version?.database.encode())
136
+ case("finalizePackage"): docReader.finalizePackage(completion: { callback(generateFinalizePackageCompletion($0.encode(), $1, $2)) })
137
+ case("finalizePackageWithFinalizeConfig"): docReader.finalizePackage(
138
+ with: DocReader.FinalizeConfig.decode(args(0))!,
139
+ completion: { callback(generateFinalizePackageCompletion($0.encode(), $1, $2)) })
140
+ case("endBackendTransaction"): docReader.endBackendTransaction()
141
+ case("textFieldValueByType"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!))
142
+ case("textFieldValueByTypeLcid"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!, lcid: LCID(rawValue: args(2))!))
143
+ case("textFieldValueByTypeSource"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!))
144
+ case("textFieldValueByTypeLcidSource"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!, lcid: LCID(rawValue: args(2))!, source: ResultType(rawValue: args(3))!))
145
+ case("textFieldValueByTypeSourceOriginal"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!, original: args(3)))
146
+ case("textFieldValueByTypeLcidSourceOriginal"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldValueByType(fieldType: FieldType(rawValue: args(1))!, lcid: LCID(rawValue: args(2))!, source: ResultType(rawValue: args(3))!, original: args(4)))
147
+ case("textFieldByType"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldByType(fieldType: FieldType(rawValue: args(1))!)?.encode())
148
+ case("textFieldByTypeLcid"): callback(DocumentReaderResults(rawJSON: args(0)).getTextFieldByType(fieldType: FieldType(rawValue: args(1))!, lcid: LCID(rawValue: args(2))!)?.encode())
149
+ case("graphicFieldByTypeSource"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!)?.encode())
150
+ case("graphicFieldByTypeSourcePageIndex"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!, pageIndex: args(3))?.encode())
151
+ case("graphicFieldByTypeSourcePageIndexLight"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!, pageIndex: args(3), light: GraphicFieldLight(rawValue: args(4))!)?.encode())
152
+ case("graphicFieldImageByType"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldImageByType(fieldType: GraphicFieldType(rawValue: args(1))!)?.encode())
153
+ case("graphicFieldImageByTypeSource"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldImageByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!)?.encode())
154
+ case("graphicFieldImageByTypeSourcePageIndex"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldImageByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!, pageIndex: args(3))?.encode())
155
+ case("graphicFieldImageByTypeSourcePageIndexLight"): callback(DocumentReaderResults(rawJSON: args(0)).getGraphicFieldImageByType(fieldType: GraphicFieldType(rawValue: args(1))!, source: ResultType(rawValue: args(2))!, pageIndex: args(3), light: GraphicFieldLight(rawValue: args(4))!)?.encode())
156
+ case("containers"): callback(DocumentReaderResults(rawJSON: args(0)).getContainers(byResultTypes: args(1)))
157
+ case("encryptedContainers"): callback(DocumentReaderResults(rawJSON: args(0)).getEncryptedContainers())
158
+ case("getTranslation"):
159
+ let value = args(1) as Int
160
+ if value == -1 { callback("Unknown"); return }
161
+ switch args(0) as String {
162
+ case("RFIDErrorCodes"): callback(RFIDErrorCodes(rawValue: UInt32(value))!.stringValue)
163
+ case("LDSParsingErrorCodes"): callback(eLDS_ParsingErrorCodes(rawValue: UInt(value))!.stringValue)
164
+ case("LDSParsingNotificationCodes"): callback(eLDS_ParsingNotificationCodes(rawValue: UInt(value))!.stringValue)
165
+ case("ImageQualityCheckType"): callback(ImageQualityCheckType.decode(value).stringValue)
166
+ case("RFIDDataFileType"): callback(RFIDDataFileType(rawValue: UInt32(value))!.stringValue)
167
+ case("VisualFieldType"): callback(FieldType(rawValue: value)!.stringValue)
168
+ case("LCID"): callback(DocumentReaderTextField.lcidName(LCID(rawValue: value)!))
169
+ default: break
170
+ }
171
+ default: break
172
+ }
173
+ }
174
+
175
+ let completion: DocumentReaderCompletion = { action, results, error in
176
+ sendEvent(completionEvent, generateCompletion(action.encode(), results, error))
177
+ }
178
+
179
+ // MARK: - Delegates
180
+
181
+ var headersDelegateKey: UInt8 = 0
182
+ class IURLRequestInterceptingDelegate: NSObject, DocReader.URLRequestInterceptingDelegate {
183
+ let headers: [String: String]
184
+ init(_ headers: [String: String]) {
185
+ self.headers = headers
186
+ }
187
+ func interceptorPrepare(_ request: URLRequest) -> URLRequest? {
188
+ var req = request
189
+ for (key, value) in headers {
190
+ req.addValue(value, forHTTPHeaderField: key)
191
+ }
192
+ return req
193
+ }
194
+ }
195
+
196
+ let databaseFetchDelegate = IDocReaderDatabaseFetchDelegate()
197
+ class IDocReaderDatabaseFetchDelegate: NSObject, RGLDocReaderDatabaseFetchDelegate {
198
+ func onProgressChanged(_ downloadedBytes: NSNumber, totalBytes: NSNumber) {
199
+ sendEvent(databaseProgressEvent, [
200
+ "downloadedBytes": downloadedBytes,
201
+ "totalBytes": totalBytes,
202
+ "progress": totalBytes.doubleValue > 0 ? Int(downloadedBytes.doubleValue / totalBytes.doubleValue * 100) : 0,
203
+ ])
204
+ }
205
+ }
206
+
207
+ let actionDelegate = ICustomizationActionDelegate()
208
+ class ICustomizationActionDelegate: NSObject, DocReader.CustomizationActionDelegate {
209
+ func onCustomButtonTapped(withTag tag: Int) {
210
+ sendEvent(onCustomButtonTappedEvent, tag)
211
+ }
212
+ }
213
+
214
+ let recordScanningProcessDelegate = IRecordScanningProcessDelegate()
215
+ class IRecordScanningProcessDelegate: NSObject, RecordScanningProcessDelegate {
216
+ func didFinishRecording(toFile fileURL: URL) {
217
+ sendEvent(videoEncoderCompletionEvent, fileURL.absoluteString)
218
+ }
219
+ func didFailWithError(_ error: Error) { }
220
+ }
221
+
222
+ let bluetooth = Bluetooth()
223
+ let bluetoothDelegate = IBluetoothDelegate()
224
+ var bluetoothCallback: Callback?
225
+ class IBluetoothDelegate: NSObject, RGLBluetoothDelegate {
226
+ func didChangeConnectionState(_ bluetooth: Bluetooth, state: BluetoothConnectionState) {
227
+ switch state {
228
+ case .none: connectionFailed()
229
+ case .searching: perform(#selector(connectionFailed), with: nil, afterDelay: 7)
230
+ case .connected:
231
+ NSObject.cancelPreviousPerformRequests(withTarget: self)
232
+ let callback = bluetoothCallback
233
+ bluetoothCallback = nil
234
+ callback?(true)
235
+ default: break
236
+ }
237
+ }
238
+ @objc func connectionFailed() {
239
+ NSObject.cancelPreviousPerformRequests(withTarget: self)
240
+ guard let callback = bluetoothCallback else { return }
241
+ bluetoothCallback = nil
242
+ bluetooth.stopSearchDevices()
243
+ bluetooth.disconnect()
244
+ callback(false)
245
+ }
246
+ }
247
+
248
+ var rfidReaderRequest: [String: Any] = [:]
249
+ var paCertificateCompletion: (([PKDCertificate]?) -> Void)?
250
+ var taCertificateCompletion: (([PKDCertificate]?) -> Void)?
251
+ var taSignatureCompletion: ((Data?) -> Void)?
252
+ var aaChallengeCompletion: ((String?) -> Void)?
253
+ var paceProtocolCompletion: ((RGLRFIDAccessControlPACE?) -> Void)?
254
+ var caProtocolCompletion: ((RGLRFIDAccessControlCA?) -> Void)?
255
+
256
+ let rfidDelegate = IDocReaderRFIDDelegate()
257
+ class IDocReaderRFIDDelegate: NSObject, RGLDocReaderRFIDDelegate {
258
+ // The SDK accepts nil callback results despite its nonnull annotations.
259
+ @objc(onRequestPACertificatesWithSerial:issuer:callback:)
260
+ func onRequestPACertificates(withSerial serialNumber: Data, issuer: PAResourcesIssuer, callback: @escaping ([PKDCertificate]?) -> Void) {
261
+ if rfidReaderRequest["paCertificates"] as? Bool == true {
262
+ paCertificateCompletion = callback
263
+ sendEvent(paCertificateCompletionEvent, ["serialNumber": serialNumber.encode(), "issuer": issuer.encode()])
264
+ } else {
265
+ paCertificateCompletion = nil
266
+ callback(nil)
267
+ }
268
+ }
269
+ @objc(onRequestTACertificatesWithKey:callback:)
270
+ func onRequestTACertificates(withKey keyCAR: String, callback: @escaping ([PKDCertificate]?) -> Void) {
271
+ if rfidReaderRequest["taCertificates"] as? Bool == true {
272
+ taCertificateCompletion = callback
273
+ sendEvent(taCertificateCompletionEvent, keyCAR)
274
+ } else {
275
+ taCertificateCompletion = nil
276
+ callback(nil)
277
+ }
278
+ }
279
+ @objc(onRequestTASignatureWithChallenge:callback:)
280
+ func onRequestTASignature(with challenge: TAChallenge, callback: @escaping (Data?) -> Void) {
281
+ if rfidReaderRequest["taSignature"] as? Bool == true {
282
+ taSignatureCompletion = callback
283
+ sendEvent(taSignatureCompletionEvent, challenge.encode())
284
+ } else {
285
+ taSignatureCompletion = nil
286
+ callback(nil)
287
+ }
288
+ }
289
+ func onRequestAAChallenge(challenge: String, callback: @escaping (String?) -> Void) {
290
+ if rfidReaderRequest["aaChallenge"] as? Bool == true {
291
+ aaChallengeCompletion = callback
292
+ sendEvent(aaChallengeCompletionEvent, challenge)
293
+ } else {
294
+ aaChallengeCompletion = nil
295
+ callback(nil)
296
+ }
297
+ }
298
+ @objc(onRequestPACEProtocolWithOptions:callback:)
299
+ func onRequestPACEProtocol(options protocols: [RGLRFIDAccessControlPACE], callback: @escaping (RGLRFIDAccessControlPACE?) -> Void) {
300
+ if rfidReaderRequest["paceProtocol"] as? Bool == true {
301
+ paceProtocolCompletion = callback
302
+ sendEvent(paceProtocolCompletionEvent, protocols.map { $0.encode() })
303
+ } else {
304
+ paceProtocolCompletion = nil
305
+ callback(nil)
306
+ }
307
+ }
308
+ @objc(onRequestCAProtocolWithOptions:callback:)
309
+ func onRequestCAProtocol(options protocols: [RGLRFIDAccessControlCA], callback: @escaping (RGLRFIDAccessControlCA?) -> Void) {
310
+ if rfidReaderRequest["caProtocol"] as? Bool == true {
311
+ caProtocolCompletion = callback
312
+ sendEvent(caProtocolCompletionEvent, protocols.map { $0.encode() })
313
+ } else {
314
+ caProtocolCompletion = nil
315
+ callback(nil)
316
+ }
317
+ }
318
+ func didChipConnected() {
319
+ sendEvent(rfidOnChipDetectedEvent)
320
+ }
321
+ func didReceivedError(_ errorCode: RFIDErrorCodes) {
322
+ sendEvent(rfidOnRetryReadChipEvent, ["code": errorCode.rawValue])
323
+ }
324
+ }
@@ -0,0 +1,86 @@
1
+ #if canImport(Cordova)
2
+ import Cordova
3
+ #endif
4
+ import UIKit
5
+
6
+ private weak var plugin: RGLWDocumentReader?
7
+
8
+ @objc(RGLWDocumentReader)
9
+ class RGLWDocumentReader: CDVPlugin {
10
+ fileprivate var databaseCallbackId: String?
11
+ fileprivate var readingCallbackId: String?
12
+
13
+ @objc(exec:)
14
+ func exec(_ command: CDVInvokedUrlCommand) {
15
+ plugin = self
16
+ let action = command.arguments.first as! String
17
+ args = legacyArguments(for: action, Array(command.arguments.dropFirst()))
18
+ switch action {
19
+ case "prepareDatabase", "runAutoUpdate": databaseCallbackId = command.callbackId
20
+ case "scan", "startScanner", "recognize", "readRFID", "startRFIDReader": readingCallbackId = command.callbackId
21
+ default: break
22
+ }
23
+
24
+ methodCall(action) { data in
25
+ DispatchQueue.main.async {
26
+ self.send(data, callbackId: command.callbackId, keepCallback: false)
27
+ }
28
+ }
29
+ }
30
+
31
+ fileprivate func send(_ data: Any?, callbackId: String?, keepCallback: Bool) {
32
+ guard let callbackId else { return }
33
+ let result: CDVPluginResult?
34
+ switch data.toSendable() {
35
+ case let value as String: result = CDVPluginResult(status: .ok, messageAs: value)
36
+ case let value as NSNumber where CFGetTypeID(value) == CFBooleanGetTypeID(): result = CDVPluginResult(status: .ok, messageAs: value.boolValue)
37
+ case let value as NSNumber: result = CDVPluginResult(status: .ok, messageAs: value.doubleValue)
38
+ default: result = CDVPluginResult(status: .ok)
39
+ }
40
+ guard let result else { return }
41
+ result.setKeepCallbackAs(keepCallback)
42
+ commandDelegate.send(result, callbackId: callbackId)
43
+ }
44
+ }
45
+
46
+ func sendEvent(_ event: String, _ data: Any? = nil) {
47
+ DispatchQueue.main.async {
48
+ guard let plugin else { return }
49
+ switch event {
50
+ case videoEncoderCompletionEvent, onCustomButtonTappedEvent: return
51
+ case databaseProgressEvent: plugin.send(data, callbackId: plugin.databaseCallbackId, keepCallback: true)
52
+ case completionEvent: plugin.send(data, callbackId: plugin.readingCallbackId, keepCallback: true)
53
+ default: plugin.send(event + String(describing: data.toSendable()), callbackId: plugin.readingCallbackId, keepCallback: true)
54
+ }
55
+ }
56
+ }
57
+
58
+ func withPresenter(_ action: @escaping (UIViewController) -> Void) {
59
+ DispatchQueue.main.async {
60
+ let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.filter { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }.flatMap { $0.windows }
61
+ let candidates = windows.filter { $0.isKeyWindow } + windows.filter { !$0.isKeyWindow && !$0.isHidden && $0.alpha > 0 && $0.windowLevel == .normal }
62
+ for window in candidates {
63
+ guard var presenter = window.rootViewController else { continue }
64
+ while let next = presenter.presentedViewController
65
+ ?? (presenter as? UINavigationController)?.visibleViewController
66
+ ?? (presenter as? UINavigationController)?.topViewController
67
+ ?? (presenter as? UITabBarController)?.selectedViewController {
68
+ presenter = next
69
+ }
70
+ guard presenter.viewIfLoaded?.window != nil else { continue }
71
+ action(presenter)
72
+ return
73
+ }
74
+ print("REGULA: Cannot present the UI: no presenter available.")
75
+ }
76
+ }
77
+
78
+ private func legacyArguments(for action: String, _ values: [Any]) -> [Any] {
79
+ switch action {
80
+ case "readRFID", "startRFIDReader": return [values.first as? [String: Any] ?? [:]]
81
+ case "startRetrieveData", "retrieveDataBLE": return [values[1], values[0]]
82
+ case "getTranslation": if values[0] as? String == "RFIDErrorCodes", let code = values[1] as? NSNumber { return [values[0], Int(code.uint32Value)] }
83
+ default: break
84
+ }
85
+ return values
86
+ }
@@ -0,0 +1,87 @@
1
+ import Foundation
2
+ import UIKit
3
+
4
+ public typealias Callback = (Any?) -> Void
5
+
6
+ var args: [Any?] = []
7
+ func args<T>(_ index: Int) -> T {
8
+ return args[index] as! T
9
+ }
10
+
11
+ func argsNullable<T>(_ index: Int) -> T? {
12
+ if args[index] is NSNull { return nil }
13
+ return args[index] as! T?
14
+ }
15
+
16
+ extension Any? {
17
+ func toSendable() -> Any {
18
+ guard let self else { return NSNull() }
19
+ if self is [String: Any?] || self is [Any?] {
20
+ let data = try! JSONSerialization.data(withJSONObject: fixNulls(self), options: .prettyPrinted)
21
+ return String(data: data, encoding: .utf8)!
22
+ }
23
+ return self
24
+ }
25
+ }
26
+
27
+ func fixNulls(_ value: Any?) -> Any {
28
+ guard let value else { return NSNull() }
29
+ switch value {
30
+ // Native results can contain unavailable scores represented by NaN or infinity.
31
+ case let value as NSNumber where !value.doubleValue.isFinite: return -1
32
+ case let value as [String: Any?]:
33
+ var dict = [String: Any]()
34
+ for (k, v) in value { if let v { dict[k] = fixNulls(v) } }
35
+ return dict
36
+ case let value as [Any?]: return value.map { fixNulls($0) }
37
+ default: return value
38
+ }
39
+ }
40
+
41
+ extension NSObject {
42
+ static func allocate() -> NSObject {
43
+ return perform(NSSelectorFromString("alloc")).takeUnretainedValue() as! NSObject
44
+ }
45
+ static func emptyInit<T>() -> T {
46
+ return allocate().perform("init".selector()).takeUnretainedValue() as! T
47
+ }
48
+ }
49
+
50
+ extension String {
51
+ func selector() -> Selector {
52
+ return NSSelectorFromString(self)
53
+ }
54
+ }
55
+
56
+ func privateInit<T, Fn>(
57
+ _ allocated: NSObject,
58
+ _ selector: Selector,
59
+ _ function: Fn.Type,
60
+ _ call: (Fn) -> Unmanaged<AnyObject>?
61
+ ) -> T {
62
+ let f = unsafeBitCast(allocated.method(for: selector), to: function)
63
+ return call(f)!.takeUnretainedValue() as! T
64
+ }
65
+
66
+ extension Data {
67
+ static func decode(_ it: Any?) -> Self? {
68
+ guard var it = it as? String else { return nil }
69
+ if it.hasPrefix("data") { it = String(it[it.index(after: it.firstIndex(of: ",")!)...]) }
70
+ return Self(base64Encoded: it)
71
+ }
72
+
73
+ func encode() -> String {
74
+ return self.base64EncodedString()
75
+ }
76
+ }
77
+
78
+ extension UIImage {
79
+ static func decode(_ it: Any?) -> Self? {
80
+ guard let it = it as? String else { return nil }
81
+ return Self(data: Data.decode(it)!)
82
+ }
83
+
84
+ func encode() -> String {
85
+ return self.pngData()!.encode()
86
+ }
87
+ }
@@ -1,44 +0,0 @@
1
- #ifndef RGLWConfig_h
2
- #define RGLWConfig_h
3
-
4
- #import <DocumentReader/DocumentReader.h>
5
- #import "RGLWJSONConstructor.h"
6
-
7
- @import CoreGraphics;
8
- @import UIKit;
9
- @import AVFoundation;
10
-
11
- @interface RGLWConfig : NSObject
12
-
13
- +(void)setFunctionality:(NSDictionary*)options :(RGLFunctionality*)functionality;
14
- +(void)setProcessParams:(NSDictionary*)options :(RGLProcessParams*)processParams;
15
- +(void)setCustomization:(NSDictionary*)options :(RGLCustomization*)customization;
16
- +(void)setRfidScenario:(NSDictionary*)options :(RGLRFIDScenario*)rfidScenario;
17
- +(void)setDataGroups:(RGLDataGroup*)dataGroup dict:(NSDictionary*)dict;
18
- +(void)setDTCDataGroup:(RGLDTCDataGroup*)dataGroup dict:(NSDictionary*)dict;
19
- +(void)setImageQA:(RGLImageQA*)result input:(NSDictionary*)input;
20
- +(void)setAuthenticityParams:(RGLAuthenticityParams*)result input:(NSDictionary*)input;
21
- +(void)setLivenessParams:(RGLLivenessParams*)result input:(NSDictionary*)input;
22
- +(void)setAuthenticityPropertiesParams:(RGLAuthenticityPropertiesParams*)result input:(NSDictionary*)input;
23
-
24
- +(NSDictionary*)getFunctionality:(RGLFunctionality*)functionality;
25
- +(NSDictionary*)getProcessParams:(RGLProcessParams*)processParams;
26
- +(NSDictionary*)getCustomization:(RGLCustomization*)customization;
27
- +(NSDictionary*)getRfidScenario:(RGLRFIDScenario*)rfidScenario;
28
- +(NSDictionary*)getDataGroups:(RGLDataGroup*)dataGroup;
29
- +(NSDictionary*)getDTCDataGroup:(RGLDTCDataGroup*)dataGroup;
30
- +(NSDictionary*)getImageQA:(RGLImageQA*)input;
31
- +(NSDictionary*)getAuthenticityParams:(RGLAuthenticityParams*)input;
32
- +(NSDictionary*)getLivenessParams:(RGLLivenessParams*)input;
33
- +(NSDictionary*)getAuthenticityPropertiesParams:(RGLAuthenticityPropertiesParams*)input;
34
-
35
- +(RGLImageQualityCheckType)imageQualityCheckTypeWithNumber:(NSNumber*)value;
36
- +(NSNumber*)generateDocReaderAction:(RGLDocReaderAction)action;
37
- +(NSNumber*)generateRFIDCompleteAction:(RGLRFIDCompleteAction)action;
38
- +(NSNumber*)generateImageQualityCheckType:(RGLImageQualityCheckType)value;
39
-
40
- +(RGLDocReaderFrame)docReaderFrameWithString:(NSString*)value;
41
- +(NSString*)generateDocReaderFrame:(RGLDocReaderFrame)value;
42
-
43
- @end
44
- #endif