@regulaforensics/cordova-plugin-document-reader-api 9.11.951-nightly → 9.11.953-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,346 @@
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
+ // MARK: - Completions
176
+
177
+ func generateSuccessCompletion(_ success: Bool, _ error: Error?) -> [String: Any?] {
178
+ return ["success": success, "error": error?.encode()]
179
+ }
180
+
181
+ func generateCompletion(_ action: Int, _ results: DocumentReaderResults?, _ error: Error?) -> [String: Any?] {
182
+ return [
183
+ "action": action,
184
+ "results": [0, 2, 3, 4, 6].contains(action) ? results?.encode() : nil,
185
+ "error": error?.encode(),
186
+ ]
187
+ }
188
+
189
+ func generateDeviceEngagementCompletion(_ deviceEngagement: DocReader.DeviceEngagement?, _ error: Error?) -> [String: Any?] {
190
+ return ["deviceEngagement": deviceEngagement?.encode(), "error": error?.encode()]
191
+ }
192
+
193
+ func generateFinalizePackageCompletion(_ action: Int, _ info: RGLTransactionInfo?, _ error: Error?) -> [String: Any?] {
194
+ return ["action": action, "info": info?.encode(), "error": error?.encode()]
195
+ }
196
+
197
+ let completion: DocumentReaderCompletion = { action, results, error in
198
+ sendEvent(completionEvent, generateCompletion(action.encode(), results, error))
199
+ }
200
+
201
+ // MARK: - Delegates
202
+
203
+ var headersDelegateKey: UInt8 = 0
204
+ class IURLRequestInterceptingDelegate: NSObject, DocReader.URLRequestInterceptingDelegate {
205
+ let headers: [String: String]
206
+ init(_ headers: [String: String]) {
207
+ self.headers = headers
208
+ }
209
+ func interceptorPrepare(_ request: URLRequest) -> URLRequest? {
210
+ var req = request
211
+ for (key, value) in headers {
212
+ req.addValue(value, forHTTPHeaderField: key)
213
+ }
214
+ return req
215
+ }
216
+ }
217
+
218
+ let databaseFetchDelegate = IDocReaderDatabaseFetchDelegate()
219
+ class IDocReaderDatabaseFetchDelegate: NSObject, RGLDocReaderDatabaseFetchDelegate {
220
+ func onProgressChanged(_ downloadedBytes: NSNumber, totalBytes: NSNumber) {
221
+ sendEvent(databaseProgressEvent, [
222
+ "downloadedBytes": downloadedBytes,
223
+ "totalBytes": totalBytes,
224
+ "progress": totalBytes.doubleValue > 0 ? Int(downloadedBytes.doubleValue / totalBytes.doubleValue * 100) : 0,
225
+ ])
226
+ }
227
+ }
228
+
229
+ let actionDelegate = ICustomizationActionDelegate()
230
+ class ICustomizationActionDelegate: NSObject, DocReader.CustomizationActionDelegate {
231
+ func onCustomButtonTapped(withTag tag: Int) {
232
+ sendEvent(onCustomButtonTappedEvent, tag)
233
+ }
234
+ }
235
+
236
+ let recordScanningProcessDelegate = IRecordScanningProcessDelegate()
237
+ class IRecordScanningProcessDelegate: NSObject, RecordScanningProcessDelegate {
238
+ func didFinishRecording(toFile fileURL: URL) {
239
+ sendEvent(videoEncoderCompletionEvent, fileURL.absoluteString)
240
+ }
241
+ func didFailWithError(_ error: Error) { }
242
+ }
243
+
244
+ let bluetooth = Bluetooth()
245
+ let bluetoothDelegate = IBluetoothDelegate()
246
+ var bluetoothCallback: Callback?
247
+ class IBluetoothDelegate: NSObject, RGLBluetoothDelegate {
248
+ func didChangeConnectionState(_ bluetooth: Bluetooth, state: BluetoothConnectionState) {
249
+ switch state {
250
+ case .none: connectionFailed()
251
+ case .searching: perform(#selector(connectionFailed), with: nil, afterDelay: 7)
252
+ case .connected:
253
+ NSObject.cancelPreviousPerformRequests(withTarget: self)
254
+ let callback = bluetoothCallback
255
+ bluetoothCallback = nil
256
+ callback?(true)
257
+ default: break
258
+ }
259
+ }
260
+ @objc func connectionFailed() {
261
+ NSObject.cancelPreviousPerformRequests(withTarget: self)
262
+ guard let callback = bluetoothCallback else { return }
263
+ bluetoothCallback = nil
264
+ bluetooth.stopSearchDevices()
265
+ bluetooth.disconnect()
266
+ callback(false)
267
+ }
268
+ }
269
+
270
+ var rfidReaderRequest: [String: Any] = [:]
271
+ var paCertificateCompletion: (([PKDCertificate]?) -> Void)?
272
+ var taCertificateCompletion: (([PKDCertificate]?) -> Void)?
273
+ var taSignatureCompletion: ((Data?) -> Void)?
274
+ var aaChallengeCompletion: ((String?) -> Void)?
275
+ var paceProtocolCompletion: ((RGLRFIDAccessControlPACE?) -> Void)?
276
+ var caProtocolCompletion: ((RGLRFIDAccessControlCA?) -> Void)?
277
+
278
+ let rfidDelegate = IDocReaderRFIDDelegate()
279
+ class IDocReaderRFIDDelegate: NSObject, RGLDocReaderRFIDDelegate {
280
+ // The SDK accepts nil callback results despite its nonnull annotations.
281
+ @objc(onRequestPACertificatesWithSerial:issuer:callback:)
282
+ func onRequestPACertificates(withSerial serialNumber: Data, issuer: PAResourcesIssuer, callback: @escaping ([PKDCertificate]?) -> Void) {
283
+ if rfidReaderRequest["paCertificates"] as? Bool == true {
284
+ paCertificateCompletion = callback
285
+ sendEvent(paCertificateCompletionEvent, ["serialNumber": serialNumber.encode(), "issuer": issuer.encode()])
286
+ } else {
287
+ paCertificateCompletion = nil
288
+ callback(nil)
289
+ }
290
+ }
291
+ @objc(onRequestTACertificatesWithKey:callback:)
292
+ func onRequestTACertificates(withKey keyCAR: String, callback: @escaping ([PKDCertificate]?) -> Void) {
293
+ if rfidReaderRequest["taCertificates"] as? Bool == true {
294
+ taCertificateCompletion = callback
295
+ sendEvent(taCertificateCompletionEvent, keyCAR)
296
+ } else {
297
+ taCertificateCompletion = nil
298
+ callback(nil)
299
+ }
300
+ }
301
+ @objc(onRequestTASignatureWithChallenge:callback:)
302
+ func onRequestTASignature(with challenge: TAChallenge, callback: @escaping (Data?) -> Void) {
303
+ if rfidReaderRequest["taSignature"] as? Bool == true {
304
+ taSignatureCompletion = callback
305
+ sendEvent(taSignatureCompletionEvent, challenge.encode())
306
+ } else {
307
+ taSignatureCompletion = nil
308
+ callback(nil)
309
+ }
310
+ }
311
+ func onRequestAAChallenge(challenge: String, callback: @escaping (String?) -> Void) {
312
+ if rfidReaderRequest["aaChallenge"] as? Bool == true {
313
+ aaChallengeCompletion = callback
314
+ sendEvent(aaChallengeCompletionEvent, challenge)
315
+ } else {
316
+ aaChallengeCompletion = nil
317
+ callback(nil)
318
+ }
319
+ }
320
+ @objc(onRequestPACEProtocolWithOptions:callback:)
321
+ func onRequestPACEProtocol(options protocols: [RGLRFIDAccessControlPACE], callback: @escaping (RGLRFIDAccessControlPACE?) -> Void) {
322
+ if rfidReaderRequest["paceProtocol"] as? Bool == true {
323
+ paceProtocolCompletion = callback
324
+ sendEvent(paceProtocolCompletionEvent, protocols.map { $0.encode() })
325
+ } else {
326
+ paceProtocolCompletion = nil
327
+ callback(nil)
328
+ }
329
+ }
330
+ @objc(onRequestCAProtocolWithOptions:callback:)
331
+ func onRequestCAProtocol(options protocols: [RGLRFIDAccessControlCA], callback: @escaping (RGLRFIDAccessControlCA?) -> Void) {
332
+ if rfidReaderRequest["caProtocol"] as? Bool == true {
333
+ caProtocolCompletion = callback
334
+ sendEvent(caProtocolCompletionEvent, protocols.map { $0.encode() })
335
+ } else {
336
+ caProtocolCompletion = nil
337
+ callback(nil)
338
+ }
339
+ }
340
+ func didChipConnected() {
341
+ sendEvent(rfidOnChipDetectedEvent)
342
+ }
343
+ func didReceivedError(_ errorCode: RFIDErrorCodes) {
344
+ sendEvent(rfidOnRetryReadChipEvent, ["code": errorCode.rawValue])
345
+ }
346
+ }
@@ -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,179 @@
1
+ import UIKit
2
+
3
+ public typealias Callback = (Any?) -> Void
4
+
5
+ // Args pass null arguments as nils, null elements in arrays as nils,
6
+ // but in maps keys with null values are removed.
7
+ var args: [Any?] = []
8
+ func args<T>(_ index: Int) -> T {
9
+ return argsNullable(index)!
10
+ }
11
+
12
+ func argsNullable<T>(_ index: Int) -> T? {
13
+ func fixNulls(_ value: Any?) -> Any? {
14
+ switch value {
15
+ case nil, is NSNull: return nil
16
+ case let dict as [String: Any]: return dict.compactMapValues(fixNulls)
17
+ case let array as [Any?]: return array.map(fixNulls)
18
+ default: return value
19
+ }
20
+ }
21
+ return fixNulls(args[index]) as! T?
22
+ }
23
+
24
+ extension Any? {
25
+ func toSendable() -> Any {
26
+ guard let self else { return NSNull() }
27
+ if self is [String: Any?] || self is [Any?] {
28
+ let data = try! JSONSerialization.data(withJSONObject: fixNulls(self), options: .prettyPrinted)
29
+ return String(data: data, encoding: .utf8)!
30
+ }
31
+ return self
32
+ }
33
+ }
34
+
35
+ func fixNulls(_ value: Any?) -> Any {
36
+ guard let value else { return NSNull() }
37
+ switch value {
38
+ // Native results can contain unavailable scores represented by NaN or infinity.
39
+ case let value as NSNumber where !value.doubleValue.isFinite: return -1
40
+ case let value as [String: Any?]:
41
+ var dict = [String: Any]()
42
+ for (k, v) in value { if let v { dict[k] = fixNulls(v) } }
43
+ return dict
44
+ case let value as [Any?]: return value.map { fixNulls($0) }
45
+ default: return value
46
+ }
47
+ }
48
+
49
+ extension NSObject {
50
+ static func allocate() -> NSObject {
51
+ return perform(NSSelectorFromString("alloc")).takeUnretainedValue() as! NSObject
52
+ }
53
+ static func emptyInit<T>() -> T {
54
+ return perform(NSSelectorFromString("new")).takeRetainedValue() as! T
55
+ }
56
+ }
57
+
58
+ extension String {
59
+ func selector() -> Selector {
60
+ return NSSelectorFromString(self)
61
+ }
62
+ }
63
+
64
+ func privateInit<T, Fn>(
65
+ _ allocated: NSObject,
66
+ _ selector: Selector,
67
+ _ function: Fn.Type,
68
+ _ call: (Fn) -> Unmanaged<AnyObject>?
69
+ ) -> T {
70
+ let f = unsafeBitCast(allocated.method(for: selector), to: function)
71
+ // init consumes the +1 from alloc and returns an owned result.
72
+ return call(f)!.takeRetainedValue() as! T
73
+ }
74
+
75
+ // MARK: - Converting
76
+
77
+ extension Data {
78
+ static func decode(_ it: Any?) -> Self? {
79
+ guard var it = it as? String else { return nil }
80
+ if it.hasPrefix("data:") {
81
+ guard let comma = it.firstIndex(of: ",") else { return nil }
82
+ it = String(it[it.index(after: comma)...])
83
+ }
84
+ return Self(base64Encoded: it)
85
+ }
86
+
87
+ func encode() -> String {
88
+ return self.base64EncodedString()
89
+ }
90
+ }
91
+
92
+ extension UIImage {
93
+ static func decode(_ it: Any?) -> Self? {
94
+ guard let data = Data.decode(it) else { return nil }
95
+ return Self(data: data)
96
+ }
97
+
98
+ func encode() -> String? {
99
+ return pngData()?.encode()
100
+ }
101
+ }
102
+
103
+ extension UIColor {
104
+ static func decode(_ it: Any?) -> Self? {
105
+ guard let it = it as? Int else { return nil }
106
+ let value = UInt32(truncatingIfNeeded: it)
107
+ guard value >= 0x100 else {
108
+ assertionFailure("Invalid color value: #\(String(value, radix: 16)). Expected #RGB, #ARGB, #RRGGBB, or #AARRGGBB")
109
+ return nil
110
+ }
111
+ // Preserve RGB/ARGB shorthand and RRGGBB/AARRGGBB formats.
112
+ let bits = value <= 0xFFFF ? 4 : 8
113
+ let mask: UInt32 = bits == 4 ? 0xF : 0xFF
114
+ func component(_ index: Int) -> CGFloat {
115
+ return CGFloat((value >> (index * bits)) & mask) / CGFloat(mask)
116
+ }
117
+ let alpha = value < (1 << (bits * 3)) ? 1 : component(3)
118
+ return Self(red: component(2), green: component(1), blue: component(0), alpha: alpha)
119
+ }
120
+ func encode() -> Int {
121
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
122
+ if !getRed(&r, green: &g, blue: &b, alpha: &a) {
123
+ if let comps = cgColor.components {
124
+ if comps.count == 2 { r = comps[0]; g = comps[0]; b = comps[0]; a = comps[1] }
125
+ else if comps.count >= 4 { r = comps[0]; g = comps[1]; b = comps[2]; a = comps[3] }
126
+ }
127
+ }
128
+ let argb = [a, r, g, b].reduce(UInt32(0)) { ($0 << 8) | UInt32(lroundf(Float($1 * 255))) }
129
+ return Int(argb)
130
+ }
131
+ }
132
+
133
+ extension UIFont {
134
+ static func decode(_ it: Any?) -> Self? {
135
+ guard let it = it as? [String: Any], let name = it["name"] as? String else { return nil }
136
+ return Self(name: name, size: it["size"] as? CGFloat ?? 0)
137
+ }
138
+ func encode() -> [String: Any?] {
139
+ return ["name": self.fontName, "size": self.pointSize]
140
+ }
141
+ }
142
+
143
+ public extension CGRect {
144
+ static func decode(_ it: Any?) -> Self {
145
+ guard let it = it as? [String: Any] else { return .zero }
146
+ let left = it["left"] as? CGFloat ?? 0
147
+ let top = it["top"] as? CGFloat ?? 0
148
+ return Self(x: left, y: top,
149
+ width: (it["right"] as? CGFloat ?? 0) - left,
150
+ height: (it["bottom"] as? CGFloat ?? 0) - top)
151
+ }
152
+ func encode() -> [String: Any?]? {
153
+ if self.origin.x == 0 && self.origin.y == 0 { return nil }
154
+ return [
155
+ "top": self.origin.y,
156
+ "left": self.origin.x,
157
+ "bottom": self.origin.y + self.size.height,
158
+ "right": self.origin.x + self.size.width,
159
+ ]
160
+ }
161
+ }
162
+
163
+ public extension CGPoint {
164
+ static func decode(_ it: Any?) -> Self {
165
+ guard let it = it as? [String: Any] else { return .zero }
166
+ return Self(x: it["x"] as? CGFloat ?? 0,
167
+ y: it["y"] as? CGFloat ?? 0)
168
+ }
169
+ func encode() -> [String: Any?] {
170
+ return ["x": self.x, "y": self.y]
171
+ }
172
+ }
173
+
174
+ public extension Error {
175
+ func encode() -> [String: Any?] {
176
+ let it = self as NSError
177
+ return ["code": it.code, "message": it.localizedDescription]
178
+ }
179
+ }
@@ -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