diff --git a/.dart_tool/package_config.json b/.dart_tool/package_config.json new file mode 100644 index 0000000000..82cdca9e1e --- /dev/null +++ b/.dart_tool/package_config.json @@ -0,0 +1,166 @@ +{ + "configVersion": 2, + "packages": [ + { + "name": "async", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/async-2.13.1", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "boolean_selector", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/boolean_selector-2.1.2", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "characters", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/characters-1.4.0", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "clock", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/clock-1.1.2", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "collection", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/collection-1.19.1", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "fake_async", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/fake_async-1.3.3", + "packageUri": "lib/", + "languageVersion": "3.3" + }, + { + "name": "flutter", + "rootUri": "file:///Users/administratorregula/development/flutter/packages/flutter", + "packageUri": "lib/", + "languageVersion": "3.8" + }, + { + "name": "flutter_test", + "rootUri": "file:///Users/administratorregula/development/flutter/packages/flutter_test", + "packageUri": "lib/", + "languageVersion": "3.8" + }, + { + "name": "leak_tracker", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/leak_tracker-11.0.2", + "packageUri": "lib/", + "languageVersion": "3.2" + }, + { + "name": "leak_tracker_flutter_testing", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/leak_tracker_flutter_testing-3.0.10", + "packageUri": "lib/", + "languageVersion": "3.2" + }, + { + "name": "leak_tracker_testing", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/leak_tracker_testing-3.0.2", + "packageUri": "lib/", + "languageVersion": "3.2" + }, + { + "name": "lints", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/lints-4.0.0", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "matcher", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/matcher-0.12.17", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "material_color_utilities", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/material_color_utilities-0.11.1", + "packageUri": "lib/", + "languageVersion": "2.17" + }, + { + "name": "meta", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/meta-1.17.0", + "packageUri": "lib/", + "languageVersion": "3.5" + }, + { + "name": "path", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/path-1.9.1", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "sky_engine", + "rootUri": "file:///Users/administratorregula/development/flutter/bin/cache/pkg/sky_engine", + "packageUri": "lib/", + "languageVersion": "3.8" + }, + { + "name": "source_span", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/source_span-1.10.2", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "stack_trace", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/stack_trace-1.12.1", + "packageUri": "lib/", + "languageVersion": "3.4" + }, + { + "name": "stream_channel", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/stream_channel-2.1.4", + "packageUri": "lib/", + "languageVersion": "3.3" + }, + { + "name": "string_scanner", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/string_scanner-1.4.1", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "term_glyph", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/term_glyph-1.2.2", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "test_api", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/test_api-0.7.7", + "packageUri": "lib/", + "languageVersion": "3.5" + }, + { + "name": "vector_math", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/vector_math-2.2.0", + "packageUri": "lib/", + "languageVersion": "3.1" + }, + { + "name": "vm_service", + "rootUri": "file:///Users/administratorregula/.pub-cache/hosted/pub.dev/vm_service-15.2.0", + "packageUri": "lib/", + "languageVersion": "3.5" + }, + { + "name": "flutter_document_reader_api", + "rootUri": "../", + "packageUri": "lib/", + "languageVersion": "3.1" + } + ], + "generator": "pub", + "generatorVersion": "3.10.0-290.4.beta", + "flutterRoot": "file:///Users/administratorregula/development/flutter", + "flutterVersion": "3.38.0", + "pubCache": "file:///Users/administratorregula/.pub-cache" +} diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md deleted file mode 100644 index ca40e33641..0000000000 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -name: Bug Report -about: Create a report to help us improve -title: "[BR] " -labels: bug -assignees: '' - ---- - -**Before Submitting, be sure to** -- [ ] Update to the latest stable version. -- [ ] Read and follow the guides described in the [documentation](https://docs.regulaforensics.com?utm_source=github). -- [ ] Try to reproduce in our demo project. -- [ ] Search for your issue in the existing GitHub issues. - -**Bug Description** - - -**Steps To Reproduce** - - -**Expected behavior** - - -**Screenshots** - - -**Environment:** - - Device: - - OS: - - OS version: - -**Additional context** - diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index bb2ed0f614..bc25558656 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: false contact_links: - - name: Regula Help Center + - name: Submit a request url: https://support.regulaforensics.com/hc/requests/new?utm_source=github - about: Please submit any requests here + about: Submit any requests to Regula Support Team diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md deleted file mode 100644 index 05181749e5..0000000000 --- a/.github/ISSUE_TEMPLATE/feature-request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature Request -about: Suggest an idea for this product -title: "[FR] " -labels: enhancement -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** - - -**Describe the solution you'd like** - - -**Describe alternatives you've considered** - - -**Additional context** - diff --git a/.gitignore b/.gitignore index e9dc58d3d6..9a864388ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,10 @@ .DS_Store -.dart_tool/ +test/json + +.dart_tool/ .packages .pub/ - build/ + +doc \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000..c680352df4 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,49 @@ +stages: + - test + - reports + +include: + - template: Jobs/SAST.gitlab-ci.yml + - template: Jobs/Secret-Detection.gitlab-ci.yml + - template: Jobs/Dependency-Scanning.gitlab-ci.yml + - local: .gitlab/report.yaml + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + inputs: + stage: reports + image: ubuntu:22.04 + ignore_vulnerabilities: "false" + sast_report_file: gl-sast-report.json + secret_detection_report_file: gl-secret-detection-report.json + dependency_scanning_report_file: gl-dependency-scanning-report.json + +trivy scan: + stage: test + image: aquasec/trivy + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + script: + - trivy fs --severity CRITICAL,HIGH,MEDIUM,LOW --ignore-unfixed --db-repository container-registry.regula.local:80/aquasecurity/trivy-db:2 --exit-code 1 . + +semgrep-sast: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + artifacts: + paths: + - gl-sast-report.json + +secret_detection: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + artifacts: + paths: + - gl-secret-detection-report.json + +gemnasium-dependency_scanning: + variables: + DS_MAX_DEPTH: -1 + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + artifacts: + paths: + - gl-dependency-scanning-report.json diff --git a/.gitlab/report.yaml b/.gitlab/report.yaml new file mode 100644 index 0000000000..6ebfab0bb4 --- /dev/null +++ b/.gitlab/report.yaml @@ -0,0 +1,75 @@ +spec: + inputs: + stage: + default: reports + image: + default: ubuntu:22.04 + ignore_vulnerabilities: + default: "false" + sast_report_file: + default: gl-sast-report.json + secret_detection_report_file: + default: gl-secret-detection-report.json + dependency_scanning_report_file: + default: gl-dependency-scanning-report.json +--- + +view reports: + image: $[[ inputs.image ]] + stage: $[[ inputs.stage ]] + variables: + IGNORE_VULNERABILITIES: $[[ inputs.ignore_vulnerabilities ]] + SAST_REPORT_FILE: $[[ inputs.sast_report_file ]] + SECRET_DETECTION_REPORT_FILE: $[[ inputs.secret_detection_report_file ]] + DEPENDENCY_SCANNING_REPORT_FILE: $[[ inputs.dependency_scanning_report_file ]] + RED: \033[0;31m + YELLOW: \033[1;33m + GREEN: \033[0;32m + NC: \033[0m + needs: + - job: semgrep-sast + artifacts: true + - job: secret_detection + artifacts: true + - job: gemnasium-dependency_scanning + artifacts: true + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + script: + - ls -la + - apt update && apt install -y jq + - | + for f in SAST_REPORT_FILE SECRET_DETECTION_REPORT_FILE DEPENDENCY_SCANNING_REPORT_FILE + do + if [[ -f "${!f}" ]] + then + echo -e "${GREEN}File ${!f} exists, adding report${NC}" + r=${f/%_FILE} + declare $r="$(cat ${!f} | jq 'select(.vulnerabilities != []).vulnerabilities')" + if [[ ! -z "${!r}" ]] + then + VULNERABILITIES_FOUND=true + echo -e "${RED}Found $r vulnerabilities${NC}" + echo "${!r}" + echo + fi + else + echo -e "${YELLOW}File ${!f} doesn't exist, skipping${NC}" + fi + done + + if [[ "$VULNERABILITIES_FOUND" == true ]] + then + if [[ "$IGNORE_VULNERABILITIES" == true ]] + then + echo -e "${GREEN}All found vulnerabilities were ignored due to IGNORE_VULNERABILITIES=true${NC}" + exit 0 + else + echo -e "${RED}Vulnerabilities found, please see reports above${NC}" + exit 1 + fi + fi + + echo -e "${GREEN}No vulnerabilities found${NC}" + + exit 0 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000000..1943b866cd --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Flutter", + "cwd": "example", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + } + ] +} \ No newline at end of file diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000000..d15db7ac9e --- /dev/null +++ b/AUTHORS @@ -0,0 +1,8 @@ +# Below is a list of people and organizations that have contributed +# to the Flutter project. Names should be added to the list like so: +# +# Name/Organization + +Regula +Pavel Masiuk + diff --git a/CHANGELOG.md b/CHANGELOG.md index 12d83aed4a..b6e90d0109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,436 +1,92 @@ +## 9.5.1277-rc +# 7.5.0 + +* Changes in `RecognizeConfig` class, see [migration guide](https://docs.regulaforensics.com/develop/doc-reader-sdk/migration/7-4-to-7-5/#mobile) +* [Document Reader SDK 7.5 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/7-5/) + +# 7.4.0 + +* [Document Reader SDK 7.4 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/7-4/) + +# 7.3.0 + +* [Document Reader SDK 7.3 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/7-3/) + +# 7.2.0 + +* Fixed the issue with incorrect selection of orientation in the `setOrientation` method. +* [Document Reader SDK 7.2 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/7-2/) + +# 7.1.0 + +* BREAKING CHANGE: whole DocumentReader plugin rewritten from scratch with focus on user experience and convenience. Migration instructions can be found [here](https://docs.regulaforensics.com/develop/doc-reader-sdk/migration/v6-to-v7/flutter/). + +* [Document Reader SDK 7.1 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/7-1/) + +# 6.9.0 + +* [Document Reader SDK 6.9 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-9/) + +# 6.8.0 + +* [Document Reader SDK 6.8 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-8/) + +# 6.7.0 + +* [Document Reader SDK 6.7 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-7/) + +# 6.6.0 + +* [Document Reader SDK 6.6 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-6/) + +# 6.5.0 + +* [Document Reader SDK 6.5 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-5/) + +# 6.4.0 + +* [Document Reader SDK 6.4 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-4/) + +# 6.3.0 + +* [Document Reader SDK 6.3 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-3/) + +# 6.2.0 + +* [Document Reader SDK 6.2 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-2/) + +# 6.1.0 + +* [Document Reader SDK 6.1 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-6-1/) + # 5.8.0 -#### API: - -* Added capability to load and process a PDF file or an image in the form of binary data -* Added the ability to change many new properties through processParams, and not through customParams only, as it was before -* Added the ability to disable automatic license renewal -* Added the ability to disable barcode parsing -* Changed processParams, most values are now objects -* Fixed memory leak when using the readRFID function -* Fixed the display of prompts while reading several pages of a document -* Fixed a problem with the display of the flashlight button -* Added new values to the `eVisualFieldType` parameter - * `FT_DLCLASSCODE_CD_FROM` - * `FT_DLCLASSCODE_CD_TO` - * `FT_DLCLASSCODE_CD_NOTES` - -#### Core: - -* Document detection and crop - * Multiple optimizations and improvements that reduce processing time and allow more precise cropping of the documents from an input image and better recognition - * Improvements of processing two sides of an ID card in one image - * Added support for Brazilian Driving Licenses format (unfolded) -* OCR - * Significantly improved recognition quality for Arabic, Chinese and Japanese - * Added correct support for perforation fonts used in the Philippines, Equatorial Guinea, Ireland, Poland - * Fixed issue with reading perforated numbers in Finland, Sweden -* MRZ - * Updated parsers: - * Albania ID card - * Cote d'Ivoire ID card - * Kenya Foreigner Certificate - * Korea passport - * Morocco ID card - * Netherlands’s passport - * Norway ID card - * Improved MRZ detection on complex backgrounds - * Fixed issue with ID1 2x30 format detection / parameters output -* Barcode - * Added new parsers: - * Argentina DL - * Bangladesh ID card - * Colombia ID card - * Honduras ID card - * Mexico DL - * Moldova Residence Permit - * Myanmar DL - * Nicaragua ID card - * Panama ID card - * Philippines DL - * Russian Federation housing and utilities bills - * Santa Lucia ID card - * Updated parsers: - * AAMWA (Issuer Identification Number added) - * Belarus ID card / Residence permit - * Jamaica Firearm License - * Rwanda ID card - * Togo ID card, Residence permit - * Minor fixes for 1D, 2D codes reading -* Text data parsing and validation - * Added parsing and conversion of the Taiwan calendar dates into Gregorian and creation of additional fields of the same type as original with LCID equal to 0 - * Added “customParams.convertCase” parameter, that may specify the desired conversion of text case in output results based on the dedicated enumeration. By default, text fields are returned in the original case as they are in the document - * Added “processParam.minimalHolderAge” parameter, that may specify minimum age threshold of document holder. If the calculated age is below this threshold, then age field validity and document validity will fail. By default, not set and restrictions are not applied - * Added possibility to specify the need of transliteration from Cyrillic to Latin for specific fields in the document template - * Added conversion from issuing authority code to its name for Belarus - * Fixed issue with field value mask used for OCR and parsing. Now they can be separated - * Fixed issue with “processParam.dateFormat” applied from the previous request if not set in consequent requests - * Fixed issue with transliteration of “ñ” in Peru documents - * Fixed issue with comparison of values from transliterated text fields from Arabic to Latin with original Latin fields. Now such transliterated fields are excluded from the comparison - * Fixed issue with Hijri dates conversion to the Gregorian calendar - * Fixed issue with Japanese dates conversion – original value was missing from results - * Fixed issue with partial comparison of the document numbers - * Fixed issue with names comparison when the visual field value is shorter than in MRZ (truncated/abbreviated) - * Updated stop words list for names -* Image QA - * Updated NN for focus detection (accuracy, size, and inference time improved) - * Updated NN for moiré detection (accuracy, size, and inference time improved) -* Authenticity - * Fixed issue with false luminescence check which led to false rejections - * Fixed issue with hologram detection in some documents -* Added new NN for face detection with improved detection accuracy and speed -* Fixed issue with not reading CAN from ID cards on normal scans when only MRZ is enabled (without Visual OCR) -* Fixed issue with requesting more than one additional page for ID cards in some cases (ID1, ID2) -* Fixed issue with the processing of some PDF files that led to incorrect results or crashes -* Fixed performance issue with performing face detection and MRZ reading twice in case the original image is already cropped, but the processParam.alreadyCropped option is not set -* Fixed performance issue with processing multiple pages in one request that led to increased processing time depending on the order of the submitted pages -* Fixed issue with no returning RFID reading results in case session saving was enabled -* Fixed issue with reducing cropped image resolution when capturing UV and IR on 7310 devices -* Fixed issue with incorrect behavior if input images in base64 in /process request contain headers with description of contents like "data:image/jpeg;base64", etc -* Fixed issue with not clearing results of the previous scan when it was submitted in encrypted format (mobile capture session for reprocessing on the server) -* Fixed issue when processing multiple pages of unknown documents and not all of them were in output results -* Fixed issue with incorrect elapsedTime value in output results -* Fixed significant performance issue with loading input data from JSON -* Fixed significant performance issue with output results into JSON -* Fixed performance and high memory usage issue with cropping of graphical fields -* Fixed performance issue when processing some cases of PDF files -* Fixed issue with losing connection to 3rd party devices when portrait comparison is called -* Fixed issue with log output format and depth setting -* Code quality improved with lots of small issues fixed - -#### Core RFID SDK: - -* Implemented capability to perform BAC after PACE was performed unsuccessfully -* Fixed issue with using extended length commands when performing AA when using key/signature length of 229 bytes - -#### Licensing: - -* Implemented capability to hide Regula logo with online transaction based mobile SDK license -* Implemented capability to automatically update an expired license on mobile via a request to our licensing service when using an offline static license in the mobile app. This is very useful, as the application does not have to be recompiled for updating the license only on its expiration. In case renewed offline license was issued for this specific application ID / bundleID, this new license will be automatically downloaded and used on SDK initialization. This can be disabled by setting a specific property in mobile SDK before initialization - -#### Database: - -* Fixed issues in multiple (over 100) document templates for better quality results -* Changed dType to diPassportPage value in passport other page templates, except for main biographical data page -* 248 countries and territories / 9813 documents included -* 166 new documents added -* For details see Supported documents list +* [Document Reader SDK 5.8 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-8/) # 5.7.0 -#### API: - -* Added restart of the process on the camera switch during the scanning process -* Added restart of the process on the camera orientation change during the scanning process. The orientation cannot be changed after the processing of at least one page is completed. -* Added the ability to receive events about the connection to the RFID chip and errors in the process of reading the chip -* Android: - * Added the ability to provide the database as a binary file during SDK initialization - * Fixed a crash on devices that do not have Google Play Services - * Removed `android.permission.INTERNET` from framework manifest. Now, if necessary, this permission should be set at the application level -* iOS: - * Implemented delivery of SDK in “.xcframework” format - * Added the `RGLCameraViewControllerActionProcessWhiteFlashLight` event notifying that the flash was turned on forcibly - * All `@import` native libraries have been replaced with `#import` -* Added new values to the [`eVisualFieldType`](https://docs.regulaforensics.com/flutter/enumerations/evisualfieldtype) parameter - -#### Core: - -* OCR - * Significantly improved recognition quality for Arabic, Western European, Chinese and Japanese - * Implemented correct reading for Arabic and Persian numbers \(correct Unicode symbols in output values\) - * Improved reading of perforated document numbers in different countries \(new fonts supported\) - * Fixed issue with not returning required fields on timeout. Now they are returned anyway, with empty values if the fields were not read -* MRZ - * Updated parsers: - * Belarus passport - * Comoros ID card - * Dominican Republic ID card - * Jordan ID card - * Russian visa - * Serbian ID card - * Switzerland DL - * Thailand passport -* Barcode - * Added new parsers: - * Belgium ID card - * Costa Rica Child ID card - * ECOWAS Id card - * India AADHAAR ID card - * Viet Nam ID card - * Improved processing time for 1D, 2D codes - * Fixed issue with CODE128 wrong treated checksums in rare cases -* Text data parsing and validation - * Added parsing and conversion of the Japanese calendar dates into Gregorian and creation of additional fields of the same type as original with LCID equal to 0 - * Added parsing and conversion of the Islamic calendar dates into Gregorian and creation of additional fields of the same type as original with LCID equal to 0 - * Added capability to shift the expiry date when calculating the document expiration status. Set the [`customParams "shiftExpiryDate"`](https://docs.regulaforensics.com/flutter/custom-settings#custom-params) parameter for shifting the date of expiry into the future or past for the number of months specified. This is useful, for example, in some cases when the document might be still valid for some period after the original expiration date to prevent negative validity status for such documents. Shifting the date to the past will set negative validity for the documents that is about to expire in the specified number of months - * Added transliteration from Arabic letters to Latin according to ICAO and creation of additional fields of the same type as original with LCID equal to 0 - * Added transliteration from Arabic and Persian numbers to ASCII numbers and creation of additional fields of the same type as original with LCID equal to 0 - * Added parsing of data from DG11 in eDL of Netherlands and extraction of the BSN number as a separate field - * Fixed issue with Vietnamese character uppercase conversion and further validation -* Image QA - * Fixed issue with glare detection on the whole portrait area instead of the face area -* Authenticity - * Fixed issue with element coordinates in output for image patterns check - * Fixed issue with UV dull paper check parameters for different documents in one series - * Fixed issue with hologram detection in some documents -* Added capability to guarantee that output image will contain correct MRZ on it in series process mode \(on mobile, for example\). Set the [`customParams "forceReadMrzBeforeLocate"`](https://docs.regulaforensics.com/flutter/custom-settings#custom-params)Boolean flag to True to enable this logic. False by default -* Added capability to provide in [`customParams`](https://docs.regulaforensics.com/flutter/custom-settings#custom-params) JSON parameters “config” object, that may contain specific settings on a per-document basis. Currently, it is possible to disable some of the authenticity checks for the listed document IDs -* Fixed issue with incorrect DPI detection in some rare cases -* Fixed issue with the expectance of additional pages for two-sided documents when both sides are already scanned -* Fixed issue with non-zero page index for one-page document results -* Fixed issue with random page indexes on multiple pages processing -* Fixed issue with rare crashes when processing specific images \(very small images\) -* Code quality improved with lots of small issues fixed -* RFID - * Implemented sending of IS certificate as part of the TA\_Signature request - * Improved the algorithm of building certificate chains for the TA process where multiple certificates from different chains are stored in one folder - * Fixed issue with TCC communication that led to exception on connection - -**Licensing:** - -* Fixed issue with the license for bank card reading functionality only - -#### Database: - -* Fixed issues in multiple document templates for better quality results -* 248 countries and territories / 9647 documents included -* 215 new documents added -* For details see [Supported documents list](https://downloads.regulaforensics.com/work/SDK/SDK%20Release%20Notes%20%28en%29.pdf) +* [Document Reader SDK 5.7 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-7/) # 5.6.0 -**API**: -* Implemented ability to read multiple pages of a document in manual mode \([`manualMultipageMode`](https://docs.regulaforensics.com/flutter/custom-settings#scanning-modes)\) -* Implemented ability to change the background for the [status message](https://docs.regulaforensics.com/flutter/custom-settings#status-message) on the scanning screen -* Fixed stopRFIDReader function -* Fixed an issue with saving video of the scanning process. Now the video is automatically saved to a separate subfolder -* Added new values to the [`eVisualFieldType`](https://docs.regulaforensics.com/flutter/enumerations/evisualfieldtype) parameter - * `FT_DLCLASSCODE_NT_FROM` - * `FT_DLCLASSCODE_NT_TO` - * `FT_DLCLASSCODE_NT_NOTES` - * `FT_DLCLASSCODE_TN_FROM` - * `FT_DLCLASSCODE_TN_TO` - * `FT_DLCLASSCODE_TN_NOTES` - * `FT_DLCLASSCODE_D3_FROM` - * `FT_DLCLASSCODE_D3_TO` - * `FT_DLCLASSCODE_D3_NOTES` - -**Core**: -* Document detection and crop - * Multiple improvements that allow more precise cropping of the documents from input image and better recognition - * Added "processParam.documentAreaMin" parameter to set area percent that document should fill on the image to be considered as document. Allowed values from 0 to 1. Default value 0.3 - * Added “processParam.forceDocFormat” parameter to force use of specified document format when locating and recognizing document to reduce the number of candidates - * Fixed issue with detection of ID card on A4 flatbed scanner produced image with incorrect resolution set -* OCR - * Significantly improved recognition quality for Korean, Hebrew, and Cyrillic alphabets. -* MRZ - * Added new parsers: - * Switzerland DL. - * Updated parsers: - * Bulgaria ID card - * Croatia ID card - * Ecuador ID card - * Netherlands passport - * Implemented 2x30 MRZ detection and reading for Switzerland DL - * Fixed issue with coordinates for rotated MRZ -* Barcode - * Added new parsers: - * France ID card - * Updated parsers: - * Guatemala passport - * Implemented mask check for data from 1D barcodes - * Fixed issue with base64 decoding from barcodes data - * Fixed issue with absence of data parsing results from images with low resolution - * Fixed issue with parsing data from multiple barcodes in one document -* Text data parsing and validation - * Fixed issue with document number validation for Ireland DL - * Fixed issue with generating full name when same parts of the name are present on different sides of the ID card -* Image QA - * Added screen captured images detection as a separate check - * Added portrait occlusion detection as a separate check - * Improved algorithm for detection of colorless images -* Authenticity - * Added new check of the halo around the portrait in UV that can be result of photo substitution. - * Improved fibers detection and validation algorithms - * Fixed issue with luminescence mask validation for some cases - * Implemented rotation of output results so the document image is correctly oriented - * Fixed issue with some PDF files processing led to crash in some rare cases - * Fixed issue with processing of multiple pages led to different results based on page order - * Fixed issue with symbols visibility on mobile platforms, that lead to incompatibility with other frameworks that use same dependencies as OpenSSL - * Code quality improved with lots of small issues fixed -* RFID - * Implemented re-processing of the previously obtained session from mobile or desktop station for validating PA and further processing data on the server side - * Fixed issue with TA status calculation based on EF.CVCA ReadingStatus for both ePassport and eDL - * Fixed issue with duplicated nodes instead of the array in JSON results generation for eRFID\_ResultType.RFID\_ResultType\_RFID\_BinaryData - -**Licensing:** -* Online transaction-based license usage implemented on mobile. Now it is possible to use same online license on mobile and on the server -* Application ID/platform/OS agnostic license implemented on mobile. This special kind of license allows running SDK on mobile for capturing data as usual but delivers encrypted results package including document images and chip reading data for further processing on the server side with separate online transaction-based license. This allows easy redistribution of the SDK inside custom mobile SDKs without licensing management efforts and issues -* Regula Reader device-based application ID agnostic offline license for Android use implemented. In this case device is storing the license, and license is checked by SDK querying device presence and reading the license from it on initialization - -**Database**: -* Templates updated in whole database where applicable: - * Rotation angle to get correct document display position - * Fibers description with regards to updated algorithms - * Nationality field output enabled for ID cards - * Supported documents list now contains details on image patterns in which lights are checked for each document template - * 248 countries and territories / 9432 documents included - * 101 new documents added - * For details see Supported documents + +* [Document Reader SDK 5.6 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-6/) # 5.5.0 -**API**: -* Added the ability to [save a video](https://docs.regulaforensics.com/flutter/custom-settings#video-settings) of the document recognition process. -* Added the ability to use the [`FullAuth`](https://docs.regulaforensics.com/flutter/scenarios) scenario in multipage mode. -* Added the ability to set the mode via [`checkRequiredTextFields`](https://docs.regulaforensics.com/flutter/custom-settings#filters) parameter where field validity would be set to failed if the required field value is missing in Visual OCR. -* Completely redesigned camera focus control implementation -* Added new values to the [`eVisualFieldType`](https://docs.regulaforensics.com/flutter/enumerations/evisualfieldtype)parameter - * `FT_DLCLASSCODE_CA_NOTES` - * `FT_CITIZENSHIP_STATUS` - * `FT_MILITARY_SERVICE_FROM` - * `FT_MILITARY_SERVICE_TO` -* `DocumentReaderResults` now contains an array of `DocumentPosition`, `BarcodePosition`, `MRZPosition`, and `ImageQualityGroup` items with information for each document page that was read, where available -* Added interactive documentation inside the SDK \(Option + tap in XCode\) -* `getTextFieldValueByType` function call with LCID parameter returns nil if the value with such LCID is not presented in the results -* RFID chip reading works correctly without first scanning the document, if the MRZ or CAN key is pre-set -* Fixed the operation of the completion block in the `stopRFIDReader` function -* Fixed the rendering position of the [help animation](https://docs.regulaforensics.com/flutter/custom-settings#animation) and the [multipage mode animations](https://docs.regulaforensics.com/flutter/custom-settings#animation) -* Fixed the position of custom statuses \([`status`](https://docs.regulaforensics.com/flutter/custom-settings#status-message) and [`resultStatus`](https://docs.regulaforensics.com/flutter/custom-settings#result-status-message)\), now they are displayed in the center -* Fixed issue with [`Capture`](https://docs.regulaforensics.com/flutter/scenarios) scenario when using the 1120 device - -**Core**: -* Document detection and crop - * Fixed issue with locating already cropped documents in [`FullAuth`](https://docs.regulaforensics.com/flutter/scenarios) scenario - * Fixed issue with locating documents on backgrounds with multiple lines aligned with the document edges - * Fixed issue with locating two sides of ID card on one image - * Fixed issue with locating documents on non-contrast backgrounds -* OCR - * Greatly improved bank cards OCR - * Improved OCR of perforated fields -* MRZ - * Added new parsers: - * Pakistan ID card - * Updated parsers: - * Austrian residence permit - * EU residence permit - * France ID card - * Kazakhstan Residence permit - * Malta ID card - * Norway ID card - * Poland ID card - * Fixed issue with incorrect MRZ detection on some images - * Fixed issue with incorrect symbol probabilities in some cases - * Fixed issue with 1-line MRZ in DL parsing -* Barcode - * Added new parsers: - * Belarus ID card - * Colombia DL - * France ID card - * Ghana Voter card - * Nigeria Voter card - * Pakistan ID card - * Updated parsers: - * Korea Alien registration card - * Moldova ID card - * Fixed issue with code types for recognition filter -* Text data parsing and validation - * Added capability to verify date of issue validity based on document template activity term - * Added capability for Italy tax code validation - * Added capability for comparison of the field value from one source with abbreviature of this value from another source - * Added XXK nationality code for Kosovo - * Fixed issue with comparison between MRZ and Visual for document without expiration date - * Fixed issue with probabilities for transliterated fields: they will have probability of original field - * Fixed issue with German Ü letter transliteration - * Fixed issue with composite surnames comparison where last part is missing in MRZ - * Fixed issue with measure units on locale change - * Fixed issue with `FT_DATE_FIRST_RENEWAL` and `FT_DATE_SECOND_RENEWAL`fields validity -* Image QA - * Improved focus detection NN - * Improved algorithm for detection of colorless images -* Authenticity - * Added new algorithm for obtaining correct IR image on 7310 devices - * Implemented correct processing of all authenticity checks in FullAuth scenario - * Improved IR visibility check for photo area, where grayscale photo should look the same in visible and IR - * Improved variable patterns check for documents with a lot of UV luminescence - * Fixed issue with hologram checks on series of frames -* Added support of reading data from both sides of bank cards -* Added support of single page \(back page\) data bank cards -* Improved processing of bank cards: now it is payment system agnostic -* Fixed issue with input images page indexes. Now they will be set automatically and correctly if missing -* Code quality improved with lots of small issues fixed -* RFID - * Fixed issue with different `.ldif` format support - * Fixed issue with parsing certificates on different platforms - -**Database**: -* Added to templates in whole database where applicable: - * Perforated text fields - * Hologram areas and checks - * Activity term for template - * Extended description for visible patterns - * Barcode format check parameters - * IR visibility for portraits, where they are the same in visible and IR -* 248 countries and territories / 9331 documents included -* 179 new documents added + +* [Document Reader SDK 5.5 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-5/) # 5.4.0 -**API**: -- Added document authentication based on the detection of the presence of a hologram -- Updated document image for NFC chip reading activity animation for USA passport which can be read only when passport book is open -- Added the ability to disable checking for the presence of a flashlight on the device -- Added new values to the `eCheckDiagnose` parameter: - - `PHOTO_WHITE_IR_DONT_MATCH` - - `FIELD_POS_CORRECTOR_GLARES_IN_PHOTO_AREA` - - `HOLOGRAM_FRAMES_IS_ABSENT` - - `HOLOGRAM_HOLO_FIELD_IS_ABSENT` - - `FINGERPRINTS_COMPARISON_MISMATCH` - - `HOLO_PHOTO_FACE_NOT_DETECTED` - - `HOLO_PHOTO_FACE_COMPARISON_FAILED` - - `HOLO_PHOTO_FACE_GLARE_IN_CENTER_ABSENT` - - `HOLO_ELEMENT_SHAPE_ERROR` - - `ALGORITHM_STEPS_ERROR` - - `HOLO_AREAS_NOT_LOADED` - - `FINISHED_BY_TIMEOUT` - -- Updated enumeration values of `eImageQualityCheckType` -- Updated `DocumentReaderException` enumeration values related to licensing errors that may occur during initialization -- Fixed an issue with incorrect camera focus in camera activity -- Fixed an issue in the `zoomFactor` property. Now when setting a value above the maximum allowed value, the camera will be zoomed to the maximum available value for this camera - -**Core**: - -- Document detection and crop - - Added Boolean flag `processParam.fastDocDetect` to shorten the list of candidates to process during document detection in a single image process mode. Enabled by default. This solves the issue introduced in 5.2, that lead to significantly longer processing times on the images with specific backgrounds - - Improved ID2 MRZ documents cropping in some cases -- OCR - - Added support for Amharic (fidäl / Ephiopian) - - Added support for perforated numbers OCR (different fonts, straight and mirror) - - Added Boolean flag `processParam.checkRequiredTextFields`. When enabled, each field in template will be checked for value presence and if the field is marked as required, but has no value, it will have "error" in validity status. Disabled by default - - Added Boolean flag `processParam.updateOCRValidityByGlare`. When enabled, OCR field validity will be updated with | tr_GlaresOnField value, if there is a glare over the text field on the image. Disabled by default - - Improved Latin NN - - Improved Hebrew NN -- Barcode - - Updated Peru ID Card parser - - Fixed issue with multiple pages processing -- Text data parsing and validation - - Implemented conversion from ROC dates (Minguo) into Gregorian - - Fixed issue with DL class field comparison between barcode and visual - - Fixed issue with incorrect validity for dates in Hijri -- Image QA - - Added new Resolution assessment check. Should be above threshold (150 ppi), otherwise the check will fail. Can be set via `processParam.imageQA.dpiThreshold` - - Added new Perspective angle assessment check. Should be below threshold (5 degrees), otherwise the check will fail. Can be set via `processParam.imageQA.angleThreshold` - - Added new Documents bounds inside the image check. All document corners should be inside the image, otherwise the check will fail -- Authenticity - - Added support for hologram presence detection by analysis of multiple frames - - Improved patterns check for visible and IR light images - - Improved patterns check for Russian Federation domestic passport - - Fixed issue with AV on specific images in IR visibility check -- Fixed issue with 1- and 8-bit images processing -- Code quality improved with lots of small issues fixed - -**Database**: -- 246 countries and territories / 9152 documents included -- 193 new documents added -- For details see [Supported documents list](https://downloads.regulaforensics.com/work/SDK/doc/AllDocs/Documents%20List.xls) + +* [Document Reader SDK 5.4 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-4/) # 5.3.0 -Flutter plugin for reading and validation of identification documents based on the Regula Document Reader SDK. + +* [Document Reader SDK 5.3 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-3/) + +# 5.2.0 + +* [Document Reader SDK 5.2 Release Notes](https://docs.regulaforensics.com/develop/doc-reader-sdk/release-notes/doc-reader-release-notes-5-2/) + +# 0.0.1 + +* Initial Release diff --git a/README.md b/README.md index c6566b9ca6..4dcb4460c9 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,13 @@ -# Regula Document Reader (Flutter) -Regula Document Reader SDK allows you to read various kinds of identification documents, passports, driving licenses, ID cards, etc. All processing is performed completely _**offline**_ on your device. No any data leaving your device. +# Regula Document Reader plugin for Flutter + -You can use native camera to scan the documents or image from gallery for extract all data from it. +[![pub package](https://img.shields.io/pub/v/flutter_document_reader_api.svg)](https://pub.dev/packages/flutter_document_reader_api) -This repository contains the source code of the Document Reader API, and the sample application that demonstrates the _**API**_ calls you can use to interact with the Document Reader library. - -# Contents -* [How to build demo application](#how-to-build-demo-application) - * [Troubleshooting license issues](#troubleshooting-license-issues) -* [Documentation](#documentation) -* [Additional information](#additional-information) - -## How to build demo application -1. Visit [client.regulaforensics.com](https://client.regulaforensics.com) to get a trial license (`regula.license` file). The license creation wizard will guide you through the necessary steps. -2. Download or clone this repository using the command `git clone https://github.com/regulaforensics/DocumentReader-Flutter.git`. -3. Copy the `regula.license` file to the `example/assets` folder. -4. Run the following commands in Terminal: -```bash -$ cd example -# Install packages -$ flutter pub get -# Check that supported devices are running -$ flutter devices -# Run the app -$ flutter run -``` - -### Troubleshooting license issues -If you have issues with license verification when running the application, please verify that next is true: -1. The OS, which you use, is specified in the license (e.g., Android and/or iOS). -2. The license is valid (not expired). -3. The date and time on the device, where you run the application, are valid. -4. You use the latest release version of the Document Reader SDK. -5. You placed the `license` into the correct folder as described [here](#how-to-build-demo-application). +Document Reader allows you to read various kinds of identification documents, passports, driving licenses, ID cards, etc. All processing is performed completely offline on your device. This plugin makes possible to use it with flutter. ## Documentation -You can find documentation on API [here](https://docs.regulaforensics.com/develop/doc-reader-sdk/mobile/flutter). - -## Additional information -If you have any technical questions, feel free to [contact](mailto:dev.support@regulaforensics.com) us or create issue [here](https://github.com/regulaforensics/DocumentReader-Flutter/issues). +* [Documentation](https://docs.regulaforensics.com/develop/doc-reader-sdk/mobile) +* [API Reference](https://pub.dev/documentation/flutter_document_reader_api) -To use our SDK in your own app you need to [purchase](https://pipedrivewebforms.com/form/394a3706041290a04fbd0d18e7d7810f1841159) a commercial license. +## Support +If you have any technical questions, feel free to [contact](mailto:support@regulaforensics.com) us or create issues [here](https://github.com/regulaforensics/DocumentReader-Flutter/issues). diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000000..cf16386eb6 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:lints/core.yaml +analyzer: + errors: + deprecated_member_use_from_same_package: ignore diff --git a/android/build.gradle b/android/build.gradle index 2a87e7f600..3bec7c6b2e 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -1,36 +1,54 @@ +rootProject.allprojects { + repositories { + google() + mavenCentral() + maven { + url "https://maven.regulaforensics.com/RegulaDocumentReader/Stage" + } + } +} + apply plugin: 'com.android.library' -apply plugin: 'org.jetbrains.kotlin.android' +apply plugin: 'kotlin-android' android { - // Conditional for compatibility with AGP <4.2. - if (project.android.hasProperty("namespace")) { - namespace 'io.flutter.plugins.regula.documentreader.flutter_document_reader_api' - } - compileSdkVersion 34 + namespace 'com.regula.plugin.documentreader' + compileSdk 36 defaultConfig { - minSdkVersion 21 + minSdk 24 } + compileOptions { - sourceCompatibility JavaVersion.VERSION_17 - targetCompatibility JavaVersion.VERSION_17 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = '11' } -} -rootProject.allprojects { - repositories { - google() - mavenCentral() - maven { - url "https://maven.regulaforensics.com/RegulaDocumentReader" + dependencies { + implementation('com.regula.documentreader:api:9.5.13002') { + transitive = true } + + testImplementation 'junit:junit:4.13.2' + testImplementation 'androidx.test:core:1.5.0' + testImplementation 'org.robolectric:robolectric:4.10.3' + testImplementation 'org.json:json:20180813' + testImplementation 'org.skyscreamer:jsonassert:1.5.1' } -} -dependencies { - //noinspection GradleDependency - implementation('com.regula.documentreader:api:6.9.9406') { - transitive = true + testOptions { + unitTests { + includeAndroidResources = true + } + unitTests.all { + testLogging { + events "passed", "skipped", "failed", "standardOut", "standardError" + outputs.upToDateWhen { false } + showStandardStreams = true + } + } } - implementation 'androidx.core:core-ktx:1.10.1' } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 84337ad35f..0000000000 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml index 6a59960647..227314eeb7 100644 --- a/android/src/main/AndroidManifest.xml +++ b/android/src/main/AndroidManifest.xml @@ -1,9 +1 @@ - - - - - - - - + \ No newline at end of file diff --git a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/BluetoothUtil.kt b/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/BluetoothUtil.kt deleted file mode 100644 index 08e4960a05..0000000000 --- a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/BluetoothUtil.kt +++ /dev/null @@ -1,108 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api - -import android.Manifest.permission.* -import android.annotation.SuppressLint -import android.app.Activity -import android.bluetooth.BluetoothAdapter -import android.content.ComponentName -import android.content.Intent -import android.content.ServiceConnection -import android.content.pm.PackageManager.PERMISSION_GRANTED -import android.os.Build -import android.os.IBinder -import android.provider.Settings -import androidx.annotation.RequiresPermission -import androidx.core.app.ActivityCompat.requestPermissions -import androidx.core.content.ContextCompat.checkSelfPermission -import com.regula.documentreader.api.ble.BLEWrapper -import com.regula.documentreader.api.ble.BleWrapperCallback -import com.regula.documentreader.api.ble.RegulaBleService -import com.regula.documentreader.api.internal.permission.BluetoothPermissionHelper.BLE_ACCESS_PERMISSION -import com.regula.documentreader.api.internal.permission.BluetoothSettingsHelper.isBluetoothEnabled -import com.regula.documentreader.api.internal.permission.BluetoothSettingsHelper.isLocationServiceEnabled - -class BluetoothUtil { - companion object { - private const val REQUEST_ENABLE_LOCATION = 196 - private const val REQUEST_ENABLE_BT = 197 - - @SuppressLint("StaticFieldLeak") - var bleManager: BLEWrapper? = null - - @RequiresPermission("android.permission.BLUETOOTH_CONNECT") - private fun requestEnableBle(activity: Activity) { - val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) - activity.startActivityForResult(enableIntent, REQUEST_ENABLE_BT) - } - - private fun requestEnableLocationService(activity: Activity) { - val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) - activity.startActivityForResult(myIntent, REQUEST_ENABLE_LOCATION) - } - - // requestEnableBle() is called after a check for permission - @SuppressLint("MissingPermission") - fun isBlePermissionsGranted(activity: Activity): Boolean { - if (!isLocationServiceEnabled(activity)) { - requestEnableLocationService(activity) - return false - } - deniedBluetoothPermissions(activity)?.let { - requestPermissions(activity, it, BLE_ACCESS_PERMISSION) - return false - } - if (!isBluetoothEnabled(activity)) { - requestEnableBle(activity) - return false - } - return true - } - - private fun deniedBluetoothPermissions(activity: Activity): Array? { - val result = mutableListOf() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - result.addAll(deniedBluetoothPermission(activity, BLUETOOTH_SCAN)) - result.addAll(deniedBluetoothPermission(activity, BLUETOOTH_CONNECT)) - } else - result.addAll(deniedBluetoothPermission(activity, ACCESS_FINE_LOCATION)) - return result.let { if (it.size > 0) it.toTypedArray() else null } - } - - private fun deniedBluetoothPermission( - activity: Activity, - permission: String - ): Array { - if (checkSelfPermission(activity, permission) != PERMISSION_GRANTED) - return arrayOf(permission) - return arrayOf() - } - - fun startBluetoothService( - activity: Activity, - onConnected: (Boolean) -> Unit, - onDisconnected: () -> Unit, - onReady: () -> Unit - ) { - val bleIntent = Intent(activity, RegulaBleService::class.java) - activity.startService(bleIntent) - - activity.bindService(bleIntent, object : ServiceConnection { - override fun onServiceConnected(name: ComponentName, service: IBinder) { - bleManager = (service as RegulaBleService.LocalBinder).service.bleManager - val isBleManagerConnected = bleManager?.isConnected == true - onConnected(isBleManagerConnected) - if (!isBleManagerConnected) { - bleManager?.addCallback(object : BleWrapperCallback() { - override fun onDeviceReady() { - bleManager!!.removeCallback(this) - onReady() - } - }) - } - } - - override fun onServiceDisconnected(name: ComponentName) = onDisconnected() - }, 0) - } - } -} \ No newline at end of file diff --git a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/FlutterDocumentReaderApiPlugin.java b/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/FlutterDocumentReaderApiPlugin.java deleted file mode 100644 index 634bd9d886..0000000000 --- a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/FlutterDocumentReaderApiPlugin.java +++ /dev/null @@ -1,1194 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api; - -import static com.regula.documentreader.api.DocumentReader.Instance; - -import static io.flutter.plugins.regula.documentreader.flutter_document_reader_api.Helpers.*; -import static io.flutter.plugins.regula.documentreader.flutter_document_reader_api.JSONConstructor.*; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.LocaleManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.nfc.NfcAdapter; -import android.nfc.tech.IsoDep; -import android.os.Build; -import android.os.Handler; -import android.os.LocaleList; -import android.os.Looper; -import android.util.Base64; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.lifecycle.Lifecycle; -import androidx.lifecycle.LifecycleEventObserver; - -import com.regula.documentreader.api.completions.ICheckDatabaseUpdate; -import com.regula.documentreader.api.completions.IDocumentReaderCompletion; -import com.regula.documentreader.api.completions.IDocumentReaderInitCompletion; -import com.regula.documentreader.api.completions.IDocumentReaderPrepareCompletion; -import com.regula.documentreader.api.completions.rfid.IRfidPKDCertificateCompletion; -import com.regula.documentreader.api.completions.rfid.IRfidReaderCompletion; -import com.regula.documentreader.api.completions.rfid.IRfidReaderRequest; -import com.regula.documentreader.api.completions.rfid.IRfidTASignatureCompletion; -import com.regula.documentreader.api.completions.rfid.ITccParamsCompletion; -import com.regula.documentreader.api.enums.DocReaderAction; -import com.regula.documentreader.api.errors.DocReaderRfidException; -import com.regula.documentreader.api.errors.DocumentReaderException; -import com.regula.documentreader.api.internal.core.CoreScenarioUtil; -import com.regula.documentreader.api.internal.params.ImageInputParam; -import com.regula.documentreader.api.internal.parser.DocReaderResultsJsonParser; -import com.regula.documentreader.api.params.BleDeviceConfig; -import com.regula.documentreader.api.params.DocReaderConfig; -import com.regula.documentreader.api.params.ImageInputData; -import com.regula.documentreader.api.params.rfid.PKDCertificate; -import com.regula.documentreader.api.params.rfid.authorization.PAResourcesIssuer; -import com.regula.documentreader.api.params.rfid.authorization.TAChallenge; -import com.regula.documentreader.api.results.DocumentReaderGraphicField; -import com.regula.documentreader.api.results.DocumentReaderNotification; -import com.regula.documentreader.api.results.DocumentReaderResults; -import com.regula.documentreader.api.results.DocumentReaderTextField; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import io.flutter.embedding.engine.plugins.FlutterPlugin; -import io.flutter.embedding.engine.plugins.activity.ActivityAware; -import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; -import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference; -import io.flutter.plugin.common.EventChannel; -import io.flutter.plugin.common.MethodCall; -import io.flutter.plugin.common.MethodChannel; -import io.flutter.plugin.common.MethodChannel.MethodCallHandler; -import io.flutter.plugin.common.MethodChannel.Result; - -@SuppressWarnings({"unchecked", "NullableProblems", "ConstantConditions", "RedundantSuppression", "deprecation"}) -public class FlutterDocumentReaderApiPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware { - private Activity activity; - private ArrayList args; - private boolean backgroundRFIDEnabled = false; - private int databaseDownloadProgress = 0; - - private IRfidPKDCertificateCompletion paCertificateCompletion; - private IRfidPKDCertificateCompletion taCertificateCompletion; - private IRfidTASignatureCompletion taSignatureCompletion; - - private EventChannel.EventSink eventDatabaseProgress; - private EventChannel.EventSink eventCompletion; - - private EventChannel.EventSink rfidOnProgressEvent; - private EventChannel.EventSink rfidOnChipDetectedEvent; - private EventChannel.EventSink rfidOnRetryReadChipEvent; - - private EventChannel.EventSink eventPACertificateCompletion; - private EventChannel.EventSink eventTACertificateCompletion; - private EventChannel.EventSink eventTASignatureCompletion; - - private EventChannel.EventSink bleOnServiceConnectedEvent; - private EventChannel.EventSink bleOnServiceDisconnectedEvent; - private EventChannel.EventSink bleOnDeviceReadyEvent; - - private EventChannel.EventSink eventVideoEncoderCompletion; - private EventChannel.EventSink onCustomButtonTappedEvent; - - @Override - public void onAttachedToEngine(FlutterPluginBinding binding) { - setupEventChannel(binding, "completion", (events) -> eventCompletion = events); - setupEventChannel(binding, "database_progress", (events) -> eventDatabaseProgress = events); - setupEventChannel(binding, "video_encoder_completion", (events) -> eventVideoEncoderCompletion = events); - setupEventChannel(binding, "rfid_notification_completion", (events) -> rfidOnProgressEvent = events); - setupEventChannel(binding, "rfidOnChipDetectedEvent", (events) -> rfidOnChipDetectedEvent = events); - setupEventChannel(binding, "rfidOnRetryReadChipEvent", (events) -> rfidOnRetryReadChipEvent = events); - setupEventChannel(binding, "pa_certificate_completion", (events) -> eventPACertificateCompletion = events); - setupEventChannel(binding, "ta_certificate_completion", (events) -> eventTACertificateCompletion = events); - setupEventChannel(binding, "ta_signature_completion", (events) -> eventTASignatureCompletion = events); - setupEventChannel(binding, "bleOnServiceConnectedEvent", (events) -> bleOnServiceConnectedEvent = events); - setupEventChannel(binding, "bleOnServiceDisconnectedEvent", (events) -> bleOnServiceDisconnectedEvent = events); - setupEventChannel(binding, "bleOnDeviceReadyEvent", (events) -> bleOnDeviceReadyEvent = events); - setupEventChannel(binding, "onCustomButtonTappedEvent", (events) -> onCustomButtonTappedEvent = events); - new MethodChannel(binding.getBinaryMessenger(), "flutter_document_reader_api/method").setMethodCallHandler(this); - } - - private interface OnListen { - void run(EventChannel.EventSink events); - } - - private void setupEventChannel(FlutterPluginBinding binding, String id, OnListen onListen) { - new EventChannel(binding.getBinaryMessenger(), "flutter_document_reader_api/event/" + id).setStreamHandler(new EventChannel.StreamHandler() { - @Override - public void onListen(Object arguments, EventChannel.EventSink events) { - onListen.run(events); - } - - @Override - public void onCancel(Object arguments) { - } - }); - } - - @Override - public void onAttachedToActivity(ActivityPluginBinding binding) { - activity = binding.getActivity(); - binding.addOnNewIntentListener(intent -> { - if (intent.getAction() != null && intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) && backgroundRFIDEnabled) - Instance().readRFID(IsoDep.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)), getRfidReaderCompletion(), getRfidReaderRequest()); - return false; - }); - ((HiddenLifecycleReference) binding.getLifecycle()).getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> { - if (event == Lifecycle.Event.ON_RESUME && backgroundRFIDEnabled) - startForegroundDispatch(getActivity()); - }); - } - - public FlutterDocumentReaderApiPlugin() { - } - - Activity getActivity() { - return activity; - } - - private Context getContext() { - return activity; - } - - @Override - public void onDetachedFromActivityForConfigChanges() { - } - - @Override - public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { - } - - @Override - public void onDetachedFromActivity() { - } - - @Override - public void onDetachedFromEngine(FlutterPluginBinding binding) { - } - - private interface Callback { - void success(Object o); - - void error(String s); - - default void success() { - success(""); - } - } - - private JSONArray arrayListToJSONArray(ArrayList list) { - JSONArray result = new JSONArray(); - for (int i = 0; i < list.size(); i++) { - if (list.get(i).getClass().equals(java.util.HashMap.class)) - result.put(hashMapToJSONObject((HashMap) list.get(i))); - else if (list.get(i).getClass().equals(java.util.ArrayList.class)) - result.put(arrayListToJSONArray((ArrayList) list.get(i))); - else - result.put(list.get(i)); - } - - return result; - } - - private JSONObject hashMapToJSONObject(HashMap map) { - JSONObject result = new JSONObject(); - try { - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().getClass().equals(java.util.HashMap.class)) - result.put(entry.getKey(), hashMapToJSONObject((HashMap) entry.getValue())); - else if (entry.getValue().getClass().equals(java.util.ArrayList.class)) - result.put(entry.getKey(), arrayListToJSONArray((ArrayList) entry.getValue())); - else - result.put(entry.getKey(), entry.getValue()); - } - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - private T args(int index) { - if (args.get(index).getClass().equals(java.util.HashMap.class)) - return (T) hashMapToJSONObject((HashMap) args.get(index)); - if (args.get(index).getClass().equals(java.util.ArrayList.class)) - return (T) arrayListToJSONArray((ArrayList) args.get(index)); - return (T) args.get(index); - } - - private void sendEvent(EventChannel.EventSink event, Object data) { - if (event == null) return; - if (data instanceof JSONObject || data instanceof JSONArray) data = data.toString(); - final Object finalData = data; - new Handler(Looper.getMainLooper()).post(() -> event.success(finalData)); - } - - @Override - public void onMethodCall(MethodCall call, Result result) { - String action = call.method; - args = (ArrayList) call.arguments; - Callback callback = new Callback() { - @Override - public void success(Object o) { - result.success(o); - } - - @Override - public void error(String s) { - result.error("", s, null); - } - }; - try { - switch (action) { - case "initializeReaderAutomatically": - initializeReaderAutomatically(callback); - break; - case "isBlePermissionsGranted": - isBlePermissionsGranted(callback); - break; - case "startBluetoothService": - startBluetoothService(callback); - break; - case "initializeReaderBleDeviceConfig": - initializeReaderBleDeviceConfig(callback); - break; - case "getTag": - getTag(callback); - break; - case "getAPIVersion": - getAPIVersion(callback); - break; - case "getAvailableScenarios": - getAvailableScenarios(callback); - break; - case "isRFIDAvailableForUse": - isRFIDAvailableForUse(callback); - break; - case "getCoreMode": - getCoreMode(callback); - break; - case "getCoreVersion": - getCoreVersion(callback); - break; - case "getDatabaseDate": - getDatabaseDate(callback); - break; - case "getDatabaseID": - getDatabaseID(callback); - break; - case "getDatabaseVersion": - getDatabaseVersion(callback); - break; - case "getDocumentReaderIsReady": - getDocumentReaderIsReady(callback); - break; - case "getDocumentReaderStatus": - getDocumentReaderStatus(callback); - break; - case "getDatabaseCountriesNumber": - getDatabaseCountriesNumber(callback); - break; - case "getDatabaseDocumentsNumber": - getDatabaseDocumentsNumber(callback); - break; - case "selectedScenario": - selectedScenario(callback); - break; - case "getSessionLogFolder": - getSessionLogFolder(callback); - break; - case "getDatabaseDescription": - getDatabaseDescription(callback); - break; - case "showScanner": - showScanner(callback); - break; - case "startNewPage": - startNewPage(callback); - break; - case "startNewSession": - startNewSession(callback); - break; - case "startRFIDReader": - startRFIDReader(callback); - break; - case "stopRFIDReader": - stopRFIDReader(callback); - break; - case "stopRFIDReaderWithErrorMessage": - stopRFIDReaderWithErrorMessage(callback, args(0)); - break; - case "stopScanner": - stopScanner(callback); - break; - case "deinitializeReader": - deinitializeReader(callback); - break; - case "isAuthenticatorAvailableForUse": - isAuthenticatorAvailableForUse(callback); - break; - case "getConfig": - getConfig(callback); - break; - case "getRfidScenario": - getRfidScenario(callback); - break; - case "getLicenseExpiryDate": - getLicenseExpiryDate(callback); - break; - case "getLicenseCountryFilter": - getLicenseCountryFilter(callback); - break; - case "licenseIsRfidAvailable": - licenseIsRfidAvailable(callback); - break; - case "getCameraSessionIsPaused": - getCameraSessionIsPaused(callback); - break; - case "removeDatabase": - removeDatabase(callback); - break; - case "cancelDBUpdate": - cancelDBUpdate(callback); - break; - case "resetConfiguration": - resetConfiguration(callback); - break; - case "clearPKDCertificates": - clearPKDCertificates(callback); - break; - case "readRFID": - readRFID(callback); - break; - case "getRfidSessionStatus": - getRfidSessionStatus(callback); - break; - case "setRfidDelegate": - setRfidDelegate(callback, args(0)); - break; - case "setEnableCoreLogs": - setEnableCoreLogs(callback, args(0)); - break; - case "addPKDCertificates": - addPKDCertificates(callback, args(0)); - break; - case "setCameraSessionIsPaused": - setCameraSessionIsPaused(callback, args(0)); - break; - case "setTag": - setTag(callback, args(0)); - break; - case "checkDatabaseUpdate": - checkDatabaseUpdate(callback, args(0)); - break; - case "scan": - scan(callback, args(0)); - break; - case "recognize": - recognize(callback, args(0)); - break; - case "recognizeImages": - recognizeImages(callback, args(0)); - break; - case "showScannerWithCameraID": - showScannerWithCameraID(callback, args(0)); - break; - case "runAutoUpdate": - runAutoUpdate(callback, args(0)); - break; - case "setConfig": - setConfig(callback, args(0)); - break; - case "setRfidScenario": - setRfidScenario(callback, args(0)); - break; - case "initializeReader": - initializeReader(callback, args(0)); - break; - case "prepareDatabase": - prepareDatabase(callback, args(0)); - break; - case "recognizeImage": - recognizeImage(callback, args(0)); - break; - case "recognizeData": - recognizeData(callback, args(0)); - break; - case "setRfidSessionStatus": - setRfidSessionStatus(callback, args(0)); - break; - case "providePACertificates": - providePACertificates(callback, args(0)); - break; - case "provideTACertificates": - provideTACertificates(callback, args(0)); - break; - case "provideTASignature": - provideTASignature(callback, args(0)); - break; - case "parseCoreResults": - parseCoreResults(callback, args(0)); - break; - case "setTCCParams": - setTCCParams(callback, args(0)); - break; - case "recognizeImageWithOpts": - recognizeImageWithOpts(callback, args(0), args(1)); - break; - case "recognizeVideoFrame": - recognizeVideoFrame(callback, args(0), args(1)); - break; - case "showScannerWithCameraIDAndOpts": - showScannerWithCameraIDAndOpts(callback, args(0), args(1)); - break; - case "recognizeImageWithCameraMode": - recognizeImageWithCameraMode(callback, args(0), args(1)); - break; - case "recognizeImagesWithImageInputs": - recognizeImagesWithImageInputs(callback, args(0)); - break; - case "setLanguage": - setLanguage(callback, args(0)); - break; - case "textFieldValueByType": - textFieldValueByType(callback, args(0), args(1)); - break; - case "textFieldValueByTypeLcid": - textFieldValueByTypeLcid(callback, args(0), args(1), args(2)); - break; - case "textFieldValueByTypeSource": - textFieldValueByTypeSource(callback, args(0), args(1), args(2)); - break; - case "textFieldValueByTypeLcidSource": - textFieldValueByTypeLcidSource(callback, args(0), args(1), args(2), args(3)); - break; - case "textFieldValueByTypeSourceOriginal": - textFieldValueByTypeSourceOriginal(callback, args(0), args(1), args(2), args(3)); - break; - case "textFieldValueByTypeLcidSourceOriginal": - textFieldValueByTypeLcidSourceOriginal(callback, args(0), args(1), args(2), args(3), args(4)); - break; - case "textFieldByType": - textFieldByType(callback, args(0), args(1)); - break; - case "textFieldByTypeLcid": - textFieldByTypeLcid(callback, args(0), args(1), args(2)); - break; - case "graphicFieldByTypeSource": - graphicFieldByTypeSource(callback, args(0), args(1), args(2)); - break; - case "graphicFieldByTypeSourcePageIndex": - graphicFieldByTypeSourcePageIndex(callback, args(0), args(1), args(2), args(3)); - break; - case "graphicFieldByTypeSourcePageIndexLight": - graphicFieldByTypeSourcePageIndexLight(callback, args(0), args(1), args(2), args(3), args(4)); - break; - case "graphicFieldImageByType": - graphicFieldImageByType(callback, args(0), args(1)); - break; - case "graphicFieldImageByTypeSource": - graphicFieldImageByTypeSource(callback, args(0), args(1), args(2)); - break; - case "graphicFieldImageByTypeSourcePageIndex": - graphicFieldImageByTypeSourcePageIndex(callback, args(0), args(1), args(2), args(3)); - break; - case "graphicFieldImageByTypeSourcePageIndexLight": - graphicFieldImageByTypeSourcePageIndexLight(callback, args(0), args(1), args(2), args(3), args(4)); - break; - case "containers": - containers(callback, args(0), args(1)); - break; - case "encryptedContainers": - encryptedContainers(callback, args(0)); - break; - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void startForegroundDispatch(final Activity activity) { - IntentFilter[] filters = new IntentFilter[1]; - filters[0] = new IntentFilter(); - filters[0].addAction(NfcAdapter.ACTION_TECH_DISCOVERED); - filters[0].addCategory(Intent.CATEGORY_DEFAULT); - String[][] techList = new String[][]{ - new String[]{"android.nfc.tech.IsoDep"} - }; - Intent intent = new Intent(activity.getApplicationContext(), activity.getClass()); - int flag = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0; - PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, flag); - NfcAdapter.getDefaultAdapter(getActivity()).enableForegroundDispatch(activity, pendingIntent, filters, techList); - } - - private void stopBackgroundRFID() { - if (!backgroundRFIDEnabled) - return; - NfcAdapter.getDefaultAdapter(getActivity()).disableForegroundDispatch(getActivity()); - backgroundRFIDEnabled = false; - } - - private void initializeReaderAutomatically(Callback callback) { - if (!Instance().isReady()) - try { - InputStream is = getContext().getAssets().open("regula.license"); - byte[] license = new byte[is.available()]; - //noinspection ResultOfMethodCallIgnored - is.read(license); - Instance().initializeReader(getContext(), new DocReaderConfig(license), getInitCompletion(callback)); - is.close(); - } catch (IOException e) { - e.printStackTrace(); - callback.error("problem reading license(see logs)"); - } - else - callback.success("already initialized"); - } - - private void isBlePermissionsGranted(Callback callback) { - callback.success(BluetoothUtil.Companion.isBlePermissionsGranted(getActivity())); - } - - private void startBluetoothService(Callback callback) { - BluetoothUtil.Companion.startBluetoothService( - getActivity(), - isBleManagerConnected -> { - sendEvent(bleOnServiceConnectedEvent, isBleManagerConnected); - return null; - }, - () -> { - sendEvent(bleOnServiceDisconnectedEvent, ""); - return null; - }, - () -> { - sendEvent(bleOnDeviceReadyEvent, ""); - return null; - } - ); - callback.success(); - } - - @SuppressLint("MissingPermission") - private void initializeReaderBleDeviceConfig(Callback callback) { - if (BluetoothUtil.Companion.getBleManager() == null) callback.error("bleManager is null"); - if (!Instance().isReady()) - Instance().initializeReader(getContext(), new BleDeviceConfig(BluetoothUtil.Companion.getBleManager()), getInitCompletion(callback)); - else - callback.success("already initialized"); - } - - private void getAvailableScenarios(Callback callback) throws JSONException { - callback.success(generateList(Instance().availableScenarios, JSONConstructor::generateDocumentReaderScenario).toString()); - } - - private void parseCoreResults(Callback callback, String json) { - DocumentReaderResults results = (DocumentReaderResults) DocReaderResultsJsonParser.parseCoreResults(json).get("docReaderResults"); - callback.success(generateDocumentReaderResults(results, getContext()).toString()); - } - - private void getAPIVersion(Callback callback) { - callback.success(Instance().version.api); - } - - private void getCoreVersion(Callback callback) { - callback.success(Instance().version.core); - } - - private void getCoreMode(Callback callback) { - callback.success(Instance().version.coreMode); - } - - private void getDatabaseID(Callback callback) { - callback.success(Instance().version.database.databaseID); - } - - private void getDatabaseVersion(Callback callback) { - callback.success(Instance().version.database.version); - } - - private void getDatabaseDate(Callback callback) { - callback.success(Instance().version.database.date); - } - - private void getDatabaseDescription(Callback callback) { - callback.success(Instance().version.database.databaseDescription); - } - - private void getDatabaseCountriesNumber(Callback callback) { - callback.success(Instance().version.database.countriesNumber); - } - - private void getDatabaseDocumentsNumber(Callback callback) { - callback.success(Instance().version.database.documentsNumber); - } - - private void setTCCParams(Callback callback, final JSONObject params) { - Instance().setTccParams(TCCParamsFromJSON(params), getTCCParamsCompletion(callback)); - } - - private void deinitializeReader(Callback callback) { - Instance().deinitializeReader(); - callback.success(); - } - - private void isAuthenticatorAvailableForUse(Callback callback) { - callback.success(Instance().isAuthenticatorAvailableForUse()); - } - - private void getConfig(Callback callback) throws JSONException { - callback.success(RegulaConfig.getConfig(Instance()).toString()); - } - - private void getRfidScenario(Callback callback) { - callback.success(Instance().rfidScenario().toJson()); - } - - private void selectedScenario(Callback callback) { - callback.success(generateDocumentReaderScenario(CoreScenarioUtil.getScenario(Instance().processParams().getScenario())).toString()); - } - - private void getLicenseExpiryDate(Callback callback) { - if (Instance().license().getExpiryDate() == null) - callback.error("null"); - else - callback.success(Instance().license().getExpiryDate().toString()); - } - - private void getLicenseCountryFilter(Callback callback) { - if (Instance().license().getCountryFilter() == null) - callback.error("null"); - else - callback.success(generateList(Instance().license().getCountryFilter()).toString()); - } - - private void licenseIsRfidAvailable(Callback callback) { - callback.success(Instance().license().isRfidAvailable()); - } - - private void getDocumentReaderIsReady(Callback callback) { - callback.success(Instance().isReady()); - } - - private void getDocumentReaderStatus(Callback callback) { - callback.success(Instance().isReady()); - } - - private void isRFIDAvailableForUse(Callback callback) { - callback.success(Instance().isRFIDAvailableForUse()); - } - - private void initializeReader(Callback callback, JSONObject config) { - if (!Instance().isReady()) - Instance().initializeReader(getContext(), DocReaderConfigFromJSON(config), getInitCompletion(callback)); - else - callback.success("already initialized"); - } - - private void startNewSession(Callback callback) { - Instance().startNewSession(); - callback.success(); - } - - private void getTag(Callback callback) { - callback.success(Instance().tag); - } - - private void setTag(Callback callback, String tag) { - Instance().tag = tag; - callback.success(); - } - - private void checkDatabaseUpdate(Callback callback, String databaseId) { - Instance().checkDatabaseUpdate(getContext(), databaseId, getCheckDatabaseUpdateCompletion(callback)); - callback.success(); - } - - private void startNewPage(Callback callback) { - Instance().startNewPage(); - callback.success(); - } - - private void scan(@SuppressWarnings("unused") Callback callback, JSONObject config) { - stopBackgroundRFID(); - Instance().showScanner(getContext(), ScannerConfigFromJSON(config), getCompletion()); - } - - private void recognize(@SuppressWarnings("unused") Callback callback, JSONObject config) { - stopBackgroundRFID(); - Instance().recognize(getContext(), RecognizeConfigFromJSON(config), getCompletion()); - } - - private void recognizeImageWithOpts(Callback callback, String base64Image, final JSONObject opts) throws JSONException { - RegulaConfig.setConfig(Instance(), opts, getContext()); - recognizeImage(callback, base64Image); - } - - private void recognizeImage(@SuppressWarnings("unused") Callback callback, String base64Image) { - stopBackgroundRFID(); - Instance().recognizeImage(Helpers.bitmapFromBase64(base64Image), getCompletion()); - } - - private void recognizeData(@SuppressWarnings("unused") Callback callback, Object data) { - stopBackgroundRFID(); - Instance().recognizeImage(Base64.decode(data.toString(), Base64.DEFAULT), getCompletion()); - } - - private void recognizeImages(@SuppressWarnings("unused") Callback callback, JSONArray base64Images) throws JSONException { - stopBackgroundRFID(); - Bitmap[] images = new Bitmap[base64Images.length()]; - for (int i = 0; i < images.length; i++) - images[i] = bitmapFromBase64(base64Images.getString(i)); - Instance().recognizeImages(images, getCompletion()); - } - - private void recognizeImagesWithImageInputs(@SuppressWarnings("unused") Callback callback, JSONArray base64Images) throws JSONException { - stopBackgroundRFID(); - ImageInputData[] images = new ImageInputData[base64Images.length()]; - for (int i = 0; i < images.length; i++) - images[i] = ImageInputDataFromJSON(base64Images.getJSONObject(i)); - Instance().recognizeImages(images, getCompletion()); - } - - private void removeDatabase(Callback callback) { - callback.success(Instance().removeDatabase(getContext())); - } - - private void cancelDBUpdate(Callback callback) { - callback.success(Instance().cancelDBUpdate(getContext())); - } - - private void resetConfiguration(Callback callback) { - Instance().resetConfiguration(); - callback.success(); - } - - private void setEnableCoreLogs(Callback callback, boolean enableLogs) { - Instance().setEnableCoreLogs(enableLogs); - callback.success(); - } - - private void addPKDCertificates(Callback callback, JSONArray certificatesJSON) throws JSONException { - List certificates = new ArrayList<>(); - for (int i = 0; i < certificatesJSON.length(); i++) { - JSONObject certificate = certificatesJSON.getJSONObject(i); - certificates.add(new PKDCertificate(Base64.decode(certificate.get("binaryData").toString(), Base64.DEFAULT), certificate.getInt("resourceType"), certificate.has("privateKey") ? Base64.decode(certificate.get("privateKey").toString(), Base64.DEFAULT) : null)); - } - Instance().addPKDCertificates(certificates); - callback.success(); - } - - private void clearPKDCertificates(Callback callback) { - Instance().clearPKDCertificates(); - callback.success(); - } - - private void recognizeVideoFrame(@SuppressWarnings("unused") Callback callback, String byteString, final JSONObject opts) throws JSONException { - stopBackgroundRFID(); - Instance().recognizeVideoFrame(byteString.getBytes(), new ImageInputParam(opts.getInt("width"), opts.getInt("height"), opts.getInt("type")), getCompletion()); - } - - private void showScannerWithCameraID(@SuppressWarnings("unused") Callback callback, int cameraID) { - stopBackgroundRFID(); - Instance().showScanner(getContext(), cameraID, getCompletion()); - } - - private void showScanner(Callback callback) { - showScannerWithCameraID(callback, -1); - } - - private void showScannerWithCameraIDAndOpts(@SuppressWarnings("unused") Callback callback, int cameraID, final JSONObject opts) throws JSONException { - stopBackgroundRFID(); - RegulaConfig.setConfig(Instance(), opts, getContext()); - Instance().showScanner(getContext(), cameraID, getCompletion()); - } - - private void stopScanner(Callback callback) { - Instance().stopScanner(getContext()); - callback.success(); - } - - private void startRFIDReader(@SuppressWarnings("unused") Callback callback) { - stopBackgroundRFID(); - Instance().startRFIDReader(getContext(), getRfidReaderCompletion(), getRfidReaderRequest()); - } - - private void stopRFIDReader(Callback callback) { - Instance().stopRFIDReader(getContext()); - stopBackgroundRFID(); - callback.success(); - } - - private void prepareDatabase(Callback callback, String dbID) { - Instance().prepareDatabase(getContext(), dbID, getPrepareCompletion(callback)); - } - - private void runAutoUpdate(Callback callback, String dbID) { - Instance().runAutoUpdate(getContext(), dbID, getPrepareCompletion(callback)); - } - - private void setRfidScenario(Callback callback, final JSONObject opts) throws JSONException { - RegulaConfig.setRfidScenario(opts); - callback.success(); - } - - private void getSessionLogFolder(Callback callback) { - callback.success(Instance().processParams().sessionLogFolder); - } - - private void setConfig(Callback callback, final JSONObject opts) throws JSONException { - RegulaConfig.setConfig(Instance(), opts, getContext()); - callback.success(); - } - - private void readRFID(@SuppressWarnings("unused") Callback callback) { - backgroundRFIDEnabled = true; - startForegroundDispatch(getActivity()); - } - - private void setLanguage(Callback callback, String language) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - LocaleManager localeManager = (LocaleManager) getContext().getSystemService(Context.LOCALE_SERVICE); - localeManager.setApplicationLocales(new LocaleList(Locale.forLanguageTag(language))); - } else { - Locale locale = new Locale(language); - Locale.setDefault(locale); - Resources resources = getContext().getResources(); - Configuration config = resources.getConfiguration(); - config.setLocale(locale); - resources.updateConfiguration(config, resources.getDisplayMetrics()); - } - callback.success(); - } - - private void providePACertificates(Callback callback, JSONArray certificatesJSON) throws JSONException { - if (paCertificateCompletion == null) { - callback.error("paCertificateCompletion is null"); - return; - } - PKDCertificate[] certificates = new PKDCertificate[certificatesJSON.length()]; - for (int i = 0; i < certificatesJSON.length(); i++) { - JSONObject certificate = certificatesJSON.getJSONObject(i); - certificates[i] = new PKDCertificate(Base64.decode(certificate.get("binaryData").toString(), Base64.DEFAULT), certificate.getInt("resourceType"), certificate.has("privateKey") ? Base64.decode(certificate.get("privateKey").toString(), Base64.DEFAULT) : null); - } - paCertificateCompletion.onCertificatesReceived(certificates); - callback.success(); - } - - private void provideTACertificates(Callback callback, JSONArray certificatesJSON) throws JSONException { - if (taCertificateCompletion == null) { - callback.error("taCertificateCompletion is null"); - return; - } - PKDCertificate[] certificates = new PKDCertificate[certificatesJSON.length()]; - for (int i = 0; i < certificatesJSON.length(); i++) { - JSONObject certificate = certificatesJSON.getJSONObject(i); - certificates[i] = new PKDCertificate(Base64.decode(certificate.get("binaryData").toString(), Base64.DEFAULT), certificate.getInt("resourceType"), certificate.has("privateKey") ? Base64.decode(certificate.get("privateKey").toString(), Base64.DEFAULT) : null); - } - taCertificateCompletion.onCertificatesReceived(certificates); - callback.success(); - } - - private void provideTASignature(Callback callback, Object signature) { - if (taSignatureCompletion == null) { - callback.error("taSignatureCompletion is null"); - return; - } - taSignatureCompletion.onSignatureReceived(Base64.decode(signature.toString(), Base64.DEFAULT)); - callback.success(); - } - - private void setRfidDelegate(Callback callback, int delegate) { - rfidDelegate = delegate; - callback.success(); - } - - private void textFieldValueByType(Callback callback, String raw, int fieldType) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByType(fieldType)); - } - - private void textFieldValueByTypeLcid(Callback callback, String raw, int fieldType, int lcid) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByType(fieldType, lcid)); - } - - private void textFieldValueByTypeSource(Callback callback, String raw, int fieldType, int source) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByTypeAndSource(fieldType, source)); - } - - private void textFieldValueByTypeLcidSource(Callback callback, String raw, int fieldType, int lcid, int source) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByType(fieldType, lcid, source)); - } - - private void textFieldValueByTypeSourceOriginal(Callback callback, String raw, int fieldType, int source, boolean original) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByTypeAndSource(fieldType, source, original)); - } - - private void textFieldValueByTypeLcidSourceOriginal(Callback callback, String raw, int fieldType, int lcid, int source, boolean original) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getTextFieldValueByType(fieldType, lcid, source, original)); - } - - private void textFieldByType(Callback callback, String raw, int fieldType) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - DocumentReaderTextField result = results.getTextFieldByType(fieldType); - if (result == null) - callback.success(null); - else - callback.success(generateDocumentReaderTextField(result, getContext()).toString()); - } - - private void textFieldByTypeLcid(Callback callback, String raw, int fieldType, int lcid) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - DocumentReaderTextField result = results.getTextFieldByType(fieldType, lcid); - if (result == null) - callback.success(null); - else - callback.success(generateDocumentReaderTextField(result, getContext()).toString()); - } - - private void graphicFieldByTypeSource(Callback callback, String raw, int fieldType, int source) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - DocumentReaderGraphicField result = results.getGraphicFieldByType(fieldType, source); - if (result == null) - callback.success(null); - else - callback.success(generateDocumentReaderGraphicField(result, getContext()).toString()); - } - - private void graphicFieldByTypeSourcePageIndex(Callback callback, String raw, int fieldType, int source, int pageIndex) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - DocumentReaderGraphicField result = results.getGraphicFieldByType(fieldType, source, pageIndex); - if (result == null) - callback.success(null); - else - callback.success(generateDocumentReaderGraphicField(result, getContext()).toString()); - } - - private void graphicFieldByTypeSourcePageIndexLight(Callback callback, String raw, int fieldType, int source, int pageIndex, int light) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - DocumentReaderGraphicField result = results.getGraphicFieldByType(fieldType, source, pageIndex, light); - if (result == null) - callback.success(null); - else - callback.success(generateDocumentReaderGraphicField(result, getContext()).toString()); - } - - private void graphicFieldImageByType(Callback callback, String raw, int fieldType) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(bitmapToBase64String(results.getGraphicFieldImageByType(fieldType))); - } - - private void graphicFieldImageByTypeSource(Callback callback, String raw, int fieldType, int source) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(bitmapToBase64String(results.getGraphicFieldImageByType(fieldType, source))); - } - - private void graphicFieldImageByTypeSourcePageIndex(Callback callback, String raw, int fieldType, int source, int pageIndex) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(bitmapToBase64String(results.getGraphicFieldImageByType(fieldType, source, pageIndex))); - } - - private void graphicFieldImageByTypeSourcePageIndexLight(Callback callback, String raw, int fieldType, int source, int pageIndex, int light) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(bitmapToBase64String(results.getGraphicFieldImageByType(fieldType, source, pageIndex, light))); - } - - @SuppressLint("WrongConstant") - private void containers(Callback callback, String raw, JSONArray resultType) { - try { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getContainers(intArrayFromJSON(resultType))); - } catch (JSONException e) { - e.printStackTrace(); - callback.error(e.toString()); - } - } - - private void encryptedContainers(Callback callback, String raw) { - DocumentReaderResults results = DocumentReaderResults.fromRawResults(raw); - callback.success(results.getEncryptedContainers()); - } - - private void setCameraSessionIsPaused(Callback callback, @SuppressWarnings("unused") boolean ignored) { - callback.error("setCameraSessionIsPaused() is an ios-only method"); - } - - private void getCameraSessionIsPaused(Callback callback) { - callback.error("getCameraSessionIsPaused() is an ios-only method"); - } - - private void stopRFIDReaderWithErrorMessage(Callback callback, @SuppressWarnings("unused") String message) { - callback.error("stopRFIDReaderWithErrorMessage() is an ios-only method"); - } - - @SuppressWarnings("unused") - private void recognizeImageWithCameraMode(Callback callback, String base64, boolean mode) { - callback.error("recognizeImageWithCameraMode() is an ios-only method"); - } - - @SuppressWarnings("unused") - private void setRfidSessionStatus(Callback callback, String s) { - callback.error("setRfidSessionStatus() is an ios-only method"); - } - - private void getRfidSessionStatus(Callback callback) { - callback.error("getRfidSessionStatus() is an ios-only method"); - } - - private IDocumentReaderCompletion getCompletion() { - return (action, results, error) -> { - sendEvent(eventCompletion, generateCompletion(action, results, error, getContext())); - if (action == DocReaderAction.ERROR || action == DocReaderAction.CANCEL || (action == DocReaderAction.COMPLETE && results != null && results.rfidResult == 1)) - stopBackgroundRFID(); - }; - } - - private IRfidReaderCompletion getRfidReaderCompletion() { - return new IRfidReaderCompletion() { - @Override - public void onCompleted(int action, @Nullable DocumentReaderResults results, @Nullable DocumentReaderException error) { - sendEvent(eventCompletion, generateCompletion(action, results, error, getContext())); - if (action == DocReaderAction.ERROR || action == DocReaderAction.CANCEL || (action == DocReaderAction.COMPLETE && results != null && results.rfidResult == 1)) - stopBackgroundRFID(); - } - - @Override - public void onChipDetected() { - sendEvent(rfidOnChipDetectedEvent, ""); - } - - @Override - public void onRetryReadChip(@NonNull DocReaderRfidException error) { - sendEvent(rfidOnRetryReadChipEvent, generateRegulaException(error)); - } - - @Override - public void onProgress(@Nullable DocumentReaderNotification notification) { - sendEvent(rfidOnProgressEvent, generateDocumentReaderNotification(notification)); - } - }; - } - - private IDocumentReaderPrepareCompletion getPrepareCompletion(Callback callback) { - return new IDocumentReaderPrepareCompletion() { - @Override - public void onPrepareProgressChanged(int progress) { - if (progress != databaseDownloadProgress) { - sendEvent(eventDatabaseProgress, progress + ""); - databaseDownloadProgress = progress; - } - } - - @Override - public void onPrepareCompleted(boolean status, @Nullable DocumentReaderException error) { - if (status) - callback.success("database prepared"); - else - callback.error("database preparation failed: " + error.toString()); - } - }; - } - - private IDocumentReaderInitCompletion getInitCompletion(Callback callback) { - return (success, error) -> { - if (success) { - Instance().setVideoEncoderCompletion((sessionId, file) -> sendEvent(eventVideoEncoderCompletion, generateVideoEncoderCompletion(sessionId, file))); - Instance().setOnClickListener(view -> sendEvent(onCustomButtonTappedEvent, view.getTag())); - callback.success("init completed"); - } else - callback.error("Init failed:" + error); - }; - } - - private ICheckDatabaseUpdate getCheckDatabaseUpdateCompletion(Callback callback) { - return (database) -> callback.success(generateDocReaderDocumentsDatabase(database)); - } - - private ITccParamsCompletion getTCCParamsCompletion(Callback callback) { - return (success, error) -> { - if (success) - callback.success("success"); - else - callback.error("failed: " + error.getMessage()); - }; - } - - private IRfidReaderRequest getIRfidReaderRequest() { - return new IRfidReaderRequest() { - @Override - public void onRequestPACertificates(byte[] serialNumber, PAResourcesIssuer issuer, @NonNull IRfidPKDCertificateCompletion completion) { - paCertificateCompletion = completion; - sendEvent(eventPACertificateCompletion, generatePACertificateCompletion(serialNumber, issuer)); - } - - @Override - public void onRequestTACertificates(String keyCAR, @NonNull IRfidPKDCertificateCompletion completion) { - taCertificateCompletion = completion; - sendEvent(eventTACertificateCompletion, keyCAR); - } - - @Override - public void onRequestTASignature(TAChallenge challenge, @NonNull IRfidTASignatureCompletion completion) { - taSignatureCompletion = completion; - sendEvent(eventTASignatureCompletion, generateTAChallenge(challenge)); - } - }; - } - - private IRfidReaderRequest getIRfidReaderRequestNoPA() { - return new IRfidReaderRequest() { - @Override - public void onRequestPACertificates(byte[] serialNumber, PAResourcesIssuer issuer, @NonNull IRfidPKDCertificateCompletion completion) { - paCertificateCompletion = null; - completion.onCertificatesReceived(new PKDCertificate[0]); - } - - @Override - public void onRequestTACertificates(String keyCAR, @NonNull IRfidPKDCertificateCompletion completion) { - taCertificateCompletion = completion; - sendEvent(eventTACertificateCompletion, keyCAR); - } - - @Override - public void onRequestTASignature(TAChallenge challenge, @NonNull IRfidTASignatureCompletion completion) { - taSignatureCompletion = completion; - sendEvent(eventTASignatureCompletion, generateTAChallenge(challenge)); - } - }; - } - - private IRfidReaderRequest getRfidReaderRequest() { - IRfidReaderRequest delegate = null; - if (rfidDelegate == RFIDDelegate.NO_PA) - delegate = getIRfidReaderRequestNoPA(); - if (rfidDelegate == RFIDDelegate.FULL) - delegate = getIRfidReaderRequest(); - return delegate; - } - - private static int rfidDelegate = RFIDDelegate.NULL; - - private static class RFIDDelegate { - public static final int NULL = 0; - public static final int NO_PA = 1; - public static final int FULL = 2; - } -} \ No newline at end of file diff --git a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/Helpers.java b/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/Helpers.java deleted file mode 100644 index ae64bda32d..0000000000 --- a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/Helpers.java +++ /dev/null @@ -1,259 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Canvas; -import android.graphics.Matrix; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.util.Base64; - -import com.regula.documentreader.api.enums.BarcodeType; -import com.regula.documentreader.api.internal.params.FaceMetaData; -import com.regula.documentreader.api.results.Bounds; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -class Helpers { - interface JSONObjectGeneratorWithContext { - JSONObject generateJSONObject(T param, Context context) throws JSONException; - } - - interface JSONObjectGenerator { - JSONObject generateJSONObject(T param) throws JSONException; - } - - static JSONArray generateList(List list) { - JSONArray result = new JSONArray(); - if (list == null) return result; - for (T t : list) - if (t != null) - result.put(t); - - return result; - } - - static JSONArray generateList(List list, JSONObjectGenerator generator) throws JSONException { - JSONArray result = new JSONArray(); - if (list == null) return result; - for (T t : list) - if (t != null) - result.put(generator.generateJSONObject(t)); - - return result; - } - - static JSONArray generateList(List list, JSONObjectGeneratorWithContext generator, Context context) throws JSONException { - JSONArray result = new JSONArray(); - if (list == null) return result; - for (T t : list) - if (t != null) - result.put(generator.generateJSONObject(t, context)); - - return result; - } - - static JSONArray generateArray(T[] array) throws JSONException { - JSONArray result = new JSONArray(); - if (array == null) return result; - for (int i = 0; i < array.length; i++) - result.put(i, array[i]); - - return result; - } - - static JSONArray generateArray(T[] array, JSONObjectGenerator generator) throws JSONException { - JSONArray result = new JSONArray(); - if (array == null) return result; - for (int i = 0; i < array.length; i++) - result.put(i, generator.generateJSONObject(array[i])); - - return result; - } - - static JSONObject generateMap(Map map) throws JSONException { - JSONObject result = new JSONObject(); - if (map == null) return result; - for (Map.Entry entry : map.entrySet()) - if (entry != null) - result.put(entry.getKey().toString(), entry.getValue()); - return result; - } - - static JSONArray generateIntArray(int[] array) throws JSONException { - JSONArray result = new JSONArray(); - if (array == null) return result; - for (int i = 0; i < array.length; i++) - result.put(i, array[i]); - - return result; - } - - static int[] intArrayFromJSON(JSONArray input) throws JSONException { - int[] result = new int[input.length()]; - for (int i = 0; i < input.length(); i++) - result[i] = input.getInt(i); - - return result; - } - - static JSONArray generateByteArray(byte[] array) throws JSONException { - JSONArray result = new JSONArray(); - if (array == null) return result; - for (int i = 0; i < array.length; i++) - result.put(i, array[i]); - - return result; - } - - static JSONArray generateLongArray(long[] array) throws JSONException { - JSONArray result = new JSONArray(); - if (array == null) return result; - for (int i = 0; i < array.length; i++) - result.put(i, array[i]); - - return result; - } - - static Bitmap bitmapFromBase64(String base64) { - byte[] decodedString = Base64.decode(base64, Base64.NO_WRAP); - Bitmap result = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - int sizeMultiplier = result.getByteCount() / 5000000; - if (result.getByteCount() > 5000000) - result = Bitmap.createScaledBitmap(result, result.getWidth() / (int) Math.sqrt(sizeMultiplier), result.getHeight() / (int) Math.sqrt(sizeMultiplier), false); - return result; - } - - static BitmapDrawable drawableFromBase64(String base64, Context context) { - byte[] decodedByte = Base64.decode(base64, 0); - Bitmap bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); - float density = context.getResources().getDisplayMetrics().density; - int width = (int) (bitmap.getWidth() * density); - int height = (int) (bitmap.getHeight() * density); - return new BitmapDrawable(context.getResources(), Bitmap.createScaledBitmap(bitmap, width, height, false)); - } - - static Bitmap bitmapFromDrawable(Drawable drawable) { - Bitmap bitmap; - - if (drawable instanceof BitmapDrawable) { - BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; - if (bitmapDrawable.getBitmap() != null) { - return bitmapDrawable.getBitmap(); - } - } - - if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { - bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); - } else { - bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); - } - - Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); - return bitmap; - } - - static String bitmapToBase64String(Bitmap bitmap) { - if (bitmap == null) return null; - - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); - byte[] byteArray = byteArrayOutputStream.toByteArray(); - - return Base64.encodeToString(byteArray, Base64.NO_WRAP); - } - - static Matrix matrixFromFloatArray(float[] floats) { - Matrix matrix = new Matrix(); - matrix.setValues(floats); - return matrix; - } - - static float[] floatArrayFromJson(JSONArray jsonArray) throws JSONException { - float[] result = new float[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - result[i] = (float) jsonArray.getDouble(i); - - return result; - } - - static int[] intArrayFromJson(JSONArray jsonArray) throws JSONException { - int[] result = new int[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - result[i] = jsonArray.getInt(i); - - return result; - } - - static String[] barcodeTypeArrayFromJson(JSONArray jsonArray) throws JSONException { - String[] result = new String[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - result[i] = BarcodeType.valueOf(jsonArray.getInt(i)); - - return result; - } - - static FaceMetaData[] faceMetaDataArrayFromJson(JSONArray jsonArray) throws JSONException { - FaceMetaData[] result = new FaceMetaData[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - result[i] = faceMetaDataFromJson(jsonArray.getJSONObject(i)); - - return result; - } - - static FaceMetaData faceMetaDataFromJson(JSONObject object) throws JSONException { - FaceMetaData result = new FaceMetaData(); - result.ID = object.getInt("ID"); - result.rollAngle = object.getInt("rollAngle"); - result.bounds = boundsFromJson(object.getJSONObject("bounds")); - - return result; - } - - static Bounds boundsFromJson(JSONObject object) throws JSONException { - Bounds result = new Bounds(); - result.height = object.getInt("height"); - result.width = object.getInt("width"); - result.x = object.getInt("x"); - result.y = object.getInt("y"); - - return result; - } - - static List stringListFromJson(JSONArray jsonArray) { - List result = new ArrayList<>(); - for (int i = 0; i < jsonArray.length(); i++) - result.add(jsonArray.optString(i)); - return result; - } - - static String[] stringArrayFromJson(JSONArray jsonArray) { - String[] result = new String[jsonArray.length()]; - for (int i = 0; i < jsonArray.length(); i++) - result[i] = jsonArray.optString(i); - return result; - } - - static Map stringMapFromJson(JSONObject input) throws JSONException { - Map result = new HashMap<>(); - Iterator keys = input.keys(); - while (keys.hasNext()) { - String key = keys.next(); - String value = input.getString(key); - result.put(key, value); - } - return result; - } -} \ No newline at end of file diff --git a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/JSONConstructor.java b/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/JSONConstructor.java deleted file mode 100644 index f622b82b17..0000000000 --- a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/JSONConstructor.java +++ /dev/null @@ -1,1119 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api; - -import static io.flutter.plugins.regula.documentreader.flutter_document_reader_api.Helpers.*; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Rect; -import android.util.Base64; - -import com.regula.common.exception.RegulaException; -import com.regula.documentreader.api.config.RecognizeConfig; -import com.regula.documentreader.api.config.ScannerConfig; -import com.regula.documentreader.api.enums.*; -import com.regula.documentreader.api.params.*; -import com.regula.documentreader.api.params.rfid.*; -import com.regula.documentreader.api.params.rfid.authorization.*; -import com.regula.documentreader.api.results.*; -import com.regula.documentreader.api.results.authenticity.*; -import com.regula.documentreader.api.results.rfid.*; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Arrays; - -@SuppressWarnings("deprecation") -class JSONConstructor { - static JSONObject generateVideoEncoderCompletion(String sessionId, java.io.File file) { - JSONObject result = new JSONObject(); - - try { - result.put("sessionId", sessionId); - result.put("filePath", file.getPath()); - - } catch (JSONException e) { - e.printStackTrace(); - } - - return result; - } - - static JSONObject generateCompletion(int action, DocumentReaderResults results, RegulaException error, Context context) { - JSONObject result = new JSONObject(); - try { - if (Arrays.asList( - DocReaderAction.COMPLETE, - DocReaderAction.MORE_PAGES_AVAILABLE, - DocReaderAction.CANCEL, - DocReaderAction.ERROR, - DocReaderAction.TIMEOUT - ).contains(action)) - result.put("results", generateDocumentReaderResults(results, context)); - result.put("action", action); - result.put("error", generateRegulaException(error)); - } catch (JSONException ignored) { - } - return result; - } - - static JSONObject generateRegulaException(RegulaException input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("errorCode", input.getErrorCode()); - result.put("message", input.getMessage()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generatePACertificateCompletion(byte[] serialNumber, PAResourcesIssuer issuer) { - JSONObject result = new JSONObject(); - try { - result.put("serialNumber", generateByteArray(serialNumber)); - result.put("issuer", generatePAResourcesIssuer(issuer)); - } catch (JSONException ignored) { - } - - return result; - } - - static TccParams TCCParamsFromJSON(JSONObject input) { - TccParams result = new TccParams(); - try { - if (input.has("serviceUrlTA")) - result.setServiceUrlTA(input.getString("serviceUrlTA")); - if (input.has("serviceUrlPA")) - result.setServiceUrlPA(input.getString("serviceUrlPA")); - if (input.has("pfxCertUrl")) - result.setPfxCertUrl(input.getString("pfxCertUrl")); - if (input.has("pfxPassPhrase")) - result.setPfxPassPhrase(input.getString("pfxPassPhrase")); - if (input.has("pfxCert")) - result.setPfxCert(Base64.decode(input.getString("pfxCert"), Base64.DEFAULT)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static ImageInputData ImageInputDataFromJSON(JSONObject input) { - if (input == null) return null; - try { - Bitmap image; - int light = 6; - int pageIndex = 0; - - if (input.has("image")) - image = bitmapFromBase64(input.getString("image")); - else return null; - if (input.has("light")) - pageIndex = input.getInt("light"); - if (input.has("pageIndex")) - pageIndex = input.getInt("pageIndex"); - return new ImageInputData(image, light, pageIndex); - } catch (JSONException e) { - e.printStackTrace(); - } - - return null; - } - - static DocReaderConfig DocReaderConfigFromJSON(JSONObject input) { - DocReaderConfig result; - byte[] license; - try { - if (input.has("license")) { - license = Base64.decode(input.getString("license"), Base64.DEFAULT); - result = new DocReaderConfig(license); - } else return null; - if (input.has("customDb")) - result = new DocReaderConfig(license, Base64.decode(input.getString("customDb"), Base64.DEFAULT)); - if (input.has("licenseUpdate")) - result.setLicenseUpdate(input.getBoolean("licenseUpdate")); - if (input.has("delayedNNLoad")) - result.setDelayedNNLoad(input.getBoolean("delayedNNLoad")); - if (input.has("blackList")) - result.setBlackList(input.getJSONObject("blackList")); - - return result; - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static ScannerConfig ScannerConfigFromJSON(JSONObject input) { - if (!input.has("scenario") && !input.has("onlineProcessingConfig")) return null; - try { - ScannerConfig.Builder builder; - if (input.has("scenario")) - builder = new ScannerConfig.Builder(input.getString("scenario")); - else - builder = new ScannerConfig.Builder(RegulaConfig.OnlineProcessingConfigFromJSON(input.getJSONObject("onlineProcessingConfig"))); - if (input.has("onlineProcessingConfig")) - builder.setOnlineProcessingConfig(RegulaConfig.OnlineProcessingConfigFromJSON(input.getJSONObject("onlineProcessingConfig"))); - if (input.has("livePortrait")) - builder.setLivePortrait(bitmapFromBase64(input.getString("livePortrait"))); - if (input.has("extPortrait")) - builder.setExtPortrait(bitmapFromBase64(input.getString("extPortrait"))); - if (input.has("cameraId")) - builder.setCameraId(input.getInt("cameraId")); - return builder.build(); - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static RecognizeConfig RecognizeConfigFromJSON(JSONObject input) { - if (!input.has("scenario") && !input.has("onlineProcessingConfig")) return null; - if (!input.has("image") && !input.has("images") && !input.has("imageInputData")) return null; - try { - RecognizeConfig.Builder builder; - if (input.has("scenario")) - builder = new RecognizeConfig.Builder(input.getString("scenario")); - else - builder = new RecognizeConfig.Builder(RegulaConfig.OnlineProcessingConfigFromJSON(input.getJSONObject("onlineProcessingConfig"))); - if (input.has("livePortrait")) - builder.setLivePortrait(bitmapFromBase64(input.getString("livePortrait"))); - if (input.has("extPortrait")) - builder.setExtPortrait(bitmapFromBase64(input.getString("extPortrait"))); - if (input.has("image")) - builder.setBitmap(bitmapFromBase64(input.getString("image"))); - if (input.has("oneShotIdentification")) - builder.setOneShotIdentification(input.getBoolean("oneShotIdentification")); - if (input.has("images")) { - JSONArray base64Images = input.getJSONArray("images"); - Bitmap[] images = new Bitmap[base64Images.length()]; - for (int i = 0; i < images.length; i++) - images[i] = bitmapFromBase64(base64Images.getString(i)); - builder.setBitmaps(images); - } - if (input.has("imageInputData")) { - JSONArray base64InputData = input.getJSONArray("imageInputData"); - ImageInputData[] inputData = new ImageInputData[base64InputData.length()]; - for (int i = 0; i < inputData.length; i++) - inputData[i] = ImageInputDataFromJSON(base64InputData.getJSONObject(i)); - builder.setImageInputData(inputData); - } - return builder.build(); - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static ImageQA ImageQAFromJSON(JSONObject input) { - if (input == null) return null; - ImageQA result = new ImageQA(); - try { - if (input.has("dpiThreshold")) - result.dpiThreshold = input.getInt("dpiThreshold"); - if (input.has("angleThreshold")) - result.angleThreshold = input.getInt("angleThreshold"); - if (input.has("focusCheck")) - result.focusCheck = input.getBoolean("focusCheck"); - if (input.has("glaresCheck")) - result.glaresCheck = input.getBoolean("glaresCheck"); - if (input.has("colornessCheck")) - result.colornessCheck = input.getBoolean("colornessCheck"); - if (input.has("moireCheck")) - result.moireCheck = input.getBoolean("moireCheck"); - if (input.has("expectedPass")) - result.expectedPass = intArrayFromJSON(input.getJSONArray("expectedPass")); - if (input.has("documentPositionIndent")) - result.documentPositionIndent = input.getInt("documentPositionIndent"); - if (input.has("glaresCheckParams")) - result.glaresCheckParams = GlaresCheckParamsFromJSON(input.getJSONObject("glaresCheckParams")); - } catch (JSONException e) { - e.printStackTrace(); - } - - return result; - } - - static ImageQA.GlaresCheckParams GlaresCheckParamsFromJSON(JSONObject input) { - if (input == null) return null; - ImageQA.GlaresCheckParams result = new ImageQA.GlaresCheckParams(); - try { - if (input.has("imgMarginPart")) - result.imgMarginPart = input.getDouble("imgMarginPart"); - if (input.has("maxGlaringPart")) - result.maxGlaringPart = input.getDouble("maxGlaringPart"); - } catch (JSONException e) { - e.printStackTrace(); - } - - return result; - } - - static JSONObject generateImageQA(ImageQA input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("dpiThreshold", input.dpiThreshold); - result.put("angleThreshold", input.angleThreshold); - result.put("focusCheck", input.focusCheck); - result.put("glaresCheck", input.glaresCheck); - result.put("colornessCheck", input.colornessCheck); - result.put("moireCheck", input.moireCheck); - result.put("documentPositionIndent", input.documentPositionIndent); - result.put("expectedPass", generateIntArray(input.expectedPass)); - result.put("glaresCheckParams", generateGlaresCheckParams(input.glaresCheckParams)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateGlaresCheckParams(ImageQA.GlaresCheckParams input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("imgMarginPart", input.imgMarginPart); - result.put("maxGlaringPart", input.maxGlaringPart); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - // To JSON - - static JSONObject generateDocumentReaderScenario(DocumentReaderScenario input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("name", input.name); - result.put("caption", input.caption); - result.put("description", input.description); - result.put("multiPageOff", input.multiPageOff); - result.put("frameKWHLandscape", input.frameKWHLandscape); - result.put("frameKWHPortrait", input.frameKWHPortrait); - result.put("frameKWHDoublePageSpreadPortrait", input.frameKWHDoublePageSpreadPortrait); - result.put("frameKWHDoublePageSpreadLandscape", input.frameKWHDoublePageSpreadLandscape); - result.put("frameOrientation", input.frameOrientation); - result.put("uvTorch", input.uvTorch); - result.put("faceExt", input.faceExt); - result.put("seriesProcessMode", input.seriesProcessMode); - result.put("manualCrop", input.manualCrop); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateRect(Rect input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("bottom", input.bottom); - result.put("top", input.top); - result.put("left", input.left); - result.put("right", input.right); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocReaderFieldRect(DocReaderFieldRect input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("bottom", input.bottom); - result.put("top", input.top); - result.put("left", input.left); - result.put("right", input.right); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderGraphicField(DocumentReaderGraphicField input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("sourceType", input.sourceType); - result.put("fieldType", input.fieldType); - result.put("light", input.light); - result.put("pageIndex", input.pageIndex); - result.put("originalPageIndex", input.originalPageIndex); - result.put("fieldName", eGraphicFieldType.getTranslation(context, input.fieldType)); - result.put("lightName", eRPRM_Lights.getTranslation(context, input.light)); - result.put("value", input.imageBase64()); - result.put("fieldRect", generateDocReaderFieldRect(input.boundRect)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderGraphicResult(DocumentReaderGraphicResult input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("fields", generateList(input.fields, JSONConstructor::generateDocumentReaderGraphicField, context)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderValue(DocumentReaderValue input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("pageIndex", input.pageIndex); - result.put("sourceType", input.sourceType); - result.put("validity", input.validity); - result.put("probability", input.probability); - result.put("value", input.value); - result.put("originalValue", input.originalValue); - result.put("boundRect", generateRect(input.boundRect)); - result.put("comparison", generateMap(input.comparison)); - result.put("originalSymbols", generateList(input.originalSymbols, JSONConstructor::generateDocumentReaderSymbol)); - result.put("rfidOrigin", generateDocumentReaderRfidOrigin(input.rfidOrigin)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderTextField(DocumentReaderTextField input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("fieldType", input.fieldType); - result.put("lcid", input.lcid); - result.put("status", input.status); - result.put("lcidName", input.getLcidName(context)); - result.put("fieldName", input.getFieldName(context)); - result.put("value", input.value); - result.put("getValue", generateDocumentReaderValue(input.value(), context)); - result.put("values", generateList(input.values, JSONConstructor::generateDocumentReaderValue, context)); - result.put("comparisonList", generateList(input.comparisonList, JSONConstructor::generateDocumentReaderComparison)); - result.put("validityList", generateList(input.validityList, JSONConstructor::generateDocumentReaderValidity)); - result.put("comparisonStatus", input.comparisonStatus); - result.put("validityStatus", input.validityStatus); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderTextResult(DocumentReaderTextResult input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("status", input.status); - result.put("comparisonStatus", input.comparisonStatus); - result.put("validityStatus", input.validityStatus); - result.put("availableSourceList", generateList(input.availableSourceList, JSONConstructor::generateDocumentReaderTextSource)); - result.put("fields", generateList(input.fields, JSONConstructor::generateDocumentReaderTextField, context)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateCoordinate(Coordinate input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("x", input.x); - result.put("y", input.y); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateElementPosition(ElementPosition input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("docFormat", input.docFormat); - result.put("width", input.width); - result.put("height", input.height); - result.put("dpi", input.dpi); - result.put("pageIndex", input.pageIndex); - result.put("inverse", input.inverse); - result.put("perspectiveTr", input.perspectiveTr); - result.put("objArea", input.objArea); - result.put("objIntAngleDev", input.objIntAngleDev); - result.put("resultStatus", input.resultStatus); - result.put("angle", input.angle); - result.put("center", generateCoordinate(input.center)); - result.put("leftTop", generateCoordinate(input.leftTop)); - result.put("leftBottom", generateCoordinate(input.leftBottom)); - result.put("rightTop", generateCoordinate(input.rightTop)); - result.put("rightBottom", generateCoordinate(input.rightBottom)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateImageQuality(ImageQuality input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("featureType", input.featureType); - result.put("result", input.result); - result.put("type", input.type); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateImageQualityGroup(ImageQualityGroup input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("count", input.count); - result.put("result", input.result); - result.put("imageQualityList", generateList(input.imageQualityList, JSONConstructor::generateImageQuality)); - result.put("pageIndex", input.pageIndex); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderDocumentType(DocumentReaderDocumentType input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("pageIndex", input.pageIndex); - result.put("documentID", input.documentID); - result.put("dType", input.dType); - result.put("dFormat", input.dFormat); - result.put("dMRZ", input.dMRZ); - result.put("isDeprecated", input.isDeprecated); - result.put("name", input.name); - result.put("ICAOCode", input.ICAOCode); - result.put("dDescription", input.dDescription); - result.put("dYear", input.dYear); - result.put("dCountryName", input.dCountryName); - result.put("FDSID", generateIntArray(input.FDSID)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderNotification(DocumentReaderNotification input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("notificationCode", input.getNotificationCode()); - result.put("dataFileType", input.getDataFileType()); - result.put("progress", input.getProgress()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateAccessControlProcedureType(AccessControlProcedureType input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("activeOptionIdx", input.activeOptionIdx); - result.put("type", input.type); - result.put("status", input.status); - result.put("notifications", generateList(input.notifications)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateFileData(FileData input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("length", input.length); - result.put("type", input.type); - result.put("status", input.status); - result.put("data", input.data); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateCertificateData(CertificateData input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("length", input.length); - result.put("data", input.data); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateSecurityObjectCertificates(SecurityObjectCertificates input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("securityObject", generateCertificateData(input.securityObject)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateFile(File input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("readingTime", input.readingTime); - result.put("type", input.type); - result.put("pAStatus", input.pAStatus); - result.put("readingStatus", input.readingStatus); - result.put("fileID", input.fileID); - result.put("fileData", generateFileData(input.fileData)); - result.put("certificates", generateSecurityObjectCertificates(input.certificates)); - result.put("docFieldsText", generateList(input.docFieldsText)); - result.put("docFieldsGraphics", generateList(input.docFieldsGraphics)); - result.put("docFieldsOriginals", generateList(input.docFieldsOriginals)); - result.put("notifications", generateList(input.notifications)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateApplication(Application input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("type", input.type); - result.put("status", input.status); - result.put("applicationID", input.applicationID); - result.put("dataHashAlgorithm", input.dataHashAlgorithm); - result.put("unicodeVersion", input.unicodeVersion); - result.put("version", input.version); - result.put("files", generateList(input.files, JSONConstructor::generateFile)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateValue(Value input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("length", input.length); - result.put("type", input.type); - result.put("status", input.status); - result.put("data", input.data); - result.put("format", input.format); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateAttribute(Attribute input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("type", input.type); - result.put("value", generateValue(input.value)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateAuthority(Authority input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", input.data); - result.put("friendlyName", generateValue(input.friendlyName)); - result.put("attributes", generateList(input.attributes, JSONConstructor::generateAttribute)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateExtension(Extension input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", input.data); - result.put("type", input.type); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateValidity(Validity input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("notAfter", generateValue(input.notAfter)); - result.put("notBefore", generateValue(input.notBefore)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateCertificateChain(CertificateChain input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("origin", input.origin); - result.put("type", input.type); - result.put("version", input.version); - result.put("paStatus", input.paStatus); - result.put("serialNumber", input.serialNumber); - result.put("signatureAlgorithm", input.signatureAlgorithm); - result.put("subjectPKAlgorithm", input.subjectPKAlgorithm); - result.put("fileName", generateValue(input.fileName)); - result.put("validity", generateValidity(input.validity)); - result.put("issuer", generateAuthority(input.issuer)); - result.put("subject", generateAuthority(input.subject)); - result.put("notifications", generateList(input.notifications)); - result.put("extensions", generateList(input.extensions, JSONConstructor::generateExtension)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateSignerInfo(SignerInfo input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("version", input.version); - result.put("paStatus", input.paStatus); - result.put("dataToHash", input.dataToHash); - result.put("digestAlgorithm", input.digestAlgorithm); - result.put("signatureAlgorithm", input.signatureAlgorithm); - result.put("serialNumber", generateValue(input.serialNumber)); - result.put("signature", generateValue(input.signature)); - result.put("subjectKeyIdentifier", generateValue(input.subjectKeyIdentifier)); - result.put("issuer", generateAuthority(input.issuer)); - result.put("notifications", generateList(input.notifications)); - result.put("signedAttributes", generateList(input.signedAttributes, JSONConstructor::generateExtension)); - result.put("certificateChain", generateList(input.certificateChain, JSONConstructor::generateCertificateChain)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateSecurityObject(SecurityObject input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("fileReference", input.fileReference); - result.put("version", input.version); - result.put("objectType", input.objectType); - result.put("notifications", generateList(input.notifications)); - result.put("signerInfos", generateList(input.signerInfos, JSONConstructor::generateSignerInfo)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateCardProperties(CardProperties input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("aTQA", input.aTQA); - result.put("bitRateR", input.bitRateR); - result.put("bitRateS", input.bitRateS); - result.put("chipTypeA", input.chipTypeA); - result.put("mifareMemory", input.mifareMemory); - result.put("rfidType", input.rfidType); - result.put("sAK", input.sAK); - result.put("support4", input.support4); - result.put("supportMifare", input.supportMifare); - result.put("aTQB", input.aTQB); - result.put("aTR", input.aTR); - result.put("baudrate1", input.baudrate1); - result.put("baudrate2", input.baudrate2); - result.put("uID", input.uID); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateRFIDSessionData(RFIDSessionData input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("totalBytesReceived", input.totalBytesReceived); - result.put("totalBytesSent", input.totalBytesSent); - result.put("status", input.status); - result.put("extLeSupport", input.extLeSupport); - result.put("processTime", input.processTime); - result.put("cardProperties", generateCardProperties(input.cardProperties)); - result.put("accessControls", generateList(input.accessControls, JSONConstructor::generateAccessControlProcedureType)); - result.put("applications", generateList(input.applications, JSONConstructor::generateApplication)); - result.put("securityObjects", generateList(input.securityObjects, JSONConstructor::generateSecurityObject)); - result.put("dataGroups", generateIntArray(input.dataGroups)); - result.put("dataFields", generateList(input.dataFields, JSONConstructor::generateDataField)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDataField(DataField input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", input.getData()); - result.put("fieldType", input.getFieldType()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderAuthenticityCheck(DocumentReaderAuthenticityCheck input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("type", input.type); - result.put("status", input.getStatus()); - result.put("typeName", input.getTypeName(context)); - result.put("pageIndex", input.pageIndex); - result.put("elements", generateList(input.elements, JSONConstructor::generateDocumentReaderAuthenticityElement, context)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generatePDF417Info(PDF417Info input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("errorLevel", input.errorLevel); - result.put("columns", input.columns); - result.put("rows", input.rows); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderBarcodeResult(DocumentReaderBarcodeResult input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("fields", generateList(input.fields, JSONConstructor::generateDocumentReaderBarcodeField)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderBarcodeField(DocumentReaderBarcodeField input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("barcodeType", input.barcodeType); - result.put("status", input.status); - result.put("pageIndex", input.pageIndex); - result.put("pdf417Info", generatePDF417Info(input.pdf417Info)); - result.put("data", generateByteArray(input.data)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderAuthenticityResult(DocumentReaderAuthenticityResult input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("status", input.getStatus()); - result.put("checks", generateList(input.checks, JSONConstructor::generateDocumentReaderAuthenticityCheck, context)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderAuthenticityElement(DocumentReaderAuthenticityElement input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("status", input.status); - result.put("elementType", input.elementType); - result.put("elementDiagnose", input.elementDiagnose); - result.put("elementTypeName", input.getElementTypeName(context)); - result.put("elementDiagnoseName", input.getElementDiagnoseName(context)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generatePAResourcesIssuer(PAResourcesIssuer input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", generateByteArray(input.data)); - result.put("friendlyName", input.friendlyName); - result.put("attributes", generateArray(input.attributes, JSONConstructor::generatePAAttribute)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generatePAAttribute(PAAttribute input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("type", input.type); - result.put("value", input.value); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateTAChallenge(TAChallenge input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", generateByteArray(input.data)); - result.put("auxPCD", input.auxPCD); - result.put("challengePICC", input.challengePICC); - result.put("hashPK", input.hashPK); - result.put("idPICC", input.idPICC); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderResultsStatus(DocumentReaderResultsStatus input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("overallStatus", input.getOverallStatus()); - result.put("optical", input.getOptical()); - result.put("detailsOptical", generateDetailsOptical(input.getDetailsOptical())); - result.put("rfid", input.getRfid()); - result.put("detailsRFID", generateDetailsRFID(input.getDetailsRFID())); - result.put("portrait", input.getPortrait()); - result.put("stopList", input.getStopList()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDetailsOptical(DocumentReaderResultsStatus.DetailsOptical input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("overallStatus", input.getOverallStatus()); - result.put("mrz", input.getMrz()); - result.put("text", input.getText()); - result.put("docType", input.getDocType()); - result.put("security", input.getSecurity()); - result.put("imageQA", input.getImageQA()); - result.put("expiry", input.getExpiry()); - result.put("vds", input.getVds()); - result.put("pagesCount", input.getPagesCount()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDetailsRFID(DocumentReaderResultsStatus.DetailsRFID input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("pa", input.getPA()); - result.put("ca", input.getCA()); - result.put("aa", input.getAA()); - result.put("ta", input.getTA()); - result.put("bac", input.getBAC()); - result.put("pace", input.getPACE()); - result.put("overallStatus", input.getOverallStatus()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateVDSNCData(VDSNCData input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("type", input.getType()); - result.put("version", input.getVersion()); - result.put("issuingCountry", input.getIssuingCountry()); - result.put("message", input.getMessage()); - result.put("signatureAlgorithm", input.getSignatureAlg()); - result.put("signature", generateBytesData(input.getSignature())); - result.put("certificate", generateBytesData(input.getCertificate())); - result.put("certificateChain", generateList(input.getCertificateChain(), JSONConstructor::generateCertificateChain)); - result.put("notifications", generateLongArray(input.getNotifications())); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateBytesData(BytesData input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("data", input.getData()); - result.put("length", input.getLength()); - result.put("status", input.getStatus()); - result.put("type", input.getType()); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocReaderDocumentsDatabase(DocReaderDocumentsDatabase input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("databaseID", input.databaseID); - result.put("version", input.version); - result.put("date", input.date); - result.put("databaseDescription", input.databaseDescription); - result.put("countriesNumber", input.countriesNumber); - result.put("documentsNumber", input.documentsNumber); - result.put("size", input.size); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderComparison(DocumentReaderComparison input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("sourceTypeLeft", input.sourceTypeLeft); - result.put("sourceTypeRight", input.sourceTypeRight); - result.put("status", input.status); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderRfidOrigin(DocumentReaderRfidOrigin input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("dg", input.dg); - result.put("dgTag", input.dgTag); - result.put("entryView", input.entryView); - result.put("tagEntry", input.tagEntry); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderTextSource(DocumentReaderTextSource input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("sourceType", input.sourceType); - result.put("source", input.source); - result.put("validityStatus", input.validityStatus); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderSymbol(DocumentReaderSymbol input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("code", input.code); - result.put("rect", generateRect(input.rect)); - result.put("probability", input.probability); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderValidity(DocumentReaderValidity input) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("sourceType", input.sourceType); - result.put("status", input.status); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - static JSONObject generateDocumentReaderResults(DocumentReaderResults input, Context context) { - JSONObject result = new JSONObject(); - if (input == null) return null; - try { - result.put("videoCaptureSessionId", input.videoCaptureSessionId); - result.put("chipPage", input.chipPage); - result.put("irElapsedTime", input.irElapsedTime); - result.put("processingFinishedStatus", input.processingFinishedStatus); - result.put("elapsedTime", input.elapsedTime); - result.put("elapsedTimeRFID", input.elapsedTimeRFID); - result.put("morePagesAvailable", input.morePagesAvailable); - result.put("rfidResult", input.rfidResult); - result.put("highResolution", input.highResolution); - result.put("graphicResult", generateDocumentReaderGraphicResult(input.graphicResult, context)); - result.put("textResult", generateDocumentReaderTextResult(input.textResult, context)); - result.put("documentPosition", generateList(input.documentPosition, JSONConstructor::generateElementPosition)); - result.put("barcodePosition", generateList(input.barcodePosition, JSONConstructor::generateElementPosition)); - result.put("mrzPosition", generateList(input.mrzPosition, JSONConstructor::generateElementPosition)); - result.put("imageQuality", generateList(input.imageQuality, JSONConstructor::generateImageQualityGroup)); - result.put("rawResult", input.rawResult); - result.put("documentReaderNotification", generateDocumentReaderNotification(input.documentReaderNotification)); - result.put("rfidSessionData", generateRFIDSessionData(input.rfidSessionData)); - result.put("authenticityResult", generateDocumentReaderAuthenticityResult(input.authenticityResult, context)); - result.put("barcodeResult", generateDocumentReaderBarcodeResult(input.barcodeResult)); - result.put("ppmIn", input.ppmIn); - result.put("documentType", generateList(input.documentType, JSONConstructor::generateDocumentReaderDocumentType)); - result.put("status", generateDocumentReaderResultsStatus(input.status)); - result.put("vdsncData", generateVDSNCData(input.vdsncData)); - } catch (JSONException e) { - e.printStackTrace(); - } - return result; - } - - // From JSON -} \ No newline at end of file diff --git a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/RegulaConfig.java b/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/RegulaConfig.java deleted file mode 100644 index a6ced3756d..0000000000 --- a/android/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api/RegulaConfig.java +++ /dev/null @@ -1,830 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api; - -import static io.flutter.plugins.regula.documentreader.flutter_document_reader_api.Helpers.*; -import static io.flutter.plugins.regula.documentreader.flutter_document_reader_api.JSONConstructor.*; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.graphics.Paint; -import android.graphics.Typeface; -import android.text.SpannableString; -import android.widget.ImageView.ScaleType; - -import com.regula.documentreader.api.DocumentReader; -import com.regula.documentreader.api.params.*; -import com.regula.documentreader.api.params.rfid.RFIDParams; -import com.regula.documentreader.api.params.rfid.ReprocParams; -import com.regula.documentreader.api.params.rfid.dg.DataGroups; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.math.BigDecimal; - -@SuppressWarnings("deprecation") -class RegulaConfig { - static void setConfig(DocumentReader reader, JSONObject opts, Context context) throws JSONException { - if (opts.has("customization")) - setCustomization(reader.customization(), opts.getJSONObject("customization"), context); - if (opts.has("functionality")) - setFunctionality(reader.functionality(), opts.getJSONObject("functionality")); - if (opts.has("processParams")) - setProcessParams(reader.processParams(), opts.getJSONObject("processParams")); - } - - static JSONObject getConfig(DocumentReader reader) throws JSONException { - JSONObject object = new JSONObject(); - object.put("customization", getCustomization(reader.customization())); - object.put("functionality", getFunctionality(reader.functionality())); - object.put("processParams", getProcessParams(reader.processParams())); - - return object; - } - - @SuppressLint("MissingPermission") - private static void setFunctionality(Functionality functionality, JSONObject opts) throws JSONException { - Functionality.FunctionalityEditor editor = functionality.edit(); - if (opts.has("pictureOnBoundsReady")) - editor.setPictureOnBoundsReady(opts.getBoolean("pictureOnBoundsReady")); - if (opts.has("showTorchButton")) - editor.setShowTorchButton(opts.getBoolean("showTorchButton")); - if (opts.has("showCloseButton")) - editor.setShowCloseButton(opts.getBoolean("showCloseButton")); - if (opts.has("videoCaptureMotionControl")) - editor.setVideoCaptureMotionControl(opts.getBoolean("videoCaptureMotionControl")); - if (opts.has("showCaptureButton")) - editor.setShowCaptureButton(opts.getBoolean("showCaptureButton")); - if (opts.has("showChangeFrameButton")) - editor.setShowChangeFrameButton(opts.getBoolean("showChangeFrameButton")); - if (opts.has("showCaptureButtonDelayFromDetect")) - editor.setShowCaptureButtonDelayFromDetect(opts.getInt("showCaptureButtonDelayFromDetect")); - if (opts.has("showCaptureButtonDelayFromStart")) - editor.setShowCaptureButtonDelayFromStart(opts.getInt("showCaptureButtonDelayFromStart")); - if (opts.has("databaseAutoupdate")) - editor.setDatabaseAutoupdate(opts.getBoolean("databaseAutoupdate")); - if (opts.has("showSkipNextPageButton")) - editor.setShowSkipNextPageButton(opts.getBoolean("showSkipNextPageButton")); - if (opts.has("useAuthenticator")) - editor.setUseAuthenticator(opts.getBoolean("useAuthenticator")); - if (opts.has("skipFocusingFrames")) - editor.setSkipFocusingFrames(opts.getBoolean("skipFocusingFrames")); - if (opts.has("showCameraSwitchButton")) - editor.setShowCameraSwitchButton(opts.getBoolean("showCameraSwitchButton")); - if (opts.has("cameraFrame")) - editor.setCameraFrame(opts.getString("cameraFrame")); - if (opts.has("btDeviceName")) - editor.setBtDeviceName(opts.getString("btDeviceName")); - if (opts.has("orientation")) - editor.setOrientation(opts.getInt("orientation")); - if (opts.has("startDocReaderForResult")) - editor.setStartDocReaderForResult(opts.getBoolean("startDocReaderForResult")); - if (opts.has("captureMode")) - editor.setCaptureMode(opts.getInt("captureMode")); - if (opts.has("displayMetadata")) - editor.setDisplayMetadata(opts.getBoolean("displayMetadata")); - if (opts.has("cameraSize")) - editor.setCameraSize(opts.getJSONObject("cameraSize").getInt("width"), opts.getJSONObject("cameraSize").getInt("height")); - if (opts.has("cameraMode")) - editor.setCameraMode(opts.getInt("cameraMode")); - if (opts.has("excludedCamera2Models")) - editor.setExcludedCamera2Models(stringListFromJson(opts.getJSONArray("excludedCamera2Models"))); - if (opts.has("isZoomEnabled")) - editor.setZoomEnabled(opts.getBoolean("isZoomEnabled")); - if (opts.has("zoomFactor")) - editor.setZoomFactor(BigDecimal.valueOf(opts.getDouble("zoomFactor")).floatValue()); - if (opts.has("isCameraTorchCheckDisabled")) - editor.setIsCameraTorchCheckDisabled(opts.getBoolean("isCameraTorchCheckDisabled")); - if (opts.has("recordScanningProcess")) - editor.setDoRecordProcessingVideo(opts.getBoolean("recordScanningProcess")); - if (opts.has("manualMultipageMode")) - editor.setManualMultipageMode(opts.getBoolean("manualMultipageMode")); - if (opts.has("exposure")) - editor.setExposure(BigDecimal.valueOf(opts.getDouble("exposure")).floatValue()); - if (opts.has("rfidTimeout")) - editor.setRfidTimeout(opts.getInt("rfidTimeout")); - if (opts.has("onlineProcessingConfiguration")) - editor.setOnlineProcessingConfiguration(OnlineProcessingConfigFromJSON(opts.getJSONObject("onlineProcessingConfiguration"))); - - editor.apply(); - } - - private static void setProcessParams(ProcessParam processParams, JSONObject opts) throws JSONException { - if (opts.has("multipageProcessing")) - processParams.multipageProcessing = opts.getBoolean("multipageProcessing"); - if (opts.has("dateFormat")) - processParams.dateFormat = opts.getString("dateFormat"); - if (opts.has("logs")) - processParams.setLogs(opts.getBoolean("logs")); - if (opts.has("debugSaveImages")) - processParams.debugSaveImages = opts.getBoolean("debugSaveImages"); - if (opts.has("debugSaveLogs")) - processParams.debugSaveLogs = opts.getBoolean("debugSaveLogs"); - if (opts.has("returnUncroppedImage")) - processParams.returnUncroppedImage = opts.getBoolean("returnUncroppedImage"); - if (opts.has("customParams")) - processParams.customParams = opts.getJSONObject("customParams"); - if (opts.has("uvTorchEnabled")) - processParams.uvTorchEnabled = opts.getBoolean("uvTorchEnabled"); - if (opts.has("debugSaveCroppedImages")) - processParams.debugSaveCroppedImages = opts.getBoolean("debugSaveCroppedImages"); - if (opts.has("scenario")) - processParams.scenario = opts.getString("scenario"); - if (opts.has("measureSystem")) - processParams.measureSystem = opts.getInt("measureSystem"); - if (opts.has("captureButtonScenario")) - processParams.captureButtonScenario = opts.getString("captureButtonScenario"); - if (opts.has("disableFocusingCheck")) - processParams.disableFocusingCheck = opts.getBoolean("disableFocusingCheck"); - if (opts.has("debugSaveRFIDSession")) - processParams.debugSaveRFIDSession = opts.getBoolean("debugSaveRFIDSession"); - if (opts.has("doublePageSpread")) - processParams.doublePageSpread = opts.getBoolean("doublePageSpread"); - if (opts.has("barcodeParserType")) - processParams.barcodeParserType = opts.getInt("barcodeParserType"); - if (opts.has("documentIDList")) - processParams.documentIDList = intArrayFromJson(opts.getJSONArray("documentIDList")); - if (opts.has("fieldTypesFilter")) - processParams.fieldTypesFilter = intArrayFromJson(opts.getJSONArray("fieldTypesFilter")); - if (opts.has("barcodeTypes")) - processParams.doBarcodes = barcodeTypeArrayFromJson(opts.getJSONArray("barcodeTypes")); - if (opts.has("faceMetaData")) - processParams.faceMetaData = faceMetaDataArrayFromJson(opts.getJSONArray("faceMetaData")); - if (opts.has("timeout")) - processParams.timeout = opts.getDouble("timeout"); - if (opts.has("timeoutFromFirstDetect")) - processParams.timeoutFromFirstDetect = opts.getDouble("timeoutFromFirstDetect"); - if (opts.has("timeoutFromFirstDocType")) - processParams.timeoutFromFirstDocType = opts.getDouble("timeoutFromFirstDocType"); - if (opts.has("manualCrop")) - processParams.manualCrop = opts.getBoolean("manualCrop"); - if (opts.has("perspectiveAngle")) - processParams.perspectiveAngle = opts.getInt("perspectiveAngle"); - if (opts.has("integralImage")) - processParams.integralImage = opts.getBoolean("integralImage"); - if (opts.has("minDPI")) - processParams.minDPI = opts.getInt("minDPI"); - if (opts.has("returnCroppedBarcode")) - processParams.returnCroppedBarcode = opts.getBoolean("returnCroppedBarcode"); - if (opts.has("checkHologram")) - processParams.checkHologram = opts.getBoolean("checkHologram"); - if (opts.has("checkRequiredTextFields")) - processParams.checkRequiredTextFields = opts.getBoolean("checkRequiredTextFields"); - if (opts.has("depersonalizeLog")) - processParams.depersonalizeLog = opts.getBoolean("depersonalizeLog"); - if (opts.has("resultTypeOutput")) - processParams.resultTypeOutput = intArrayFromJson(opts.getJSONArray("resultTypeOutput")); - if (opts.has("generateDoublePageSpreadImage")) - processParams.generateDoublePageSpreadImage = opts.getBoolean("generateDoublePageSpreadImage"); - if (opts.has("imageDpiOutMax")) - processParams.imageDpiOutMax = opts.getInt("imageDpiOutMax"); - if (opts.has("alreadyCropped")) - processParams.alreadyCropped = opts.getBoolean("alreadyCropped"); - if (opts.has("forceDocID")) - processParams.forceDocID = opts.getInt("forceDocID"); - if (opts.has("matchTextFieldMask")) - processParams.matchTextFieldMask = opts.getBoolean("matchTextFieldMask"); - if (opts.has("fastDocDetect")) - processParams.fastDocDetect = opts.getBoolean("fastDocDetect"); - if (opts.has("updateOCRValidityByGlare")) - processParams.updateOCRValidityByGlare = opts.getBoolean("updateOCRValidityByGlare"); - if (opts.has("imageQA")) - processParams.imageQA = ImageQAFromJSON(opts.getJSONObject("imageQA")); - if (opts.has("forceDocFormat")) - processParams.forceDocFormat = opts.getInt("forceDocFormat"); - if (opts.has("noGraphics")) - processParams.noGraphics = opts.getBoolean("noGraphics"); - if (opts.has("documentAreaMin")) - processParams.documentAreaMin = opts.getDouble("documentAreaMin"); - if (opts.has("multiDocOnImage")) - processParams.multiDocOnImage = opts.getBoolean("multiDocOnImage"); - if (opts.has("shiftExpiryDate")) - processParams.shiftExpiryDate = opts.getInt("shiftExpiryDate"); - if (opts.has("minimalHolderAge")) - processParams.minimalHolderAge = opts.getInt("minimalHolderAge"); - if (opts.has("mrzFormatsFilter")) - processParams.mrzFormatsFilter = stringArrayFromJson(opts.getJSONArray("mrzFormatsFilter")); - if (opts.has("forceReadMrzBeforeLocate")) - processParams.forceReadMrzBeforeLocate = opts.getBoolean("forceReadMrzBeforeLocate"); - if (opts.has("parseBarcodes")) - processParams.parseBarcodes = opts.getBoolean("parseBarcodes"); - if (opts.has("shouldReturnPackageForReprocess")) - processParams.shouldReturnPackageForReprocess = opts.getBoolean("shouldReturnPackageForReprocess"); - if (opts.has("imageOutputMaxHeight")) - processParams.imageOutputMaxHeight = opts.getInt("imageOutputMaxHeight"); - if (opts.has("imageOutputMaxWidth")) - processParams.imageOutputMaxWidth = opts.getInt("imageOutputMaxWidth"); - if (opts.has("disablePerforationOCR")) - processParams.disablePerforationOCR = opts.getBoolean("disablePerforationOCR"); - if (opts.has("documentGroupFilter")) - processParams.documentGroupFilter = intArrayFromJson(opts.getJSONArray("documentGroupFilter")); - if (opts.has("respectImageQuality")) - processParams.respectImageQuality = opts.getBoolean("respectImageQuality"); - if (opts.has("splitNames")) - processParams.splitNames = opts.getBoolean("splitNames"); - if (opts.has("convertCase")) - processParams.convertCase = opts.getInt("convertCase"); - if (opts.has("doFlipYAxis")) - processParams.doFlipYAxis = opts.getBoolean("doFlipYAxis"); - if (opts.has("rfidParams")) - processParams.rfidParams = RFIDParamsFromJSON(opts.getJSONObject("rfidParams")); - if (opts.has("doDetectCan")) - processParams.doDetectCan = opts.getBoolean("doDetectCan"); - if (opts.has("faceApiParams")) - processParams.faceApiParams = FaceApiParamsFromJSON(opts.getJSONObject("faceApiParams")); - if (opts.has("useFaceApi")) - processParams.useFaceApi = opts.getBoolean("useFaceApi"); - } - - private static void setCustomization(ParamsCustomization customization, JSONObject opts, Context context) throws JSONException { - ParamsCustomization.CustomizationEditor editor = customization.edit(); - if (opts.has("status")) - editor.setStatus(opts.getString("status")); - if (opts.has("resultStatus")) - editor.setResultStatus(opts.getString("resultStatus")); - if (opts.has("cameraFrameDefaultColor")) - editor.setCameraFrameDefaultColor(opts.getString("cameraFrameDefaultColor")); - if (opts.has("cameraFrameActiveColor")) - editor.setCameraFrameActiveColor(opts.getString("cameraFrameActiveColor")); - if (opts.has("statusTextColor")) - editor.setStatusTextColor(opts.getString("statusTextColor")); - if (opts.has("resultStatusTextColor")) - editor.setResultStatusTextColor(opts.getString("resultStatusTextColor")); - if (opts.has("resultStatusBackgroundColor")) - editor.setResultStatusBackgroundColor(opts.getString("resultStatusBackgroundColor")); - if (opts.has("multipageButtonBackgroundColor")) - editor.setMultipageButtonBackgroundColor(opts.getString("multipageButtonBackgroundColor")); - if (opts.has("tintColor")) - editor.setTintColor(opts.getString("tintColor")); - if (opts.has("cameraPreviewBackgroundColor")) - editor.setCameraPreviewBackgroundColor(opts.getString("cameraPreviewBackgroundColor")); - if (opts.has("activityIndicatorColor")) - editor.setActivityIndicatorColor(opts.getString("activityIndicatorColor")); - if (opts.has("showStatusMessages")) - editor.setShowStatusMessages(opts.getBoolean("showStatusMessages")); - if (opts.has("showResultStatusMessages")) - editor.setShowResultStatusMessages(opts.getBoolean("showResultStatusMessages")); - if (opts.has("showHelpAnimation")) - editor.setShowHelpAnimation(opts.getBoolean("showHelpAnimation")); - if (opts.has("showNextPageAnimation")) - editor.setShowNextPageAnimation(opts.getBoolean("showNextPageAnimation")); - if (opts.has("showBackgroundMask")) - editor.setShowBackgroundMask(opts.getBoolean("showBackgroundMask")); - if (opts.has("cameraFrameBorderWidth")) - editor.setCameraFrameBorderWidth(opts.getInt("cameraFrameBorderWidth")); - if (opts.has("statusTextSize")) - editor.setStatusTextSize(opts.getInt("statusTextSize")); - if (opts.has("cameraFrameLineLength")) - editor.setCameraFrameLineLength(opts.getInt("cameraFrameLineLength")); - if (opts.has("cameraFrameShapeType")) - editor.setCameraFrameShapeType(opts.getInt("cameraFrameShapeType")); - if (opts.has("resultStatusTextSize")) - editor.setResultStatusTextSize(opts.getInt("resultStatusTextSize")); - if (opts.has("cameraFrameOffsetWidth")) - editor.setCameraFrameOffsetWidth(opts.getInt("cameraFrameOffsetWidth")); - if (opts.has("customLabelStatus")) - editor.setCustomLabelStatus(new SpannableString(opts.getString("customLabelStatus"))); - if (opts.has("multipageAnimationFrontImage")) - editor.setMultipageAnimationFrontImage(drawableFromBase64(opts.getString("multipageAnimationFrontImage"), context)); - if (opts.has("multipageAnimationBackImage")) - editor.setMultipageAnimationBackImage(drawableFromBase64(opts.getString("multipageAnimationBackImage"), context)); - if (opts.has("borderBackgroundImage")) - editor.setBorderBackgroundImage(drawableFromBase64(opts.getString("borderBackgroundImage"), context)); - if (opts.has("helpAnimationImage")) - editor.setHelpAnimationImage(drawableFromBase64(opts.getString("helpAnimationImage"), context)); - if (opts.has("statusPositionMultiplier")) - editor.setStatusPositionMultiplier(BigDecimal.valueOf(opts.getDouble("statusPositionMultiplier")).floatValue()); - if (opts.has("resultStatusPositionMultiplier")) - editor.setResultStatusPositionMultiplier(BigDecimal.valueOf(opts.getDouble("resultStatusPositionMultiplier")).floatValue()); - if (opts.has("backgroundMaskAlpha")) - editor.setBackgroundMaskAlpha((float) opts.getDouble("backgroundMaskAlpha")); - if (opts.has("statusTextFont")) - editor.setStatusTextFont(Typeface.create(opts.getString("statusTextFont"), opts.has("statusTextFontStyle") ? opts.getInt("statusTextFontStyle") : Typeface.NORMAL)); - if (opts.has("resultStatusTextFont")) - editor.setResultStatusTextFont(Typeface.create(opts.getString("resultStatusTextFont"), opts.has("resultStatusTextFontStyle") ? opts.getInt("resultStatusTextFontStyle") : Typeface.NORMAL)); - if (opts.has("helpAnimationImageScaleType")) - editor.setHelpAnimationImageScaleType(ScaleType.valueOf(opts.getString("helpAnimationImageScaleType"))); - if (opts.has("multipageAnimationFrontImageScaleType")) - editor.setMultipageAnimationFrontImageScaleType(ScaleType.valueOf(opts.getString("multipageAnimationFrontImageScaleType"))); - if (opts.has("multipageAnimationBackImageScaleType")) - editor.setMultipageAnimationBackImageScaleType(ScaleType.valueOf(opts.getString("multipageAnimationBackImageScaleType"))); - if (opts.has("borderBackgroundImageScaleType")) - editor.setBorderBackgroundImageScaleType(ScaleType.valueOf(opts.getString("borderBackgroundImageScaleType"))); - if (opts.has("helpAnimationImageMatrix")) - editor.setHelpAnimationImageMatrix(matrixFromFloatArray(floatArrayFromJson(opts.getJSONArray("helpAnimationImageMatrix")))); - if (opts.has("multipageAnimationFrontImageMatrix")) - editor.setMultipageAnimationFrontImageMatrix(matrixFromFloatArray(floatArrayFromJson(opts.getJSONArray("multipageAnimationFrontImageMatrix")))); - if (opts.has("multipageAnimationBackImageMatrix")) - editor.setMultipageAnimationBackImageMatrix(matrixFromFloatArray(floatArrayFromJson(opts.getJSONArray("multipageAnimationBackImageMatrix")))); - if (opts.has("borderBackgroundImageMatrix")) - editor.setBorderBackgroundImageMatrix(matrixFromFloatArray(floatArrayFromJson(opts.getJSONArray("borderBackgroundImageMatrix")))); - if (opts.has("customStatusPositionMultiplier")) - editor.setCustomStatusPositionMultiplier((float) opts.getDouble("customStatusPositionMultiplier")); - if (opts.has("cameraFrameVerticalPositionMultiplier")) - editor.setCameraFrameVerticalPositionMultiplier((float) opts.getDouble("cameraFrameVerticalPositionMultiplier")); - if (opts.has("cameraFrameLandscapeAspectRatio")) - editor.setCameraFrameLandscapeAspectRatio((float) opts.getDouble("cameraFrameLandscapeAspectRatio")); - if (opts.has("cameraFramePortraitAspectRatio")) - editor.setCameraFramePortraitAspectRatio((float) opts.getDouble("cameraFramePortraitAspectRatio")); - if (opts.has("cameraFrameCornerRadius")) - editor.setCameraFrameCornerRadius((float) opts.getDouble("cameraFrameCornerRadius")); - if (opts.has("cameraFrameLineCap")) - editor.setCameraFrameLineCap(Paint.Cap.values()[(opts.getInt("cameraFrameLineCap"))]); - if (opts.has("closeButtonImage")) - editor.setCloseButtonImage(drawableFromBase64(opts.getString("closeButtonImage"), context)); - if (opts.has("captureButtonImage")) - editor.setCaptureButtonImage(drawableFromBase64(opts.getString("captureButtonImage"), context)); - if (opts.has("changeFrameCollapseButtonImage")) - editor.setChangeFrameCollapseButtonImage(drawableFromBase64(opts.getString("changeFrameCollapseButtonImage"), context)); - if (opts.has("changeFrameExpandButtonImage")) - editor.setChangeFrameExpandButtonImage(drawableFromBase64(opts.getString("changeFrameExpandButtonImage"), context)); - if (opts.has("cameraSwitchButtonImage")) - editor.setCameraSwitchButtonImage(drawableFromBase64(opts.getString("cameraSwitchButtonImage"), context)); - if (opts.has("torchButtonOnImage")) - editor.setTorchImageOn(drawableFromBase64(opts.getString("torchButtonOnImage"), context)); - if (opts.has("torchButtonOffImage")) - editor.setTorchImageOff(drawableFromBase64(opts.getString("torchButtonOffImage"), context)); - if (opts.has("changeFrameButtonExpandImage")) - editor.setChangeFrameExpandButtonImage(drawableFromBase64(opts.getString("changeFrameButtonExpandImage"), context)); - if (opts.has("changeFrameButtonCollapseImage")) - editor.setChangeFrameCollapseButtonImage(drawableFromBase64(opts.getString("changeFrameButtonCollapseImage"), context)); - if (opts.has("toolbarSize")) - editor.setToolbarSize(BigDecimal.valueOf(opts.getDouble("toolbarSize")).floatValue()); - if (opts.has("statusBackgroundColor")) - editor.setStatusBackgroundColor(opts.getString("statusBackgroundColor")); - if (opts.has("hologramAnimationImage")) - editor.setHologramAnimationImage(drawableFromBase64(opts.getString("hologramAnimationImage"), context)); - if (opts.has("hologramAnimationPositionMultiplier")) - editor.setHologramAnimationPositionMultiplier((float) opts.getDouble("hologramAnimationPositionMultiplier")); - if (opts.has("hologramAnimationImageMatrix")) - editor.setHologramAnimationImageMatrix(matrixFromFloatArray(floatArrayFromJson(opts.getJSONArray("hologramAnimationImageMatrix")))); - if (opts.has("hologramAnimationImageScaleType")) - editor.setHologramAnimationImageScaleType(ScaleType.valueOf(opts.getString("hologramAnimationImageScaleType"))); - if (opts.has("uiCustomizationLayer")) - editor.setUiCustomizationLayer(opts.getJSONObject("uiCustomizationLayer")); - if (opts.has("activityIndicatorSize")) - editor.setActivityIndicatorSize(opts.getInt("activityIndicatorSize")); - - editor.applyImmediately(context); - } - - private static JSONObject getFunctionality(Functionality functionality) throws JSONException { - JSONObject object = new JSONObject(); - object.put("pictureOnBoundsReady", functionality.isPictureOnBoundsReady()); - object.put("showTorchButton", functionality.isShowTorchButton()); - object.put("showCloseButton", functionality.isShowCloseButton()); - object.put("videoCaptureMotionControl", functionality.isVideoCaptureMotionControl()); - object.put("showCaptureButton", functionality.isShowCaptureButton()); - object.put("showChangeFrameButton", functionality.isShowChangeFrameButton()); - object.put("showCaptureButtonDelayFromDetect", functionality.getShowCaptureButtonDelayFromDetect()); - object.put("showCaptureButtonDelayFromStart", functionality.getShowCaptureButtonDelayFromStart()); - object.put("databaseAutoupdate", functionality.isDatabaseAutoupdate()); - object.put("showSkipNextPageButton", functionality.isShowSkipNextPageButton()); - object.put("useAuthenticator", functionality.isUseAuthenticator()); - object.put("skipFocusingFrames", functionality.isSkipFocusingFrames()); - object.put("showCameraSwitchButton", functionality.isShowCameraSwitchButton()); - object.put("cameraFrame", functionality.getCameraFrame()); - object.put("btDeviceName", functionality.getBtDeviceName()); - object.put("orientation", functionality.getOrientation()); - object.put("BTDeviceApiPresent", functionality.isBTDeviceApiPresent()); - object.put("startDocReaderForResult", functionality.getStartDocReaderForResult()); - object.put("captureMode", functionality.getCaptureMode()); - object.put("displayMetadata", functionality.isDisplayMetaData()); - object.put("cameraSize", new JSONObject() {{ - put("width", functionality.getCameraWidth()); - put("height", functionality.getCameraHeight()); - }}); - object.put("cameraMode", functionality.getCameraMode()); - object.put("excludedCamera2Models", generateList(functionality.getExcludedCamera2Models())); - object.put("isZoomEnabled", functionality.isZoomEnabled()); - object.put("zoomFactor", functionality.getZoomFactor()); - object.put("isCameraTorchCheckDisabled", functionality.isCameraTorchCheckDisabled()); - object.put("recordScanningProcess", functionality.doRecordProcessingVideo()); - object.put("manualMultipageMode", functionality.isManualMultipageMode()); - object.put("exposure", functionality.getExposure()); - object.put("rfidTimeout", functionality.getRfidTimeout()); - - return object; - } - - private static JSONObject getCustomization(ParamsCustomization customization) throws JSONException { - JSONObject object = new JSONObject(); - object.put("status", customization.getStatus()); - object.put("resultStatus", customization.getResultStatus()); - object.put("cameraFrameDefaultColor", customization.getCameraFrameDefaultColor()); - object.put("cameraFrameActiveColor", customization.getCameraFrameActiveColor()); - object.put("cameraPreviewBackgroundColor", customization.getCameraPreviewBackgroundColor()); - object.put("statusTextColor", customization.getStatusTextColor()); - object.put("resultStatusTextColor", customization.getResultStatusTextColor()); - object.put("resultStatusBackgroundColor", customization.getResultStatusBackgroundColor()); - object.put("multipageButtonBackgroundColor", customization.getMultipageButtonBackgroundColor()); - object.put("tintColor", customization.getTintColor()); - object.put("activityIndicatorColor", customization.getActivityIndicatorColor()); - object.put("showStatusMessages", customization.isShowStatusMessages()); - object.put("showResultStatusMessages", customization.isShowResultStatusMessages()); - object.put("showHelpAnimation", customization.isShowHelpAnimation()); - object.put("showNextPageAnimation", customization.isShowNextPageAnimation()); - object.put("showBackgroundMask", customization.isShowBackgroundMask()); - object.put("cameraFrameBorderWidth", customization.getCameraFrameBorderWidth()); - object.put("statusTextSize", customization.getStatusTextSize()); - object.put("cameraFrameLineLength", customization.getCameraFrameLineLength()); - object.put("cameraFrameShapeType", customization.getCameraFrameShapeType()); - object.put("resultStatusTextSize", customization.getResultStatusTextSize()); - object.put("multipageAnimationFrontImage", bitmapToBase64String(bitmapFromDrawable(customization.getMultipageAnimationFrontImage()))); - object.put("multipageAnimationBackImage", bitmapToBase64String(bitmapFromDrawable(customization.getMultipageAnimationBackImage()))); - object.put("borderBackgroundImage", bitmapToBase64String(bitmapFromDrawable(customization.getBorderBackgroundImage()))); - object.put("helpAnimationImageScaleType", customization.getHelpAnimationImageScaleType()); - object.put("multipageAnimationFrontImageScaleType", customization.getMultipageAnimationFrontImageScaleType()); - object.put("multipageAnimationBackImageScaleType", customization.getMultipageAnimationBackImageScaleType()); - object.put("borderBackgroundImageScaleType", customization.getBorderBackgroundImageScaleType()); - object.put("helpAnimationImageMatrix", customization.getHelpAnimationImageMatrix()); - object.put("multipageAnimationFrontImageMatrix", customization.getMultipageAnimationFrontImageMatrix()); - object.put("multipageAnimationBackImageMatrix", customization.getMultipageAnimationBackImageMatrix()); - object.put("borderBackgroundImageMatrix", customization.getBorderBackgroundImageMatrix()); - object.put("statusTextFont", customization.getStatusTextFont()); - object.put("resultStatusTextFont", customization.getResultStatusTextFont()); - object.put("statusPositionMultiplier", customization.getStatusPositionMultiplier()); - object.put("resultStatusPositionMultiplier", customization.getResultStatusPositionMultiplier()); - object.put("backgroundMaskAlpha", customization.getBackgroundMaskAlpha()); - object.put("helpAnimationImage", bitmapToBase64String(bitmapFromDrawable(customization.getHelpAnimationImageDrawable()))); - object.put("cameraFrameOffsetWidth", customization.getCameraFrameOffsetWidth()); - object.put("customLabelStatus", customization.getCustomLabelStatus().toString()); - object.put("customStatusPositionMultiplier", customization.getCustomStatusPositionMultiplier()); - object.put("cameraFrameVerticalPositionMultiplier", customization.getCameraFrameVerticalPositionMultiplier()); - object.put("cameraFrameLandscapeAspectRatio", customization.getCameraFrameLandscapeAspectRatio()); - object.put("cameraFramePortraitAspectRatio", customization.getCameraFramePortraitAspectRatio()); - object.put("cameraFrameCornerRadius", customization.getCameraFrameCornerRadius()); - object.put("cameraFrameLineCap", customization.getCameraFrameLineCap().toString()); - object.put("closeButtonImage", bitmapToBase64String(bitmapFromDrawable(customization.getCloseButtonDrawable()))); - object.put("captureButtonImage", bitmapToBase64String(bitmapFromDrawable(customization.getCaptureButtonDrawable()))); - object.put("changeFrameCollapseButtonImage", bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameCollapseButtonDrawable()))); - object.put("changeFrameExpandButtonImage", bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameExpandButtonDrawable()))); - object.put("cameraSwitchButtonImage", bitmapToBase64String(bitmapFromDrawable(customization.getCameraSwitchButtonDrawable()))); - object.put("torchButtonOnImage", bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOnDrawable()))); - object.put("torchButtonOffImage", bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOffDrawable()))); - object.put("changeFrameButtonExpandImage", bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameExpandButtonDrawable()))); - object.put("changeFrameButtonCollapseImage", bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameCollapseButtonDrawable()))); - object.put("toolbarSize", customization.getToolbarSize()); - object.put("statusBackgroundColor", customization.getStatusBackgroundColor()); - object.put("hologramAnimationImage", bitmapToBase64String(bitmapFromDrawable(customization.getHologramAnimationImage()))); - object.put("hologramAnimationPositionMultiplier", customization.getHologramAnimationPositionMultiplier()); - object.put("hologramAnimationImageMatrix", customization.getHologramAnimationImageMatrix()); - object.put("hologramAnimationImageScaleType", customization.getHologramAnimationImageScaleType()); - object.put("uiCustomizationLayer", customization.getUiCustomizationLayer()); - object.put("activityIndicatorSize", customization.getActivityIndicatorSize()); - - return object; - } - - private static JSONObject getProcessParams(ProcessParam processParams) throws JSONException { - JSONObject object = new JSONObject(); - object.put("documentIDList", processParams.documentIDList != null ? generateIntArray(processParams.documentIDList) : null); - object.put("barcodeTypes", processParams.doBarcodes != null ? generateArray(processParams.doBarcodes) : null); - object.put("fieldTypesFilter", processParams.fieldTypesFilter != null ? generateIntArray(processParams.fieldTypesFilter) : null); - object.put("scenario", processParams.scenario); - object.put("measureSystem", processParams.measureSystem); - object.put("uvTorchEnabled", processParams.uvTorchEnabled); - object.put("debugSaveImages", true); - object.put("debugSaveLogs", processParams.debugSaveLogs); - object.put("multipageProcessing", processParams.multipageProcessing); - object.put("dateFormat", processParams.dateFormat); - object.put("debugSaveCroppedImages", processParams.debugSaveCroppedImages); - object.put("sessionLogFolder", processParams.sessionLogFolder); - object.put("disableFocusingCheck", processParams.disableFocusingCheck); - object.put("captureButtonScenario", processParams.captureButtonScenario); - object.put("returnUncroppedImage", processParams.returnUncroppedImage); - object.put("customParams", processParams.customParams != null ? processParams.customParams.toString() : new JSONArray()); - object.put("debugSaveRFIDSession", processParams.debugSaveRFIDSession); - object.put("barcodeParserType", processParams.barcodeParserType); - object.put("doublePageSpread", processParams.doublePageSpread); - object.put("timeout", processParams.timeout); - object.put("timeoutFromFirstDetect", processParams.timeoutFromFirstDetect); - object.put("timeoutFromFirstDocType", processParams.timeoutFromFirstDocType); - object.put("manualCrop", processParams.manualCrop); - object.put("perspectiveAngle", processParams.perspectiveAngle); - object.put("integralImage", processParams.integralImage); - object.put("minDPI", processParams.minDPI); - object.put("logs", processParams.isLogEnable()); - object.put("returnCroppedBarcode", processParams.returnCroppedBarcode); - object.put("checkHologram", processParams.checkHologram); - object.put("checkRequiredTextFields", processParams.checkRequiredTextFields); - object.put("depersonalizeLog", processParams.depersonalizeLog); - object.put("resultTypeOutput", processParams.resultTypeOutput); - object.put("generateDoublePageSpreadImage", processParams.generateDoublePageSpreadImage); - object.put("imageDpiOutMax", processParams.imageDpiOutMax); - object.put("alreadyCropped", processParams.alreadyCropped); - object.put("forceDocID", processParams.forceDocID); - object.put("matchTextFieldMask", processParams.matchTextFieldMask); - object.put("fastDocDetect", processParams.fastDocDetect); - object.put("updateOCRValidityByGlare", processParams.updateOCRValidityByGlare); - object.put("imageQA", generateImageQA(processParams.imageQA)); - object.put("forceDocFormat", processParams.forceDocFormat); - object.put("noGraphics", processParams.noGraphics); - object.put("documentAreaMin", processParams.documentAreaMin); - object.put("multiDocOnImage", processParams.multiDocOnImage); - object.put("shiftExpiryDate", processParams.shiftExpiryDate); - object.put("minimalHolderAge", processParams.minimalHolderAge); - object.put("mrzFormatsFilter", processParams.mrzFormatsFilter != null ? generateArray(processParams.mrzFormatsFilter) : null); - object.put("forceReadMrzBeforeLocate", processParams.forceReadMrzBeforeLocate); - object.put("parseBarcodes", processParams.parseBarcodes); - object.put("shouldReturnPackageForReprocess", processParams.shouldReturnPackageForReprocess); - object.put("imageOutputMaxHeight", processParams.imageOutputMaxHeight); - object.put("imageOutputMaxWidth", processParams.imageOutputMaxWidth); - object.put("disablePerforationOCR", processParams.disablePerforationOCR); - object.put("documentGroupFilter", generateIntArray(processParams.documentGroupFilter)); - object.put("respectImageQuality", processParams.respectImageQuality); - object.put("splitNames", processParams.splitNames); - object.put("convertCase", processParams.convertCase); - object.put("doFlipYAxis", processParams.doFlipYAxis); - object.put("doDetectCan", processParams.doDetectCan); - object.put("useFaceApi", processParams.useFaceApi); - - return object; - } - - static void setRfidScenario(JSONObject opts) throws JSONException { - if (opts.has("paceStaticBinding")) - DocumentReader.Instance().rfidScenario().setPaceStaticBinding(opts.getBoolean("PACE_StaticBinding")); - if (opts.has("signManagementAction")) - DocumentReader.Instance().rfidScenario().setSignManagementAction(opts.getInt("signManagementAction")); - if (opts.has("readingBuffer")) - DocumentReader.Instance().rfidScenario().setReadingBuffer(opts.getInt("readingBuffer")); - if (opts.has("onlineTAToSignDataType")) - DocumentReader.Instance().rfidScenario().setOnlineTAToSignDataType(opts.getInt("onlineTAToSignDataType")); - if (opts.has("onlineTA")) - DocumentReader.Instance().rfidScenario().setOnlineTA(opts.getBoolean("onlineTA")); - if (opts.has("writeEid")) - DocumentReader.Instance().rfidScenario().setWriteEid(opts.getBoolean("writeEid")); - if (opts.has("profilerType")) - DocumentReader.Instance().rfidScenario().setProfilerType(opts.getInt("profilerType")); - if (opts.has("authProcType")) - DocumentReader.Instance().rfidScenario().setAuthProcType(opts.getInt("authProcType")); - if (opts.has("baseSMProcedure")) - DocumentReader.Instance().rfidScenario().setBaseSMProcedure(opts.getInt("baseSMProcedure")); - if (opts.has("pacePasswordType")) - DocumentReader.Instance().rfidScenario().setPacePasswordType(opts.getInt("pacePasswordType")); - if (opts.has("terminalType")) - DocumentReader.Instance().rfidScenario().setTerminalType(opts.getInt("terminalType")); - if (opts.has("universalAccessRights")) - DocumentReader.Instance().rfidScenario().setUniversalAccessRights(opts.getBoolean("universalAccessRights")); - if (opts.has("authorizedRestrictedIdentification")) - DocumentReader.Instance().rfidScenario().setAuthorizedRestrictedIdentification(opts.getBoolean("authorizedRestrictedIdentification")); - if (opts.has("auxVerificationCommunityID")) - DocumentReader.Instance().rfidScenario().setAuxVerificationCommunityID(opts.getBoolean("auxVerificationCommunityID")); - if (opts.has("auxVerificationDateOfBirth")) - DocumentReader.Instance().rfidScenario().setAuxVerificationDateOfBirth(opts.getBoolean("auxVerificationDateOfBirth")); - if (opts.has("skipAA")) - DocumentReader.Instance().rfidScenario().setSkipAA(opts.getBoolean("skipAA")); - if (opts.has("strictProcessing")) - DocumentReader.Instance().rfidScenario().setStrictProcessing(opts.getBoolean("strictProcessing")); - if (opts.has("pkdDSCertPriority")) - DocumentReader.Instance().rfidScenario().setPkdDSCertPriority(opts.getBoolean("pkdDSCertPriority")); - if (opts.has("pkdUseExternalCSCA")) - DocumentReader.Instance().rfidScenario().setPkdUseExternalCSCA(opts.getBoolean("pkdUseExternalCSCA")); - if (opts.has("trustedPKD")) - DocumentReader.Instance().rfidScenario().setTrustedPKD(opts.getBoolean("trustedPKD")); - if (opts.has("passiveAuth")) - DocumentReader.Instance().rfidScenario().setPassiveAuth(opts.getBoolean("passiveAuth")); - if (opts.has("password")) - DocumentReader.Instance().rfidScenario().setPassword(opts.getString("password")); - if (opts.has("useSFI")) - DocumentReader.Instance().rfidScenario().setUseSFI(opts.getBoolean("useSFI")); - if (opts.has("pkdPA")) - DocumentReader.Instance().rfidScenario().setPkdPA(opts.getString("pkdPA")); - if (opts.has("pkdEAC")) - DocumentReader.Instance().rfidScenario().setPkdEAC(opts.getString("pkdEAC")); - if (opts.has("readEPassport")) - DocumentReader.Instance().rfidScenario().setReadEPassport(opts.getBoolean("readEPassport")); - if (opts.has("readEID")) - DocumentReader.Instance().rfidScenario().setReadEID(opts.getBoolean("readEID")); - if (opts.has("readEDL")) - DocumentReader.Instance().rfidScenario().setReadEDL(opts.getBoolean("readEDL")); - if (opts.has("mrz")) - DocumentReader.Instance().rfidScenario().setMrz(opts.getString("mrz")); - if (opts.has("eSignPINDefault")) - DocumentReader.Instance().rfidScenario().seteSignPINDefault(opts.getString("eSignPINDefault")); - if (opts.has("eSignPINNewValue")) - DocumentReader.Instance().rfidScenario().seteSignPINNewValue(opts.getString("eSignPINNewValue")); - if (opts.has("authorizedSTSignature")) - DocumentReader.Instance().rfidScenario().setAuthorizedSTSignature(opts.getBoolean("authorizedSTSignature")); - if (opts.has("authorizedSTQSignature")) - DocumentReader.Instance().rfidScenario().setAuthorizedSTQSignature(opts.getBoolean("authorizedSTQSignature")); - if (opts.has("authorizedWriteDG17")) - DocumentReader.Instance().rfidScenario().setAuthorizedWriteDG17(opts.getBoolean("authorizedWriteDG17")); - if (opts.has("authorizedWriteDG18")) - DocumentReader.Instance().rfidScenario().setAuthorizedWriteDG18(opts.getBoolean("authorizedWriteDG18")); - if (opts.has("authorizedWriteDG19")) - DocumentReader.Instance().rfidScenario().setAuthorizedWriteDG19(opts.getBoolean("authorizedWriteDG19")); - if (opts.has("authorizedWriteDG20")) - DocumentReader.Instance().rfidScenario().setAuthorizedWriteDG20(opts.getBoolean("authorizedWriteDG20")); - if (opts.has("authorizedWriteDG21")) - DocumentReader.Instance().rfidScenario().setAuthorizedWriteDG21(opts.getBoolean("authorizedWriteDG21")); - if (opts.has("authorizedVerifyAge")) - DocumentReader.Instance().rfidScenario().setAuthorizedVerifyAge(opts.getBoolean("authorizedVerifyAge")); - if (opts.has("authorizedVerifyCommunityID")) - DocumentReader.Instance().rfidScenario().setAuthorizedVerifyCommunityID(opts.getBoolean("authorizedVerifyCommunityID")); - if (opts.has("authorizedPrivilegedTerminal")) - DocumentReader.Instance().rfidScenario().setAuthorizedPrivilegedTerminal(opts.getBoolean("authorizedPrivilegedTerminal")); - if (opts.has("authorizedCANAllowed")) - DocumentReader.Instance().rfidScenario().setAuthorizedCANAllowed(opts.getBoolean("authorizedCANAllowed")); - if (opts.has("authorizedPINManagement")) - DocumentReader.Instance().rfidScenario().setAuthorizedPINManagment(opts.getBoolean("authorizedPINManagement")); - if (opts.has("authorizedInstallCert")) - DocumentReader.Instance().rfidScenario().setAuthorizedInstallCert(opts.getBoolean("authorizedInstallCert")); - if (opts.has("authorizedInstallQCert")) - DocumentReader.Instance().rfidScenario().setAuthorizedInstallQCert(opts.getBoolean("authorizedInstallQCert")); - if (opts.has("applyAmendments")) - DocumentReader.Instance().rfidScenario().setApplyAmendments(opts.getBoolean("applyAmendments")); - if (opts.has("autoSettings")) - DocumentReader.Instance().rfidScenario().setAutoSettings(opts.getBoolean("autoSettings")); - if (opts.has("ePassportDataGroups")) - setDataGroups(DocumentReader.Instance().rfidScenario().ePassportDataGroups(), opts.getJSONObject("ePassportDataGroups")); - if (opts.has("eIDDataGroups")) - setDataGroups(DocumentReader.Instance().rfidScenario().eIDDataGroups(), opts.getJSONObject("eIDDataGroups")); - if (opts.has("eDLDataGroups")) - setDataGroups(DocumentReader.Instance().rfidScenario().eDLDataGroups(), opts.getJSONObject("eDLDataGroups")); - if (opts.has("reprocessParams")) - DocumentReader.Instance().rfidScenario().setReprocessParams(ReprocParamsFromJSON(opts.getJSONObject("reprocessParams"))); - if (opts.has("defaultReadingBufferSize")) - DocumentReader.Instance().rfidScenario().setDefaultReadingBufferSize(opts.getInt("defaultReadingBufferSize")); - } - - private static void setDataGroups(DataGroups dataGroup, JSONObject opts) throws JSONException { - if (opts.has("DG1")) - dataGroup.setDG1(opts.getBoolean("DG1")); - if (opts.has("DG2")) - dataGroup.setDG2(opts.getBoolean("DG2")); - if (opts.has("DG3")) - dataGroup.setDG3(opts.getBoolean("DG3")); - if (opts.has("DG4")) - dataGroup.setDG4(opts.getBoolean("DG4")); - if (opts.has("DG5")) - dataGroup.setDG5(opts.getBoolean("DG5")); - if (opts.has("DG6")) - dataGroup.setDG6(opts.getBoolean("DG6")); - if (opts.has("DG7")) - dataGroup.setDG7(opts.getBoolean("DG7")); - if (opts.has("DG8")) - dataGroup.setDG8(opts.getBoolean("DG8")); - if (opts.has("DG9")) - dataGroup.setDG9(opts.getBoolean("DG9")); - if (opts.has("DG10")) - dataGroup.setDG10(opts.getBoolean("DG10")); - if (opts.has("DG11")) - dataGroup.setDG11(opts.getBoolean("DG11")); - if (opts.has("DG12")) - dataGroup.setDG12(opts.getBoolean("DG12")); - if (opts.has("DG13")) - dataGroup.setDG13(opts.getBoolean("DG13")); - if (opts.has("DG14")) - dataGroup.setDG14(opts.getBoolean("DG14")); - if (opts.has("DG15")) - dataGroup.setDG14(opts.getBoolean("DG15")); - if (opts.has("DG16")) - dataGroup.setDG14(opts.getBoolean("DG16")); - if (opts.has("DG17")) - dataGroup.setDG14(opts.getBoolean("DG17")); - if (opts.has("DG18")) - dataGroup.setDG14(opts.getBoolean("DG18")); - if (opts.has("DG19")) - dataGroup.setDG14(opts.getBoolean("DG19")); - if (opts.has("DG20")) - dataGroup.setDG14(opts.getBoolean("DG20")); - if (opts.has("DG21")) - dataGroup.setDG14(opts.getBoolean("DG21")); - } - - private static ReprocParams ReprocParamsFromJSON(JSONObject input) { - try { - ReprocParams result; - if (input.has("serviceUrl")) - result = new ReprocParams(input.getString("serviceUrl")); - else return null; - if (input.has("failIfNoService")) - result.setFailIfNoService(input.getBoolean("failIfNoService")); - if (input.has("httpHeaders")) - result.setHttpHeaders(stringMapFromJson(input.getJSONObject("httpHeaders"))); - return result; - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static OnlineProcessingConfig OnlineProcessingConfigFromJSON(JSONObject input) { - if(input == null) return null; - try { - OnlineProcessingConfig.Builder builder; - if (input.has("mode")) - builder = new OnlineProcessingConfig.Builder(input.getInt("mode")); - else return null; - if (input.has("imageFormat")) - builder.setImageFormat(input.getInt("imageFormat")); - if (input.has("url")) - builder.setUrl(input.getString("url")); - if (input.has("imageCompressionQuality")) - builder.setImageCompressionQuality((float) input.getDouble("imageCompressionQuality")); - if (input.has("processParams")) { - ProcessParam params = new ProcessParam(); - setProcessParams(params, input.getJSONObject("processParams")); - builder.setProcessParams(params); - } - return builder.build(); - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - private static RFIDParams RFIDParamsFromJSON(JSONObject input) { - try { - RFIDParams result = new RFIDParams(); - - if (input.has("paIgnoreNotificationCodes")) - result.setPaIgnoreNotificationCodes(intArrayFromJSON(input.getJSONArray("paIgnoreNotificationCodes"))); - - return result; - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static FaceApiParams FaceApiParamsFromJSON(JSONObject input) { - try { - FaceApiParams result = new FaceApiParams(); - String url; - if (input.has("url") && !input.isNull("url")) { - url = input.getString("url"); - result.setUrl(url); - } - String mode; - if (input.has("mode") && !input.isNull("mode")) { - mode = input.getString("mode"); - result.setMode(mode); - } - FaceApiParams.Search search; - if (input.has("searchParams") && !input.isNull("searchParams")) { - search = SearchFromJSON(input.getJSONObject("searchParams")); - result.setSearch(search); - } - int threshold; - if (input.has("threshold") && !input.isNull("threshold")) { - threshold = input.getInt("threshold"); - result.setThreshold(threshold); - } - int serviceTimeout; - if (input.has("serviceTimeout") && !input.isNull("serviceTimeout")) { - serviceTimeout = input.getInt("serviceTimeout"); - result.setServiceTimeout(serviceTimeout); - } - String proxy; - if (input.has("proxy") && !input.isNull("proxy")) { - proxy = input.getString("proxy"); - result.setProxy(proxy); - } - String proxyUserPwd; - if (input.has("proxyPassword") && !input.isNull("proxyPassword")) { - proxyUserPwd = input.getString("proxyPassword"); - result.setProxyUserPwd(proxyUserPwd); - } - int proxyType; - if (input.has("proxyType") && !input.isNull("proxyType")) { - proxyType = input.getInt("proxyType"); - result.setProxyType(proxyType); - } - return result; - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } - - static FaceApiParams.Search SearchFromJSON(JSONObject input) { - try { - FaceApiParams.Search result = new FaceApiParams.Search(); - int limit; - if (input.has("limit") && !input.isNull("limit")) { - limit = input.getInt("limit"); - result.setLimit(limit); - } - double threshold; - if (input.has("threshold") && !input.isNull("threshold")) { - threshold = input.getDouble("threshold"); - result.setThreshold((float) threshold); - } - int[] groupIds; - if (input.has("groupIds") && !input.isNull("groupIds")) { - JSONArray jsonArray_groupIds = input.getJSONArray("groupIds"); - groupIds = new int[jsonArray_groupIds.length()]; - for (int i = 0; i < jsonArray_groupIds.length(); i++) - groupIds[i] = jsonArray_groupIds.getInt(i); - result.setGroupIds(groupIds); - } - return result; - } catch (JSONException e) { - e.printStackTrace(); - } - return null; - } -} \ No newline at end of file diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/BluetoothUtil.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/BluetoothUtil.kt new file mode 100644 index 0000000000..b47543c6b0 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/BluetoothUtil.kt @@ -0,0 +1,164 @@ +package com.regula.plugin.documentreader + +import android.Manifest.permission.ACCESS_FINE_LOCATION +import android.Manifest.permission.BLUETOOTH_CONNECT +import android.Manifest.permission.BLUETOOTH_SCAN +import android.annotation.SuppressLint +import android.app.Activity +import android.bluetooth.BluetoothAdapter +import android.content.ComponentName +import android.content.Context.BIND_AUTO_CREATE +import android.content.Intent +import android.content.ServiceConnection +import android.content.pm.PackageManager.PERMISSION_GRANTED +import android.os.Build +import android.os.IBinder +import android.provider.Settings +import android.util.Log +import androidx.core.content.ContextCompat.checkSelfPermission +import com.regula.common.ble.BLEWrapper +import com.regula.common.ble.BleWrapperCallback +import com.regula.common.ble.RegulaBleService +import com.regula.documentreader.api.internal.permission.BluetoothPermissionHelper.BLE_ACCESS_PERMISSION +import com.regula.documentreader.api.internal.permission.BluetoothSettingsHelper.isBluetoothEnabled +import com.regula.documentreader.api.internal.permission.BluetoothSettingsHelper.isLocationServiceEnabled +import java.util.Timer +import java.util.TimerTask + +const val SEARCHING_TIMEOUT: Long = 7000 + +const val INTENT_REQUEST_ENABLE_LOCATION = 196 +const val INTENT_REQUEST_ENABLE_BLUETOOTH = 197 + +@SuppressLint("StaticFieldLeak") +var bluetooth: BLEWrapper? = null +lateinit var savedDeviceNameForPermissionResult: String +lateinit var savedCallbackForPermissionResult: Callback + +fun connectBluetoothDevice(deviceName: String, callback: Callback) { + if (bluetooth?.isConnected == true) { + Log.e("REGULA", "Bluetooth device already connected, returning false") + callback(false) + return + } + + if (!isBluetoothSettingsReady(activity)) { + savedDeviceNameForPermissionResult = deviceName + savedCallbackForPermissionResult = callback + return + } + + val timeout = object : TimerTask() { + override fun run() { + callback(false) + bluetooth?.stopDeviceScan() + bluetooth?.disconnect() + } + } + Timer().schedule(timeout, SEARCHING_TIMEOUT) + + val bleIntent = Intent(context, RegulaBleService::class.java) + bleIntent.putExtra(RegulaBleService.DEVICE_NAME, deviceName) + context.startService(bleIntent) + context.bindService(bleIntent, object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + bluetooth = (service as RegulaBleService.LocalBinder).service.bleManager + if (bluetooth!!.isConnected) callback(true) + else bluetooth!!.addCallback(object : BleWrapperCallback() { + override fun onDeviceReady() { + timeout.cancel() + bluetooth!!.removeCallback(this) + callback(true) + } + }) + } + + override fun onServiceDisconnected(name: ComponentName) {} + }, BIND_AUTO_CREATE) +} + +fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray +): Boolean { + if (requestCode != BLE_ACCESS_PERMISSION || permissions.isEmpty()) return false + if (grantResults.isEmpty() || grantResults[0] != PERMISSION_GRANTED) { + savedCallbackForPermissionResult(false) + return true + } + connectBluetoothDevice(savedDeviceNameForPermissionResult, savedCallbackForPermissionResult) + return true +} + +fun onActivityResult(requestCode: Int, rc: Int, @Suppress("UNUSED_PARAMETER") data: Intent?): Boolean { + var resultCode = rc + if (requestCode == INTENT_REQUEST_ENABLE_LOCATION) + resultCode = if (isLocationServiceEnabled(activity)) Activity.RESULT_OK + else requestCode + + if (requestCode == INTENT_REQUEST_ENABLE_BLUETOOTH || requestCode == INTENT_REQUEST_ENABLE_LOCATION) { + if (resultCode == Activity.RESULT_OK) + connectBluetoothDevice(savedDeviceNameForPermissionResult, savedCallbackForPermissionResult) + else + savedCallbackForPermissionResult(false) + return true + } + return false +} + +fun isBluetoothSettingsReady(activity: Activity): Boolean { + deniedBluetoothPermissions()?.let { + requestPermissions(activity, it, BLE_ACCESS_PERMISSION) + return false + } + if (!isBluetoothEnabled(activity)) { + requestEnableBluetooth(activity) + return false + } + if (!isLocationServiceEnabled(activity)) { + requestEnableLocationService(activity) + return false + } + return true +} + +fun deniedBluetoothPermissions(): Array? { + val result = mutableListOf() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + result.addAll(deniedBluetoothPermission(BLUETOOTH_SCAN)) + result.addAll(deniedBluetoothPermission(BLUETOOTH_CONNECT)) + } else + result.addAll(deniedBluetoothPermission(ACCESS_FINE_LOCATION)) + return result.let { if (it.isNotEmpty()) it.toTypedArray() else null } +} + +fun deniedBluetoothPermission(permission: String): Array { + if (checkSelfPermission(context, permission) != PERMISSION_GRANTED) + return arrayOf(permission) + return arrayOf() +} + +fun requestEnableBluetooth(activity: Activity) { + val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) + startActivityForResult(activity, enableIntent, INTENT_REQUEST_ENABLE_BLUETOOTH) +} + +fun requestEnableLocationService(activity: Activity) { + val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) + startActivityForResult(activity, myIntent, INTENT_REQUEST_ENABLE_LOCATION) +} + +// btDevice functionality(temporary, will be reworked) + +fun btDeviceRequestFlashing() { + bluetooth?.requestFlashing() +} + +fun btDeviceRequestFlashingFullIR() { + bluetooth?.requestFlashingFullIR() +} + +fun btDeviceRequestTurnOffAll() { + bluetooth?.requestTurnOffAll() +} diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/Config.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/Config.kt new file mode 100644 index 0000000000..23a649c0f6 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/Config.kt @@ -0,0 +1,993 @@ +@file:Suppress("EnumValuesSoftDeprecate", "DEPRECATION") + +package com.regula.plugin.documentreader + +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Typeface +import android.graphics.drawable.Drawable +import android.text.SpannableString +import android.widget.ImageView +import com.regula.documentreader.api.enums.CustomizationColor +import com.regula.documentreader.api.enums.CustomizationFont +import com.regula.documentreader.api.enums.CustomizationImage +import com.regula.documentreader.api.enums.CustomizationMatrix +import com.regula.documentreader.api.enums.CustomizationScaleType +import com.regula.documentreader.api.enums.CustomizationTiming +import com.regula.documentreader.api.enums.LogLevel +import com.regula.documentreader.api.params.AuthenticityParams +import com.regula.documentreader.api.params.Functionality +import com.regula.documentreader.api.params.ImageQA +import com.regula.documentreader.api.params.LivenessParams +import com.regula.documentreader.api.params.ParamsCustomization +import com.regula.documentreader.api.params.ProcessParam +import com.regula.documentreader.api.params.RfidScenario +import com.regula.documentreader.api.params.rfid.dg.DTCDataGroup +import com.regula.documentreader.api.params.rfid.dg.DataGroups +import com.regula.documentreader.api.params.rfid.dg.EIDDataGroups +import com.regula.documentreader.api.params.rfid.dg.EPassportDataGroups +import com.regula.plugin.documentreader.Convert.toBase64 +import com.regula.plugin.documentreader.Convert.toDrawable +import org.json.JSONArray +import org.json.JSONObject + +fun setFunctionality(config: Functionality, input: JSONObject) = input.forEach { k, v -> + val editor = config.edit() + when (k) { + "pictureOnBoundsReady" -> editor.setPictureOnBoundsReady(v as Boolean) + "showTorchButton" -> editor.setShowTorchButton(v as Boolean) + "showCloseButton" -> editor.setShowCloseButton(v as Boolean) + "videoCaptureMotionControl" -> editor.setVideoCaptureMotionControl(v as Boolean) + "showCaptureButton" -> editor.setShowCaptureButton(v as Boolean) + "showChangeFrameButton" -> editor.setShowChangeFrameButton(v as Boolean) + "showSkipNextPageButton" -> editor.setShowSkipNextPageButton(v as Boolean) + "useAuthenticator" -> editor.setUseAuthenticator(v as Boolean) + "skipFocusingFrames" -> editor.setSkipFocusingFrames(v as Boolean) + "showCameraSwitchButton" -> editor.setShowCameraSwitchButton(v as Boolean) + "displayMetadata" -> editor.setDisplayMetadata(v as Boolean) + "isZoomEnabled" -> editor.setZoomEnabled(v as Boolean) + "isCameraTorchCheckDisabled" -> editor.setIsCameraTorchCheckDisabled(v as Boolean) + "recordScanningProcess" -> editor.setDoRecordProcessingVideo(v as Boolean) + "manualMultipageMode" -> editor.setManualMultipageMode(v as Boolean) + "torchTurnedOn" -> editor.setTorchTurnedOn(v as Boolean) + "preventScreenRecording" -> editor.setPreventScreenRecording(v as Boolean) + "hideStatusBar" -> editor.setHideStatusBar(v as Boolean) + "showCaptureButtonDelayFromDetect" -> editor.setShowCaptureButtonDelayFromDetect(v.toLong()) + "showCaptureButtonDelayFromStart" -> editor.setShowCaptureButtonDelayFromStart(v.toLong()) + "orientation" -> editor.setOrientation(v.toInt()) + "captureMode" -> editor.setCaptureMode(v.toInt()) + "cameraMode" -> editor.setCameraMode(v.toInt()) + "rfidTimeout" -> editor.setRfidTimeout(v.toInt()) + "forcePagesCount" -> editor.setForcePagesCount(v.toInt()) + "cameraFrame" -> editor.setCameraFrame(v as String) + "btDeviceName" -> editor.setBtDeviceName(v as String) + "zoomFactor" -> editor.setZoomFactor(v.toFloat()) + "exposure" -> editor.setExposure(v.toFloat()) + "videoRecordingSizeDownscaleFactor" -> editor.setVideoRecordingSizeDownscaleFactor(v.toFloat()) + "mdlTimeout" -> editor.setMDLTimeout(v.toDouble()) + "excludedCamera2Models" -> editor.setExcludedCamera2Models((v as JSONArray).toList()) + "cameraSize" -> editor.setCameraSize(cameraSizeFromJSON(v as JSONObject).first, cameraSizeFromJSON(v).second) + } + editor.apply() +} + +fun getFunctionality(input: Functionality) = mapOf( + "pictureOnBoundsReady" to input.isPictureOnBoundsReady, + "showTorchButton" to input.isShowTorchButton, + "showCloseButton" to input.isShowCloseButton, + "videoCaptureMotionControl" to input.isVideoCaptureMotionControl, + "showCaptureButton" to input.isShowCaptureButton, + "showChangeFrameButton" to input.isShowChangeFrameButton, + "showSkipNextPageButton" to input.isShowSkipNextPageButton, + "useAuthenticator" to input.isUseAuthenticator, + "skipFocusingFrames" to input.isSkipFocusingFrames, + "showCameraSwitchButton" to input.isShowCameraSwitchButton, + "displayMetadata" to input.isDisplayMetaData, + "isZoomEnabled" to input.isZoomEnabled, + "isCameraTorchCheckDisabled" to input.isCameraTorchCheckDisabled, + "recordScanningProcess" to input.doRecordProcessingVideo(), + "manualMultipageMode" to input.isManualMultipageMode, + "torchTurnedOn" to input.isTorchTurnedOn, + "preventScreenRecording" to input.doPreventScreenRecording(), + "hideStatusBar" to input.doHideStatusBar(), + "showCaptureButtonDelayFromDetect" to input.showCaptureButtonDelayFromDetect, + "showCaptureButtonDelayFromStart" to input.showCaptureButtonDelayFromStart, + "orientation" to input.orientation, + "captureMode" to input.captureMode, + "cameraMode" to input.cameraMode, + "rfidTimeout" to input.rfidTimeout, + "forcePagesCount" to input.forcePagesCount, + "cameraFrame" to input.cameraFrame, + "btDeviceName" to input.btDeviceName, + "zoomFactor" to input.zoomFactor, + "exposure" to input.exposure, + "videoRecordingSizeDownscaleFactor" to input.videoRecordingSizeDownscaleFactor, + "mdlTimeout" to input.mdlTimeout, + "excludedCamera2Models" to input.excludedCamera2Models.toJson(), + "cameraSize" to generateCameraSize(input.cameraWidth, input.cameraHeight) +).toJson() + +@Suppress("DEPRECATION") +fun setProcessParams(processParams: ProcessParam, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "multipageProcessing" -> processParams.multipageProcessing = v as Boolean + "logs" -> processParams.setLogs(v as Boolean) + "debugSaveImages" -> processParams.debugSaveImages = v as Boolean + "debugSaveLogs" -> processParams.debugSaveLogs = v as Boolean + "returnUncroppedImage" -> processParams.returnUncroppedImage = v as Boolean + "uvTorchEnabled" -> processParams.uvTorchEnabled = v as Boolean + "debugSaveCroppedImages" -> processParams.debugSaveCroppedImages = v as Boolean + "disableFocusingCheck" -> processParams.disableFocusingCheck = v as Boolean + "debugSaveRFIDSession" -> processParams.debugSaveRFIDSession = v as Boolean + "doublePageSpread" -> processParams.doublePageSpread = v as Boolean + "manualCrop" -> processParams.manualCrop = v as Boolean + "integralImage" -> processParams.integralImage = v as Boolean + "returnCroppedBarcode" -> processParams.returnCroppedBarcode = v as Boolean + "checkRequiredTextFields" -> processParams.checkRequiredTextFields = v as Boolean + "depersonalizeLog" -> processParams.depersonalizeLog = v as Boolean + "generateDoublePageSpreadImage" -> processParams.generateDoublePageSpreadImage = v as Boolean + "alreadyCropped" -> processParams.alreadyCropped = v as Boolean + "matchTextFieldMask" -> processParams.matchTextFieldMask = v as Boolean + "updateOCRValidityByGlare" -> processParams.updateOCRValidityByGlare = v as Boolean + "noGraphics" -> processParams.noGraphics = v as Boolean + "multiDocOnImage" -> processParams.multiDocOnImage = v as Boolean + "parseBarcodes" -> processParams.parseBarcodes = v as Boolean + "shouldReturnPackageForReprocess" -> processParams.shouldReturnPackageForReprocess = v as Boolean + "disablePerforationOCR" -> processParams.disablePerforationOCR = v as Boolean + "respectImageQuality" -> processParams.respectImageQuality = v as Boolean + "strictImageQuality" -> processParams.strictImageQuality = v as Boolean + "splitNames" -> processParams.splitNames = v as Boolean + "doDetectCan" -> processParams.doDetectCan = v as Boolean + "useFaceApi" -> processParams.useFaceApi = v as Boolean + "useAuthenticityCheck" -> processParams.useAuthenticityCheck = v as Boolean + "checkHologram" -> processParams.checkHologram = v as Boolean + "generateNumericCodes" -> processParams.generateNumericCodes = v as Boolean + "strictBarcodeDigitalSignatureCheck" -> processParams.strictBarcodeDigitalSignatureCheck = v as Boolean + "selectLongestNames" -> processParams.selectLongestNames = v as Boolean + "generateDTCVC" -> processParams.generateDTCVC = v as Boolean + "strictDLCategoryExpiry" -> processParams.strictDLCategoryExpiry = v as Boolean + "generateAlpha2Codes" -> processParams.generateAlpha2Codes = v as Boolean + "disableAuthResolutionFilter" -> processParams.disableAuthResolutionFilter = v as Boolean + "strictSecurityChecks" -> processParams.strictSecurityChecks = v as Boolean + "returnTransliteratedFields" -> processParams.returnTransliteratedFields = v as Boolean + "checkCaptureProcessIntegrity" -> processParams.checkCaptureProcessIntegrity = v as Boolean + "strictExpiryDate" -> processParams.strictExpiryDate = v as Boolean + "debugSaveBinarySession" -> processParams.debugSaveBinarySession = v as Boolean + "checkVDS" -> processParams.checkVDS = v as Boolean + "strictAgeCheck" -> processParams.strictAgeCheck = v as Boolean + "measureSystem" -> processParams.measureSystem = v.toInt() + "barcodeParserType" -> processParams.barcodeParserType = v.toInt() + "perspectiveAngle" -> processParams.perspectiveAngle = v.toInt() + "minDPI" -> processParams.minDPI = v.toInt() + "imageDpiOutMax" -> processParams.imageDpiOutMax = v.toInt() + "forceDocID" -> processParams.forceDocID = v.toInt() + "forceDocFormat" -> processParams.forceDocFormat = v.toInt() + "shiftExpiryDate" -> processParams.shiftExpiryDate = v.toInt() + "minimalHolderAge" -> processParams.minimalHolderAge = v.toInt() + "imageOutputMaxHeight" -> processParams.imageOutputMaxHeight = v.toInt() + "imageOutputMaxWidth" -> processParams.imageOutputMaxWidth = v.toInt() + "processAuth" -> processParams.processAuth = v.toInt() + "convertCase" -> processParams.convertCase = v.toInt() + "logLevel" -> processParams.logLevel = LogLevel.valueOf(v.toString()) + "mrzDetectMode" -> processParams.mrzDetectMode = v.toInt() + "pdfPagesLimit" -> processParams.pdfPagesLimit = v.toInt() + "dateFormat" -> processParams.dateFormat = v as String + "scenario" -> processParams.scenario = v as String + "captureButtonScenario" -> processParams.captureButtonScenario = v as String + "timeout" -> processParams.timeout = v.toDouble() + "timeoutFromFirstDetect" -> processParams.timeoutFromFirstDetect = v.toDouble() + "timeoutFromFirstDocType" -> processParams.timeoutFromFirstDocType = v.toDouble() + "documentAreaMin" -> processParams.documentAreaMin = v.toDouble() + "timeoutLiveness" -> processParams.timeoutLiveness = v.toDouble() + "documentIDList" -> processParams.documentIDList = v.toIntArray() + "fieldTypesFilter" -> processParams.fieldTypesFilter = v.toIntArray() + "resultTypeOutput" -> processParams.resultTypeOutput = v.toIntArray() + "documentGroupFilter" -> processParams.documentGroupFilter = v.toIntArray() + "lcidIgnoreFilter" -> processParams.lcidIgnoreFilter = v.toIntArray() + "lcidFilter" -> processParams.lcidFilter = v.toIntArray() + "fieldTypesIgnoreFilter" -> processParams.fieldTypesIgnoreFilter = v.toIntArray() + "barcodeTypes" -> processParams.doBarcodes = barcodeTypeArrayFromJson(v as JSONArray) + "mrzFormatsFilter" -> processParams.mrzFormatsFilter = (v as JSONArray).toArray() + "customParams" -> processParams.customParams = v as JSONObject + "imageQA" -> setImageQA(processParams.imageQA, v as JSONObject) + "rfidParams" -> processParams.rfidParams = rfidParamsFromJSON(v as JSONObject) + "faceApiParams" -> processParams.faceApiParams = faceApiParamsFromJSON(v as JSONObject) + "backendProcessingConfig" -> processParams.backendProcessingConfig = backendProcessingConfigFromJSON(v as JSONObject) + "bsiTr03135" -> processParams.bsiTr03135 = bsiFromJSON(v as JSONObject) + "authenticityParams" -> { + if (processParams.authenticityParams == null) processParams.authenticityParams = AuthenticityParams.defaultParams() + setAuthenticityParams(processParams.authenticityParams!!, v as JSONObject) + } + } +} + +@Suppress("DEPRECATION") +fun getProcessParams(processParams: ProcessParam) = mapOf( + "multipageProcessing" to processParams.multipageProcessing, + "logs" to processParams.isLogEnable, + "debugSaveImages" to processParams.debugSaveImages, + "debugSaveLogs" to processParams.debugSaveLogs, + "returnUncroppedImage" to processParams.returnUncroppedImage, + "uvTorchEnabled" to processParams.uvTorchEnabled, + "debugSaveCroppedImages" to processParams.debugSaveCroppedImages, + "disableFocusingCheck" to processParams.disableFocusingCheck, + "debugSaveRFIDSession" to processParams.debugSaveRFIDSession, + "doublePageSpread" to processParams.doublePageSpread, + "manualCrop" to processParams.manualCrop, + "integralImage" to processParams.integralImage, + "returnCroppedBarcode" to processParams.returnCroppedBarcode, + "checkRequiredTextFields" to processParams.checkRequiredTextFields, + "depersonalizeLog" to processParams.depersonalizeLog, + "generateDoublePageSpreadImage" to processParams.generateDoublePageSpreadImage, + "alreadyCropped" to processParams.alreadyCropped, + "matchTextFieldMask" to processParams.matchTextFieldMask, + "updateOCRValidityByGlare" to processParams.updateOCRValidityByGlare, + "noGraphics" to processParams.noGraphics, + "multiDocOnImage" to processParams.multiDocOnImage, + "parseBarcodes" to processParams.parseBarcodes, + "shouldReturnPackageForReprocess" to processParams.shouldReturnPackageForReprocess, + "disablePerforationOCR" to processParams.disablePerforationOCR, + "respectImageQuality" to processParams.respectImageQuality, + "strictImageQuality" to processParams.strictImageQuality, + "splitNames" to processParams.splitNames, + "doDetectCan" to processParams.doDetectCan, + "useFaceApi" to processParams.useFaceApi, + "useAuthenticityCheck" to processParams.useAuthenticityCheck, + "checkHologram" to processParams.checkHologram, + "generateNumericCodes" to processParams.generateNumericCodes, + "strictBarcodeDigitalSignatureCheck" to processParams.strictBarcodeDigitalSignatureCheck, + "selectLongestNames" to processParams.selectLongestNames, + "generateDTCVC" to processParams.generateDTCVC, + "strictDLCategoryExpiry" to processParams.strictDLCategoryExpiry, + "generateAlpha2Codes" to processParams.generateAlpha2Codes, + "disableAuthResolutionFilter" to processParams.disableAuthResolutionFilter, + "strictSecurityChecks" to processParams.strictSecurityChecks, + "returnTransliteratedFields" to processParams.returnTransliteratedFields, + "checkCaptureProcessIntegrity" to processParams.checkCaptureProcessIntegrity, + "strictExpiryDate" to processParams.strictExpiryDate, + "debugSaveBinarySession" to processParams.debugSaveBinarySession, + "checkVDS" to processParams.checkVDS, + "strictAgeCheck" to processParams.strictAgeCheck, + "measureSystem" to processParams.measureSystem, + "barcodeParserType" to processParams.barcodeParserType, + "perspectiveAngle" to processParams.perspectiveAngle, + "minDPI" to processParams.minDPI, + "imageDpiOutMax" to processParams.imageDpiOutMax, + "forceDocID" to processParams.forceDocID, + "forceDocFormat" to processParams.forceDocFormat, + "shiftExpiryDate" to processParams.shiftExpiryDate, + "minimalHolderAge" to processParams.minimalHolderAge, + "imageOutputMaxHeight" to processParams.imageOutputMaxHeight, + "imageOutputMaxWidth" to processParams.imageOutputMaxWidth, + "processAuth" to processParams.processAuth, + "convertCase" to processParams.convertCase, + "logLevel" to processParams.logLevel?.toString(), + "mrzDetectMode" to processParams.mrzDetectMode, + "pdfPagesLimit" to processParams.pdfPagesLimit, + "dateFormat" to processParams.dateFormat, + "scenario" to processParams.scenario, + "captureButtonScenario" to processParams.captureButtonScenario, + "timeout" to processParams.timeout, + "timeoutFromFirstDetect" to processParams.timeoutFromFirstDetect, + "timeoutFromFirstDocType" to processParams.timeoutFromFirstDocType, + "documentAreaMin" to processParams.documentAreaMin, + "timeoutLiveness" to processParams.timeoutLiveness, + "documentIDList" to processParams.documentIDList.toJson(), + "fieldTypesFilter" to processParams.fieldTypesFilter.toJson(), + "documentGroupFilter" to processParams.documentGroupFilter.toJson(), + "lcidIgnoreFilter" to processParams.lcidIgnoreFilter.toJson(), + "lcidFilter" to processParams.lcidFilter.toJson(), + "fieldTypesIgnoreFilter" to processParams.fieldTypesIgnoreFilter.toJson(), + "resultTypeOutput" to processParams.resultTypeOutput.toJson(), + "mrzFormatsFilter" to processParams.mrzFormatsFilter.toJson(), + "barcodeTypes" to generateBarcodeTypeArray(processParams.doBarcodes), + "imageQA" to getImageQA(processParams.imageQA), + "rfidParams" to generateRFIDParams(processParams.rfidParams), + "faceApiParams" to generateFaceApiParams(processParams.faceApiParams), + "backendProcessingConfig" to generateBackendProcessingConfig(processParams.backendProcessingConfig), + "bsiTr03135" to generateBsi(processParams.bsiTr03135), + "authenticityParams" to getAuthenticityParams(processParams.authenticityParams), + "customParams" to processParams.customParams, +).toJson() + +fun setCustomization(customization: ParamsCustomization, opts: JSONObject) = opts.forEach { k, v -> + val editor = customization.edit() + when (k) { + "showStatusMessages" -> editor.setShowStatusMessages(v as Boolean) + "showResultStatusMessages" -> editor.setShowResultStatusMessages(v as Boolean) + "showHelpAnimation" -> editor.setShowHelpAnimation(v as Boolean) + "showNextPageAnimation" -> editor.setShowNextPageAnimation(v as Boolean) + "showBackgroundMask" -> editor.setShowBackgroundMask(v as Boolean) + "cameraFrameBorderWidth" -> editor.setCameraFrameBorderWidth(v.toInt()) + "cameraFrameLineLength" -> editor.setCameraFrameLineLength(v.toInt()) + "cameraFrameShapeType" -> editor.setCameraFrameShapeType(v.toInt()) + "cameraFrameOffsetWidth" -> editor.setCameraFrameOffsetWidth(v.toInt()) + "activityIndicatorSize" -> editor.setActivityIndicatorSize(v.toInt()) + "status" -> editor.setStatus(v as String) + "resultStatus" -> editor.setResultStatus(v as String) + "multipageButtonText" -> editor.setMultipageButtonText(v as String) + "cameraFrameDefaultColor" -> editor.setCameraFrameDefaultColor(v.toColor()) + "cameraFrameActiveColor" -> editor.setCameraFrameActiveColor(v.toColor()) + "statusTextColor" -> editor.setStatusTextColor(v.toColor()) + "resultStatusTextColor" -> editor.setResultStatusTextColor(v.toColor()) + "resultStatusBackgroundColor" -> editor.setResultStatusBackgroundColor(v.toColor()) + "multipageButtonBackgroundColor" -> editor.setMultipageButtonBackgroundColor(v.toColor()) + "tintColor" -> editor.setTintColor(v.toColor()) + "activityIndicatorColor" -> editor.setActivityIndicatorColor(v.toColor()) + "statusBackgroundColor" -> editor.setStatusBackgroundColor(v.toColor()) + "cameraPreviewBackgroundColor" -> editor.setCameraPreviewBackgroundColor(v.toColor()) + "backgroundMaskColor" -> editor.setBackgroundMaskColor(v.toColor()) + "multipageButtonTextColor" -> editor.setMultipageButtonTextColor(v.toColor()) + "statusPositionMultiplier" -> editor.setStatusPositionMultiplier(v.toFloat()) + "resultStatusPositionMultiplier" -> editor.setResultStatusPositionMultiplier(v.toFloat()) + "toolbarSize" -> editor.setToolbarSize(v.toFloat()) + "backgroundMaskAlpha" -> editor.setBackgroundMaskAlpha(v.toFloat()) + "customStatusPositionMultiplier" -> editor.setCustomStatusPositionMultiplier(v.toFloat()) + "cameraFrameVerticalPositionMultiplier" -> editor.setCameraFrameVerticalPositionMultiplier(v.toFloat()) + "cameraFrameLandscapeAspectRatio" -> editor.setCameraFrameLandscapeAspectRatio(v.toFloat()) + "cameraFramePortraitAspectRatio" -> editor.setCameraFramePortraitAspectRatio(v.toFloat()) + "cameraFrameCornerRadius" -> editor.setCameraFrameCornerRadius(v.toFloat()) + "livenessAnimationPositionMultiplier" -> editor.setLivenessAnimationPositionMultiplier(v.toFloat()) + "nextPageAnimationStartDelay" -> editor.setNextPageAnimationStartDelay(v.toFloat()) + "nextPageAnimationEndDelay" -> editor.setNextPageAnimationEndDelay(v.toFloat()) + "activityIndicatorPortraitPositionMultiplier" -> editor.setActivityIndicatorPortraitPositionMultiplier(v.toFloat()) + "activityIndicatorLandscapePositionMultiplier" -> editor.setActivityIndicatorLandscapePositionMultiplier(v.toFloat()) + "cameraPreviewVerticalPositionMultiplier" -> editor.setCameraPreviewVerticalPositionMultiplier(v.toFloat()) + "multipageButtonPositionMultiplier" -> editor.setMultipageButtonPositionMultiplier(v.toFloat()) + "multipageAnimationFrontImage" -> editor.setMultipageAnimationFrontImage(v.toDrawable()) + "multipageAnimationBackImage" -> editor.setMultipageAnimationBackImage(v.toDrawable()) + "borderBackgroundImage" -> editor.setBorderBackgroundImage(v.toDrawable()) + "helpAnimationImage" -> editor.setHelpAnimationImage(v.toDrawable()) + "closeButtonImage" -> editor.setCloseButtonImage(v.toDrawable()) + "captureButtonImage" -> editor.setCaptureButtonImage(v.toDrawable()) + "changeFrameButtonCollapseImage" -> editor.setChangeFrameCollapseButtonImage(v.toDrawable()) + "changeFrameButtonExpandImage" -> editor.setChangeFrameExpandButtonImage(v.toDrawable()) + "cameraSwitchButtonImage" -> editor.setCameraSwitchButtonImage(v.toDrawable()) + "torchButtonOnImage" -> editor.setTorchImageOn(v.toDrawable()) + "torchButtonOffImage" -> editor.setTorchImageOff(v.toDrawable()) + "livenessAnimationImage" -> editor.setLivenessAnimationImage(v.toDrawable()) + "multipageButtonImage" -> editor.setMultipageButtonImage(v.toDrawable()) + "helpAnimationImageMatrix" -> editor.setHelpAnimationImageMatrix(matrixFromJSON(v as JSONArray?)).setHelpAnimationImageScaleType(ImageView.ScaleType.MATRIX) + "multipageAnimationFrontImageMatrix" -> editor.setMultipageAnimationFrontImageMatrix(matrixFromJSON(v as JSONArray?)).setMultipageAnimationFrontImageScaleType(ImageView.ScaleType.MATRIX) + "multipageAnimationBackImageMatrix" -> editor.setMultipageAnimationBackImageMatrix(matrixFromJSON(v as JSONArray?)).setMultipageAnimationBackImageScaleType(ImageView.ScaleType.MATRIX) + "livenessAnimationImageMatrix" -> editor.setLivenessAnimationImageMatrix(matrixFromJSON(v as JSONArray?)).setLivenessAnimationImageScaleType(ImageView.ScaleType.MATRIX) + "borderBackgroundImageMatrix" -> editor.setBorderBackgroundImageMatrix(matrixFromJSON(v as JSONArray?)).setBorderBackgroundImageScaleType(ImageView.ScaleType.MATRIX) + "customLabelStatus" -> editor.setCustomLabelStatus(SpannableString(v as String)) + "cameraFrameLineCap" -> editor.setCameraFrameLineCap(Paint.Cap.values()[v.toInt()]) + "uiCustomizationLayer" -> editor.setUiCustomizationLayer(JSONObject(v.toString())) + "colors" -> setColors(editor, v as JSONObject) + "fonts" -> setFonts(editor, v as JSONObject) + "images" -> setImages(editor, v as JSONObject) + "timings" -> setTimings(editor, v as JSONObject) + "matrices" -> setMatrices(editor, v as JSONObject) + "statusTextFont" -> { + val font = typefaceFromJSON(v as JSONObject) + editor.setStatusTextFont(font.first) + font.second?.let { editor.setStatusTextSize(it) } + } + + "resultStatusTextFont" -> { + val font = typefaceFromJSON(v as JSONObject) + editor.setResultStatusTextFont(font.first) + font.second?.let { editor.setResultStatusTextSize(it) } + } + + "multipageButtonTextFont" -> { + val font = typefaceFromJSON(v as JSONObject) + editor.setMultipageButtonTextFont(font.first) + font.second?.let { editor.setMultipageButtonTextSize(it) } + } + } + editor.applyImmediately(context) +} + +fun getCustomization(customization: ParamsCustomization) = mapOf( + "showStatusMessages" to customization.isShowStatusMessages, + "showResultStatusMessages" to customization.isShowResultStatusMessages, + "showHelpAnimation" to customization.isShowHelpAnimation, + "showNextPageAnimation" to customization.isShowNextPageAnimation, + "showBackgroundMask" to customization.isShowBackgroundMask, + "cameraFrameBorderWidth" to customization.cameraFrameBorderWidth, + "cameraFrameLineLength" to customization.cameraFrameLineLength, + "cameraFrameShapeType" to customization.cameraFrameShapeType, + "cameraFrameOffsetWidth" to customization.cameraFrameOffsetWidth, + "activityIndicatorSize" to customization.activityIndicatorSize, + "status" to customization.status, + "resultStatus" to customization.resultStatus, + "multipageButtonText" to customization.multipageButtonText, + "cameraFrameDefaultColor" to customization.cameraFrameDefaultColor.colorToLong(), + "cameraFrameActiveColor" to customization.cameraFrameActiveColor.colorToLong(), + "statusTextColor" to customization.statusTextColor.colorToLong(), + "resultStatusTextColor" to customization.resultStatusTextColor.colorToLong(), + "resultStatusBackgroundColor" to customization.resultStatusBackgroundColor.colorToLong(), + "multipageButtonBackgroundColor" to customization.multipageButtonBackgroundColor.colorToLong(), + "tintColor" to customization.tintColor.colorToLong(), + "activityIndicatorColor" to customization.activityIndicatorColor.colorToLong(), + "statusBackgroundColor" to customization.statusBackgroundColor.colorToLong(), + "cameraPreviewBackgroundColor" to customization.cameraPreviewBackgroundColor.colorToLong(), + "backgroundMaskColor" to customization.backgroundMaskColor.colorToLong(), + "multipageButtonTextColor" to customization.multipageButtonTextColor.colorToLong(), + "statusPositionMultiplier" to customization.statusPositionMultiplier, + "resultStatusPositionMultiplier" to customization.resultStatusPositionMultiplier, + "backgroundMaskAlpha" to customization.backgroundMaskAlpha, + "toolbarSize" to customization.toolbarSize, + "customStatusPositionMultiplier" to customization.customStatusPositionMultiplier, + "cameraFrameVerticalPositionMultiplier" to customization.cameraFrameVerticalPositionMultiplier, + "cameraFrameLandscapeAspectRatio" to customization.cameraFrameLandscapeAspectRatio, + "cameraFramePortraitAspectRatio" to customization.cameraFramePortraitAspectRatio, + "cameraFrameCornerRadius" to customization.cameraFrameCornerRadius, + "livenessAnimationPositionMultiplier" to customization.livenessAnimationPositionMultiplier, + "nextPageAnimationStartDelay" to customization.nextPageAnimationStartDelay, + "nextPageAnimationEndDelay" to customization.nextPageAnimationEndDelay, + "activityIndicatorPortraitPositionMultiplier" to customization.activityIndicatorPortraitPositionMultiplier, + "activityIndicatorLandscapePositionMultiplier" to customization.activityIndicatorLandscapePositionMultiplier, + "cameraPreviewVerticalPositionMultiplier" to customization.cameraPreviewVerticalPositionMultiplier, + "multipageButtonPositionMultiplier" to customization.multipageButtonPositionMultiplier, + "multipageAnimationFrontImage" to customization.multipageAnimationFrontImage.toBase64(), + "multipageAnimationBackImage" to customization.multipageAnimationBackImage.toBase64(), + "borderBackgroundImage" to customization.borderBackgroundImage.toBase64(), + "helpAnimationImage" to customization.helpAnimationImageDrawable.toBase64(), + "closeButtonImage" to customization.closeButtonDrawable.toBase64(), + "captureButtonImage" to customization.captureButtonDrawable.toBase64(), + "changeFrameButtonCollapseImage" to customization.changeFrameCollapseButtonDrawable.toBase64(), + "changeFrameButtonExpandImage" to customization.changeFrameExpandButtonDrawable.toBase64(), + "cameraSwitchButtonImage" to customization.cameraSwitchButtonDrawable.toBase64(), + "torchButtonOnImage" to customization.torchImageOnDrawable.toBase64(), + "torchButtonOffImage" to customization.torchImageOffDrawable.toBase64(), + "livenessAnimationImage" to customization.livenessAnimationImage.toBase64(), + "multipageButtonImage" to customization.multipageButtonDrawable.toBase64(), + "helpAnimationImageMatrix" to generateMatrix(customization.helpAnimationImageMatrix), + "multipageAnimationFrontImageMatrix" to generateMatrix(customization.multipageAnimationFrontImageMatrix), + "multipageAnimationBackImageMatrix" to generateMatrix(customization.multipageAnimationBackImageMatrix), + "livenessAnimationImageMatrix" to generateMatrix(customization.livenessAnimationImageMatrix), + "borderBackgroundImageMatrix" to generateMatrix(customization.borderBackgroundImageMatrix), + "statusTextFont" to generateTypeface(customization.statusTextFont, customization.statusTextSize), + "resultStatusTextFont" to generateTypeface(customization.resultStatusTextFont, customization.resultStatusTextSize), + "multipageButtonTextFont" to generateTypeface(customization.multipageButtonTextFont, customization.multipageButtonTextSize), + "customLabelStatus" to customization.customLabelStatus?.toString(), + "cameraFrameLineCap" to customization.cameraFrameLineCap.ordinal, + "uiCustomizationLayer" to customization.uiCustomizationLayer, + "colors" to getColors(customization.colors), + "fonts" to getFonts(customization.typeFaces, customization.fontSizes), + "images" to getImages(customization.images), + "timings" to getTimings(customization.timings), + "matrices" to getMatrices(customization.matrices), +).toJson() + +fun setRfidScenario(rfidScenario: RfidScenario, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "paceStaticBinding" -> rfidScenario.isPaceStaticBinding = v as Boolean + "onlineTA" -> rfidScenario.isOnlineTA = v as Boolean + "writeEid" -> rfidScenario.isWriteEid = v as Boolean + "universalAccessRights" -> rfidScenario.isUniversalAccessRights = v as Boolean + "authorizedRestrictedIdentification" -> rfidScenario.isAuthorizedRestrictedIdentification = v as Boolean + "auxVerificationCommunityID" -> rfidScenario.isAuxVerificationCommunityID = v as Boolean + "auxVerificationDateOfBirth" -> rfidScenario.isAuxVerificationDateOfBirth = v as Boolean + "skipAA" -> rfidScenario.isSkipAA = v as Boolean + "strictProcessing" -> rfidScenario.isStrictProcessing = v as Boolean + "pkdDSCertPriority" -> rfidScenario.isPkdDSCertPriority = v as Boolean + "pkdUseExternalCSCA" -> rfidScenario.isPkdUseExternalCSCA = v as Boolean + "trustedPKD" -> rfidScenario.isTrustedPKD = v as Boolean + "passiveAuth" -> rfidScenario.isPassiveAuth = v as Boolean + "useSFI" -> rfidScenario.isUseSFI = v as Boolean + "readEPassport" -> rfidScenario.isReadEPassport = v as Boolean + "readEID" -> rfidScenario.isReadEID = v as Boolean + "readEDL" -> rfidScenario.isReadEDL = v as Boolean + "authorizedSTSignature" -> rfidScenario.isAuthorizedSTSignature = v as Boolean + "authorizedSTQSignature" -> rfidScenario.isAuthorizedSTQSignature = v as Boolean + "authorizedWriteDG17" -> rfidScenario.isAuthorizedWriteDG17 = v as Boolean + "authorizedWriteDG18" -> rfidScenario.isAuthorizedWriteDG18 = v as Boolean + "authorizedWriteDG19" -> rfidScenario.isAuthorizedWriteDG19 = v as Boolean + "authorizedWriteDG20" -> rfidScenario.isAuthorizedWriteDG20 = v as Boolean + "authorizedWriteDG21" -> rfidScenario.isAuthorizedWriteDG21 = v as Boolean + "authorizedVerifyAge" -> rfidScenario.isAuthorizedVerifyAge = v as Boolean + "authorizedVerifyCommunityID" -> rfidScenario.isAuthorizedVerifyCommunityID = v as Boolean + "authorizedPrivilegedTerminal" -> rfidScenario.isAuthorizedPrivilegedTerminal = v as Boolean + "authorizedCANAllowed" -> rfidScenario.isAuthorizedCANAllowed = v as Boolean + "authorizedPINManagement" -> rfidScenario.isAuthorizedPINManagment = v as Boolean + "authorizedInstallCert" -> rfidScenario.isAuthorizedInstallCert = v as Boolean + "authorizedInstallQCert" -> rfidScenario.isAuthorizedInstallQCert = v as Boolean + "applyAmendments" -> rfidScenario.isApplyAmendments = v as Boolean + "autoSettings" -> rfidScenario.isAutoSettings = v as Boolean + "proceedReadingAlways" -> rfidScenario.proceedReadingAlways = v as Boolean + "readDTC" -> rfidScenario.isReadDTC = v as Boolean + "mrzStrictCheck" -> rfidScenario.isMrzStrictCheck = v as Boolean + "loadCRLFromRemote" -> rfidScenario.isLoadCRLFromRemote = v as Boolean + "independentSODStatus" -> rfidScenario.isIndependentSODStatus = v as Boolean + "signManagementAction" -> rfidScenario.signManagementAction = v.toInt() + "readingBuffer" -> rfidScenario.readingBuffer = v.toInt() + "onlineTAToSignDataType" -> rfidScenario.onlineTAToSignDataType = v.toInt() + "profilerType" -> rfidScenario.profilerType = v.toInt() + "authProcType" -> rfidScenario.authProcType = v.toInt() + "baseSMProcedure" -> rfidScenario.baseSMProcedure = v.toInt() + "pacePasswordType" -> rfidScenario.pacePasswordType = v.toInt() + "terminalType" -> rfidScenario.terminalType = v.toInt() + "defaultReadingBufferSize" -> rfidScenario.defaultReadingBufferSize = v.toInt() + "password" -> rfidScenario.password = v as String + "pkdPA" -> rfidScenario.pkdPA = v as String + "pkdEAC" -> rfidScenario.pkdEAC = v as String + "mrz" -> rfidScenario.mrz = v as String + "eSignPINDefault" -> rfidScenario.seteSignPINDefault(v as String) + "eSignPINNewValue" -> rfidScenario.seteSignPINNewValue(v as String) + "cardAccess" -> rfidScenario.cardAccess = v as String + "mrzHash" -> rfidScenario.mrzHash = v as String + "documentNumber" -> rfidScenario.documentNumber = v as String + "dateOfBirth" -> rfidScenario.dateOfBirth = v as String + "dateOfExpiry" -> rfidScenario.dateOfExpiry = v as String + "ePassportDataGroups" -> setDataGroups(rfidScenario.ePassportDataGroups(), v as JSONObject) + "eIDDataGroups" -> setDataGroups(rfidScenario.eIDDataGroups(), v as JSONObject) + "eDLDataGroups" -> setDataGroups(rfidScenario.eDLDataGroups(), v as JSONObject) + "dtcDataGroups" -> setDTCDataGroup(rfidScenario.DTCDataGroup(), v as JSONObject) + } +} + +fun getRfidScenario(rfidScenario: RfidScenario) = mapOf( + "paceStaticBinding" to rfidScenario.isPaceStaticBinding, + "onlineTA" to rfidScenario.isOnlineTA, + "writeEid" to rfidScenario.isWriteEid, + "universalAccessRights" to rfidScenario.isUniversalAccessRights, + "authorizedRestrictedIdentification" to rfidScenario.isAuthorizedRestrictedIdentification, + "auxVerificationCommunityID" to rfidScenario.isAuxVerificationCommunityID, + "auxVerificationDateOfBirth" to rfidScenario.isAuxVerificationDateOfBirth, + "skipAA" to rfidScenario.isSkipAA, + "strictProcessing" to rfidScenario.isStrictProcessing, + "pkdDSCertPriority" to rfidScenario.isPkdDSCertPriority, + "pkdUseExternalCSCA" to rfidScenario.isPkdUseExternalCSCA, + "trustedPKD" to rfidScenario.isTrustedPKD, + "passiveAuth" to rfidScenario.isPassiveAuth, + "useSFI" to rfidScenario.isUseSFI, + "readEPassport" to rfidScenario.isReadEPassport, + "readEID" to rfidScenario.isReadEID, + "readEDL" to rfidScenario.isReadEDL, + "authorizedSTSignature" to rfidScenario.isAuthorizedSTSignature, + "authorizedSTQSignature" to rfidScenario.isAuthorizedSTQSignature, + "authorizedWriteDG17" to rfidScenario.isAuthorizedWriteDG17, + "authorizedWriteDG18" to rfidScenario.isAuthorizedWriteDG18, + "authorizedWriteDG19" to rfidScenario.isAuthorizedWriteDG19, + "authorizedWriteDG20" to rfidScenario.isAuthorizedWriteDG20, + "authorizedWriteDG21" to rfidScenario.isAuthorizedWriteDG21, + "authorizedVerifyAge" to rfidScenario.isAuthorizedVerifyAge, + "authorizedVerifyCommunityID" to rfidScenario.isAuthorizedVerifyCommunityID, + "authorizedPrivilegedTerminal" to rfidScenario.isAuthorizedPrivilegedTerminal, + "authorizedCANAllowed" to rfidScenario.isAuthorizedCANAllowed, + "authorizedPINManagement" to rfidScenario.isAuthorizedPINManagment, + "authorizedInstallCert" to rfidScenario.isAuthorizedInstallCert, + "authorizedInstallQCert" to rfidScenario.isAuthorizedInstallQCert, + "applyAmendments" to rfidScenario.isApplyAmendments, + "autoSettings" to rfidScenario.isAutoSettings, + "proceedReadingAlways" to rfidScenario.proceedReadingAlways, + "readDTC" to rfidScenario.isReadDTC, + "mrzStrictCheck" to rfidScenario.isMrzStrictCheck, + "loadCRLFromRemote" to rfidScenario.isLoadCRLFromRemote, + "independentSODStatus" to rfidScenario.isIndependentSODStatus, + "signManagementAction" to rfidScenario.signManagementAction, + "readingBuffer" to rfidScenario.readingBuffer, + "onlineTAToSignDataType" to rfidScenario.onlineTAToSignDataType, + "profilerType" to rfidScenario.profilerType, + "authProcType" to rfidScenario.authProcType, + "baseSMProcedure" to rfidScenario.baseSMProcedure, + "pacePasswordType" to rfidScenario.pacePasswordType, + "terminalType" to rfidScenario.terminalType, + "defaultReadingBufferSize" to rfidScenario.defaultReadingBufferSize, + "password" to rfidScenario.password, + "pkdPA" to rfidScenario.pkdPA, + "pkdEAC" to rfidScenario.pkdEAC, + "mrz" to rfidScenario.mrz, + "eSignPINDefault" to rfidScenario.geteSignPINDefault(), + "eSignPINNewValue" to rfidScenario.geteSignPINNewValue(), + "cardAccess" to rfidScenario.cardAccess, + "mrzHash" to rfidScenario.mrzHash, + "documentNumber" to rfidScenario.documentNumber, + "dateOfBirth" to rfidScenario.dateOfBirth, + "dateOfExpiry" to rfidScenario.dateOfExpiry, + "ePassportDataGroups" to getDataGroups(rfidScenario.ePassportDataGroups()), + "eIDDataGroups" to getDataGroups(rfidScenario.eIDDataGroups()), + "eDLDataGroups" to getDataGroups(rfidScenario.eDLDataGroups()), + "dtcDataGroups" to getDTCDataGroup(rfidScenario.DTCDataGroup()) +).toJson() + +fun setDataGroups(dataGroup: DataGroups, opts: JSONObject) = opts.forEach { k, v -> + val value = v as Boolean + when (k) { + "DG1" -> dataGroup.isDG1 = value + "DG2" -> dataGroup.isDG2 = value + "DG3" -> dataGroup.isDG3 = value + "DG4" -> dataGroup.isDG4 = value + "DG5" -> dataGroup.isDG5 = value + "DG6" -> dataGroup.isDG6 = value + "DG7" -> dataGroup.isDG7 = value + "DG8" -> dataGroup.isDG8 = value + "DG9" -> dataGroup.isDG9 = value + "DG10" -> dataGroup.isDG10 = value + "DG11" -> dataGroup.isDG11 = value + "DG12" -> dataGroup.isDG12 = value + "DG13" -> dataGroup.isDG13 = value + "DG14" -> dataGroup.isDG14 = value + } + if (dataGroup is EPassportDataGroups) when (k) { + "DG15" -> dataGroup.isDG15 = value + "DG16" -> dataGroup.isDG16 = value + } + if (dataGroup is EIDDataGroups) when (k) { + "DG15" -> dataGroup.isDG15 = value + "DG16" -> dataGroup.isDG16 = value + "DG17" -> dataGroup.isDG17 = value + "DG18" -> dataGroup.isDG18 = value + "DG19" -> dataGroup.isDG19 = value + "DG20" -> dataGroup.isDG20 = value + "DG21" -> dataGroup.isDG21 = value + } +} + +fun getDataGroups(dataGroup: DataGroups): JSONObject { + val result = mutableMapOf( + "DG1" to dataGroup.isDG1, + "DG2" to dataGroup.isDG2, + "DG3" to dataGroup.isDG3, + "DG4" to dataGroup.isDG4, + "DG5" to dataGroup.isDG5, + "DG6" to dataGroup.isDG6, + "DG7" to dataGroup.isDG7, + "DG8" to dataGroup.isDG8, + "DG9" to dataGroup.isDG9, + "DG10" to dataGroup.isDG10, + "DG11" to dataGroup.isDG11, + "DG12" to dataGroup.isDG12, + "DG13" to dataGroup.isDG13, + "DG14" to dataGroup.isDG14 + ) + if (dataGroup is EPassportDataGroups) { + result["DG15"] = dataGroup.isDG15 + result["DG16"] = dataGroup.isDG16 + } + if (dataGroup is EIDDataGroups) { + result["DG15"] = dataGroup.isDG15 + result["DG16"] = dataGroup.isDG16 + result["DG17"] = dataGroup.isDG17 + result["DG18"] = dataGroup.isDG18 + result["DG19"] = dataGroup.isDG19 + result["DG20"] = dataGroup.isDG20 + result["DG21"] = dataGroup.isDG21 + } + return result.toJson() +} + +fun setDTCDataGroup(dataGroup: DTCDataGroup, opts: JSONObject) = opts.forEach { k, v -> + val value = v as Boolean + when (k) { + "DG17" -> dataGroup.isDG17 = value + "DG18" -> dataGroup.isDG18 = value + "DG22" -> dataGroup.isDG22 = value + "DG23" -> dataGroup.isDG23 = value + "DG24" -> dataGroup.isDG24 = value + } +} + +fun getDTCDataGroup(dataGroup: DTCDataGroup) = mapOf( + "DG17" to dataGroup.isDG17, + "DG18" to dataGroup.isDG18, + "DG22" to dataGroup.isDG22, + "DG23" to dataGroup.isDG23, + "DG24" to dataGroup.isDG24, +).toJson() + +fun setImageQA(input: ImageQA, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "focusCheck" -> input.focusCheck = v as Boolean + "glaresCheck" -> input.glaresCheck = v as Boolean + "colornessCheck" -> input.colornessCheck = v as Boolean + "screenCapture" -> input.screenCapture = v as Boolean + "dpiThreshold" -> input.dpiThreshold = v.toInt() + "angleThreshold" -> input.angleThreshold = v.toInt() + "documentPositionIndent" -> input.documentPositionIndent = v.toInt() + "brightnessThreshold" -> input.brightnessThreshold = v.toDouble() + "expectedPass" -> input.expectedPass = v.toIntArray() + "glaresCheckParams" -> input.glaresCheckParams = glaresCheckParamsFromJSON(v as JSONObject) + "occlusionCheck" -> input.occlusionCheck = v as Boolean + } +} + +fun getImageQA(input: ImageQA) = mapOf( + "focusCheck" to input.focusCheck, + "glaresCheck" to input.glaresCheck, + "colornessCheck" to input.colornessCheck, + "screenCapture" to input.screenCapture, + "dpiThreshold" to input.dpiThreshold, + "angleThreshold" to input.angleThreshold, + "documentPositionIndent" to input.documentPositionIndent, + "brightnessThreshold" to input.brightnessThreshold, + "expectedPass" to input.expectedPass.toJson(), + "glaresCheckParams" to generateGlaresCheckParams(input.glaresCheckParams), + "occlusionCheck" to input.occlusionCheck, +).toJson() + +fun setAuthenticityParams(input: AuthenticityParams, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "useLivenessCheck" -> input.useLivenessCheck = v as Boolean + "checkUVLuminiscence" -> input.checkUVLuminiscence = v as Boolean + "checkIRB900" -> input.checkIRB900 = v as Boolean + "checkImagePatterns" -> input.checkImagePatterns = v as Boolean + "checkFibers" -> input.checkFibers = v as Boolean + "checkExtMRZ" -> input.checkExtMRZ = v as Boolean + "checkExtOCR" -> input.checkExtOCR = v as Boolean + "checkAxial" -> input.checkAxial = v as Boolean + "checkBarcodeFormat" -> input.checkBarcodeFormat = v as Boolean + "checkIRVisibility" -> input.checkIRVisibility = v as Boolean + "checkIPI" -> input.checkIPI = v as Boolean + "checkPhotoEmbedding" -> input.checkPhotoEmbedding = v as Boolean + "checkPhotoComparison" -> input.checkPhotoComparison = v as Boolean + "checkLetterScreen" -> input.checkLetterScreen = v as Boolean + "checkSecurityText" -> input.checkSecurityText = v as Boolean + "livenessParams" -> { + if (input.livenessParams == null) input.livenessParams = LivenessParams.defaultParams() + setLivenessParams(input.livenessParams!!, v as JSONObject) + } + } +} + +fun getAuthenticityParams(input: AuthenticityParams?) = input?.let { + mapOf( + "useLivenessCheck" to it.useLivenessCheck, + "checkUVLuminiscence" to it.checkUVLuminiscence, + "checkIRB900" to input.checkIRB900, + "checkImagePatterns" to it.checkImagePatterns, + "checkFibers" to it.checkFibers, + "checkExtMRZ" to it.checkExtMRZ, + "checkExtOCR" to it.checkExtOCR, + "checkAxial" to it.checkAxial, + "checkBarcodeFormat" to it.checkBarcodeFormat, + "checkIRVisibility" to it.checkIRVisibility, + "checkIPI" to it.checkIPI, + "checkPhotoEmbedding" to it.checkPhotoEmbedding, + "checkPhotoComparison" to it.checkPhotoComparison, + "checkLetterScreen" to it.checkLetterScreen, + "checkSecurityText" to it.checkSecurityText, + "livenessParams" to getLivenessParams(it.livenessParams) + ).toJson() +} + +fun setLivenessParams(input: LivenessParams, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "checkOVI" -> input.checkOVI = v as Boolean + "checkMLI" -> input.checkMLI = v as Boolean + "checkHolo" -> input.checkHolo = v as Boolean + "checkED" -> input.checkED = v as Boolean + "checkBlackAndWhiteCopy" -> input.checkBlackAndWhiteCopy = v as Boolean + "checkDynaprint" -> input.checkDynaprint = v as Boolean + "checkGeometry" -> input.checkGeometry = v as Boolean + "checkBarcodeBackground" -> input.checkBarcodeBackground = v as Boolean + } +} + +fun getLivenessParams(input: LivenessParams?) = input?.let { + mapOf( + "checkOVI" to input.checkOVI, + "checkMLI" to input.checkMLI, + "checkHolo" to input.checkHolo, + "checkED" to input.checkED, + "checkBlackAndWhiteCopy" to input.checkBlackAndWhiteCopy, + "checkDynaprint" to input.checkDynaprint, + "checkGeometry" to input.checkGeometry, + "checkBarcodeBackground" to input.checkBarcodeBackground, + ).toJson() +} + +fun setColors(input: ParamsCustomization.CustomizationEditor, opts: JSONObject) = opts.forEach { k, value -> + val v = value.toLong() + when (k) { + "rfidProcessingScreenBackground" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_BACKGROUND, v) + "rfidProcessingScreenHintLabelText" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_HINT_LABEL_TEXT, v) + "rfidProcessingScreenHintLabelBackground" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_HINT_LABEL_BACKGROUND, v) + "rfidProcessingScreenProgressLabelText" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_LABEL_TEXT, v) + "rfidProcessingScreenProgressBar" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_BAR, v) + "rfidProcessingScreenProgressBarBackground" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_BAR_BACKGROUND, v) + "rfidProcessingScreenResultLabelText" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_RESULT_LABEL_TEXT, v) + "rfidProcessingScreenLoadingBar" -> input.setColor(CustomizationColor.RFID_PROCESSING_SCREEN_LOADING_BAR, v) + "rfidEnableNfcTitleText" -> input.setColor(CustomizationColor.RFID_ENABLE_NFC_TITLE_TEXT, v) + "rfidEnableNfcDescriptionText" -> input.setColor(CustomizationColor.RFID_ENABLE_NFC_DESCRIPTION_TEXT, v) + "rfidEnableNfcButtonText" -> input.setColor(CustomizationColor.RFID_ENABLE_NFC_BUTTON_TEXT, v) + "rfidEnableNfcButtonBackground" -> input.setColor(CustomizationColor.RFID_ENABLE_NFC_BUTTON_BACKGROUND, v) + "mdlProcessingScreenBackground" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_BACKGROUND, v) + "mdlProcessingScreenHintLabelText" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_HINT_LABEL_TEXT, v) + "mdlProcessingScreenHintLabelBackground" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_HINT_LABEL_BACKGROUND, v) + "mdlProcessingScreenProgressLabelText" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_PROGRESS_LABEL_TEXT, v) + "mdlProcessingScreenResultLabelText" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_RESULT_LABEL_TEXT, v) + "mdlProcessingScreenLoadingBar" -> input.setColor(CustomizationColor.MDL_PROCESSING_SCREEN_LOADING_BAR, v) + "mdlEnableNfcTitleText" -> input.setColor(CustomizationColor.MDL_ENABLE_NFC_TITLE_TEXT, v) + "mdlEnableNfcDescriptionText" -> input.setColor(CustomizationColor.MDL_ENABLE_NFC_DESCRIPTION_TEXT, v) + "mdlEnableNfcButtonText" -> input.setColor(CustomizationColor.MDL_ENABLE_NFC_BUTTON_TEXT, v) + "mdlEnableNfcButtonBackground" -> input.setColor(CustomizationColor.MDL_ENABLE_NFC_BUTTON_BACKGROUND, v) + "nextPageIdCardFront" -> input.setColor(CustomizationColor.NEXT_PAGE_ID_CARD_FRONT, v) + "nextPageIdCardBack" -> input.setColor(CustomizationColor.NEXT_PAGE_ID_CARD_BACK, v) + "nextPagePassportShift" -> input.setColor(CustomizationColor.NEXT_PAGE_PASSPORT_SHIFT, v) + "nextPagePassportFlip" -> input.setColor(CustomizationColor.NEXT_PAGE_PASSPORT_FLIP, v) + } +} + +fun getColors(input: Map) = mapOf( + "rfidProcessingScreenBackground" to input[CustomizationColor.RFID_PROCESSING_SCREEN_BACKGROUND], + "rfidProcessingScreenHintLabelText" to input[CustomizationColor.RFID_PROCESSING_SCREEN_HINT_LABEL_TEXT], + "rfidProcessingScreenHintLabelBackground" to input[CustomizationColor.RFID_PROCESSING_SCREEN_HINT_LABEL_BACKGROUND], + "rfidProcessingScreenProgressLabelText" to input[CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_LABEL_TEXT], + "rfidProcessingScreenProgressBar" to input[CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_BAR], + "rfidProcessingScreenProgressBarBackground" to input[CustomizationColor.RFID_PROCESSING_SCREEN_PROGRESS_BAR_BACKGROUND], + "rfidProcessingScreenResultLabelText" to input[CustomizationColor.RFID_PROCESSING_SCREEN_RESULT_LABEL_TEXT], + "rfidProcessingScreenLoadingBar" to input[CustomizationColor.RFID_PROCESSING_SCREEN_LOADING_BAR], + "rfidEnableNfcTitleText" to input[CustomizationColor.RFID_ENABLE_NFC_TITLE_TEXT], + "rfidEnableNfcDescriptionText" to input[CustomizationColor.RFID_ENABLE_NFC_DESCRIPTION_TEXT], + "rfidEnableNfcButtonText" to input[CustomizationColor.RFID_ENABLE_NFC_BUTTON_TEXT], + "rfidEnableNfcButtonBackground" to input[CustomizationColor.RFID_ENABLE_NFC_BUTTON_BACKGROUND], + "mdlProcessingScreenBackground" to input[CustomizationColor.MDL_PROCESSING_SCREEN_BACKGROUND], + "mdlProcessingScreenHintLabelText" to input[CustomizationColor.MDL_PROCESSING_SCREEN_HINT_LABEL_TEXT], + "mdlProcessingScreenHintLabelBackground" to input[CustomizationColor.MDL_PROCESSING_SCREEN_HINT_LABEL_BACKGROUND], + "mdlProcessingScreenProgressLabelText" to input[CustomizationColor.MDL_PROCESSING_SCREEN_PROGRESS_LABEL_TEXT], + "mdlProcessingScreenResultLabelText" to input[CustomizationColor.MDL_PROCESSING_SCREEN_RESULT_LABEL_TEXT], + "mdlProcessingScreenLoadingBar" to input[CustomizationColor.MDL_PROCESSING_SCREEN_LOADING_BAR], + "mdlEnableNfcTitleText" to input[CustomizationColor.MDL_ENABLE_NFC_TITLE_TEXT], + "mdlEnableNfcDescriptionText" to input[CustomizationColor.MDL_ENABLE_NFC_DESCRIPTION_TEXT], + "mdlEnableNfcButtonText" to input[CustomizationColor.MDL_ENABLE_NFC_BUTTON_TEXT], + "mdlEnableNfcButtonBackground" to input[CustomizationColor.MDL_ENABLE_NFC_BUTTON_BACKGROUND], + "nextPageIdCardFront" to input[CustomizationColor.NEXT_PAGE_ID_CARD_FRONT], + "nextPageIdCardBack" to input[CustomizationColor.NEXT_PAGE_ID_CARD_BACK], + "nextPagePassportShift" to input[CustomizationColor.NEXT_PAGE_PASSPORT_SHIFT], + "nextPagePassportFlip" to input[CustomizationColor.NEXT_PAGE_PASSPORT_FLIP], +).toJson() + +fun setFonts(input: ParamsCustomization.CustomizationEditor, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "rfidProcessingScreenHintLabel" -> CustomizationFont.RFID_PROCESSING_SCREEN_HINT_LABEL.setFont(input, v) + "rfidProcessingScreenProgressLabel" -> CustomizationFont.RFID_PROCESSING_SCREEN_PROGRESS_LABEL.setFont(input, v) + "rfidProcessingScreenResultLabel" -> CustomizationFont.RFID_PROCESSING_SCREEN_RESULT_LABEL.setFont(input, v) + "rfidEnableNfcTitleText" -> CustomizationFont.RFID_ENABLE_NFC_TITLE_TEXT.setFont(input, v) + "rfidEnableNfcDescriptionText" -> CustomizationFont.RFID_ENABLE_NFC_DESCRIPTION_TEXT.setFont(input, v) + "rfidEnableNfcButtonText" -> CustomizationFont.RFID_ENABLE_NFC_BUTTON_TEXT.setFont(input, v) + "mdlProcessingScreenHintLabel" -> CustomizationFont.MDL_PROCESSING_SCREEN_HINT_LABEL.setFont(input, v) + "mdlProcessingScreenProgressLabel" -> CustomizationFont.MDL_PROCESSING_SCREEN_PROGRESS_LABEL.setFont(input, v) + "mdlProcessingScreenResultLabel" -> CustomizationFont.MDL_PROCESSING_SCREEN_RESULT_LABEL.setFont(input, v) + "mdlEnableNfcTitleText" -> CustomizationFont.MDL_ENABLE_NFC_TITLE_TEXT.setFont(input, v) + "mdlEnableNfcDescriptionText" -> CustomizationFont.MDL_ENABLE_NFC_DESCRIPTION_TEXT.setFont(input, v) + "mdlEnableNfcButtonText" -> CustomizationFont.MDL_ENABLE_NFC_BUTTON_TEXT.setFont(input, v) + } +} + +fun getFonts(fonts: Map, sizes: Map) = mapOf( + "rfidProcessingScreenHintLabel" to CustomizationFont.RFID_PROCESSING_SCREEN_HINT_LABEL.getFont(fonts, sizes), + "rfidProcessingScreenProgressLabel" to CustomizationFont.RFID_PROCESSING_SCREEN_PROGRESS_LABEL.getFont(fonts, sizes), + "rfidProcessingScreenResultLabel" to CustomizationFont.RFID_PROCESSING_SCREEN_RESULT_LABEL.getFont(fonts, sizes), + "rfidEnableNfcTitleText" to CustomizationFont.RFID_ENABLE_NFC_TITLE_TEXT.getFont(fonts, sizes), + "rfidEnableNfcDescriptionText" to CustomizationFont.RFID_ENABLE_NFC_DESCRIPTION_TEXT.getFont(fonts, sizes), + "rfidEnableNfcButtonText" to CustomizationFont.RFID_ENABLE_NFC_BUTTON_TEXT.getFont(fonts, sizes), + "mdlProcessingScreenHintLabel" to CustomizationFont.MDL_PROCESSING_SCREEN_HINT_LABEL.getFont(fonts, sizes), + "mdlProcessingScreenProgressLabel" to CustomizationFont.MDL_PROCESSING_SCREEN_PROGRESS_LABEL.getFont(fonts, sizes), + "mdlProcessingScreenResultLabel" to CustomizationFont.MDL_PROCESSING_SCREEN_RESULT_LABEL.getFont(fonts, sizes), + "mdlEnableNfcTitleText" to CustomizationFont.MDL_ENABLE_NFC_TITLE_TEXT.getFont(fonts, sizes), + "mdlEnableNfcDescriptionText" to CustomizationFont.MDL_ENABLE_NFC_DESCRIPTION_TEXT.getFont(fonts, sizes), + "mdlEnableNfcButtonText" to CustomizationFont.MDL_ENABLE_NFC_BUTTON_TEXT.getFont(fonts, sizes), +).toJson() + +fun setImages(input: ParamsCustomization.CustomizationEditor, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "helpAnimation" -> input.setImage(CustomizationImage.HELP_ANIMATION, v.toDrawable()) + "livenessAnimation" -> input.setImage(CustomizationImage.LIVENESS_ANIMATION, v.toDrawable()) + "borderBackground" -> input.setImage(CustomizationImage.BORDER_BACKGROUND, v.toDrawable()) + "torchButtonOn" -> input.setImage(CustomizationImage.TORCH_BUTTON_ON, v.toDrawable()) + "torchButtonOff" -> input.setImage(CustomizationImage.TORCH_BUTTON_OFF, v.toDrawable()) + "captureButton" -> input.setImage(CustomizationImage.CAPTURE_BUTTON, v.toDrawable()) + "switchButton" -> input.setImage(CustomizationImage.SWITCH_BUTTON, v.toDrawable()) + "closeButton" -> input.setImage(CustomizationImage.CLOSE_BUTTON, v.toDrawable()) + "multipageButton" -> input.setImage(CustomizationImage.MULTIPAGE_BUTTON, v.toDrawable()) + "rfidProcessingScreenFailureImage" -> input.setImage(CustomizationImage.RFID_PROCESSING_SCREEN_FAILURE_IMAGE, v.toDrawable()) + "rfidEnableNfcImage" -> input.setImage(CustomizationImage.RFID_ENABLE_NFC_IMAGE, v.toDrawable()) + "rfidDisableNfcImage" -> input.setImage(CustomizationImage.RFID_DISABLE_NFC_IMAGE, v.toDrawable()) + "mdlProcessingScreenFailureImage" -> input.setImage(CustomizationImage.MDL_PROCESSING_SCREEN_FAILURE_IMAGE, v.toDrawable()) + "mdlEnableNfcImage" -> input.setImage(CustomizationImage.MDL_ENABLE_NFC_IMAGE, v.toDrawable()) + "mdlDisableNfcImage" -> input.setImage(CustomizationImage.MDL_DISABLE_NFC_IMAGE, v.toDrawable()) + "nextPageIdCardFront" -> input.setImage(CustomizationImage.NEXT_PAGE_ID_CARD_FRONT, v.toDrawable()) + "nextPageIdCardBack" -> input.setImage(CustomizationImage.NEXT_PAGE_ID_CARD_BACK, v.toDrawable()) + "nextPagePassportShift" -> input.setImage(CustomizationImage.NEXT_PAGE_PASSPORT_SHIFT, v.toDrawable()) + "nextPagePassportFlipStart" -> input.setImage(CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_START, v.toDrawable()) + "nextPagePassportFlipClean" -> input.setImage(CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_CLEAN, v.toDrawable()) + "nextPagePassportFlipTop" -> input.setImage(CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_TOP, v.toDrawable()) + "nextPagePassportFlipBottom" -> input.setImage(CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_BOTTOM, v.toDrawable()) + } +} + +fun getImages(input: Map) = mapOf( + "helpAnimation" to input[CustomizationImage.HELP_ANIMATION.value].toBase64(), + "livenessAnimation" to input[CustomizationImage.LIVENESS_ANIMATION.value].toBase64(), + "borderBackground" to input[CustomizationImage.BORDER_BACKGROUND.value].toBase64(), + "torchButtonOn" to input[CustomizationImage.TORCH_BUTTON_ON.value].toBase64(), + "torchButtonOff" to input[CustomizationImage.TORCH_BUTTON_OFF.value].toBase64(), + "captureButton" to input[CustomizationImage.CAPTURE_BUTTON.value].toBase64(), + "switchButton" to input[CustomizationImage.SWITCH_BUTTON.value].toBase64(), + "closeButton" to input[CustomizationImage.CLOSE_BUTTON.value].toBase64(), + "multipageButton" to input[CustomizationImage.MULTIPAGE_BUTTON.value].toBase64(), + "rfidProcessingScreenFailureImage" to input[CustomizationImage.RFID_PROCESSING_SCREEN_FAILURE_IMAGE.value].toBase64(), + "rfidEnableNfcImage" to input[CustomizationImage.RFID_ENABLE_NFC_IMAGE.value].toBase64(), + "rfidDisableNfcImage" to input[CustomizationImage.RFID_DISABLE_NFC_IMAGE.value].toBase64(), + "mdlProcessingScreenFailureImage" to input[CustomizationImage.MDL_PROCESSING_SCREEN_FAILURE_IMAGE.value].toBase64(), + "mdlEnableNfcImage" to input[CustomizationImage.MDL_ENABLE_NFC_IMAGE.value].toBase64(), + "mdlDisableNfcImage" to input[CustomizationImage.MDL_DISABLE_NFC_IMAGE.value].toBase64(), + "nextPageIdCardFront" to input[CustomizationImage.NEXT_PAGE_ID_CARD_FRONT.value].toBase64(), + "nextPageIdCardBack" to input[CustomizationImage.NEXT_PAGE_ID_CARD_BACK.value].toBase64(), + "nextPagePassportShift" to input[CustomizationImage.NEXT_PAGE_PASSPORT_SHIFT.value].toBase64(), + "nextPagePassportFlipStart" to input[CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_START.value].toBase64(), + "nextPagePassportFlipClean" to input[CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_CLEAN.value].toBase64(), + "nextPagePassportFlipTop" to input[CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_TOP.value].toBase64(), + "nextPagePassportFlipBottom" to input[CustomizationImage.NEXT_PAGE_PASSPORT_FLIP_BOTTOM.value].toBase64(), +).toJson() + +fun setTimings(input: ParamsCustomization.CustomizationEditor, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "nextPageIdCardStartDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_ID_CARD_START_DELAY, v.toInt()) + "nextPageIdCardEndDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_ID_CARD_END_DELAY, v.toInt()) + "nextPagePassportShiftStartDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_PASSPORT_SHIFT_START_DELAY, v.toInt()) + "nextPagePassportShiftEndDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_PASSPORT_SHIFT_END_DELAY, v.toInt()) + "nextPagePassportFlipStartDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_PASSPORT_FLIP_START_DELAY, v.toInt()) + "nextPagePassportFlipEndDelay" -> input.setTiming(CustomizationTiming.NEXT_PAGE_PASSPORT_FLIP_END_DELAY, v.toInt()) + } +} + +fun getTimings(input: Map) = mapOf( + "nextPageIdCardStartDelay" to input[CustomizationTiming.NEXT_PAGE_ID_CARD_START_DELAY], + "nextPageIdCardEndDelay" to input[CustomizationTiming.NEXT_PAGE_ID_CARD_END_DELAY], + "nextPagePassportShiftStartDelay" to input[CustomizationTiming.NEXT_PAGE_PASSPORT_SHIFT_START_DELAY], + "nextPagePassportShiftEndDelay" to input[CustomizationTiming.NEXT_PAGE_PASSPORT_SHIFT_END_DELAY], + "nextPagePassportFlipStartDelay" to input[CustomizationTiming.NEXT_PAGE_PASSPORT_FLIP_START_DELAY], + "nextPagePassportFlipEndDelay" to input[CustomizationTiming.NEXT_PAGE_PASSPORT_FLIP_END_DELAY], +).toJson() + +fun setMatrices(input: ParamsCustomization.CustomizationEditor, opts: JSONObject) = opts.forEach { k, v -> + when (k) { + "nextPageIdCardFront" -> input.setMatrix(CustomizationMatrix.NEXT_PAGE_ID_CARD_FRONT, matrixFromJSON(v as JSONArray?)).setScaleType(CustomizationScaleType.NEXT_PAGE_ID_CARD_FRONT, ImageView.ScaleType.MATRIX) + "nextPageIdCardBack" -> input.setMatrix(CustomizationMatrix.NEXT_PAGE_ID_CARD_BACK, matrixFromJSON(v as JSONArray?)).setScaleType(CustomizationScaleType.NEXT_PAGE_ID_CARD_BACK, ImageView.ScaleType.MATRIX) + } +} + +fun getMatrices(input: Map) = mapOf( + "nextPageIdCardFront" to generateMatrix(input[CustomizationMatrix.NEXT_PAGE_ID_CARD_FRONT]), + "nextPageIdCardBack" to generateMatrix(input[CustomizationMatrix.NEXT_PAGE_ID_CARD_BACK]), +).toJson() + +fun CustomizationFont.getFont(fonts: Map, sizes: Map) = + generateTypeface(fonts[this], sizes[this]) + +fun CustomizationFont.setFont(editor: ParamsCustomization.CustomizationEditor, value: Any?) { + val font = typefaceFromJSON(value as JSONObject) + editor.setFont(this, font.first) + font.second?.let { editor.setFontSize(this, it) } +} + +fun Any.toInt() = when (this) { + is Double -> toInt() + is Long -> toInt() + is String -> Integer.parseInt(this) + else -> this as Int +} + +fun Any.toLong() = when (this) { + is Double -> toLong() + is Int -> toLong() + else -> this as Long +} + +fun Any.toFloat() = when (this) { + is Int -> toFloat() + is Double -> toFloat() + else -> this as Float +} + +fun Any.toDouble() = when (this) { + is Int -> toDouble() + is Long -> toDouble() + else -> this as Double +} + +fun Any?.toColor() = this?.let { + "#" + toLong().toString(16) +} + +fun String?.colorToLong() = this?.let { + if (this[0] == '#') this.substring(1).toLong(16) + else this.toLong(16) +} diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt new file mode 100644 index 0000000000..d3de82fb42 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt @@ -0,0 +1,97 @@ +@file:SuppressLint("MissingPermission") + +package com.regula.plugin.documentreader + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.os.Handler +import android.os.Looper +import android.util.Log +import androidx.core.app.ActivityCompat +import androidx.lifecycle.Lifecycle +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding +import io.flutter.embedding.engine.plugins.lifecycle.HiddenLifecycleReference +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.EventChannel.EventSink +import io.flutter.plugin.common.EventChannel.StreamHandler +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.MethodChannel.MethodCallHandler + +const val channelID = "flutter_document_reader_api" +val eventSinks = mutableMapOf() + +lateinit var args: List +lateinit var binding: FlutterPluginBinding +lateinit var activityBinding: ActivityPluginBinding +val context: Context + get() = binding.applicationContext +val activity: Activity + get() = activityBinding.activity +val lifecycle: Lifecycle + get() = (activityBinding.lifecycle as HiddenLifecycleReference).lifecycle + +fun sendEvent(id: String, data: Any? = "") { + eventSinks[id]?.let { Handler(Looper.getMainLooper()).post { it.success(data.toSendable()) } } +} + +inline fun argsNullable(index: Int) = when (val v = args[index]) { + null -> null + is Map<*, *> -> v.toJson() as T + is List<*> -> v.toJson() as T + else -> v as T +} + +fun setupEventChannel(id: String) = EventChannel(binding.binaryMessenger, "$channelID/event/$id").setStreamHandler(object : StreamHandler { + override fun onListen(arguments: Any?, events: EventSink) = events.let { eventSinks[id] = it } + override fun onCancel(arguments: Any?) = Unit +}) + +fun requestPermissions(activity: Activity, permissions: Array, requestCode: Int) = ActivityCompat.requestPermissions(activity, permissions, requestCode) +fun startActivityForResult(activity: Activity, intent: Intent, requestCode: Int) = activity.startActivityForResult(intent, requestCode) + +class FlutterDocumentReaderApiPlugin : FlutterPlugin, MethodCallHandler, ActivityAware { + override fun onDetachedFromActivityForConfigChanges() = Unit + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) = Unit + override fun onDetachedFromActivity() = Unit + override fun onDetachedFromEngine(binding: FlutterPluginBinding) = Unit + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + args = call.arguments as List<*> + try { + methodCall(call.method) { data -> result.success(data.toSendable()) } + } catch (error: Exception) { + Log.e("REGULA", "Caught exception in \"${call.method}\" function:", error) + } + } + + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + activityBinding = binding + binding.addOnNewIntentListener(::newIntent) + binding.addActivityResultListener(::onActivityResult) + binding.addRequestPermissionsResultListener(::onRequestPermissionsResult) + } + + override fun onAttachedToEngine(flutterBinding: FlutterPluginBinding) { + binding = flutterBinding + for (event in arrayOf( + completionEvent, + databaseProgressEvent, + rfidOnProgressEvent, + rfidOnChipDetectedEvent, + rfidOnRetryReadChipEvent, + paCertificateCompletionEvent, + taCertificateCompletionEvent, + taSignatureCompletionEvent, + paceProtocolCompletionEvent, + caProtocolCompletionEvent, + videoEncoderCompletionEvent, + onCustomButtonTappedEvent + )) setupEventChannel(event) + MethodChannel(binding.binaryMessenger, "$channelID/method").setMethodCallHandler(this) + } +} diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/JSONConstructor.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/JSONConstructor.kt new file mode 100644 index 0000000000..435f8ee2f0 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/JSONConstructor.kt @@ -0,0 +1,2176 @@ +@file:SuppressLint("MissingPermission") +@file:Suppress("unused", "EnumValuesSoftDeprecate", "UNCHECKED_CAST") + +package com.regula.plugin.documentreader + +import android.annotation.SuppressLint +import android.graphics.Bitmap +import android.graphics.Matrix +import android.graphics.Rect +import android.graphics.Typeface +import android.os.Build +import android.util.Pair +import com.regula.common.exception.RegulaException +import com.regula.documentreader.api.License +import com.regula.documentreader.api.completions.model.PrepareProgress +import com.regula.documentreader.api.config.FinalizeConfig +import com.regula.documentreader.api.config.RecognizeConfig +import com.regula.documentreader.api.config.ScannerConfig +import com.regula.documentreader.api.enums.BarcodeType +import com.regula.documentreader.api.enums.DocReaderAction +import com.regula.documentreader.api.enums.PDF417Info +import com.regula.documentreader.api.enums.eGraphicFieldType +import com.regula.documentreader.api.enums.eMDLDeviceRetrieval +import com.regula.documentreader.api.enums.eMDLDocRequestPreset +import com.regula.documentreader.api.enums.eMDLIntentToRetain +import com.regula.documentreader.api.enums.eRFID_DataFile_Type +import com.regula.documentreader.api.enums.eRPRM_Lights +import com.regula.documentreader.api.listener.NetworkInterceptorListener +import com.regula.documentreader.api.params.AuthenticityParams +import com.regula.documentreader.api.params.BackendProcessingConfig +import com.regula.documentreader.api.params.BleDeviceConfig +import com.regula.documentreader.api.params.Bsi +import com.regula.documentreader.api.params.DocReaderConfig +import com.regula.documentreader.api.params.FaceApiParams +import com.regula.documentreader.api.params.Functionality +import com.regula.documentreader.api.params.ImageInputData +import com.regula.documentreader.api.params.ImageQA +import com.regula.documentreader.api.params.ImageQA.GlaresCheckParams +import com.regula.documentreader.api.params.LivenessParams +import com.regula.documentreader.api.params.OnlineProcessingConfig +import com.regula.documentreader.api.params.ParamsCustomization +import com.regula.documentreader.api.params.ProcessParam +import com.regula.documentreader.api.params.RfidScenario +import com.regula.documentreader.api.params.mdl.DataRetrieval +import com.regula.documentreader.api.params.mdl.DeviceEngagement +import com.regula.documentreader.api.params.mdl.DeviceRetrievalMethod +import com.regula.documentreader.api.params.mdl.DocumentRequest18013MDL +import com.regula.documentreader.api.params.mdl.DocumentRequestMDL +import com.regula.documentreader.api.params.mdl.NameSpaceMDL +import com.regula.documentreader.api.params.rfid.CaProtocol +import com.regula.documentreader.api.params.rfid.PKDCertificate +import com.regula.documentreader.api.params.rfid.PaceProtocol +import com.regula.documentreader.api.params.rfid.RFIDParams +import com.regula.documentreader.api.params.rfid.TccParams +import com.regula.documentreader.api.params.rfid.authorization.PAAttribute +import com.regula.documentreader.api.params.rfid.authorization.PAResourcesIssuer +import com.regula.documentreader.api.params.rfid.authorization.TAChallenge +import com.regula.documentreader.api.params.rfid.dg.DTCDataGroup +import com.regula.documentreader.api.params.rfid.dg.EDLDataGroups +import com.regula.documentreader.api.params.rfid.dg.EIDDataGroups +import com.regula.documentreader.api.params.rfid.dg.EPassportDataGroups +import com.regula.documentreader.api.results.BytesData +import com.regula.documentreader.api.results.Coordinate +import com.regula.documentreader.api.results.DocFeature +import com.regula.documentreader.api.results.DocReaderDocumentsDatabase +import com.regula.documentreader.api.results.DocReaderFieldRect +import com.regula.documentreader.api.results.DocReaderVersion +import com.regula.documentreader.api.results.DocumentReaderBarcodeField +import com.regula.documentreader.api.results.DocumentReaderBarcodeResult +import com.regula.documentreader.api.results.DocumentReaderComparison +import com.regula.documentreader.api.results.DocumentReaderDocumentType +import com.regula.documentreader.api.results.DocumentReaderGraphicField +import com.regula.documentreader.api.results.DocumentReaderGraphicResult +import com.regula.documentreader.api.results.DocumentReaderNotification +import com.regula.documentreader.api.results.DocumentReaderResults +import com.regula.documentreader.api.results.DocumentReaderResultsStatus +import com.regula.documentreader.api.results.DocumentReaderResultsStatus.DetailsOptical +import com.regula.documentreader.api.results.DocumentReaderResultsStatus.DetailsRFID +import com.regula.documentreader.api.results.DocumentReaderResultsStatus.DetailsAge +import com.regula.documentreader.api.results.DocumentReaderRfidOrigin +import com.regula.documentreader.api.results.DocumentReaderScenario +import com.regula.documentreader.api.results.DocumentReaderSymbol +import com.regula.documentreader.api.results.DocumentReaderTextField +import com.regula.documentreader.api.results.DocumentReaderTextResult +import com.regula.documentreader.api.results.DocumentReaderTextSource +import com.regula.documentreader.api.results.DocumentReaderValidity +import com.regula.documentreader.api.results.DocumentReaderValue +import com.regula.documentreader.api.results.ElementPosition +import com.regula.documentreader.api.results.ImageQuality +import com.regula.documentreader.api.results.ImageQualityGroup +import com.regula.documentreader.api.results.TransactionInfo +import com.regula.documentreader.api.results.VDSData +import com.regula.documentreader.api.results.VDSNCData +import com.regula.documentreader.api.results.authenticity.DocumentReaderAuthenticityCheck +import com.regula.documentreader.api.results.authenticity.DocumentReaderAuthenticityElement +import com.regula.documentreader.api.results.authenticity.DocumentReaderAuthenticityResult +import com.regula.documentreader.api.results.rfid.AccessControlProcedureType +import com.regula.documentreader.api.results.rfid.Application +import com.regula.documentreader.api.results.rfid.Attribute +import com.regula.documentreader.api.results.rfid.Authority +import com.regula.documentreader.api.results.rfid.CardProperties +import com.regula.documentreader.api.results.rfid.CertificateChain +import com.regula.documentreader.api.results.rfid.CertificateData +import com.regula.documentreader.api.results.rfid.DataField +import com.regula.documentreader.api.results.rfid.Extension +import com.regula.documentreader.api.results.rfid.File +import com.regula.documentreader.api.results.rfid.FileData +import com.regula.documentreader.api.results.rfid.RFIDSessionData +import com.regula.documentreader.api.results.rfid.SecurityObject +import com.regula.documentreader.api.results.rfid.SecurityObjectCertificates +import com.regula.documentreader.api.results.rfid.SignerInfo +import com.regula.documentreader.api.results.rfid.Validity +import com.regula.documentreader.api.results.rfid.Value +import org.json.JSONArray +import org.json.JSONObject +import com.regula.plugin.documentreader.Convert.toBase64 +import com.regula.plugin.documentreader.Convert.toBitmap +import com.regula.plugin.documentreader.Convert.toByteArray + +fun generateCompletion(action: Int, results: DocumentReaderResults?, error: RegulaException?) = mapOf( + "action" to action, + "results" to if (listOf(DocReaderAction.COMPLETE, DocReaderAction.MORE_PAGES_AVAILABLE, DocReaderAction.CANCEL, DocReaderAction.ERROR, DocReaderAction.TIMEOUT).contains(action)) generateDocumentReaderResults(results) else null, + "error" to generateRegulaException(error) +).toJson() + +fun generateSuccessCompletion(success: Boolean, error: RegulaException?) = mapOf( + "success" to success, + "error" to generateRegulaException(error) +).toJson() + +fun prepareProgressFromJSON(it: JSONObject) = PrepareProgress( + it.getInt("downloadedBytes"), + it.getInt("totalBytes") +) + +fun generatePrepareProgress(it: PrepareProgress) = mapOf( + "downloadedBytes" to it.downloadedBytes, + "totalBytes" to it.totalBytes, + "progress" to it.progress +).toJson() + +fun generatePACertificateCompletion(serialNumber: ByteArray?, issuer: PAResourcesIssuer?) = mapOf( + "serialNumber" to serialNumber.toBase64(), + "issuer" to generatePAResourcesIssuer(issuer) +).toJson() + +fun generateFinalizePackageCompletion(action: Int, info: TransactionInfo?, error: RegulaException?) = mapOf( + "action" to action, + "info" to generateTransactionInfo(info), + "error" to generateRegulaException(error) +).toJson() + +fun regulaExceptionFromJSON(input: JSONObject?) = input?.let { + RegulaException( + it.optInt("code"), + it.optString("message") + ) +} + +fun generateRegulaException(input: RegulaException?) = input?.let { + mapOf( + "code" to it.errorCode, + "message" to it.message + ).toJson() +} + +fun transactionInfoFromJSON(input: JSONObject?) = input?.let { + val result = TransactionInfo() + result.transactionId = it.getStringOrNull("transactionId") + result.tag = it.getStringOrNull("tag") + result.sessionLogFolder = it.getStringOrNull("sessionLogFolder") + result +} + +fun generateTransactionInfo(input: TransactionInfo?) = input?.let { + mapOf( + "transactionId" to it.transactionId, + "tag" to it.tag, + "sessionLogFolder" to it.sessionLogFolder + ).toJson() +} + +fun tccParamsFromJSON(input: JSONObject) = input.let { + val result = TccParams() + result.serviceUrlTA = it.getStringOrNull("serviceUrlTA") + result.serviceUrlPA = it.getStringOrNull("serviceUrlPA") + result.pfxCertUrl = it.getStringOrNull("pfxCertUrl") + result.pfxPassPhrase = it.getStringOrNull("pfxPassPhrase") + result.pfxCert = it.getStringOrNull("pfxCert").toByteArray() + result +} + +fun generateTccParams(input: TccParams?) = input?.let { + mapOf( + "serviceUrlTA" to it.serviceUrlTA, + "serviceUrlPA" to it.serviceUrlPA, + "pfxCertUrl" to it.pfxCertUrl, + "pfxPassPhrase" to it.pfxPassPhrase, + "pfxCert" to it.pfxCert.toBase64() + ).toJson() +} + +fun initConfigFromJSON(input: JSONObject) = input.let { + val license = it.getString("license").toByteArray()!! + var result = DocReaderConfig(license) + if (it.has("customDb")) result = DocReaderConfig(license, it.getString("customDb").toByteArray()!!) + if (it.has("databasePath")) result = DocReaderConfig(license, it.getString("databasePath")) + + if (it.has("licenseUpdate")) result.setLicenseUpdate(it.getBoolean("licenseUpdate")) + if (it.has("delayedNNLoad")) result.isDelayedNNLoad = it.getBoolean("delayedNNLoad") + result.licenseUpdateTimeout = it.getDoubleOrNull("licenseUpdateTimeout") + result.blackList = it.getJSONObjectOrNull("blackList") + result +} + +fun generateInitConfig(input: DocReaderConfig?) = input?.let { + mapOf( + "license" to it.license.toBase64(), + "customDb" to it.customDb.toBase64(), + "databasePath" to it.customDbPath, + "licenseUpdate" to it.isLicenseUpdate, + "delayedNNLoad" to it.isDelayedNNLoad, + "licenseUpdateTimeout" to it.licenseUpdateTimeout, + "blackList" to it.blackList + ).toJson() +} + +fun initBleDeviceConfigFromJSON(input: JSONObject) = input.let { + var result = BleDeviceConfig(bluetooth!!) + if (it.has("customDb")) result = BleDeviceConfig(bluetooth!!, it.getString("customDb").toByteArray()) + + if (it.has("licenseUpdate")) result.setLicenseUpdate(it.getBoolean("licenseUpdate")) + if (it.has("delayedNNLoad")) result.isDelayedNNLoad = it.getBoolean("delayedNNLoad") + result.licenseUpdateTimeout = it.getDoubleOrNull("licenseUpdateTimeout") + result.blackList = it.getJSONObjectOrNull("blackList") + result +} + +fun scannerConfigFromJSON(input: JSONObject) = input.let { + val builder = if (it.has("scenario")) ScannerConfig.Builder(it.getString("scenario")) + else ScannerConfig.Builder(onlineProcessingConfigFromJSON(it.getJSONObject("onlineProcessingConfig"))!!) + + if (it.has("onlineProcessingConfig")) builder.setOnlineProcessingConfig(onlineProcessingConfigFromJSON(it.getJSONObject("onlineProcessingConfig"))) + if (it.has("livePortrait")) builder.setLivePortrait(it.getString("livePortrait").toBitmap()!!) + if (it.has("extPortrait")) builder.setExtPortrait(it.getString("extPortrait").toBitmap()!!) + if (it.has("cameraId")) builder.setCameraId(it.getInt("cameraId")) + builder.build() +} + +fun generateScannerConfig(input: ScannerConfig?) = input?.let { + mapOf( + "scenario" to it.scenario, + "onlineProcessingConfig" to generateOnlineProcessingConfig(it.onlineProcessingConfig), + "livePortrait" to it.livePortrait.toBase64(), + "extPortrait" to it.extPortrait.toBase64(), + "cameraId" to it.cameraId + ).toJson() +} + +fun recognizeConfigFromJSON(input: JSONObject) = input.let { + val builder = if (it.has("scenario")) RecognizeConfig.Builder(it.getString("scenario")) + else RecognizeConfig.Builder(onlineProcessingConfigFromJSON(it.getJSONObject("onlineProcessingConfig"))!!) + + if (it.has("oneShotIdentification")) builder.setOneShotIdentification(it.getBoolean("oneShotIdentification")) + if (it.has("dtc")) builder.setDTC(it.getString("dtc").toByteArray()!!) + if (it.has("livePortrait")) builder.setLivePortrait(it.getString("livePortrait").toBitmap()!!) + if (it.has("extPortrait")) builder.setExtPortrait(it.getString("extPortrait").toBitmap()!!) + if (it.has("image")) builder.setBitmap(it.getString("image").toBitmap()!!) + if (it.has("data")) builder.setData(it.getString("data").toByteArray()!!) + if (it.has("images")) { + val base64Images = it.getJSONArray("images") + val images = arrayOfNulls(base64Images.length()) + for (i in images.indices) images[i] = base64Images.getString(i).toBitmap() + builder.setBitmaps(images) + } + if (it.has("dataList")) { + val array = it.getJSONArray("dataList") + val dataList = mutableListOf() + for (i in 0..< array.length()) dataList.add(array.getString(i).toByteArray()!!) + builder.setData(dataList) + } + if (it.has("imageInputData")) { + val base64InputData = it.getJSONArray("imageInputData") + val inputData = arrayOfNulls(base64InputData.length()) + for (i in inputData.indices) inputData[i] = imageInputDataFromJSON(base64InputData.getJSONObject(i)) + builder.setImageInputData(inputData) + } + builder.build() +} + +fun generateRecognizeConfig(input: RecognizeConfig?) = input?.let { + mapOf( + "scenario" to it.scenario, + "onlineProcessingConfig" to generateOnlineProcessingConfig(it.onlineProcessingConfig), + "oneShotIdentification" to it.oneShotIdentification, + "dtc" to it.dtc.toBase64(), + "livePortrait" to it.livePortrait.toBase64(), + "extPortrait" to it.extPortrait.toBase64(), + "image" to it.bitmap.toBase64(), + "images" to it.bitmaps?.map { bp -> bp.toBase64() }?.toJson(), + "dataList" to it.data?.map { bp -> bp.toBase64() }?.toJson(), + "imageInputData" to it.imageInputData.toJson(::generateImageInputData) + ).toJson() +} + +fun backendProcessingConfigFromJSON(input: JSONObject?) = input?.let { + val result = BackendProcessingConfig(it.getString("url")) + if (it.has("httpHeaders")) { + val httpHeaders: MutableMap = HashMap() + it.getJSONObject("httpHeaders").forEach { key, value -> httpHeaders[key] = value as String } + result.httpHeaders = httpHeaders + } + result.rfidServerSideChipVerification = it.getBooleanOrNull("rfidServerSideChipVerification") + result.timeoutConnection = it.getDoubleOrNull("timeoutConnection") + if (it.has("mdlVerification")) result.mdlVerification = it.getBoolean("mdlVerification") + result +} + +fun generateBackendProcessingConfig(input: BackendProcessingConfig?) = input?.let { + mapOf( + "url" to it.url, + "rfidServerSideChipVerification" to it.rfidServerSideChipVerification, + "timeoutConnection" to it.timeoutConnection, + "httpHeaders" to if (it.httpHeaders == null) null else { + val httpHeaders = JSONObject() + for ((key, value) in it.httpHeaders!!) httpHeaders.put(key, value) + httpHeaders + }, + "mdlVerification" to it.mdlVerification, + ).toJson() +} + +fun bsiFromJSON(input: JSONObject?) = input?.let { + val result = Bsi() + result.generateResult = it.getBooleanOrNull("generateResult") + result +} + +fun generateBsi(input: Bsi?) = input?.let { + mapOf( + "generateResult" to it.generateResult, + ).toJson() +} + +val weakReferencesHolder = mutableListOf() +fun onlineProcessingConfigFromJSON(input: JSONObject?) = input?.let { + val builder = OnlineProcessingConfig.Builder(it.getInt("mode")) + + if (it.has("imageFormat")) builder.setImageFormat(it.getInt("imageFormat")) + if (it.has("url")) builder.setUrl(it.getString("url")) + if (it.has("imageCompressionQuality")) builder.setImageCompressionQuality(it.getDouble("imageCompressionQuality").toFloat()) + if (it.has("processParams")) builder.setProcessParams(processParamFromJSON(it.getJSONObject("processParams"))) + if (it.has("requestHeaders")) { + val listener = NetworkInterceptorListener { self -> input.getJSONObject("requestHeaders").forEach { k, v -> self.setRequestProperty(k, v as String) } } + weakReferencesHolder.add(listener) + builder.setNetworkInterceptorListener(listener) + } + builder.build() +} + +fun generateOnlineProcessingConfig(input: OnlineProcessingConfig?) = input?.let { + mapOf( + "mode" to it.mode, + "url" to it.url, + "processParams" to getProcessParams(it.processParam), + "imageFormat" to it.imageFormat, + "imageCompressionQuality" to it.imageCompressionQuality + ).toJson() +} + +fun faceApiParamsFromJSON(input: JSONObject?) = input?.let { + val result = FaceApiParams() + + if (it.has("url")) result.url = it.getString("url") + if (it.has("mode")) result.mode = it.getString("mode") + if (it.has("threshold") && !it.isNull("threshold")) result.threshold = it.getInt("threshold") + if (it.has("serviceTimeout") && !it.isNull("serviceTimeout")) result.serviceTimeout = it.getInt("serviceTimeout") + result.search = faceApiSearchParamsFromJSON(it.getJSONObjectOrNull("searchParams")) + result.proxy = it.getStringOrNull("proxy") + result.proxyUserPwd = it.getStringOrNull("proxyPassword") + result.proxyType = it.getIntOrNull("proxyType") + + result +} + +fun generateFaceApiParams(input: FaceApiParams?) = input?.let { + mapOf( + "url" to it.url, + "mode" to it.mode, + "searchParams" to generateFaceApiSearchParams(it.search), + "threshold" to it.threshold, + "serviceTimeout" to it.serviceTimeout, + "proxy" to it.proxy, + "proxyPassword" to it.proxyUserPwd, + "proxyType" to it.proxyType + ).toJson() +} + +fun faceApiSearchParamsFromJSON(input: JSONObject?) = input?.let { + val result = FaceApiParams.Search() + + if (it.has("limit") && !it.isNull("limit")) result.limit = it.getInt("limit") + if (it.has("threshold") && !it.isNull("threshold")) result.threshold = it.getDouble("threshold").toFloat() + if (it.has("groupIds") && !it.isNull("groupIds")) { + val jsonArrayGroupIds = it.getJSONArray("groupIds") + val groupIds = arrayOfNulls(jsonArrayGroupIds.length()) + for (i in 0 until jsonArrayGroupIds.length()) + groupIds[i] = jsonArrayGroupIds.getString(i) + result.groupIds = groupIds + } + + result +} + +fun generateFaceApiSearchParams(input: FaceApiParams.Search?) = input?.let { + mapOf( + "limit" to it.limit, + "threshold" to it.threshold, + "groupIds" to it.groupIds.toJson() + ).toJson() +} + +fun rfidParamsFromJSON(input: JSONObject?) = input?.let { + val result = RFIDParams() + if (it.has("paIgnoreNotificationCodes")) result.paIgnoreNotificationCodes = it.getJSONArray("paIgnoreNotificationCodes").toIntArray() + result +} + +fun generateRFIDParams(input: RFIDParams?) = input?.let { + mapOf( + "paIgnoreNotificationCodes" to it.paIgnoreNotificationCodes.toJson() + ).toJson() +} + +fun processParamFromJSON(input: JSONObject): ProcessParam { + val result = ProcessParam() + setProcessParams(result, input) + return result +} + +fun generateProcessParam(input: ProcessParam): JSONObject = getProcessParams(input) + +fun imageQAFromJSON(input: JSONObject): ImageQA { + val result = ImageQA() + setImageQA(result, input) + return result +} + +fun generateImageQA(input: ImageQA) = getImageQA(input) + +fun authenticityParamsFromJSON(input: JSONObject): AuthenticityParams { + val result = AuthenticityParams.defaultParams() + setAuthenticityParams(result, input) + return result +} + +fun generateAuthenticityParams(input: AuthenticityParams?) = getAuthenticityParams(input) + +fun livenessParamsFromJSON(input: JSONObject): LivenessParams { + val result = LivenessParams.defaultParams() + setLivenessParams(result, input) + return result +} + +fun generateLivenessParams(input: LivenessParams?) = getLivenessParams(input) + +fun eDLDataGroupsFromJSON(input: JSONObject): EDLDataGroups { + val result = EDLDataGroups() + setDataGroups(result, input) + return result +} + +fun generateEDLDataGroups(input: EDLDataGroups): JSONObject = getDataGroups(input) + +fun ePassportDataGroupsFromJSON(input: JSONObject): EPassportDataGroups { + val result = EPassportDataGroups() + setDataGroups(result, input) + return result +} + +fun generateEPassportDataGroups(input: EPassportDataGroups): JSONObject = getDataGroups(input) + +fun eIDDataGroupsFromJSON(input: JSONObject): EIDDataGroups { + val result = EIDDataGroups() + setDataGroups(result, input) + return result +} + +fun generateEIDDataGroups(input: EIDDataGroups): JSONObject = getDataGroups(input) + +fun dtcDataGroupFromJSON(input: JSONObject): DTCDataGroup { + val result = DTCDataGroup() + setDTCDataGroup(result, input) + return result +} + +fun generateDTCDataGroup(input: DTCDataGroup): JSONObject = getDTCDataGroup(input) + +fun rfidScenarioFromJSON(input: JSONObject): RfidScenario { + val result = RfidScenario() + setRfidScenario(result, input) + return result +} + +fun generateRfidScenario(input: RfidScenario): JSONObject = getRfidScenario(input) + +fun customizationFromJSON(input: JSONObject): ParamsCustomization { + val result = ParamsCustomization() + setCustomization(result, input) + return result +} + +fun generateCustomization(input: ParamsCustomization): JSONObject = getCustomization(input) + +fun functionalityFromJSON(input: JSONObject): Functionality { + val result = Functionality() + setFunctionality(result, input) + return result +} + +fun generateFunctionality(input: Functionality): JSONObject = getFunctionality(input) + +fun glaresCheckParamsFromJSON(input: JSONObject?) = input?.let { + val result = GlaresCheckParams() + if (it.has("imgMarginPart")) result.imgMarginPart = it.getDouble("imgMarginPart") + if (it.has("maxGlaringPart")) result.maxGlaringPart = it.getDouble("maxGlaringPart") + result +} + +fun generateGlaresCheckParams(input: GlaresCheckParams?) = input?.let { + mapOf( + "imgMarginPart" to it.imgMarginPart, + "maxGlaringPart" to it.maxGlaringPart + ).toJson() +} + +@SuppressLint("DiscouragedApi") +fun typefaceFromJSON(it: JSONObject): Pair { + val font = try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + context.resources.getFont( + context.resources.getIdentifier( + it.getString("name"), + "font", + context.packageName + ) + ) + else throw Exception("") + } catch (_: Exception) { + Typeface.create( + it.getString("name"), + it.optInt("style", Typeface.NORMAL) + ) + } + return Pair( + font, + if (it.has("size")) it.getInt("size") else null + ) +} + +fun generateTypeface(input: Typeface?, size: Int? = null) = input?.let { + mapOf( + "name" to "undefined", + "style" to it.style, + "size" to size + ).toJson() +} + +fun imageInputDataFromJSON(input: JSONObject?) = input?.let { + ImageInputData( + it.getString("image").toBitmap()!!, + it.getIntOrNull("light") ?: 6, + it.getIntOrNull("pageIndex") ?: 0 + ) +} + +fun generateImageInputData(input: ImageInputData?) = input?.let { + mapOf( + "image" to it.bitmap.toBase64(), + "light" to it.light, + "pageIndex" to it.pageIndex + ).toJson() +} + +fun pkdCertificateFromJSON(input: JSONObject?) = input?.let { + var resourceType = 0 + var binaryData = ByteArray(0) + + if (it.has("resourceType")) resourceType = it.getInt("resourceType") + if (it.has("binaryData")) binaryData = it.getString("binaryData").toByteArray()!! + if (it.has("privateKey")) { + val privateKey = it.getString("privateKey").toByteArray() + return PKDCertificate(binaryData, resourceType, privateKey) + } + PKDCertificate(binaryData, resourceType) +} + +fun generatePKDCertificate(input: PKDCertificate?) = input?.let { + mapOf( + "resourceType" to it.resourceType, + "binaryData" to it.binaryData.toBase64(), + "privateKey" to it.privateKey.toBase64() + ).toJson() +} + +fun documentReaderScenarioFromJSON(input: JSONObject?) = input?.let { + DocumentReaderScenario( + it.optString("name"), + it.optString("caption"), + it.optString("description"), + if (it.optBoolean("multiPageOff")) 1 else 0, + it.optDouble("frameKWHLandscape"), + it.optDouble("frameKWHPortrait"), + it.optDouble("frameKWHDoublePageSpreadPortrait"), + it.optDouble("frameKWHDoublePageSpreadLandscape"), + it.optInt("frameOrientation"), + it.optBoolean("uvTorch"), + it.optBoolean("faceExt"), + it.optBoolean("seriesProcessMode"), + it.optBoolean("manualCrop"), + null + ) +} + +fun generateDocumentReaderScenario(input: DocumentReaderScenario?) = input?.let { + mapOf( + "name" to it.name, + "caption" to it.caption, + "description" to it.description, + "multiPageOff" to it.multiPageOff, + "frameKWHLandscape" to it.frameKWHLandscape, + "frameKWHPortrait" to it.frameKWHPortrait, + "frameKWHDoublePageSpreadPortrait" to it.frameKWHDoublePageSpreadPortrait, + "frameKWHDoublePageSpreadLandscape" to it.frameKWHDoublePageSpreadLandscape, + "frameOrientation" to it.frameOrientation, + "uvTorch" to it.uvTorch, + "faceExt" to it.faceExt, + "seriesProcessMode" to it.seriesProcessMode, + "manualCrop" to it.manualCrop + ).toJson() +} + +fun rectFromJSON(input: JSONObject?) = input?.let { + val result = Rect() + + result.bottom = it.optInt("bottom") + result.top = it.optInt("top") + result.left = it.optInt("left") + result.right = it.optInt("right") + + result +} + +fun generateRect(input: Rect?) = input?.let { + mapOf( + "bottom" to it.bottom, + "top" to it.top, + "left" to it.left, + "right" to it.right + ).toJson() +} + +fun docReaderFieldRectFromJSON(input: JSONObject?) = input?.let { + val result = DocReaderFieldRect() + + result.bottom = it.optInt("bottom") + result.top = it.optInt("top") + result.left = it.optInt("left") + result.right = it.optInt("right") + + result +} + +fun generateDocReaderFieldRect(input: DocReaderFieldRect?) = input?.let { + mapOf( + "bottom" to it.bottom, + "top" to it.top, + "left" to it.left, + "right" to it.right + ).toJson() +} + +fun documentReaderGraphicFieldFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderGraphicField() + + it.remove("value") + result.sourceType = it.optInt("sourceType") + result.fieldType = it.optInt("fieldType") + result.light = it.optInt("light") + result.pageIndex = it.optInt("pageIndex") + result.originalPageIndex = it.optInt("originalPageIndex") + result.boundRect = docReaderFieldRectFromJSON(it.optJSONObject("fieldRect")) + + result +} + +fun generateDocumentReaderGraphicField(input: DocumentReaderGraphicField?) = input?.let { + mapOf( + "sourceType" to it.sourceType, + "fieldType" to it.fieldType, + "light" to it.light, + "pageIndex" to it.pageIndex, + "originalPageIndex" to it.originalPageIndex, + "fieldName" to eGraphicFieldType.getTranslation(context, it.fieldType), + "lightName" to eRPRM_Lights.getTranslation(context, it.light), + "value" to it.imageBase64(), + "fieldRect" to generateDocReaderFieldRect(it.boundRect) + ).toJson() +} + +fun documentReaderGraphicResultFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderGraphicResult() + result.fields = it.optJSONArray("fields").toList(::documentReaderGraphicFieldFromJSON)!! + result +} + +fun generateDocumentReaderGraphicResult(input: DocumentReaderGraphicResult?) = input?.let { + mapOf( + "fields" to it.fields.toJson(::generateDocumentReaderGraphicField) + ).toJson() +} + +fun documentReaderValueFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderValue() + + result.pageIndex = it.optInt("pageIndex") + result.sourceType = it.optInt("sourceType") + result.probability = it.optInt("probability") + result.value = it.optString("value") + result.originalValue = it.optString("originalValue") + result.boundRect = rectFromJSON(it.optJSONObject("boundRect")) + result.originalSymbols = it.optJSONArray("originalSymbols").toList(::documentReaderSymbolFromJSON)!! + result.rfidOrigin = documentReaderRFIDOriginFromJSON(it.optJSONObject("rfidOrigin")) + + result +} + +fun generateDocumentReaderValue(input: DocumentReaderValue?) = input?.let { + mapOf( + "pageIndex" to it.pageIndex, + "sourceType" to it.sourceType, + "probability" to it.probability, + "value" to it.value, + "originalValue" to it.originalValue, + "boundRect" to generateRect(it.boundRect), + "originalSymbols" to it.originalSymbols.toJson(::generateDocumentReaderSymbol), + "rfidOrigin" to generateDocumentReaderRFIDOrigin(it.rfidOrigin) + ).toJson() +} + +fun documentReaderTextFieldFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderTextField() + + it.remove("getValue") + result.fieldType = it.optInt("fieldType") + result.lcid = it.optInt("lcid") + result.status = it.optInt("status") + result.value = it.optString("value") + result.values = it.optJSONArray("values").toList(::documentReaderValueFromJSON)!! + result.comparisonList = it.optJSONArray("comparisonList").toList(::documentReaderComparisonFromJSON)!! + result.validityList = it.optJSONArray("validityList").toList(::documentReaderValidityFromJSON)!! + result.comparisonStatus = it.optInt("comparisonStatus") + result.validityStatus = it.optInt("validityStatus") + + result +} + +fun generateDocumentReaderTextField(input: DocumentReaderTextField?) = input?.let { + mapOf( + "fieldType" to it.fieldType, + "lcid" to it.lcid, + "status" to it.status, + "lcidName" to it.getLcidName(context), + "fieldName" to it.getFieldName(context), + "value" to it.value, + "getValue" to generateDocumentReaderValue(it.value()), + "values" to it.values.toJson(::generateDocumentReaderValue), + "comparisonList" to it.comparisonList.toJson(::generateDocumentReaderComparison), + "validityList" to it.validityList.toJson(::generateDocumentReaderValidity), + "comparisonStatus" to it.comparisonStatus, + "validityStatus" to it.validityStatus + ).toJson() +} + +fun documentReaderTextResultFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderTextResult() + + result.status = it.optInt("status") + result.comparisonStatus = it.optInt("comparisonStatus") + result.validityStatus = it.optInt("validityStatus") + result.availableSourceList = it.optJSONArray("availableSourceList").toList(::documentReaderTextSourceFromJSON)!! + result.fields = it.optJSONArray("fields").toList(::documentReaderTextFieldFromJSON)!! + + result +} + +fun generateDocumentReaderTextResult(input: DocumentReaderTextResult?) = input?.let { + mapOf( + "status" to it.status, + "comparisonStatus" to it.comparisonStatus, + "validityStatus" to it.validityStatus, + "availableSourceList" to it.availableSourceList.toJson(::generateDocumentReaderTextSource), + "fields" to it.fields.toJson(::generateDocumentReaderTextField) + ).toJson() +} + +fun coordinateFromJSON(input: JSONObject?) = input?.let { + val result = Coordinate() + result.x = it.optInt("x") + result.y = it.optInt("y") + result +} + +fun generateCoordinate(input: Coordinate?) = input?.let { + mapOf( + "x" to it.x, + "y" to it.y + ).toJson() +} + +fun elementPositionFromJSON(input: JSONObject?) = input?.let { + val result = ElementPosition() + + result.docFormat = it.optInt("docFormat") + result.width = it.optInt("width") + result.height = it.optInt("height") + result.dpi = it.optInt("dpi") + result.pageIndex = it.optInt("pageIndex") + result.inverse = it.optInt("inverse") + result.perspectiveTr = it.optInt("perspectiveTr") + result.objArea = it.optInt("objArea") + result.objIntAngleDev = it.optInt("objIntAngleDev") + result.resultStatus = it.optInt("resultStatus") + result.angle = it.optDouble("angle") + result.center = coordinateFromJSON(it.optJSONObject("center")) + result.leftTop = coordinateFromJSON(it.optJSONObject("leftTop")) + result.leftBottom = coordinateFromJSON(it.optJSONObject("leftBottom")) + result.rightTop = coordinateFromJSON(it.optJSONObject("rightTop")) + result.rightBottom = coordinateFromJSON(it.optJSONObject("rightBottom")) + + result +} + +fun generateElementPosition(input: ElementPosition?) = input?.let { + mapOf( + "docFormat" to it.docFormat, + "width" to it.width, + "height" to it.height, + "dpi" to it.dpi, + "pageIndex" to it.pageIndex, + "inverse" to it.inverse, + "perspectiveTr" to it.perspectiveTr, + "objArea" to it.objArea, + "objIntAngleDev" to it.objIntAngleDev, + "resultStatus" to it.resultStatus, + "angle" to it.angle, + "center" to generateCoordinate(it.center), + "leftTop" to generateCoordinate(it.leftTop), + "leftBottom" to generateCoordinate(it.leftBottom), + "rightTop" to generateCoordinate(it.rightTop), + "rightBottom" to generateCoordinate(it.rightBottom) + ).toJson() +} + +fun imageQualityFromJSON(input: JSONObject?) = input?.let { + val result = ImageQuality() + + result.featureType = it.optInt("featureType") + result.result = it.optInt("result") + result.type = it.optInt("type") + result.boundRects = it.optJSONArray("boundRects").toList(::docReaderFieldRectFromJSON)!! + + result +} + +fun generateImageQuality(input: ImageQuality?) = input?.let { + mapOf( + "featureType" to it.featureType, + "result" to it.result, + "type" to it.type, + "boundRects" to it.boundRects.toJson(::generateDocReaderFieldRect) + ).toJson() +} + +fun imageQualityGroupFromJSON(input: JSONObject?) = input?.let { + val result = ImageQualityGroup() + + result.count = it.optInt("count") + result.result = it.optInt("result") + result.pageIndex = it.optInt("pageIndex") + result.imageQualityList = it.optJSONArray("imageQualityList").toList(::imageQualityFromJSON)!! + + result +} + +fun generateImageQualityGroup(input: ImageQualityGroup?) = input?.let { + mapOf( + "count" to it.count, + "result" to it.result, + "imageQualityList" to it.imageQualityList.toJson(::generateImageQuality), + "pageIndex" to it.pageIndex + ).toJson() +} + +fun cameraSizeFromJSON(input: JSONObject) = input.let { + val width = it.getInt("width") + val height = it.getInt("height") + Pair(width, height) +} + +fun generateCameraSize(width: Int?, height: Int?): JSONObject? { + width ?: return null + height ?: return null + return mapOf( + "width" to width, + "height" to height + ).toJson() +} + +fun documentReaderDocumentTypeFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderDocumentType() + + result.pageIndex = it.getInt("pageIndex") + result.documentID = it.getInt("documentID") + result.dType = it.getInt("dType") + result.dFormat = it.getInt("dFormat") + result.dMRZ = it.getBoolean("dMRZ") + result.isDeprecated = it.getBoolean("isDeprecated") + result.name = it.getStringOrNull("name") + result.ICAOCode = it.getStringOrNull("ICAOCode") + result.dDescription = it.getStringOrNull("dDescription") + result.dCountryName = it.getStringOrNull("dCountryName") + result.dYear = it.getStringOrNull("dYear") + result.FDSID = it.getJSONArrayOrNull("FDSID").toIntArray() + + result +} + +fun generateDocumentReaderDocumentType(input: DocumentReaderDocumentType?) = input?.let { + mapOf( + "pageIndex" to it.pageIndex, + "documentID" to it.documentID, + "dType" to it.dType, + "dFormat" to it.dFormat, + "dMRZ" to it.dMRZ, + "isDeprecated" to it.isDeprecated, + "name" to it.name, + "ICAOCode" to it.ICAOCode, + "dDescription" to it.dDescription, + "dYear" to it.dYear, + "dCountryName" to it.dCountryName, + "FDSID" to it.FDSID.toJson() + ).toJson() +} + +fun generateDocumentReaderNotification(input: DocumentReaderNotification?) = input?.let { + mapOf( + "notificationCode" to it.notificationCode, + "dataFileType" to it.dataFileType, + "progress" to it.progress + ).toJson() +} + +fun accessControlProcedureTypeFromJSON(input: JSONObject?) = input?.let { + val result = AccessControlProcedureType() + + result.activeOptionIdx = it.optInt("activeOptionIdx") + result.type = it.optInt("type") + result.status = it.optInt("status").toLong() + result.notifications = it.optJSONArray("notifications")!!.toList() + + result +} + +fun generateAccessControlProcedureType(input: AccessControlProcedureType?) = input?.let { + mapOf( + "activeOptionIdx" to it.activeOptionIdx, + "type" to it.type, + "status" to it.status, + "notifications" to it.notifications.toJson() + ).toJson() +} + +fun fileDataFromJSON(input: JSONObject?) = input?.let { + val result = FileData() + + result.length = it.optInt("length") + result.type = it.optInt("type") + result.status = it.optInt("status").toLong() + result.data = it.optString("data") + + result +} + +fun generateFileData(input: FileData?) = input?.let { + mapOf( + "length" to it.length, + "type" to it.type, + "status" to it.status, + "data" to it.data + ).toJson() +} + +fun certificateDataFromJSON(input: JSONObject?) = input?.let { + val result = CertificateData() + result.length = it.optInt("length") + result.data = it.optString("data") + result +} + +fun generateCertificateData(input: CertificateData?) = input?.let { + mapOf( + "length" to it.length, + "data" to it.data + ).toJson() +} + +fun securityObjectCertificatesFromJSON(input: JSONObject?) = input?.let { + val result = SecurityObjectCertificates() + result.securityObject = certificateDataFromJSON(it.optJSONObject("securityObject")) + result +} + +fun generateSecurityObjectCertificates(input: SecurityObjectCertificates?) = input?.let { + mapOf( + "securityObject" to generateCertificateData(it.securityObject) + ).toJson() +} + +fun fileFromJSON(input: JSONObject?) = input?.let { + val result = File() + + result.readingTime = it.optInt("readingTime") + result.type = it.optInt("type") + result.pAStatus = it.optLong("pAStatus") + result.readingStatus = it.optInt("readingStatus").toLong() + result.fileID = it.optString("fileID") + result.fileData = fileDataFromJSON(it.optJSONObject("fileData")) + result.certificates = securityObjectCertificatesFromJSON(it.optJSONObject("certificates")) + result.docFieldsText = it.optJSONArray("docFieldsText")!!.toList() + result.docFieldsGraphics = it.optJSONArray("docFieldsGraphics")!!.toList() + result.docFieldsOriginals = it.optJSONArray("docFieldsOriginals")!!.toList() + result.notifications = it.optJSONArray("notifications")!!.toList() + + result +} + +fun generateFile(input: File?) = input?.let { + mapOf( + "readingTime" to it.readingTime, + "type" to it.type, + "typeName" to eRFID_DataFile_Type.getTranslation(context, it.type), + "pAStatus" to it.pAStatus, + "readingStatus" to it.readingStatus, + "fileID" to it.fileID, + "fileData" to generateFileData(it.fileData), + "certificates" to generateSecurityObjectCertificates(it.certificates), + "docFieldsText" to it.docFieldsText.toJson(), + "docFieldsGraphics" to it.docFieldsGraphics.toJson(), + "docFieldsOriginals" to it.docFieldsOriginals.toJson(), + "notifications" to it.notifications.toJson() + ).toJson() +} + +fun applicationFromJSON(input: JSONObject?) = input?.let { + val result = Application() + + result.type = it.optInt("type") + result.status = it.optInt("status") + result.applicationID = it.optString("applicationID") + result.dataHashAlgorithm = it.optString("dataHashAlgorithm") + result.unicodeVersion = it.optString("unicodeVersion") + result.version = it.optString("version") + result.files = it.optJSONArray("files").toList(::fileFromJSON)!! + + result +} + +fun generateApplication(input: Application?) = input?.let { + mapOf( + "type" to it.type, + "status" to it.status, + "applicationID" to it.applicationID, + "dataHashAlgorithm" to it.dataHashAlgorithm, + "unicodeVersion" to it.unicodeVersion, + "version" to it.version, + "files" to it.files.toJson(::generateFile) + ).toJson() +} + +fun valueFromJSON(input: JSONObject?) = input?.let { + val result = Value() + + result.length = it.optInt("length") + result.type = it.optInt("type") + result.status = it.optInt("status").toLong() + result.data = it.optString("data") + result.format = it.optString("format") + + result +} + +fun generateValue(input: Value?) = input?.let { + mapOf( + "length" to it.length, + "type" to it.type, + "status" to it.status, + "data" to it.data, + "format" to it.format + ).toJson() +} + +fun attributeFromJSON(input: JSONObject?) = input?.let { + val result = Attribute() + result.type = it.optString("type") + result.value = valueFromJSON(it.optJSONObject("value")) + result +} + +fun generateAttribute(input: Attribute?) = input?.let { + mapOf( + "type" to it.type, + "value" to generateValue(it.value) + ).toJson() +} + +fun authorityFromJSON(input: JSONObject?) = input?.let { + val result = Authority() + result.data = it.optString("data") + result.friendlyName = valueFromJSON(it.optJSONObject("friendlyName")) + result.attributes = it.optJSONArray("attributes").toList(::attributeFromJSON)!! + result +} + +fun generateAuthority(input: Authority?) = input?.let { + mapOf( + "data" to it.data, + "friendlyName" to generateValue(it.friendlyName), + "attributes" to it.attributes.toJson(::generateAttribute) + ).toJson() +} + +fun extensionFromJSON(input: JSONObject?) = input?.let { + val result = Extension() + result.data = it.optString("data") + result.type = it.optString("type") + result +} + +fun generateExtension(input: Extension?) = input?.let { + mapOf( + "data" to it.data, + "type" to it.type + ).toJson() +} + +fun validityFromJSON(input: JSONObject?) = input?.let { + val result = Validity() + result.notAfter = valueFromJSON(it.optJSONObject("notAfter")) + result.notBefore = valueFromJSON(it.optJSONObject("notBefore")) + result +} + +fun generateValidity(input: Validity?) = input?.let { + mapOf( + "notAfter" to generateValue(it.notAfter), + "notBefore" to generateValue(it.notBefore) + ).toJson() +} + +fun certificateChainFromJSON(input: JSONObject?) = input?.let { + val result = CertificateChain() + + result.origin = it.optInt("origin") + result.type = it.optInt("type") + result.version = it.optInt("version") + result.paStatus = it.optInt("paStatus").toLong() + result.serialNumber = it.optString("serialNumber") + result.signatureAlgorithm = it.optString("signatureAlgorithm") + result.subjectPKAlgorithm = it.optString("subjectPKAlgorithm") + result.fileName = valueFromJSON(it.optJSONObject("fileName")) + result.validity = validityFromJSON(it.optJSONObject("validity")) + result.issuer = authorityFromJSON(it.optJSONObject("issuer")) + result.subject = authorityFromJSON(it.optJSONObject("subject")) + result.notifications = it.optJSONArray("notifications")!!.toList() + result.extensions = it.optJSONArray("extensions").toList(::extensionFromJSON)!! + + result +} + +fun generateCertificateChain(input: CertificateChain?) = input?.let { + mapOf( + "origin" to it.origin, + "type" to it.type, + "version" to it.version, + "paStatus" to it.paStatus, + "serialNumber" to it.serialNumber, + "signatureAlgorithm" to it.signatureAlgorithm, + "subjectPKAlgorithm" to it.subjectPKAlgorithm, + "fileName" to generateValue(it.fileName), + "validity" to generateValidity(it.validity), + "issuer" to generateAuthority(it.issuer), + "subject" to generateAuthority(it.subject), + "notifications" to it.notifications.toJson(), + "extensions" to it.extensions.toJson(::generateExtension) + ).toJson() +} + +fun signerInfoFromJSON(input: JSONObject?) = input?.let { + val result = SignerInfo() + + result.version = it.optInt("version") + result.paStatus = it.optInt("paStatus").toLong() + result.dataToHash = it.optString("dataToHash") + result.digestAlgorithm = it.optString("digestAlgorithm") + result.signatureAlgorithm = it.optString("signatureAlgorithm") + result.serialNumber = valueFromJSON(it.optJSONObject("serialNumber")) + result.signature = valueFromJSON(it.optJSONObject("signature")) + result.subjectKeyIdentifier = valueFromJSON(it.optJSONObject("subjectKeyIdentifier")) + result.issuer = authorityFromJSON(it.optJSONObject("issuer")) + result.notifications = it.optJSONArray("notifications")!!.toList() + result.signedAttributes = it.optJSONArray("signedAttributes").toList(::extensionFromJSON)!! + result.certificateChain = it.optJSONArray("certificateChain").toList(::certificateChainFromJSON)!! + + result +} + +fun generateSignerInfo(input: SignerInfo?) = input?.let { + mapOf( + "version" to it.version, + "paStatus" to it.paStatus, + "dataToHash" to it.dataToHash, + "digestAlgorithm" to it.digestAlgorithm, + "signatureAlgorithm" to it.signatureAlgorithm, + "serialNumber" to generateValue(it.serialNumber), + "signature" to generateValue(it.signature), + "subjectKeyIdentifier" to generateValue(it.subjectKeyIdentifier), + "issuer" to generateAuthority(it.issuer), + "notifications" to it.notifications.toJson(), + "signedAttributes" to it.signedAttributes.toJson(::generateExtension), + "certificateChain" to it.certificateChain.toJson(::generateCertificateChain) + ).toJson() +} + +fun securityObjectFromJSON(input: JSONObject?) = input?.let { + val result = SecurityObject() + + result.fileReference = it.optInt("fileReference") + result.version = it.optInt("version") + result.objectType = it.optString("objectType") + result.notifications = it.optJSONArray("notifications")!!.toList() + result.signerInfos = it.optJSONArray("signerInfos").toList(::signerInfoFromJSON)!! + + result +} + +fun generateSecurityObject(input: SecurityObject?) = input?.let { + mapOf( + "fileReference" to it.fileReference, + "version" to it.version, + "objectType" to it.objectType, + "notifications" to it.notifications.toJson(), + "signerInfos" to it.signerInfos.toJson(::generateSignerInfo) + ).toJson() +} + +fun cardPropertiesFromJSON(input: JSONObject?) = input?.let { + val result = CardProperties() + + result.aTQA = it.optInt("aTQA") + result.bitRateR = it.optInt("bitRateR") + result.bitRateS = it.optInt("bitRateS") + result.chipTypeA = it.optInt("chipTypeA") + result.mifareMemory = it.optInt("mifareMemory") + result.rfidType = it.optInt("rfidType") + result.sAK = it.optInt("sAK") + result.support4 = it.optBoolean("support4") + result.supportMifare = it.optBoolean("supportMifare") + result.aTQB = it.optString("aTQB") + result.aTR = it.optString("aTR") + result.baudrate1 = it.optString("baudrate1") + result.baudrate2 = it.optString("baudrate2") + result.uID = it.optString("uID") + + result +} + +fun generateCardProperties(input: CardProperties?) = input?.let { + mapOf( + "aTQA" to it.aTQA, + "bitRateR" to it.bitRateR, + "bitRateS" to it.bitRateS, + "chipTypeA" to it.chipTypeA, + "mifareMemory" to it.mifareMemory, + "rfidType" to it.rfidType, + "sAK" to it.sAK, + "support4" to it.support4, + "supportMifare" to it.supportMifare, + "aTQB" to it.aTQB, + "aTR" to it.aTR, + "baudrate1" to it.baudrate1, + "baudrate2" to it.baudrate2, + "uID" to it.uID + ).toJson() +} + +fun rfidSessionDataFromJSON(input: JSONObject?) = input?.let { + val result = RFIDSessionData() + + result.totalBytesReceived = it.optInt("totalBytesReceived") + result.totalBytesSent = it.optInt("totalBytesSent") + result.status = it.optInt("status").toLong() + result.extLeSupport = it.optLong("extLeSupport") + result.processTime = it.optLong("processTime") + result.cardProperties = cardPropertiesFromJSON(it.optJSONObject("cardProperties")) + result.accessControls = it.optJSONArray("accessControls").toList(::accessControlProcedureTypeFromJSON)!! + result.applications = it.optJSONArray("applications").toList(::applicationFromJSON)!! + result.securityObjects = it.optJSONArray("securityObjects").toList(::securityObjectFromJSON)!! + result.dataFields = it.optJSONArray("dataFields").toList(::dataFieldFromJSON)!! + result.dataGroups = it.optJSONArray("dataGroups").toIntArray() + + result +} + +fun generateRFIDSessionData(input: RFIDSessionData?) = input?.let { + mapOf( + "totalBytesReceived" to it.totalBytesReceived, + "totalBytesSent" to it.totalBytesSent, + "status" to it.status, + "extLeSupport" to it.extLeSupport, + "processTime" to it.processTime, + "cardProperties" to generateCardProperties(it.cardProperties), + "accessControls" to it.accessControls.toJson(::generateAccessControlProcedureType), + "applications" to it.applications.toJson(::generateApplication), + "securityObjects" to it.securityObjects.toJson(::generateSecurityObject), + "dataGroups" to it.dataGroups.toJson(), + "dataFields" to it.dataFields.toJson(::generateDataField) + ).toJson() +} + +fun dataFieldFromJSON(input: JSONObject?) = input?.let { + val result = DataField() + result.data = it.optString("data") + result.fieldType = it.optInt("fieldType") + result +} + +fun generateDataField(input: DataField?) = input?.let { + mapOf( + "data" to it.data, + "fieldType" to it.fieldType + ).toJson() +} + +fun documentReaderAuthenticityCheckFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderAuthenticityCheck() + result.type = it.optInt("type") + result.pageIndex = it.optInt("pageIndex") + result.elements = it.optJSONArray("elements").toList(::documentReaderAuthenticityElementFromJSON)!! + result +} + +fun generateDocumentReaderAuthenticityCheck(input: DocumentReaderAuthenticityCheck?) = input?.let { + mapOf( + "type" to it.type, + "status" to it.status, + "typeName" to it.getTypeName(context), + "pageIndex" to it.pageIndex, + "elements" to it.elements.toJson(::generateDocumentReaderAuthenticityElement) + ).toJson() +} + +fun pdf417InfoFromJSON(input: JSONObject?) = input?.let { + val result = PDF417Info() + result.errorLevel = it.optInt("errorLevel") + result.columns = it.optInt("columns") + result.rows = it.optInt("rows") + result +} + +fun generatePDF417Info(input: PDF417Info?) = input?.let { + mapOf( + "errorLevel" to it.errorLevel, + "columns" to it.columns, + "rows" to it.rows + ).toJson() +} + +fun documentReaderBarcodeResultFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderBarcodeResult() + result.fields = it.optJSONArray("fields").toList(::documentReaderBarcodeFieldFromJSON)!! + result +} + +fun generateDocumentReaderBarcodeResult(input: DocumentReaderBarcodeResult?) = input?.let { + mapOf( + "fields" to it.fields.toJson(::generateDocumentReaderBarcodeField) + ).toJson() +} + +fun documentReaderBarcodeFieldFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderBarcodeField() + + result.barcodeType = it.optInt("barcodeType") + result.status = it.optInt("status") + result.pageIndex = it.optInt("pageIndex") + result.pdf417Info = pdf417InfoFromJSON(it.optJSONObject("pdf417Info")) + result.data = it.optString("data").toByteArray() + + result +} + +fun generateDocumentReaderBarcodeField(input: DocumentReaderBarcodeField?) = input?.let { + mapOf( + "barcodeType" to it.barcodeType, + "status" to it.status, + "pageIndex" to it.pageIndex, + "pdf417Info" to generatePDF417Info(it.pdf417Info), + "data" to it.data.toBase64() + ).toJson() +} + +fun documentReaderAuthenticityResultFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderAuthenticityResult() + result.checks = it.optJSONArray("checks").toList(::documentReaderAuthenticityCheckFromJSON)!! + result +} + +@Suppress("DEPRECATION") +fun generateDocumentReaderAuthenticityResult(input: DocumentReaderAuthenticityResult?) = input?.let { + mapOf( + "status" to it.status, + "checks" to it.checks.toJson(::generateDocumentReaderAuthenticityCheck) + ).toJson() +} + +fun documentReaderAuthenticityElementFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderAuthenticityElement() + result.status = it.optInt("status") + result.elementType = it.optInt("elementType") + result.elementDiagnose = it.optInt("elementDiagnose") + result +} + +fun generateDocumentReaderAuthenticityElement(input: DocumentReaderAuthenticityElement?) = input?.let { + mapOf( + "status" to it.status, + "elementType" to it.elementType, + "elementDiagnose" to it.elementDiagnose, + "elementTypeName" to it.getElementTypeName(context), + "elementDiagnoseName" to it.getElementDiagnoseName(context) + ).toJson() +} + +fun paResourcesIssuerFromJSON(input: JSONObject?) = input?.let { + val result = PAResourcesIssuer() + result.data = it.optString("data").toByteArray() + result.friendlyName = it.getStringOrNull("friendlyName") + result.attributes = it.optJSONArray("attributes").toArray(::paAttributeFromJSON) + result +} + +fun generatePAResourcesIssuer(input: PAResourcesIssuer?) = input?.let { + mapOf( + "data" to it.data.toBase64(), + "friendlyName" to it.friendlyName, + "attributes" to it.attributes.toJson(::generatePAAttribute) + ).toJson() +} + +fun paAttributeFromJSON(input: JSONObject?) = input?.let { + val result = PAAttribute() + result.type = it.optString("type") + result.value = it.optString("value") + result +} + +fun generatePAAttribute(input: PAAttribute?) = input?.let { + mapOf( + "type" to it.type, + "value" to it.value + ).toJson() +} + +fun taChallengeFromJSON(input: JSONObject?) = input?.let { + val result = TAChallenge() + + result.data = it.optString("data").toByteArray() + result.auxPCD = it.optString("auxPCD") + result.challengePICC = it.optString("challengePICC") + result.hashPK = it.optString("hashPK") + result.idPICC = it.optString("idPICC") + + result +} + +fun generateTAChallenge(input: TAChallenge?) = input?.let { + mapOf( + "data" to it.data.toBase64(), + "auxPCD" to it.auxPCD, + "challengePICC" to it.challengePICC, + "hashPK" to it.hashPK, + "idPICC" to it.idPICC + ).toJson() +} + +fun documentReaderResultsStatusFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderResultsStatus::class.constructor().instantiate() + result.setPrivateProperty("overallStatus", it.getInt("overallStatus")) + result.setPrivateProperty("optical", it.getInt("optical")) + result.setPrivateProperty("detailsOptical", detailsOpticalFromJSON(it.getJSONObject("detailsOptical"))) + result.setPrivateProperty("rfid", it.getInt("rfid")) + result.setPrivateProperty("detailsRFID", detailsRFIDFromJSON(it.getJSONObject("detailsRFID"))) + result.setPrivateProperty("portrait", it.getInt("portrait")) + result.setPrivateProperty("stopList", it.getInt("stopList")) + result.setPrivateProperty("mDL", it.getInt("mDL")) + result.setPrivateProperty("age", it.getInt("age")) + result.setPrivateProperty("captureProcessIntegrity", it.getInt("captureProcessIntegrity")) + result.setPrivateProperty("detailsAge", detailsAgeFromJSON(it.getJSONObject("detailsAge"))) + result +} + +fun generateDocumentReaderResultsStatus(input: DocumentReaderResultsStatus?) = input?.let { + mapOf( + "overallStatus" to it.overallStatus, + "optical" to it.optical, + "detailsOptical" to generateDetailsOptical(it.detailsOptical), + "rfid" to it.rfid, + "detailsRFID" to generateDetailsRFID(it.detailsRFID), + "portrait" to it.portrait, + "stopList" to it.stopList, + "mDL" to it.mdl, + "age" to it.age, + "captureProcessIntegrity" to it.captureProcessIntegrity, + "detailsAge" to generateDetailsAge(it.detailsAge), + ).toJson() +} + +fun detailsOpticalFromJSON(input: JSONObject?) = input?.let { + val result = DetailsOptical::class.constructor().instantiate() + result.setPrivateProperty("overallStatus", it.getInt("overallStatus")) + result.setPrivateProperty("mrz", it.getInt("mrz")) + result.setPrivateProperty("text", it.getInt("text")) + result.setPrivateProperty("docType", it.getInt("docType")) + result.setPrivateProperty("security", it.getInt("security")) + result.setPrivateProperty("imageQA", it.getInt("imageQA")) + result.setPrivateProperty("expiry", it.getInt("expiry")) + result.setPrivateProperty("vds", it.getInt("vds")) + result.setPrivateProperty("pagesCount", it.getInt("pagesCount")) + result +} + +fun generateDetailsOptical(input: DetailsOptical?) = input?.let { + mapOf( + "overallStatus" to it.overallStatus, + "mrz" to it.mrz, + "text" to it.text, + "docType" to it.docType, + "security" to it.security, + "imageQA" to it.imageQA, + "expiry" to it.expiry, + "vds" to it.vds, + "pagesCount" to it.pagesCount + ).toJson() +} + +fun detailsRFIDFromJSON(input: JSONObject?) = input?.let { + val result = DetailsRFID::class.constructor().instantiate() + result.setPrivateProperty("overallStatus", it.getInt("overallStatus")) + result.setPrivateProperty("pa", it.getInt("pa")) + result.setPrivateProperty("ca", it.getInt("ca")) + result.setPrivateProperty("aa", it.getInt("aa")) + result.setPrivateProperty("ta", it.getInt("ta")) + result.setPrivateProperty("bac", it.getInt("bac")) + result.setPrivateProperty("pace", it.getInt("pace")) + result +} + +fun generateDetailsRFID(input: DetailsRFID?) = input?.let { + mapOf( + "pa" to it.pa, + "ca" to it.ca, + "aa" to it.aa, + "ta" to it.ta, + "bac" to it.bac, + "pace" to it.pace, + "overallStatus" to it.overallStatus + ).toJson() +} + +fun detailsAgeFromJSON(input: JSONObject?) = input?.let { + val result = DetailsAge::class.constructor().instantiate() + result.setPrivateProperty("threshold", it.getInt("threshold")) + result.setPrivateProperty("overThreshold", it.getInt("overThreshold")) + result.setPrivateProperty("over18", it.getInt("over18")) + result.setPrivateProperty("over21", it.getInt("over21")) + result.setPrivateProperty("over25", it.getInt("over25")) + result.setPrivateProperty("over65", it.getInt("over65")) + result +} + +fun generateDetailsAge(input: DetailsAge?) = input?.let { + mapOf( + "threshold" to it.threshold, + "overThreshold" to it.overThreshold, + "over18" to it.over18, + "over21" to it.over21, + "over25" to it.over25, + "over65" to it.over65 + ).toJson() +} + +fun vdsncDataFromJSON(input: JSONObject?) = input?.let { + val result = VDSNCData::class.constructor().instantiate() + result.setPrivateProperty("type", it.getStringOrNull("type")) + result.setPrivateProperty("version", it.getInt("version")) + result.setPrivateProperty("issuingCountry", it.getStringOrNull("issuingCountry")) + result.setPrivateProperty("message", it.getJSONObjectOrNull("message")) + result.setPrivateProperty("signatureAlg", it.getStringOrNull("signatureAlgorithm")) + result.setPrivateProperty("signature", bytesDataFromJSON(it.getJSONObjectOrNull("signature"))) + result.setPrivateProperty("certificate", bytesDataFromJSON(it.getJSONObjectOrNull("certificate"))) + result.setPrivateProperty("certificateChain", it.getJSONArray("certificateChain").toList(::certificateChainFromJSON)) + result.setPrivateProperty("notifications", it.getJSONArray("notifications").toLongArray()) + result +} + +fun generateVDSNCData(input: VDSNCData?) = input?.let { + mapOf( + "type" to it.type, + "version" to it.version, + "issuingCountry" to it.issuingCountry, + "message" to it.message, + "signatureAlgorithm" to it.signatureAlg, + "signature" to generateBytesData(it.signature), + "certificate" to generateBytesData(it.certificate), + "certificateChain" to it.certificateChain.toJson(::generateCertificateChain), + "notifications" to it.notifications.toJson() + ).toJson() +} + +fun bytesDataFromJSON(input: JSONObject?) = input?.let { + val result = BytesData::class.constructor().instantiate() + result.setPrivateProperty("data", it.getString("data")) + result.setPrivateProperty("length", it.getInt("length")) + result.setPrivateProperty("status", it.getLong("status")) + result.setPrivateProperty("type", it.getInt("type")) + result +} + +fun generateBytesData(input: BytesData?) = input?.let { + mapOf( + "data" to it.data, + "length" to it.length, + "status" to it.status, + "type" to it.type + ).toJson() +} + +fun generateLicense(input: License?) = input?.let { + mapOf( + "expiryDate" to it.expiryDate?.toString(), + "countryFilter" to it.countryFilter?.toJson(), + "isRfidAvailable" to it.isRfidAvailable + ).toJson() +} + +fun generateDocReaderVersion(input: DocReaderVersion?) = input?.let { + mapOf( + "api" to it.api, + "core" to it.core, + "coreMode" to it.coreMode, + "database" to generateDocReaderDocumentsDatabase(it.database) + ).toJson() +} + +fun docReaderDocumentsDatabaseFromJSON(input: JSONObject?) = input?.let { + DocReaderDocumentsDatabase::class.constructor(String::class, String::class, String::class, String::class, Int::class, Int::class, java.lang.Long::class).instantiate( + it.getStringOrNull("databaseID"), + it.getStringOrNull("version"), + it.getStringOrNull("date"), + it.getStringOrNull("databaseDescription"), + it.getInt("countriesNumber"), + it.getInt("documentsNumber"), + it.getLongOrNull("size"), + ) +} + +fun generateDocReaderDocumentsDatabase(input: DocReaderDocumentsDatabase?) = input?.let { + mapOf( + "databaseID" to it.databaseID, + "version" to it.version, + "date" to it.date, + "databaseDescription" to it.databaseDescription, + "countriesNumber" to it.countriesNumber, + "documentsNumber" to it.documentsNumber, + "size" to it.size + ).toJson() +} + +fun documentReaderComparisonFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderComparison() + result.sourceTypeLeft = it.optInt("sourceTypeLeft") + result.sourceTypeRight = it.optInt("sourceTypeRight") + result.status = it.optInt("status") + result +} + +fun generateDocumentReaderComparison(input: DocumentReaderComparison?) = input?.let { + mapOf( + "sourceTypeLeft" to it.sourceTypeLeft, + "sourceTypeRight" to it.sourceTypeRight, + "status" to it.status + ).toJson() +} + +fun documentReaderRFIDOriginFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderRfidOrigin() + + result.dg = it.optInt("dg") + result.dgTag = it.optInt("dgTag") + result.entryView = it.optInt("entryView") + result.tagEntry = it.optInt("tagEntry") + + result +} + +fun generateDocumentReaderRFIDOrigin(input: DocumentReaderRfidOrigin?) = input?.let { + mapOf( + "dg" to it.dg, + "dgTag" to it.dgTag, + "entryView" to it.entryView, + "tagEntry" to it.tagEntry + ).toJson() +} + +fun documentReaderTextSourceFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderTextSource() + result.sourceType = it.getInt("sourceType") + result.source = it.getStringOrNull("source") + result.validityStatus = it.getInt("validityStatus") + result +} + +fun generateDocumentReaderTextSource(input: DocumentReaderTextSource?) = input?.let { + mapOf( + "sourceType" to it.sourceType, + "source" to it.source, + "validityStatus" to it.validityStatus + ).toJson() +} + +fun documentReaderSymbolFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderSymbol() + result.code = it.optInt("code") + result.probability = it.optInt("probability") + result.rect = rectFromJSON(it.optJSONObject("rect")) + result +} + +fun generateDocumentReaderSymbol(input: DocumentReaderSymbol?) = input?.let { + mapOf( + "code" to it.code, + "rect" to generateRect(it.rect), + "probability" to it.probability + ).toJson() +} + +fun documentReaderValidityFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderValidity() + result.sourceType = it.optInt("sourceType") + result.status = it.optInt("status") + result +} + +fun generateDocumentReaderValidity(input: DocumentReaderValidity?) = input?.let { + mapOf( + "sourceType" to it.sourceType, + "status" to it.status + ).toJson() +} + +fun barcodeTypeArrayFromJson(input: JSONArray?) = input?.let { + val result = arrayOfNulls(it.length()) + for (i in 0 until it.length()) result[i] = BarcodeType.valueOf(it.getInt(i)) + result +} + +fun generateBarcodeTypeArray(input: Array?) = input?.let { + val result = JSONArray() + for (s in it) result.put( + when (s) { + "bct_Code128" -> 1 + "bct_Code39" -> 2 + "bct_EAN8" -> 3 + "bct_ITF" -> 4 + "bct_PDF417" -> 5 + "bct_STF" -> 6 + "bct_MTF" -> 7 + "bct_IATA" -> 8 + "bct_CODABAR" -> 9 + "bct_UPCA" -> 10 + "bct_CODE93" -> 11 + "bct_UPCE" -> 12 + "bct_EAN13" -> 13 + "bct_QRCODE" -> 14 + "bct_AZTEC" -> 15 + "bct_DATAMATRIX" -> 16 + "bct_ALL_1D" -> 17 + "bct_Code11" -> 18 + "bct_JABCODE" -> 19 + else -> 0 + } + ) + result +} + +fun docFeatureFromJSON(input: JSONObject?) = input?.let { + val result = DocFeature::class.constructor().instantiate() + result.setPrivateProperty("type", it.getIntOrNull("type")) + result.setPrivateProperty("data", bytesDataFromJSON(it.getJSONObjectOrNull("data"))) + result +} + +fun generateDocFeature(input: DocFeature?) = input?.let { + mapOf( + "type" to it.type, + "data" to generateBytesData(it.data), + ).toJson() +} + +fun vdsDataFromJSON(input: JSONObject?) = input?.let { + val result = VDSData::class.constructor().instantiate() + result.setPrivateProperty("version", it.getIntOrNull("version")) + result.setPrivateProperty("type", it.getIntOrNull("type")) + result.setPrivateProperty("docType", it.getIntOrNull("docType")) + result.setPrivateProperty("featureRef", it.getIntOrNull("featureRef")) + result.setPrivateProperty("issuingCountry", it.getStringOrNull("issuingCountry")) + result.setPrivateProperty("docIssueDate", it.getStringOrNull("docIssueDate")) + result.setPrivateProperty("signature", bytesDataFromJSON(it.getJSONObjectOrNull("signature"))) + result.setPrivateProperty("signatureDate", it.getStringOrNull("signatureDate")) + result.setPrivateProperty("signer", it.getStringOrNull("signer")) + result.setPrivateProperty("certificate", it.getStringOrNull("certificate")) + result.setPrivateProperty("certificateChain", it.getJSONArray("certificateChain").toList(::certificateChainFromJSON)) + result.setPrivateProperty("docFeatures", it.getJSONArray("docFeatures").toList(::docFeatureFromJSON)) + result.setPrivateProperty("notifications", it.getJSONArray("notifications").toLongArray()) + result +} + +fun generateVDSData(input: VDSData?) = input?.let { + mapOf( + "version" to it.version, + "type" to it.type, + "docType" to it.docType, + "featureRef" to it.featureRef, + "issuingCountry" to it.issuingCountry, + "docIssueDate" to it.docIssueDate, + "signature" to generateBytesData(it.signature), + "signatureDate" to it.signatureDate, + "signer" to it.signer, + "certificate" to it.certificate, + "certificateChain" to it.certificateChain.toJson(::generateCertificateChain), + "docFeatures" to it.docFeatures.toJson(::generateDocFeature), + "notifications" to it.notifications.toJson(), + ).toJson() +} + +fun documentReaderResultsFromJSON(input: JSONObject?) = input?.let { + val result = DocumentReaderResults() + + result.chipPage = it.optInt("chipPage") + result.processingFinishedStatus = it.optInt("processingFinishedStatus") + result.elapsedTime = it.optInt("elapsedTime") + result.elapsedTimeRFID = it.optInt("elapsedTimeRFID") + result.morePagesAvailable = it.optInt("morePagesAvailable") + result.graphicResult = documentReaderGraphicResultFromJSON(it.optJSONObject("graphicResult")) + result.textResult = documentReaderTextResultFromJSON(it.optJSONObject("textResult")) + result.documentPosition = it.optJSONArray("documentPosition").toList(::elementPositionFromJSON)!! + result.barcodePosition = it.optJSONArray("barcodePosition").toList(::elementPositionFromJSON)!! + result.mrzPosition = it.optJSONArray("mrzPosition").toList(::elementPositionFromJSON)!! + result.imageQuality = it.optJSONArray("imageQuality").toList(::imageQualityGroupFromJSON)!! + result.rawResult = it.optString("rawResult") + result.bsiTr03135Results = it.getStringOrNull("bsiTr03135Results") + result.rfidSessionData = rfidSessionDataFromJSON(it.optJSONObject("rfidSessionData")) + result.authenticityResult = documentReaderAuthenticityResultFromJSON(it.optJSONObject("authenticityResult")) + result.barcodeResult = documentReaderBarcodeResultFromJSON(it.optJSONObject("barcodeResult")) + result.rfidSessionData = rfidSessionDataFromJSON(it.optJSONObject("rfidSessionData")) + result.documentType = it.optJSONArray("documentType").toList(::documentReaderDocumentTypeFromJSON)!! + result.status = documentReaderResultsStatusFromJSON(it.optJSONObject("status"))!! + result.vdsncData = vdsncDataFromJSON(it.getJSONObject("vdsncData")) + result.vdsData = vdsDataFromJSON(it.getJSONObjectOrNull("vdsData")) + result.dtcData = it.getString("dtcData") + result.transactionInfo = transactionInfoFromJSON(it.optJSONObject("transactionInfo"))!! + result +} + +fun generateDocumentReaderResults(input: DocumentReaderResults?) = input?.let { + mapOf( + "chipPage" to it.chipPage, + "processingFinishedStatus" to it.processingFinishedStatus, + "elapsedTime" to it.elapsedTime, + "elapsedTimeRFID" to it.elapsedTimeRFID, + "morePagesAvailable" to it.morePagesAvailable, + "graphicResult" to generateDocumentReaderGraphicResult(it.graphicResult), + "textResult" to generateDocumentReaderTextResult(it.textResult), + "documentPosition" to it.documentPosition.toJson(::generateElementPosition), + "barcodePosition" to it.barcodePosition.toJson(::generateElementPosition), + "mrzPosition" to it.mrzPosition.toJson(::generateElementPosition), + "imageQuality" to it.imageQuality.toJson(::generateImageQualityGroup), + "rawResult" to it.rawResult, + "bsiTr03135Results" to it.bsiTr03135Results, + "rfidSessionData" to generateRFIDSessionData(it.rfidSessionData), + "authenticityResult" to generateDocumentReaderAuthenticityResult(it.authenticityResult), + "barcodeResult" to generateDocumentReaderBarcodeResult(it.barcodeResult), + "documentType" to it.documentType.toJson(::generateDocumentReaderDocumentType), + "status" to generateDocumentReaderResultsStatus(it.status), + "vdsncData" to generateVDSNCData(it.vdsncData), + "vdsData" to generateVDSData(it.vdsData), + "dtcData" to it.dtcData, + "transactionInfo" to generateTransactionInfo(it.transactionInfo) + ).toJson() +} + +fun matrixFromJSON(input: JSONArray?) = input?.let { + val matrix = Matrix() + val result = FloatArray(it.length()) + for (i in 0 until it.length()) result[i] = it.getDouble(i).toFloat() + matrix.setValues(result) + matrix +} + +fun generateMatrix(input: Matrix?) = input?.let { + val floats = FloatArray(9) + it.getValues(floats) + val result = JSONArray() + for (f in floats) result.put(java.lang.Float.valueOf(f)) + result +} + +fun deviceRetrievalMethodFromJSON(input: JSONObject?) = input?.let { + val result = DeviceRetrievalMethod::class.constructor().instantiate() + result.setPrivateProperty("type", it.getInt("type")) + result.setPrivateProperty("version", it.getIntOrNull("version")) + result.setPrivateProperty("cmdMaxLength", it.getIntOrNull("cmdMaxLength")) + result.setPrivateProperty("respMaxLength", it.getIntOrNull("respMaxLength")) + result.setPrivateProperty("clientModeSupport", it.getBooleanOrNull("clientModeSupport")) + result.setPrivateProperty("clientModeUUID", it.getStringOrNull("clientModeUUID")) + result.setPrivateProperty("serverModeSupport", it.getBooleanOrNull("serverModeSupport")) + result.setPrivateProperty("serverModeUUID", it.getStringOrNull("serverModeUUID")) + result +} + +fun generateDeviceRetrievalMethod(input: DeviceRetrievalMethod?) = input?.let { + mapOf( + "type" to it.type, + "version" to it.version, + "cmdMaxLength" to it.cmdMaxLength, + "respMaxLength" to it.respMaxLength, + "clientModeSupport" to it.clientModeSupport, + "clientModeUUID" to it.clientModeUUID, + "serverModeSupport" to it.serverModeSupport, + "serverModeUUID" to it.serverModeUUID, + ).toJson() +} + +fun deviceEngagementFromJSON(input: JSONObject?) = input?.let { + val result = DeviceEngagement::class.constructor().instantiate() + + result.setPrivateProperty("deviceRetrievalMethods", it.getJSONArray("deviceRetrievalMethods").toList(::deviceRetrievalMethodFromJSON)) + + result +} + +fun generateDeviceEngagement(input: DeviceEngagement?) = input?.let { + mapOf( + "deviceRetrievalMethods" to it.deviceRetrievalMethods.toJson(::generateDeviceRetrievalMethod) + ).toJson() +} + +fun nameSpaceMDLFromJSON(input: JSONObject?) = input?.let { + val result = NameSpaceMDL(it.getString("name")) + it.getJSONObject("map").forEach { key, value -> + result.addField(key, eMDLIntentToRetain.values()[value.toInt()]) + } + result +} + +fun generateNameSpaceMDL(input: NameSpaceMDL?) = input?.let { + val map = JSONObject() + (it.getPrivateProperty("map") as Map).forEach { (key, value) -> + map.put(key, value.ordinal) + } + mapOf( + "name" to it.getPrivateProperty("name"), + "map" to map, + ).toJson() +} + +fun documentRequestMDLFromJSON(input: JSONObject?): DocumentRequestMDL? = input?.let { + val docType = it.getString("docType") + if (docType == "org.iso.18013.5.1.mDL") return@let documentRequest18013MDLFromJSON(it) + val result = DocumentRequestMDL(docType) + + result.setPrivateProperty("nameSpaceMDLs", it.getJSONArray("namespaces").toList(::nameSpaceMDLFromJSON)) + + result +} + +fun generateDocumentRequestMDL(input: DocumentRequestMDL?): JSONObject? = input?.let { + val docType = it.getPrivateProperty("docType") as String + if (docType == "org.iso.18013.5.1.mDL") return@let generateDocumentRequest18013MDL(it as DocumentRequest18013MDL?) + mapOf( + "docType" to docType, + "namespaces" to (it.getPrivateProperty("nameSpaceMDLs") as List).toJson(::generateNameSpaceMDL), + ).toJson() +} + +fun documentRequest18013MDLFromJSON(input: JSONObject?) = input?.let { + val result = DocumentRequest18013MDL() + + if (it.has("docType")) result.setPrivateProperty("docType", it.getString("docType")) + if (it.has("namespaces")) result.setPrivateProperty("nameSpaceMDLs", it.getJSONArray("namespaces").toList(::nameSpaceMDLFromJSON)) + result.familyName = it.getIntOrNull("familyName")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.givenName = it.getIntOrNull("givenName")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.birthDate = it.getIntOrNull("birthDate")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.issueDate = it.getIntOrNull("issueDate")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.expiryDate = it.getIntOrNull("expiryDate")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.issuingCountry = it.getIntOrNull("issuingCountry")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.issuingAuthority = it.getIntOrNull("issuingAuthority")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.documentNumber = it.getIntOrNull("documentNumber")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.portrait = it.getIntOrNull("portrait")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.drivingPrivileges = it.getIntOrNull("drivingPrivileges")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.unDistinguishingSign = it.getIntOrNull("unDistinguishingSign")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.administrativeNumber = it.getIntOrNull("administrativeNumber")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.sex = it.getIntOrNull("sex")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.height = it.getIntOrNull("height")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.weight = it.getIntOrNull("weight")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.eyeColour = it.getIntOrNull("eyeColour")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.hairColour = it.getIntOrNull("hairColour")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.birthPlace = it.getIntOrNull("birthPlace")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.residentAddress = it.getIntOrNull("residentAddress")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.portraitCaptureDate = it.getIntOrNull("portraitCaptureDate")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.ageInYears = it.getIntOrNull("ageInYears")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.ageBirthYear = it.getIntOrNull("ageBirthYear")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.ageOver18 = it.getIntOrNull("ageOver18")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.issuingJurisdiction = it.getIntOrNull("issuingJurisdiction")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.nationality = it.getIntOrNull("nationality")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.residentCity = it.getIntOrNull("residentCity")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.residentState = it.getIntOrNull("residentState")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.residentPostalCode = it.getIntOrNull("residentPostalCode")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.residentCountry = it.getIntOrNull("residentCountry")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.biometricTemplateFace = it.getIntOrNull("biometricTemplateFace")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.biometricTemplateIris = it.getIntOrNull("biometricTemplateIris")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.biometricTemplateFinger = it.getIntOrNull("biometricTemplateFinger")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.biometricTemplateSignatureSign = it.getIntOrNull("biometricTemplateSignatureSign")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.familyNameNationalCharacter = it.getIntOrNull("familyNameNationalCharacter")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.givenNameNationalCharacter = it.getIntOrNull("givenNameNationalCharacter")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result.signatureUsualMark = it.getIntOrNull("signatureUsualMark")?.let { enm -> eMDLIntentToRetain.values()[enm] } + result +} + +fun generateDocumentRequest18013MDL(input: DocumentRequest18013MDL?) = input?.let { + mapOf( + "docType" to it.getPrivateProperty("docType"), + "namespaces" to (it.getPrivateProperty("nameSpaceMDLs") as List).toJson(::generateNameSpaceMDL), + "familyName" to it.familyName?.ordinal, + "givenName" to it.givenName?.ordinal, + "birthDate" to it.birthDate?.ordinal, + "issueDate" to it.issueDate?.ordinal, + "expiryDate" to it.expiryDate?.ordinal, + "issuingCountry" to it.issuingCountry?.ordinal, + "issuingAuthority" to it.issuingAuthority?.ordinal, + "documentNumber" to it.documentNumber?.ordinal, + "portrait" to it.portrait?.ordinal, + "drivingPrivileges" to it.drivingPrivileges?.ordinal, + "unDistinguishingSign" to it.unDistinguishingSign?.ordinal, + "administrativeNumber" to it.administrativeNumber?.ordinal, + "sex" to it.sex?.ordinal, + "height" to it.height?.ordinal, + "weight" to it.weight?.ordinal, + "eyeColour" to it.eyeColour?.ordinal, + "hairColour" to it.hairColour?.ordinal, + "birthPlace" to it.birthPlace?.ordinal, + "residentAddress" to it.residentAddress?.ordinal, + "portraitCaptureDate" to it.portraitCaptureDate?.ordinal, + "ageInYears" to it.ageInYears?.ordinal, + "ageBirthYear" to it.ageBirthYear?.ordinal, + "ageOver18" to it.ageOver18?.ordinal, + "issuingJurisdiction" to it.issuingJurisdiction?.ordinal, + "nationality" to it.nationality?.ordinal, + "residentCity" to it.residentCity?.ordinal, + "residentState" to it.residentState?.ordinal, + "residentPostalCode" to it.residentPostalCode?.ordinal, + "residentCountry" to it.residentCountry?.ordinal, + "biometricTemplateFace" to it.biometricTemplateFace?.ordinal, + "biometricTemplateIris" to it.biometricTemplateIris?.ordinal, + "biometricTemplateFinger" to it.biometricTemplateFinger?.ordinal, + "biometricTemplateSignatureSign" to it.biometricTemplateSignatureSign?.ordinal, + "familyNameNationalCharacter" to it.familyNameNationalCharacter?.ordinal, + "givenNameNationalCharacter" to it.givenNameNationalCharacter?.ordinal, + "signatureUsualMark" to it.signatureUsualMark?.ordinal, + ).toJson() +} + +fun dataRetrievalFromJSON(input: JSONObject?) = input?.let { + val result = DataRetrieval(eMDLDeviceRetrieval.values().first { enm -> enm.value == it.getInt("deviceRetrieval") }) + result.setPrivateProperty("docRequestPreset", it.getIntOrNull("docRequestPreset")?.let { enm -> eMDLDocRequestPreset.values()[enm] }) + result.setPrivateProperty("intentToRetain", it.getIntOrNull("intentToRetain")?.let { enm -> eMDLIntentToRetain.values()[enm] }) + it.getJSONArray("requests").toList(::documentRequestMDLFromJSON)?.forEach { r -> result.addDocRequest(r!!) } + result +} + +fun generateDataRetrieval(input: DataRetrieval?) = input?.let { + mapOf( + "deviceRetrieval" to it.deviceRetrieval.value, + "docRequestPreset" to (it.getPrivateProperty("docRequestPreset") as eMDLDocRequestPreset).ordinal, + "intentToRetain" to (it.getPrivateProperty("intentToRetain") as eMDLIntentToRetain).ordinal, + "requests" to (it.getPrivateProperty("docRequests") as List).toJson(::generateDocumentRequestMDL), + ).toJson() +} + +fun generateDeviceEngagementCompletion(deviceEngagement: DeviceEngagement?, error: RegulaException?) = mapOf( + "deviceEngagement" to generateDeviceEngagement(deviceEngagement), + "error" to generateRegulaException(error) +) + +fun finalizeConfigFromJSON(input: JSONObject?) = input?.let { + val result = FinalizeConfig.Builder() + if (it.has("rawImages")) result.setRawImages(it.getBoolean("rawImages")) + if (it.has("video")) result.setVideo(it.getBoolean("video")) + if (it.has("rfidSession")) result.setRfidSession(it.getBoolean("rfidSession")) + if (it.has("mdlSession")) result.setMdlSession(it.getBoolean("mdlSession")) + result.build() +} + +fun generateFinalizeConfig(input: FinalizeConfig?) = input?.let { + mapOf( + "rawImages" to it.getPrivateProperty("rawImages"), + "video" to it.getPrivateProperty("video"), + "rfidSession" to it.getPrivateProperty("rfidSession"), + "mdlSession" to it.getPrivateProperty("mdlSession"), + ).toJson() +} + +fun paceProtocolFromJSON(input: JSONObject?) = input?.let { + PaceProtocol( + it.getString("version"), + it.getString("stdDomainParams"), + it.getString("keyAlgorithm"), + ) +} + +fun generatePaceProtocol(input: PaceProtocol?) = input?.let { + mapOf( + "version" to it.version, + "stdDomainParams" to it.stdDomainParams, + "keyAlgorithm" to it.keyAlgorithm, + ).toJson() +} + +fun caProtocolFromJSON(input: JSONObject?) = input?.let { + CaProtocol( + it.getString("version"), + it.getString("scheme"), + it.getString("keyAlgorithm"), + it.getBoolean("chipIndividual"), + ) +} + +fun generateCaProtocol(input: CaProtocol?) = input?.let { + mapOf( + "version" to it.version, + "scheme" to it.scheme, + "keyAlgorithm" to it.keyAlgorithm, + "chipIndividual" to it.isChipIndividual, + ).toJson() +} diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/Main.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/Main.kt new file mode 100644 index 0000000000..4718a11237 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/Main.kt @@ -0,0 +1,646 @@ +@file:SuppressLint("MissingPermission") +@file:Suppress("EnumValuesSoftDeprecate") + +package com.regula.plugin.documentreader + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Intent +import android.content.IntentFilter +import android.nfc.NfcAdapter +import android.nfc.tech.IsoDep +import android.os.Build +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import com.regula.common.LocalizationCallbacks +import com.regula.documentreader.api.DocumentReader.Instance +import com.regula.documentreader.api.completions.IDocumentReaderCompletion +import com.regula.documentreader.api.completions.IDocumentReaderInitCompletion +import com.regula.documentreader.api.completions.IDocumentReaderPrepareDbCompletion +import com.regula.documentreader.api.completions.IVideoEncoderCompletion +import com.regula.documentreader.api.completions.model.PrepareProgress +import com.regula.documentreader.api.completions.rfid.ICaProtocolCompletion +import com.regula.documentreader.api.completions.rfid.IPaceProtocolCompletion +import com.regula.documentreader.api.completions.rfid.IRfidPKDCertificateCompletion +import com.regula.documentreader.api.completions.rfid.IRfidReaderCompletion +import com.regula.documentreader.api.completions.rfid.IRfidReaderRequest +import com.regula.documentreader.api.completions.rfid.IRfidTASignatureCompletion +import com.regula.documentreader.api.completions.rfid.certificates.IRfidAccessControl +import com.regula.documentreader.api.enums.DocReaderAction +import com.regula.documentreader.api.enums.LCID +import com.regula.documentreader.api.enums.eImageQualityCheckType +import com.regula.documentreader.api.enums.eLDS_ParsingErrorCodes +import com.regula.documentreader.api.enums.eLDS_ParsingNotificationCodes +import com.regula.documentreader.api.enums.eMDLDeviceEngagement +import com.regula.documentreader.api.enums.eRFID_DataFile_Type +import com.regula.documentreader.api.enums.eRFID_ErrorCodes +import com.regula.documentreader.api.enums.eVisualFieldType +import com.regula.documentreader.api.errors.DocReaderRfidException +import com.regula.documentreader.api.errors.DocumentReaderException +import com.regula.documentreader.api.internal.core.CoreScenarioUtil +import com.regula.documentreader.api.params.mdl.DataRetrieval +import com.regula.documentreader.api.params.rfid.CaProtocol +import com.regula.documentreader.api.params.rfid.PaceProtocol +import com.regula.documentreader.api.results.DocumentReaderNotification +import com.regula.documentreader.api.results.DocumentReaderResults +import com.regula.documentreader.api.results.DocumentReaderResults.fromRawResults +import com.regula.documentreader.api.results.DocumentReaderScenario +import org.json.JSONArray +import org.json.JSONObject +import com.regula.plugin.documentreader.Convert.toBase64 +import com.regula.plugin.documentreader.Convert.toByteArray + +fun methodCall(method: String, callback: (Any?) -> Unit): Any = when (method) { + "getDocumentReaderIsReady" -> getDocumentReaderIsReady(callback) + "getDocumentReaderStatus" -> getDocumentReaderStatus(callback) + "getRfidSessionStatus" -> getRfidSessionStatus(callback) + "setRfidSessionStatus" -> setRfidSessionStatus() + "getTag" -> getTag(callback) + "setTag" -> setTag(argsNullable(0)) + "getTenant" -> getTenant(callback) + "setTenant" -> setTenant(argsNullable(0)) + "getEnv" -> getEnv(callback) + "setEnv" -> setEnv(argsNullable(0)) + "getLocale" -> getLocale(callback) + "setLocale" -> setLocale(argsNullable(0)) + "getFunctionality" -> getFunctionality(callback) + "setFunctionality" -> setFunctionality(args(0)) + "getProcessParams" -> getProcessParams(callback) + "setProcessParams" -> setProcessParams(args(0)) + "getCustomization" -> getCustomization(callback) + "setCustomization" -> setCustomization(args(0)) + "getRfidScenario" -> getRfidScenario(callback) + "setRfidScenario" -> setRfidScenario(args(0)) + "resetConfiguration" -> resetConfiguration() + "initialize" -> initialize(callback, args(0)) + "initializeReader" -> initialize(callback, args(0)) // deprecated + "initializeReaderWithBleDeviceConfig" -> initializeReaderWithBleDeviceConfig(callback, args(0)) // deprecated + "deinitializeReader" -> deinitializeReader() + "prepareDatabase" -> prepareDatabase(callback, args(0)) + "removeDatabase" -> removeDatabase(callback) + "runAutoUpdate" -> runAutoUpdate(callback, args(0)) + "cancelDBUpdate" -> cancelDBUpdate(callback) + "checkDatabaseUpdate" -> checkDatabaseUpdate(callback, args(0)) + "scan" -> scan(args(0)) + "startScanner" -> startScanner(args(0)) + "recognize" -> recognize(args(0)) + "startNewPage" -> startNewPage() + "stopScanner" -> stopScanner() + "startRFIDReader" -> startRFIDReader(argsNullable(0)) + "readRFID" -> readRFID(argsNullable(0)) + "stopRFIDReader" -> stopRFIDReader() + "providePACertificates" -> providePACertificates(argsNullable(0)) + "provideTACertificates" -> provideTACertificates(argsNullable(0)) + "provideTASignature" -> provideTASignature(args(0)) + "selectPACEProtocol" -> selectPACEProtocol(args(0)) + "selectCAProtocol" -> selectCAProtocol(args(0)) + "setTCCParams" -> setTCCParams(callback, args(0)) + "addPKDCertificates" -> addPKDCertificates(args(0)) + "clearPKDCertificates" -> clearPKDCertificates() + "startNewSession" -> startNewSession() + "connectBluetoothDevice" -> connectBluetoothDevice(args(0), callback) + "btDeviceRequestFlashing" -> btDeviceRequestFlashing() + "btDeviceRequestFlashingFullIR" -> btDeviceRequestFlashingFullIR() + "btDeviceRequestTurnOffAll" -> btDeviceRequestTurnOffAll() + "startReadMDl" -> startReadMDl(args(0), args(1), callback) + "startEngageDevice" -> startEngageDevice(args(0), callback) + "engageDeviceNFC" -> engageDeviceNFC(callback) + "engageDeviceData" -> engageDeviceData(args(0), callback) + "startRetrieveData" -> startRetrieveData(args(0), args(1), callback) + "retrieveDataNFC" -> retrieveDataNFC(args(0), callback) + "retrieveDataBLE" -> retrieveDataBLE(args(0), args(1), callback) + "setLocalizationDictionary" -> setLocalizationDictionary(args(0)) + "getLicense" -> getLicense(callback) + "getAvailableScenarios" -> getAvailableScenarios(callback) + "getIsRFIDAvailableForUse" -> getIsRFIDAvailableForUse(callback) + "isAuthenticatorAvailableForUse" -> isAuthenticatorAvailableForUse(callback) + "isAuthenticatorRFIDAvailableForUse" -> isAuthenticatorRFIDAvailableForUse(callback) + "getDocReaderVersion" -> getDocReaderVersion(callback) + "getDocReaderDocumentsDatabase" -> getDocReaderDocumentsDatabase(callback) + "textFieldValueByType" -> textFieldValueByType(callback, args(0), args(1)) + "textFieldValueByTypeLcid" -> textFieldValueByTypeLcid(callback, args(0), args(1), args(2)) + "textFieldValueByTypeSource" -> textFieldValueByTypeSource(callback, args(0), args(1), args(2)) + "textFieldValueByTypeLcidSource" -> textFieldValueByTypeLcidSource(callback, args(0), args(1), args(2), args(3)) + "textFieldValueByTypeSourceOriginal" -> textFieldValueByTypeSourceOriginal(callback, args(0), args(1), args(2), args(3)) + "textFieldValueByTypeLcidSourceOriginal" -> textFieldValueByTypeLcidSourceOriginal(callback, args(0), args(1), args(2), args(3), args(4)) + "textFieldByType" -> textFieldByType(callback, args(0), args(1)) + "textFieldByTypeLcid" -> textFieldByTypeLcid(callback, args(0), args(1), args(2)) + "graphicFieldByTypeSource" -> graphicFieldByTypeSource(callback, args(0), args(1), args(2)) + "graphicFieldByTypeSourcePageIndex" -> graphicFieldByTypeSourcePageIndex(callback, args(0), args(1), args(2), args(3)) + "graphicFieldByTypeSourcePageIndexLight" -> graphicFieldByTypeSourcePageIndexLight(callback, args(0), args(1), args(2), args(3), args(4)) + "graphicFieldImageByType" -> graphicFieldImageByType(callback, args(0), args(1)) + "graphicFieldImageByTypeSource" -> graphicFieldImageByTypeSource(callback, args(0), args(1), args(2)) + "graphicFieldImageByTypeSourcePageIndex" -> graphicFieldImageByTypeSourcePageIndex(callback, args(0), args(1), args(2), args(3)) + "graphicFieldImageByTypeSourcePageIndexLight" -> graphicFieldImageByTypeSourcePageIndexLight(callback, args(0), args(1), args(2), args(3), args(4)) + "containers" -> containers(callback, args(0), args(1)) + "encryptedContainers" -> encryptedContainers(callback, args(0)) + "finalizePackage" -> finalizePackage(callback) + "finalizePackageWithFinalizeConfig" -> finalizePackageWithFinalizeConfig(callback, args(0)) + "endBackendTransaction" -> endBackendTransaction() + "getTranslation" -> getTranslation(callback, args(0), args(1)) + else -> Unit +} + +inline fun args(index: Int) = argsNullable(index)!! +typealias Callback = (Any?) -> Unit + +const val completionEvent = "completion" +const val databaseProgressEvent = "database_progress" + +const val rfidOnProgressEvent = "rfidOnProgressCompletion" +const val rfidOnChipDetectedEvent = "rfidOnChipDetectedEvent" +const val rfidOnRetryReadChipEvent = "rfidOnRetryReadChipEvent" + +const val paCertificateCompletionEvent = "pa_certificate_completion" +const val taCertificateCompletionEvent = "ta_certificate_completion" +const val taSignatureCompletionEvent = "ta_signature_completion" +const val paceProtocolCompletionEvent = "paceProtocolCompletionEvent" +const val caProtocolCompletionEvent = "caProtocolCompletionEvent" + +const val videoEncoderCompletionEvent = "video_encoder_completion" +const val onCustomButtonTappedEvent = "onCustomButtonTappedEvent" + +fun getDocumentReaderIsReady(callback: Callback) = callback(Instance().isReady) + +fun getDocumentReaderStatus(callback: Callback) = callback(Instance().status) + +fun getRfidSessionStatus(iosOnly: Callback) = iosOnly(null) + +fun setRfidSessionStatus() = Unit + +fun getTag(callback: Callback) = callback(Instance().tag) + +fun setTag(tag: String?) = tag.let { Instance().tag = it } + +fun getTenant(callback: Callback) = callback(Instance().tenant) + +fun setTenant(tag: String?) = tag.let { Instance().tenant = it } + +fun getEnv(callback: Callback) = callback(Instance().env) + +fun setEnv(tag: String?) = tag.let { Instance().env = it } + +fun getLocale(callback: Callback) = callback(Instance().locale) + +fun setLocale(locale: String?) = locale.let { Instance().locale = it } + +fun getFunctionality(callback: Callback) = callback(getFunctionality(Instance().functionality())) + +fun setFunctionality(functionality: JSONObject) = setFunctionality(Instance().functionality(), functionality) + +fun getProcessParams(callback: Callback) = callback(getProcessParams(Instance().processParams())) + +fun setProcessParams(processParams: JSONObject) = setProcessParams(Instance().processParams(), processParams) + +fun getCustomization(callback: Callback) = callback(getCustomization(Instance().customization())) + +fun setCustomization(customization: JSONObject) = setCustomization(Instance().customization(), customization) + +fun getRfidScenario(callback: Callback) = callback(getRfidScenario(Instance().rfidScenario())) + +fun setRfidScenario(rfidScenario: JSONObject) = setRfidScenario(Instance().rfidScenario(), rfidScenario) + +fun resetConfiguration() = Instance().resetConfiguration() + +fun initialize(callback: Callback, config: JSONObject) = + if (config.getBooleanOrNull("useBleDevice") != true) + Instance().initializeReader(context, initConfigFromJSON(config), initCompletion(callback)) + else + Instance().initializeReader(context, initBleDeviceConfigFromJSON(config), initCompletion(callback)) + +// deprecated +fun initializeReaderWithBleDeviceConfig(callback: Callback, config: JSONObject) = Instance().initializeReader(context, initBleDeviceConfigFromJSON(config), initCompletion(callback)) + +fun deinitializeReader() = Instance().deinitializeReader() + +fun prepareDatabase(callback: Callback, databaseID: String) = Instance().prepareDatabase( + context, + databaseID, + prepareCompletion(callback) +) + +fun removeDatabase(callback: Callback) = callback(Instance().removeDatabase(context)) + +fun runAutoUpdate(callback: Callback, databaseID: String) = Instance().runAutoUpdate( + context, + databaseID, + prepareCompletion(callback) +) + +fun cancelDBUpdate(callback: Callback) = callback(Instance().cancelDBUpdate(context)) + +fun checkDatabaseUpdate(callback: Callback, databaseID: String) = Instance().checkDatabaseUpdate( + context, + databaseID +) { callback(generateDocReaderDocumentsDatabase(it)) } + +@Suppress("DEPRECATION") +fun scan(config: JSONObject) { + stopBackgroundRFID() + Instance().showScanner(activity, scannerConfigFromJSON(config), IDocumentReaderCompletion(completion)) +} + +fun startScanner(config: JSONObject) { + stopBackgroundRFID() + Instance().startScanner(activity, scannerConfigFromJSON(config), IDocumentReaderCompletion(completion)) +} + +fun recognize(config: JSONObject) { + stopBackgroundRFID() + Instance().recognize(recognizeConfigFromJSON(config), IDocumentReaderCompletion(completion)) +} + +fun startNewPage() = Instance().startNewPage() + +fun stopScanner() = Instance().stopScanner(context) + +fun startRFIDReader(config: JSONObject?) { + stopBackgroundRFID() + Instance().startRFIDReader(activity, rfidReaderCompletion, getRfidReaderRequest(config)) +} + +fun readRFID(config: JSONObject?) { + rfidReaderRequest = getRfidReaderRequest(config) + startForegroundDispatch("readRFID") +} + +fun stopRFIDReader() { + Instance().stopRFIDReader(context) + stopBackgroundRFID() +} + +fun providePACertificates(certificates: JSONArray?) = paCertificateCompletion.onCertificatesReceived( + certificates.toArray(::pkdCertificateFromJSON) +) + +fun provideTACertificates(certificates: JSONArray?) = taCertificateCompletion.onCertificatesReceived( + certificates.toArray(::pkdCertificateFromJSON) +) + +fun provideTASignature(signature: String?) = taSignatureCompletion.onSignatureReceived( + signature.toByteArray() +) + +fun selectPACEProtocol(protocol: JSONObject) = paceProtocolCompletion.onPaceProtocolSelected( + paceProtocolFromJSON(protocol)!! +) + +fun selectCAProtocol(protocol: JSONObject) = caProtocolCompletion.onCaProtocolSelected( + caProtocolFromJSON(protocol)!! +) + +fun setTCCParams(callback: Callback, params: JSONObject) { + Instance().setTccParams(tccParamsFromJSON(params)) { success, error -> + callback(generateSuccessCompletion(success, error)) + } +} + +fun addPKDCertificates(certificates: JSONArray) = Instance().addPKDCertificates( + certificates.toList(::pkdCertificateFromJSON)!! +) + +fun clearPKDCertificates() = Instance().clearPKDCertificates() + +fun startNewSession() = Instance().startNewSession() + +fun startReadMDl(type: Int, dataRetrieval: JSONObject, callback: Callback) { + stopBackgroundRFID() + Instance().startReadMDL(activity, eMDLDeviceEngagement.values()[type], dataRetrievalFromJSON(dataRetrieval)!!) { v1, v2, v3 -> callback(generateCompletion(v1, v2, v3)) } +} + +fun startEngageDevice(type: Int, callback: Callback) { + stopBackgroundRFID() + Instance().startEngageDevice(activity, eMDLDeviceEngagement.values()[type]) { v1, v2 -> callback(generateDeviceEngagementCompletion(v1, v2)) } +} + +lateinit var engageDeviceNFCCallback: Callback +fun engageDeviceNFC(callback: Callback) { + engageDeviceNFCCallback = callback + stopBackgroundRFID() + startForegroundDispatch("engageDeviceNFC") +} + +fun engageDeviceData(data: String, callback: Callback) { + stopBackgroundRFID() + Instance().engageDeviceData(data) { v1, v2 -> callback(generateDeviceEngagementCompletion(v1, v2)) } +} + +fun startRetrieveData(dataRetrieval: JSONObject, deviceEngagement: JSONObject, callback: Callback) { + stopBackgroundRFID() + Instance().startRetrieveData(activity, deviceEngagementFromJSON(deviceEngagement)!!, dataRetrievalFromJSON(dataRetrieval)!!) { v1, v2, v3 -> callback(generateCompletion(v1, v2, v3)) } +} + +lateinit var retrieveDataNFCCallback: Callback +lateinit var retrieveDataNFCProp: DataRetrieval +fun retrieveDataNFC(dataRetrieval: JSONObject, callback: Callback) { + retrieveDataNFCCallback = callback + retrieveDataNFCProp = dataRetrievalFromJSON(dataRetrieval)!! + stopBackgroundRFID() + startForegroundDispatch("retrieveDataNFC") +} + +fun retrieveDataBLE(dataRetrieval: JSONObject, deviceEngagement: JSONObject, callback: Callback) { + stopBackgroundRFID() + Instance().retrieveDataBLE(context, deviceEngagementFromJSON(deviceEngagement)!!, dataRetrievalFromJSON(dataRetrieval)!!) { v1, v2, v3 -> callback(generateCompletion(v1, v2, v3)) } +} + +fun setLocalizationDictionary(dictionary: JSONObject) { + localizationCallbacks = LocalizationCallbacks { if (dictionary.has(it)) dictionary.getString(it) else null } + Instance().setLocalizationCallback(localizationCallbacks) +} + +fun getLicense(callback: Callback) = callback(generateLicense(Instance().license())) + +fun getAvailableScenarios(callback: Callback) { + val scenarios: MutableList = ArrayList() + for (scenario: DocumentReaderScenario in Instance().availableScenarios) + scenarios.add(CoreScenarioUtil.getScenario(scenario.name)) + callback(scenarios.toJsonNullable(::generateDocumentReaderScenario)) +} + +fun getIsRFIDAvailableForUse(callback: Callback) = callback(Instance().isRFIDAvailableForUse) + +fun isAuthenticatorAvailableForUse(callback: Callback) = callback(Instance().isAuthenticatorAvailableForUse) + +fun isAuthenticatorRFIDAvailableForUse(callback: Callback) = callback(Instance().isAuthenticatorRFIDAvailableForUse) + +fun getDocReaderVersion(callback: Callback) = callback(generateDocReaderVersion(Instance().version)) + +fun getDocReaderDocumentsDatabase(callback: Callback) = callback(Instance().version?.let { + generateDocReaderDocumentsDatabase(it.database) +}) + +fun finalizePackage(callback: Callback) = Instance().finalizePackage { action, info, error -> + callback(generateFinalizePackageCompletion(action, info, error)) +} + +fun finalizePackageWithFinalizeConfig(callback: Callback, config: JSONObject) = Instance().finalizePackage( + finalizeConfigFromJSON(config) +) { action, info, error -> + callback(generateFinalizePackageCompletion(action, info, error)) +} + +fun endBackendTransaction() = Instance().endBackendTransaction() + +fun textFieldValueByType( + callback: Callback, + raw: String, + fieldType: Int +) = callback(fromRawResults(raw).getTextFieldValueByType(fieldType)) + +fun textFieldValueByTypeLcid( + callback: Callback, + raw: String, + fieldType: Int, + lcid: Int +) = callback(fromRawResults(raw).getTextFieldValueByType(fieldType, lcid)) + +fun textFieldValueByTypeSource( + callback: Callback, + raw: String, + fieldType: Int, + source: Int +) = callback(fromRawResults(raw).getTextFieldValueByTypeAndSource(fieldType, source)) + +fun textFieldValueByTypeLcidSource( + callback: Callback, + raw: String, + fieldType: Int, + lcid: Int, + source: Int +) = callback(fromRawResults(raw).getTextFieldValueByType(fieldType, lcid, source)) + +fun textFieldValueByTypeSourceOriginal( + callback: Callback, + raw: String, + fieldType: Int, + source: Int, + original: Boolean +) = callback(fromRawResults(raw).getTextFieldValueByTypeAndSource(fieldType, source, original)) + +fun textFieldValueByTypeLcidSourceOriginal( + callback: Callback, + raw: String, + fieldType: Int, + lcid: Int, + source: Int, + original: Boolean +) = callback(fromRawResults(raw).getTextFieldValueByType(fieldType, lcid, source, original)) + +fun textFieldByType( + callback: Callback, + raw: String, + fieldType: Int +) = callback(generateDocumentReaderTextField(fromRawResults(raw).getTextFieldByType(fieldType))) + +fun textFieldByTypeLcid( + callback: Callback, + raw: String, + fieldType: Int, + lcid: Int +) = callback(generateDocumentReaderTextField(fromRawResults(raw).getTextFieldByType(fieldType, lcid))) + +fun graphicFieldByTypeSource( + callback: Callback, + raw: String, + fieldType: Int, + source: Int +) = callback(generateDocumentReaderGraphicField(fromRawResults(raw).getGraphicFieldByType(fieldType, source))) + +fun graphicFieldByTypeSourcePageIndex( + callback: Callback, + raw: String, + fieldType: Int, + source: Int, + pageIndex: Int +) = callback(generateDocumentReaderGraphicField(fromRawResults(raw).getGraphicFieldByType(fieldType, source, pageIndex))) + +fun graphicFieldByTypeSourcePageIndexLight( + callback: Callback, + raw: String, + fieldType: Int, + source: Int, + pageIndex: Int, + light: Int +) = callback(generateDocumentReaderGraphicField(fromRawResults(raw).getGraphicFieldByType(fieldType, source, pageIndex, light))) + +fun graphicFieldImageByType( + callback: Callback, + raw: String, + fieldType: Int +) = callback(fromRawResults(raw).getGraphicFieldImageByType(fieldType).toBase64()) + +fun graphicFieldImageByTypeSource( + callback: Callback, + raw: String, + fieldType: Int, + source: Int +) = callback(fromRawResults(raw).getGraphicFieldImageByType(fieldType, source).toBase64()) + +fun graphicFieldImageByTypeSourcePageIndex( + callback: Callback, + raw: String, + fieldType: Int, + source: Int, + pageIndex: Int +) = callback(fromRawResults(raw).getGraphicFieldImageByType(fieldType, source, pageIndex).toBase64()) + +fun graphicFieldImageByTypeSourcePageIndexLight( + callback: Callback, + raw: String, + fieldType: Int, + source: Int, + pageIndex: Int, + light: Int +) = callback(fromRawResults(raw).getGraphicFieldImageByType(fieldType, source, pageIndex, light).toBase64()) + +fun containers( + callback: Callback, + raw: String, + resultType: JSONArray +) = callback(fromRawResults(raw).getContainers(resultType.toIntArray()!!)) + +fun encryptedContainers( + callback: Callback, + raw: String +) = callback(fromRawResults(raw).encryptedContainers) + +fun getTranslation(callback: Callback, className: String, value: Int) = when (className) { + "RFIDErrorCodes" -> callback(eRFID_ErrorCodes.getTranslation(context, value)) + "LDSParsingErrorCodes" -> callback(eLDS_ParsingErrorCodes.getTranslation(context, value)) + "LDSParsingNotificationCodes" -> callback(eLDS_ParsingNotificationCodes.getTranslation(context, value)) + "ImageQualityCheckType" -> callback(eImageQualityCheckType.getTranslation(context, value)) + "RFIDDataFileType" -> callback(eRFID_DataFile_Type.getTranslation(context, value)) + "VisualFieldType" -> callback(eVisualFieldType.getTranslation(context, value)) + "LCID" -> callback(LCID.getTranslation(context, value)) + else -> Unit +} + +// -------------------------------------------------------------------------------------------------------------------------- + +val completion = { action: Int, results: DocumentReaderResults?, error: DocumentReaderException? -> + sendEvent(completionEvent, generateCompletion(action, results, error)) + if ((action == DocReaderAction.ERROR) || + (action == DocReaderAction.CANCEL) || + ((action == DocReaderAction.COMPLETE) && (results?.rfidResult == 1)) + ) stopBackgroundRFID() +} + +val rfidReaderCompletion = object : IRfidReaderCompletion() { + override fun onCompleted(action: Int, results: DocumentReaderResults?, error: DocumentReaderException?): Unit = completion(action, results, error) + override fun onChipDetected(): Unit = sendEvent(rfidOnChipDetectedEvent) + override fun onRetryReadChip(error: DocReaderRfidException) = sendEvent(rfidOnRetryReadChipEvent, generateRegulaException(error)) + override fun onProgress(notification: DocumentReaderNotification) = sendEvent(rfidOnProgressEvent, generateDocumentReaderNotification(notification)) +} + +fun prepareCompletion(callback: Callback) = object : IDocumentReaderPrepareDbCompletion() { + override fun onPrepareProgressChanged(progress: PrepareProgress) = sendEvent(databaseProgressEvent, generatePrepareProgress(progress)) + override fun onPrepareCompleted(success: Boolean, error: DocumentReaderException?) = callback(generateSuccessCompletion(success, error)) +} + +fun initCompletion(callback: Callback) = IDocumentReaderInitCompletion { success, error -> + if (success) { + videoEncoderCompletion = IVideoEncoderCompletion { _, file -> sendEvent(videoEncoderCompletionEvent, file.path) } + Instance().setVideoEncoderCompletion(videoEncoderCompletion) + Instance().setOnClickListener { sendEvent(onCustomButtonTappedEvent, it.tag) } + } + callback(generateSuccessCompletion(success, error)) +} + +lateinit var paCertificateCompletion: IRfidPKDCertificateCompletion +lateinit var taCertificateCompletion: IRfidPKDCertificateCompletion +lateinit var taSignatureCompletion: IRfidTASignatureCompletion +lateinit var paceProtocolCompletion: IPaceProtocolCompletion +lateinit var caProtocolCompletion: ICaProtocolCompletion + +var rfidReaderRequest = getRfidReaderRequest() + +fun getRfidReaderRequest(config: JSONObject? = null): IRfidReaderRequest { + val result = IRfidReaderRequest() + if (config == null) return result + + if (config.getBoolean("paCertificates")) result.setPACertificates { serialNumber, issuer, completion -> + paCertificateCompletion = completion + sendEvent(paCertificateCompletionEvent, generatePACertificateCompletion(serialNumber, issuer)) + } + if (config.getBoolean("taCertificates")) result.setTACertificates { keyCAR, completion -> + taCertificateCompletion = completion + sendEvent(taCertificateCompletionEvent, keyCAR) + } + if (config.getBoolean("taSignature")) result.setTASignature { challenge, completion -> + taSignatureCompletion = completion + sendEvent(taSignatureCompletionEvent, generateTAChallenge(challenge)) + } + if (config.getBoolean("paceProtocol") || config.getBoolean("caProtocol")) result.setRfidAccessControl(object : IRfidAccessControl { + override fun onRequestPaceProtocol(list: List, completion: IPaceProtocolCompletion) { + paceProtocolCompletion = completion + sendEvent(paceProtocolCompletionEvent, list.toJson(::generatePaceProtocol)) + } + override fun onRequestCaProtocol(list: List, completion: ICaProtocolCompletion) { + caProtocolCompletion = completion + sendEvent(caProtocolCompletionEvent, list.toJson(::generateCaProtocol)) + } + }) + + return result +} + +@Suppress("DEPRECATION", "MissingPermission") +fun newIntent(intent: Intent): Boolean { + if (intent.action != NfcAdapter.ACTION_TECH_DISCOVERED) return false + val isoDep = IsoDep.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)) + when (nfcFunction) { + "readRFID" -> Instance().readRFID(isoDep, rfidReaderCompletion, rfidReaderRequest) + "engageDeviceNFC" -> Instance().engageDeviceNFC(isoDep) { v1, v2 -> engageDeviceNFCCallback(generateDeviceEngagementCompletion(v1, v2)) } + "retrieveDataNFC" -> Instance().retrieveDataNFC(isoDep, retrieveDataNFCProp) { v1, v2, v3 -> retrieveDataNFCCallback(generateCompletion(v1, v2, v3)) } + } + return true +} + +var backgroundRFIDEnabled = false +var nfcFunction = "" +lateinit var lifecycleObserver: LifecycleEventObserver + +fun startForegroundDispatch(tag: String) { + backgroundRFIDEnabled = true + nfcFunction = tag + val filters: Array = arrayOfNulls(1) + filters[0] = IntentFilter() + filters[0]!!.addAction(NfcAdapter.ACTION_TECH_DISCOVERED) + filters[0]!!.addCategory(Intent.CATEGORY_DEFAULT) + val techList = arrayOf(arrayOf("android.nfc.tech.IsoDep")) + val intent = Intent(activity, activity.javaClass) + val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else 0 + val pendingIntent = PendingIntent.getActivity(activity, 0, intent, flag) + + if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) + enableForegroundDispatch(pendingIntent, filters, techList) + lifecycleObserver = LifecycleEventObserver { _, event -> + if (backgroundRFIDEnabled) when (event) { + Lifecycle.Event.ON_RESUME -> enableForegroundDispatch(pendingIntent, filters, techList) + Lifecycle.Event.ON_PAUSE -> disableForegroundDispatch() + else -> Unit + } + } + activity.runOnUiThread { lifecycle.addObserver(lifecycleObserver) } +} + +fun enableForegroundDispatch( + pendingIntent: PendingIntent, + filters: Array, + techList: Array> +) = NfcAdapter.getDefaultAdapter(context).enableForegroundDispatch(activity, pendingIntent, filters, techList) + +fun disableForegroundDispatch() = NfcAdapter.getDefaultAdapter(activity).disableForegroundDispatch(activity) + +fun stopBackgroundRFID() { + if (!backgroundRFIDEnabled) return + backgroundRFIDEnabled = false + if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) + disableForegroundDispatch() + activity.runOnUiThread { lifecycle.removeObserver(lifecycleObserver) } +} + +// Weak references +lateinit var localizationCallbacks: LocalizationCallbacks +lateinit var videoEncoderCompletion: IVideoEncoderCompletion diff --git a/android/src/main/kotlin/com/regula/plugin/documentreader/Utils.kt b/android/src/main/kotlin/com/regula/plugin/documentreader/Utils.kt new file mode 100644 index 0000000000..8093ef9c41 --- /dev/null +++ b/android/src/main/kotlin/com/regula/plugin/documentreader/Utils.kt @@ -0,0 +1,248 @@ +@file:SuppressLint("UseKtx") + +package com.regula.plugin.documentreader + +import android.annotation.SuppressLint +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Canvas +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import android.util.Base64 +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.lang.reflect.Constructor +import kotlin.math.sqrt +import kotlin.reflect.KClass + +fun List<*>.toJson(): JSONArray { + val result = JSONArray() + for (i in indices) + when (val v = this[i]) { + null -> result.put(null) + is Map<*, *> -> result.put(v.toJson()) + is List<*> -> result.put(v.toJson()) + else -> result.put(v) + } + return result +} + +fun Map<*, *>.toJson(): JSONObject { + val result = JSONObject() + for ((k, v) in this) { + when (v) { + null -> result.put(k as String, null) + is Map<*, *> -> result.put(k as String, v.toJson()) + is List<*> -> result.put(k as String, v.toJson()) + else -> result.put(k as String, v) + } + } + return result +} + +fun Any?.toSendable(): Any? = this?.let { + if (it is JSONObject || it is JSONArray) it.toString() + else it +} + +fun List?.toJson(toJson: (T?) -> Any?) = this?.let { + val result = JSONArray() + for (item in it) result.put(toJson(item)) + result +} + +fun List?.toJsonNullable(toJson: (T?) -> Any?) = this?.let { + val result = JSONArray() + for (item in it) result.put(toJson(item)) + result +} + +fun JSONArray?.toList(fromJson: (JSONObject) -> T) = this?.let { + val result: MutableList = ArrayList() + for (i in 0 until it.length()) result.add(fromJson(it.getJSONObject(i))) + result +} + +fun JSONArray.toList() = this.let { + val result = mutableListOf() + @Suppress("UNCHECKED_CAST") + for (i in 0 until length()) result.add(get(i) as T) + result +} + +inline fun JSONArray?.toArray() = this?.let { + val result = arrayOfNulls(length()) + for (i in 0 until length()) result[i] = get(i) as T + result +} + +inline fun JSONArray?.toArray(fromJson: (JSONObject?) -> T) = this?.let { + val result = arrayOfNulls(length()) + for (i in 0 until length()) result[i] = fromJson(getJSONObject(i)) + result +} + +fun Array?.toJson() = this?.let { + val result = JSONArray() + for (i in it.indices) result.put(i, it[i]) + result +} + +fun Array?.toJson(toJson: (T?) -> JSONObject?) = this?.let { + val result = JSONArray() + for (i in indices) result.put(i, toJson(this[i])) + result +} + +fun Any?.toIntArray() = (this as JSONArray?)?.let { + val result = IntArray(it.length()) + for (i in 0 until it.length()) result[i] = it.getInt(i) + result +} + +fun IntArray?.toJson() = this?.let { + val result = JSONArray() + for (i in it.indices) result.put(i, it[i]) + result +} + +fun JSONArray.toLongArray(): LongArray { + val result = LongArray(length()) + for (i in 0 until length()) result[i] = getLong(i) + return result +} + +fun LongArray.toJson(): JSONArray { + val result = JSONArray() + for (i in indices) result.put(i, this[i]) + return result +} + +fun JSONObject.forEach(action: (String, Any) -> Unit) { + val keys: Iterator = keys() + while (keys.hasNext()) { + val key = keys.next() + action(key, get(key)) + } +} + +fun JSONObject.getJSONObjectOrNull(name: String): JSONObject? { + if (has(name) && get(name).toString() != "null") return getJSONObject(name) + return null +} + +fun JSONObject.getIntOrNull(name: String): Int? { + if (has(name) && get(name).toString() != "null") return getInt(name) + return null +} + +fun JSONObject.getLongOrNull(name: String): Long? { + if (has(name) && get(name).toString() != "null") return getLong(name) + return null +} + +fun JSONObject.getDoubleOrNull(name: String): Double? { + if (has(name) && get(name).toString() != "null") return getDouble(name) + return null +} + +fun JSONObject.getBooleanOrNull(name: String): Boolean? { + if (has(name) && get(name).toString() != "null") return getBoolean(name) + return null +} + +fun JSONObject.getStringOrNull(name: String): String? { + if (has(name) && get(name).toString() != "null") return getString(name) + return null +} + +fun JSONObject.getJSONArrayOrNull(name: String): JSONArray? { + if (has(name) && get(name).toString() != "null") return getJSONArray(name) + return null +} + +fun KClass.constructor(vararg argTypes: KClass<*>): Constructor { + val types = mutableListOf>() + for (argType in argTypes) types.add(argType.java) + return java.getDeclaredConstructor(*types.toTypedArray()) +} + +fun Constructor.instantiate(vararg args: Any?): T { + isAccessible = true + return newInstance(*args) +} + +fun T.setPrivateProperty(varName: String, data: Any?) { + try { + setPrivateProperty(javaClass, varName, data) + } catch (_: java.lang.Exception) { + try { + setPrivateProperty(javaClass.superclass!!, varName, data) + } catch (_: java.lang.Exception) { + } + } +} + +fun T.setPrivateProperty(clazz: Class, varName: String, data: Any?) = clazz.getDeclaredField(varName).let { + it.isAccessible = true + it.set(this, data) +} + +fun T.getPrivateProperty(varName: String): Any? { + var clazz: Class<*>? = this.javaClass + while (clazz != null) { + try { + val field = clazz.getDeclaredField(varName) + field.isAccessible = true + return field.get(this) + } catch (_: NoSuchFieldException) { + clazz = clazz.superclass + } + } + throw NoSuchFieldException( + "Field '$varName' not found in class hierarchy of ${this.javaClass.name}" + ) +} + +internal object Convert { + fun String?.toByteArray(): ByteArray? { + var str = this ?: return null + if (str.startsWith("data")) str = str.substring(str.indexOf(",") + 1) + return Base64.decode(str, Base64.NO_WRAP) + } + + fun ByteArray?.toBase64() = this?.let { Base64.encodeToString(it, Base64.NO_WRAP) } + + fun Bitmap?.toBase64() = this?.let { + val byteArrayOutputStream = ByteArrayOutputStream() + it.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) + byteArrayOutputStream.toByteArray().toBase64() + } + + fun String?.toBitmap() = this?.let { + val decodedString = toByteArray()!! + var result = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) + val sizeMultiplier = result.byteCount / 5000000 + if (result.byteCount > 5000000) result = Bitmap.createScaledBitmap(result, result.width / sqrt(sizeMultiplier.toDouble()).toInt(), result.height / sqrt(sizeMultiplier.toDouble()).toInt(), false) + result + } + + fun Any?.toDrawable() = (this as String?)?.let { + val decodedByte = it.toByteArray()!! + val bitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.size) + val density = context.resources.displayMetrics.density + val width = (bitmap.width * density).toInt() + val height = (bitmap.height * density).toInt() + BitmapDrawable(context.resources, Bitmap.createScaledBitmap(bitmap, width, height, false)) + } + + fun Drawable?.toBase64() = this?.let { + if (this is BitmapDrawable) if (bitmap != null) return bitmap.toBase64() + val bitmap: Bitmap = if (intrinsicWidth <= 0 || intrinsicHeight <= 0) Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) else Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + setBounds(0, 0, canvas.width, canvas.height) + draw(canvas) + bitmap.toBase64() + } +} diff --git a/android/src/test/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt b/android/src/test/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt new file mode 100644 index 0000000000..dbccea2c31 --- /dev/null +++ b/android/src/test/kotlin/com/regula/plugin/documentreader/FlutterDocumentReaderApiPlugin.kt @@ -0,0 +1,366 @@ +package com.regula.plugin.documentreader + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@Suppress("unused") +val context: Context + get() = ApplicationProvider.getApplicationContext() + +@RunWith(RobolectricTestRunner::class) +@Config(shadows = [MyShadowBitmap::class, MyShadowDrawable::class, MyShadowBitmapDrawable::class]) +class FlutterDocumentReaderApiPluginTest { + // config + + @Test + fun initConfig() = compare( + "initConfig", ::initConfigFromJSON, ::generateInitConfig, + "customDb", + "useBleDevice" + ) + + @Test + fun onlineProcessingConfig() = compare( + "onlineProcessingConfig", ::onlineProcessingConfigFromJSON, ::generateOnlineProcessingConfig, + "requestHeaders" + ) + + @Test + fun imageInputData() = compare("imageInputData", ::imageInputDataFromJSON, ::generateImageInputData) + + @Test + fun recognizeConfig() = compare( + "recognizeConfig", ::recognizeConfigFromJSON, ::generateRecognizeConfig, + "data" + ) + + @Test + fun recognizeConfig2() = compare( + "recognizeConfig2", ::recognizeConfigFromJSON, ::generateRecognizeConfig, + "onlineProcessingConfig.requestHeaders", + "data" + ) + + @Test + fun scannerConfig() = compare( + "scannerConfig", ::scannerConfigFromJSON, ::generateScannerConfig, + "onlineProcessingConfig.requestHeaders" + ) + + @Test + fun finalizeConfig() = compare("finalizeConfig", ::finalizeConfigFromJSON, ::generateFinalizeConfig) + + // params.process_params + + @Test + fun faceApiSearchParams() = compare("faceApiSearchParams", ::faceApiSearchParamsFromJSON, ::generateFaceApiSearchParams) + + @Test + fun faceApiParams() = compare("faceApiParams", ::faceApiParamsFromJSON, ::generateFaceApiParams) + + @Test + fun livenessParams() = compare("livenessParams", ::livenessParamsFromJSON, ::generateLivenessParams) + + @Test + fun authenticityParams() = compare("authenticityParams", ::authenticityParamsFromJSON, ::generateAuthenticityParams) + + @Test + fun glaresCheckParams() = compare("glaresCheckParams", ::glaresCheckParamsFromJSON, ::generateGlaresCheckParams) + + @Test + fun imageQA() = compare("imageQA", ::imageQAFromJSON, ::generateImageQA) + + @Test + fun rfidParams() = compare("rfidParams", ::rfidParamsFromJSON, ::generateRFIDParams) + + @Test + fun backendProcessingConfig() = compare("backendProcessingConfig", ::backendProcessingConfigFromJSON, ::generateBackendProcessingConfig) + + @Test + fun bsi() = compare("bsi", ::bsiFromJSON, ::generateBsi) + + @Test + fun processParams() = compare("processParams", ::processParamFromJSON, ::generateProcessParam) + + //params.rfid_scenario + + @Test + fun eDLDataGroups() = compare("eDLDataGroups", ::eDLDataGroupsFromJSON, ::generateEDLDataGroups) + + @Test + fun ePassportDataGroups() = compare("ePassportDataGroups", ::ePassportDataGroupsFromJSON, ::generateEPassportDataGroups) + + @Test + fun eIDDataGroups() = compare("eIDDataGroups", ::eIDDataGroupsFromJSON, ::generateEIDDataGroups) + + @Test + fun dtcDataGroup() = compare("dtcDataGroup", ::dtcDataGroupFromJSON, ::generateDTCDataGroup) + + @Test + fun rfidScenario() = compare("rfidScenario", ::rfidScenarioFromJSON, ::generateRfidScenario) + + // params + + @Test + fun customization() = compare( + "customization", ::customizationFromJSON, ::generateCustomization, + "helpAnimationImageContentMode", + "multipageAnimationFrontImageContentMode", + "multipageAnimationBackImageContentMode", + "livenessAnimationImageContentMode", + "borderBackgroundImageContentMode", + "statusTextFont", + "resultStatusTextFont", + "multipageButtonTextFont", + "fonts", + "contentModes", + ) + + @Test + fun functionality() = compare( + "functionality", ::functionalityFromJSON, ::generateFunctionality, + "useAuthenticator", + "singleResult", + "videoSessionPreset", + "cameraPositionIOS", + "homeIndicatorAutoHide" + ) + + // info + + @Test + fun prepareProgress() = compare("prepareProgress", ::prepareProgressFromJSON, ::generatePrepareProgress) + + @Test + fun documentsDatabase() = compare("documentsDatabase", ::docReaderDocumentsDatabaseFromJSON, ::generateDocReaderDocumentsDatabase) + + @Test + fun docReaderScenario() = compare( + "docReaderScenario", ::documentReaderScenarioFromJSON, ::generateDocumentReaderScenario, + "barcodeExt", + "frame" + ) + + @Test + fun docReaderException() = compare("docReaderException", ::regulaExceptionFromJSON, ::generateRegulaException) + + // results.authenticity + + @Test + fun authenticityElement() = compare("authenticityElement", ::documentReaderAuthenticityElementFromJSON, ::generateDocumentReaderAuthenticityElement) + + @Test + fun authenticityCheck() = compare("authenticityCheck", ::documentReaderAuthenticityCheckFromJSON, ::generateDocumentReaderAuthenticityCheck) + + @Test + fun authenticityResult() = compare("authenticityResult", ::documentReaderAuthenticityResultFromJSON, ::generateDocumentReaderAuthenticityResult) + + // results.barcode + + @Test + fun pdf417Info() = compare("pdf417Info", ::pdf417InfoFromJSON, ::generatePDF417Info) + + @Test + fun barcodeField() = compare("barcodeField", ::documentReaderBarcodeFieldFromJSON, ::generateDocumentReaderBarcodeField) + + @Test + fun barcodeResult() = compare("barcodeResult", ::documentReaderBarcodeResultFromJSON, ::generateDocumentReaderBarcodeResult) + + // results.image_quality + + @Test + fun imageQuality() = compare("imageQuality", ::imageQualityFromJSON, ::generateImageQuality) + + @Test + fun imageQualityGroup() = compare("imageQualityGroup", ::imageQualityGroupFromJSON, ::generateImageQualityGroup) + + // results.rfid + + @Test + fun accessControlProcedureType() = compare("accessControlProcedureType", ::accessControlProcedureTypeFromJSON, ::generateAccessControlProcedureType) + + @Test + fun fileData() = compare("fileData", ::fileDataFromJSON, ::generateFileData) + + @Test + fun certificateData() = compare("certificateData", ::certificateDataFromJSON, ::generateCertificateData) + + @Test + fun securityObjectCertificates() = compare("securityObjectCertificates", ::securityObjectCertificatesFromJSON, ::generateSecurityObjectCertificates) + + @Test + fun file() = compare("file", ::fileFromJSON, ::generateFile) + + @Test + fun application() = compare("application", ::applicationFromJSON, ::generateApplication) + + @Test + fun rfidValue() = compare("rfidValue", ::valueFromJSON, ::generateValue) + + @Test + fun attribute() = compare("attribute", ::attributeFromJSON, ::generateAttribute) + + @Test + fun authority() = compare("authority", ::authorityFromJSON, ::generateAuthority) + + @Test + fun cardProperties() = compare("cardProperties", ::cardPropertiesFromJSON, ::generateCardProperties) + + @Test + fun extension() = compare("extension", ::extensionFromJSON, ::generateExtension) + + @Test + fun rfidValidity() = compare("rfidValidity", ::validityFromJSON, ::generateValidity) + + @Test + fun certificateChain() = compare("certificateChain", ::certificateChainFromJSON, ::generateCertificateChain) + + @Test + fun dataField() = compare("dataField", ::dataFieldFromJSON, ::generateDataField) + + @Test + fun signerInfo() = compare("signerInfo", ::signerInfoFromJSON, ::generateSignerInfo) + + @Test + fun securityObject() = compare("securityObject", ::securityObjectFromJSON, ::generateSecurityObject) + + @Test + fun rfidSessionData() = compare("rfidSessionData", ::rfidSessionDataFromJSON, ::generateRFIDSessionData) + + @Test + fun bytesData() = compare("bytesData", ::bytesDataFromJSON, ::generateBytesData) + + @Test + fun vdsncData() = compare("vdsncData", ::vdsncDataFromJSON, ::generateVDSNCData) + + @Test + fun docFeature() = compare("docFeature", ::docFeatureFromJSON, ::generateDocFeature) + + @Test + fun vdsData() = compare("vdsData", ::vdsDataFromJSON, ::generateVDSData) + + // results.visual_results + + @Test + fun comparison() = compare("comparison", ::documentReaderComparisonFromJSON, ::generateDocumentReaderComparison) + + @Test + fun rect() = compare("rect", ::rectFromJSON, ::generateRect) + + @Test + fun graphicField() = compare("graphicField", ::documentReaderGraphicFieldFromJSON, ::generateDocumentReaderGraphicField) + + @Test + fun graphicResult() = compare("graphicResult", ::documentReaderGraphicResultFromJSON, ::generateDocumentReaderGraphicResult) + + @Test + fun rfidOrigin() = compare("rfidOrigin", ::documentReaderRFIDOriginFromJSON, ::generateDocumentReaderRFIDOrigin) + + @Test + fun symbol() = compare("symbol", ::documentReaderSymbolFromJSON, ::generateDocumentReaderSymbol) + + @Test + fun validity() = compare("validity", ::documentReaderValidityFromJSON, ::generateDocumentReaderValidity) + + @Test + fun value() = compare("value", ::documentReaderValueFromJSON, ::generateDocumentReaderValue) + + @Test + fun textField() = compare( + "textField", ::documentReaderTextFieldFromJSON, ::generateDocumentReaderTextField, + "getValue" + ) + + @Test + fun textSource() = compare("textSource", ::documentReaderTextSourceFromJSON, ::generateDocumentReaderTextSource) + + @Test + fun textResult() = compare( + "textResult", ::documentReaderTextResultFromJSON, ::generateDocumentReaderTextResult, + "fields.getValue" + ) + + // results + + @Test + fun resultsStatus() = compare("resultsStatus", ::documentReaderResultsStatusFromJSON, ::generateDocumentReaderResultsStatus) + + @Test + fun detailsOptical() = compare("opticalStatus", ::detailsOpticalFromJSON, ::generateDetailsOptical) + + @Test + fun rfidStatus() = compare("rfidStatus", ::detailsRFIDFromJSON, ::generateDetailsRFID) + + @Test + fun ageStatus() = compare("ageStatus", ::detailsAgeFromJSON, ::generateDetailsAge) + + @Test + fun documentType() = compare("documentType", ::documentReaderDocumentTypeFromJSON, ::generateDocumentReaderDocumentType) + + @Test + fun coordinate() = compare("coordinate", ::coordinateFromJSON, ::generateCoordinate) + + @Test + fun position() = compare("position", ::elementPositionFromJSON, ::generateElementPosition) + + @Test + fun transactionInfo() = compare("transactionInfo", ::transactionInfoFromJSON, ::generateTransactionInfo) + + @Test + fun results() = compare( + "results", ::documentReaderResultsFromJSON, ::generateDocumentReaderResults, + "textResult.fields.getValue") + + // rfid + + @Test + fun paAttribute() = compare("paAttribute", ::paAttributeFromJSON, ::generatePAAttribute) + + @Test + fun paResourcesIssuer() = compare("paResourcesIssuer", ::paResourcesIssuerFromJSON, ::generatePAResourcesIssuer) + + @Test + fun pkdCertificate() = compare("pkdCertificate", ::pkdCertificateFromJSON, ::generatePKDCertificate) + + @Test + fun taChallenge() = compare("taChallenge", ::taChallengeFromJSON, ::generateTAChallenge) + + @Test + fun tccParams() = compare("tccParams", ::tccParamsFromJSON, ::generateTccParams) + + @Test + fun paceProtocol() = compare("paceProtocol", ::paceProtocolFromJSON, ::generatePaceProtocol) + + @Test + fun caProtocol() = compare("caProtocol", ::caProtocolFromJSON, ::generateCaProtocol) + + // mdl + + @Test + fun deviceRetrievalMethod() = compare( + "deviceRetrievalMethod", ::deviceRetrievalMethodFromJSON, ::generateDeviceRetrievalMethod, + "serverModeUUID" + ) + + @Test + fun deviceEngagement() = compare( + "deviceEngagement", ::deviceEngagementFromJSON, ::generateDeviceEngagement, + "deviceRetrievalMethods.serverModeUUID" + ) + + @Test + fun nameSpaceMDL() = compare("nameSpaceMDL", ::nameSpaceMDLFromJSON, ::generateNameSpaceMDL) + + @Test + fun documentRequestMDL() = compare("documentRequestMDL", ::documentRequestMDLFromJSON, ::generateDocumentRequestMDL) + + @Test + fun documentRequest18013MDL() = compare("documentRequest18013MDL", ::documentRequest18013MDLFromJSON, ::generateDocumentRequest18013MDL) + + @Test + fun dataRetrieval() = compare("dataRetrieval", ::dataRetrievalFromJSON, ::generateDataRetrieval) +} \ No newline at end of file diff --git a/android/src/test/kotlin/com/regula/plugin/documentreader/Shadows.kt b/android/src/test/kotlin/com/regula/plugin/documentreader/Shadows.kt new file mode 100644 index 0000000000..391d1f96de --- /dev/null +++ b/android/src/test/kotlin/com/regula/plugin/documentreader/Shadows.kt @@ -0,0 +1,19 @@ +package com.regula.plugin.documentreader + +import android.graphics.Bitmap +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import org.robolectric.annotation.Implements + +@Implements(Bitmap::class) +class MyShadowBitmap { + var data: ByteArray? = null +} + +@Implements(Drawable::class) +open class MyShadowDrawable { + var data: ByteArray? = null +} + +@Implements(BitmapDrawable::class) +class MyShadowBitmapDrawable : MyShadowDrawable() \ No newline at end of file diff --git a/android/src/test/kotlin/com/regula/plugin/documentreader/TestUtils.kt b/android/src/test/kotlin/com/regula/plugin/documentreader/TestUtils.kt new file mode 100644 index 0000000000..a43b51c4f6 --- /dev/null +++ b/android/src/test/kotlin/com/regula/plugin/documentreader/TestUtils.kt @@ -0,0 +1,122 @@ +package com.regula.plugin.documentreader + +import android.graphics.Bitmap +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable +import org.json.JSONArray +import org.json.JSONObject +import org.robolectric.shadow.api.Shadow +import org.skyscreamer.jsonassert.JSONAssert +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Paths +import java.util.Base64 + +fun readFile(name: String): JSONObject { + val bytes = Files.readAllBytes(Paths.get("../test/json/$name.json")) + return JSONObject(String(bytes)) +} + +fun compareJSONs(name: String, expected: JSONObject, actual: JSONObject) = + try { + JSONAssert.assertEquals(expected, floatToDouble(actual), true) + } catch (e: Throwable) { + println("\nAndroid test failed: $name") + println(" Expected JSON:\n$expected") + println(" Actual JSON:\n$actual") + throw e + } + +fun compareSingle( + name: String, + fromJson: (JSONObject) -> T, + toJson: (T) -> JSONObject?, + vararg omit: String +) { + try { + var expected = readFile(name) + for (key in omit) expected = omitDeep(expected, key.split("."), 0) + var actual = toJson(fromJson(expected))!! + for (key in omit) actual = omitDeep(actual, key.split("."), 0) + compareJSONs(name, expected, actual) + } catch (_: IOException) { + } +} + +fun compare( + name: String, + fromJson: (JSONObject) -> T, + toJson: (T) -> JSONObject?, + vararg omit: String +) { + compareSingle(name, fromJson, toJson, *omit) + compareSingle(name + "Nullable", fromJson, toJson, *omit) +} + +fun omitDeep(dict: JSONObject, path: List, index: Int): JSONObject { + if (index < path.size - 1) { + val node = dict.get(path[index]) + if (node is JSONObject) + dict.put(path[index], omitDeep(node, path, index + 1)) + else if (node is JSONArray) + dict.put(path[index], omitDeep(node, path, index + 1)) + } else + dict.remove(path[index]) + return dict +} + +fun omitDeep(dict: JSONArray, path: List, index: Int): JSONArray { + for (i in 0 until dict.length()) + dict.put(i, omitDeep(dict.getJSONObject(i), path, index)) + return dict +} + +fun floatToDouble(input: JSONObject): JSONObject { + for (key in input.keys()) { + val value = input.get(key) + if (value is JSONObject) input.put(key, floatToDouble(value)) + if (value is JSONArray) input.put(key, floatToDouble(value)) + if (value is Float) input.put(key, java.lang.Double.parseDouble(value.toString())) + } + return input +} + +fun floatToDouble(input: JSONArray): JSONArray { + for (i in 0 until input.length()) { + val value = input.get(i) + if (value is JSONObject) input.put(i, floatToDouble(value)) + if (value is JSONArray) input.put(i, floatToDouble(value)) + if (value is Float) input.put(i, java.lang.Double.parseDouble(value.toString())) + } + return input +} + +@Suppress("unused", "MemberVisibilityCanBePrivate") +internal object Convert { + fun String?.toByteArray() = this?.let { Base64.getDecoder().decode(it) } + fun ByteArray?.toBase64() = this?.let { Base64.getEncoder().encodeToString(it) } + + fun String?.toBitmap() = this?.let { + val bitmap = Shadow.newInstanceOf(Bitmap::class.java) + val shadow = Shadow.extract(bitmap) + shadow.data = it.toByteArray() + bitmap + } + + fun Bitmap?.toBase64() = this?.let { + val shadow = Shadow.extract(it) + shadow.data.toBase64() + } + + fun Any?.toDrawable() = (this as String?)?.let { + val bitmap = Shadow.newInstanceOf(BitmapDrawable::class.java) + val shadow = Shadow.extract(bitmap) + shadow.data = it.toByteArray() + bitmap + } + + fun Drawable?.toBase64() = this?.let { + val shadow = Shadow.extract(this) + shadow.data.toBase64() + } +} diff --git a/example/.gitignore b/example/.gitignore index 1ba9c339ef..79c113f9b5 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -5,9 +5,12 @@ *.swp .DS_Store .atom/ +.build/ .buildlog/ .history .svn/ +.swiftpm/ +migrate_working_dir/ # IntelliJ related *.iml @@ -22,22 +25,21 @@ # Flutter/Dart/Pub related **/doc/api/ +**/ios/Flutter/.last_build_id .dart_tool/ .flutter-plugins .flutter-plugins-dependencies -.packages .pub-cache/ .pub/ /build/ -# Web related -lib/generated_plugin_registrant.dart - # Symbolication related app.*.symbols # Obfuscation related app.*.map.json -# Exceptions to above rules. -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/example/.metadata b/example/.metadata new file mode 100644 index 0000000000..fac5aec07d --- /dev/null +++ b/example/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: android + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: ios + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: linux + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: macos + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: web + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + - platform: windows + create_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + base_revision: 68415ad1d920f6fe5ec284f5c2febf7c4dd5b0b3 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/example/.vscode/launch.json b/example/.vscode/launch.json new file mode 100644 index 0000000000..2e08f749e1 --- /dev/null +++ b/example/.vscode/launch.json @@ -0,0 +1,10 @@ +{ + "configurations": [ + { + "name": "Flutter", + "request": "launch", + "type": "dart", + "flutterMode": "profile" + } + ] + } \ No newline at end of file diff --git a/example/.vscode/settings.json b/example/.vscode/settings.json new file mode 100644 index 0000000000..d780454b65 --- /dev/null +++ b/example/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "dart.flutterRunAdditionalArgs": [ + "--profile" + ] +} \ No newline at end of file diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000000..939ec94cbb --- /dev/null +++ b/example/README.md @@ -0,0 +1,19 @@ +# Demo application for Document Reader plugin + +## How to build demo application + +1. Download or the clone current repository using the command `git clone https://github.com/regulaforensics/DocumentReader-Flutter.git`. +2. Put `regula.license` file at `assets/` (you can get a trial license [here](https://client.regulaforensics.com)). +3. Put `db.dat` file at `ios/Runner/` and `android/app/src/main/assets/Regula/` (you can get a trial database [here](https://client.regulaforensics.com/customer/databases)) +4. Execute `flutter pub get && (cd ios && pod install || pod update)` within this directory. +5. Run the app: `flutter run`. + +## Additional examples + +### Bluetooth device + +In order to connect to an external scanning device, change the `useBtDevice` constant to true in `src/extra/bt_device`, and set `btDeviceName` to the name of your device. After running the app, click `Connect`. + +### RFID self hosted UI + +This app also demonstraits how you can implement you own UI for the RFID reading process. To enable it, change the `useRfidSelfHostedUI` constant to true in `src/extra/custom_rfid`. Run the app and initiate RFID reading. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000000..c36c2c5d39 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1 @@ +include: package:lints/core.yaml diff --git a/example/android/.gitignore b/example/android/.gitignore index bc2100d8f7..55afd919c6 100644 --- a/example/android/.gitignore +++ b/example/android/.gitignore @@ -5,3 +5,9 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 9d061f9807..934a776574 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -1,51 +1,34 @@ -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" } -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -apply plugin: 'com.android.application' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - android { - compileSdkVersion 34 + namespace = "com.regula.example.dr.flutter" + compileSdk = flutter.compileSdkVersion + ndkVersion = "27.0.12077973" + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } defaultConfig { - applicationId "com.regula.documentreader" - minSdkVersion 21 - targetSdkVersion 34 - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName + applicationId = "com.regula.example.dr.flutter" + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName } buildTypes { release { - signingConfig signingConfigs.debug + signingConfig = signingConfigs.debug } } - namespace 'io.flutter.plugins.regula.documentreader.flutter_document_reader_api_example' - lint { - disable 'InvalidPackage' - } } flutter { - source '../..' + source = "../.." } diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml index dd5e376d31..02872909ce 100644 --- a/example/android/app/src/debug/AndroidManifest.xml +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -1,4 +1,5 @@ - - + + + + diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index d567b0eb02..3d0da8f530 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -1,38 +1,40 @@ + xmlns:tools="http://schemas.android.com/tools"> + - + + android:label="Document" + android:usesCleartextTraffic="true" + tools:targetApi="23"> - + android:name="io.flutter.embedding.android.NormalTheme" + android:resource="@style/NormalTheme" /> - - + + + + + + + + diff --git a/example/android/app/src/main/assets/Regula/.gitignore b/example/android/app/src/main/assets/Regula/.gitignore deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/ios/Assets/.gitkeep b/example/android/app/src/main/assets/Regula/.gitkeep similarity index 100% rename from ios/Assets/.gitkeep rename to example/android/app/src/main/assets/Regula/.gitkeep diff --git a/example/android/app/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api_example/MainActivity.java b/example/android/app/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api_example/MainActivity.java deleted file mode 100644 index e86611a55b..0000000000 --- a/example/android/app/src/main/java/io/flutter/plugins/regula/documentreader/flutter_document_reader_api_example/MainActivity.java +++ /dev/null @@ -1,6 +0,0 @@ -package io.flutter.plugins.regula.documentreader.flutter_document_reader_api_example; - -import io.flutter.embedding.android.FlutterActivity; - -public class MainActivity extends FlutterActivity { -} diff --git a/example/android/app/src/main/kotlin/com/regula/example/dr/flutter/MainActivity.kt b/example/android/app/src/main/kotlin/com/regula/example/dr/flutter/MainActivity.kt new file mode 100644 index 0000000000..756e50c79f --- /dev/null +++ b/example/android/app/src/main/kotlin/com/regula/example/dr/flutter/MainActivity.kt @@ -0,0 +1,5 @@ +package com.regula.example.dr.flutter + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000000..f74085f3f6 --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000000..06952be745 --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml index 1f83a33fd4..cb1ef88056 100644 --- a/example/android/app/src/main/res/values/styles.xml +++ b/example/android/app/src/main/res/values/styles.xml @@ -1,18 +1,18 @@ - - - diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml index dd5e376d31..02872909ce 100644 --- a/example/android/app/src/profile/AndroidManifest.xml +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -1,4 +1,5 @@ - - + + + + diff --git a/example/android/build.gradle b/example/android/build.gradle index 2aa6e9c9d5..d2ffbffa4c 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -1,18 +1,3 @@ -buildscript { - ext { - kotlin_version = '1.9.0' - } - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.0.2' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - allprojects { repositories { google() @@ -20,14 +5,14 @@ allprojects { } } -rootProject.buildDir = '../build' +rootProject.buildDir = "../build" subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { - project.evaluationDependsOn(':app') + project.evaluationDependsOn(":app") } -task clean(type: Delete) { +tasks.register("clean", Delete) { delete rootProject.buildDir } diff --git a/example/android/gradle.properties b/example/android/gradle.properties index bbd7acc823..2597170821 100644 --- a/example/android/gradle.properties +++ b/example/android/gradle.properties @@ -1,3 +1,3 @@ -org.gradle.jvmargs=-Xmx1536M +org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true -android.enableJetifier=false +android.enableJetifier=true diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties index dba0b08390..afa1e8eb0a 100644 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip diff --git a/example/android/settings.gradle b/example/android/settings.gradle index 5a2f14fb18..3f4554ad3c 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -1,15 +1,25 @@ -include ':app' +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + }() -def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") -def plugins = new Properties() -def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') -if (pluginsFile.exists()) { - pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } + repositories { + google() + mavenCentral() + gradlePluginPortal() + } } -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version '8.8.0' apply false + id "org.jetbrains.kotlin.android" version "1.9.25" apply false } + +include ":app" diff --git a/example/assets/certificates/.gitignore b/example/assets/certificates/.gitignore deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/example/ios/.gitignore b/example/ios/.gitignore index e96ef602b8..7a7f9873ad 100644 --- a/example/ios/.gitignore +++ b/example/ios/.gitignore @@ -1,3 +1,4 @@ +**/dgph *.mode1v3 *.mode2v3 *.moved-aside @@ -18,6 +19,7 @@ Flutter/App.framework Flutter/Flutter.framework Flutter/Flutter.podspec Flutter/Generated.xcconfig +Flutter/ephemeral/ Flutter/app.flx Flutter/app.zip Flutter/flutter_assets/ diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist index 6b4c0f78a7..4620da1781 100644 --- a/example/ios/Flutter/AppFrameworkInfo.plist +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -3,7 +3,7 @@ CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) + en CFBundleExecutable App CFBundleIdentifier @@ -21,6 +21,6 @@ CFBundleVersion 1.0 MinimumOSVersion - 8.0 + 15.6 diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig index 779c75aa98..ec97fc6f30 100644 --- a/example/ios/Flutter/Debug.xcconfig +++ b/example/ios/Flutter/Debug.xcconfig @@ -1,3 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" - -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" \ No newline at end of file diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig index e5b3d35e5b..c4855bfe20 100644 --- a/example/ios/Flutter/Release.xcconfig +++ b/example/ios/Flutter/Release.xcconfig @@ -1,4 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" - -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig" \ No newline at end of file diff --git a/example/ios/Podfile b/example/ios/Podfile index 57951e673e..3cbd4302be 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -1,8 +1,10 @@ +source "https://github.com/CocoaPods/Specs.git" + +platform :ios, '13.0' + # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' -platform :ios, '11.0' - project 'Runner', { 'Debug' => :debug, 'Profile' => :release, @@ -27,7 +29,13 @@ require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelpe flutter_ios_podfile_setup target 'Runner' do + use_frameworks! + use_modular_headers! + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end end post_install do |installer| diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock new file mode 100644 index 0000000000..b958f5acd6 --- /dev/null +++ b/example/ios/Podfile.lock @@ -0,0 +1,58 @@ +PODS: + - Flutter (1.0.0) + - flutter_document_reader_api (7.6.98): + - Flutter + - flutter_document_reader_btdevice (7.5.41): + - Flutter + - flutter_document_reader_core_fullauthrfid (7.5.887): + - Flutter + - image_picker_ios (0.0.1): + - Flutter + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - Flutter (from `Flutter`) + - flutter_document_reader_api (from `.symlinks/plugins/flutter_document_reader_api/ios`) + - flutter_document_reader_btdevice (from `.symlinks/plugins/flutter_document_reader_btdevice/ios`) + - flutter_document_reader_core_fullauthrfid (from `.symlinks/plugins/flutter_document_reader_core_fullauthrfid/ios`) + - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) + - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + +SPEC REPOS: + https://github.com/CocoaPods/Specs.git: + - BTDevice + - DocumentReader + - DocumentReaderFullAuthRFID + - RegulaCommon + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + flutter_document_reader_api: + :path: ".symlinks/plugins/flutter_document_reader_api/ios" + flutter_document_reader_btdevice: + :path: ".symlinks/plugins/flutter_document_reader_btdevice/ios" + flutter_document_reader_core_fullauthrfid: + :path: ".symlinks/plugins/flutter_document_reader_core_fullauthrfid/ios" + image_picker_ios: + :path: ".symlinks/plugins/image_picker_ios/ios" + path_provider_foundation: + :path: ".symlinks/plugins/path_provider_foundation/darwin" + +SPEC CHECKSUMS: + BTDevice: c27e5547dc55e28cb45c761ba07971a390118092 + DocumentReader: f69fec81e53ca0ce52e8298f44299059f3c2391c + DocumentReaderFullAuthRFID: 638b2a1716d9f9c349d4be47e1ef2126241e25af + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + flutter_document_reader_api: 9ccda59f43c837bdd71423f765d2e4e091f81348 + flutter_document_reader_btdevice: a41da909b33c908eba5e9af9bda240c8bd57fb34 + flutter_document_reader_core_fullauthrfid: 48e8196ef3ddaf7158c6068d16bb3b4a39194d2b + image_picker_ios: 7fe1ff8e34c1790d6fff70a32484959f563a928a + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + RegulaCommon: 8f212fc65e045ced82f28be371da9b0598d16690 + +PODFILE CHECKSUM: 54d85b47c8d60ae7253b9a38905f64c617325429 + +COCOAPODS: 1.16.2 diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index b04c6c4963..e40d2d7ffc 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -3,19 +3,32 @@ archiveVersion = 1; classes = { }; - objectVersion = 50; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* Tests.swift */; }; + 343450152B07B4D3008D8706 /* json in Resources */ = {isa = PBXBuildFile; fileRef = 343450142B07B4D3008D8706 /* json */; }; + 34A6AF2A2B86298700266440 /* db.dat in Resources */ = {isa = PBXBuildFile; fileRef = 34A6AF292B86298700266440 /* db.dat */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; - 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + C311E6862D36F55D00718A18 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = C311E6852D36F55D00718A18 /* Utils.swift */; }; /* End PBXBuildFile section */ +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + /* Begin PBXCopyFilesBuildPhase section */ 9705A1C41CF9048500538489 /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; @@ -32,19 +45,23 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Tests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 343450142B07B4D3008D8706 /* json */ = {isa = PBXFileReference; lastKnownFileType = text; name = json; path = ../../../test/json; sourceTree = ""; }; + 34A6AF292B86298700266440 /* db.dat */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.dat; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C3E7CA4524D1B0D4008FBAB2 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + C311E6842D36D6FF00718A18 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + C311E6852D36F55D00718A18 /* Utils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -58,6 +75,16 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* Tests */ = { + isa = PBXGroup; + children = ( + 343450142B07B4D3008D8706 /* json */, + 331C807B294A618700263BE5 /* Tests.swift */, + C311E6852D36F55D00718A18 /* Utils.swift */, + ); + path = Tests; + sourceTree = ""; + }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -75,6 +102,7 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* Tests */, ); sourceTree = ""; }; @@ -82,6 +110,7 @@ isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, ); name = Products; sourceTree = ""; @@ -89,31 +118,40 @@ 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( - C3E7CA4524D1B0D4008FBAB2 /* Runner.entitlements */, - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */, - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */, + C311E6842D36D6FF00718A18 /* Runner.entitlements */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + 34A6AF292B86298700266440 /* db.dat */, ); path = Runner; sourceTree = ""; }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 97C146F21CF9000F007C117D /* main.m */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; @@ -140,11 +178,17 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1020; + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; ORGANIZATIONNAME = ""; TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; }; }; }; @@ -162,15 +206,25 @@ projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 343450152B07B4D3008D8706 /* json in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 97C146EC1CF9000F007C117D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 34A6AF2A2B86298700266440 /* db.dat in Resources */, 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, @@ -183,10 +237,12 @@ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", ); name = "Thin Binary"; outputPaths = ( @@ -197,6 +253,7 @@ }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); @@ -212,18 +269,34 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* Tests.swift in Sources */, + C311E6862D36F55D00718A18 /* Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */, - 97C146F31CF9000F007C117D /* main.m in Sources */, + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + /* Begin PBXVariantGroup section */ 97C146FA1CF9000F007C117D /* Main.storyboard */ = { isa = PBXVariantGroup; @@ -246,9 +319,9 @@ /* Begin XCBuildConfiguration section */ 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -278,6 +351,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -286,7 +360,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -300,34 +374,79 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = regula.DocumentReader; + PRODUCT_BUNDLE_IDENTIFIER = com.regula.example.dr.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Profile; }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterDocumentReaderApiExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterDocumentReaderApiExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterDocumentReaderApiExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -357,6 +476,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -371,7 +491,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -381,9 +501,9 @@ }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -413,6 +533,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -421,10 +542,12 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -435,25 +558,21 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = regula.DocumentReader; + PRODUCT_BUNDLE_IDENTIFIER = com.regula.example.dr.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; @@ -463,25 +582,20 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.6; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = regula.DocumentReader; + PRODUCT_BUNDLE_IDENTIFIER = com.regula.example.dr.flutter; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; @@ -489,6 +603,16 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 1d526a16ed..919434a625 100644 --- a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a28140cfdb..f08940f69f 100644 --- a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ - - - - + + + + + + - - -#import - -@interface AppDelegate : FlutterAppDelegate - -@end diff --git a/example/ios/Runner/AppDelegate.m b/example/ios/Runner/AppDelegate.m deleted file mode 100644 index 70e83933db..0000000000 --- a/example/ios/Runner/AppDelegate.m +++ /dev/null @@ -1,13 +0,0 @@ -#import "AppDelegate.h" -#import "GeneratedPluginRegistrant.h" - -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application - didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [GeneratedPluginRegistrant registerWithRegistry:self]; - // Override point for customization after application launch. - return [super application:application didFinishLaunchingWithOptions:launchOptions]; -} - -@end diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000000..626664468b --- /dev/null +++ b/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 28c6bf0301..7353c41ecf 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 2ccbfd967d..797d452e45 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index f091b6b0bc..6ed2d933e1 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cde12118d..4cd7b0099c 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index d0ef06e7ed..fe730945a0 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index dcdc2306c2..321773cd85 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 2ccbfd967d..797d452e45 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index c8f9ed8f5c..502f463a9b 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index a6d6b8609d..0ec3034392 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index a6d6b8609d..0ec3034392 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 75b2d164a5..e9f5fea27c 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index c4df70d39d..84ac32ae7d 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 6a84f41e14..8953cba090 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index d0e1f58536..0467bf12aa 100644 Binary files a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist index b6f9229e34..7a88af3f79 100644 --- a/example/ios/Runner/Info.plist +++ b/example/ios/Runner/Info.plist @@ -2,8 +2,12 @@ + CADisableMinimumFrameDurationOnPhone + CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Document CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -24,10 +28,14 @@ NFCReaderUsageDescription To use NFC + NSBluetoothAlwaysUsageDescription + To use bluetooth device NSCameraUsageDescription To use camera NSPhotoLibraryUsageDescription To use gallery + UIApplicationSupportsIndirectInputEvents + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile @@ -38,15 +46,6 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - UIViewControllerBasedStatusBarAppearance - com.apple.developer.nfc.readersession.iso7816.select-identifiers A0000002471001 @@ -55,7 +54,9 @@ A0000002480100 A0000002480200 A0000002480300 + A0000002480400 A00000045645444C2D3031 + D2760000850101 diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000000..308a2a560b --- /dev/null +++ b/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/example/ios/Runner/Runner.entitlements b/example/ios/Runner/Runner.entitlements index 91c9872190..2bb4dee14a 100644 --- a/example/ios/Runner/Runner.entitlements +++ b/example/ios/Runner/Runner.entitlements @@ -4,7 +4,6 @@ com.apple.developer.nfc.readersession.formats - NDEF TAG diff --git a/example/ios/Runner/main.m b/example/ios/Runner/main.m deleted file mode 100644 index dff6597e45..0000000000 --- a/example/ios/Runner/main.m +++ /dev/null @@ -1,9 +0,0 @@ -#import -#import -#import "AppDelegate.h" - -int main(int argc, char* argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} diff --git a/example/ios/Tests/Tests.swift b/example/ios/Tests/Tests.swift new file mode 100644 index 0000000000..93e259fb68 --- /dev/null +++ b/example/ios/Tests/Tests.swift @@ -0,0 +1,462 @@ +import XCTest +import DocumentReader +import flutter_document_reader_api + +class Tests: XCTestCase { + // config + + func test_imageInputData() { + compare(name: "imageInputData", fromJson: RGLWJSONConstructor.imageInput, generate: RGLWJSONConstructor.generate) + } + + func test_initConfig() { + compare(name: "initConfig", fromJson: RGLWJSONConstructor.config, generate: RGLWJSONConstructor.generate, + omit: ["blackList", + "customDb", + "useBleDevice"]) + } + + func test_onlineProcessingConfig() { + compare(name: "onlineProcessingConfig", fromJson: RGLWJSONConstructor.onlineProcessingConfig, generate: RGLWJSONConstructor.generate, + omit: ["requestHeaders", + "processParams.sessionLogFolder", + "processParams.checkCaptureProcessIntegrity", + "processParams.uvTorchEnabled"]) + } + + func test_recognizeConfig() { + compare(name: "recognizeConfig", fromJson: RGLWJSONConstructor.recognizeConfig, generate: RGLWJSONConstructor.generate, + omit: ["onlineProcessingConfig.processParams.sessionLogFolder", + "onlineProcessingConfig.processParams.checkCaptureProcessIntegrity", + "onlineProcessingConfig.processParams.uvTorchEnabled"]) + } + + func test_recognizeConfig2() { + compare(name: "recognizeConfig2", fromJson: RGLWJSONConstructor.recognizeConfig, generate: RGLWJSONConstructor.generate, + omit: ["onlineProcessingConfig.processParams.sessionLogFolder", + "onlineProcessingConfig.processParams.uvTorchEnabled", + "onlineProcessingConfig.processParams.checkCaptureProcessIntegrity", + "onlineProcessingConfig.requestHeaders"]) + } + + func test_scannerConfig() { + compare(name: "scannerConfig", fromJson: RGLWJSONConstructor.scannerConfig, generate: RGLWJSONConstructor.generate, + omit: ["cameraId", + "onlineProcessingConfig.processParams.sessionLogFolder", + "onlineProcessingConfig.processParams.uvTorchEnabled", + "onlineProcessingConfig.processParams.checkCaptureProcessIntegrity", + "onlineProcessingConfig.requestHeaders"]) + } + + func test_finalizeConfig() { + compare(name: "finalizeConfig", fromJson: RGLWJSONConstructor.finalizeConfig, generate: RGLWJSONConstructor.generate) + } + + // params.process_params + + func test_faceApiSearchParams() { + compare(name: "faceApiSearchParams", fromJson: RGLWJSONConstructor.faceAPISearchParams, generate: RGLWJSONConstructor.generate) + } + + func test_faceApiParams() { + compare(name: "faceApiParams", fromJson: RGLWJSONConstructor.faceAPIParams, generate: RGLWJSONConstructor.generate) + } + + func test_livenessParams() { + compare(name: "livenessParams", fromJson: RGLWJSONConstructor.livenessParams, generate: RGLWJSONConstructor.generate) + } + + func test_authenticityParams() { + compare(name: "authenticityParams", fromJson: RGLWJSONConstructor.authenticityParams, generate: RGLWJSONConstructor.generate) + } + + func test_glaresCheckParams() { + compare(name: "glaresCheckParams", fromJson: RGLWJSONConstructor.glaresCheckParams, generate: RGLWJSONConstructor.generate) + } + + func test_imageQA() { + compare(name: "imageQA", fromJson: RGLWJSONConstructor.imageQA, generate: RGLWJSONConstructor.generate) + } + + func test_rfidParams() { + compare(name: "rfidParams", fromJson: RGLWJSONConstructor.rfidParams, generate: RGLWJSONConstructor.generate) + } + + func test_backendProcessingConfig() { + compare(name: "backendProcessingConfig", fromJson: RGLWJSONConstructor.backendProcessingConfig, generate: RGLWJSONConstructor.generate) + } + + func test_bsi() { + compare(name: "bsi", fromJson: RGLWJSONConstructor.bsi, generate: RGLWJSONConstructor.generate) + } + + func test_processParams() { + compare(name: "processParams", fromJson: RGLWJSONConstructor.processParams, generate: RGLWJSONConstructor.generate, + omit: ["sessionLogFolder", + "uvTorchEnabled", + "checkCaptureProcessIntegrity",]) + } + + // params.rfid_scenario + + func test_eDLDataGroups() { + compare(name: "eDLDataGroups", fromJson: RGLWJSONConstructor.eDLDataGroups, generate: RGLWJSONConstructor.generateEDLDataGroups) + } + + func test_ePassportDataGroups() { + compare(name: "ePassportDataGroups", fromJson: RGLWJSONConstructor.ePassportDataGroups, generate: RGLWJSONConstructor.generateEPassportDataGroups) + } + + func test_eIDDataGroups() { + compare(name: "eIDDataGroups", fromJson: RGLWJSONConstructor.eIDDataGroups, generate: RGLWJSONConstructor.generateEIDDataGroups) + } + + func test_dtcDataGroup() { + compare(name: "dtcDataGroup", fromJson: RGLWJSONConstructor.dtcDataGroup, generate: RGLWJSONConstructor.generateRGLDTCDataGroup) + } + + func test_rfidScenario() { + compare(name: "rfidScenario", fromJson: RGLWJSONConstructor.rfidScenario, generate: RGLWJSONConstructor.generate) + } + + // params + + func test_customization() { + compare(name: "customization", fromJson: RGLWJSONConstructor.customization, generate: RGLWJSONConstructor.generate, + omit: ["helpAnimationImageMatrix", + "multipageAnimationFrontImageMatrix", + "multipageAnimationBackImageMatrix", + "livenessAnimationImageMatrix", + "borderBackgroundImageMatrix", + "statusTextFont.style", + "resultStatusTextFont.style", + "multipageButtonTextFont.style", + "colors.rfidEnableNfcButtonBackground", + "colors.rfidEnableNfcButtonText", + "colors.rfidEnableNfcDescriptionText", + "colors.rfidEnableNfcTitleText", + "colors.mdlEnableNfcTitleText", + "colors.mdlEnableNfcDescriptionText", + "colors.mdlEnableNfcButtonText", + "colors.mdlEnableNfcButtonBackground", + "fonts.rfidProcessingScreenHintLabel.style", + "fonts.rfidProcessingScreenProgressLabel.style", + "fonts.rfidProcessingScreenResultLabel.style", + "fonts.mdlProcessingScreenHintLabel.style", + "fonts.mdlProcessingScreenProgressLabel.style", + "fonts.mdlProcessingScreenResultLabel.style", + "fonts.rfidEnableNfcTitleText", + "fonts.rfidEnableNfcDescriptionText", + "fonts.rfidEnableNfcButtonText", + "fonts.mdlEnableNfcTitleText", + "fonts.mdlEnableNfcDescriptionText", + "fonts.mdlEnableNfcButtonText", + "images.rfidEnableNfcImage", + "images.rfidDisableNfcImage", + "images.mdlEnableNfcImage", + "images.mdlDisableNfcImage", + "matrices", + ]) + } + + func test_functionality() { + compare(name: "functionality", fromJson: RGLWJSONConstructor.functionality, generate: RGLWJSONConstructor.generate, + omit: ["useAuthenticator", + "pictureOnBoundsReady", + "isCameraTorchCheckDisabled", + "rfidTimeout", + "exposure", + "videoRecordingSizeDownscaleFactor", + "excludedCamera2Models", + "cameraSize", + "hideStatusBar", + "cameraMode"]) + } + + // info + + func test_documentsDatabase() { + compare(name: "documentsDatabase", fromJson: RGLWJSONConstructor.docReaderDocumentsDatabase, generate: RGLWJSONConstructor.generate) + } + + func test_docReaderScenario() { + compare(name: "docReaderScenario", fromJson: RGLWJSONConstructor.scenario, generate: RGLWJSONConstructor.generate) + } + + func test_docReaderException() { + compare(name: "docReaderException", fromJson: RGLWJSONConstructor.error, generate: RGLWJSONConstructor.generateError) + } + + // results.authenticity + + func test_authenticityElement() { + compare(name: "authenticityElement", fromJson: RGLWJSONConstructor.authenticityElement, generate: RGLWJSONConstructor.generate) + } + + func test_authenticityCheck() { + compare(name: "authenticityCheck", fromJson: RGLWJSONConstructor.authenticityCheck, generate: RGLWJSONConstructor.generate) + } + + func test_authenticityResult() { + compare(name: "authenticityResult", fromJson: RGLWJSONConstructor.documentReaderAuthenticityResult, generate: RGLWJSONConstructor.generate) + } + + // results.barcode + + func test_pdf417Info() { + compare(name: "pdf417Info", fromJson: RGLWJSONConstructor.pdf417Info, generate: RGLWJSONConstructor.generate) + } + + func test_barcodeField() { + compare(name: "barcodeField", fromJson: RGLWJSONConstructor.documentReaderBarcodeField, generate: RGLWJSONConstructor.generate) + } + + func test_barcodeResult() { + compare(name: "barcodeResult", fromJson: RGLWJSONConstructor.documentReaderBarcodeResult, generate: RGLWJSONConstructor.generate) + } + + // results.image_quality + + func test_imageQuality() { + compare(name: "imageQuality", fromJson: RGLWJSONConstructor.imageQuality, generate: RGLWJSONConstructor.generate) + } + + func test_imageQualityGroup() { + compare(name: "imageQualityGroup", fromJson: RGLWJSONConstructor.imageQualityGroup, generate: RGLWJSONConstructor.generate) + } + + // results.rfid + + func test_accessControlProcedureType() { + compare(name: "accessControlProcedureType", fromJson: RGLWJSONConstructor.accessControlProcedureType, generate: RGLWJSONConstructor.generate) + } + + func test_fileData() { + compare(name: "fileData", fromJson: RGLWJSONConstructor.fileData, generate: RGLWJSONConstructor.generate) + } + + func test_certificateData() { + compare(name: "certificateData", fromJson: RGLWJSONConstructor.certificateData, generate: RGLWJSONConstructor.generate) + } + + func test_securityObjectCertificates() { + compare(name: "securityObjectCertificates", fromJson: RGLWJSONConstructor.securityObjectCertificates, generate: RGLWJSONConstructor.generate) + } + + func test_file() { + compare(name: "file", fromJson: RGLWJSONConstructor.file, generate: RGLWJSONConstructor.generate) + } + + func test_application() { + compare(name: "application", fromJson: RGLWJSONConstructor.application, generate: RGLWJSONConstructor.generate) + } + + func test_rfidValue() { + compare(name: "rfidValue", fromJson: RGLWJSONConstructor.rfidValue, generate: RGLWJSONConstructor.generate) + } + + func test_attribute() { + compare(name: "attribute", fromJson: RGLWJSONConstructor.attribute, generate: RGLWJSONConstructor.generate) + } + + func test_authority() { + compare(name: "authority", fromJson: RGLWJSONConstructor.authority, generate: RGLWJSONConstructor.generate) + } + + func test_cardProperties() { + compare(name: "cardProperties", fromJson: RGLWJSONConstructor.cardProperties, generate: RGLWJSONConstructor.generate) + } + + func test_extension() { + compare(name: "extension", fromJson: RGLWJSONConstructor.extension, generate: RGLWJSONConstructor.generate) + } + + func test_rfidValidity() { + compare(name: "rfidValidity", fromJson: RGLWJSONConstructor.validity, generate: RGLWJSONConstructor.generate) + } + + func test_certificateChain() { + compare(name: "certificateChain", fromJson: RGLWJSONConstructor.certificateChain, generate: RGLWJSONConstructor.generate) + } + + func test_dataField() { + compare(name: "dataField", fromJson: RGLWJSONConstructor.dataField, generate: RGLWJSONConstructor.generate) + } + + func test_signerInfo() { + compare(name: "signerInfo", fromJson: RGLWJSONConstructor.signerInfo, generate: RGLWJSONConstructor.generate) + } + + func test_securityObject() { + compare(name: "securityObject", fromJson: RGLWJSONConstructor.securityObject, generate: RGLWJSONConstructor.generate) + } + + func test_rfidSessionData() { + compare(name: "rfidSessionData", fromJson: RGLWJSONConstructor.rfidSessionData, generate: RGLWJSONConstructor.generate) + } + + func test_bytesData() { + compare(name: "sytesData", fromJson: RGLWJSONConstructor.bytesData, generate: RGLWJSONConstructor.generate) + } + + func test_vdsncData() { + compare(name: "vdsncData", fromJson: RGLWJSONConstructor.vdsncData, generate: RGLWJSONConstructor.generate) + } + + func test_docFeature() { + compare(name: "docFeature", fromJson: RGLWJSONConstructor.docFeature, generate: RGLWJSONConstructor.generate) + } + + func test_vdsData() { + compare(name: "vdsData", fromJson: RGLWJSONConstructor.vdsData, generate: RGLWJSONConstructor.generate) + } + + // results.status + + func test_opticalStatus() { + compare(name: "opticalStatus", fromJson: RGLWJSONConstructor.opticalStatus, generate: RGLWJSONConstructor.generate) + } + + func test_rfidStatus() { + compare(name: "rfidStatus", fromJson: RGLWJSONConstructor.rfidSessionDataStatus, generate: RGLWJSONConstructor.generate) + } + + func test_ageStatus() { + compare(name: "ageStatus", fromJson: RGLWJSONConstructor.detailsAge, generate: RGLWJSONConstructor.generate) + } + + func test_resultsStatus() { + compare(name: "resultsStatus", fromJson: RGLWJSONConstructor.documentReaderResultsStatus, generate: RGLWJSONConstructor.generate, + omit: ["captureProcessIntegrity"]) + } + + // results.visual_results + + func test_rect() { + do{ + var rect = try readJSONFile(forName: "rect") + XCTAssertEqual(rect as NSDictionary?, RGLWJSONConstructor.generate(RGLWJSONConstructor.rect(fromJson: rect))! as NSDictionary?) + rect = try readJSONFile(forName: "rectNullable") + XCTAssertEqual(rect as NSDictionary?, RGLWJSONConstructor.generate(RGLWJSONConstructor.rect(fromJson: rect))! as NSDictionary?) + }catch{} + } + + func test_Comparison() { + compare(name: "comparison", fromJson: RGLWJSONConstructor.documentReaderComparison, generate: RGLWJSONConstructor.generate) + } + + func test_GraphicField() { + compare(name: "graphicField", fromJson: RGLWJSONConstructor.documentReaderGraphicField, generate: RGLWJSONConstructor.generate) + } + + func test_GraphicResult() { + compare(name: "graphicResult", fromJson: RGLWJSONConstructor.documentReaderGraphicResult, generate: RGLWJSONConstructor.generate) + } + + func test_rfidOrigin() { + compare(name: "rfidOrigin", fromJson: RGLWJSONConstructor.documentReaderRfidOrigin, generate: RGLWJSONConstructor.generate) + } + + func test_symbol() { + compare(name: "symbol", fromJson: RGLWJSONConstructor.documentReaderSymbol, generate: RGLWJSONConstructor.generate) + } + + func test_validity() { + compare(name: "validity", fromJson: RGLWJSONConstructor.documentReaderValidity, generate: RGLWJSONConstructor.generate) + } + + func test_value() { + compare(name: "value", fromJson: RGLWJSONConstructor.documentReaderValue, generate: RGLWJSONConstructor.generate) + } + + func test_textField() { + compare(name: "textField", fromJson: RGLWJSONConstructor.documentReaderTextField, generate: RGLWJSONConstructor.generate) + } + + func test_textSource() { + compare(name: "textSource", fromJson: RGLWJSONConstructor.documentReaderTextSource, generate: RGLWJSONConstructor.generate) + } + + func test_textResult() { + compare(name: "textResult", fromJson: RGLWJSONConstructor.documentReaderTextResult, generate: RGLWJSONConstructor.generate) + } + + // results + + func test_documentType() { + compare(name: "documentType", fromJson: RGLWJSONConstructor.documentReaderDocumentType, generate: RGLWJSONConstructor.generate) + } + + func test_coordinate() { + do{ + var coordinate = try readJSONFile(forName: "coordinate") + XCTAssertEqual(coordinate as NSDictionary?, RGLWJSONConstructor.generate(RGLWJSONConstructor.point(fromJson: coordinate))! as NSDictionary?) + coordinate = try readJSONFile(forName: "coordinateNullable") + XCTAssertEqual(coordinate as NSDictionary?, RGLWJSONConstructor.generate(RGLWJSONConstructor.point(fromJson: coordinate))! as NSDictionary?) + } catch {} + } + + func test_position() { + compare(name: "position", fromJson: RGLWJSONConstructor.position, generate: RGLWJSONConstructor.generate) + } + + func test_transactionInfo() { + compare(name: "transactionInfo", fromJson: RGLWJSONConstructor.transactionInfo, generate: RGLWJSONConstructor.generate) + } + + func test_results() { + compare(name: "results", fromJson: RGLWJSONConstructor.documentReaderResults, generate: RGLWJSONConstructor.generate, + omit: ["status.captureProcessIntegrity"]); + } + + // rfid + + func test_paAttribute() { + compare(name: "paAttribute", fromJson: RGLWJSONConstructor.paAttribute, generate: RGLWJSONConstructor.generate) + } + + func test_paResourcesIssuer() { +// compare(name: "paResourcesIssuer", fromJson: RGLWJSONConstructor.paResourcesIssuer, generate: RGLWJSONConstructor.generate) + } + + func test_pkdCertificate() { + compare(name: "pkdCertificate", fromJson: RGLWJSONConstructor.pkdCertificate, generate: RGLWJSONConstructor.generate) + } + + func test_taChallenge() { + compare(name: "taChallenge", fromJson: RGLWJSONConstructor.taChallenge, generate: RGLWJSONConstructor.generate) + } + + func test_TccParams() { + compare(name: "tccParams", fromJson: RGLWJSONConstructor.tccParams, generate: RGLWJSONConstructor.generate) + } + + func test_paceProtocol() { + compare(name: "paceProtocol", fromJson: RGLWJSONConstructor.paceProtocol, generate: RGLWJSONConstructor.generatePaceProtocol) + } + + func test_caProtocol() { + compare(name: "caProtocol", fromJson: RGLWJSONConstructor.caProtocol, generate: RGLWJSONConstructor.generateCaProtocol) + } + + // mdl + + func test_deviceRetrievalMethod() { + compare(name: "deviceRetrievalMethod", fromJson: RGLWJSONConstructor.deviceRetrievalMethod, generate: RGLWJSONConstructor.generate) + } + func test_deviceEngagement() { + compare(name: "deviceEngagement", fromJson: RGLWJSONConstructor.deviceEngagement, generate: RGLWJSONConstructor.generate) + } + func test_nameSpaceMDL() { + compare(name: "nameSpaceMDL", fromJson: RGLWJSONConstructor.nameSpaceMDL, generate: RGLWJSONConstructor.generate) + } + func test_documentRequestMDL() { + compare(name: "documentRequestMDL", fromJson: RGLWJSONConstructor.documentRequestMDL, generate: RGLWJSONConstructor.generate) + } + func test_documentRequest18013MDL() { + compare(name: "documentRequest18013MDL", fromJson: RGLWJSONConstructor.documentRequest18013MDL, generate: RGLWJSONConstructor.generate) + } + func test_dataRetrieval() { + compare(name: "dataRetrieval", fromJson: RGLWJSONConstructor.dataRetrieval, generate: RGLWJSONConstructor.generate) + } +} diff --git a/example/ios/Tests/Utils.swift b/example/ios/Tests/Utils.swift new file mode 100644 index 0000000000..18381ed850 --- /dev/null +++ b/example/ios/Tests/Utils.swift @@ -0,0 +1,82 @@ +import XCTest + +func compare(name: String, + fromJson: ([AnyHashable : Any]?) -> T?, + generate: (T?) -> [AnyHashable: Any]?, + omit: [String] = [] +) { + compareSingle(name: name, fromJson: fromJson, generate: generate, omit: omit) + compareSingle(name: name + "Nullable", fromJson: fromJson, generate: generate, omit: omit) +} + +func compareSingle(name: String, + fromJson: ([AnyHashable : Any]?) -> T?, + generate: (T?) -> [AnyHashable: Any]?, + omit: [String] = [] +) { + do { + var expected = try readJSONFile(forName: name) + for s in omit { + expected = omitDeep(dict: expected, path: s.components(separatedBy: "."), index: 0) + } + var actual = generate(fromJson(expected))! + for s in omit { + actual = omitDeep(dict: actual as! [String: Any], path: s.components(separatedBy: "."), index: 0) + } + actual = removeNulls(input: actual as! [String: Any]) + XCTAssertEqual(expected as NSDictionary, actual as NSDictionary) + } catch { } +} + +func omitDeep(dict: [String: Any], path: [String], index: Int) -> [String: Any] { + var mutableDict = dict + if (index < path.count - 1) { + if(dict[path[index]] == nil) { + return dict // not found + } + let node = dict[path[index]] + if (node is [String : Any]) { + mutableDict[path[index]] = omitDeep(dict: node as! [String : Any], path: path, index: index + 1) + } else if (node is Array) { + mutableDict[path[index]] = omitDeep(arr: node as! Array, path: path, index: index + 1) + } + } else { + mutableDict.removeValue(forKey: path[index]) + } + return mutableDict +} + +func omitDeep(arr: Array, path: [String], index: Int) -> Array { + var mutableArr = arr + for (i, item) in arr.enumerated() { + mutableArr[i] = omitDeep(dict: item as! [String : Any], path: path, index: index) + } + return mutableArr +} + +func removeNulls(input: [String: Any]) -> [String: Any] { + var result = input + for (key, value) in input { + if (value as! NSObject == NSNull()) { + result.removeValue(forKey: key) + } else if (value is [String: Any]) { + result[key] = removeNulls(input: value as! [String: Any]) + } + } + return result +} + +func readJSONFile(forName name: String) throws -> [String: Any] { + do { + let path = Bundle(for: Tests.self).path(forResource: "json/" + name, ofType: "json") + if(path == nil){ + throw "file not found" + } + let data = try String(contentsOfFile: path!).data(using: .utf8)! + return try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [String: Any] + } catch { + throw(error) + } +} + +extension String: Error {} diff --git a/example/lib/extra/bt_device.dart b/example/lib/extra/bt_device.dart new file mode 100644 index 0000000000..2630d32f6c --- /dev/null +++ b/example/lib/extra/bt_device.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_document_reader_api/flutter_document_reader_api.dart'; +import 'package:flutter_document_reader_api_example/main.dart'; + +var useBtDevice = false; +var btDeviceName = "Regula 0000"; + +void setupBTDevice() { + setStatus("Connect to a bluetooth device"); +} + +void connect() async { + setStatus("Searching for devices..."); + if (await DocumentReader.instance.connectBluetoothDevice(btDeviceName)) { + await init(); + DocumentReader.instance.functionality.useAuthenticator = true; + useBtDevice = false; + } else { + setStatus("Failed to connect"); + } +} + +Future initializeWithBTDevice() async { + setStatus("Initializing..."); + + var initConfig = InitConfig.withBleDevice(); + initConfig.delayedNNLoad = true; + var (success, error) = await DocumentReader.instance.initialize(initConfig); + + handleException(error); + return success; +} + +Widget btDeviceUI() { + return Visibility( + visible: useBtDevice, + child: Row(children: [Expanded(child: button("Connect", () => connect()))]), + ); +} diff --git a/example/lib/extra/rfid_custom_ui.dart b/example/lib/extra/rfid_custom_ui.dart new file mode 100644 index 0000000000..efdf1dd842 --- /dev/null +++ b/example/lib/extra/rfid_custom_ui.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_document_reader_api/flutter_document_reader_api.dart'; +import 'package:flutter_document_reader_api_example/main.dart'; + +var useRfidSelfHostedUI = false; + +void rfidSelfHostedUI() { + var config = RFIDConfig.withoutUI((action, results, _) { + action.stopped() ? stop() : null; + action.finished() ? displayResults(results) : null; + action.interrupted() ? setStatus("Error reading RFID") : null; + }); + + config.onProgress = (notification) async { + if (notification.progress == 1) return; + if (notification.notificationCode == + RFIDNotificationCodes.PCSC_READING_DATAGROUP) { + setDescription(await notification.dataFileType.getTranslation()); + } + setStatus("Reading RFID"); + setProgress(notification.progress); + }; + + setup(); + DocumentReader.instance.rfid(config); +} + +void setup() { + setStatus("Reading RFID"); + setDescription("Place your phone on top of the NFC tag"); + setProgress(-1); + currentProgress = -1; + setShowing(true); +} + +void stop() { + DocumentReader.instance.stopRFIDReader(); + displayResults(null); + setShowing(false); +} + +var rfidDescription = "Place your phone on top of the NFC tag"; +void setDescription(String data) { + MyAppState.update(() => rfidDescription = data); +} + +var currentProgress = -1; +var isIncreasing = true; +void setProgress(int next) { + // make progress bar look better + if (next == 0) return; // ignore idle 0s, leave progress at 100 instead + if (next < currentProgress) next = 0; // move to 0 if progress is moving + if (next >= 95) next = 100; // rfid never returns 100 and it looks ugly + + MyAppState.update(() => isIncreasing = next > currentProgress); + MyAppState.update(() => currentProgress = next); +} + +var isShowingRfidSelfHostedUI = false; +void setShowing(bool data) { + MyAppState.update(() => isShowingRfidSelfHostedUI = data); +} + +List rfidCustomUI() { + return [ + label(rfidDescription), + TweenAnimationBuilder( + tween: Tween(begin: currentProgress / 100, end: currentProgress / 100), + duration: Duration(milliseconds: isIncreasing ? 500 : 0), + builder: (context, value, child) => Container( + width: MediaQuery.of(context).size.width * 0.75, + margin: EdgeInsets.only(top: 30), + decoration: BoxDecoration( + border: Border.all(color: Colors.black26, width: 3), + borderRadius: BorderRadius.circular(8), + ), + child: LinearProgressIndicator( + value: value, + minHeight: 20, + backgroundColor: Colors.white, + borderRadius: BorderRadius.all(Radius.circular(4)), + ), + ), + ), + TextButton( + onPressed: () => stop(), + child: Text("X"), + style: TextButton.styleFrom( + padding: EdgeInsets.only(top: 50), + textStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), + ), + SizedBox(height: 100) + ]; +} diff --git a/example/lib/main.dart b/example/lib/main.dart index fba878e664..9cfcee86cb 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,357 +1,285 @@ -import 'dart:convert'; -import 'dart:io' as io; -import 'dart:io'; -import 'dart:typed_data'; import 'package:flutter/material.dart'; +import 'package:flutter_document_reader_api_example/extra/bt_device.dart'; +import 'package:flutter_document_reader_api_example/extra/rfid_custom_ui.dart'; import 'dart:async'; -import 'package:flutter/services.dart' - show EventChannel, PlatformException, rootBundle; -import 'package:flutter_document_reader_api/document_reader.dart'; import 'package:image_picker/image_picker.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_document_reader_api/flutter_document_reader_api.dart'; -void main() => runApp(MyApp()); +void main() => runApp(new MaterialApp(home: new MyApp())); +var documentReader = DocumentReader.instance; +var selectedScenario = Scenario.MRZ; +var doRfid = false; +var isReadingRfid = false; -class MyApp extends StatefulWidget { - @override - _MyAppState createState() => _MyAppState(); +Future init() async { + if (!await initialize()) return; + setScenarios(documentReader.availableScenarios); + setCanRfid(await documentReader.isRFIDAvailableForUse()); + setStatus("Ready"); } -class _MyAppState extends State { - Future> getImages() async { - setStatus("Processing image..."); - List? files = await ImagePicker().pickMultiImage(); - List result = []; - for (XFile file in files) - result.add(base64Encode(io.File(file.path).readAsBytesSync())); - return result; - } +void scan() async { + if (!await documentReader.isReady) return; + clearResults(); + documentReader.startScanner( + ScannerConfig.withScenario(selectedScenario), + handleCompletion, + ); +} - Object setStatus(String s) => {setState(() => _status = s)}; - String _status = "Loading..."; - bool isReadingRfidCustomUi = false; - bool isReadingRfid = false; - String rfidUIHeader = "Reading RFID"; - Color rfidUIHeaderColor = Colors.black; - String rfidDescription = "Place your phone on top of the NFC tag"; - double rfidProgress = -1; - var _portrait = Image.asset('assets/images/portrait.png'); - var _docImage = Image.asset('assets/images/id.png'); - List> _scenarios = []; - String _selectedScenario = "Mrz"; - bool _canRfid = false; - bool _doRfid = false; - var printError = - (Object error) => print((error as PlatformException).message); +void recognize() async { + if (!await documentReader.isReady) return; + var image = await pickImage(); + if (image == null) return; - @override - void initState() { - super.initState(); - initPlatformState(); - const EventChannel('flutter_document_reader_api/event/completion') - .receiveBroadcastStream() - .listen((jsonString) => this.handleCompletion( - DocumentReaderCompletion.fromJson(json.decode(jsonString))!)); - const EventChannel('flutter_document_reader_api/event/database_progress') - .receiveBroadcastStream() - .listen((progress) => setStatus("Downloading database: $progress%")); + clearResults(); + documentReader.recognize( + RecognizeConfig.withScenario(selectedScenario, image: image), + handleCompletion, + ); +} + +void handleCompletion( + DocReaderAction action, + Results? results, + DocReaderException? error, +) { + handleException(error); + if (action.stopped() && !shouldRfid(results)) { + displayResults(results); + } else if (action.finished() && shouldRfid(results)) { + isReadingRfid = true; + readRfid(); } +} - void addCertificates() async { - List certificates = []; - final manifestJson = - await DefaultAssetBundle.of(context).loadString('AssetManifest.json'); - final certPaths = json - .decode(manifestJson) - .keys - .where((String key) => key.startsWith('assets/certificates')); - - for (var path in certPaths) { - var findExt = path.split('.'); - var pkdResourceType = 0; - if (findExt.length > 0) - pkdResourceType = - PKDResourceType.getType(findExt[findExt.length - 1].toLowerCase()); - ByteData byteData = await rootBundle.load(path); - var certBase64 = base64.encode(byteData.buffer - .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes)); - certificates - .add({"binaryData": certBase64, "resourceType": pkdResourceType}); - } +void displayResults(Results? results) async { + isReadingRfid = false; + clearResults(); + if (results == null) return; - DocumentReader.addPKDCertificates(certificates) - .then((value) => print("certificates added")); - } + var name = + await results.textFieldValueByType(FieldType.SURNAME_AND_GIVEN_NAMES); + var docImage = + await results.graphicFieldImageByType(GraphicFieldType.DOCUMENT_IMAGE); + var portrait = + await results.graphicFieldImageByType(GraphicFieldType.PORTRAIT); + portrait = await results.graphicFieldImageByTypeSource( + GraphicFieldType.PORTRAIT, + ResultType.RFID_IMAGE_DATA, + ) ?? + portrait; - void handleCompletion(DocumentReaderCompletion completion) { - print("DocReaderAction: ${completion.action}"); - if (isReadingRfidCustomUi && - (completion.action == DocReaderAction.CANCEL || - completion.action == DocReaderAction.ERROR)) this.hideRfidUI(); - if (isReadingRfidCustomUi && - completion.action == DocReaderAction.NOTIFICATION) - this.updateRfidUI(completion.results!.documentReaderNotification); - if (completion.action == - DocReaderAction.COMPLETE) if (isReadingRfidCustomUi) if (completion - .results!.rfidResult != - 1) - this.restartRfidUI(); - else { - this.hideRfidUI(); - this.displayResults(completion.results!); - } - else - this.handleResults(completion.results!); - if (completion.action == DocReaderAction.TIMEOUT) - this.handleResults(completion.results!); - } + setStatus(name); + setPortrait(portrait); + setDocImage(docImage); +} - void showRfidUI() { - // show animation - setState(() => isReadingRfidCustomUi = true); - } +var readRfid = () => documentReader.rfid(RFIDConfig(handleCompletion)); - hideRfidUI() { - // show animation - this.restartRfidUI(); - DocumentReader.stopRFIDReader(); - setState(() { - isReadingRfidCustomUi = false; - rfidUIHeader = "Reading RFID"; - rfidUIHeaderColor = Colors.black; - }); - } +bool shouldRfid(Results? results) => + doRfid && !isReadingRfid && results != null && results.chipPage != 0; - restartRfidUI() { - setState(() { - rfidUIHeaderColor = Colors.red; - rfidUIHeader = "Failed!"; - rfidDescription = "Place your phone on top of the NFC tag"; - rfidProgress = -1; - }); - } +var initialize = () async { + setStatus("Initializing..."); - updateRfidUI(results) { - if (results.notificationCode == - ERFIDNotificationCodes.RFID_NOTIFICATION_PCSC_READING_DATAGROUP) - setState(() => rfidDescription = "ERFIDDataFileType: " + results.dataFileType); - setState(() { - rfidUIHeader = "Reading RFID"; - rfidUIHeaderColor = Colors.black; - rfidProgress = results.progress / 100; - }); - if (Platform.isIOS) DocumentReader.setRfidSessionStatus("$rfidDescription\n${results.progress.toString()}%"); - } + ByteData license = await rootBundle.load("assets/regula.license"); + var initConfig = InitConfig(license); + initConfig.delayedNNLoad = true; + var (success, error) = await documentReader.initialize(initConfig); - customRFID() { - this.showRfidUI(); - DocumentReader.readRFID(); - } + handleException(error); + return success; +}; - usualRFID() { - isReadingRfid = true; - DocumentReader.startRFIDReader(); +void handleException(DocReaderException? error) { + if (error != null) { + setStatus(error.message); + print("${error.code}: ${error.message}"); } +} - Future initPlatformState() async { - print(await DocumentReader.prepareDatabase("Full")); - setStatus("Initializing..."); - ByteData byteData = await rootBundle.load("assets/regula.license"); - print(await DocumentReader.initializeReader({ - "license": base64.encode(byteData.buffer - .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes)), - "delayedNNLoad": true - })); - setStatus("Ready"); - bool canRfid = await DocumentReader.isRFIDAvailableForUse(); - setState(() => _canRfid = canRfid); - List> scenarios = []; - var scenariosTemp = - json.decode(await DocumentReader.getAvailableScenarios()); - for (var i = 0; i < scenariosTemp.length; i++) { - DocumentReaderScenario scenario = DocumentReaderScenario.fromJson( - scenariosTemp[i] is String - ? json.decode(scenariosTemp[i]) - : scenariosTemp[i])!; - scenarios.add([scenario.name!, scenario.caption!]); - } - setState(() => _scenarios = scenarios); - DocumentReader.setConfig({ - "functionality": { - "videoCaptureMotionControl": true, - "showCaptureButton": true - }, - "customization": { - "showResultStatusMessages": true, - "showStatusMessages": true - }, - "processParams": {"scenario": _selectedScenario} - }); - DocumentReader.setRfidDelegate(RFIDDelegate.NO_PA); - // addCertificates(); - } +// -------------------------------------------------------------------------------------------------------------------- - displayResults(DocumentReaderResults results) async { - var name = await results.textFieldValueByType(EVisualFieldType.FT_SURNAME_AND_GIVEN_NAMES); - var doc = await results.graphicFieldImageByType(EGraphicFieldType.GF_DOCUMENT_IMAGE); - var portrait = await results.graphicFieldImageByType(EGraphicFieldType.GF_PORTRAIT); - setState(() { - _status = name ?? ""; - _docImage = Image.asset('assets/images/id.png'); - _portrait = Image.asset('assets/images/portrait.png'); - if (doc != null) - _docImage = Image.memory(doc.data!.contentAsBytes()); - if (portrait != null) - _portrait = Image.memory(portrait.data!.contentAsBytes()); - }); +var status = "Loading..."; +void setStatus(String? s) { + if (s != null) { + MyAppState.update(() => status = s); } +} - void handleResults(DocumentReaderResults results) { - if (_doRfid && !isReadingRfid && results.chipPage != 0) { - // customRFID(); - usualRFID(); - } else { - isReadingRfid = false; - displayResults(results); - } +var portraitUIImage = Image.asset('assets/images/portrait.png'); +void setPortrait(Uint8List? data) { + if (data != null) { + MyAppState.update(() => portraitUIImage = Image.memory(data)); } +} - void onChangeRfid(bool? value) { - setState(() => _doRfid = value! && _canRfid); - DocumentReader.setConfig({ - "processParams": {"doRfid": _doRfid} - }); +var documentUIImage = Image.asset('assets/images/id.png'); +void setDocImage(Uint8List? data) { + if (data != null) { + MyAppState.update(() => documentUIImage = Image.memory(data)); } +} - Widget createImage( - String title, double height, double width, ImageProvider image) { - return Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text(title), - Image(height: height, width: width, image: image) - ]); - } +void clearResults() { + MyAppState.update(() { + status = "Ready"; + portraitUIImage = Image.asset('assets/images/portrait.png'); + documentUIImage = Image.asset('assets/images/id.png'); + }); +} + +var canRfid = false; +void setCanRfid(bool data) { + MyAppState.update(() => canRfid = data); +} + +List scenarios = []; +void setScenarios(List data) { + MyAppState.update(() => scenarios = data); +} - Widget createButton(String text, VoidCallback onPress) { - return Container( - padding: const EdgeInsets.fromLTRB(5, 0, 5, 0), - transform: Matrix4.translationValues(0, -7.5, 0), - child: TextButton( - style: ButtonStyle( - foregroundColor: MaterialStateProperty.all(Colors.blue), - backgroundColor: MaterialStateProperty.all(Colors.black12), +List ui() { + return [ + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + image("Portrait", portraitUIImage.image), + image("Document image", documentUIImage.image), + ]), + Expanded( + child: Container( + color: Color.fromARGB(5, 0, 0, 0), + margin: EdgeInsets.only(top: 10), + padding: EdgeInsets.only(left: 40), + child: RadioGroup( + groupValue: selectedScenario.value, + onChanged: (value) => MyAppState.update( + () => selectedScenario = Scenario.getByValue(value)!), + child: ListView.builder( + itemCount: scenarios.length, + itemBuilder: (context, int index) => ListTile( + leading: Radio(value: scenarios[index].name), + title: Text(scenarios[index].caption), + onTap: () => MyAppState.update(() => selectedScenario = + Scenario.getByValue(scenarios[index].name)!), + ), ), - onPressed: onPress, - child: Text(text)), - width: 150, - ); - } + ), + ), + ), + CheckboxListTile( + value: doRfid, + title: Text("Process rfid reading" + (canRfid ? "" : " (unavailable)")), + onChanged: (value) => MyAppState.update(() => doRfid = value! && canRfid), + ), + Row(children: [ + Expanded(child: button("Scan document", scan)), + Expanded(child: button("Scan image", recognize)) + ]), + btDeviceUI() + ]; +} + +Widget image(String title, ImageProvider image) => Column(children: [ + Text(title), + Padding( + padding: EdgeInsets.all(5), + child: Image(height: 150, image: image), + ) + ]); + +Widget button(String text, VoidCallback onPressed) => Padding( + padding: EdgeInsets.all(5), + child: SizedBox( + height: 40, + child: FilledButton(onPressed: onPressed, child: Text(text)), + )); + +Widget label(String text, {bool small = false}) => Text(text, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: small ? 15 : 18, + fontWeight: FontWeight.w600, + )); - Widget _buildRow(int index) { - Radio radio = new Radio( - value: _scenarios[index][0], - groupValue: _selectedScenario, - onChanged: (value) => setState(() { - _selectedScenario = value; - })); - return Container( - child: ListTile( - title: GestureDetector( - onTap: () => radio.onChanged!(_scenarios[index][0]), - child: Text(_scenarios[index][1])), - leading: radio), - padding: const EdgeInsets.only(left: 40)); +Widget header(List children, {bool top = true}) => Container( + padding: EdgeInsets.only(top: top ? 70 : 13), + color: Colors.black.withValues(alpha: 0.03), + child: Column(children: [ + ...children, + Container( + margin: EdgeInsets.only(top: 13), + child: Divider( + height: 1, + thickness: 1, + color: Color.fromRGBO(0, 0, 0, 0.075), + ), + ), + ])); + +// -------------------------------------------------------------------------------------------------------------------- + +Future pickImage() async { + XFile? file = await ImagePicker().pickImage(source: ImageSource.gallery); + if (file == null) return null; + return await file.readAsBytes(); +} + +class MyAppState extends State { + @override + void initState() { + super.initState(); + instance = this; + + // custom rfid + if (useRfidSelfHostedUI) readRfid = () => rfidSelfHostedUI(); + + // bt device + if (!useBtDevice) { + init(); + } else { + setupBTDevice(); + initialize = initializeWithBTDevice; + } } @override - Widget build(BuildContext context) { - return MaterialApp( + Widget build(_) => MaterialApp( + theme: ThemeData(colorScheme: theme), home: Scaffold( - appBar: AppBar(title: Center(child: Text(_status))), - body: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Visibility( - visible: isReadingRfidCustomUi, - child: Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: const []), - Container( - child: Text(rfidUIHeader, - textScaleFactor: 1.75, - style: TextStyle(color: rfidUIHeaderColor)), - padding: const EdgeInsets.only(bottom: 40)), - Container( - child: - Text(rfidDescription, textScaleFactor: 1.4), - padding: const EdgeInsets.only(bottom: 40)), - FractionallySizedBox( - widthFactor: 0.6, - child: LinearProgressIndicator( - value: rfidProgress, - minHeight: 10, - valueColor: - const AlwaysStoppedAnimation( - Color(0xFF4285F4)))), - TextButton( - onPressed: () => hideRfidUI(), - child: const Text("X"), - style: TextButton.styleFrom( - padding: const EdgeInsets.only(top: 50)), - ), - ]))), - Visibility( - visible: !isReadingRfidCustomUi, - child: Expanded( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - createImage( - "Portrait", 150, 150, _portrait.image), - createImage("Document image", 150, 200, - _docImage.image), - ]), - Expanded( - child: Container( - color: const Color.fromARGB(5, 10, 10, 10), - child: ListView.builder( - itemCount: _scenarios.length, - itemBuilder: - (BuildContext context, int index) => - _buildRow(index)))), - CheckboxListTile( - value: _doRfid, - onChanged: onChangeRfid, - title: Text( - "Process rfid reading ${_canRfid ? "" : "(unavailable)"}")), - Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - createButton("Scan document", () { - var config = new ScannerConfig(); - config.scenario = _selectedScenario; - DocumentReader.scan(config.toJson()); - }), - createButton("Scan image", () async { - var config = new RecognizeConfig(); - config.scenario = _selectedScenario; - config.images = await getImages(); - DocumentReader.recognize(config.toJson()); - }), - ]) - ]))), - ])), - ); + body: Column(children: [ + header([label(status)]), + Visibility( + visible: !isShowingRfidSelfHostedUI, + child: Expanded( + child: Padding( + padding: EdgeInsets.fromLTRB(10, 10, 10, 35), + child: Column(children: ui()), + ), + ), + ), + Visibility( + visible: isShowingRfidSelfHostedUI, + child: Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: rfidCustomUI(), + ), + ), + ) + ]), + )); + + static final theme = ColorScheme.fromSwatch(accentColor: Color(0xFF4285F4)); + static late MyAppState instance; + static update(VoidCallback state) => {instance.setState(state)}; +} + +class MyApp extends StatefulWidget { + @override + MyAppState createState() { + SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + return MyAppState(); } } diff --git a/example/pubspec.lock b/example/pubspec.lock new file mode 100644 index 0000000000..f3e3795ccd --- /dev/null +++ b/example/pubspec.lock @@ -0,0 +1,465 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63 + url: "https://pub.dev" + source: hosted + version: "2.12.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" + url: "https://pub.dev" + source: hosted + version: "0.3.4+2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc" + url: "https://pub.dev" + source: hosted + version: "1.3.2" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33" + url: "https://pub.dev" + source: hosted + version: "0.9.3+2" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc" + url: "https://pub.dev" + source: hosted + version: "0.9.4+2" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b + url: "https://pub.dev" + source: hosted + version: "2.6.2" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "320fcfb6f33caa90f0b58380489fc5ac05d99ee94b61aa96ec2bff0ba81d3c2b" + url: "https://pub.dev" + source: hosted + version: "0.9.3+4" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_document_reader_api: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "7.5.1093" + flutter_document_reader_btdevice: + dependency: "direct main" + description: + name: flutter_document_reader_btdevice + sha256: "6282a7cfe3731756df24f79925e995329110a35e233e7a3f2857dc2521a588b9" + url: "https://pub.dev" + source: hosted + version: "7.5.41" + flutter_document_reader_core_fullauthrfid: + dependency: "direct main" + description: + name: flutter_document_reader_core_fullauthrfid + sha256: "3a258f5bd26e988db0419a591941af9d67741e4bc1287ea78231c7b4a1693515" + url: "https://pub.dev" + source: hosted + version: "7.5.887" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "5a1e6fb2c0561958d7e4c33574674bda7b77caaca7a33b758876956f2902eea3" + url: "https://pub.dev" + source: hosted + version: "2.0.27" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + http: + dependency: transitive + description: + name: http + sha256: fe7ab022b76f3034adc518fb6ea04a82387620e19977665ea18d30a1cf43442f + url: "https://pub.dev" + source: hosted + version: "1.3.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "021834d9c0c3de46bf0fe40341fa07168407f694d9b2bb18d532dc1261867f7a" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "82652a75e3dd667a91187769a6a2cc81bd8c111bbead698d8e938d2b63e5e89a" + url: "https://pub.dev" + source: hosted + version: "0.8.12+21" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "717eb042ab08c40767684327be06a5d8dbb341fe791d514e4b92c7bbe1b7bb83" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "05da758e67bc7839e886b3959848aa6b44ff123ab4b28f67891008afe8ef9100" + url: "https://pub.dev" + source: hosted + version: "0.8.12+2" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "4ed1d9bb36f7cd60aa6e6cd479779cc56a4cb4e4de8f49d487b1aaad831300fa" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "1b90ebbd9dcf98fb6c1d01427e49a55bd96b5d67b8c67cf955d60a5de74207c1" + url: "https://pub.dev" + source: hosted + version: "0.2.1+2" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "886d57f0be73c4b140004e78b9f28a8914a09e50c2d816bdd0520051a71236a0" + url: "https://pub.dev" + source: hosted + version: "2.10.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: "6ad07afc4eb1bc25f3a01084d28520496c4a3bb0cb13685435838167c9dcedeb" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec + url: "https://pub.dev" + source: hosted + version: "10.0.8" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14" + url: "https://pub.dev" + source: hosted + version: "14.3.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" +sdks: + dart: ">=3.7.0 <4.0.0" + flutter: ">=3.27.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml index c852de2174..c481807b57 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,28 +1,30 @@ name: flutter_document_reader_api_example description: Demonstrates how to use the flutter_document_reader_api plugin. - -publish_to: 'none' +publish_to: none +version: 1.0.0 environment: - sdk: ">=2.12.0 <3.0.0" + sdk: '>=3.1.5 <4.0.0' + flutter: '>=3.10.0' dependencies: - path_provider: ^2.0.5 - image_picker: ^0.8.4+2 + path_provider: ^2.1.5 + image_picker: ^1.1.2 flutter: sdk: flutter flutter_document_reader_api: path: ../ - flutter_document_reader_core_fullrfid: 6.9.0 - cupertino_icons: ^1.0.3 + flutter_document_reader_core_fullauthrfid: 9.6.2546-nightly + flutter_document_reader_btdevice: 9.5.56-rc + cupertino_icons: ^1.0.8 dev_dependencies: flutter_test: sdk: flutter + lints: ^5.0.0 flutter: assets: + - assets/ - assets/images/ - - assets/regula.license - - assets/certificates/ uses-material-design: true diff --git a/flutter_document_reader_api.iml b/flutter_document_reader_api.iml deleted file mode 100644 index 1a852c417c..0000000000 --- a/flutter_document_reader_api.iml +++ /dev/null @@ -1,161 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore deleted file mode 100644 index aa479fd3ce..0000000000 --- a/ios/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ -GeneratedPluginRegistrant.h -GeneratedPluginRegistrant.m - -.generated/ - -*.pbxuser -*.mode1v3 -*.mode2v3 -*.perspectivev3 - -!default.pbxuser -!default.mode1v3 -!default.mode2v3 -!default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - -/Flutter/Generated.xcconfig -/Flutter/flutter_export_environment.sh \ No newline at end of file diff --git a/ios/Classes/FlutterDocumentReaderApiPlugin.h b/ios/Classes/FlutterDocumentReaderApiPlugin.h index c77faae0d4..a1bd886561 100644 --- a/ios/Classes/FlutterDocumentReaderApiPlugin.h +++ b/ios/Classes/FlutterDocumentReaderApiPlugin.h @@ -1,50 +1,31 @@ #import -#import -#import "RGLWJSONConstructor.h" -#import "RGLWRegulaConfig.h" - -typedef void (^RGLWCallback)(NSString* _Nullable response); - -@interface FlutterDocumentReaderApiPlugin : NSObject - -@property (strong, nonatomic, class) FlutterMethodChannel* _Nullable channel; -@property (class) NSNumber* _Nullable databasePercentageDownloaded; +#import "RGLWMain.h" +@interface FlutterDocumentReaderApiPlugin : NSObject @end -typedef void (^RGLWRFIDSignatureCallback)(NSData * _Nonnull signature); -@interface RGLWRFIDDelegateNoPA : NSObject -@end +static NSMutableDictionary* _Nonnull eventSinks; -@interface RGLWDatabaseProgressStreamHandler : NSObject -@end @interface RGLWCompletionStreamHandler : NSObject @end - +@interface RGLWDatabaseProgressStreamHandler : NSObject +@end @interface RGLWRfidOnProgressEventStreamHandler : NSObject @end @interface RGLWRfidOnChipDetectedEventStreamHandler : NSObject @end @interface RGLWRfidOnRetryReadChipEventStreamHandler : NSObject @end - @interface RGLWPACertificateCompletionStreamHandler : NSObject @end @interface RGLWTACertificateCompletionStreamHandler : NSObject @end @interface RGLWTASignatureCompletionStreamHandler : NSObject @end - -@interface RGLWBleOnServiceConnectedStreamHandler : NSObject -@end -@interface RGLWBleOnServiceDisconnectedStreamHandler : NSObject +@interface RGLWPACEProtocolCompletionStreamHandler : NSObject @end -@interface RGLWBleOnDeviceReadyStreamHandler : NSObject +@interface RGLWCAProtocolCompletionStreamHandler : NSObject @end - @interface RGLWVideoEncoderCompletionStreamHandler : NSObject @end @interface RGLWOnCustomButtonTappedStreamHandler : NSObject diff --git a/ios/Classes/FlutterDocumentReaderApiPlugin.m b/ios/Classes/FlutterDocumentReaderApiPlugin.m index b9f25465c5..8a2451b622 100644 --- a/ios/Classes/FlutterDocumentReaderApiPlugin.m +++ b/ios/Classes/FlutterDocumentReaderApiPlugin.m @@ -1,1055 +1,197 @@ #import "FlutterDocumentReaderApiPlugin.h" -RGLWRFIDSignatureCallback RGLWTaSignatureCompletion; -RGLRFIDCertificatesCallback RGLWPaCertificateCompletion; -RGLRFIDCertificatesCallback RGLWTaCertificateCompletion; - -FlutterEventSink RGLWDatabaseProgressEvent; -FlutterEventSink RGLWCompletionEvent; - -FlutterEventSink RGLWRfidOnProgressEvent; -FlutterEventSink RGLWRfidOnChipDetectedEvent; -FlutterEventSink RGLWRfidOnRetryReadChipEvent; - -FlutterEventSink RGLWPaCertificateCompletionEvent; -FlutterEventSink RGLWTaCertificateCompletionEvent; -FlutterEventSink RGLWTaSignatureCompletionEvent; - -FlutterEventSink RGLWBleOnServiceConnectedEvent; -FlutterEventSink RGLWBleOnServiceDisconnectedEvent; -FlutterEventSink RGLWBleOnDeviceReadyEvent; +@implementation FlutterDocumentReaderApiPlugin -FlutterEventSink RGLWVideoEncoderCompletionEvent; -FlutterEventSink RGLWOnCustomButtonTappedEvent; +UIViewController*(^RGLWRootViewController)(void) = ^UIViewController*() { + for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) + if ([scene isKindOfClass:[UIWindowScene class]]) { + UIWindowScene *windowScene = (UIWindowScene *)scene; + for (UIWindow *window in windowScene.windows) + if (window.isKeyWindow) + return window.rootViewController; + } + return nil; +}; -RGLWRFIDDelegateNoPA* RGLWRfidDelegateNoPA; ++ (void)registerWithRegistrar:(NSObject*)registrar { + eventSinks = [NSMutableDictionary new]; + void(^setupEventChannel)(NSObject* registrar, NSString*eventId, NSObject*handler) = ^(NSObject* registrar, NSString*eventId, NSObject*handler) { + [[FlutterEventChannel eventChannelWithName:[NSString stringWithFormat:@"%@%@", @"flutter_document_reader_api/event/", eventId] binaryMessenger:[registrar messenger]] setStreamHandler:handler]; + }; + setupEventChannel(registrar, completionEvent, [RGLWCompletionStreamHandler new]); + setupEventChannel(registrar, databaseProgressEvent, [RGLWDatabaseProgressStreamHandler new]); + setupEventChannel(registrar, rfidOnProgressEvent, [RGLWRfidOnProgressEventStreamHandler new]); + setupEventChannel(registrar, rfidOnChipDetectedEvent, [RGLWRfidOnChipDetectedEventStreamHandler new]); + setupEventChannel(registrar, rfidOnRetryReadChipEvent, [RGLWRfidOnRetryReadChipEventStreamHandler new]); + setupEventChannel(registrar, paCertificateCompletionEvent, [RGLWPACertificateCompletionStreamHandler new]); + setupEventChannel(registrar, taCertificateCompletionEvent, [RGLWTACertificateCompletionStreamHandler new]); + setupEventChannel(registrar, taSignatureCompletionEvent, [RGLWTASignatureCompletionStreamHandler new]); + setupEventChannel(registrar, paceProtocolCompletionEvent, [RGLWPACEProtocolCompletionStreamHandler new]); + setupEventChannel(registrar, caProtocolCompletionEvent, [RGLWCAProtocolCompletionStreamHandler new]); + setupEventChannel(registrar, drVideoEncoderCompletionEvent, [RGLWVideoEncoderCompletionStreamHandler new]); + setupEventChannel(registrar, drOnCustomButtonTappedEvent, [RGLWOnCustomButtonTappedStreamHandler new]); -@implementation RGLWCompletionStreamHandler -- (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWCompletionEvent = eventSink; - return nil; + FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"flutter_document_reader_api/method" binaryMessenger:[registrar messenger]]; + [registrar addMethodCallDelegate:[FlutterDocumentReaderApiPlugin new] channel:channel]; } -- (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWCompletionEvent = nil; - return nil; +- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { + RGLWEventSender sendEvent = ^(NSString* event, id data) { + dispatch_async(dispatch_get_main_queue(), ^{ + if (eventSinks[event] != nil) eventSinks[event]([RGLWJSONConstructor toSendable:data]); + }); + }; + + [RGLWMain methodCall:call.method + :call.arguments + :^(id data) { result([RGLWJSONConstructor toSendable:data]); } + :sendEvent]; } + @end -@implementation RGLWVideoEncoderCompletionStreamHandler + +@implementation RGLWCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWVideoEncoderCompletionEvent = eventSink; - return nil; + eventSinks[completionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWVideoEncoderCompletionEvent = nil; - return nil; + eventSinks[completionEvent] = nil; + return nil; } @end @implementation RGLWDatabaseProgressStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWDatabaseProgressEvent = eventSink; - return nil; + eventSinks[databaseProgressEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWDatabaseProgressEvent = nil; - return nil; + eventSinks[databaseProgressEvent] = nil; + return nil; } + @end @implementation RGLWRfidOnProgressEventStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWRfidOnProgressEvent = eventSink; - return nil; + eventSinks[rfidOnProgressEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWRfidOnProgressEvent = nil; - return nil; + eventSinks[rfidOnProgressEvent] = nil; + return nil; } @end @implementation RGLWRfidOnChipDetectedEventStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWRfidOnChipDetectedEvent = eventSink; - return nil; + eventSinks[rfidOnChipDetectedEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWRfidOnChipDetectedEvent = nil; - return nil; + eventSinks[rfidOnChipDetectedEvent] = nil; + return nil; } @end @implementation RGLWRfidOnRetryReadChipEventStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWRfidOnRetryReadChipEvent = eventSink; - return nil; + eventSinks[rfidOnRetryReadChipEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWRfidOnRetryReadChipEvent = nil; - return nil; + eventSinks[rfidOnRetryReadChipEvent] = nil; + return nil; } @end @implementation RGLWPACertificateCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWPaCertificateCompletionEvent = eventSink; - return nil; + eventSinks[paCertificateCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWPaCertificateCompletionEvent = nil; - return nil; + eventSinks[paCertificateCompletionEvent] = nil; + return nil; } @end @implementation RGLWTACertificateCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWTaCertificateCompletionEvent = eventSink; - return nil; + eventSinks[taCertificateCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWTaCertificateCompletionEvent = nil; - return nil; + eventSinks[taCertificateCompletionEvent] = nil; + return nil; } @end @implementation RGLWTASignatureCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWTaSignatureCompletionEvent = eventSink; - return nil; + eventSinks[taSignatureCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWTaSignatureCompletionEvent = nil; - return nil; + eventSinks[taSignatureCompletionEvent] = nil; + return nil; } @end -@implementation RGLWBleOnServiceConnectedStreamHandler +@implementation RGLWPACEProtocolCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWBleOnServiceConnectedEvent = eventSink; - return nil; + eventSinks[paceProtocolCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWBleOnServiceConnectedEvent = nil; - return nil; + eventSinks[paceProtocolCompletionEvent] = nil; + return nil; } @end -@implementation RGLWBleOnServiceDisconnectedStreamHandler +@implementation RGLWCAProtocolCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWBleOnServiceDisconnectedEvent = eventSink; - return nil; + eventSinks[caProtocolCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWBleOnServiceDisconnectedEvent = nil; - return nil; + eventSinks[caProtocolCompletionEvent] = nil; + return nil; } @end -@implementation RGLWBleOnDeviceReadyStreamHandler +@implementation RGLWVideoEncoderCompletionStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWBleOnDeviceReadyEvent = eventSink; - return nil; + eventSinks[drVideoEncoderCompletionEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWBleOnDeviceReadyEvent = nil; - return nil; + eventSinks[drVideoEncoderCompletionEvent] = nil; + return nil; } @end @implementation RGLWOnCustomButtonTappedStreamHandler - (FlutterError*)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)eventSink { - RGLWOnCustomButtonTappedEvent = eventSink; - return nil; + eventSinks[drOnCustomButtonTappedEvent] = eventSink; + return nil; } - (FlutterError*)onCancelWithArguments:(id)arguments { - RGLWOnCustomButtonTappedEvent = nil; - return nil; -} -@end - -@implementation RGLWRFIDDelegateNoPA - -- (void)onRequestTACertificatesWithKey:(NSString *)keyCAR callback:(RGLRFIDCertificatesCallback)callback { - RGLWTaCertificateCompletion = callback; - if(RGLWTaCertificateCompletionEvent != nil) - RGLWTaCertificateCompletionEvent(keyCAR); -} - -- (void)onRequestTASignatureWithChallenge:(RGLTAChallenge *)challenge callback:(void(^)(NSData *signature))callback { - RGLWTaSignatureCompletion = callback; - if(RGLWTaSignatureCompletionEvent != nil) - RGLWTaSignatureCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLTAChallenge:challenge]]); -} - -- (void)didChipConnected { - if(RGLWRfidOnChipDetectedEvent == nil) return; - RGLWRfidOnChipDetectedEvent(@""); -} - -- (void)didReceivedError:(RGLRFIDErrorCodes)errorCode { - if(RGLWRfidOnRetryReadChipEvent == nil) return; - NSMutableDictionary *result = [NSMutableDictionary new]; - result[@"errorCode"] = [NSNumber numberWithInteger:errorCode]; - RGLWRfidOnRetryReadChipEvent([RGLWJSONConstructor dictToString:result]); -} - -@end - - -@implementation FlutterDocumentReaderApiPlugin - -static FlutterMethodChannel * _channel; -static NSNumber * _databasePercentageDownloaded; - -+ (FlutterMethodChannel *)channel { return _channel; } -+ (void)setChannel:(FlutterMethodChannel *)newChannel { _channel = newChannel; } -+ (NSNumber*)databasePercentageDownloaded{ return _databasePercentageDownloaded; } -+ (void)setDatabasePercentageDownloaded:(NSNumber *)number { _databasePercentageDownloaded = number; } - -- (void) result:(id _Nullable)message :(RGLWCallback)callback { - callback(message); -} - --(void (^_Nullable)(NSProgress * _Nonnull progress))getProgressHandler:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - return ^(NSProgress * _Nonnull progress) { - if(FlutterDocumentReaderApiPlugin.databasePercentageDownloaded != [NSNumber numberWithDouble:progress.fractionCompleted * 100]){ - if(RGLWDatabaseProgressEvent != nil) - RGLWDatabaseProgressEvent([NSString stringWithFormat:@"%.1f", progress.fractionCompleted * 100]); - [FlutterDocumentReaderApiPlugin setDatabasePercentageDownloaded:[NSNumber numberWithDouble:progress.fractionCompleted * 100]]; - } - }; -} - --(RGLDocumentReaderCompletion _Nonnull)getCompletion { - return ^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { - if(RGLWCompletionEvent == nil) return; - RGLWCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateCompletion:[RGLWJSONConstructor generateDocReaderAction: action] :results :error]]); - }; -} - --(RGLRFIDProcessCompletion _Nonnull)getRFIDCompletion { - return ^(RGLRFIDCompleteAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error, RGLRFIDErrorCodes errorCode) { - if(RGLWCompletionEvent == nil) return; - RGLWCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateCompletion:[RGLWJSONConstructor generateRFIDCompleteAction: action] :results :error]]); - }; -} - --(RGLRFIDNotificationCallback _Nonnull)getRFIDNotificationCallback { - return ^(RGLRFIDNotificationAction action, RGLRFIDNotify* _Nullable notification) { - if(RGLWRfidOnProgressEvent == nil) return; - RGLWRfidOnProgressEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderNotification:notification]]); - }; -} - -- (void)didFinishRecordingToFile:(NSURL *)fileURL { - if(RGLWVideoEncoderCompletionEvent == nil) return; - RGLWVideoEncoderCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateVideoEncoderCompletion:fileURL :nil]]); -} - -- (void)didFailWithError:(NSError *)error { - if(RGLWVideoEncoderCompletionEvent == nil) return; - RGLWVideoEncoderCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateVideoEncoderCompletion:nil :error]]); -} - -- (void)onRequestPACertificatesWithSerial:(NSData *)serialNumber issuer:(RGLPAResourcesIssuer *)issuer callback:(RGLRFIDCertificatesCallback)callback { - RGLWPaCertificateCompletion = callback; - if(RGLWPaCertificateCompletionEvent == nil) return; - RGLWPaCertificateCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generatePACertificateCompletion:serialNumber :issuer]]); -} - -- (void)onRequestTACertificatesWithKey:(NSString *)keyCAR callback:(RGLRFIDCertificatesCallback)callback { - RGLWTaCertificateCompletion = callback; - if(RGLWTaCertificateCompletionEvent == nil) return; - RGLWTaCertificateCompletionEvent(keyCAR); -} - -- (void)onRequestTASignatureWithChallenge:(RGLTAChallenge *)challenge callback:(void(^)(NSData *signature))callback { - RGLWTaSignatureCompletion = callback; - if(RGLWTaSignatureCompletionEvent == nil) return; - RGLWTaSignatureCompletionEvent([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLTAChallenge:challenge]]); -} - -- (void)didChipConnected { - if(RGLWRfidOnChipDetectedEvent == nil) return; - RGLWRfidOnChipDetectedEvent(@""); -} - -- (void)didReceivedError:(RGLRFIDErrorCodes)errorCode { - if(RGLWRfidOnRetryReadChipEvent == nil) return; - NSMutableDictionary *result = [NSMutableDictionary new]; - result[@"errorCode"] = [NSNumber numberWithInteger:errorCode]; - RGLWRfidOnRetryReadChipEvent([RGLWJSONConstructor dictToString:result]); -} - -- (void)onCustomButtonTappedWithTag:(NSInteger)tag { - if(RGLWOnCustomButtonTappedEvent == nil) return; - RGLWOnCustomButtonTappedEvent([NSString stringWithFormat:@"%ld", tag]); -} - -+ (void)registerWithRegistrar:(NSObject*)registrar { - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWCompletionStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/database_progress" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWDatabaseProgressStreamHandler new]]; - - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/rfid_notification_completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWRfidOnProgressEventStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/rfidOnChipDetectedEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWRfidOnChipDetectedEventStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/rfidOnRetryReadChipEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWRfidOnRetryReadChipEventStreamHandler new]]; - - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/pa_certificate_completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWPACertificateCompletionStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/ta_certificate_completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWTACertificateCompletionStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/ta_signature_completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWTASignatureCompletionStreamHandler new]]; - - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/bleOnServiceConnectedEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWBleOnServiceConnectedStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/bleOnServiceDisconnectedEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWBleOnServiceDisconnectedStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/bleOnDeviceReadyEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWBleOnDeviceReadyStreamHandler new]]; - - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/video_encoder_completion" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWVideoEncoderCompletionStreamHandler new]]; - [[FlutterEventChannel eventChannelWithName:@"flutter_document_reader_api/event/onCustomButtonTappedEvent" binaryMessenger:[registrar messenger]] setStreamHandler:[RGLWOnCustomButtonTappedStreamHandler new]]; - - FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"flutter_document_reader_api/method" binaryMessenger:[registrar messenger]]; - [FlutterDocumentReaderApiPlugin setChannel:channel]; - FlutterDocumentReaderApiPlugin* instance = [FlutterDocumentReaderApiPlugin new]; - [registrar addMethodCallDelegate:instance channel:channel]; -} - -- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { - NSString* action = call.method; - NSMutableArray* args = call.arguments; - - RGLWCallback successCallback = ^(id _Nullable response){ - result(response); - }; - RGLWCallback errorCallback = ^(NSString* error){ - result([FlutterError errorWithCode:@"error" message:error details:nil]); - }; - - if([action isEqualToString:@"initializeReaderAutomatically"]) - [self initializeReaderAutomatically :successCallback :errorCallback]; - else if([action isEqualToString:@"isBlePermissionsGranted"]) - [self isBlePermissionsGranted :successCallback :errorCallback]; - else if([action isEqualToString:@"startBluetoothService"]) - [self startBluetoothService :successCallback :errorCallback]; - else if([action isEqualToString:@"initializeReaderBleDeviceConfig"]) - [self initializeReaderBleDeviceConfig :successCallback :errorCallback]; - else if([action isEqualToString:@"getTag"]) - [self getTag :successCallback :errorCallback]; - else if([action isEqualToString:@"getAPIVersion"]) - [self getAPIVersion :successCallback :errorCallback]; - else if([action isEqualToString:@"getAvailableScenarios"]) - [self getAvailableScenarios :successCallback :errorCallback]; - else if([action isEqualToString:@"isRFIDAvailableForUse"]) - [self isRFIDAvailableForUse :successCallback :errorCallback]; - else if([action isEqualToString:@"getCoreMode"]) - [self getCoreMode :successCallback :errorCallback]; - else if([action isEqualToString:@"getCoreVersion"]) - [self getCoreVersion :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseDate"]) - [self getDatabaseDate :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseID"]) - [self getDatabaseID :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseVersion"]) - [self getDatabaseVersion :successCallback :errorCallback]; - else if([action isEqualToString:@"getDocumentReaderIsReady"]) - [self getDocumentReaderIsReady :successCallback :errorCallback]; - else if([action isEqualToString:@"getDocumentReaderStatus"]) - [self getDocumentReaderStatus :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseCountriesNumber"]) - [self getDatabaseCountriesNumber :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseDocumentsNumber"]) - [self getDatabaseDocumentsNumber :successCallback :errorCallback]; - else if([action isEqualToString:@"selectedScenario"]) - [self selectedScenario :successCallback :errorCallback]; - else if([action isEqualToString:@"getSessionLogFolder"]) - [self getSessionLogFolder :successCallback :errorCallback]; - else if([action isEqualToString:@"getDatabaseDescription"]) - [self getDatabaseDescription :successCallback :errorCallback]; - else if([action isEqualToString:@"showScanner"]) - [self showScanner :successCallback :errorCallback]; - else if([action isEqualToString:@"startNewPage"]) - [self startNewPage :successCallback :errorCallback]; - else if([action isEqualToString:@"startNewSession"]) - [self startNewSession :successCallback :errorCallback]; - else if([action isEqualToString:@"startRFIDReader"]) - [self startRFIDReader :successCallback :errorCallback]; - else if([action isEqualToString:@"stopRFIDReader"]) - [self stopRFIDReader :successCallback :errorCallback]; - else if([action isEqualToString:@"stopRFIDReaderWithErrorMessage"]) - [self stopRFIDReaderWithErrorMessage :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"stopScanner"]) - [self stopScanner :successCallback :errorCallback]; - else if([action isEqualToString:@"deinitializeReader"]) - [self deinitializeReader :successCallback :errorCallback]; - else if([action isEqualToString:@"isAuthenticatorAvailableForUse"]) - [self isAuthenticatorAvailableForUse :successCallback :errorCallback]; - else if([action isEqualToString:@"getConfig"]) - [self getConfig :successCallback :errorCallback]; - else if([action isEqualToString:@"getRfidScenario"]) - [self getRfidScenario :successCallback :errorCallback]; - else if([action isEqualToString:@"getLicenseExpiryDate"]) - [self getLicenseExpiryDate :successCallback :errorCallback]; - else if([action isEqualToString:@"getLicenseCountryFilter"]) - [self getLicenseCountryFilter :successCallback :errorCallback]; - else if([action isEqualToString:@"licenseIsRfidAvailable"]) - [self licenseIsRfidAvailable :successCallback :errorCallback]; - else if([action isEqualToString:@"getCameraSessionIsPaused"]) - [self getCameraSessionIsPaused :successCallback :errorCallback]; - else if([action isEqualToString:@"removeDatabase"]) - [self removeDatabase :successCallback :errorCallback]; - else if([action isEqualToString:@"cancelDBUpdate"]) - [self cancelDBUpdate :successCallback :errorCallback]; - else if([action isEqualToString:@"resetConfiguration"]) - [self resetConfiguration :successCallback :errorCallback]; - else if([action isEqualToString:@"clearPKDCertificates"]) - [self clearPKDCertificates :successCallback :errorCallback]; - else if([action isEqualToString:@"readRFID"]) - [self readRFID :successCallback :errorCallback]; - else if([action isEqualToString:@"getRfidSessionStatus"]) - [self getRfidSessionStatus :successCallback :errorCallback]; - else if([action isEqualToString:@"setRfidDelegate"]) - [self setRfidDelegate :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setEnableCoreLogs"]) - [self setEnableCoreLogs :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"addPKDCertificates"]) - [self addPKDCertificates :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setCameraSessionIsPaused"]) - [self setCameraSessionIsPaused :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setTag"]) - [self setTag :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"checkDatabaseUpdate"]) - [self checkDatabaseUpdate :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"scan"]) - [self scan :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognize"]) - [self recognize :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeImages"]) - [self recognizeImages :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"showScannerWithCameraID"]) - [self showScannerWithCameraID :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"runAutoUpdate"]) - [self runAutoUpdate :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setConfig"]) - [self setConfig :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setRfidScenario"]) - [self setRfidScenario :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"initializeReader"]) - [self initializeReader :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"prepareDatabase"]) - [self prepareDatabase :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeImage"]) - [self recognizeImage :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeData"]) - [self recognizeData :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setRfidSessionStatus"]) - [self setRfidSessionStatus :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"providePACertificates"]) - [self providePACertificates :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"provideTACertificates"]) - [self provideTACertificates :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"provideTASignature"]) - [self provideTASignature :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"parseCoreResults"]) - [self parseCoreResults :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setTCCParams"]) - [self setTCCParams :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeImageWithOpts"]) - [self recognizeImageWithOpts :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeVideoFrame"]) - [self recognizeVideoFrame :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"showScannerWithCameraIDAndOpts"]) - [self showScannerWithCameraIDAndOpts :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeImageWithCameraMode"]) - [self recognizeImageWithCameraMode :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"recognizeImagesWithImageInputs"]) - [self recognizeImagesWithImageInputs :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"setLanguage"]) - [self setLanguage :[args objectAtIndex:0] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByType"]) - [self textFieldValueByType :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByTypeLcid"]) - [self textFieldValueByTypeLcid :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByTypeSource"]) - [self textFieldValueByTypeSource :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByTypeLcidSource"]) - [self textFieldValueByTypeLcidSource :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByTypeSourceOriginal"]) - [self textFieldValueByTypeSourceOriginal :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldValueByTypeLcidSourceOriginal"]) - [self textFieldValueByTypeLcidSourceOriginal :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :[args objectAtIndex:4] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldByType"]) - [self textFieldByType :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"textFieldByTypeLcid"]) - [self textFieldByTypeLcid :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldByTypeSource"]) - [self graphicFieldByTypeSource :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldByTypeSourcePageIndex"]) - [self graphicFieldByTypeSourcePageIndex :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldByTypeSourcePageIndexLight"]) - [self graphicFieldByTypeSourcePageIndexLight :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :[args objectAtIndex:4] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldImageByType"]) - [self graphicFieldImageByType :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldImageByTypeSource"]) - [self graphicFieldImageByTypeSource :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldImageByTypeSourcePageIndex"]) - [self graphicFieldImageByTypeSourcePageIndex :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :successCallback :errorCallback]; - else if([action isEqualToString:@"graphicFieldImageByTypeSourcePageIndexLight"]) - [self graphicFieldImageByTypeSourcePageIndexLight :[args objectAtIndex:0] :[args objectAtIndex:1] :[args objectAtIndex:2] :[args objectAtIndex:3] :[args objectAtIndex:4] :successCallback :errorCallback]; - else if([action isEqualToString:@"containers"]) - [self containers :[args objectAtIndex:0] :[args objectAtIndex:1] :successCallback :errorCallback]; - else if([action isEqualToString:@"encryptedContainers"]) - [self encryptedContainers :[args objectAtIndex:0] :successCallback :errorCallback]; - else - [self result:[NSString stringWithFormat:@"%@/%@", @"method not implemented: ", action] :errorCallback]; -} - -- (void) initializeReaderAutomatically:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"regula.license" ofType:nil]; - NSData *licenseData = [NSData dataWithContentsOfFile:dataPath]; - [RGLDocReader.shared initializeReaderWithConfig:[RGLConfig configWithLicenseData:licenseData] completion:[self getInitCompletion :successCallback :errorCallback]]; -} - -- (void) isBlePermissionsGranted:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"isBlePermissionsGranted() is an android-only method" :errorCallback]; -} - -- (void) startBluetoothService:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"startBluetoothService() is an android-only method" :errorCallback]; -} - -- (void) initializeReaderBleDeviceConfig:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"initializeReaderBleDeviceConfig() is an android-only method" :errorCallback]; -} - -- (void) resetConfiguration:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocReader.shared.functionality = [RGLFunctionality new]; - RGLDocReader.shared.processParams = [RGLProcessParams new]; - RGLDocReader.shared.customization = [RGLCustomization new]; - successCallback(@""); -} - -- (void) setEnableCoreLogs:(BOOL)logs :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"setEnableCoreLogs() is an android-only method" :errorCallback]; -} - -- (void) showScannerWithCameraID:(NSNumber*)cameraID :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"showScannerWithCameraID() is an android-only method" :errorCallback]; -} - -- (void) stopRFIDReaderWithErrorMessage:(NSMutableString*)message :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared stopRFIDReaderWithErrorMessage:message completion:^() { - [self result:@"" :successCallback]; - }]; -} - -- (void) recognizeImageWithOpts:(NSString*)base64 :(NSDictionary*)opts :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"recognizeImageWithOpts() is an android-only method" :errorCallback]; -} - -- (void) recognizeVideoFrame:(NSString*)byteString :(NSDictionary*)opts :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"recognizeVideoFrame() is an android-only method" :errorCallback]; -} - -- (void) showScannerWithCameraIDAndOpts:(NSNumber*)cameraID :(NSDictionary*)opts :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"showScannerWithCameraIDAndOpts() is an android-only method" :errorCallback]; -} - -- (void) getLicenseMessage:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:@"getLicenseMessage() is an android-only method" :successCallback]; -} - -- (void) setLanguage:(NSString*)language :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocReader.shared.localizationHandler = ^NSString * _Nullable(NSString * _Nonnull localizationKey) { - NSString *result = NSLocalizedStringFromTable(localizationKey, language, @""); - if (![result isEqualToString:localizationKey]) - return result; - return nil; - }; - [self result:@"" :successCallback]; -} - -- (void) initializeReader:(NSDictionary*)config :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared initializeReaderWithConfig:[RGLWJSONConstructor RGLConfigFromJson:config] completion:[self getInitCompletion :successCallback :errorCallback]]; -} - -- (void) parseCoreResults:(NSString*)json :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderResults:[RGLDocumentReaderResults initWithRawString: json]]] :successCallback]; -} - -- (void) startRFIDReader:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - dispatch_async(dispatch_get_main_queue(), ^{ - [RGLDocReader.shared startRFIDReaderFromPresenter:[[[UIApplication sharedApplication] keyWindow] rootViewController] completion:[self getCompletion]]; - }); -} - -- (void) prepareDatabase:(NSString*)dbID :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared prepareDatabase:dbID progressHandler:[self getProgressHandler :successCallback :errorCallback] completion:[self getPrepareCompletion :successCallback :errorCallback]]; -} - -- (void) removeDatabase:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared removeDatabase:^(BOOL successful, NSError * _Nullable error) { - if (successful) - [self result:@"database removed" :successCallback]; - else - [self result:[NSString stringWithFormat:@"%@/%@", @"database removal failed: ", error.description] :errorCallback]; - }]; -} - -- (void) cancelDBUpdate:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared cancelDBUpdate]; - [self result:@"" :successCallback]; -} - --(void) runAutoUpdate:(NSString*)dbID :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared runAutoUpdate:dbID progressHandler:[self getProgressHandler :successCallback :errorCallback] completion:[self getPrepareCompletion :successCallback :errorCallback]]; -} - -- (void) showScanner:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - dispatch_async(dispatch_get_main_queue(), ^{ - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; - #pragma clang diagnostic pop - UIViewController *currentViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController]; - [RGLDocReader.shared showScanner:currentViewController completion:[self getCompletion]]; - }); -} - -- (void) recognizeImage:(NSMutableString*)base64 :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self recognizeImageWith :base64 :false :successCallback :errorCallback]; -} - -- (void) recognizeData:(NSString*)data :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared recognizeData :[[NSData alloc] initWithBase64EncodedString:data options:0] completion:[self getCompletion]]; -} - -- (void) recognizeImages:(NSArray*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSMutableArray* images = [[NSMutableArray alloc] init]; - for(__strong NSMutableString* base64 in input) - [images addObject:[RGLWJSONConstructor imageWithBase64:base64]]; - dispatch_async(dispatch_get_main_queue(), ^{ - [RGLDocReader.shared recognizeImages:images completion:[self getCompletion]]; - }); - -} - -- (void) recognizeImagesWithImageInputs:(NSArray*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSMutableArray* images = [[NSMutableArray alloc] init]; - for(__strong NSDictionary* image in input) - [images addObject:[RGLWJSONConstructor RGLImageInputFromJson: image]]; - dispatch_async(dispatch_get_main_queue(), ^{ - [RGLDocReader.shared recognizeImagesWithImageInputs:images completion:[self getCompletion]]; - }); -} - -- (void) recognizeImageWithCameraMode:(NSMutableString*)base64 :(BOOL)cameraMode :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self recognizeImageWith :base64 :cameraMode :successCallback :errorCallback]; -} - -- (void) recognizeImageWith:(NSMutableString*)base64 :(BOOL)cameraMode :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - dispatch_async(dispatch_get_main_queue(), ^{ - [RGLDocReader.shared recognizeImage:[RGLWJSONConstructor imageWithBase64:base64] cameraMode:cameraMode completion:[self getCompletion]]; - }); + eventSinks[drOnCustomButtonTappedEvent] = nil; + return nil; } - -- (void) setConfig:(NSDictionary*)config :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLWRegulaConfig setConfig:config :RGLDocReader.shared]; - [self result:@"" :successCallback]; -} - -- (void) getConfig:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[RGLWRegulaConfig getConfig:RGLDocReader.shared] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] :successCallback]; -} - -- (void) checkDatabaseUpdate:(NSString*)databaseId :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared checkDatabaseUpdate:databaseId completion:[self getCheckDatabaseUpdateCompletion: successCallback: errorCallback]]; -} - -- (void) getTag:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[RGLDocReader.shared tag] :successCallback]; -} - -- (void) setTag:(NSString*)tag :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared setTag:tag]; - [self result:@"" :successCallback]; -} - -- (void) setRfidScenario:(NSDictionary*)rfidScenario :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLWRegulaConfig setRfidScenario:rfidScenario :RGLDocReader.shared.rfidScenario]; - [self result:@"" :successCallback]; -} - -- (void) getRfidScenario:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:RGLDocReader.shared.rfidScenario.rfidScenarioDictionary options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] :successCallback]; -} - -- (void) readRFID:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared readRFID:[self getRFIDNotificationCallback] completion:[self getRFIDCompletion]]; -} - -- (void) stopRFIDReader:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared stopRFIDReader:^(){[self result:@"" :successCallback];}]; -} - -- (void) clearPKDCertificates:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared clearPKDCertificates]; - [self result:@"" :successCallback]; -} - -- (void) addPKDCertificates:(NSArray*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSMutableArray *certificates = [[NSMutableArray alloc] init]; - for(NSDictionary* certificateJSON in input) - [certificates addObject:[RGLWJSONConstructor RGLPKDCertificateFromJson:certificateJSON]]; - [RGLDocReader.shared addPKDCertificates:certificates]; - [self result:@"" :successCallback]; -} - -- (void) deinitializeReader:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared deinitializeReader]; - [self result:@"" :successCallback]; -} - -- (void) selectedScenario:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLScenario:RGLDocReader.shared.selectedScenario]] :successCallback]; -} - -- (void) stopScanner:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - dispatch_async(dispatch_get_main_queue(), ^{ - [RGLDocReader.shared stopScanner:^(){ - [self result:@"" :successCallback]; - }]; - }); -} - -- (void) startNewSession:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared startNewSession]; - [self result:@"" :successCallback]; -} - -- (void) startNewPage:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared startNewPage]; - [self result:@"" :successCallback]; -} - -- (void) scan:(NSDictionary*)config :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - dispatch_async(dispatch_get_main_queue(), ^{ - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; - #pragma clang diagnostic pop - UIViewController *currentViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController]; - [RGLDocReader.shared showScannerFromPresenter:currentViewController config:[RGLWJSONConstructor RGLScannerConfigFromJson:config] completion:[self getCompletion]]; - }); -} - -- (void) recognize:(NSDictionary*)config :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - UIViewController *currentViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController]; - [RGLDocReader.shared recognizeImageFromPresenter:currentViewController config:[RGLWJSONConstructor RGLRecognizeConfigFromJson:config] completion:[self getCompletion]]; -} - -- (void) getDocumentReaderIsReady:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[RGLDocReader.shared isDocumentReaderIsReady] ? @YES : @NO :successCallback]; -} - -- (void) getAPIVersion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.api :successCallback]; -} - -- (void) getCoreVersion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.core :successCallback]; -} - -- (void) getCoreMode:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.coreMode :successCallback]; -} - -- (void) getDatabaseID:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.database.databaseID :successCallback]; -} - -- (void) getDatabaseVersion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.database.version :successCallback]; -} - -- (void) getDatabaseDate:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.database.date :successCallback]; -} - -- (void) getDatabaseDescription:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.version.database.databaseDescription :successCallback]; -} - -- (void) getDatabaseCountriesNumber:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[NSNumber numberWithInteger:RGLDocReader.shared.version.database.countriesNumber] :successCallback]; -} - -- (void) getDatabaseDocumentsNumber:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:[NSNumber numberWithInteger:RGLDocReader.shared.version.database.documentsNumber] :successCallback]; -} - -- (void) getLicenseExpiryDate:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setFormatterBehavior:NSDateFormatterBehaviorDefault]; - [formatter setDateStyle:NSDateFormatterShortStyle]; - [formatter setTimeStyle:NSDateFormatterNoStyle]; - [self result:[formatter stringFromDate:RGLDocReader.shared.license.expiryDate] :successCallback]; -} - -- (void) getLicenseCountryFilter:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - if(RGLDocReader.shared.license.countryFilter == nil) - [self result:@"nil" :successCallback]; - else - [self result:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:RGLDocReader.shared.license.countryFilter options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] :successCallback]; -} - -- (void) licenseIsRfidAvailable:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.license.isRfidAvailable ? @YES : @NO :successCallback]; -} - -- (void) getDocumentReaderStatus:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.documentReaderStatus :successCallback]; -} - -- (void) setTCCParams:(NSDictionary*)params :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [RGLDocReader.shared setTCCParams:[RGLWJSONConstructor RGLTCCParamsFromJson:params] completion:[self getTCCParamsCompletion:successCallback :errorCallback]]; -} - -- (void) getRfidSessionStatus:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.rfidSessionStatus :successCallback]; -} - -- (void) setRfidSessionStatus:(NSString*)status :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocReader.shared.rfidSessionStatus = status; - [self result:@"" :successCallback]; -} - -- (void) getCurrentScenario:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.processParams.scenario :successCallback]; -} - -- (void) getCameraSessionIsPaused:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.isCameraSessionIsPaused ? @YES : @NO :successCallback]; -} - -- (void) setCameraSessionIsPaused:(BOOL)paused :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocReader.shared.cameraSessionIsPaused = paused; - [self result:@"" :successCallback]; -} - -- (void) isRFIDAvailableForUse:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.isRFIDAvailableForUse ? @YES : @NO :successCallback]; -} - -- (void) isAuthenticatorAvailableForUse:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.isAuthenticatorAvailableForUse ? @YES : @NO :successCallback]; -} - -- (void) getSessionLogFolder:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - [self result:RGLDocReader.shared.processParams.sessionLogFolder :successCallback]; -} - -- (void) providePACertificates:(NSArray*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - if(RGLWPaCertificateCompletion == nil){ - [self result:@"paCertificateCompletion is nil" :errorCallback]; - return; - } - NSMutableArray *certificates = [[NSMutableArray alloc] init]; - for(NSDictionary* certificateJSON in input) - [certificates addObject:[RGLWJSONConstructor RGLPKDCertificateFromJson:certificateJSON]]; - RGLWPaCertificateCompletion(certificates); - [self result:@"" :successCallback]; -} - -- (void) provideTACertificates:(NSArray*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - if(RGLWTaCertificateCompletion == nil){ - [self result:@"taCertificateCompletion is nil" :errorCallback]; - return; - } - NSMutableArray *certificates = [[NSMutableArray alloc] init]; - for(NSDictionary* certificateJSON in input) - [certificates addObject:[RGLWJSONConstructor RGLPKDCertificateFromJson:certificateJSON]]; - RGLWTaCertificateCompletion(certificates); - [self result:@"" :successCallback]; -} - -- (void) provideTASignature:(NSString*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - if(RGLWTaSignatureCompletion == nil){ - [self result:@"taSignatureCompletion is nil" :errorCallback]; - return; - } - RGLWTaSignatureCompletion([[NSData alloc] initWithBase64EncodedString:input options:0]); - [self result:@"" :successCallback]; -} - -- (void) setRfidDelegate:(NSNumber*)input :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - switch([input integerValue]){ - case 0: - [RGLDocReader shared].rfidDelegate = nil; - break; - case 1: - if(RGLWRfidDelegateNoPA == nil) - RGLWRfidDelegateNoPA = [RGLWRFIDDelegateNoPA new]; - [RGLDocReader shared].rfidDelegate = RGLWRfidDelegateNoPA; - break; - case 2: - [RGLDocReader shared].rfidDelegate = self; - break; - default: - [self result:@"wrong input" :errorCallback]; - return; - } - - [self result:@"" :successCallback]; -} - -- (void) getAvailableScenarios:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - NSMutableArray *availableScenarios = [[NSMutableArray alloc] init]; - for(RGLScenario *scenario in RGLDocReader.shared.availableScenarios) - [availableScenarios addObject:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLScenario:scenario]]]; - [self result:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:availableScenarios options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] :successCallback]; -} - -- (void) textFieldValueByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue]] :successCallback]; -} - -- (void) textFieldValueByTypeLcid:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue]] :successCallback]; -} - -- (void) textFieldValueByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue] source:[source integerValue]] :successCallback]; -} - -- (void) textFieldValueByTypeLcidSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(NSNumber*)source :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue] source:[source integerValue]] :successCallback]; -} - -- (void) textFieldValueByTypeSourceOriginal:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(BOOL)original :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue] source:[source integerValue] original:original] :successCallback]; -} - -- (void) textFieldValueByTypeLcidSourceOriginal:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(NSNumber*)source :(BOOL)original :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue] source:[source integerValue] original:original] :successCallback]; -} - -- (void) textFieldByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - RGLDocumentReaderTextField* result = [results getTextFieldByType:[fieldType integerValue]]; - if(result == nil) - [self result:nil :successCallback]; - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderTextField:result]] :successCallback]; -} - -- (void) textFieldByTypeLcid:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - RGLDocumentReaderTextField* result = [results getTextFieldByType:[fieldType integerValue] lcid:[lcid integerValue]]; - if(result == nil) - [self result:nil :successCallback]; - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderTextField:result]] :successCallback]; -} - -- (void) graphicFieldByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue]]; - if(result == nil) - [self result:nil :successCallback]; - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderGraphicField:result]] :successCallback]; -} - -- (void) graphicFieldByTypeSourcePageIndex:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue]]; - if(result == nil) - [self result:nil :successCallback]; - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderGraphicField:result]] :successCallback]; -} - -- (void) graphicFieldByTypeSourcePageIndexLight:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(NSNumber*)light :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue] light:[light integerValue]]; - if(result == nil) - [self result:nil :successCallback]; - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocumentReaderGraphicField:result]] :successCallback]; -} - -- (void) graphicFieldImageByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue]]] :successCallback]; -} - -- (void) graphicFieldImageByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue]]] :successCallback]; -} - -- (void) graphicFieldImageByTypeSourcePageIndex:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue]]] :successCallback]; -} - -- (void) graphicFieldImageByTypeSourcePageIndexLight:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(NSNumber*)light :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue] light:[light integerValue]]] :successCallback]; -} - -- (void) containers:(NSString*)rawResult :(NSArray*)resultType :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getContainersByResultTypes:resultType] :successCallback]; -} - -- (void) encryptedContainers:(NSString*)rawResult :(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; - [self result:[results getEncryptedContainers] :successCallback]; -} - --(RGLDocumentReaderInitializationCompletion)getInitCompletion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - return ^(BOOL successful, NSError * _Nullable error ) { - if (successful){ - [RGLDocReader shared].functionality.recordScanningProcessDelegate = self; - RGLDocReader.shared.customization.actionDelegate = self; - [self result:@"init complete" :successCallback]; - }else - [self result:[NSString stringWithFormat:@"%@/%@", @"init failed: ", error.description] :errorCallback]; - }; -} - --(RGLDocumentReaderPrepareCompletion _Nonnull)getPrepareCompletion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - return ^(BOOL successful, NSError * _Nullable error) { - if (successful) - [self result:@"database prepared" :successCallback]; - else - [self result:[NSString stringWithFormat:@"%@/%@", @"database preparation failed: ", error.description] :errorCallback]; - }; -} - --(void (^_Nullable)(BOOL success, NSError * _Nullable error))getTCCParamsCompletion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - return ^(BOOL success, NSError * _Nullable error) { - if (success) - [self result:@"success" :successCallback]; - else - [self result:[NSString stringWithFormat:@"%@/%@", @"failed: ", error.description] :errorCallback]; - }; -} - --(RGLDocumentReaderCheckUpdateCompletion)getCheckDatabaseUpdateCompletion:(RGLWCallback)successCallback :(RGLWCallback)errorCallback{ - return ^(RGLDocReaderDocumentsDatabase* database) { - [self result:[RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateRGLDocReaderDocumentsDatabase:database]] :successCallback]; - }; -} - @end diff --git a/ios/Classes/RGLWConfig.h b/ios/Classes/RGLWConfig.h new file mode 100644 index 0000000000..63e07c97d3 --- /dev/null +++ b/ios/Classes/RGLWConfig.h @@ -0,0 +1,42 @@ +#ifndef RGLWConfig_h +#define RGLWConfig_h + +#import +#import "RGLWJSONConstructor.h" + +@import CoreGraphics; +@import UIKit; +@import AVFoundation; + +@interface RGLWConfig : NSObject + ++(void)setFunctionality:(NSDictionary*)options :(RGLFunctionality*)functionality; ++(void)setProcessParams:(NSDictionary*)options :(RGLProcessParams*)processParams; ++(void)setCustomization:(NSDictionary*)options :(RGLCustomization*)customization; ++(void)setRfidScenario:(NSDictionary*)options :(RGLRFIDScenario*)rfidScenario; ++(void)setDataGroups:(RGLDataGroup*)dataGroup dict:(NSDictionary*)dict; ++(void)setDTCDataGroup:(RGLDTCDataGroup*)dataGroup dict:(NSDictionary*)dict; ++(void)setImageQA:(RGLImageQA*)result input:(NSDictionary*)input; ++(void)setAuthenticityParams:(RGLAuthenticityParams*)result input:(NSDictionary*)input; ++(void)setLivenessParams:(RGLLivenessParams*)result input:(NSDictionary*)input; + ++(NSDictionary*)getFunctionality:(RGLFunctionality*)functionality; ++(NSDictionary*)getProcessParams:(RGLProcessParams*)processParams; ++(NSDictionary*)getCustomization:(RGLCustomization*)customization; ++(NSDictionary*)getRfidScenario:(RGLRFIDScenario*)rfidScenario; ++(NSDictionary*)getDataGroups:(RGLDataGroup*)dataGroup; ++(NSDictionary*)getDTCDataGroup:(RGLDTCDataGroup*)dataGroup; ++(NSDictionary*)getImageQA:(RGLImageQA*)input; ++(NSDictionary*)getAuthenticityParams:(RGLAuthenticityParams*)input; ++(NSDictionary*)getLivenessParams:(RGLLivenessParams*)input; + ++(RGLImageQualityCheckType)imageQualityCheckTypeWithNumber:(NSNumber*)value; ++(NSNumber*)generateDocReaderAction:(RGLDocReaderAction)action; ++(NSNumber*)generateRFIDCompleteAction:(RGLRFIDCompleteAction)action; ++(NSNumber*)generateImageQualityCheckType:(RGLImageQualityCheckType)value; + ++(RGLDocReaderFrame)docReaderFrameWithString:(NSString*)value; ++(NSString*)generateDocReaderFrame:(RGLDocReaderFrame)value; + +@end +#endif diff --git a/ios/Classes/RGLWConfig.m b/ios/Classes/RGLWConfig.m new file mode 100644 index 0000000000..9fbc4fe3ce --- /dev/null +++ b/ios/Classes/RGLWConfig.m @@ -0,0 +1,1545 @@ +#import +#import "RGLWConfig.h" + +@implementation RGLWConfig + ++(void)setFunctionality:(NSDictionary*)options :(RGLFunctionality*)functionality { + // Boolean + if([options valueForKey:@"showTorchButton"] != nil) + functionality.showTorchButton = [[options valueForKey:@"showTorchButton"] boolValue]; + if([options valueForKey:@"showCloseButton"] != nil) + functionality.showCloseButton = [[options valueForKey:@"showCloseButton"] boolValue]; + if([options valueForKey:@"videoCaptureMotionControl"] != nil) + functionality.videoCaptureMotionControl = [[options valueForKey:@"videoCaptureMotionControl"] boolValue]; + if([options valueForKey:@"showCaptureButton"] != nil) + functionality.showCaptureButton = [[options valueForKey:@"showCaptureButton"] boolValue]; + if([options valueForKey:@"showChangeFrameButton"] != nil) + functionality.showChangeFrameButton = [[options valueForKey:@"showChangeFrameButton"] boolValue]; + if([options valueForKey:@"showSkipNextPageButton"] != nil) + functionality.showSkipNextPageButton = [[options valueForKey:@"showSkipNextPageButton"] boolValue]; + if([options valueForKey:@"useAuthenticator"] != nil) + functionality.useAuthenticator = [[options valueForKey:@"useAuthenticator"] boolValue]; + if([options valueForKey:@"skipFocusingFrames"] != nil) + functionality.skipFocusingFrames = [[options valueForKey:@"skipFocusingFrames"] boolValue]; + if([options valueForKey:@"showCameraSwitchButton"] != nil) + functionality.showCameraSwitchButton = [[options valueForKey:@"showCameraSwitchButton"] boolValue]; + if([options valueForKey:@"displayMetadata"] != nil) + functionality.showMetadataInfo = [[options valueForKey:@"displayMetadata"] boolValue]; + if([options valueForKey:@"isZoomEnabled"] != nil) + functionality.isZoomEnabled = [[options valueForKey:@"isZoomEnabled"] boolValue]; + if([options valueForKey:@"recordScanningProcess"] != nil) + functionality.recordScanningProcess = [[options valueForKey:@"recordScanningProcess"] boolValue]; + if([options valueForKey:@"manualMultipageMode"] != nil) + functionality.manualMultipageMode = [[options valueForKey:@"manualMultipageMode"] boolValue]; + if([options valueForKey:@"singleResult"] != nil) + functionality.singleResult = [[options valueForKey:@"singleResult"] boolValue]; + if(options[@"torchTurnedOn"]) functionality.torchTurnedOn = [options[@"torchTurnedOn"] boolValue]; + if(options[@"preventScreenRecording"]) functionality.preventScreenRecording = [options[@"preventScreenRecording"] boolValue]; + if(options[@"homeIndicatorAutoHide"]) functionality.homeIndicatorAutoHide = [options[@"homeIndicatorAutoHide"] boolValue]; + + // Int + if([options valueForKey:@"showCaptureButtonDelayFromDetect"] != nil) + functionality.showCaptureButtonDelayFromDetect = [[options valueForKey:@"showCaptureButtonDelayFromDetect"] doubleValue]; + if([options valueForKey:@"showCaptureButtonDelayFromStart"] != nil) + functionality.showCaptureButtonDelayFromStart = [[options valueForKey:@"showCaptureButtonDelayFromStart"] doubleValue]; + if([options valueForKey:@"forcePagesCount"] != nil) + functionality.forcePagesCount = [options valueForKey:@"forcePagesCount"]; + if([options valueForKey:@"orientation"] != nil) + functionality.orientation = [self interfaceOrientationMaskWithNumber:[options valueForKey:@"orientation"]]; + if([options valueForKey:@"captureMode"] != nil) + functionality.captureMode = [[options valueForKey:@"captureMode"] integerValue]; + if(options[@"cameraPositionIOS"]) + functionality.cameraPosition = [options[@"cameraPositionIOS"] integerValue]; + + // String + if([options valueForKey:@"cameraFrame"] != nil) + functionality.cameraFrame = [self docReaderFrameWithString:[options valueForKey:@"cameraFrame"]]; +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if([options valueForKey:@"btDeviceName"] != nil) + functionality.btDeviceName = [options valueForKey:@"btDeviceName"]; +#pragma clang diagnostic pop + + // Float + if([options valueForKey:@"zoomFactor"] != nil) + functionality.zoomFactor = [[options valueForKey:@"zoomFactor"] floatValue]; + if(options[@"mdlTimeout"]) functionality.mDLTimeout = [options[@"mdlTimeout"] doubleValue]; + + // Custom + // in android - cameraSize + if([options valueForKey:@"videoSessionPreset"] != nil) + functionality.videoSessionPreset = [self captureSessionPresetWithNumber:[options valueForKey:@"videoSessionPreset"]]; + if([options valueForKey:@"videoOutputSettings"] != nil) + functionality.videoOutputSettings = [options valueForKey:@"videoOutputSettings"]; +} + ++(NSDictionary*)getFunctionality:(RGLFunctionality*)functionality { + NSMutableDictionary *result = [NSMutableDictionary new]; + + // Boolean + result[@"showTorchButton"] = [NSNumber numberWithBool:functionality.showTorchButton]; + result[@"showCloseButton"] = [NSNumber numberWithBool:functionality.showCloseButton]; + result[@"videoCaptureMotionControl"] = [NSNumber numberWithBool:functionality.videoCaptureMotionControl]; + result[@"showCaptureButton"] = [NSNumber numberWithBool:functionality.showCaptureButton]; + result[@"showChangeFrameButton"] = [NSNumber numberWithBool:functionality.showChangeFrameButton]; + result[@"showSkipNextPageButton"] = [NSNumber numberWithBool:functionality.showSkipNextPageButton]; + result[@"useAuthenticator"] = [NSNumber numberWithBool:functionality.isUseAuthenticator]; + result[@"skipFocusingFrames"] = [NSNumber numberWithBool:functionality.skipFocusingFrames]; + result[@"showCameraSwitchButton"] = [NSNumber numberWithBool:functionality.showCameraSwitchButton]; + result[@"displayMetadata"] = [NSNumber numberWithBool:functionality.showMetadataInfo]; + result[@"isZoomEnabled"] = [NSNumber numberWithBool:functionality.isZoomEnabled]; + result[@"recordScanningProcess"] = [NSNumber numberWithBool:functionality.recordScanningProcess]; + result[@"manualMultipageMode"] = [NSNumber numberWithBool:functionality.manualMultipageMode]; + result[@"singleResult"] = [NSNumber numberWithBool:functionality.singleResult]; + result[@"torchTurnedOn"] = @(functionality.torchTurnedOn); + result[@"preventScreenRecording"] = @(functionality.preventScreenRecording); + result[@"homeIndicatorAutoHide"] = @(functionality.homeIndicatorAutoHide); + + // Int + result[@"showCaptureButtonDelayFromDetect"] = [NSNumber numberWithDouble:functionality.showCaptureButtonDelayFromDetect]; + result[@"showCaptureButtonDelayFromStart"] = [NSNumber numberWithDouble:functionality.showCaptureButtonDelayFromStart]; + result[@"forcePagesCount"] = functionality.forcePagesCount; + result[@"orientation"] = [self generateInterfaceOrientationMask:functionality.orientation]; + result[@"captureMode"] = [NSNumber numberWithInteger:functionality.captureMode]; + result[@"cameraPositionIOS"] = @(functionality.cameraPosition); + + // String + result[@"cameraFrame"] = [self generateDocReaderFrame:functionality.cameraFrame]; +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + result[@"btDeviceName"] = functionality.btDeviceName; +#pragma clang diagnostic pop + + // Float + result[@"zoomFactor"] = [NSNumber numberWithFloat:functionality.zoomFactor]; + result[@"mdlTimeout"] = @(functionality.mDLTimeout); + + // Custom + // in android - cameraSize + result[@"videoSessionPreset"] = [self generateCaptureSessionPreset:functionality.videoSessionPreset]; + result[@"videoOutputSettings"] = functionality.videoOutputSettings; + + return result; +} + ++(void)setProcessParams:(NSDictionary*)options :(RGLProcessParams*)processParams { + + // Boolean + if([options valueForKey:@"multipageProcessing"] != nil) + processParams.multipageProcessing = [options valueForKey:@"multipageProcessing"]; + if([options valueForKey:@"logs"] != nil) + processParams.logs = [options valueForKey:@"logs"]; + if([options valueForKey:@"debugSaveImages"] != nil) + processParams.debugSaveImages = [options valueForKey:@"debugSaveImages"]; + if([options valueForKey:@"debugSaveLogs"] != nil) + processParams.debugSaveLogs = [options valueForKey:@"debugSaveLogs"]; + if([options valueForKey:@"returnUncroppedImage"] != nil) + processParams.returnUncroppedImage = [options valueForKey:@"returnUncroppedImage"]; + if([options valueForKey:@"debugSaveCroppedImages"] != nil) + processParams.debugSaveCroppedImages = [options valueForKey:@"debugSaveCroppedImages"]; + if([options valueForKey:@"disableFocusingCheck"] != nil) + processParams.disableFocusingCheck = [options valueForKey:@"disableFocusingCheck"]; + if([options valueForKey:@"debugSaveRFIDSession"] != nil) + processParams.debugSaveRFIDSession = [options valueForKey:@"debugSaveRFIDSession"]; + if([options valueForKey:@"doublePageSpread"] != nil) + processParams.doublePageSpread = [options valueForKey:@"doublePageSpread"]; + if([options valueForKey:@"manualCrop"] != nil) + processParams.manualCrop = [options valueForKey:@"manualCrop"]; + if([options valueForKey:@"integralImage"] != nil) + processParams.integralImage = [options valueForKey:@"integralImage"]; + if([options valueForKey:@"returnCroppedBarcode"] != nil) + processParams.returnCroppedBarcode = [options valueForKey:@"returnCroppedBarcode"]; + if([options valueForKey:@"checkRequiredTextFields"] != nil) + processParams.checkRequiredTextFields = [options valueForKey:@"checkRequiredTextFields"]; + if([options valueForKey:@"depersonalizeLog"] != nil) + processParams.depersonalizeLog = [options valueForKey:@"depersonalizeLog"]; + if([options valueForKey:@"generateDoublePageSpreadImage"] != nil) + processParams.generateDoublePageSpreadImage = [options valueForKey:@"generateDoublePageSpreadImage"]; + if([options valueForKey:@"alreadyCropped"] != nil) + processParams.alreadyCropped = [options valueForKey:@"alreadyCropped"]; + if([options valueForKey:@"matchTextFieldMask"] != nil) + processParams.matchTextFieldMask = [options valueForKey:@"matchTextFieldMask"]; + if([options valueForKey:@"updateOCRValidityByGlare"] != nil) + processParams.updateOCRValidityByGlare = [options valueForKey:@"updateOCRValidityByGlare"]; + if([options valueForKey:@"noGraphics"] != nil) + processParams.noGraphics = [options valueForKey:@"noGraphics"]; + if([options valueForKey:@"multiDocOnImage"] != nil) + processParams.multiDocOnImage = [options valueForKey:@"multiDocOnImage"]; + if([options valueForKey:@"parseBarcodes"] != nil) + processParams.parseBarcodes = [options valueForKey:@"parseBarcodes"]; + if([options valueForKey:@"shouldReturnPackageForReprocess"] != nil) + processParams.shouldReturnPackageForReprocess = [options valueForKey:@"shouldReturnPackageForReprocess"]; + if([options valueForKey:@"disablePerforationOCR"] != nil) + processParams.disablePerforationOCR = [options valueForKey:@"disablePerforationOCR"]; + if([options valueForKey:@"respectImageQuality"] != nil) + processParams.respectImageQuality = [options valueForKey:@"respectImageQuality"]; + if (options[@"strictImageQuality"]) processParams.strictImageQuality = options[@"strictImageQuality"]; + if([options valueForKey:@"splitNames"] != nil) + processParams.splitNames = [options valueForKey:@"splitNames"]; + if([options valueForKey:@"doDetectCan"] != nil) + processParams.doDetectCan = [options valueForKey:@"doDetectCan"]; + if([options valueForKey:@"useFaceApi"] != nil) + processParams.useFaceApi = [options valueForKey:@"useFaceApi"]; + if([options valueForKey:@"useAuthenticityCheck"] != nil) + processParams.useAuthenticityCheck = [options valueForKey:@"useAuthenticityCheck"]; + if([options valueForKey:@"checkHologram"] != nil) + processParams.checkHologram = [options valueForKey:@"checkHologram"]; + if (options[@"generateNumericCodes"]) processParams.generateNumericCodes = options[@"generateNumericCodes"]; + if (options[@"strictBarcodeDigitalSignatureCheck"]) processParams.strictBarcodeDigitalSignatureCheck = options[@"strictBarcodeDigitalSignatureCheck"]; + if (options[@"selectLongestNames"]) processParams.selectLongestNames = options[@"selectLongestNames"]; + if (options[@"generateDTCVC"]) processParams.generateDTCVC = options[@"generateDTCVC"]; + if (options[@"strictDLCategoryExpiry"]) processParams.strictDLCategoryExpiry = options[@"strictDLCategoryExpiry"]; + if (options[@"generateAlpha2Codes"]) processParams.generateAlpha2Codes = options[@"generateAlpha2Codes"]; + if (options[@"disableAuthResolutionFilter"]) processParams.disableAuthResolutionFilter = options[@"disableAuthResolutionFilter"]; + if (options[@"strictSecurityChecks"]) processParams.strictSecurityChecks = options[@"strictSecurityChecks"]; + if (options[@"returnTransliteratedFields"]) processParams.returnTransliteratedFields = options[@"returnTransliteratedFields"]; + if (options[@"checkCaptureProcessIntegrity"]) processParams.checkCaptureProcessIntegrity = options[@"checkCaptureProcessIntegrity"]; + if (options[@"strictExpiryDate"]) processParams.strictExpiryDate = options[@"strictExpiryDate"]; + if (options[@"debugSaveBinarySession"]) processParams.debugSaveBinarySession = options[@"debugSaveBinarySession"]; + if (options[@"checkVDS"]) processParams.checkVDS = options[@"checkVDS"]; + if (options[@"strictAgeCheck"]) processParams.strictAgeCheck = options[@"strictAgeCheck"]; + + // Int + if([options valueForKey:@"measureSystem"] != nil) + processParams.measureSystem = [[options valueForKey:@"measureSystem"] integerValue]; + if([options valueForKey:@"barcodeParserType"] != nil) + processParams.barcodeParserType = [options valueForKey:@"barcodeParserType"]; + if([options valueForKey:@"perspectiveAngle"] != nil) + processParams.perspectiveAngle = [options valueForKey:@"perspectiveAngle"]; + if([options valueForKey:@"minDPI"] != nil) + processParams.minDPI = [options valueForKey:@"minDPI"]; + if([options valueForKey:@"imageDpiOutMax"] != nil) + processParams.imageDpiOutMax = [options valueForKey:@"imageDpiOutMax"]; + if([options valueForKey:@"forceDocID"] != nil) + processParams.forceDocID = [options valueForKey:@"forceDocID"]; + if([options valueForKey:@"forceDocFormat"] != nil) + processParams.forceDocFormat = [options valueForKey:@"forceDocFormat"]; + if([options valueForKey:@"shiftExpiryDate"] != nil) + processParams.shiftExpiryDate = [options valueForKey:@"shiftExpiryDate"]; + if([options valueForKey:@"minimalHolderAge"] != nil) + processParams.minimalHolderAge = [options valueForKey:@"minimalHolderAge"]; + if([options valueForKey:@"imageOutputMaxHeight"] != nil) + processParams.imageOutputMaxHeight = [options valueForKey:@"imageOutputMaxHeight"]; + if([options valueForKey:@"imageOutputMaxWidth"] != nil) + processParams.imageOutputMaxWidth = [options valueForKey:@"imageOutputMaxWidth"]; + if([options valueForKey:@"processAuth"] != nil) + processParams.processAuth = [options valueForKey:@"processAuth"]; + if([options valueForKey:@"convertCase"] != nil) + processParams.convertCase = [self textProcessingWithNumber:[options valueForKey:@"convertCase"]]; + if(options[@"logLevel"]) processParams.logLevel = options[@"logLevel"]; + if(options[@"mrzDetectMode"]) processParams.mrzDetectMode = options[@"mrzDetectMode"]; + if(options[@"pdfPagesLimit"]) processParams.pdfPagesLimit = options[@"pdfPagesLimit"]; + + // String + if([options valueForKey:@"dateFormat"] != nil) + processParams.dateFormat = [options valueForKey:@"dateFormat"]; + if([options valueForKey:@"scenario"] != nil) + processParams.scenario = [options valueForKey:@"scenario"]; + if([options valueForKey:@"captureButtonScenario"] != nil) + processParams.captureButtonScenario = [options valueForKey:@"captureButtonScenario"]; + + // Double + if([options valueForKey:@"timeout"] != nil) + processParams.timeout = [options valueForKey:@"timeout"]; + if([options valueForKey:@"timeoutFromFirstDetect"] != nil) + processParams.timeoutFromFirstDetect = [options valueForKey:@"timeoutFromFirstDetect"]; + if([options valueForKey:@"timeoutFromFirstDocType"] != nil) + processParams.timeoutFromFirstDocType = [options valueForKey:@"timeoutFromFirstDocType"]; + if([options valueForKey:@"documentAreaMin"] != nil) + processParams.documentAreaMin = [options valueForKey:@"documentAreaMin"]; + if([options valueForKey:@"timeoutLiveness"] != nil) + processParams.timeoutLiveness = [options valueForKey:@"timeoutLiveness"]; + + // JSONArray + if([options valueForKey:@"documentIDList"] != nil) + processParams.documentIDList = [options valueForKey:@"documentIDList"]; + if([options valueForKey:@"fieldTypesFilter"] != nil) + processParams.fieldTypesFilter = [options valueForKey:@"fieldTypesFilter"]; + if([options valueForKey:@"barcodeTypes"] != nil) + processParams.barcodeTypes = [options valueForKey:@"barcodeTypes"]; + if([options valueForKey:@"resultTypeOutput"] != nil) + processParams.resultTypeOutput = [options valueForKey:@"resultTypeOutput"]; + if([options valueForKey:@"mrzFormatsFilter"] != nil) + processParams.mrzFormatsFilter = [options valueForKey:@"mrzFormatsFilter"]; + if([options valueForKey:@"documentGroupFilter"] != nil) + processParams.documentGroupFilter = [options mutableArrayValueForKey:@"documentGroupFilter"]; + if([options valueForKey:@"lcidIgnoreFilter"] != nil) + processParams.lcidIgnoreFilter = [options mutableArrayValueForKey:@"lcidIgnoreFilter"]; + if (options[@"lcidFilter"]) processParams.lcidFilter = options[@"lcidFilter"]; + if (options[@"fieldTypesIgnoreFilter"]) processParams.fieldTypesIgnoreFilter = options[@"fieldTypesIgnoreFilter"]; + + // JSONObject + if (options[@"customParams"]) processParams.customParams = options[@"customParams"]; + if ([options valueForKey:@"imageQA"] != nil) + [self setImageQA:processParams.imageQA input:[options valueForKey:@"imageQA"]]; + if ([options valueForKey:@"authenticityParams"] != nil) { + if(processParams.authenticityParams == nil) processParams.authenticityParams = [RGLAuthenticityParams defaultParams]; + [self setAuthenticityParams:processParams.authenticityParams input:[options valueForKey:@"authenticityParams"]]; + } + if ([options valueForKey:@"rfidParams"] != nil) + processParams.rfidParams = [RGLWJSONConstructor rfidParamsFromJson:[options valueForKey:@"rfidParams"]]; + if ([options valueForKey:@"faceApiParams"] != nil) + processParams.faceApiParams = [RGLWJSONConstructor faceAPIParamsFromJson:[options valueForKey:@"faceApiParams"]]; + if ([options valueForKey:@"backendProcessingConfig"] != nil) + processParams.backendProcessingConfig = [RGLWJSONConstructor backendProcessingConfigFromJson:[options valueForKey:@"backendProcessingConfig"]]; + if (options[@"bsiTr03135"]) processParams.bsiTr03135 = [RGLWJSONConstructor bsiFromJson:options[@"bsiTr03135"]]; +} + ++(NSDictionary*)getProcessParams:(RGLProcessParams*)processParams { + NSMutableDictionary *result = [NSMutableDictionary new]; + + // Boolean + result[@"multipageProcessing"] = processParams.multipageProcessing; + result[@"logs"] = processParams.logs; + result[@"debugSaveImages"] = processParams.debugSaveImages; + result[@"debugSaveLogs"] = processParams.debugSaveLogs; + result[@"returnUncroppedImage"] = processParams.returnUncroppedImage; + result[@"debugSaveCroppedImages"] = processParams.debugSaveCroppedImages; + result[@"disableFocusingCheck"] = processParams.disableFocusingCheck; + result[@"debugSaveRFIDSession"] = processParams.debugSaveRFIDSession; + result[@"doublePageSpread"] = processParams.doublePageSpread; + result[@"manualCrop"] = processParams.manualCrop; + result[@"integralImage"] = processParams.integralImage; + result[@"returnCroppedBarcode"] = processParams.returnCroppedBarcode; + result[@"checkRequiredTextFields"] = processParams.checkRequiredTextFields; + result[@"depersonalizeLog"] = processParams.depersonalizeLog; + result[@"generateDoublePageSpreadImage"] = processParams.generateDoublePageSpreadImage; + result[@"alreadyCropped"] = processParams.alreadyCropped; + result[@"matchTextFieldMask"] = processParams.matchTextFieldMask; + result[@"updateOCRValidityByGlare"] = processParams.updateOCRValidityByGlare; + result[@"noGraphics"] = processParams.noGraphics; + result[@"multiDocOnImage"] = processParams.multiDocOnImage; + result[@"parseBarcodes"] = processParams.parseBarcodes; + result[@"shouldReturnPackageForReprocess"] = processParams.shouldReturnPackageForReprocess; + result[@"disablePerforationOCR"] = processParams.disablePerforationOCR; + result[@"respectImageQuality"] = processParams.respectImageQuality; + result[@"strictImageQuality"] = processParams.strictImageQuality; + result[@"splitNames"] = processParams.splitNames; + result[@"doDetectCan"] = processParams.doDetectCan; + result[@"useFaceApi"] = processParams.useFaceApi; + result[@"useAuthenticityCheck"] = processParams.useAuthenticityCheck; + result[@"checkHologram"] = processParams.checkHologram; + result[@"generateNumericCodes"] = processParams.generateNumericCodes; + result[@"strictBarcodeDigitalSignatureCheck"] = processParams.strictBarcodeDigitalSignatureCheck; + result[@"selectLongestNames"] = processParams.selectLongestNames; + result[@"generateDTCVC"] = processParams.generateDTCVC; + result[@"strictDLCategoryExpiry"] = processParams.strictDLCategoryExpiry; + result[@"generateAlpha2Codes"] = processParams.generateAlpha2Codes; + result[@"disableAuthResolutionFilter"] = processParams.disableAuthResolutionFilter; + result[@"strictSecurityChecks"] = processParams.strictSecurityChecks; + result[@"returnTransliteratedFields"] = processParams.returnTransliteratedFields; + result[@"checkCaptureProcessIntegrity"] = processParams.checkCaptureProcessIntegrity; + result[@"strictExpiryDate"] = processParams.strictExpiryDate; + result[@"debugSaveBinarySession"] = processParams.debugSaveBinarySession; + result[@"checkVDS"] = processParams.checkVDS; + result[@"strictAgeCheck"] = processParams.strictAgeCheck; + + // Int + result[@"measureSystem"] = [NSNumber numberWithInteger:processParams.measureSystem]; + result[@"barcodeParserType"] = processParams.barcodeParserType; + result[@"perspectiveAngle"] = processParams.perspectiveAngle; + result[@"minDPI"] = processParams.minDPI; + result[@"imageDpiOutMax"] = processParams.imageDpiOutMax; + result[@"forceDocID"] = processParams.forceDocID; + result[@"forceDocFormat"] = processParams.forceDocFormat; + result[@"shiftExpiryDate"] = processParams.shiftExpiryDate; + result[@"minimalHolderAge"] = processParams.minimalHolderAge; + result[@"imageOutputMaxHeight"] = processParams.imageOutputMaxHeight; + result[@"imageOutputMaxWidth"] = processParams.imageOutputMaxWidth; + result[@"processAuth"] = processParams.processAuth; + result[@"convertCase"] = [self generateWithTextProcessing:processParams.convertCase]; + result[@"logLevel"] = processParams.logLevel; + result[@"mrzDetectMode"] = processParams.mrzDetectMode; + result[@"pdfPagesLimit"] = processParams.pdfPagesLimit; + + // String + result[@"dateFormat"] = processParams.dateFormat; + result[@"scenario"] = processParams.scenario; + result[@"captureButtonScenario"] = processParams.captureButtonScenario; + + // Double + result[@"timeout"] = processParams.timeout; + result[@"timeoutFromFirstDetect"] = processParams.timeoutFromFirstDetect; + result[@"timeoutFromFirstDocType"] = processParams.timeoutFromFirstDocType; + result[@"documentAreaMin"] = processParams.documentAreaMin; + result[@"timeoutLiveness"] = processParams.timeoutLiveness; + + // JSONArray + result[@"documentIDList"] = processParams.documentIDList; + result[@"barcodeTypes"] = processParams.barcodeTypes; + result[@"fieldTypesFilter"] = processParams.fieldTypesFilter; + result[@"documentGroupFilter"] = processParams.documentGroupFilter; + result[@"lcidIgnoreFilter"] = processParams.lcidIgnoreFilter; + result[@"lcidFilter"] = processParams.lcidFilter; + result[@"fieldTypesIgnoreFilter"] = processParams.fieldTypesIgnoreFilter; + result[@"mrzFormatsFilter"] = processParams.mrzFormatsFilter; + result[@"resultTypeOutput"] = processParams.resultTypeOutput; + + // JSONObject + result[@"imageQA"] = [self getImageQA:processParams.imageQA]; + result[@"authenticityParams"] = [self getAuthenticityParams:processParams.authenticityParams]; + result[@"rfidParams"] = [RGLWJSONConstructor generateRFIDParams:processParams.rfidParams]; + result[@"faceApiParams"] = [RGLWJSONConstructor generateFaceAPIParams:processParams.faceApiParams]; + result[@"backendProcessingConfig"] = [RGLWJSONConstructor generateBackendProcessingConfig:processParams.backendProcessingConfig]; + result[@"bsiTr03135"] = [RGLWJSONConstructor generateBsi:processParams.bsiTr03135]; + + // Custom + result[@"customParams"] = processParams.customParams; + + return result; +} + ++(void)setCustomization:(NSDictionary*)options :(RGLCustomization*)customization { + // Boolean + if([options valueForKey:@"showStatusMessages"] != nil) + customization.showStatusMessages = [[options valueForKey:@"showStatusMessages"] boolValue]; + if([options valueForKey:@"showResultStatusMessages"] != nil) + customization.showResultStatusMessages = [[options valueForKey:@"showResultStatusMessages"] boolValue]; + if([options valueForKey:@"showHelpAnimation"] != nil) + customization.showHelpAnimation = [[options valueForKey:@"showHelpAnimation"] boolValue]; + if([options valueForKey:@"showNextPageAnimation"] != nil) + customization.showNextPageAnimation = [[options valueForKey:@"showNextPageAnimation"] boolValue]; + if([options valueForKey:@"showBackgroundMask"] != nil) + customization.showBackgroundMask = [[options valueForKey:@"showBackgroundMask"] boolValue]; + + // Int + if([options valueForKey:@"cameraFrameBorderWidth"] != nil) + customization.cameraFrameBorderWidth = [[options valueForKey:@"cameraFrameBorderWidth"] floatValue]; + if([options valueForKey:@"cameraFrameLineLength"] != nil) + customization.cameraFrameLineLength = [[options valueForKey:@"cameraFrameLineLength"] floatValue]; + if([options valueForKey:@"cameraFrameShapeType"] != nil) + customization.cameraFrameShapeType = [[options valueForKey:@"cameraFrameShapeType"] integerValue]; + if([options valueForKey:@"cameraFrameOffsetWidth"] != nil) + customization.cameraFrameOffsetWidth = [[options valueForKey:@"cameraFrameOffsetWidth"] floatValue]; + if(options[@"nextPageAnimationStartDelay"]) customization.nextPageAnimationStartDelay = [options[@"nextPageAnimationStartDelay"] floatValue]; + if(options[@"nextPageAnimationEndDelay"]) customization.nextPageAnimationEndDelay = [options[@"nextPageAnimationEndDelay"] floatValue]; + + // String + if([options valueForKey:@"status"] != nil) + customization.status = [options valueForKey:@"status"]; + if([options valueForKey:@"resultStatus"] != nil) + customization.resultStatus = [options valueForKey:@"resultStatus"]; + if(options[@"multipageButtonText"]) customization.multipageButtonText = options[@"multipageButtonText"]; + + // Color + if([options valueForKey:@"cameraFrameDefaultColor"] != nil) + customization.cameraFrameDefaultColor = [self colorWithInt:[options valueForKey:@"cameraFrameDefaultColor"]]; + if([options valueForKey:@"cameraFrameActiveColor"] != nil) + customization.cameraFrameActiveColor = [self colorWithInt:[options valueForKey:@"cameraFrameActiveColor"]]; + if([options valueForKey:@"statusTextColor"] != nil) + customization.statusTextColor = [self colorWithInt:[options valueForKey:@"statusTextColor"]]; + if([options valueForKey:@"resultStatusTextColor"] != nil) + customization.resultStatusTextColor = [self colorWithInt:[options valueForKey:@"resultStatusTextColor"]]; + if([options valueForKey:@"resultStatusBackgroundColor"] != nil) + customization.resultStatusBackgroundColor = [self colorWithInt:[options valueForKey:@"resultStatusBackgroundColor"]]; + if([options valueForKey:@"multipageButtonBackgroundColor"] != nil) + customization.multipageButtonBackgroundColor = [self colorWithInt:[options valueForKey:@"multipageButtonBackgroundColor"]]; + if([options valueForKey:@"tintColor"] != nil) + customization.tintColor = [self colorWithInt:[options valueForKey:@"tintColor"]]; + if([options valueForKey:@"activityIndicatorColor"] != nil) + customization.activityIndicatorColor = [self colorWithInt:[options valueForKey:@"activityIndicatorColor"]]; + if([options valueForKey:@"statusBackgroundColor"] != nil) + customization.statusBackgroundColor = [self colorWithInt:[options valueForKey:@"statusBackgroundColor"]]; + if([options valueForKey:@"cameraPreviewBackgroundColor"] != nil) + customization.cameraPreviewBackgroundColor = [self colorWithInt:[options valueForKey:@"cameraPreviewBackgroundColor"]]; + if([options valueForKey:@"backgroundMaskColor"] != nil) + customization.backgroundMaskColor = [self colorWithInt:[options valueForKey:@"backgroundMaskColor"]]; + if(options[@"multipageButtonTextColor"]) customization.multipageButtonTextColor = [self colorWithInt:options[@"multipageButtonTextColor"]]; + + // Float + if([options valueForKey:@"statusPositionMultiplier"] != nil) + customization.statusPositionMultiplier = [[options valueForKey:@"statusPositionMultiplier"] floatValue]; + if([options valueForKey:@"resultStatusPositionMultiplier"] != nil) + customization.resultStatusPositionMultiplier = [[options valueForKey:@"resultStatusPositionMultiplier"] floatValue]; + if([options valueForKey:@"toolbarSize"] != nil) + customization.toolbarSize = [[options valueForKey:@"toolbarSize"] floatValue]; + if([options valueForKey:@"backgroundMaskAlpha"] != nil) + customization.backgroundMaskAlpha = [[options valueForKey:@"backgroundMaskAlpha"] floatValue]; + if([options valueForKey:@"customStatusPositionMultiplier"] != nil) + customization.customStatusPositionMultiplier = [[options valueForKey:@"customStatusPositionMultiplier"] floatValue]; + if([options valueForKey:@"cameraFrameVerticalPositionMultiplier"] != nil) + customization.cameraFrameVerticalPositionMultiplier = [[options valueForKey:@"cameraFrameVerticalPositionMultiplier"] floatValue]; + if([options valueForKey:@"cameraFrameLandscapeAspectRatio"] != nil) + customization.cameraFrameLandscapeAspectRatio = [[options valueForKey:@"cameraFrameLandscapeAspectRatio"] floatValue]; + if([options valueForKey:@"cameraFramePortraitAspectRatio"] != nil) + customization.cameraFramePortraitAspectRatio = [[options valueForKey:@"cameraFramePortraitAspectRatio"] floatValue]; + if([options valueForKey:@"cameraFrameCornerRadius"] != nil) + customization.cameraFrameCornerRadius = [[options valueForKey:@"cameraFrameCornerRadius"] floatValue]; + if([options valueForKey:@"livenessAnimationPositionMultiplier"] != nil) + customization.livenessAnimationPositionMultiplier = [[options valueForKey:@"livenessAnimationPositionMultiplier"] floatValue]; + if(options[@"activityIndicatorPortraitPositionMultiplier"]) customization.activityIndicatorPortraitPositionMultiplier = [options[@"activityIndicatorPortraitPositionMultiplier"] floatValue]; + if(options[@"activityIndicatorLandscapePositionMultiplier"]) customization.activityIndicatorLandscapePositionMultiplier = [options[@"activityIndicatorLandscapePositionMultiplier"] floatValue]; + if(options[@"cameraPreviewVerticalPositionMultiplier"]) customization.previewLayerPositionMultiplier = [options[@"cameraPreviewVerticalPositionMultiplier"] floatValue]; + if(options[@"multipageButtonPositionMultiplier"]) customization.multipageButtonPositionMultiplier = [options[@"multipageButtonPositionMultiplier"] floatValue]; + + // Drawable + if([options valueForKey:@"multipageAnimationFrontImage"] != nil) + customization.multipageAnimationFrontImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"multipageAnimationFrontImage"]]; + if([options valueForKey:@"multipageAnimationBackImage"] != nil) + customization.multipageAnimationBackImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"multipageAnimationBackImage"]]; + if([options valueForKey:@"borderBackgroundImage"] != nil) + customization.borderBackgroundImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"borderBackgroundImage"]]; + if([options valueForKey:@"helpAnimationImage"] != nil) + customization.helpAnimationImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"helpAnimationImage"]]; + if([options valueForKey:@"closeButtonImage"] != nil) + customization.closeButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"closeButtonImage"]]; + if([options valueForKey:@"captureButtonImage"] != nil) + customization.captureButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"captureButtonImage"]]; + if([options valueForKey:@"changeFrameButtonCollapseImage"] != nil) + customization.changeFrameButtonCollapseImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"changeFrameButtonCollapseImage"]]; + if([options valueForKey:@"changeFrameButtonExpandImage"] != nil) + customization.changeFrameButtonExpandImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"changeFrameButtonExpandImage"]]; + if([options valueForKey:@"cameraSwitchButtonImage"] != nil) + customization.cameraSwitchButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"cameraSwitchButtonImage"]]; + if([options valueForKey:@"torchButtonOnImage"] != nil) + customization.torchButtonOnImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"torchButtonOnImage"]]; + if([options valueForKey:@"torchButtonOffImage"] != nil) + customization.torchButtonOffImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"torchButtonOffImage"]]; + if([options valueForKey:@"livenessAnimationImage"] != nil) + customization.livenessAnimationImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"livenessAnimationImage"]]; + if(options[@"multipageButtonImage"]) customization.multipageButtonImage = [RGLWJSONConstructor imageWithBase64:options[@"multipageButtonImage"]]; + + // Font + if([options valueForKey:@"statusTextFont"] != nil) + customization.statusTextFont = [self UIFontFromJSON:[options valueForKey:@"statusTextFont"]]; + if([options valueForKey:@"resultStatusTextFont"] != nil) + customization.resultStatusTextFont = [self UIFontFromJSON:[options valueForKey:@"resultStatusTextFont"]]; + if(options[@"multipageButtonTextFont"]) customization.multipageButtonTextFont = [self UIFontFromJSON:options[@"multipageButtonTextFont"]]; + + // Custom + if([options valueForKey:@"customLabelStatus"] != nil) + customization.customLabelStatus = [[NSAttributedString alloc]initWithString:[options valueForKey:@"customLabelStatus"]]; + if([options valueForKey:@"cameraFrameLineCap"] != nil) + customization.cameraFrameLineCap = [self lineCapWithNumber:[options valueForKey:@"cameraFrameLineCap"]]; + if([options valueForKey:@"uiCustomizationLayer"] != nil) + customization.customUILayerJSON = [options valueForKey:@"uiCustomizationLayer"]; + + // ContentMode + if([options valueForKey:@"helpAnimationImageContentMode"] != nil) + customization.helpAnimationImageContentMode = [self viewContentModeWithNumber:[options valueForKey:@"helpAnimationImageContentMode"]]; + if([options valueForKey:@"multipageAnimationFrontImageContentMode"] != nil) + customization.multipageAnimationFrontImageContentMode = [self viewContentModeWithNumber:[options valueForKey:@"multipageAnimationFrontImageContentMode"]]; + if([options valueForKey:@"multipageAnimationBackImageContentMode"] != nil) + customization.multipageAnimationBackImageContentMode = [self viewContentModeWithNumber:[options valueForKey:@"multipageAnimationBackImageContentMode"]]; + if([options valueForKey:@"livenessAnimationImageContentMode"] != nil) + customization.livenessAnimationImageContentMode = [self viewContentModeWithNumber:[options valueForKey:@"livenessAnimationImageContentMode"]]; + if([options valueForKey:@"borderBackgroundImageContentMode"] != nil) + customization.borderBackgroundImageContentMode = [self viewContentModeWithNumber:[options valueForKey:@"borderBackgroundImageContentMode"]]; + + if(options[@"colors"]) [self setColors:[customization.uiConfiguration valueForKey:@"colors"] input:options[@"colors"]]; + if(options[@"fonts"]) [self setFonts:[customization.uiConfiguration valueForKey:@"fonts"] input:options[@"fonts"]]; + if(options[@"images"]) [self setImages:[customization.uiConfiguration valueForKey:@"images"] input:options[@"images"]]; + if(options[@"timings"]) [self setTimings:[customization.uiConfiguration valueForKey:@"timings"] input:options[@"timings"]]; + if(options[@"contentModes"]) [self setContentModes:[customization.uiConfiguration valueForKey:@"contentModes"] input:options[@"contentModes"]]; +} + ++(NSDictionary*)getCustomization:(RGLCustomization*)customization { + NSMutableDictionary *result = [NSMutableDictionary new]; + + // Boolean + result[@"showStatusMessages"] = [NSNumber numberWithBool:customization.showStatusMessages]; + result[@"showResultStatusMessages"] = [NSNumber numberWithBool:customization.showResultStatusMessages]; + result[@"showHelpAnimation"] = [NSNumber numberWithBool:customization.showHelpAnimation]; + result[@"showNextPageAnimation"] = [NSNumber numberWithBool:customization.showNextPageAnimation]; + result[@"showBackgroundMask"] = [NSNumber numberWithBool:customization.showBackgroundMask]; + + // Int + result[@"cameraFrameBorderWidth"] = [NSNumber numberWithFloat:customization.cameraFrameBorderWidth]; + result[@"cameraFrameLineLength"] = [NSNumber numberWithFloat:customization.cameraFrameLineLength]; + result[@"cameraFrameShapeType"] = [NSNumber numberWithFloat:customization.cameraFrameShapeType]; + result[@"cameraFrameOffsetWidth"] = [NSNumber numberWithFloat:customization.cameraFrameOffsetWidth]; + result[@"nextPageAnimationStartDelay"] = [NSNumber numberWithFloat:customization.nextPageAnimationStartDelay]; + result[@"nextPageAnimationEndDelay"] = [NSNumber numberWithFloat:customization.nextPageAnimationEndDelay]; + + // String + result[@"status"] = customization.status; + result[@"resultStatus"] = customization.resultStatus; + result[@"multipageButtonText"] = customization.multipageButtonText; + + // Color + result[@"cameraFrameDefaultColor"] = [self intWithColor:customization.cameraFrameDefaultColor]; + result[@"cameraFrameActiveColor"] = [self intWithColor:customization.cameraFrameActiveColor]; + result[@"statusTextColor"] = [self intWithColor:customization.statusTextColor]; + result[@"resultStatusTextColor"] = [self intWithColor:customization.resultStatusTextColor]; + result[@"resultStatusBackgroundColor"] = [self intWithColor:customization.resultStatusBackgroundColor]; + result[@"multipageButtonBackgroundColor"] = [self intWithColor:customization.multipageButtonBackgroundColor]; + result[@"tintColor"] = [self intWithColor:customization.tintColor]; + result[@"activityIndicatorColor"] = [self intWithColor:customization.activityIndicatorColor]; + result[@"statusBackgroundColor"] = [self intWithColor:customization.statusBackgroundColor]; + result[@"cameraPreviewBackgroundColor"] = [self intWithColor:customization.cameraPreviewBackgroundColor]; + result[@"backgroundMaskColor"] = [self intWithColor:customization.backgroundMaskColor]; + result[@"multipageButtonTextColor"] = [self intWithColor:customization.multipageButtonTextColor]; + + // Float + result[@"statusPositionMultiplier"] = [NSNumber numberWithFloat:customization.statusPositionMultiplier]; + result[@"resultStatusPositionMultiplier"] = [NSNumber numberWithFloat:customization.resultStatusPositionMultiplier]; + result[@"backgroundMaskAlpha"] = [NSNumber numberWithFloat:customization.backgroundMaskAlpha]; + result[@"toolbarSize"] = [NSNumber numberWithFloat:customization.toolbarSize]; + result[@"customStatusPositionMultiplier"] = [NSNumber numberWithFloat:customization.customStatusPositionMultiplier]; + result[@"cameraFrameVerticalPositionMultiplier"] = [NSNumber numberWithFloat:customization.cameraFrameVerticalPositionMultiplier]; + result[@"cameraFrameLandscapeAspectRatio"] = [NSNumber numberWithFloat:customization.cameraFrameLandscapeAspectRatio]; + result[@"cameraFramePortraitAspectRatio"] = [NSNumber numberWithFloat:customization.cameraFramePortraitAspectRatio]; + result[@"cameraFrameCornerRadius"] = [NSNumber numberWithFloat:customization.cameraFrameCornerRadius]; + result[@"livenessAnimationPositionMultiplier"] = [NSNumber numberWithFloat:customization.livenessAnimationPositionMultiplier]; + result[@"activityIndicatorPortraitPositionMultiplier"] = [NSNumber numberWithFloat:customization.activityIndicatorPortraitPositionMultiplier]; + result[@"activityIndicatorLandscapePositionMultiplier"] = [NSNumber numberWithFloat:customization.activityIndicatorLandscapePositionMultiplier]; + result[@"cameraPreviewVerticalPositionMultiplier"] = [NSNumber numberWithFloat:customization.previewLayerPositionMultiplier]; + result[@"multipageButtonPositionMultiplier"] = [NSNumber numberWithFloat:customization.multipageButtonPositionMultiplier]; + + // Drawable + result[@"multipageAnimationFrontImage"] = [RGLWJSONConstructor base64WithImage:customization.multipageAnimationFrontImage]; + result[@"multipageAnimationBackImage"] = [RGLWJSONConstructor base64WithImage:customization.multipageAnimationBackImage]; + result[@"borderBackgroundImage"] = [RGLWJSONConstructor base64WithImage:customization.borderBackgroundImage]; + result[@"helpAnimationImage"] = [RGLWJSONConstructor base64WithImage:customization.helpAnimationImage]; + result[@"closeButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.closeButtonImage]; + result[@"captureButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.captureButtonImage]; + result[@"changeFrameButtonCollapseImage"] = [RGLWJSONConstructor base64WithImage:customization.changeFrameButtonCollapseImage]; + result[@"changeFrameButtonExpandImage"] = [RGLWJSONConstructor base64WithImage:customization.changeFrameButtonExpandImage]; + result[@"cameraSwitchButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.cameraSwitchButtonImage]; + result[@"torchButtonOnImage"] = [RGLWJSONConstructor base64WithImage:customization.torchButtonOnImage]; + result[@"torchButtonOffImage"] = [RGLWJSONConstructor base64WithImage:customization.torchButtonOffImage]; + result[@"livenessAnimationImage"] = [RGLWJSONConstructor base64WithImage:customization.livenessAnimationImage]; + result[@"multipageButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.multipageButtonImage]; + + // Font + result[@"statusTextFont"] = [self generateUIFont:customization.statusTextFont]; + result[@"resultStatusTextFont"] = [self generateUIFont:customization.resultStatusTextFont]; + result[@"multipageButtonTextFont"] = [self generateUIFont:customization.multipageButtonTextFont]; + + // Custom + if(customization.customLabelStatus != nil) result[@"customLabelStatus"] = customization.customLabelStatus.string; + result[@"cameraFrameLineCap"] = [self generateLineCap:customization.cameraFrameLineCap]; + result[@"uiCustomizationLayer"] = customization.customUILayerJSON; + + // ContentMode + result[@"helpAnimationImageContentMode"] = [self generateViewContentMode:customization.helpAnimationImageContentMode]; + result[@"multipageAnimationFrontImageContentMode"] = [self generateViewContentMode:customization.multipageAnimationFrontImageContentMode]; + result[@"multipageAnimationBackImageContentMode"] = [self generateViewContentMode:customization.multipageAnimationBackImageContentMode]; + result[@"livenessAnimationImageContentMode"] = [self generateViewContentMode:customization.livenessAnimationImageContentMode]; + result[@"borderBackgroundImageContentMode"] = [self generateViewContentMode:customization.borderBackgroundImageContentMode]; + + result[@"colors"] = [self getColors: [customization.uiConfiguration valueForKey:@"colors"]]; + result[@"fonts"] = [self getFonts: [customization.uiConfiguration valueForKey:@"fonts"]]; + result[@"images"] = [self getImages: [customization.uiConfiguration valueForKey:@"images"]]; + result[@"timings"] = [self getTimings: [customization.uiConfiguration valueForKey:@"timings"]]; + result[@"contentModes"] = [self getContentModes: [customization.uiConfiguration valueForKey:@"contentModes"]]; + + return result; +} + ++(void)setRfidScenario:(NSDictionary*)options :(RGLRFIDScenario*)rfidScenario { + // Boolean + if([options valueForKey:@"paceStaticBinding"] != nil) + rfidScenario.paceStaticBinding = [[options valueForKey:@"paceStaticBinding"] boolValue]; + if([options valueForKey:@"onlineTA"] != nil) + rfidScenario.onlineTA = [[options valueForKey:@"onlineTA"] boolValue]; + if([options valueForKey:@"writeEid"] != nil) + rfidScenario.writeEid = [[options valueForKey:@"writeEid"] boolValue]; + if([options valueForKey:@"universalAccessRights"] != nil) + rfidScenario.universalAccessRights = [[options valueForKey:@"universalAccessRights"] boolValue]; + if([options valueForKey:@"authorizedRestrictedIdentification"] != nil) + rfidScenario.authorizedRestrictedIdentification = [[options valueForKey:@"authorizedRestrictedIdentification"] boolValue]; + if([options valueForKey:@"auxVerificationCommunityID"] != nil) + rfidScenario.auxVerificationCommunityID = [[options valueForKey:@"auxVerificationCommunityID"] boolValue]; + if([options valueForKey:@"auxVerificationDateOfBirth"] != nil) + rfidScenario.auxVerificationDateOfBirth = [[options valueForKey:@"auxVerificationDateOfBirth"] boolValue]; + if([options valueForKey:@"skipAA"] != nil) + rfidScenario.skipAA = [[options valueForKey:@"skipAA"] boolValue]; + if([options valueForKey:@"strictProcessing"] != nil) + rfidScenario.strictProcessing = [[options valueForKey:@"strictProcessing"] boolValue]; + if([options valueForKey:@"pkdDSCertPriority"] != nil) + rfidScenario.pkdDSCertPriority = [[options valueForKey:@"pkdDSCertPriority"] boolValue]; + if([options valueForKey:@"pkdUseExternalCSCA"] != nil) + rfidScenario.pkdUseExternalCSCA = [[options valueForKey:@"pkdUseExternalCSCA"] boolValue]; + if([options valueForKey:@"trustedPKD"] != nil) + rfidScenario.trustedPKD = [[options valueForKey:@"trustedPKD"] boolValue]; + if([options valueForKey:@"passiveAuth"] != nil) + rfidScenario.passiveAuth = [[options valueForKey:@"passiveAuth"] boolValue]; + if([options valueForKey:@"useSFI"] != nil) + rfidScenario.useSFI = [[options valueForKey:@"useSFI"] boolValue]; + if([options valueForKey:@"readEPassport"] != nil) + rfidScenario.readEPassport = [[options valueForKey:@"readEPassport"] boolValue]; + if([options valueForKey:@"readEID"] != nil) + rfidScenario.readEID = [[options valueForKey:@"readEID"] boolValue]; + if([options valueForKey:@"readEDL"] != nil) + rfidScenario.readEDL = [[options valueForKey:@"readEDL"] boolValue]; + if([options valueForKey:@"authorizedSTSignature"] != nil) + rfidScenario.authorizedSTSignature = [[options valueForKey:@"authorizedSTSignature"] boolValue]; + if([options valueForKey:@"authorizedSTQSignature"] != nil) + rfidScenario.authorizedSTQSignature = [[options valueForKey:@"authorizedSTQSignature"] boolValue]; + if([options valueForKey:@"authorizedWriteDG17"] != nil) + rfidScenario.authorizedWriteDG17 = [[options valueForKey:@"authorizedWriteDG17"] boolValue]; + if([options valueForKey:@"authorizedWriteDG18"] != nil) + rfidScenario.authorizedWriteDG18 = [[options valueForKey:@"authorizedWriteDG18"] boolValue]; + if([options valueForKey:@"authorizedWriteDG19"] != nil) + rfidScenario.authorizedWriteDG19 = [[options valueForKey:@"authorizedWriteDG19"] boolValue]; + if([options valueForKey:@"authorizedWriteDG20"] != nil) + rfidScenario.authorizedWriteDG20 = [[options valueForKey:@"authorizedWriteDG20"] boolValue]; + if([options valueForKey:@"authorizedWriteDG21"] != nil) + rfidScenario.authorizedWriteDG21 = [[options valueForKey:@"authorizedWriteDG21"] boolValue]; + if([options valueForKey:@"authorizedVerifyAge"] != nil) + rfidScenario.authorizedVerifyAge = [[options valueForKey:@"authorizedVerifyAge"] boolValue]; + if([options valueForKey:@"authorizedVerifyCommunityID"] != nil) + rfidScenario.authorizedVerifyCommunityID = [[options valueForKey:@"authorizedVerifyCommunityID"] boolValue]; + if([options valueForKey:@"authorizedPrivilegedTerminal"] != nil) + rfidScenario.authorizedPrivilegedTerminal = [[options valueForKey:@"authorizedPrivilegedTerminal"] boolValue]; + if([options valueForKey:@"authorizedCANAllowed"] != nil) + rfidScenario.authorizedCANAllowed = [[options valueForKey:@"authorizedCANAllowed"] boolValue]; + if([options valueForKey:@"authorizedPINManagement"] != nil) + rfidScenario.authorizedPINManagment = [[options valueForKey:@"authorizedPINManagement"] boolValue]; + if([options valueForKey:@"authorizedInstallCert"] != nil) + rfidScenario.authorizedInstallCert = [[options valueForKey:@"authorizedInstallCert"] boolValue]; + if([options valueForKey:@"authorizedInstallQCert"] != nil) + rfidScenario.authorizedInstallQCert = [[options valueForKey:@"authorizedInstallQCert"] boolValue]; + if([options valueForKey:@"applyAmendments"] != nil) + rfidScenario.applyAmendments = [[options valueForKey:@"applyAmendments"] boolValue]; + if([options valueForKey:@"autoSettings"] != nil) + rfidScenario.autoSettings = [[options valueForKey:@"autoSettings"] boolValue]; + if([options valueForKey:@"proceedReadingAlways"] != nil) + rfidScenario.proceedReadingAlways = [[options valueForKey:@"proceedReadingAlways"] boolValue]; + if(options[@"readDTC"]) rfidScenario.readDTC = [options[@"readDTC"] boolValue]; + if(options[@"mrzStrictCheck"]) rfidScenario.mrzStrictCheck = options[@"mrzStrictCheck"]; + if(options[@"loadCRLFromRemote"]) rfidScenario.loadCRLFromRemote = [options[@"loadCRLFromRemote"] boolValue]; + if(options[@"independentSODStatus"]) rfidScenario.independentSODStatus = options[@"independentSODStatus"]; + + // Int + if([options valueForKey:@"signManagementAction"] != nil) + rfidScenario.signManagementAction = [[options valueForKey:@"signManagementAction"] integerValue]; + if([options valueForKey:@"readingBuffer"] != nil) + rfidScenario.readingBuffer = [[options valueForKey:@"readingBuffer"] integerValue]; + if([options valueForKey:@"onlineTAToSignDataType"] != nil) + rfidScenario.onlineTAToSignDataType = [[options valueForKey:@"onlineTAToSignDataType"] intValue]; + if([options valueForKey:@"profilerType"] != nil) + rfidScenario.profilerType = [[options valueForKey:@"profilerType"] intValue]; + if([options valueForKey:@"authProcType"] != nil) + rfidScenario.authProcType = [[options valueForKey:@"authProcType"] integerValue]; + if([options valueForKey:@"baseSMProcedure"] != nil) + rfidScenario.baseSMProcedure = [[options valueForKey:@"baseSMProcedure"] integerValue]; + if([options valueForKey:@"pacePasswordType"] != nil) + rfidScenario.pacePasswordType = [[options valueForKey:@"pacePasswordType"] integerValue]; + if([options valueForKey:@"terminalType"] != nil) + rfidScenario.terminalType = [[options valueForKey:@"terminalType"] integerValue]; + if([options valueForKey:@"defaultReadingBufferSize"] != nil) + rfidScenario.defaultReadingBufferSize = [[options valueForKey:@"defaultReadingBufferSize"] intValue]; + + // String + if([options valueForKey:@"password"] != nil) + rfidScenario.password = [options valueForKey:@"password"]; + if([options valueForKey:@"pkdPA"] != nil) + rfidScenario.pkdPA = [options valueForKey:@"pkdPA"]; + if([options valueForKey:@"pkdEAC"] != nil) + rfidScenario.pkdEAC = [options valueForKey:@"pkdEAC"]; + if([options valueForKey:@"mrz"] != nil) + rfidScenario.mrz = [options valueForKey:@"mrz"]; + if([options valueForKey:@"eSignPINDefault"] != nil) + rfidScenario.eSignPINDefault = [options valueForKey:@"eSignPINDefault"]; + if([options valueForKey:@"eSignPINNewValue"] != nil) + rfidScenario.eSignPINNewValue = [options valueForKey:@"eSignPINNewValue"]; + if(options[@"cardAccess"]) rfidScenario.cardAccess = options[@"cardAccess"]; + if(options[@"mrzHash"]) rfidScenario.mrzHash = options[@"mrzHash"]; + if(options[@"documentNumber"]) rfidScenario.documentNumber = options[@"documentNumber"]; + if(options[@"dateOfBirth"]) rfidScenario.dateOfBirth = options[@"dateOfBirth"]; + if(options[@"dateOfExpiry"]) rfidScenario.dateOfExpiry = options[@"dateOfExpiry"]; + + // DataGroup + if([options valueForKey:@"ePassportDataGroups"] != nil) + [self setDataGroups :rfidScenario.ePassportDataGroups dict:[options valueForKey:@"ePassportDataGroups"]]; + if([options valueForKey:@"eIDDataGroups"] != nil) + [self setDataGroups :rfidScenario.eIDDataGroups dict:[options valueForKey:@"eIDDataGroups"]]; + if([options valueForKey:@"eDLDataGroups"] != nil) + [self setDataGroups :rfidScenario.eDLDataGroups dict:[options valueForKey:@"eDLDataGroups"]]; + if(options[@"dtcDataGroups"]) [self setDTCDataGroup :rfidScenario.DTCDataGroups dict:options[@"dtcDataGroups"]]; +} + ++(NSDictionary*)getRfidScenario:(RGLRFIDScenario*)rfidScenario { + NSMutableDictionary *result = [NSMutableDictionary new]; + + // Boolean + result[@"paceStaticBinding"] = [NSNumber numberWithBool:rfidScenario.paceStaticBinding]; + result[@"onlineTA"] = [NSNumber numberWithBool:rfidScenario.onlineTA]; + result[@"writeEid"] = [NSNumber numberWithBool:rfidScenario.writeEid]; + result[@"universalAccessRights"] = [NSNumber numberWithBool:rfidScenario.universalAccessRights]; + result[@"authorizedRestrictedIdentification"] = [NSNumber numberWithBool:rfidScenario.authorizedRestrictedIdentification]; + result[@"auxVerificationCommunityID"] = [NSNumber numberWithBool:rfidScenario.auxVerificationCommunityID]; + result[@"auxVerificationDateOfBirth"] = [NSNumber numberWithBool:rfidScenario.auxVerificationDateOfBirth]; + result[@"skipAA"] = [NSNumber numberWithBool:rfidScenario.skipAA]; + result[@"strictProcessing"] = [NSNumber numberWithBool:rfidScenario.strictProcessing]; + result[@"pkdDSCertPriority"] = [NSNumber numberWithBool:rfidScenario.pkdDSCertPriority]; + result[@"pkdUseExternalCSCA"] = [NSNumber numberWithBool:rfidScenario.pkdUseExternalCSCA]; + result[@"trustedPKD"] = [NSNumber numberWithBool:rfidScenario.trustedPKD]; + result[@"passiveAuth"] = [NSNumber numberWithBool:rfidScenario.passiveAuth]; + result[@"useSFI"] = [NSNumber numberWithBool:rfidScenario.useSFI]; + result[@"readEPassport"] = [NSNumber numberWithBool:rfidScenario.readEPassport]; + result[@"readEID"] = [NSNumber numberWithBool:rfidScenario.readEID]; + result[@"readEDL"] = [NSNumber numberWithBool:rfidScenario.readEDL]; + result[@"authorizedSTSignature"] = [NSNumber numberWithBool:rfidScenario.authorizedSTSignature]; + result[@"authorizedSTQSignature"] = [NSNumber numberWithBool:rfidScenario.authorizedSTQSignature]; + result[@"authorizedWriteDG17"] = [NSNumber numberWithBool:rfidScenario.authorizedWriteDG17]; + result[@"authorizedWriteDG18"] = [NSNumber numberWithBool:rfidScenario.authorizedWriteDG18]; + result[@"authorizedWriteDG19"] = [NSNumber numberWithBool:rfidScenario.authorizedWriteDG19]; + result[@"authorizedWriteDG20"] = [NSNumber numberWithBool:rfidScenario.authorizedWriteDG20]; + result[@"authorizedWriteDG21"] = [NSNumber numberWithBool:rfidScenario.authorizedWriteDG21]; + result[@"authorizedVerifyAge"] = [NSNumber numberWithBool:rfidScenario.authorizedVerifyAge]; + result[@"authorizedVerifyCommunityID"] = [NSNumber numberWithBool:rfidScenario.authorizedVerifyCommunityID]; + result[@"authorizedPrivilegedTerminal"] = [NSNumber numberWithBool:rfidScenario.authorizedPrivilegedTerminal]; + result[@"authorizedCANAllowed"] = [NSNumber numberWithBool:rfidScenario.authorizedCANAllowed]; + result[@"authorizedPINManagement"] = [NSNumber numberWithBool:rfidScenario.authorizedPINManagment]; + result[@"authorizedInstallCert"] = [NSNumber numberWithBool:rfidScenario.authorizedInstallCert]; + result[@"authorizedInstallQCert"] = [NSNumber numberWithBool:rfidScenario.authorizedInstallQCert]; + result[@"applyAmendments"] = [NSNumber numberWithBool:rfidScenario.applyAmendments]; + result[@"autoSettings"] = [NSNumber numberWithBool:rfidScenario.autoSettings]; + result[@"proceedReadingAlways"] = [NSNumber numberWithBool:rfidScenario.proceedReadingAlways]; + result[@"readDTC"] = [NSNumber numberWithBool:rfidScenario.readDTC]; + result[@"mrzStrictCheck"] = rfidScenario.mrzStrictCheck; + result[@"loadCRLFromRemote"] = @(rfidScenario.loadCRLFromRemote); + result[@"independentSODStatus"] = rfidScenario.independentSODStatus; + + // Int + result[@"signManagementAction"] = [NSNumber numberWithInteger:rfidScenario.signManagementAction]; + result[@"readingBuffer"] = [NSNumber numberWithInteger:rfidScenario.readingBuffer]; + result[@"onlineTAToSignDataType"] = [NSNumber numberWithInteger:rfidScenario.onlineTAToSignDataType]; + result[@"profilerType"] = [NSNumber numberWithInteger:rfidScenario.profilerType]; + result[@"authProcType"] = [NSNumber numberWithInteger:rfidScenario.authProcType]; + result[@"baseSMProcedure"] = [NSNumber numberWithInteger:rfidScenario.baseSMProcedure]; + result[@"pacePasswordType"] = [NSNumber numberWithInteger:rfidScenario.pacePasswordType]; + result[@"terminalType"] = [NSNumber numberWithInteger:rfidScenario.terminalType]; + result[@"defaultReadingBufferSize"] = [NSNumber numberWithInteger:rfidScenario.defaultReadingBufferSize]; + + // String + result[@"password"] = rfidScenario.password; + result[@"pkdPA"] = rfidScenario.pkdPA; + result[@"pkdEAC"] = rfidScenario.pkdEAC; + result[@"mrz"] = rfidScenario.mrz; + result[@"eSignPINDefault"] = rfidScenario.eSignPINDefault; + result[@"eSignPINNewValue"] = rfidScenario.eSignPINNewValue; + result[@"cardAccess"] = rfidScenario.cardAccess; + result[@"mrzHash"] = rfidScenario.mrzHash; + result[@"documentNumber"] = rfidScenario.documentNumber; + result[@"dateOfBirth"] = rfidScenario.dateOfBirth; + result[@"dateOfExpiry"] = rfidScenario.dateOfExpiry; + + // DataGroup + result[@"eDLDataGroups"] = [self getDataGroups:rfidScenario.eDLDataGroups]; + result[@"ePassportDataGroups"] = [self getDataGroups:rfidScenario.ePassportDataGroups]; + result[@"eIDDataGroups"] = [self getDataGroups:rfidScenario.eIDDataGroups]; + result[@"dtcDataGroups"] = [self getDTCDataGroup:rfidScenario.DTCDataGroups]; + + return result; +} + ++(void)setDataGroups:(RGLDataGroup*)dataGroup dict:(NSDictionary*)dict { + + // EDLDataGroups/Common: 1-14 + if([dict valueForKey:@"DG1"] != nil) + dataGroup.dG1 = [[dict valueForKey:@"DG1"] boolValue]; + if([dict valueForKey:@"DG2"] != nil) + dataGroup.dG2 = [[dict valueForKey:@"DG2"] boolValue]; + if([dict valueForKey:@"DG3"] != nil) + dataGroup.dG3 = [[dict valueForKey:@"DG3"] boolValue]; + if([dict valueForKey:@"DG4"] != nil) + dataGroup.dG4 = [[dict valueForKey:@"DG4"] boolValue]; + if([dict valueForKey:@"DG5"] != nil) + dataGroup.dG5 = [[dict valueForKey:@"DG5"] boolValue]; + if([dict valueForKey:@"DG6"] != nil) + dataGroup.dG6 = [[dict valueForKey:@"DG6"] boolValue]; + if([dict valueForKey:@"DG7"] != nil) + dataGroup.dG7 = [[dict valueForKey:@"DG7"] boolValue]; + if([dict valueForKey:@"DG8"] != nil) + dataGroup.dG8 = [[dict valueForKey:@"DG8"] boolValue]; + if([dict valueForKey:@"DG9"] != nil) + dataGroup.dG9 = [[dict valueForKey:@"DG9"] boolValue]; + if([dict valueForKey:@"DG10"] != nil) + dataGroup.dG10 = [[dict valueForKey:@"DG10"] boolValue]; + if([dict valueForKey:@"DG11"] != nil) + dataGroup.dG11 = [[dict valueForKey:@"DG11"] boolValue]; + if([dict valueForKey:@"DG12"] != nil) + dataGroup.dG12 = [[dict valueForKey:@"DG12"] boolValue]; + if([dict valueForKey:@"DG13"] != nil) + dataGroup.dG13 = [[dict valueForKey:@"DG13"] boolValue]; + if([dict valueForKey:@"DG14"] != nil) + dataGroup.dG14 = [[dict valueForKey:@"DG14"] boolValue]; + + // EPassportDataGroups: 1-16 + if ([dataGroup class] == [RGLePassportDataGroup class]) { + if([dict valueForKey:@"DG15"] != nil) + ((RGLePassportDataGroup*)dataGroup).dG15 = [[dict valueForKey:@"DG15"] boolValue]; + if([dict valueForKey:@"DG16"] != nil) + ((RGLePassportDataGroup*)dataGroup).dG16 = [[dict valueForKey:@"DG16"] boolValue]; + } + + // EIDDataGroups: 1-21 + if ([dataGroup class] == [RGLeIDDataGroup class]) { + if([dict valueForKey:@"DG15"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG15 = [[dict valueForKey:@"DG15"] boolValue]; + if([dict valueForKey:@"DG16"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG16 = [[dict valueForKey:@"DG16"] boolValue]; + if([dict valueForKey:@"DG17"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG17 = [[dict valueForKey:@"DG17"] boolValue]; + if([dict valueForKey:@"DG18"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG18 = [[dict valueForKey:@"DG18"] boolValue]; + if([dict valueForKey:@"DG19"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG19 = [[dict valueForKey:@"DG19"] boolValue]; + if([dict valueForKey:@"DG20"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG20 = [[dict valueForKey:@"DG20"] boolValue]; + if([dict valueForKey:@"DG21"] != nil) + ((RGLeIDDataGroup*)dataGroup).dG21 = [[dict valueForKey:@"DG21"] boolValue]; + } +} + ++(NSDictionary *)getDataGroups:(RGLDataGroup*)dataGroup { + NSMutableDictionary *result = [NSMutableDictionary new]; + + // EDLDataGroups/Common: 1-14 + result[@"DG1"] = [NSNumber numberWithBool:dataGroup.dG1]; + result[@"DG2"] = [NSNumber numberWithBool:dataGroup.dG2]; + result[@"DG3"] = [NSNumber numberWithBool:dataGroup.dG3]; + result[@"DG4"] = [NSNumber numberWithBool:dataGroup.dG4]; + result[@"DG5"] = [NSNumber numberWithBool:dataGroup.dG5]; + result[@"DG6"] = [NSNumber numberWithBool:dataGroup.dG6]; + result[@"DG7"] = [NSNumber numberWithBool:dataGroup.dG7]; + result[@"DG8"] = [NSNumber numberWithBool:dataGroup.dG8]; + result[@"DG9"] = [NSNumber numberWithBool:dataGroup.dG9]; + result[@"DG10"] = [NSNumber numberWithBool:dataGroup.dG10]; + result[@"DG11"] = [NSNumber numberWithBool:dataGroup.dG11]; + result[@"DG12"] = [NSNumber numberWithBool:dataGroup.dG12]; + result[@"DG13"] = [NSNumber numberWithBool:dataGroup.dG13]; + result[@"DG14"] = [NSNumber numberWithBool:dataGroup.dG14]; + + // EPassportDataGroups: 1-16 + if ([dataGroup class] == [RGLePassportDataGroup class]) { + result[@"DG15"] = [NSNumber numberWithBool:((RGLePassportDataGroup*)dataGroup).dG15]; + result[@"DG16"] = [NSNumber numberWithBool:((RGLePassportDataGroup*)dataGroup).dG16]; + } + + // EIDDataGroups: 1-21 + if ([dataGroup class] == [RGLeIDDataGroup class]) { + result[@"DG15"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG15]; + result[@"DG16"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG16]; + result[@"DG17"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG17]; + result[@"DG18"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG18]; + result[@"DG19"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG19]; + result[@"DG20"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG20]; + result[@"DG21"] = [NSNumber numberWithBool:((RGLeIDDataGroup*)dataGroup).dG21]; + } + + return result; +} + ++(void)setDTCDataGroup:(RGLDTCDataGroup*)dataGroup dict:(NSDictionary*)dict { + if(dict[@"DG17"]) dataGroup.dG17 = [dict[@"DG17"] boolValue]; + if(dict[@"DG18"]) dataGroup.dG18 = [dict[@"DG18"] boolValue]; + if(dict[@"DG22"]) dataGroup.dG22 = [dict[@"DG22"] boolValue]; + if(dict[@"DG23"]) dataGroup.dG23 = [dict[@"DG23"] boolValue]; + if(dict[@"DG24"]) dataGroup.dG24 = [dict[@"DG24"] boolValue]; +} + ++(NSDictionary *)getDTCDataGroup:(RGLDTCDataGroup*)dataGroup { + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"DG17"] = @(dataGroup.dG17); + result[@"DG18"] = @(dataGroup.dG18); + result[@"DG22"] = @(dataGroup.dG22); + result[@"DG23"] = @(dataGroup.dG23); + result[@"DG24"] = @(dataGroup.dG24); + + return result; +} + ++(void)setImageQA:(RGLImageQA*)result input:(NSDictionary*)input { + if([input valueForKey:@"dpiThreshold"] != nil) + result.dpiThreshold = [input valueForKey:@"dpiThreshold"]; + if([input valueForKey:@"angleThreshold"] != nil) + result.angleThreshold = [input valueForKey:@"angleThreshold"]; + if([input valueForKey:@"focusCheck"] != nil) + result.focusCheck = [input valueForKey:@"focusCheck"]; + if([input valueForKey:@"glaresCheck"] != nil) + result.glaresCheck = [input valueForKey:@"glaresCheck"]; + if([input valueForKey:@"colornessCheck"] != nil) + result.colornessCheck = [input valueForKey:@"colornessCheck"]; + if([input valueForKey:@"screenCapture"] != nil) + result.screenCapture = [input valueForKey:@"screenCapture"]; + if (input[@"expectedPass"]) { + NSMutableArray* expectedPass = @[].mutableCopy; + for(NSNumber* item in input[@"expectedPass"]) [expectedPass addObject:[self imageQualityCheckTypeWithNumber:item]]; + result.expectedPass = expectedPass; + } + if([input valueForKey:@"documentPositionIndent"] != nil) + result.documentPositionIndent = [input valueForKey:@"documentPositionIndent"]; + if([input valueForKey:@"glaresCheckParams"] != nil) + result.glaresCheckParams = [RGLWJSONConstructor glaresCheckParamsFromJson:[input valueForKey:@"glaresCheckParams"]]; + if([input valueForKey:@"brightnessThreshold"] != nil) + result.brightnessThreshold = [input valueForKey:@"brightnessThreshold"]; + if(input[@"occlusionCheck"]) result.occlusionCheck = input[@"occlusionCheck"]; +} + ++(NSDictionary*)getImageQA:(RGLImageQA*)input { + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"dpiThreshold"] = input.dpiThreshold; + result[@"angleThreshold"] = input.angleThreshold; + result[@"focusCheck"] = input.focusCheck; + result[@"glaresCheck"] = input.glaresCheck; + result[@"colornessCheck"] = input.colornessCheck; + result[@"screenCapture"] = input.screenCapture; + if (input.expectedPass) { + NSMutableArray* expectedPass = @[].mutableCopy; + for(RGLImageQualityCheckType item in input.expectedPass) [expectedPass addObject:[self generateImageQualityCheckType:item]]; + result[@"expectedPass"] = expectedPass; + } + result[@"documentPositionIndent"] = input.documentPositionIndent; + result[@"glaresCheckParams"] = [RGLWJSONConstructor generateGlaresCheckParams:input.glaresCheckParams]; + result[@"brightnessThreshold"] = input.brightnessThreshold; + result[@"occlusionCheck"] = input.occlusionCheck; + + return result; +} + ++(void)setAuthenticityParams:(RGLAuthenticityParams*)result input:(NSDictionary*)input { + if([input valueForKey:@"useLivenessCheck"] != nil) + result.useLivenessCheck = [input valueForKey:@"useLivenessCheck"]; + if([input valueForKey:@"livenessParams"] != nil) { + if(result.livenessParams == nil) result.livenessParams = [RGLLivenessParams defaultParams]; + [self setLivenessParams:result.livenessParams input:[input valueForKey:@"livenessParams"]]; + } + if([input valueForKey:@"checkUVLuminiscence"] != nil) + result.checkUVLuminiscence = [input valueForKey:@"checkUVLuminiscence"]; + if([input valueForKey:@"checkIRB900"] != nil) + result.checkIRB900 = [input valueForKey:@"checkIRB900"]; + if([input valueForKey:@"checkImagePatterns"] != nil) + result.checkImagePatterns = [input valueForKey:@"checkImagePatterns"]; + if([input valueForKey:@"checkFibers"] != nil) + result.checkFibers = [input valueForKey:@"checkFibers"]; + if([input valueForKey:@"checkExtMRZ"] != nil) + result.checkExtMRZ = [input valueForKey:@"checkExtMRZ"]; + if([input valueForKey:@"checkExtOCR"] != nil) + result.checkExtOCR = [input valueForKey:@"checkExtOCR"]; + if([input valueForKey:@"checkAxial"] != nil) + result.checkAxial = [input valueForKey:@"checkAxial"]; + if([input valueForKey:@"checkBarcodeFormat"] != nil) + result.checkBarcodeFormat = [input valueForKey:@"checkBarcodeFormat"]; + if([input valueForKey:@"checkIRVisibility"] != nil) + result.checkIRVisibility = [input valueForKey:@"checkIRVisibility"]; + if([input valueForKey:@"checkIPI"] != nil) + result.checkIPI = [input valueForKey:@"checkIPI"]; + if([input valueForKey:@"checkPhotoEmbedding"] != nil) + result.checkPhotoEmbedding = [input valueForKey:@"checkPhotoEmbedding"]; + if([input valueForKey:@"checkPhotoComparison"] != nil) + result.checkPhotoComparison = [input valueForKey:@"checkPhotoComparison"]; + if([input valueForKey:@"checkLetterScreen"] != nil) + result.checkLetterScreen = [input valueForKey:@"checkLetterScreen"]; + if(input[@"checkSecurityText"]) result.checkSecurityText = input[@"checkSecurityText"]; +} + ++(NSDictionary*)getAuthenticityParams:(RGLAuthenticityParams*)input { + if(input == nil) return nil; + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"useLivenessCheck"] = input.useLivenessCheck; + result[@"livenessParams"] = [self getLivenessParams:input.livenessParams]; + result[@"checkUVLuminiscence"] = input.checkUVLuminiscence; + result[@"checkIRB900"] = input.checkIRB900; + result[@"checkImagePatterns"] = input.checkImagePatterns; + result[@"checkFibers"] = input.checkFibers; + result[@"checkExtMRZ"] = input.checkExtMRZ; + result[@"checkExtOCR"] = input.checkExtOCR; + result[@"checkAxial"] = input.checkAxial; + result[@"checkBarcodeFormat"] = input.checkBarcodeFormat; + result[@"checkIRVisibility"] = input.checkIRVisibility; + result[@"checkIPI"] = input.checkIPI; + result[@"checkPhotoEmbedding"] = input.checkPhotoEmbedding; + result[@"checkPhotoComparison"] = input.checkPhotoComparison; + result[@"checkLetterScreen"] = input.checkLetterScreen; + result[@"checkSecurityText"] = input.checkSecurityText; + + return result; +} + ++(void)setLivenessParams:(RGLLivenessParams*)result input:(NSDictionary*)input { + if([input valueForKey:@"checkOVI"] != nil) + result.checkOVI = [input valueForKey:@"checkOVI"]; + if([input valueForKey:@"checkMLI"] != nil) + result.checkMLI = [input valueForKey:@"checkMLI"]; + if([input valueForKey:@"checkHolo"] != nil) + result.checkHolo = [input valueForKey:@"checkHolo"]; + if([input valueForKey:@"checkED"] != nil) + result.checkED = [input valueForKey:@"checkED"]; + if(input[@"checkBlackAndWhiteCopy"]) result.checkBlackAndWhiteCopy = input[@"checkBlackAndWhiteCopy"]; + if(input[@"checkDynaprint"]) result.checkDynaprint = input[@"checkDynaprint"]; + if(input[@"checkGeometry"]) result.checkGeometry = input[@"checkGeometry"]; + if(input[@"checkBarcodeBackground"]) result.checkBarcodeBackground = input[@"checkBarcodeBackground"]; +} + ++(NSDictionary*)getLivenessParams:(RGLLivenessParams*)input { + if(input == nil) return nil; + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"checkOVI"] = input.checkOVI; + result[@"checkMLI"] = input.checkMLI; + result[@"checkHolo"] = input.checkHolo; + result[@"checkED"] = input.checkED; + result[@"checkBlackAndWhiteCopy"] = input.checkBlackAndWhiteCopy; + result[@"checkDynaprint"] = input.checkDynaprint; + result[@"checkGeometry"] = input.checkGeometry; + result[@"checkBarcodeBackground"] = input.checkBarcodeBackground; + + return result; +} + ++(void)setColors:(NSMutableDictionary*)result input:(NSDictionary*)input { + if([input valueForKey:@"rfidProcessingScreenBackground"] != nil) + result[@(RFIDProcessingScreenBackground)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenBackground"]]; + if([input valueForKey:@"rfidProcessingScreenHintLabelText"] != nil) + result[@(RFIDProcessingScreenHintLabelText)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenHintLabelText"]]; + if([input valueForKey:@"rfidProcessingScreenHintLabelBackground"] != nil) + result[@(RFIDProcessingScreenHintLabelBackground)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenHintLabelBackground"]]; + if([input valueForKey:@"rfidProcessingScreenProgressLabelText"] != nil) + result[@(RFIDProcessingScreenProgressLabelText)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenProgressLabelText"]]; + if([input valueForKey:@"rfidProcessingScreenProgressBar"] != nil) + result[@(RFIDProcessingScreenProgressBar)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenProgressBar"]]; + if([input valueForKey:@"rfidProcessingScreenProgressBarBackground"] != nil) + result[@(RFIDProcessingScreenProgressBarBackground)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenProgressBarBackground"]]; + if([input valueForKey:@"rfidProcessingScreenResultLabelText"] != nil) + result[@(RFIDProcessingScreenResultLabelText)] = [self colorWithInt:[input valueForKey:@"rfidProcessingScreenResultLabelText"]]; + if(input[@"rfidProcessingScreenLoadingBar"]) result[@(RFIDProcessingScreenLoadingBar)] = [self colorWithInt:input[@"rfidProcessingScreenLoadingBar"]]; + if(input[@"mdlProcessingScreenBackground"]) result[@(MDLProcessingScreenBackground)] = [self colorWithInt:input[@"mdlProcessingScreenBackground"]]; + if(input[@"mdlProcessingScreenHintLabelText"]) result[@(MDLProcessingScreenHintLabelText)] = [self colorWithInt:input[@"mdlProcessingScreenHintLabelText"]]; + if(input[@"mdlProcessingScreenHintLabelBackground"]) result[@(MDLProcessingScreenHintLabelBackground)] = [self colorWithInt:input[@"mdlProcessingScreenHintLabelBackground"]]; + if(input[@"mdlProcessingScreenProgressLabelText"]) result[@(MDLProcessingScreenProgressLabelText)] = [self colorWithInt:input[@"mdlProcessingScreenProgressLabelText"]]; + if(input[@"mdlProcessingScreenResultLabelText"]) result[@(MDLProcessingScreenResultLabelText)] = [self colorWithInt:input[@"mdlProcessingScreenResultLabelText"]]; + if(input[@"mdlProcessingScreenLoadingBar"]) result[@(MDLProcessingScreenLoadingBar)] = [self colorWithInt:input[@"mdlProcessingScreenLoadingBar"]]; + if(input[@"nextPageIdCardFront"]) result[@(RGLCustomizationColorNextPageIdCardFront)] = [self colorWithInt:input[@"nextPageIdCardFront"]]; + if(input[@"nextPageIdCardBack"]) result[@(RGLCustomizationColorNextPageIdCardBack)] = [self colorWithInt:input[@"nextPageIdCardBack"]]; + if(input[@"nextPagePassportShift"]) result[@(RGLCustomizationColorNextPagePassportShift)] = [self colorWithInt:input[@"nextPagePassportShift"]]; + if(input[@"nextPagePassportFlip"]) result[@(RGLCustomizationColorNextPagePassportFlip)] = [self colorWithInt:input[@"nextPagePassportFlip"]]; +} + ++(NSDictionary*)getColors:(NSDictionary*)input { + id result = @{}.mutableCopy; + + if(input[@(RFIDProcessingScreenBackground)]) result[@"rfidProcessingScreenBackground"] = [self intWithColor:input[@(RFIDProcessingScreenBackground)]]; + if(input[@(RFIDProcessingScreenHintLabelText)]) result[@"rfidProcessingScreenHintLabelText"] = [self intWithColor:input[@(RFIDProcessingScreenHintLabelText)]]; + if(input[@(RFIDProcessingScreenHintLabelBackground)]) result[@"rfidProcessingScreenHintLabelBackground"] = [self intWithColor:input[@(RFIDProcessingScreenHintLabelBackground)]]; + if(input[@(RFIDProcessingScreenProgressLabelText)]) result[@"rfidProcessingScreenProgressLabelText"] = [self intWithColor:input[@(RFIDProcessingScreenProgressLabelText)]]; + if(input[@(RFIDProcessingScreenProgressBar)]) result[@"rfidProcessingScreenProgressBar"] = [self intWithColor:input[@(RFIDProcessingScreenProgressBar)]]; + if(input[@(RFIDProcessingScreenProgressBarBackground)]) result[@"rfidProcessingScreenProgressBarBackground"] = [self intWithColor:input[@(RFIDProcessingScreenProgressBarBackground)]]; + if(input[@(RFIDProcessingScreenResultLabelText)]) result[@"rfidProcessingScreenResultLabelText"] = [self intWithColor:input[@(RFIDProcessingScreenResultLabelText)]]; + if(input[@(RFIDProcessingScreenLoadingBar)]) result[@"rfidProcessingScreenLoadingBar"] = [self intWithColor:input[@(RFIDProcessingScreenLoadingBar)]]; + if(input[@(MDLProcessingScreenBackground)]) result[@"mdlProcessingScreenBackground"] = [self intWithColor:input[@(MDLProcessingScreenBackground)]]; + if(input[@(MDLProcessingScreenHintLabelText)]) result[@"mdlProcessingScreenHintLabelText"] = [self intWithColor:input[@(MDLProcessingScreenHintLabelText)]]; + if(input[@(MDLProcessingScreenHintLabelBackground)]) result[@"mdlProcessingScreenHintLabelBackground"] = [self intWithColor:input[@(MDLProcessingScreenHintLabelBackground)]]; + if(input[@(MDLProcessingScreenProgressLabelText)]) result[@"mdlProcessingScreenProgressLabelText"] = [self intWithColor:input[@(MDLProcessingScreenProgressLabelText)]]; + if(input[@(MDLProcessingScreenResultLabelText)]) result[@"mdlProcessingScreenResultLabelText"] = [self intWithColor:input[@(MDLProcessingScreenResultLabelText)]]; + if(input[@(MDLProcessingScreenLoadingBar)]) result[@"mdlProcessingScreenLoadingBar"] = [self intWithColor:input[@(MDLProcessingScreenLoadingBar)]]; + if(input[@(RGLCustomizationColorNextPageIdCardFront)]) result[@"nextPageIdCardFront"] = [self intWithColor:input[@(RGLCustomizationColorNextPageIdCardFront)]]; + if(input[@(RGLCustomizationColorNextPageIdCardBack)]) result[@"nextPageIdCardBack"] = [self intWithColor:input[@(RGLCustomizationColorNextPageIdCardBack)]]; + if(input[@(RGLCustomizationColorNextPagePassportShift)]) result[@"nextPagePassportShift"] = [self intWithColor:input[@(RGLCustomizationColorNextPagePassportShift)]]; + if(input[@(RGLCustomizationColorNextPagePassportFlip)]) result[@"nextPagePassportFlip"] = [self intWithColor:input[@(RGLCustomizationColorNextPagePassportFlip)]]; + + return result; +} + ++(void)setFonts:(NSMutableDictionary*)result input:(NSDictionary*)input { + if([input valueForKey:@"rfidProcessingScreenHintLabel"] != nil) + result[@(RFIDProcessingScreenHintLabel)] = [self UIFontFromJSON:[input valueForKey:@"rfidProcessingScreenHintLabel"]]; + if([input valueForKey:@"rfidProcessingScreenProgressLabel"] != nil) + result[@(RFIDProcessingScreenProgressLabel)] = [self UIFontFromJSON:[input valueForKey:@"rfidProcessingScreenProgressLabel"]]; + if(input[@"rfidProcessingScreenResultLabel"]) result[@(RFIDProcessingScreenResultLabel)] = [self UIFontFromJSON:input[@"rfidProcessingScreenResultLabel"]]; + if(input[@"mdlProcessingScreenHintLabel"]) result[@(MDLProcessingScreenHintLabel)] = [self UIFontFromJSON:input[@"mdlProcessingScreenHintLabel"]]; + if(input[@"mdlProcessingScreenProgressLabel"]) result[@(MDLProcessingScreenProgressLabel)] = [self UIFontFromJSON:input[@"mdlProcessingScreenProgressLabel"]]; + if(input[@"mdlProcessingScreenResultLabel"]) result[@(MDLProcessingScreenResultLabel)] = [self UIFontFromJSON:input[@"mdlProcessingScreenResultLabel"]]; +} + ++(NSDictionary*)getFonts:(NSDictionary*)input { + return @{ + @"rfidProcessingScreenHintLabel": [self generateUIFont:input[@(RFIDProcessingScreenHintLabel)]], + @"rfidProcessingScreenProgressLabel": [self generateUIFont:input[@(RFIDProcessingScreenProgressLabel)]], + @"rfidProcessingScreenResultLabel": [self generateUIFont:input[@(RFIDProcessingScreenResultLabel)]], + @"mdlProcessingScreenHintLabel": [self generateUIFont:input[@(MDLProcessingScreenHintLabel)]], + @"mdlProcessingScreenProgressLabel": [self generateUIFont:input[@(MDLProcessingScreenProgressLabel)]], + @"mdlProcessingScreenResultLabel": [self generateUIFont:input[@(MDLProcessingScreenResultLabel)]], + }; +} + ++(void)setImages:(NSMutableDictionary*)result input:(NSDictionary*)input { + if(input[@"helpAnimation"]) result[RGLCustomizationImageHelpAnimation] = [RGLWJSONConstructor imageWithBase64:input[@"helpAnimation"]]; + if(input[@"livenessAnimation"]) result[RGLCustomizationImageLivenessAnimation] = [RGLWJSONConstructor imageWithBase64:input[@"livenessAnimation"]]; + if(input[@"borderBackground"]) result[RGLCustomizationImageBorderBackground] = [RGLWJSONConstructor imageWithBase64:input[@"borderBackground"]]; + if(input[@"torchButtonOn"]) result[RGLCustomizationImageTorchButtonOn] = [RGLWJSONConstructor imageWithBase64:input[@"torchButtonOn"]]; + if(input[@"torchButtonOff"]) result[RGLCustomizationImageTorchButtonOff] = [RGLWJSONConstructor imageWithBase64:input[@"torchButtonOff"]]; + if(input[@"captureButton"]) result[RGLCustomizationImageCaptureButton] = [RGLWJSONConstructor imageWithBase64:input[@"captureButton"]]; + if(input[@"switchButton"]) result[RGLCustomizationImageSwitchButton] = [RGLWJSONConstructor imageWithBase64:input[@"switchButton"]]; + if(input[@"closeButton"]) result[RGLCustomizationImageCloseButton] = [RGLWJSONConstructor imageWithBase64:input[@"closeButton"]]; + if(input[@"multipageButton"]) result[RGLCustomizationImageMultipageButton] = [RGLWJSONConstructor imageWithBase64:input[@"multipageButton"]]; + if(input[@"rfidProcessingScreenFailureImage"]) result[RGLCustomizationImageRFIDProcessingScreenFailure] = [RGLWJSONConstructor imageWithBase64:input[@"rfidProcessingScreenFailureImage"]]; + if(input[@"mdlProcessingScreenFailureImage"]) result[RGLCustomizationImageMDLProcessingScreenFailure] = [RGLWJSONConstructor imageWithBase64:input[@"mdlProcessingScreenFailureImage"]]; + if(input[@"nextPageIdCardFront"]) result[RGLCustomizationImageNextPageIdCardFront] = [RGLWJSONConstructor imageWithBase64:input[@"nextPageIdCardFront"]]; + if(input[@"nextPageIdCardBack"]) result[RGLCustomizationImageNextPageIdCardBack] = [RGLWJSONConstructor imageWithBase64:input[@"nextPageIdCardBack"]]; + if(input[@"nextPagePassportShift"]) result[RGLCustomizationImageNextPagePassportShift] = [RGLWJSONConstructor imageWithBase64:input[@"nextPagePassportShift"]]; + if(input[@"nextPagePassportFlipStart"]) result[RGLCustomizationImageNextPagePassportFlipStart] = [RGLWJSONConstructor imageWithBase64:input[@"nextPagePassportFlipStart"]]; + if(input[@"nextPagePassportFlipClean"]) result[RGLCustomizationImageNextPagePassportFlipClean] = [RGLWJSONConstructor imageWithBase64:input[@"nextPagePassportFlipClean"]]; + if(input[@"nextPagePassportFlipTop"]) result[RGLCustomizationImageNextPagePassportFlipTop] = [RGLWJSONConstructor imageWithBase64:input[@"nextPagePassportFlipTop"]]; + if(input[@"nextPagePassportFlipBottom"]) result[RGLCustomizationImageNextPagePassportFlipBottom] = [RGLWJSONConstructor imageWithBase64:input[@"nextPagePassportFlipBottom"]]; +} + ++(NSDictionary*)getImages:(NSDictionary*)input { + id result = @{}.mutableCopy; + id i; + + i = RGLCustomizationImageHelpAnimation; + if(input[i]) result[@"helpAnimation"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageLivenessAnimation; + if(input[i]) result[@"livenessAnimation"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageBorderBackground; + if(input[i]) result[@"borderBackground"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageTorchButtonOn; + if(input[i]) result[@"torchButtonOn"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageTorchButtonOff; + if(input[i]) result[@"torchButtonOff"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageCaptureButton; + if(input[i]) result[@"captureButton"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageSwitchButton; + if(input[i]) result[@"switchButton"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageCloseButton; + if(input[i]) result[@"closeButton"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageMultipageButton; + if(input[i]) result[@"multipageButton"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageRFIDProcessingScreenFailure; + if(input[i]) result[@"rfidProcessingScreenFailureImage"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageMDLProcessingScreenFailure; + if(input[i]) result[@"mdlProcessingScreenFailureImage"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPageIdCardFront; + if(input[i]) result[@"nextPageIdCardFront"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPageIdCardBack; + if(input[i]) result[@"nextPageIdCardBack"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPagePassportShift; + if(input[i]) result[@"nextPagePassportShift"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPagePassportFlipStart; + if(input[i]) result[@"nextPagePassportFlipStart"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPagePassportFlipClean; + if(input[i]) result[@"nextPagePassportFlipClean"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPagePassportFlipTop; + if(input[i]) result[@"nextPagePassportFlipTop"] = [RGLWJSONConstructor base64WithImage:input[i]]; + i = RGLCustomizationImageNextPagePassportFlipBottom; + if(input[i]) result[@"nextPagePassportFlipBottom"] = [RGLWJSONConstructor base64WithImage:input[i]]; + + return result; +} + ++(void)setTimings:(NSMutableDictionary*)result input:(NSDictionary*)input { + if(input[@"nextPageIdCardStartDelay"]) result[@(RGLCustomizationTimingNextPageIdCardStartDelay)] = input[@"nextPageIdCardStartDelay"]; + if(input[@"nextPageIdCardEndDelay"]) result[@(RGLCustomizationTimingNextPageIdCardEndDelay)] = input[@"nextPageIdCardEndDelay"]; + if(input[@"nextPagePassportShiftStartDelay"]) result[@(RGLCustomizationTimingNextPagePassportShiftStartDelay)] = input[@"nextPagePassportShiftStartDelay"]; + if(input[@"nextPagePassportShiftEndDelay"]) result[@(RGLCustomizationTimingNextPagePassportShiftEndDelay)] = input[@"nextPagePassportShiftEndDelay"]; + if(input[@"nextPagePassportFlipStartDelay"]) result[@(RGLCustomizationTimingNextPagePassportFlipStartDelay)] = input[@"nextPagePassportFlipStartDelay"]; + if(input[@"nextPagePassportFlipEndDelay"]) result[@(RGLCustomizationTimingNextPagePassportFlipEndDelay)] = input[@"nextPagePassportFlipEndDelay"]; +} + ++(NSDictionary*)getTimings:(NSDictionary*)input { + id result = @{}.mutableCopy; + id i; + + i = @(RGLCustomizationTimingNextPageIdCardStartDelay); + if(input[i]) result[@"nextPageIdCardStartDelay"] = input[i]; + i = @(RGLCustomizationTimingNextPageIdCardEndDelay); + if(input[i]) result[@"nextPageIdCardEndDelay"] = input[i]; + i = @(RGLCustomizationTimingNextPagePassportShiftStartDelay); + if(input[i]) result[@"nextPagePassportShiftStartDelay"] = input[i]; + i = @(RGLCustomizationTimingNextPagePassportShiftEndDelay); + if(input[i]) result[@"nextPagePassportShiftEndDelay"] = input[i]; + i = @(RGLCustomizationTimingNextPagePassportFlipStartDelay); + if(input[i]) result[@"nextPagePassportFlipStartDelay"] = input[i]; + i = @(RGLCustomizationTimingNextPagePassportFlipEndDelay); + if(input[i]) result[@"nextPagePassportFlipEndDelay"] = input[i]; + + return result; +} + ++(void)setContentModes:(NSMutableDictionary*)result input:(NSDictionary*)input { + if(input[@"nextPageIdCardFront"]) result[@(RGLCustomizationContentModeNextPageIdCardFront)] = input[@"nextPageIdCardFront"]; + if(input[@"nextPageIdCardBack"]) result[@(RGLCustomizationContentModeNextPageIdCardBack)] = input[@"nextPageIdCardBack"]; +} + ++(NSDictionary*)getContentModes:(NSDictionary*)input { + return @{ + @"nextPageIdCardFront": input[@(RGLCustomizationContentModeNextPageIdCardFront)], + @"nextPageIdCardBack": input[@(RGLCustomizationContentModeNextPageIdCardBack)], + }; +} + ++(UIColor*)colorWithInt:(NSNumber*)input { + // Convert hex int to hex string + NSInteger hexInt = [input integerValue]; + NSString* numbers = @"0123456789ABCDEF"; + NSString* hexString = @""; + while(hexInt>0){ + int digit = hexInt % 16; + hexString = [NSString stringWithFormat:@"%@%@", [numbers substringWithRange:NSMakeRange(digit, 1)], hexString]; + hexInt = hexInt/16; + } + // If we use int, then all the starting zeros are lost: 0x0F123456 == 0xF123456 + if(hexString.length == 5 || hexString.length == 7) + hexString = [NSString stringWithFormat:@"0%@", hexString]; + hexString = [NSString stringWithFormat:@"#%@", hexString]; + + // Convert hex string to UIColor + NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString]; + CGFloat alpha, red, blue, green; + switch ([colorString length]) { + case 3: // #RGB + alpha = 1.0f; + red = [self colorComponentFrom: colorString start: 0 length: 1]; + green = [self colorComponentFrom: colorString start: 1 length: 1]; + blue = [self colorComponentFrom: colorString start: 2 length: 1]; + break; + case 4: // #ARGB + alpha = [self colorComponentFrom: colorString start: 0 length: 1]; + red = [self colorComponentFrom: colorString start: 1 length: 1]; + green = [self colorComponentFrom: colorString start: 2 length: 1]; + blue = [self colorComponentFrom: colorString start: 3 length: 1]; + break; + case 6: // #RRGGBB + alpha = 1.0f; + red = [self colorComponentFrom: colorString start: 0 length: 2]; + green = [self colorComponentFrom: colorString start: 2 length: 2]; + blue = [self colorComponentFrom: colorString start: 4 length: 2]; + break; + case 8: // #AARRGGBB + alpha = [self colorComponentFrom: colorString start: 0 length: 2]; + red = [self colorComponentFrom: colorString start: 2 length: 2]; + green = [self colorComponentFrom: colorString start: 4 length: 2]; + blue = [self colorComponentFrom: colorString start: 6 length: 2]; + break; + default: + [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString]; + break; + } + return [UIColor colorWithRed: red green: green blue: blue alpha: alpha]; +} + ++(CGFloat)colorComponentFrom:(NSString*)string start:(NSUInteger)start length:(NSUInteger)length { + NSString *substring = [string substringWithRange: NSMakeRange(start, length)]; + NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring]; + unsigned hexComponent; + [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent]; + return hexComponent / 255.0; +} + ++(NSNumber*)intWithColor:(UIColor*)color { + if(color == nil) return nil; + + const CGFloat *components = CGColorGetComponents(color.CGColor); + CGFloat r = components[0]; + CGFloat g = components[1]; + CGFloat b = components[2]; + CGFloat a = components[3]; + + NSString* hexString = [NSString stringWithFormat:@"#%02lX%02lX%02lX%02lX", + lroundf(a * 255), + lroundf(r * 255), + lroundf(g * 255), + lroundf(b * 255)]; + + unsigned int hexInt = 0; + NSScanner *scanner = [NSScanner scannerWithString:hexString]; + [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; + [scanner scanHexInt:&hexInt]; + + return [NSNumber numberWithInteger:hexInt]; +} + ++(UIFont*)UIFontFromJSON:(NSDictionary*)input { + UIFont* result = [UIFont fontWithName:[input valueForKey:@"name"] size:[[input valueForKey:@"size"] integerValue]]; + if (!result || !result.fontName) return nil; + return result; +} + ++(NSDictionary*)generateUIFont:(UIFont*)input { + if (!input || !input.fontName) return nil; + return @{ + @"name": input.fontName, + @"size": @(input.pointSize) + }; +} + ++(AVCaptureSessionPreset)captureSessionPresetWithNumber:(NSNumber*)value { + int input = [value intValue]; + if(input == 0) return AVCaptureSessionPresetLow; + if(input == 1) return AVCaptureSessionPresetMedium; + if(input == 2) return AVCaptureSessionPresetHigh; + if(input == 3) return AVCaptureSessionPresetPhoto; + if(input == 4) return AVCaptureSessionPresetInputPriority; + if(input == 6) return AVCaptureSessionPreset1280x720; + if(input == 7) return AVCaptureSessionPreset1920x1080; + if(input == 8) return AVCaptureSessionPreset3840x2160; + if(input == 9) return AVCaptureSessionPresetiFrame960x540; + if(input == 10) return AVCaptureSessionPresetiFrame1280x720; + if(input == 12) return AVCaptureSessionPreset640x480; + if(input == 13) return AVCaptureSessionPreset352x288; + return AVCaptureSessionPreset1920x1080; +} + ++(NSNumber*)generateCaptureSessionPreset:(AVCaptureSessionPreset)value { + if(value == AVCaptureSessionPresetLow) return @0; + if(value == AVCaptureSessionPresetMedium) return @1; + if(value == AVCaptureSessionPresetHigh) return @2; + if(value == AVCaptureSessionPresetPhoto) return @3; + if(value == AVCaptureSessionPresetInputPriority) return @4; + if(value == AVCaptureSessionPreset1280x720) return @6; + if(value == AVCaptureSessionPreset1920x1080) return @7; + if(value == AVCaptureSessionPreset3840x2160) return @8; + if(value == AVCaptureSessionPresetiFrame960x540) return @9; + if(value == AVCaptureSessionPresetiFrame1280x720) return @10; + if(value == AVCaptureSessionPreset640x480) return @12; + if(value == AVCaptureSessionPreset352x288) return @13; + return @0; +} + ++(CGLineCap)lineCapWithNumber:(NSNumber*)value { + int input = [value intValue]; + if(input == 0) return kCGLineCapButt; + if(input == 1) return kCGLineCapRound; + if(input == 2) return kCGLineCapSquare; + return kCGLineCapButt; +} + ++(NSNumber*)generateLineCap:(CGLineCap)value { + if(value == kCGLineCapButt) return @0; + if(value == kCGLineCapRound) return @1; + if(value == kCGLineCapSquare) return @2; + return @0;; +} + ++(UIInterfaceOrientationMask)interfaceOrientationMaskWithNumber:(NSNumber*)value { + int input = [value intValue]; + if(input == 0) return UIInterfaceOrientationMaskAll; + if(input == 1) return UIInterfaceOrientationMaskPortrait; + if(input == 2) return UIInterfaceOrientationMaskLandscape; + if(input == 3) return UIInterfaceOrientationMaskLandscapeLeft; + if(input == 4) return UIInterfaceOrientationMaskLandscapeRight; + return UIInterfaceOrientationMaskPortrait; +} + ++(NSNumber*)generateInterfaceOrientationMask:(UIInterfaceOrientationMask)value { + if(value == UIInterfaceOrientationMaskAll) return @0; + if(value == UIInterfaceOrientationMaskPortrait) return @1; + if(value == UIInterfaceOrientationMaskLandscape) return @2; + if(value == UIInterfaceOrientationMaskLandscapeLeft) return @3; + if(value == UIInterfaceOrientationMaskLandscapeRight) return @4; + return @0; +} + ++(UIViewContentMode)viewContentModeWithNumber:(NSNumber*)value { + int input = [value intValue]; + if(input == 0) return UIViewContentModeScaleToFill; + if(input == 1) return UIViewContentModeScaleAspectFit; + if(input == 2) return UIViewContentModeScaleAspectFill; + if(input == 3) return UIViewContentModeRedraw; + if(input == 4) return UIViewContentModeCenter; + if(input == 5) return UIViewContentModeTop; + if(input == 6) return UIViewContentModeBottom; + if(input == 7) return UIViewContentModeLeft; + if(input == 8) return UIViewContentModeRight; + if(input == 9) return UIViewContentModeTopLeft; + if(input == 10) return UIViewContentModeTopRight; + if(input == 11) return UIViewContentModeBottomLeft; + if(input == 12) return UIViewContentModeBottomRight; + return UIViewContentModeCenter; +} + ++(NSNumber*)generateViewContentMode:(UIViewContentMode)value { + if(value == UIViewContentModeScaleToFill) return @0; + if(value == UIViewContentModeScaleAspectFit) return @1; + if(value == UIViewContentModeScaleAspectFill) return @2; + if(value == UIViewContentModeRedraw) return @3; + if(value == UIViewContentModeCenter) return @4; + if(value == UIViewContentModeTop) return @5; + if(value == UIViewContentModeBottom) return @6; + if(value == UIViewContentModeLeft) return @7; + if(value == UIViewContentModeRight) return @8; + if(value == UIViewContentModeTopLeft) return @9; + if(value == UIViewContentModeTopRight) return @10; + if(value == UIViewContentModeBottomLeft) return @11; + if(value == UIViewContentModeBottomRight) return @12; + return @4; +} + ++(RGLDocReaderFrame)docReaderFrameWithString:(NSString*)value { + if([value isEqual: @"id1"]) return RGLDocReaderFrameScenarioDefault; + if([value isEqual: @"max"]) return RGLDocReaderFrameMax; + if([value isEqual: @"none"]) return RGLDocReaderFrameNone; + if([value isEqual: @"document"]) return RGLDocReaderFrameDocument; + return RGLDocReaderFrameNone; +} + ++(NSString*)generateDocReaderFrame:(RGLDocReaderFrame)value { + if(value == RGLDocReaderFrameScenarioDefault) return @"id1"; + if(value == RGLDocReaderFrameMax) return @"max"; + if(value == RGLDocReaderFrameNone) return @"none"; + if(value == RGLDocReaderFrameDocument) return @"document"; + return @"none"; +} + ++(RGLTextProcessing*)textProcessingWithNumber:(NSNumber*)value { + int input = [value intValue]; + if(input == 0) return RGLTextProcessing.noChange; + if(input == 1) return RGLTextProcessing.uppercase; + if(input == 2) return RGLTextProcessing.lowercase; + if(input == 3) return RGLTextProcessing.capital; + return RGLTextProcessing.noChange; +} + ++(NSNumber*)generateWithTextProcessing:(RGLTextProcessing*)value { + return [value valueForKey:@"rawValue"]; +} + ++(NSNumber*)generateDocReaderAction:(RGLDocReaderAction)value { + if(value == RGLDocReaderActionComplete) return @0; + if(value == RGLDocReaderActionProcess) return @1; + if(value == RGLDocReaderActionMorePagesAvailable) return @2; + if(value == RGLDocReaderActionCancel) return @3; + if(value == RGLDocReaderActionError) return @4; + if(value == RGLDocReaderActionProcessWhiteFlashLight) return @5; + if(value == RGLDocReaderActionProcessTimeout) return @6; + if(value == RGLDocReaderActionProcessOnServer) return @7; + return @4; +} + ++(NSNumber*)generateRFIDCompleteAction:(RGLRFIDCompleteAction)value { + if(value == RGLRFIDCompleteActionComplete) return @0; + if(value == RGLRFIDCompleteActionError) return @4; + if(value == RGLRFIDCompleteActionCancel) return @3; + if(value == RGLRFIDCompleteActionSessionRestarted) return @0; + return @0; +} + ++(NSNumber*)generateImageQualityCheckType:(RGLImageQualityCheckType)value { + if(value == RGLImageQualityCheckTypeImageGlares) return @0; + if(value == RGLImageQualityCheckTypeImageFocus) return @1; + if(value == RGLImageQualityCheckTypeImageResolution) return @2; + if(value == RGLImageQualityCheckTypeImageColorness) return @3; + if(value == RGLImageQualityCheckTypeImagePerspective) return @4; + if(value == RGLImageQualityCheckTypeImageBounds) return @5; + if(value == RGLImageQualityCheckTypeScreenCapture) return @6; + if(value == RGLImageQualityCheckTypePortrait) return @7; + if(value == RGLImageQualityCheckTypeHandwritten) return @8; + if(value == RGLImageQualityCheckTypeBrightness) return @9; + if(value == RGLImageQualityCheckTypeOcclusion) return @10; + return 0; +} + ++(RGLImageQualityCheckType)imageQualityCheckTypeWithNumber:(NSNumber*)input { + if(input == nil) return nil; + int value = [input intValue]; + if(value == 0) return RGLImageQualityCheckTypeImageGlares; + if(value == 1) return RGLImageQualityCheckTypeImageFocus; + if(value == 2) return RGLImageQualityCheckTypeImageResolution; + if(value == 3) return RGLImageQualityCheckTypeImageColorness; + if(value == 4) return RGLImageQualityCheckTypeImagePerspective; + if(value == 5) return RGLImageQualityCheckTypeImageBounds; + if(value == 6) return RGLImageQualityCheckTypeScreenCapture; + if(value == 7) return RGLImageQualityCheckTypePortrait; + if(value == 8) return RGLImageQualityCheckTypeHandwritten; + if(value == 9) return RGLImageQualityCheckTypeBrightness; + if(value == 10) return RGLImageQualityCheckTypeOcclusion; + return RGLImageQualityCheckTypeImageGlares; +} + +@end diff --git a/ios/Classes/RGLWJSONConstructor.h b/ios/Classes/RGLWJSONConstructor.h index 5975a6564f..ca4c98c96c 100644 --- a/ios/Classes/RGLWJSONConstructor.h +++ b/ios/Classes/RGLWJSONConstructor.h @@ -2,79 +2,211 @@ #define RGLWJSONConstructor_h #import -#import "RGLWRegulaConfig.h" +#import "RGLWConfig.h" + @import CoreGraphics; @import UIKit; @interface RGLWJSONConstructor : NSObject -+(NSString* _Nonnull)dictToString:(NSMutableDictionary* _Nonnull)input; -+(NSString* _Nonnull)arrayToString:(NSMutableArray* _Nonnull)input; -+(NSMutableDictionary* _Nonnull)generateNSDictionary:(NSDictionary* _Nullable)input; -+(UIImage* _Nullable)imageWithBase64:(NSString* _Nullable)input; + ++(NSString* _Nullable)toSendable:(id _Nullable)input; ++(NSString* _Nullable)dictToString:(NSDictionary* _Nullable)input; ++(NSString* _Nullable)arrayToString:(NSArray* _Nullable)input; +(NSString* _Nullable)base64WithImage:(UIImage* _Nullable)input; -+(RGLPKDCertificate* _Nullable)RGLPKDCertificateFromJson:(NSDictionary* _Nullable) dict; -+(RGLTCCParams* _Nonnull)RGLTCCParamsFromJson:(NSDictionary* _Nonnull)input; -+(RGLConfig* _Nullable)RGLConfigFromJson:(NSDictionary* _Nonnull)input; -+(RGLScannerConfig* _Nullable)RGLScannerConfigFromJson:(NSDictionary* _Nonnull)input; -+(RGLRecognizeConfig* _Nullable)RGLRecognizeConfigFromJson:(NSDictionary* _Nonnull)input; -+(RGLImageInput* _Nonnull)RGLImageInputFromJson:(NSDictionary* _Nonnull)input; -+(NSInteger)generateDocReaderAction:(RGLDocReaderAction)action; -+(NSInteger)generateRFIDCompleteAction:(RGLRFIDCompleteAction)action; -+(NSMutableDictionary* _Nullable)generateCompletion:(NSInteger)action :(RGLDocumentReaderResults*_Nullable)results :(NSError*_Nullable)error; -+(NSMutableDictionary* _Nonnull)generateVideoEncoderCompletion:(NSURL* _Nullable)input :(NSError* _Nullable)error; -+(NSString*_Nonnull)generateNSData:(NSData *_Nullable)input; -+(NSMutableDictionary* _Nonnull)generatePACertificateCompletion:(NSData *_Nullable)serialNumber :(RGLPAResourcesIssuer *_Nullable)issuer; -+(NSMutableDictionary* _Nonnull)generateDocumentReaderNotification:(RGLRFIDNotify* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderResults:(RGLDocumentReaderResults* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLPosition:(RGLPosition* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderBarcodeResult:(RGLDocumentReaderBarcodeResult* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderBarcodeField:(RGLDocumentReaderBarcodeField* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLPDF417Info:(RGLPDF417Info* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderAuthenticityResult:(RGLDocumentReaderAuthenticityResult* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLAuthenticityCheck:(RGLAuthenticityCheck* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLAuthenticityElement:(RGLAuthenticityElement* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLImageQualityGroup:(RGLImageQualityGroup* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLImageQuality:(RGLImageQuality* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderGraphicResult:(RGLDocumentReaderGraphicResult* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderGraphicField:(RGLDocumentReaderGraphicField* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextResult:(RGLDocumentReaderTextResult* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextField:(RGLDocumentReaderTextField* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderValue:(RGLDocumentReaderValue* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderDocumentType:(RGLDocumentReaderDocumentType* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLScenario:(RGLScenario* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLRFIDSessionData:(RGLRFIDSessionData* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDataField:(RGLDataField* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLCardProperties:(RGLCardProperties* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLRFIDSessionDataStatus:(RGLRFIDSessionDataStatus* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLAccessControlProcedureType:(RGLAccessControlProcedureType* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLApplication:(RGLApplication* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLFile:(RGLFile* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLFileData:(RGLFileData* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLSecurityObjectCertificates:(RGLSecurityObjectCertificates* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLCertificateData:(RGLCertificateData* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLSecurityObject:(RGLSecurityObject* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLSignerInfo:(RGLSignerInfo* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLAuthority:(RGLAuthority* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLRFIDValue:(RGLRFIDValue* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLAttribute:(RGLAttribute* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLExtension:(RGLExtension* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLCertificateChain:(RGLCertificateChain* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLValidity:(RGLValidity* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLPAResourcesIssuer:(RGLPAResourcesIssuer* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLPAAttribute:(RGLPAAttribute* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLTAChallenge:(RGLTAChallenge* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderResultsStatus:(RGLDocumentReaderResultsStatus* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLOpticalStatus:(RGLOpticalStatus* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLVDSNCData:(RGLVDSNCData* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLBytesData:(RGLBytesData* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLUVFiberElement:(RGLUVFiberElement* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocReaderDocumentsDatabase:(RGLDocReaderDocumentsDatabase* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderComparison:(RGLDocumentReaderComparison* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderValidity:(RGLDocumentReaderValidity* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderSymbol:(RGLDocumentReaderSymbol* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextSource:(RGLDocumentReaderTextSource* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderRfidOrigin:(RGLDocumentReaderRfidOrigin* _Nullable)input; -+(NSMutableDictionary* _Nonnull)generateRGLElementRect:(RGLElementRect* _Nullable)input; ++(UIImage* _Nullable)imageWithBase64:(NSString* _Nullable)input; ++(NSData* _Nullable)base64Decode:(NSString* _Nullable)input; + ++(NSString* _Nonnull)generateSuccessCompletion:(BOOL)success :(NSError* _Nullable)error; ++(NSString* _Nullable)generateCompletion:(NSNumber*_Nonnull)action :(RGLDocumentReaderResults*_Nullable)results :(NSError*_Nullable)error; ++(NSString* _Nonnull)generatePACertificateCompletion:(NSData *_Nullable)serialNumber :(RGLPAResourcesIssuer *_Nullable)issuer; ++(NSString* _Nullable)generateFinalizePackageCompletion:(NSNumber*_Nonnull)action :(RGLTransactionInfo*_Nullable)info :(NSError*_Nullable)error; ++(NSString* _Nullable)generateDeviceEngagementCompletion:(RGLDeviceEngagement* _Nullable)deviceEngagement :(NSError* _Nullable)error; ++(RGLConfig* _Nullable)configFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateConfig:(RGLConfig* _Nullable)input; ++(RGLBleConfig* _Nullable)bleDeviceConfigFromJson:(NSDictionary* _Nullable)input :(RGLBluetooth* _Nonnull)bluetooth; ++(RGLOnlineProcessingConfig* _Nullable)onlineProcessingConfigFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateOnlineProcessingConfig:(RGLOnlineProcessingConfig* _Nullable)input; ++(RGLImageInput* _Nullable)imageInputFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateImageInput:(RGLImageInput* _Nullable)input; ++(RGLRecognizeConfig* _Nullable)recognizeConfigFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRecognizeConfig:(RGLRecognizeConfig* _Nullable)input; ++(RGLScannerConfig* _Nullable)scannerConfigFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateScannerConfig:(RGLScannerConfig* _Nullable)input; ++(RGLFaceAPISearchParams* _Nullable)faceAPISearchParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFaceAPISearchParams:(RGLFaceAPISearchParams* _Nullable)input; ++(RGLFaceAPIParams* _Nullable)faceAPIParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFaceAPIParams:(RGLFaceAPIParams* _Nullable)input; ++(RGLAuthenticityParams* _Nullable)authenticityParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAuthenticityParams:(RGLAuthenticityParams* _Nullable)input; ++(RGLLivenessParams* _Nullable)livenessParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateLivenessParams:(RGLLivenessParams* _Nullable)input; ++(RGLGlaresCheckParams* _Nullable)glaresCheckParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateGlaresCheckParams:(RGLGlaresCheckParams* _Nullable)input; ++(RGLImageQA* _Nullable)imageQAFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateImageQA:(RGLImageQA* _Nullable)input; ++(RGLRFIDParams* _Nullable)rfidParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRFIDParams:(RGLRFIDParams* _Nullable)input; ++(RGLProcessParams* _Nullable)processParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateProcessParams:(RGLProcessParams* _Nullable)input; ++(RGLBackendProcessingConfig* _Nullable)backendProcessingConfigFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateBackendProcessingConfig:(RGLBackendProcessingConfig* _Nullable)input; ++(RGLBsi* _Nullable)bsiFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateBsi:(RGLBsi* _Nullable)input; ++(RGLeDLDataGroup* _Nullable)eDLDataGroupsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateEDLDataGroups:(RGLeDLDataGroup* _Nullable)input; ++(RGLePassportDataGroup* _Nullable)ePassportDataGroupsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateEPassportDataGroups:(RGLePassportDataGroup* _Nullable)input; ++(RGLeIDDataGroup* _Nullable)eIDDataGroupsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateEIDDataGroups:(RGLeIDDataGroup* _Nullable)input; ++(RGLeIDDataGroup* _Nullable)dtcDataGroupFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRGLDTCDataGroup:(RGLeIDDataGroup* _Nullable)input; ++(RGLRFIDScenario* _Nullable)rfidScenarioFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRFIDScenario:(RGLRFIDScenario* _Nullable)input; ++(RGLCustomization* _Nullable)customizationFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateCustomization:(RGLCustomization* _Nullable)input; ++(RGLFunctionality* _Nullable)functionalityFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFunctionality:(RGLFunctionality* _Nullable)input; ++(RGLDocReaderDocumentsDatabase* _Nullable)docReaderDocumentsDatabaseFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocReaderDocumentsDatabase:(RGLDocReaderDocumentsDatabase* _Nullable)input; ++(NSDictionary* _Nullable)generateDocReaderVersion:(RGLDocReaderVersion* _Nullable)input; ++(RGLScenario* _Nullable)scenarioFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nonnull)generateScenario:(RGLScenario* _Nullable)input; ++(NSString* _Nullable)generateLicense:(RGLLicense* _Nullable)input; ++(NSError* _Nullable)errorFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateError:(NSError* _Nullable)input; ++(RGLAuthenticityElement* _Nullable)authenticityElementFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAuthenticityElement:(RGLAuthenticityElement* _Nullable)input; ++(RGLAuthenticityCheck* _Nullable)authenticityCheckFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAuthenticityCheck:(RGLAuthenticityCheck* _Nullable)input; ++(RGLDocumentReaderAuthenticityResult* _Nullable)documentReaderAuthenticityResultFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderAuthenticityResult:(RGLDocumentReaderAuthenticityResult* _Nullable)input; ++(RGLPDF417Info* _Nullable)pdf417InfoFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePDF417Info:(RGLPDF417Info* _Nullable)input; ++(RGLDocumentReaderBarcodeField* _Nullable)documentReaderBarcodeFieldFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderBarcodeField:(RGLDocumentReaderBarcodeField* _Nullable)input; ++(RGLDocumentReaderBarcodeResult* _Nullable)documentReaderBarcodeResultFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderBarcodeResult:(RGLDocumentReaderBarcodeResult* _Nullable)input; ++(RGLImageQuality* _Nullable)imageQualityFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateImageQuality:(RGLImageQuality* _Nullable)input; ++(RGLImageQualityGroup* _Nullable)imageQualityGroupFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateImageQualityGroup:(RGLImageQualityGroup* _Nullable)input; ++(RGLAccessControlProcedureType* _Nullable)accessControlProcedureTypeFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAccessControlProcedureType:(RGLAccessControlProcedureType* _Nullable)input; ++(RGLFileData* _Nullable)fileDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFileData:(RGLFileData* _Nullable)input; ++(RGLCertificateData* _Nullable)certificateDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateCertificateData:(RGLCertificateData* _Nullable)input; ++(RGLSecurityObjectCertificates* _Nullable)securityObjectCertificatesFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateSecurityObjectCertificates:(RGLSecurityObjectCertificates* _Nullable)input; ++(RGLFile* _Nullable)fileFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFile:(RGLFile* _Nullable)input; ++(RGLApplication* _Nullable)applicationFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateApplication:(RGLApplication* _Nullable)input; ++(RGLRFIDValue* _Nullable)rfidValueFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRFIDValue:(RGLRFIDValue* _Nullable)input; ++(RGLAttribute* _Nullable)attributeFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAttribute:(RGLAttribute* _Nullable)input; ++(RGLAuthority* _Nullable)authorityFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateAuthority:(RGLAuthority* _Nullable)input; ++(RGLCardProperties* _Nullable)cardPropertiesFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateCardProperties:(RGLCardProperties* _Nullable)input; ++(RGLExtension* _Nullable)extensionFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateExtension:(RGLExtension* _Nullable)input; ++(RGLValidity* _Nullable)validityFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateValidity:(RGLValidity* _Nullable)input; ++(RGLCertificateChain* _Nullable)certificateChainFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateCertificateChain:(RGLCertificateChain* _Nullable)input; ++(RGLDataField* _Nullable)dataFieldFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDataField:(RGLDataField* _Nullable)input; ++(RGLSignerInfo* _Nullable)signerInfoFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateSignerInfo:(RGLSignerInfo* _Nullable)input; ++(RGLSecurityObject* _Nullable)securityObjectFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateSecurityObject:(RGLSecurityObject* _Nullable)input; ++(RGLRFIDSessionData* _Nullable)rfidSessionDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRFIDSessionData:(RGLRFIDSessionData* _Nullable)input; ++(RGLBytesData* _Nullable)bytesDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateBytesData:(RGLBytesData* _Nullable)input; ++(RGLVDSNCData* _Nullable)vdsncDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateVDSNCData:(RGLVDSNCData* _Nullable)input; ++(RGLDocFeature* _Nullable)docFeatureFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocFeature:(RGLDocFeature* _Nullable)input; ++(RGLVDSData* _Nullable)vdsDataFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateVDSData:(RGLVDSData* _Nullable)input; ++(RGLOpticalStatus* _Nullable)opticalStatusFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateOpticalStatus:(RGLOpticalStatus* _Nullable)input; ++(RGLRFIDSessionDataStatus* _Nullable)rfidSessionDataStatusFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRFIDSessionDataStatus:(RGLRFIDSessionDataStatus* _Nullable)input; ++(RGLDocumentReaderResultsStatus* _Nullable)documentReaderResultsStatusFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderResultsStatus:(RGLDocumentReaderResultsStatus* _Nullable)input; ++(RGLDocumentReaderComparison* _Nullable)documentReaderComparisonFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderComparison:(RGLDocumentReaderComparison* _Nullable)input; ++(CGRect)rectFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateRect:(CGRect)input; ++(RGLDocumentReaderGraphicField* _Nullable)documentReaderGraphicFieldFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderGraphicField:(RGLDocumentReaderGraphicField* _Nullable)input; ++(RGLDocumentReaderGraphicResult* _Nullable)documentReaderGraphicResultFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderGraphicResult:(RGLDocumentReaderGraphicResult* _Nullable)input; ++(RGLDocumentReaderRfidOrigin* _Nullable)documentReaderRfidOriginFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderRfidOrigin:(RGLDocumentReaderRfidOrigin* _Nullable)input; ++(RGLDocumentReaderSymbol* _Nullable)documentReaderSymbolFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderSymbol:(RGLDocumentReaderSymbol* _Nullable)input; ++(RGLDocumentReaderValidity* _Nullable)documentReaderValidityFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderValidity:(RGLDocumentReaderValidity* _Nullable)input; ++(RGLDocumentReaderValue* _Nullable)documentReaderValueFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderValue:(RGLDocumentReaderValue* _Nullable)input; ++(RGLDocumentReaderTextField* _Nullable)documentReaderTextFieldFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderTextField:(RGLDocumentReaderTextField* _Nullable)input; ++(RGLDocumentReaderTextSource* _Nullable)documentReaderTextSourceFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderTextSource:(RGLDocumentReaderTextSource* _Nullable)input; ++(RGLDocumentReaderTextResult* _Nullable)documentReaderTextResultFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderTextResult:(RGLDocumentReaderTextResult* _Nullable)input; ++(RGLDocumentReaderDocumentType* _Nullable)documentReaderDocumentTypeFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderDocumentType:(RGLDocumentReaderDocumentType* _Nullable)input; ++(CGPoint)pointFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePoint:(CGPoint)input; ++(RGLPosition* _Nullable)positionFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePosition:(RGLPosition* _Nullable)input; ++(RGLDocumentReaderResults* _Nullable)documentReaderResultsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentReaderResults:(RGLDocumentReaderResults* _Nullable)input; ++(NSString* _Nonnull)generateDocumentReaderNotification:(RGLRFIDNotify* _Nullable)input; ++(RGLPAAttribute* _Nullable)paAttributeFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePAAttribute:(RGLPAAttribute* _Nullable)input; ++(RGLPAResourcesIssuer* _Nullable)paResourcesIssuerFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePAResourcesIssuer:(RGLPAResourcesIssuer* _Nullable)input; ++(RGLPKDCertificate* _Nullable)pkdCertificateFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePKDCertificate:(RGLPKDCertificate* _Nullable)input; ++(NSDictionary* _Nullable)generateTAChallenge:(RGLTAChallenge* _Nullable)input; ++(RGLTAChallenge* _Nullable)taChallengeFromJson:(NSDictionary* _Nullable)input; ++(RGLTCCParams* _Nullable)tccParamsFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateTCCParams:(RGLTCCParams* _Nullable)input; ++(RGLTransactionInfo* _Nullable)transactionInfoFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateTransactionInfo:(RGLTransactionInfo* _Nullable)input; ++(RGLDetailsAge* _Nullable)detailsAgeFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDetailsAge:(RGLDetailsAge* _Nullable)input; ++(RGLDeviceRetrievalMethod* _Nullable)deviceRetrievalMethodFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDeviceRetrievalMethod:(RGLDeviceRetrievalMethod* _Nullable)input; ++(RGLDocumentRequest18013MDL* _Nullable)documentRequest18013MDLFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentRequest18013MDL:(RGLDocumentRequest18013MDL* _Nullable)input; ++(RGLDataRetrieval* _Nullable)dataRetrievalFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDataRetrieval:(RGLDataRetrieval* _Nullable)input; ++(RGLDeviceEngagement* _Nullable)deviceEngagementFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDeviceEngagement:(RGLDeviceEngagement* _Nullable)input; ++(RGLNameSpaceMDL* _Nullable)nameSpaceMDLFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateNameSpaceMDL:(RGLNameSpaceMDL* _Nullable)input; ++(RGLDocumentRequestMDL* _Nullable)documentRequestMDLFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateDocumentRequestMDL:(RGLDocumentRequestMDL* _Nullable)input; ++(RGLFinalizeConfig* _Nullable)finalizeConfigFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateFinalizeConfig:(RGLFinalizeConfig* _Nullable)input; ++(RGLRFIDAccessControlPACE* _Nullable)paceProtocolFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generatePaceProtocol:(RGLRFIDAccessControlPACE* _Nullable)input; ++(RGLRFIDAccessControlCA* _Nullable)caProtocolFromJson:(NSDictionary* _Nullable)input; ++(NSDictionary* _Nullable)generateCaProtocol:(RGLRFIDAccessControlCA* _Nullable)input; + +@end + +@interface RGLWRequestInterceptorProxy : NSObject +- (instancetype _Nonnull)initWithHeaders:(NSDictionary*_Nonnull)headers; @end -#endif \ No newline at end of file + +#endif diff --git a/ios/Classes/RGLWJSONConstructor.m b/ios/Classes/RGLWJSONConstructor.m index f112497d40..7cdf9c4f1f 100644 --- a/ios/Classes/RGLWJSONConstructor.m +++ b/ios/Classes/RGLWJSONConstructor.m @@ -1,550 +1,817 @@ #import #import "RGLWJSONConstructor.h" -#pragma clang diagnostic ignored "-Wdeprecated-declarations" @implementation RGLWJSONConstructor -+(NSString*)dictToString:(NSMutableDictionary*)input { +static NSMutableArray* weakReferencesHolder; ++(void) holdWeakReference:(id)reference { + if(!weakReferencesHolder) + weakReferencesHolder = [NSMutableArray new]; + [weakReferencesHolder addObject:reference]; +} + ++(id)toSendable:(id)input { + if (!input || [input isEqual:[NSNull null]]) return nil; + if ([input isKindOfClass:[NSDictionary class]] || [input isKindOfClass:[NSArray class]]) + return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:input + options:NSJSONWritingPrettyPrinted + error:nil] + encoding:NSUTF8StringEncoding]; + return input; +} + ++(NSString*)dictToString:(NSDictionary*)input { + if(input == nil) return nil; return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:input options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; } -+(NSString*)arrayToString:(NSMutableArray*)input { ++(NSString*)arrayToString:(NSArray*)input { + if(input == nil) return nil; return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:input options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; } -+(NSMutableDictionary* _Nonnull)generateNSError:(NSError* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSData*)base64Decode:(NSString*)input { + if(input == nil) return nil; + if ([input hasPrefix:@"data"]) input = [input substringFromIndex:[input rangeOfString:@","].location + 1]; + return [[NSData alloc] initWithBase64EncodedString:input options:0]; +} - result[@"errorCode"] = [NSNumber numberWithInteger:input.code]; - result[@"message"] = input.localizedDescription; ++(NSString*)base64Encode:(NSData*)input { + if(input == nil) return nil; + return [input base64EncodedStringWithOptions:0]; +} - return result; ++(UIImage*)imageWithBase64:(NSString*)input { + if(input == nil) return nil; + return [UIImage imageWithData:[self base64Decode:input]]; } -+(NSMutableDictionary* _Nonnull)generateNSDictionary:(NSDictionary* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSString*)base64WithImage:(UIImage*)input { + return [self base64Encode: UIImagePNGRepresentation(input)]; +} - for(NSNumber* key in input) - result[[key stringValue]] = input[key]; ++(NSError*)errorFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSInteger code = [[input valueForKey:@"code"] integerValue]; + NSString* message = [input valueForKey:@"message"]; + NSDictionary *userInfo = @{NSLocalizedDescriptionKey: NSLocalizedString(message, nil)}; + return [NSError errorWithDomain:RGLDocumentReaderDomain code:code userInfo:userInfo]; +} ++(NSDictionary*)generateError:(NSError*)input { + if(input == nil) return nil; + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"code"] = [NSNumber numberWithInteger:input.code]; + result[@"message"] = input.localizedDescription; + return result; } -+(UIImage*)imageWithBase64:(NSString*)input { - if(input == nil) return nil; - return [UIImage imageWithData:[[NSData alloc]initWithBase64EncodedString:input options:NSDataBase64DecodingIgnoreUnknownCharacters]]; ++(NSString*)generateCompletion:(NSNumber*)action :(RGLDocumentReaderResults*)results :(NSError*)error { + NSMutableDictionary *result = [NSMutableDictionary new]; + int actionInt = [action intValue]; + + if(actionInt == 0 || actionInt == 2 || actionInt == 3 || actionInt == 4 || actionInt == 6) + result[@"results"] = [self generateDocumentReaderResults:results]; + result[@"action"] = action; + result[@"error"] = [self generateError:error]; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(NSString*)generateSuccessCompletion:(BOOL)success :(NSError*)error { + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"success"] = success? @YES : @NO; + result[@"error"] = [self generateError:error]; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(NSString*)generatePACertificateCompletion:(NSData *)serialNumber :(RGLPAResourcesIssuer *)issuer{ + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"serialNumber"] = [self base64Encode:serialNumber];; + result[@"issuer"] = [self generatePAResourcesIssuer:issuer]; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(NSString*)generateFinalizePackageCompletion:(NSNumber*)action :(RGLTransactionInfo*)info :(NSError*)error { + NSMutableDictionary *result = [NSMutableDictionary new]; + + result[@"action"] = action; + result[@"info"] = [self generateTransactionInfo:info]; + result[@"error"] = [self generateError:error]; + + return [RGLWJSONConstructor dictToString: result]; } -+(NSString*)base64WithImage:(UIImage*)input { ++(RGLTransactionInfo*)transactionInfoFromJson:(NSDictionary*)input { if(input == nil) return nil; - return [UIImageJPEGRepresentation(input, 1.0) base64EncodedStringWithOptions:0]; + + NSString* transactionId = [input valueForKey:@"transactionId"]; + NSString* tag = [input valueForKey:@"tag"]; + NSString* sessionLogFolder = input[@"sessionLogFolder"]; + + return [[RGLTransactionInfo alloc] initWithTag:tag transactionId:transactionId sessionLogFolder:sessionLogFolder]; } -+(RGLPKDCertificate*)RGLPKDCertificateFromJson:(NSDictionary*)input { - NSInteger type = [[input valueForKey:@"resourceType"] integerValue]; - NSData* binaryData = [[NSData alloc] initWithBase64EncodedString:[input objectForKey:@"binaryData"] options:0]; - NSData* privateKey = [input objectForKey:@"privateKey"] != nil ? [[NSData alloc] initWithBase64EncodedString:[input objectForKey:@"privateKey"] options:0] : nil; - - return [[RGLPKDCertificate alloc] initWithBinaryData:binaryData resourceType:type privateKey:privateKey]; ++(NSDictionary*)generateTransactionInfo:(RGLTransactionInfo*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"transactionId"] = input.transactionId; + result[@"tag"] = input.tag; + result[@"sessionLogFolder"] = input.sessionLogFolder; + + return result; } -+(RGLTCCParams*)RGLTCCParamsFromJson:(NSDictionary*)input { ++(RGLTCCParams*)tccParamsFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSString* serviceTAURLString = [input valueForKey:@"serviceUrlTA"]; NSString* servicePAURLString = [input valueForKey:@"serviceUrlPA"]; NSString* pfxCertURLString = [input valueForKey:@"pfxCertUrl"]; NSString* pfxPassPhrase = [input valueForKey:@"pfxPassPhrase"]; - NSData* pfxCertData = [input objectForKey:@"pfxCert"] != nil ? [[NSData alloc] initWithBase64EncodedString:[input objectForKey:@"pfxCert"] options:0] : nil; - + NSData* pfxCertData = [self base64Decode:[input objectForKey:@"pfxCert"]]; + return [[RGLTCCParams alloc] initWithServiceTAURLString:serviceTAURLString servicePAURLString:servicePAURLString pfxCertURLString:pfxCertURLString pfxCertData: pfxCertData pfxPassPhrase:pfxPassPhrase]; } -+(RGLConfig*)RGLConfigFromJson:(NSDictionary*)input { - if([input valueForKey:@"license"] == nil) return nil; - RGLConfig *config = [[RGLConfig alloc] initWithLicenseData:[[NSData alloc] initWithBase64EncodedString:[input valueForKey:@"license"] options:0]]; - - if([input valueForKey:@"databasePath"] != nil) - config.databasePath = [[input valueForKey:@"databasePath"] stringValue]; - if([input valueForKey:@"licenseUpdate"] != nil) - config.licenseUpdateCheck = [[input valueForKey:@"licenseUpdate"] boolValue]; - if([input valueForKey:@"delayedNNLoad"] != nil) - config.delayedNNLoadEnabled = [[input valueForKey:@"delayedNNLoad"] boolValue]; ++(NSDictionary*)generateTCCParams:(RGLTCCParams*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"serviceUrlTA"] = input.serviceTAURLString; + result[@"serviceUrlPA"] = input.servicePAURLString; + result[@"pfxCertUrl"] = input.pfxCertURLString; + result[@"pfxPassPhrase"] = input.pfxPassPhrase; + result[@"pfxCert"] = [self base64Encode:input.pfxCertData]; + + return result; +} ++(RGLConfig*)configFromJson:(NSDictionary*)input { + if (!input) return nil; + if (!input[@"license"]) return nil; + RGLConfig *config = [[RGLConfig alloc] initWithLicenseData:[self base64Decode: input[@"license"]]]; + + if (input[@"databasePath"]) config.databasePath = input[@"databasePath"]; + if (input[@"licenseUpdateTimeout"]) config.licenseUpdateTimeout = input[@"licenseUpdateTimeout"]; + if (input[@"licenseUpdate"]) config.licenseUpdateCheck = [input[@"licenseUpdate"] boolValue]; + if (input[@"delayedNNLoad"]) config.delayedNNLoadEnabled = [input[@"delayedNNLoad"] boolValue]; + return config; } -+(RGLScannerConfig*)RGLScannerConfigFromJson:(NSDictionary*)input { - if([input valueForKey:@"scenario"] == nil && [input valueForKey:@"onlineProcessingConfig"] == nil) return nil; - RGLScannerConfig *config = [RGLScannerConfig new]; - - if([input valueForKey:@"scenario"] != nil) - config.scenario = [input valueForKey:@"scenario"]; - if([input valueForKey:@"onlineProcessingConfig"] != nil) - config.onlineProcessingConfig = [RGLWRegulaConfig RGLOnlineProcessingConfigFromJSON:[input valueForKey:@"onlineProcessingConfig"]]; - if([input valueForKey:@"livePortrait"] != nil) - config.livePortrait = [self imageWithBase64:[input valueForKey:@"livePortrait"]]; - if([input valueForKey:@"extPortrait"] != nil) - config.extPortrait = [self imageWithBase64:[input valueForKey:@"extPortrait"]]; ++(NSDictionary*)generateConfig:(RGLConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"license"] = [self base64Encode: input.licenseData]; + result[@"databasePath"] = input.databasePath; + result[@"licenseUpdateTimeout"] = input.licenseUpdateTimeout; + result[@"licenseUpdate"] = @(input.licenseUpdateCheck); + result[@"delayedNNLoad"] = @(input.delayedNNLoadEnabled); + + return result; +} ++(RGLBleConfig*)bleDeviceConfigFromJson:(NSDictionary*)input :(RGLBluetooth*)bluetooth { + if (!input) return nil; + RGLBleConfig *config = [[RGLBleConfig alloc] initWithBluetooth:bluetooth]; + + if (input[@"databasePath"]) config.databasePath = input[@"databasePath"]; + if (input[@"licenseUpdateTimeout"]) config.licenseUpdateTimeout = input[@"licenseUpdateTimeout"]; + if (input[@"licenseUpdate"]) config.licenseUpdateCheck = [input[@"licenseUpdate"] boolValue]; + if (input[@"delayedNNLoad"]) config.delayedNNLoadEnabled = [input[@"delayedNNLoad"] boolValue]; + return config; } -+(RGLRecognizeConfig*)RGLRecognizeConfigFromJson:(NSDictionary*)input { - if([input valueForKey:@"scenario"] == nil && [input valueForKey:@"onlineProcessingConfig"] == nil) return nil; - if([input valueForKey:@"image"] == nil && [input valueForKey:@"images"] == nil && [input valueForKey:@"imageInputs"] == nil) return nil; - RGLRecognizeConfig *config = [RGLRecognizeConfig alloc]; - - if([input valueForKey:@"image"] != nil) - config = [config initWithImage:[RGLWJSONConstructor imageWithBase64:[input valueForKey:@"image"]]]; - else if([input valueForKey:@"images"] != nil){ - NSMutableArray* images = [[NSMutableArray alloc] init]; - for(NSMutableString* base64 in [input valueForKey:@"images"]) - [images addObject:[RGLWJSONConstructor imageWithBase64:base64]]; - config = [config initWithImages:images]; - } else if([input valueForKey:@"imageInputs"] != nil){ - NSMutableArray* images = [[NSMutableArray alloc] init]; - for(NSDictionary* image in [input valueForKey:@"imageInputs"]) - [images addObject:[RGLWJSONConstructor RGLImageInputFromJson: image]]; - config = [config initWithImageInputs:images]; - } - - if([input valueForKey:@"scenario"] != nil) - config.scenario = [input valueForKey:@"scenario"]; - if([input valueForKey:@"onlineProcessingConfig"] != nil) - config.onlineProcessingConfig = [RGLWRegulaConfig RGLOnlineProcessingConfigFromJSON:[input valueForKey:@"onlineProcessingConfig"]]; - if([input valueForKey:@"livePortrait"] != nil) - config.livePortrait = [self imageWithBase64:[input valueForKey:@"livePortrait"]]; - if([input valueForKey:@"extPortrait"] != nil) - config.extPortrait = [self imageWithBase64:[input valueForKey:@"extPortrait"]]; - if([input valueForKey:@"oneShotIdentification"] != nil) - config.oneShotIdentification = [input valueForKey:@"oneShotIdentification"]; - ++(RGLScannerConfig*)scannerConfigFromJson:(NSDictionary*)input { + RGLScannerConfig *config = [RGLScannerConfig alloc]; + if (input[@"scenario"]) config = [config initWithScenario:input[@"scenario"]]; + else config = [config initWithOnlineProcessingConfig:[self onlineProcessingConfigFromJson:input[@"onlineProcessingConfig"]]]; + + if(input[@"onlineProcessingConfig"]) + config.onlineProcessingConfig = [self onlineProcessingConfigFromJson:input[@"onlineProcessingConfig"]]; + if(input[@"livePortrait"]) + config.livePortrait = [self imageWithBase64:input[@"livePortrait"]]; + if(input[@"extPortrait"]) + config.extPortrait = [self imageWithBase64:input[@"extPortrait"]]; + return config; } -+(RGLImageInput*)RGLImageInputFromJson:(NSDictionary*)input { - NSInteger pageIndex = 0; - if([input valueForKey:@"pageIndex"] != nil) - pageIndex = [[input valueForKey:@"pageIndex"] integerValue]; - NSInteger light = 6; - if([input valueForKey:@"light"] != nil) - light = [[input valueForKey:@"light"] integerValue]; - if([input valueForKey:@"image"] != nil) - return [[RGLImageInput alloc] initWithImage:[self imageWithBase64:[input valueForKey:@"image"]] light:light pageIndex:pageIndex]; - return nil; ++(NSDictionary*)generateScannerConfig:(RGLScannerConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"scenario"] = input.scenario; + result[@"onlineProcessingConfig"] = [self generateOnlineProcessingConfig: input.onlineProcessingConfig]; + result[@"livePortrait"] = [self base64WithImage: input.livePortrait]; + result[@"extPortrait"] = [self base64WithImage: input.extPortrait]; + + return result; } -+(NSMutableDictionary*)generateCGPoint:(CGPoint)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - - result[@"x"] = [NSNumber numberWithFloat:input.x]; - result[@"y"] = [NSNumber numberWithFloat:input.y]; ++(RGLRecognizeConfig*)recognizeConfigFromJson:(NSDictionary*)input { + RGLRecognizeConfig *config = [RGLRecognizeConfig alloc]; + if (input[@"scenario"]) config = [config initWithScenario:input[@"scenario"]]; + else config = [config initWithOnlineProcessingConfig:[self onlineProcessingConfigFromJson:input[@"onlineProcessingConfig"]]]; + + if (input[@"image"]) config.image = [RGLWJSONConstructor imageWithBase64:input[@"image"]]; + if (input[@"data"]) config.imageData = [RGLWJSONConstructor base64Decode:input[@"data"]]; + if (input[@"images"]) { + NSMutableArray* list = [NSMutableArray new]; + for(NSString* item in input[@"images"]) + [list addObject:[RGLWJSONConstructor imageWithBase64:item]]; + config.images = list; + } + if (input[@"dataList"]) { + NSMutableArray* list = [NSMutableArray new]; + for(NSString* item in input[@"dataList"]) + [list addObject:[RGLWJSONConstructor base64Decode:item]]; + config.imageDataArray = list; + } + if(input[@"imageInputData"]) { + NSMutableArray* imageInputs = [NSMutableArray new]; + for(NSDictionary* imageInput in input[@"imageInputData"]) + [imageInputs addObject:[RGLWJSONConstructor imageInputFromJson: imageInput]]; + config.imageInputs = imageInputs; + } + + if (input[@"scenario"]) config.scenario = input[@"scenario"]; + if (input[@"livePortrait"]) config.livePortrait = [self imageWithBase64:input[@"livePortrait"]]; + if (input[@"extPortrait"]) config.extPortrait = [self imageWithBase64:input[@"extPortrait"]]; + if (input[@"oneShotIdentification"]) config.oneShotIdentification = input[@"oneShotIdentification"]; + if (input[@"dtc"]) config.dtc = [RGLWJSONConstructor base64Decode:input[@"dtc"]]; + + return config; +} ++(NSDictionary*)generateRecognizeConfig:(RGLRecognizeConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"scenario"] = input.scenario; + result[@"onlineProcessingConfig"] = [self generateOnlineProcessingConfig: input.onlineProcessingConfig]; + result[@"livePortrait"] = [self base64WithImage: input.livePortrait]; + result[@"extPortrait"] = [self base64WithImage: input.extPortrait]; + result[@"oneShotIdentification"] = @(input.oneShotIdentification); + result[@"dtc"] = [self base64Encode: input.dtc]; + result[@"image"] = [self base64WithImage: input.image]; + result[@"data"] = [self base64Encode: input.imageData]; + if(input.images != nil) { + NSMutableArray *list = [NSMutableArray new]; + for(UIImage* item in input.images) + [list addObject:[self base64WithImage:item]]; + result[@"images"] = list; + } + if(input.imageDataArray != nil) { + NSMutableArray *list = [NSMutableArray new]; + for(NSData* item in input.imageDataArray) + [list addObject:[self base64Encode:item]]; + result[@"dataList"] = list; + } + if(input.imageInputs != nil) { + NSMutableArray *array = [NSMutableArray new]; + for(RGLImageInput* item in input.imageInputs) + [array addObject:[self generateImageInput:item]]; + result[@"imageInputData"] = array; + } + return result; } -+(NSMutableDictionary*)generateCGRect:(CGRect)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - - result[@"top"] = @(input.origin.y); - result[@"left"] = @(input.origin.x); - result[@"bottom"] = @(input.origin.y+input.size.height); - result[@"right"] = @(input.origin.x+input.size.width); ++(RGLBackendProcessingConfig*)backendProcessingConfigFromJson:(NSDictionary*)input { + if(input == nil) return nil; + RGLBackendProcessingConfig *result = [RGLBackendProcessingConfig new]; + + if([input valueForKey:@"url"] != nil) + result.url = [input valueForKey:@"url"]; + if([input valueForKey:@"httpHeaders"] != nil) + result.httpHeaders = [input valueForKey:@"httpHeaders"]; + if([input valueForKey:@"rfidServerSideChipVerification"] != nil) + result.rfidServerSideChipVerification = [input valueForKey:@"rfidServerSideChipVerification"]; + if([input valueForKey:@"mdlVerification"] != nil) + result.mDLVerification = [input valueForKey:@"mdlVerification"]; + if (input[@"timeoutConnection"]) result.timeoutConnection = input[@"timeoutConnection"]; + + return result; +} ++(NSDictionary*)generateBackendProcessingConfig:(RGLBackendProcessingConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"url"] = input.url; + result[@"httpHeaders"] = input.httpHeaders; + result[@"rfidServerSideChipVerification"] = input.rfidServerSideChipVerification; + result[@"mdlVerification"] = input.mDLVerification; + result[@"timeoutConnection"] = input.timeoutConnection; + return result; } -+(NSMutableArray*)generateNSArrayCGRect:(NSArray* _Nonnull)input { - NSMutableArray *result = [NSMutableArray new]; - for(NSValue* rect in input) - if(rect != nil) - [result addObject:[self generateCGRect:[rect CGRectValue]]]; ++(RGLBsi*)bsiFromJson:(NSDictionary*)input { + if(input == nil) return nil; + RGLBsi *result = [RGLBsi new]; + + if(input[@"generateResult"]) result.generateResult = input[@"generateResult"]; + return result; } -+(NSMutableDictionary*)generateVideoEncoderCompletion:(NSURL*)input :(NSError*)error { - NSMutableDictionary *result = [NSMutableDictionary new]; ++(NSDictionary*)generateBsi:(RGLBsi*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"generateResult"] = input.generateResult; + + return result; +} - result[@"filePath"] = input.absoluteString; - result[@"error"] = [self generateNSError:error]; - - return result; -} - -+(NSInteger)generateDocReaderAction:(RGLDocReaderAction)input { - NSInteger result = -1; - switch (input) { - case RGLDocReaderActionComplete: - result = 0; - break; - case RGLDocReaderActionProcess: - result = 1; - break; - case RGLDocReaderActionMorePagesAvailable: - result = 2; - break; - case RGLDocReaderActionCancel: - result = 3; - break; - case RGLDocReaderActionError: - result = 4; - break; - case RGLDocReaderActionProcessWhiteFlashLight: - result = 5; - break; - case RGLDocReaderActionProcessTimeout: - result = 6; - break; - case RGLDocReaderActionProcessOnServer: - result = 7; - break; - default: - break; - } - - return result; -} - -+(NSInteger)generateRFIDCompleteAction:(RGLRFIDCompleteAction)input { - NSInteger result = 0; - switch (input) { - case RGLRFIDCompleteActionComplete: - result = 0; - break; - case RGLRFIDCompleteActionError: - result = 4; - break; - case RGLRFIDCompleteActionCancel: - result = 3; - break; - case RGLRFIDCompleteActionSessionRestarted: - result = 0; - break; - default: - break; - } - - return result; -} - -+(NSMutableDictionary*)generateCompletion:(NSInteger)action :(RGLDocumentReaderResults*)results :(NSError*)error { - NSMutableDictionary *result = [NSMutableDictionary new]; ++(RGLImageQA*)imageQAFromJson:(NSDictionary*)input { + RGLImageQA *result = [RGLImageQA new]; + [RGLWConfig setImageQA:result input:input]; + return result; +} - if(action == 0 || action == 2 || action == 3 || action == 4 || action == 6) - result[@"results"] = [self generateRGLDocumentReaderResults:results]; - result[@"action"] = [NSNumber numberWithInteger:action]; - result[@"error"] = [self generateNSError:error]; ++(NSDictionary*)generateImageQA:(RGLImageQA*)input { + return [RGLWConfig getImageQA:input]; +} ++(RGLAuthenticityParams*)authenticityParamsFromJson:(NSDictionary*)input { + RGLAuthenticityParams *result = [RGLAuthenticityParams defaultParams]; + [RGLWConfig setAuthenticityParams:result input:input]; return result; } -+(NSNumber*)generateRGLImageQualityCheckType:(RGLImageQualityCheckType)value { - if(value == RGLImageQualityCheckTypeImageGlares) - return @0; - else if(value == RGLImageQualityCheckTypeImageFocus) - return @1; - else if(value == RGLImageQualityCheckTypeImageResolution) - return @2; - else if(value == RGLImageQualityCheckTypeImageColorness) - return @3; - else if(value == RGLImageQualityCheckTypeImagePerspective) - return @4; - else if(value == RGLImageQualityCheckTypeImageBounds) - return @5; - else if(value == RGLImageQualityCheckTypeScreenCapture) - return @6; - else if(value == RGLImageQualityCheckTypePortrait) - return @7; - else if(value == RGLImageQualityCheckTypeHandwritten) - return @8; - else - return @0; ++(NSDictionary*)generateAuthenticityParams:(RGLAuthenticityParams*)input { + return [RGLWConfig getAuthenticityParams:input]; } -+(NSString*)generateNSData:(NSData *)input { - return [NSKeyedUnarchiver unarchiveObjectWithData:input]; ++(RGLLivenessParams*)livenessParamsFromJson:(NSDictionary*)input { + RGLLivenessParams *result = [RGLLivenessParams defaultParams]; + [RGLWConfig setLivenessParams:result input:input]; + return result; } -+(NSMutableDictionary* _Nonnull)generatePACertificateCompletion:(NSData *)serialNumber :(RGLPAResourcesIssuer *)issuer{ - NSMutableDictionary *result = [NSMutableDictionary new]; - - result[@"serialNumber"] = [self generateNSData:serialNumber]; - result[@"issuer"] = [self generateRGLPAResourcesIssuer:issuer]; ++(NSDictionary*)generateLivenessParams:(RGLLivenessParams*)input { + return [RGLWConfig getLivenessParams:input]; +} ++(RGLeDLDataGroup*)eDLDataGroupsFromJson:(NSDictionary*)input { + RGLeDLDataGroup *result = [RGLeDLDataGroup new]; + [RGLWConfig setDataGroups :result dict:input]; return result; } -+(NSMutableDictionary* _Nonnull)generateDocumentReaderNotification:(RGLRFIDNotify* _Nullable)input{ - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"notificationCode"] = @(input.code & 0xFFFF0000); - result[@"dataFileType"] = @(input.code & 0x0000FFFF); - result[@"progress"] = @((int)input.value & 0xFFFFFFF0); ++(NSDictionary*)generateEDLDataGroups:(RGLeDLDataGroup*)input { + return [RGLWConfig getDataGroups:input]; +} ++(RGLePassportDataGroup*)ePassportDataGroupsFromJson:(NSDictionary*)input { + RGLePassportDataGroup *result = [RGLePassportDataGroup new]; + [RGLWConfig setDataGroups :result dict:input]; return result; } - // To JSON ++(NSDictionary*)generateEPassportDataGroups:(RGLePassportDataGroup*)input { + return [RGLWConfig getDataGroups:input]; +} -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderResults:(RGLDocumentReaderResults* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLeIDDataGroup*)eIDDataGroupsFromJson:(NSDictionary*)input { + RGLeIDDataGroup *result = [RGLeIDDataGroup new]; + [RGLWConfig setDataGroups :result dict:input]; + return result; +} - if(input.documentType != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderDocumentType* item in input.documentType) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderDocumentType:item]]; - result[@"documentType"] = array; - } - result[@"textResult"] = [self generateRGLDocumentReaderTextResult:input.textResult]; - result[@"graphicResult"] = [self generateRGLDocumentReaderGraphicResult:input.graphicResult]; - if(input.documentPosition != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLPosition* item in input.documentPosition) - if(item != nil) - [array addObject:[self generateRGLPosition:item]]; - result[@"documentPosition"] = array; - } - if(input.barcodePosition != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLPosition* item in input.barcodePosition) - if(item != nil) - [array addObject:[self generateRGLPosition:item]]; - result[@"barcodePosition"] = array; - } - if(input.mrzPosition != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLPosition* item in input.mrzPosition) - if(item != nil) - [array addObject:[self generateRGLPosition:item]]; - result[@"mrzPosition"] = array; - } - if(input.imageQualityGroup != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLImageQualityGroup* item in input.imageQualityGroup) - if(item != nil) - [array addObject:[self generateRGLImageQualityGroup:item]]; - result[@"imageQuality"] = array; - } - result[@"authenticityResult"] = [self generateRGLDocumentReaderAuthenticityResult:input.authenticityResults]; - result[@"rfidSessionData"] = [self generateRGLRFIDSessionData:input.rfidSessionData]; - result[@"chipPage"] = @(input.chipPage); - result[@"barcodeResult"] = [self generateRGLDocumentReaderBarcodeResult:input.barcodeResult]; - result[@"processingFinishedStatus"] = @(input.processingFinishedStatus); - result[@"morePagesAvailable"] = @(input.morePagesAvailable); - result[@"elapsedTime"] = @(input.elapsedTime); - result[@"elapsedTimeRFID"] = @(input.elapsedTimeRFID); - result[@"rawResult"] = input.rawResult; - result[@"status"] = [self generateRGLDocumentReaderResultsStatus:input.status]; - result[@"vdsncData"] = [self generateRGLVDSNCData:input.vdsncData]; ++(NSDictionary*)generateEIDDataGroups:(RGLeIDDataGroup*)input { + return [RGLWConfig getDataGroups:input]; +} ++(RGLDTCDataGroup*)dtcDataGroupFromJson:(NSDictionary*)input { + RGLDTCDataGroup *result = [RGLDTCDataGroup new]; + [RGLWConfig setDTCDataGroup:result dict:input]; return result; } -+(NSMutableDictionary* _Nonnull)generateRGLPosition:(RGLPosition* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"width"] = @(input.size.width); - result[@"height"] = @(input.size.height); - result[@"center"] = [self generateCGPoint:input.center]; - result[@"leftTop"] = [self generateCGPoint:input.leftTop]; - result[@"leftBottom"] = [self generateCGPoint:input.leftBottom]; - result[@"rightTop"] = [self generateCGPoint:input.rightTop]; - result[@"rightBottom"] = [self generateCGPoint:input.rightBottom]; - result[@"angle"] = @(input.angle); - result[@"perspectiveTr"] = @(input.perspectiveTr); - result[@"objArea"] = @(input.objArea); - result[@"objIntAngleDev"] = @(input.objIntAngleDev); - result[@"resultStatus"] = @(input.resultStatus); - result[@"docFormat"] = @(input.docFormat); - result[@"pageIndex"] = @(input.pageIndex); - result[@"dpi"] = @(input.dpi); - result[@"inverse"] = @(input.inverse); ++(NSDictionary*)generateRGLDTCDataGroup:(RGLDTCDataGroup*)input { + return [RGLWConfig getDTCDataGroup:input]; +} ++(RGLRFIDScenario*)rfidScenarioFromJson:(NSDictionary*)input { + RGLRFIDScenario *result = [RGLRFIDScenario new]; + [RGLWConfig setRfidScenario:input :result]; return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderBarcodeResult:(RGLDocumentReaderBarcodeResult* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - if(input.fields != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderBarcodeField* item in input.fields) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderBarcodeField:item]]; - result[@"fields"] = array; - } ++(NSDictionary*)generateRFIDScenario:(RGLRFIDScenario*)input { + return [RGLWConfig getRfidScenario:input]; +} ++(RGLCustomization*)customizationFromJson:(NSDictionary*)input { + RGLCustomization *result = [RGLCustomization new]; + [RGLWConfig setCustomization:input :result]; return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderBarcodeField:(RGLDocumentReaderBarcodeField* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"barcodeType"] = @(input.barcodeType); - result[@"status"] = @(input.status); - result[@"pdf417Info"] = [self generateRGLPDF417Info:input.pdf417Info]; - result[@"data"] = [NSKeyedUnarchiver unarchiveObjectWithData:input.data]; - result[@"pageIndex"] = @(input.pageIndex); ++(NSDictionary*)generateCustomization:(RGLCustomization*)input { + return [RGLWConfig getCustomization:input]; +} ++(RGLFunctionality*)functionalityFromJson:(NSDictionary*)input { + RGLFunctionality *result = [RGLFunctionality new]; + [RGLWConfig setFunctionality:input :result]; return result; } -+(NSMutableDictionary* _Nonnull)generateRGLPDF417Info:(RGLPDF417Info* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"errorLevel"] = @(input.errorLevel); - result[@"columns"] = @(input.columns); - result[@"rows"] = @(input.rows); ++(NSDictionary*)generateFunctionality:(RGLFunctionality*)input { + return [RGLWConfig getFunctionality:input]; +} ++(RGLOnlineProcessingConfig*)onlineProcessingConfigFromJson:(NSDictionary*)input { + if(input == nil) return nil; + if([input valueForKey:@"mode"] == nil) return nil; + + RGLOnlineProcessingConfig *result = [[RGLOnlineProcessingConfig alloc] initWithMode:[[input valueForKey:@"mode"] integerValue]]; + + if([input valueForKey:@"imageFormat"] != nil) + result.imageFormat = [[input valueForKey:@"imageFormat"] integerValue]; + if([input valueForKey:@"url"] != nil) + result.serviceURL = [input valueForKey:@"url"]; + if([input valueForKey:@"imageCompressionQuality"] != nil) + result.imageCompressionQuality = [[input valueForKey:@"imageCompressionQuality"] floatValue]; + if([input valueForKey:@"processParams"] != nil) { + RGLProcessParams *params = [RGLProcessParams new]; + [RGLWConfig setProcessParams:[input valueForKey:@"processParams"] :params]; + result.processParams = params; + } + if([input valueForKey:@"requestHeaders"] != nil) { + RGLWRequestInterceptorProxy* proxy = [[RGLWRequestInterceptorProxy alloc] initWithHeaders:[input valueForKey:@"requestHeaders"]]; + [self holdWeakReference: proxy]; + result.requestInterceptingDelegate = proxy; + } + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderAuthenticityResult:(RGLDocumentReaderAuthenticityResult* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)generateOnlineProcessingConfig:(RGLOnlineProcessingConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"mode"] = @(input.mode); + result[@"url"] = input.serviceURL; + result[@"processParams"] = [RGLWConfig getProcessParams:input.processParams]; + result[@"imageFormat"] = @(input.imageFormat); + result[@"imageCompressionQuality"] = @(input.imageCompressionQuality); + + return result; +} - result[@"status"] = @(input.status); - if(input.checks != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLAuthenticityCheck* item in input.checks) - if(item != nil) - [array addObject:[self generateRGLAuthenticityCheck:item]]; - result[@"checks"] = array; - } ++(RGLGlaresCheckParams*)glaresCheckParamsFromJson:(NSDictionary*)input { + if(input == nil) return nil; + RGLGlaresCheckParams *result = [RGLGlaresCheckParams new]; + + if([input valueForKey:@"imgMarginPart"] != nil) + result.imgMarginPart = [input valueForKey:@"imgMarginPart"]; + if([input valueForKey:@"maxGlaringPart"] != nil) + result.maxGlaringPart = [input valueForKey:@"maxGlaringPart"]; + + return result; +} ++(NSDictionary*)generateGlaresCheckParams:(RGLGlaresCheckParams*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"imgMarginPart"] = input.imgMarginPart; + result[@"maxGlaringPart"] = input.maxGlaringPart; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLAuthenticityCheck:(RGLAuthenticityCheck* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLImageInput*)imageInputFromJson:(NSDictionary*)input { + if(input == nil) return nil; + + NSInteger pageIndex = 0; + if([input valueForKey:@"pageIndex"] != nil) + pageIndex = [[input valueForKey:@"pageIndex"] integerValue]; + NSInteger light = 6; + if([input valueForKey:@"light"] != nil) + light = [[input valueForKey:@"light"] integerValue]; + if([input valueForKey:@"image"] != nil) + return [[RGLImageInput alloc] initWithImage:[self imageWithBase64:[input valueForKey:@"image"]] light:light pageIndex:pageIndex]; + return nil; +} - result[@"type"] = @(input.type); - result[@"typeName"] = input.typeName; - result[@"status"] = @(input.status); - if(input.elements != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLAuthenticityElement* item in input.elements) - if(item != nil) - [array addObject:[self generateRGLAuthenticityElement:item]]; - result[@"elements"] = array; - } ++(NSDictionary*)generateImageInput:(RGLImageInput*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"pageIndex"] = @(input.pageIndex); - + result[@"light"] = @(input.lightType); + result[@"image"] = [self base64WithImage:input.image]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLAuthenticityElement:(RGLAuthenticityElement* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLPKDCertificate*)pkdCertificateFromJson:(NSDictionary*)input { + if(input == nil) return nil; + + NSInteger type = [[input valueForKey:@"resourceType"] integerValue]; + NSData* binaryData = [self base64Decode:[input objectForKey:@"binaryData"]]; + NSData* privateKey = [self base64Decode:[input objectForKey:@"privateKey"]]; + + return [[RGLPKDCertificate alloc] initWithBinaryData:binaryData resourceType:type privateKey:privateKey]; +} - result[@"status"] = @(input.status); - result[@"elementType"] = @(input.elementType); - result[@"elementTypeName"] = input.elementTypeName; - result[@"elementDiagnose"] = @(input.elementDiagnose); - result[@"elementDiagnoseName"] = input.elementDiagnoseName; ++(NSDictionary*)generatePKDCertificate:(RGLPKDCertificate*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"resourceType"] = @(input.resourceType); + result[@"binaryData"] = [self base64Encode:input.binaryData]; + result[@"privateKey"] = [self base64Encode:input.privateKey]; + + return result; +} ++(RGLRFIDParams*)rfidParamsFromJson:(NSDictionary*)input { + RGLRFIDParams* result = [RGLRFIDParams new]; + + if([input valueForKey:@"paIgnoreNotificationCodes"] != nil) + result.paIgnoreNotificationCodes = [input valueForKey:@"paIgnoreNotificationCodes"]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLImageQualityGroup:(RGLImageQualityGroup* _Nullable)input { ++(NSDictionary*)generateRFIDParams:(RGLRFIDParams*)input { + if(input == nil) return nil; NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; + + result[@"paIgnoreNotificationCodes"] = input.paIgnoreNotificationCodes; + + return result; +} - result[@"count"] = @(input.count); - result[@"result"] = @(input.result); - if(input.imageQualityList != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLImageQuality* item in input.imageQualityList) - if(item != nil) - [array addObject:[self generateRGLImageQuality:item]]; - result[@"imageQualityList"] = array; - } ++(RGLProcessParams*)processParamsFromJson:(NSDictionary*)input { + RGLProcessParams* result = [RGLProcessParams new]; + [RGLWConfig setProcessParams:input :result]; + return result; +} ++(NSDictionary*)generateProcessParams:(RGLProcessParams*)input { + return [RGLWConfig getProcessParams:input]; +} + ++(RGLFaceAPIParams*)faceAPIParamsFromJson:(NSDictionary*)input { + RGLFaceAPIParams* result = [RGLFaceAPIParams defaultParams]; + + if([input valueForKey:@"url"] != nil) + result.url = [input valueForKey:@"url"]; + if([input valueForKey:@"mode"] != nil) + result.mode = [input valueForKey:@"mode"]; + if([input valueForKey:@"threshold"] != nil) + result.threshold = [input valueForKey:@"threshold"]; + if([input valueForKey:@"searchParams"] != nil) + result.searchParams = [self faceAPISearchParamsFromJson:[input valueForKey:@"searchParams"]]; + if([input valueForKey:@"serviceTimeout"] != nil) + result.serviceTimeout = [input valueForKey:@"serviceTimeout"]; + if([input valueForKey:@"proxy"] != nil) + result.proxy = [input valueForKey:@"proxy"]; + if([input valueForKey:@"proxyPassword"] != nil) + result.proxyPassword = [input valueForKey:@"proxyPassword"]; + if([input valueForKey:@"proxyType"] != nil) + result.proxyType = [input valueForKey:@"proxyType"]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLImageQuality:(RGLImageQuality* _Nullable)input { ++(NSDictionary*)generateFaceAPIParams:(RGLFaceAPIParams*)input { + if(input == nil) return nil; NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"type"] = [self generateRGLImageQualityCheckType:input.type]; - result[@"result"] = @(input.result); - result[@"featureType"] = @(input.featureType); - result[@"boundRects"] = [self generateNSArrayCGRect:input.boundRects]; + + result[@"url"] = input.url; + result[@"mode"] = input.mode; + result[@"searchParams"] = [self generateFaceAPISearchParams:input.searchParams]; + result[@"threshold"] = input.threshold; + result[@"serviceTimeout"] = input.serviceTimeout; + result[@"proxy"] = input.proxy; + result[@"proxyPassword"] = input.proxyPassword; + result[@"proxyType"] = input.proxyType; + + return result; +} ++(RGLFaceAPISearchParams*)faceAPISearchParamsFromJson:(NSDictionary*)input { + RGLFaceAPISearchParams* result = [RGLFaceAPISearchParams new]; + + if([input valueForKey:@"limit"] != nil) + result.limit = [input valueForKey:@"limit"]; + if([input valueForKey:@"threshold"] != nil) + result.threshold = [input valueForKey:@"threshold"]; + if([input valueForKey:@"groupIds"] != nil) + result.groupIDs = [input valueForKey:@"groupIds"]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderGraphicResult:(RGLDocumentReaderGraphicResult* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)generateFaceAPISearchParams:(RGLFaceAPISearchParams*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"limit"] = input.limit; + result[@"threshold"] = input.threshold; + result[@"groupIds"] = input.groupIDs; + + return result; +} - if(input.fields != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderGraphicField* item in input.fields) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderGraphicField:item]]; - result[@"fields"] = array; - } ++(RGLScenario*)scenarioFromJson:(NSDictionary*)input { + if(input == nil) return nil; + + NSString* identifier = [input valueForKey:@"name"]; + double frameKWHLandscape = [[input valueForKey:@"frameKWHLandscape"] doubleValue]; + double frameKWHPortrait = [[input valueForKey:@"frameKWHPortrait"] doubleValue]; + double frameKWHDoublePageSpreadPortrait = [[input valueForKey:@"frameKWHDoublePageSpreadPortrait"] doubleValue]; + double frameKWHDoublePageSpreadLandscape = [[input valueForKey:@"frameKWHDoublePageSpreadLandscape"] doubleValue]; + NSString* scenarioDescription = [input valueForKey:@"description"]; + BOOL faceExt = [[input valueForKey:@"faceExt"] boolValue]; + BOOL multiPageOff = [[input valueForKey:@"multiPageOff"] boolValue]; + BOOL seriesProcessMode = [[input valueForKey:@"seriesProcessMode"] boolValue]; + NSString* caption = [input valueForKey:@"caption"]; + BOOL uvTorch = [[input valueForKey:@"uvTorch"] boolValue]; + NSInteger frameOrientation = [[input valueForKey:@"frameOrientation"] integerValue]; + BOOL manualCrop = [[input valueForKey:@"manualCrop"] boolValue]; + + return [[RGLScenario new] initWithIdentifier:identifier frame:0 frameKWHLandscape:frameKWHLandscape frameKWHPortrait:frameKWHPortrait frameKWHDoublePageSpreadPortrait:frameKWHDoublePageSpreadPortrait frameKWHDoublePageSpreadLandscape:frameKWHDoublePageSpreadLandscape scenarioDescription:scenarioDescription barcodeExt:nil faceExt:faceExt multiPageOff:multiPageOff caption:caption uvTorch:uvTorch frameOrientation:frameOrientation seriesProcessMode:seriesProcessMode manualCrop:manualCrop]; +} + ++(NSDictionary*)generateScenario:(RGLScenario*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"name"] = input.identifier; + result[@"frameKWHLandscape"] = @(input.frameKWHLandscape); + result[@"frameKWHPortrait"] = @(input.frameKWHPortrait); + result[@"frameKWHDoublePageSpreadPortrait"] = @(input.frameKWHDoublePageSpreadPortrait); + result[@"frameKWHDoublePageSpreadLandscape"] = @(input.frameKWHDoublePageSpreadLandscape); + result[@"description"] = input.scenarioDescription; + result[@"faceExt"] = @(input.faceExt); + result[@"multiPageOff"] = @(input.multiPageOff); + result[@"seriesProcessMode"] = @(input.seriesProcessMode); + result[@"caption"] = input.caption; + result[@"uvTorch"] = @(input.uvTorch); + result[@"frameOrientation"] = @(input.frameOrientation); + result[@"manualCrop"] = @(input.manualCrop); + + return result; +} + ++(CGRect)rectFromJson:(NSDictionary*)input { + return CGRectMake( + [[input valueForKey:@"left"] floatValue], + [[input valueForKey:@"top"] floatValue], + [[input valueForKey:@"right"] floatValue] - [[input valueForKey:@"left"] floatValue], + [[input valueForKey:@"bottom"] floatValue] - [[input valueForKey:@"top"] floatValue]); +} ++(NSDictionary*)generateRect:(CGRect)input { + NSMutableDictionary* result = [NSMutableDictionary new]; + if(input.origin.x == 0 && input.origin.y == 0) return nil; + + result[@"top"] = @(input.origin.y); + result[@"left"] = @(input.origin.x); + result[@"bottom"] = @(input.origin.y+input.size.height); + result[@"right"] = @(input.origin.x+input.size.width); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderGraphicField:(RGLDocumentReaderGraphicField* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLDocumentReaderGraphicField*)documentReaderGraphicFieldFromJson:(NSDictionary*)input { + return [[RGLDocumentReaderGraphicField alloc] + initWithSourceType:[[input valueForKey:@"sourceType"] integerValue] + fieldType:[[input valueForKey:@"fieldType"] integerValue] + boundRect:[self rectFromJson: [input valueForKey:@"fieldRect"]] + value:[self imageWithBase64: [input valueForKey:@"value"]] + light:[[input valueForKey:@"light"] integerValue] + pageIndex:[[input valueForKey:@"pageIndex"] integerValue] + originalPageIndex:[[input valueForKey:@"originalPageIndex"] integerValue]]; +} ++(NSDictionary*)generateDocumentReaderGraphicField:(RGLDocumentReaderGraphicField*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"sourceType"] = @(input.sourceType); result[@"fieldType"] = @(input.fieldType); result[@"fieldName"] = input.fieldName; - result[@"fieldRect"] = [self generateCGRect:input.boundRect]; - result[@"value"] = [UIImageJPEGRepresentation(input.value, 1.0) base64EncodedStringWithOptions:0]; + result[@"fieldRect"] = [self generateRect:input.boundRect]; + result[@"value"] = [self base64WithImage:input.value]; result[@"light"] = @(input.lightType); result[@"lightName"] = input.lightName; result[@"pageIndex"] = @(input.pageIndex); result[@"originalPageIndex"] = @(input.originalPageIndex); - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextResult:(RGLDocumentReaderTextResult* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLDocumentReaderGraphicResult*)documentReaderGraphicResultFromJson:(NSDictionary*)input { + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"fields"]){ + [array addObject:[self documentReaderGraphicFieldFromJson: item]]; + } + return [[RGLDocumentReaderGraphicResult alloc] initWithFields:array]; +} - if(input.fields != nil){ ++(NSDictionary*)generateDocumentReaderGraphicResult:(RGLDocumentReaderGraphicResult*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.fields != nil) { NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderTextField* item in input.fields) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderTextField:item]]; + for(RGLDocumentReaderGraphicField* item in input.fields) + [array addObject:[self generateDocumentReaderGraphicField:item]]; result[@"fields"] = array; } - result[@"status"] = @(input.status); - result[@"comparisonStatus"] = @(input.comparisonStatus); - result[@"validityStatus"] = @(input.validityStatus); - if(input.availableSourceList != nil){ + + return result; +} + ++(NSDictionary*)documentReaderValueDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"containerType"] = [input valueForKey:@"sourceType"]; + json[@"fieldRect"] = [input valueForKey:@"boundRect"]; + + return json; +} + ++(RGLDocumentReaderValue*)documentReaderValueFromJson:(NSDictionary*)input { + return [RGLDocumentReaderValue initWithJSON:[self documentReaderValueDictionaryFromJson:input] field:[RGLDocumentReaderTextField initWithJSON:[NSDictionary new] sourceList:[NSDictionary new]]]; +} + ++(NSDictionary*)generateDocumentReaderValue:(RGLDocumentReaderValue*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"sourceType"] = @(input.sourceType); + result[@"value"] = input.value; + result[@"originalValue"] = input.originalValue; + result[@"boundRect"] = [self generateRect:input.boundRect]; + result[@"pageIndex"] = @(input.pageIndex); + result[@"probability"] = @(input.probability); + if(input.originalSymbols != nil){ NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderTextSource* item in input.availableSourceList) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderTextSource:item]]; - result[@"availableSourceList"] = array; + for(RGLDocumentReaderSymbol* item in input.originalSymbols) + [array addObject:[self generateDocumentReaderSymbol:item]]; + result[@"originalSymbols"] = array; } - + result[@"rfidOrigin"] = [self generateDocumentReaderRfidOrigin:input.rfidOrigin]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextField:(RGLDocumentReaderTextField* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)documentReaderTextFieldDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"sourceType"] = [[[input mutableArrayValueForKey:@"validityList"] objectAtIndex:0] valueForKey:@"sourceType"]; + json[@"sourceTypeLeft"] = [[[input mutableArrayValueForKey:@"comparisonList"] objectAtIndex:0] valueForKey:@"sourceTypeLeft"]; + json[@"sourceTypeRight"] = [[[input mutableArrayValueForKey:@"comparisonList"] objectAtIndex:0] valueForKey:@"sourceTypeRight"]; + NSMutableArray* validityList = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"validityList"]){ + [validityList addObject:[self documentReaderValidityDictionaryFromJson:item]]; + } + json[@"validityList"] = validityList; + NSMutableArray* comparisonList = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"comparisonList"]){ + [comparisonList addObject:[self documentReaderComparisonDictionaryFromJson:item]]; + } + json[@"comparisonList"] = comparisonList; + NSMutableArray* valueList = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"values"]){ + [valueList addObject:[self documentReaderValueDictionaryFromJson:item]]; + } + json[@"valueList"] = valueList; + + return json; +} + ++(RGLDocumentReaderTextField*)documentReaderTextFieldFromJson:(NSDictionary*)input { + return [RGLDocumentReaderTextField initWithJSON:[self documentReaderTextFieldDictionaryFromJson:input] sourceList:[self documentReaderTextFieldDictionaryFromJson:input]]; +} ++(NSDictionary*)generateDocumentReaderTextField:(RGLDocumentReaderTextField*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"fieldType"] = @(input.fieldType); result[@"fieldName"] = input.fieldName; result[@"lcid"] = @(input.lcid); @@ -552,67 +819,233 @@ +(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextField:(RGLDocumentR if(input.values != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLDocumentReaderValue* item in input.values) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderValue:item]]; + [array addObject:[self generateDocumentReaderValue:item]]; result[@"values"] = array; } result[@"status"] = @(input.status); + result[@"comparisonStatus"] = @(input.comparisonStatus); + result[@"validityStatus"] = @(input.validityStatus); result[@"value"] = input.value; - result[@"getValue"] = [self generateRGLDocumentReaderValue:[input getValue]]; + result[@"getValue"] = [self generateDocumentReaderValue:[input getValue]]; if(input.comparisonList != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLDocumentReaderComparison* item in input.comparisonList) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderComparison:item]]; + [array addObject:[self generateDocumentReaderComparison:item]]; result[@"comparisonList"] = array; } if(input.validityList != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLDocumentReaderValidity* item in input.validityList) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderValidity:item]]; + [array addObject:[self generateDocumentReaderValidity:item]]; result[@"validityList"] = array; } + + return result; +} + ++(NSDictionary*)documentReaderTextResultDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + NSMutableArray* availableSourceList = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"availableSourceList"]){ + [availableSourceList addObject:[self documentReaderTextSourceDictionaryFromJson:item]]; + } + json[@"availableSourceList"] = availableSourceList; + NSMutableArray* fields = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"fields"]){ + [fields addObject:[self documentReaderTextFieldDictionaryFromJson:item]]; + } + json[@"fieldList"] = fields; + + return json; +} + ++(RGLDocumentReaderTextResult*)documentReaderTextResultFromJson:(NSDictionary*)input { + return [RGLDocumentReaderTextResult initWithJSON:[self documentReaderTextResultDictionaryFromJson: input]]; +} ++(NSDictionary*)generateDocumentReaderTextResult:(RGLDocumentReaderTextResult*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.fields != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocumentReaderTextField* item in input.fields) + [array addObject:[self generateDocumentReaderTextField:item]]; + result[@"fields"] = array; + } + result[@"status"] = @(input.status); + result[@"comparisonStatus"] = @(input.comparisonStatus); + result[@"validityStatus"] = @(input.validityStatus); + if(input.availableSourceList != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocumentReaderTextSource* item in input.availableSourceList) + [array addObject:[self generateDocumentReaderTextSource:item]]; + result[@"availableSourceList"] = array; + } + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderValue:(RGLDocumentReaderValue* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(CGPoint)pointFromJson:(NSDictionary*)input { + return CGPointMake([[input valueForKey:@"x"] floatValue], [[input valueForKey:@"y"] floatValue]); +} - result[@"sourceType"] = @(input.sourceType); - result[@"value"] = input.value; - result[@"originalValue"] = input.originalValue; - result[@"boundRect"] = [self generateCGRect:input.boundRect]; - result[@"validity"] = @(input.validity); - result[@"comparison"] = [self generateNSDictionary:input.comparison]; ++(NSDictionary*)generatePoint:(CGPoint)input { + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"x"] = [NSNumber numberWithFloat:input.x]; + result[@"y"] = [NSNumber numberWithFloat:input.y]; + + return result; +} + ++(RGLPosition*)positionFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"Width"] = [input valueForKey:@"width"]; + json[@"Height"] = [input valueForKey:@"height"]; + json[@"Angle"] = [input valueForKey:@"angle"]; + json[@"Center"] = [input valueForKey:@"center"]; + json[@"LeftTop"] = [input valueForKey:@"leftTop"]; + json[@"LeftBottom"] = [input valueForKey:@"leftBottom"]; + json[@"RightTop"] = [input valueForKey:@"rightTop"]; + json[@"RightBottom"] = [input valueForKey:@"rightBottom"]; + json[@"PerspectiveTr"] = [input valueForKey:@"perspectiveTr"]; + json[@"ObjArea"] = [input valueForKey:@"objArea"]; + json[@"ObjIntAngleDev"] = [input valueForKey:@"objIntAngleDev"]; + json[@"ResultStatus"] = [input valueForKey:@"resultStatus"]; + json[@"docFormat"] = [input valueForKey:@"docFormat"]; + json[@"page_idx"] = [input valueForKey:@"pageIndex"]; + json[@"Dpi"] = [input valueForKey:@"dpi"]; + json[@"Inverse"] = [input valueForKey:@"inverse"]; + + return [RGLPosition initWithJSON:json]; +} + ++(NSDictionary*)generatePosition:(RGLPosition*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"width"] = @(input.size.width); + result[@"height"] = @(input.size.height); + result[@"angle"] = @(input.angle); + result[@"center"] = [self generatePoint:input.center]; + result[@"leftTop"] = [self generatePoint:input.leftTop]; + result[@"leftBottom"] = [self generatePoint:input.leftBottom]; + result[@"rightTop"] = [self generatePoint:input.rightTop]; + result[@"rightBottom"] = [self generatePoint:input.rightBottom]; + result[@"perspectiveTr"] = @(input.perspectiveTr); + result[@"objArea"] = @(input.objArea); + result[@"objIntAngleDev"] = @(input.objIntAngleDev); + result[@"resultStatus"] = @(input.resultStatus); + result[@"docFormat"] = @(input.docFormat); result[@"pageIndex"] = @(input.pageIndex); - result[@"probability"] = @(input.probability); - if(input.originalSymbols != nil){ + result[@"dpi"] = @(input.dpi); + result[@"inverse"] = @(input.inverse); + + return result; +} + ++(NSDictionary*)imageQualityDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"featureType"] = [input valueForKey:@"featureType"]; + json[@"type"] = [RGLWConfig imageQualityCheckTypeWithNumber:[input valueForKey:@"type"]]; + json[@"result"] = [input valueForKey:@"result"]; + NSDictionary* dict = @{@"List":[input valueForKey:@"boundRects"]}; + json[@"areas"] = dict; + + return json; +} + ++(RGLImageQuality*)imageQualityFromJson:(NSDictionary*)input { + return [RGLImageQuality initWithJSON:[self imageQualityDictionaryFromJson:input]]; +} + ++(NSDictionary*)generateImageQuality:(RGLImageQuality*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = [RGLWConfig generateImageQualityCheckType:input.type]; + result[@"result"] = @(input.result); + result[@"featureType"] = @(input.featureType); + if(input.boundRects != nil){ NSMutableArray *array = [NSMutableArray new]; - for(RGLDocumentReaderSymbol* item in input.originalSymbols) - if(item != nil) - [array addObject:[self generateRGLDocumentReaderSymbol:item]]; - result[@"originalSymbols"] = array; + for(NSValue* item in input.boundRects) { + id rect = [self generateRect:[item CGRectValue]]; + if(rect) [array addObject:rect]; + } + result[@"boundRects"] = array; } - result[@"rfidOrigin"] = [self generateRGLDocumentReaderRfidOrigin:input.rfidOrigin]; - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderDocumentType:(RGLDocumentReaderDocumentType* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLImageQualityGroup*)imageQualityGroupFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Count"] = [input valueForKey:@"count"]; + json[@"result"] = [input valueForKey:@"result"]; + json[@"page_idx"] = [input valueForKey:@"pageIndex"]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"imageQualityList"]){ + [array addObject:[self imageQualityDictionaryFromJson:item]]; + } + json[@"List"] = array; + + return [RGLImageQualityGroup initWithJSON:json]; +} + ++(NSDictionary*)generateImageQualityGroup:(RGLImageQualityGroup*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"count"] = @(input.count); + result[@"result"] = @(input.result); + if(input.imageQualityList != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLImageQuality* item in input.imageQualityList) + [array addObject:[self generateImageQuality:item]]; + result[@"imageQualityList"] = array; + } + result[@"pageIndex"] = @(input.pageIndex); + + return result; +} ++(RGLDocumentReaderDocumentType*)documentReaderDocumentTypeFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"DocumentName"] = [input valueForKey:@"name"]; + json[@"ID"] = [input valueForKey:@"documentID"]; + json[@"ICAOCode"] = [input valueForKey:@"ICAOCode"]; + json[@"List"] = [input valueForKey:@"FDSID"]; + json[@"dType"] = [input valueForKey:@"dType"]; + json[@"dFormat"] = [input valueForKey:@"dFormat"]; + json[@"dMRZ"] = [input valueForKey:@"dMRZ"]; + json[@"isDeprecated"] = [input valueForKey:@"isDeprecated"]; + json[@"dDescription"] = [input valueForKey:@"dDescription"]; + json[@"dYear"] = [input valueForKey:@"dYear"]; + json[@"dCountryName"] = [input valueForKey:@"dCountryName"]; + json[@"page_idx"] = [input valueForKey:@"pageIndex"]; + json[@"FDSIDList"] = json.copy; + + return [RGLDocumentReaderDocumentType initWithJSON:json]; +} + ++(NSDictionary*)generateDocumentReaderDocumentType:(RGLDocumentReaderDocumentType*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"name"] = input.name; result[@"documentID"] = @(input.documentID); result[@"ICAOCode"] = input.ICAOCode; if(input.FDSID != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.FDSID) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"FDSID"] = array; } result[@"dType"] = @(input.dType); @@ -623,179 +1056,156 @@ +(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderDocumentType:(RGLDocume result[@"dYear"] = input.dYear; result[@"dCountryName"] = input.dCountryName; result[@"pageIndex"] = @(input.pageIndex); - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLScenario:(RGLScenario* _Nullable)input { ++(NSString*)generateDocumentReaderNotification:(RGLRFIDNotify*)input{ + if(input == nil) return nil; NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"name"] = input.identifier; - result[@"frame"] = @(input.frame); - result[@"frameKWHLandscape"] = @(input.frameKWHLandscape); - result[@"frameKWHPortrait"] = @(input.frameKWHPortrait); - result[@"frameKWHDoublePageSpreadPortrait"] = @(input.frameKWHDoublePageSpreadPortrait); - result[@"frameKWHDoublePageSpreadLandscape"] = @(input.frameKWHDoublePageSpreadLandscape); - result[@"description"] = input.scenarioDescription; - result[@"barcodeExt"] = @(input.barcodeExt); - result[@"faceExt"] = @(input.faceExt); - result[@"multiPageOff"] = @(input.multiPageOff); - result[@"seriesProcessMode"] = @(input.seriesProcessMode); - result[@"caption"] = input.caption; - result[@"uvTorch"] = @(input.uvTorch); - result[@"frameOrientation"] = @(input.frameOrientation); - result[@"manualCrop"] = @(input.manualCrop); + + result[@"notificationCode"] = @(input.code & -0x10000); + result[@"dataFileType"] = @((int)input.attachment); + result[@"progress"] = @((int)input.value); + + return [RGLWJSONConstructor dictToString: result]; +} - return result; ++(NSDictionary*)accessControlProcedureTypeDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"ActiveOptionIdx"] = [input valueForKey:@"activeOptionIdx"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"Type"] = [input valueForKey:@"type"]; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLRFIDSessionData:(RGLRFIDSessionData* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLAccessControlProcedureType*)accessControlProcedureTypeFromJson:(NSDictionary*)input { + return [RGLAccessControlProcedureType initWithJSON:[self accessControlProcedureTypeDictionaryFromJson:input]]; +} - if(input.accessControls != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLAccessControlProcedureType* item in input.accessControls) - if(item != nil) - [array addObject:[self generateRGLAccessControlProcedureType:item]]; - result[@"accessControls"] = array; - } - if(input.applications != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLApplication* item in input.applications) - if(item != nil) - [array addObject:[self generateRGLApplication:item]]; - result[@"applications"] = array; - } - if(input.securityObjects != nil){ ++(NSDictionary*)generateAccessControlProcedureType:(RGLAccessControlProcedureType*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"activeOptionIdx"] = @(input.activeOptionIdx); + if(input.notifications != nil){ NSMutableArray *array = [NSMutableArray new]; - for(RGLSecurityObject* item in input.securityObjects) - if(item != nil) - [array addObject:[self generateRGLSecurityObject:item]]; - result[@"securityObjects"] = array; + for(NSNumber* item in input.notifications) + [array addObject:item]; + result[@"notifications"] = array; } - result[@"cardProperties"] = [self generateRGLCardProperties:input.cardProperties]; - result[@"totalBytesReceived"] = @(input.totalBytesReceived); - result[@"totalBytesSent"] = @(input.totalBytesSent); result[@"status"] = @(input.status); - result[@"extLeSupport"] = @(input.extLeSupport); - result[@"processTime"] = @(input.processTime); - if(input.dataGroups != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.dataGroups) - if(item != nil) - [array addObject:item]; - result[@"dataGroups"] = array; - } - if(input.dataFields != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLDataField* item in input.dataFields) - if(item != nil) - [array addObject:[self generateRGLDataField:item]]; - result[@"dataFields"] = array; - } - + result[@"type"] = @(input.type); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDataField:(RGLDataField* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)fileDataDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"Length"] = [input valueForKey:@"length"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"Type"] = [input valueForKey:@"type"]; + + return json; +} - result[@"data"] = input.data; - result[@"fieldType"] = @(input.fieldType); ++(RGLFileData*)fileDataFromJson:(NSDictionary*)input { + return [RGLFileData initWithJSON:[self fileDataDictionaryFromJson:input]]; +} ++(NSDictionary*)generateFileData:(RGLFileData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = input.data; + result[@"length"] = @(input.length); + result[@"status"] = @(input.status); + result[@"type"] = @(input.type); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLCardProperties:(RGLCardProperties* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)certificateDataDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"Length"] = [input valueForKey:@"length"]; + + return json; +} - result[@"aTQA"] = @(input.aTQA); - result[@"aTQB"] = input.aTQB; - result[@"aTR"] = input.aTR; - result[@"baudrate1"] = input.baudrate1; - result[@"baudrate2"] = input.baudrate2; - result[@"bitRateR"] = @(input.bitRateR); - result[@"bitRateS"] = @(input.bitRateS); - result[@"chipTypeA"] = @(input.chipTypeA); - result[@"mifareMemory"] = @(input.mifareMemory); - result[@"rfidType"] = @(input.rfidType); - result[@"sAK"] = @(input.sAK); - result[@"support4"] = @(input.support4); - result[@"supportMifare"] = @(input.supportMifare); - result[@"uID"] = input.uID; ++(RGLCertificateData*)certificateDataFromJson:(NSDictionary*)input { + return [RGLCertificateData initWithJSON:[self certificateDataDictionaryFromJson:input]]; +} ++(NSDictionary*)generateCertificateData:(RGLCertificateData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = input.data; + result[@"length"] = @(input.length); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLRFIDSessionDataStatus:(RGLRFIDSessionDataStatus* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"AA"] = @(input.AA); - result[@"BAC"] = @(input.BAC); - result[@"CA"] = @(input.CA); - result[@"PA"] = @(input.PA); - result[@"PACE"] = @(input.PACE); - result[@"TA"] = @(input.TA); - result[@"overallStatus"] = @(input.overallStatus); ++(NSDictionary*)securityObjectCertificatesDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Certificate_Data"] = [self certificateDataDictionaryFromJson: [input valueForKey:@"securityObject"]]; + + return json; +} ++(RGLSecurityObjectCertificates*)securityObjectCertificatesFromJson:(NSDictionary*)input { + return [RGLSecurityObjectCertificates initWithJSON:[self securityObjectCertificatesDictionaryFromJson:input]]; +} + ++(NSDictionary*)generateSecurityObjectCertificates:(RGLSecurityObjectCertificates*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"securityObject"] = [self generateCertificateData:input.securityObject]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLAccessControlProcedureType:(RGLAccessControlProcedureType* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)fileDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"FileData"] = [self fileDataDictionaryFromJson: [input valueForKey:@"fileData"]]; + json[@"SecurityObject_Certificates"] = [self securityObjectCertificatesDictionaryFromJson: [input valueForKey:@"certificates"]]; + json[@"FileID"] = [input valueForKey:@"fileID"]; + json[@"PA_Status"] = [input valueForKey:@"pAStatus"]; + json[@"ReadingStatus"] = [input valueForKey:@"readingStatus"]; + json[@"ReadingTime"] = [input valueForKey:@"readingTime"]; + json[@"Type"] = [input valueForKey:@"type"]; + json[@"DocFields_Originals"] = [input valueForKey:@"docFieldsOriginals"]; + json[@"DocFields_Graphics"] = [input valueForKey:@"docFieldsGraphics"]; + json[@"DocFields_Text"] = [input valueForKey:@"docFieldsText"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + + return json; +} - result[@"activeOptionIdx"] = @(input.activeOptionIdx); - if(input.notifications != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; - result[@"notifications"] = array; - } - result[@"status"] = @(input.status); - result[@"type"] = @(input.type); - - return result; -} - -+(NSMutableDictionary* _Nonnull)generateRGLApplication:(RGLApplication* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"applicationID"] = input.applicationID; - result[@"dataHashAlgorithm"] = input.dataHashAlgorithm; - if(input.files != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLFile* item in input.files) - if(item != nil) - [array addObject:[self generateRGLFile:item]]; - result[@"files"] = array; - } - result[@"type"] = @(input.type); - result[@"status"] = @(input.status); - result[@"unicodeVersion"] = input.unicodeVersion; - result[@"version"] = input.version; - - return result; ++(RGLFile*)fileFromJson:(NSDictionary*)input { + return [RGLFile initWithJSON:[self fileDictionaryFromJson:input]]; } -+(NSMutableDictionary* _Nonnull)generateRGLFile:(RGLFile* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"fileData"] = [self generateRGLFileData:input.fileData]; ++(NSDictionary*)generateFile:(RGLFile*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"fileData"] = [self generateFileData:input.fileData]; result[@"fileID"] = input.fileID; if(input.notifications != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"notifications"] = array; } result[@"pAStatus"] = @(input.pAStatus); @@ -806,383 +1216,989 @@ +(NSMutableDictionary* _Nonnull)generateRGLFile:(RGLFile* _Nullable)input { if(input.docFieldsText != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.docFieldsText) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"docFieldsText"] = array; } if(input.docFieldsGraphics != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.docFieldsGraphics) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"docFieldsGraphics"] = array; } if(input.docFieldsOriginals != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.docFieldsOriginals) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"docFieldsOriginals"] = array; } - result[@"certificates"] = [self generateRGLSecurityObjectCertificates:input.certificates]; - + result[@"certificates"] = [self generateSecurityObjectCertificates:input.certificates]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLFileData:(RGLFileData* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)applicationDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"ApplicationID"] = [input valueForKey:@"applicationID"]; + json[@"DataHashAlgorithm"] = [input valueForKey:@"dataHashAlgorithm"]; + json[@"Type"] = [input valueForKey:@"type"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"UnicodeVersion"] = [input valueForKey:@"unicodeVersion"]; + json[@"Version"] = [input valueForKey:@"version"]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"files"]){ + [array addObject:[self fileDictionaryFromJson:item]]; + } + json[@"Files"] = array; + + return json; +} - result[@"data"] = input.data; - result[@"length"] = @(input.length); - result[@"status"] = @(input.status); - result[@"type"] = @(input.type); ++(RGLApplication*)applicationFromJson:(NSDictionary*)input { + return [RGLApplication initWithJSON:[self applicationDictionaryFromJson:input]]; +} ++(NSDictionary*)generateApplication:(RGLApplication*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"applicationID"] = input.applicationID; + result[@"dataHashAlgorithm"] = input.dataHashAlgorithm; + if(input.files != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLFile* item in input.files) + [array addObject:[self generateFile:item]]; + result[@"files"] = array; + } + result[@"type"] = @(input.type); + result[@"status"] = @(input.status); + result[@"unicodeVersion"] = input.unicodeVersion; + result[@"version"] = input.version; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLSecurityObjectCertificates:(RGLSecurityObjectCertificates* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"securityObject"] = [self generateRGLCertificateData:input.securityObject]; - - return result; ++(NSDictionary*)rfidValueDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Type"] = [input valueForKey:@"type"]; + json[@"Data"] = [input valueForKey:@"data"]; + json[@"Length"] = [input valueForKey:@"length"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"Format"] = [input valueForKey:@"format"]; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLCertificateData:(RGLCertificateData* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLRFIDValue*)rfidValueFromJson:(NSDictionary*)input { + return [RGLRFIDValue initWithJSON:[self rfidValueDictionaryFromJson:input]]; +} ++(NSDictionary*)generateRFIDValue:(RGLRFIDValue*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"data"] = input.data; result[@"length"] = @(input.length); - + result[@"status"] = @(input.status); + result[@"type"] = @(input.type); + result[@"format"] = input.format; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLSecurityObject:(RGLSecurityObject* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)attributeDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Type"] = [input valueForKey:@"type"]; + json[@"Value"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"value"]]; + + return json; +} - result[@"fileReference"] = @(input.fileReference); - result[@"objectType"] = input.objectType; - result[@"version"] = @(input.version); - if(input.signerInfos != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLSignerInfo* item in input.signerInfos) - if(item != nil) - [array addObject:[self generateRGLSignerInfo:item]]; - result[@"signerInfos"] = array; - } - if(input.notifications != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; - result[@"notifications"] = array; - } ++(RGLAttribute*)attributeFromJson:(NSDictionary*)input { + return [RGLAttribute initWithJSON:[self attributeDictionaryFromJson:input]]; +} ++(NSDictionary*)generateAttribute:(RGLAttribute*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = input.type; + result[@"value"] = [self generateRFIDValue:input.value]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLSignerInfo:(RGLSignerInfo* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"dataToHash"] = input.dataToHash; - result[@"digestAlgorithm"] = input.digestAlgorithm; - result[@"paStatus"] = @(input.paStatus); - result[@"signatureAlgorithm"] = input.signatureAlgorithm; - result[@"version"] = @(input.version); - result[@"issuer"] = [self generateRGLAuthority:input.issuer]; - result[@"serialNumber"] = [self generateRGLRFIDValue:input.serialNumber]; - result[@"signature"] = [self generateRGLRFIDValue:input.signature]; - if(input.signedAttributes != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLExtension* item in input.signedAttributes) - if(item != nil) - [array addObject:[self generateRGLExtension:item]]; - result[@"signedAttributes"] = array; - } - result[@"subjectKeyIdentifier"] = [self generateRGLRFIDValue:input.subjectKeyIdentifier]; - if(input.certificateChain != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLCertificateChain* item in input.certificateChain) - if(item != nil) - [array addObject:[self generateRGLCertificateChain:item]]; - result[@"certificateChain"] = array; - } - if(input.notifications != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; - result[@"notifications"] = array; ++(NSDictionary*)authorityDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"FriendlyName"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"friendlyName"]]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"attributes"]){ + [array addObject:[self attributeDictionaryFromJson:item]]; } - - return result; + json[@"Attributes"] = array; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLAuthority:(RGLAuthority* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLAuthority*)authorityFromJson:(NSDictionary*)input { + return [RGLAuthority initWithJSON:[self authorityDictionaryFromJson:input]]; +} ++(NSDictionary*)generateAuthority:(RGLAuthority*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + if(input.attributes != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLAttribute* item in input.attributes) - if(item != nil) - [array addObject:[self generateRGLAttribute:item]]; + [array addObject:[self generateAttribute:item]]; result[@"attributes"] = array; } result[@"data"] = input.data; - result[@"friendlyName"] = [self generateRGLRFIDValue:input.friendlyName]; - + result[@"friendlyName"] = [self generateRFIDValue:input.friendlyName]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLRFIDValue:(RGLRFIDValue* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"data"] = input.data; - result[@"length"] = @(input.length); - result[@"status"] = @(input.status); - result[@"type"] = @(input.type); - result[@"format"] = input.format; - - return result; ++(NSDictionary*)extensionDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"Type"] = [input valueForKey:@"type"]; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLAttribute:(RGLAttribute* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLExtension*)extensionFromJson:(NSDictionary*)input { + return [RGLExtension initWithJSON:[self extensionDictionaryFromJson:input]]; +} ++(NSDictionary*)generateExtension:(RGLExtension*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = input.data; result[@"type"] = input.type; - result[@"value"] = [self generateRGLRFIDValue:input.value]; - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLExtension:(RGLExtension* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)validityDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"NotAfter"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"notAfter"]]; + json[@"NotBefore"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"notBefore"]]; + + return json; +} - result[@"data"] = input.data; - result[@"type"] = input.type; ++(RGLValidity*)validityFromJson:(NSDictionary*)input { + return [RGLValidity initWithJSON:[self validityDictionaryFromJson:input]]; +} ++(NSDictionary*)generateValidity:(RGLValidity*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"notAfter"] = [self generateRFIDValue:input.notAfter]; + result[@"notBefore"] = [self generateRFIDValue:input.notBefore]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLCertificateChain:(RGLCertificateChain* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)certificateChainDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Version"] = [input valueForKey:@"version"]; + json[@"Type"] = [input valueForKey:@"type"]; + json[@"SubjectPKAlgorithm"] = [input valueForKey:@"subjectPKAlgorithm"]; + json[@"SignatureAlgorithm"] = [input valueForKey:@"signatureAlgorithm"]; + json[@"SerialNumber"] = [input valueForKey:@"serialNumber"]; + json[@"PA_Status"] = [input valueForKey:@"paStatus"]; + json[@"Origin"] = [input valueForKey:@"origin"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + json[@"Validity"] = [self validityDictionaryFromJson: [input valueForKey:@"validity"]]; + json[@"Subject"] = [self authorityDictionaryFromJson: [input valueForKey:@"subject"]]; + json[@"Issuer"] = [self authorityDictionaryFromJson: [input valueForKey:@"issuer"]]; + json[@"FileName"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"fileName"]]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"extensions"]){ + [array addObject:[self extensionDictionaryFromJson:item]]; + } + json[@"Extensions"] = array; + + return json; +} + ++(RGLCertificateChain*)certificateChainFromJson:(NSDictionary*)input { + return [RGLCertificateChain initWithJSON:[self certificateChainDictionaryFromJson:input]]; +} ++(NSDictionary*)generateCertificateChain:(RGLCertificateChain*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + if(input.extensions != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLExtension* item in input.extensions) - if(item != nil) - [array addObject:[self generateRGLExtension:item]]; + [array addObject:[self generateExtension:item]]; result[@"extensions"] = array; } - result[@"fileName"] = [self generateRGLRFIDValue:input.fileName]; - result[@"issuer"] = [self generateRGLAuthority:input.issuer]; + result[@"fileName"] = [self generateRFIDValue:input.fileName]; + result[@"issuer"] = [self generateAuthority:input.issuer]; if(input.notifications != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"notifications"] = array; } result[@"origin"] = @(input.origin); result[@"paStatus"] = @(input.paStatus); result[@"serialNumber"] = input.serialNumber; result[@"signatureAlgorithm"] = input.signatureAlgorithm; - result[@"subject"] = [self generateRGLAuthority:input.subject]; + result[@"subject"] = [self generateAuthority:input.subject]; result[@"subjectPKAlgorithm"] = input.subjectPKAlgorithm; result[@"type"] = @(input.type); - result[@"validity"] = [self generateRGLValidity:input.validity]; + result[@"validity"] = [self generateValidity:input.validity]; result[@"version"] = @(input.version); - - return result; -} - -+(NSMutableDictionary* _Nonnull)generateRGLValidity:(RGLValidity* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"notAfter"] = [self generateRGLRFIDValue:input.notAfter]; - result[@"notBefore"] = [self generateRGLRFIDValue:input.notBefore]; - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLPAResourcesIssuer:(RGLPAResourcesIssuer* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"data"] = [NSKeyedUnarchiver unarchiveObjectWithData:input.data]; - result[@"friendlyName"] = input.friendlyName; - if(input.attributes != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(RGLPAAttribute* item in input.attributes) - if(item != nil) - [array addObject:[self generateRGLPAAttribute:item]]; - result[@"attributes"] = array; ++(NSDictionary*)signerInfoDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"DataToHash"] = [input valueForKey:@"dataToHash"]; + json[@"DigestAlgorithm"] = [input valueForKey:@"digestAlgorithm"]; + json[@"PA_Status"] = [input valueForKey:@"paStatus"]; + json[@"SignatureAlgorithm"] = [input valueForKey:@"signatureAlgorithm"]; + json[@"Version"] = [input valueForKey:@"version"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + json[@"Issuer"] = [self authorityDictionaryFromJson: [input valueForKey:@"issuer"]]; + json[@"SerialNumber"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"serialNumber"]]; + json[@"Signature"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"signature"]]; + json[@"SubjectKeyIdentifier"] = [self rfidValueDictionaryFromJson: [input valueForKey:@"subjectKeyIdentifier"]]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"certificateChain"]){ + [array addObject:[self certificateChainDictionaryFromJson:item]]; } - - return result; -} - -+(NSMutableDictionary* _Nonnull)generateRGLPAAttribute:(RGLPAAttribute* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"value"] = input.value; - result[@"type"] = input.type; - - return result; -} - -+(NSMutableDictionary* _Nonnull)generateRGLTAChallenge:(RGLTAChallenge* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"data"] = [NSKeyedUnarchiver unarchiveObjectWithData:input.data]; - result[@"auxPCD"] = input.auxPCD; - result[@"challengePICC"] = input.challengePICC; - result[@"hashPK"] = input.hashPK; - result[@"idPICC"] = input.idPICC; - - return result; -} - -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderResultsStatus:(RGLDocumentReaderResultsStatus* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"overallStatus"] = @(input.overallStatus); - result[@"optical"] = @(input.optical); - result[@"detailsOptical"] = [self generateRGLOpticalStatus:input.detailsOptical]; - result[@"rfid"] = @(input.rfid); - result[@"detailsRFID"] = [self generateRGLRFIDSessionDataStatus:input.detailsRFID]; - result[@"portrait"] = @(input.portrait); - result[@"stopList"] = @(input.stopList); - - return result; + json[@"CertificateChain"] = array; + NSMutableArray* array2 = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"signedAttributes"]){ + [array2 addObject:[self extensionDictionaryFromJson:item]]; + } + json[@"SignedAttributes"] = array2; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLOpticalStatus:(RGLOpticalStatus* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"overallStatus"] = @(input.overallStatus); - result[@"mrz"] = @(input.mrz); - result[@"text"] = @(input.text); - result[@"docType"] = @(input.docType); - result[@"security"] = @(input.security); - result[@"imageQA"] = @(input.imageQA); - result[@"expiry"] = @(input.expiry); - result[@"vds"] = @(input.vds); - result[@"pagesCount"] = @(input.pagesCount); - - return result; ++(RGLSignerInfo*)signerInfoFromJson:(NSDictionary*)input { + return [RGLSignerInfo initWithJSON:[self signerInfoDictionaryFromJson:input]]; } -+(NSMutableDictionary* _Nonnull)generateRGLVDSNCData:(RGLVDSNCData* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"type"] = input.type; - result[@"version"] = @(input.version); - result[@"issuingCountry"] = input.issuingCountry; - result[@"message"] = [self generateNSDictionary:input.message]; ++(NSDictionary*)generateSignerInfo:(RGLSignerInfo*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"dataToHash"] = input.dataToHash; + result[@"digestAlgorithm"] = input.digestAlgorithm; + result[@"paStatus"] = @(input.paStatus); result[@"signatureAlgorithm"] = input.signatureAlgorithm; - result[@"signature"] = [self generateRGLBytesData:input.signature]; - result[@"certificate"] = [self generateRGLBytesData:input.certificate]; + result[@"version"] = @(input.version); + result[@"issuer"] = [self generateAuthority:input.issuer]; + result[@"serialNumber"] = [self generateRFIDValue:input.serialNumber]; + result[@"signature"] = [self generateRFIDValue:input.signature]; + if(input.signedAttributes != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLExtension* item in input.signedAttributes) + [array addObject:[self generateExtension:item]]; + result[@"signedAttributes"] = array; + } + result[@"subjectKeyIdentifier"] = [self generateRFIDValue:input.subjectKeyIdentifier]; if(input.certificateChain != nil){ NSMutableArray *array = [NSMutableArray new]; for(RGLCertificateChain* item in input.certificateChain) - if(item != nil) - [array addObject:[self generateRGLCertificateChain:item]]; + [array addObject:[self generateCertificateChain:item]]; result[@"certificateChain"] = array; } if(input.notifications != nil){ NSMutableArray *array = [NSMutableArray new]; for(NSNumber* item in input.notifications) - if(item != nil) - [array addObject:item]; + [array addObject:item]; result[@"notifications"] = array; } - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLBytesData:(RGLBytesData* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"data"] = input.data; - result[@"length"] = @(input.length); - result[@"status"] = @(input.status); - result[@"type"] = @(input.type); - - return result; ++(NSDictionary*)securityObjectDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"FileReference"] = [input valueForKey:@"fileReference"]; + json[@"ObjectType"] = [input valueForKey:@"objectType"]; + json[@"Version"] = [input valueForKey:@"version"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"signerInfos"]){ + [array addObject:[self signerInfoDictionaryFromJson:item]]; + } + json[@"SignerInfos"] = array; + + return json; } -+(NSMutableDictionary* _Nonnull)generateRGLUVFiberElement:(RGLUVFiberElement* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLSecurityObject*)securityObjectFromJson:(NSDictionary*)input { + return [RGLSecurityObject initWithJSON:[self securityObjectDictionaryFromJson:input]]; +} - if(input.rectArray != nil){ ++(NSDictionary*)generateSecurityObject:(RGLSecurityObject*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"fileReference"] = @(input.fileReference); + result[@"objectType"] = input.objectType; + result[@"version"] = @(input.version); + if(input.signerInfos != nil){ NSMutableArray *array = [NSMutableArray new]; - for(RGLElementRect* item in input.rectArray) - if(item != nil) - [array addObject:[self generateRGLElementRect:item]]; - result[@"rectArray"] = array; + for(RGLSignerInfo* item in input.signerInfos) + [array addObject:[self generateSignerInfo:item]]; + result[@"signerInfos"] = array; } - result[@"rectCount"] = @(input.rectCount); - result[@"expectedCount"] = @(input.expectedCount); - if(input.width != nil){ + if(input.notifications != nil){ NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.width) - if(item != nil) - [array addObject:item]; - result[@"width"] = array; + for(NSNumber* item in input.notifications) + [array addObject:item]; + result[@"notifications"] = array; } - if(input.length != nil){ - NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.length) - if(item != nil) - [array addObject:item]; - result[@"length"] = array; + + return result; +} + ++(NSDictionary*)cardPropertiesDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"ATQ_A"] = [input valueForKey:@"aTQA"]; + json[@"ATQ_B"] = [input valueForKey:@"aTQB"]; + json[@"ATR"] = [input valueForKey:@"aTR"]; + json[@"Baudrate1"] = [input valueForKey:@"baudrate1"]; + json[@"Baudrate2"] = [input valueForKey:@"baudrate2"]; + json[@"BitRateR"] = [input valueForKey:@"bitRateR"]; + json[@"BitRateS"] = [input valueForKey:@"bitRateS"]; + json[@"ChipType_A"] = [input valueForKey:@"chipTypeA"]; + json[@"MifareMemory"] = [input valueForKey:@"mifareMemory"]; + json[@"RFID_Type"] = [input valueForKey:@"rfidType"]; + json[@"SAK"] = [input valueForKey:@"sAK"]; + json[@"Support_4"] = [input valueForKey:@"support4"]; + json[@"Support_Mifare"] = [input valueForKey:@"supportMifare"]; + json[@"UID"] = [input valueForKey:@"uID"]; + + return json; +} + ++(RGLCardProperties*)cardPropertiesFromJson:(NSDictionary*)input { + return [RGLCardProperties initWithJSON:[self cardPropertiesDictionaryFromJson:input]]; +} + ++(NSDictionary*)generateCardProperties:(RGLCardProperties*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"aTQA"] = @(input.aTQA); + result[@"aTQB"] = input.aTQB; + result[@"aTR"] = input.aTR; + result[@"baudrate1"] = input.baudrate1; + result[@"baudrate2"] = input.baudrate2; + result[@"bitRateR"] = @(input.bitRateR); + result[@"bitRateS"] = @(input.bitRateS); + result[@"chipTypeA"] = @(input.chipTypeA); + result[@"mifareMemory"] = @(input.mifareMemory); + result[@"rfidType"] = @(input.rfidType); + result[@"sAK"] = @(input.sAK); + result[@"support4"] = @(input.support4); + result[@"supportMifare"] = @(input.supportMifare); + result[@"uID"] = input.uID; + + return result; +} + ++(NSDictionary*)rfidSessionDataDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"ExtLeSupport"] = [input valueForKey:@"extLeSupport"]; + json[@"ProcessTime"] = [input valueForKey:@"processTime"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"TotalBytesReceived"] = [input valueForKey:@"totalBytesReceived"]; + json[@"TotalBytesSent"] = [input valueForKey:@"totalBytesSent"]; + json[@"DataGroups"] = [input valueForKey:@"dataGroups"]; + json[@"CardProperties"] = [self cardPropertiesDictionaryFromJson: [input valueForKey:@"cardProperties"]]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"accessControls"]){ + [array addObject:[self accessControlProcedureTypeDictionaryFromJson:item]]; + } + json[@"AccessControls"] = array; + NSMutableArray* array2 = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"applications"]){ + [array2 addObject:[self applicationDictionaryFromJson:item]]; + } + json[@"Applications"] = array2; + NSMutableArray* array3 = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"securityObjects"]){ + [array3 addObject:[self securityObjectDictionaryFromJson:item]]; + } + json[@"SecurityObjects"] = array3; + + return json; +} + ++(RGLRFIDSessionData*)rfidSessionDataFromJson:(NSDictionary*)input { + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"dataFields"]){ + [array addObject:[self dataFieldFromJson:item]]; } - if(input.area != nil){ + return [RGLRFIDSessionData + initWithJSON:[self rfidSessionDataDictionaryFromJson:input] + dataFields:array]; +} + ++(NSDictionary*)generateRFIDSessionData:(RGLRFIDSessionData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.accessControls != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLAccessControlProcedureType* item in input.accessControls) + [array addObject:[self generateAccessControlProcedureType:item]]; + result[@"accessControls"] = array; + } + if(input.applications != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLApplication* item in input.applications) + [array addObject:[self generateApplication:item]]; + result[@"applications"] = array; + } + if(input.securityObjects != nil){ NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.area) + for(RGLSecurityObject* item in input.securityObjects) + [array addObject:[self generateSecurityObject:item]]; + result[@"securityObjects"] = array; + } + result[@"cardProperties"] = [self generateCardProperties:input.cardProperties]; + result[@"totalBytesReceived"] = @(input.totalBytesReceived); + result[@"totalBytesSent"] = @(input.totalBytesSent); + result[@"status"] = @(input.status); + result[@"extLeSupport"] = @(input.extLeSupport); + result[@"processTime"] = @(input.processTime); + if(input.dataGroups != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(NSNumber* item in input.dataGroups) if(item != nil) [array addObject:item]; - result[@"area"] = array; + result[@"dataGroups"] = array; } - if(input.colorValues != nil){ + if(input.dataFields != nil){ NSMutableArray *array = [NSMutableArray new]; - for(NSNumber* item in input.colorValues) + for(RGLDataField* item in input.dataFields) if(item != nil) - [array addObject:item]; - result[@"colorValues"] = array; + [array addObject:[self generateDataField:item]]; + result[@"dataFields"] = array; + } + + return result; +} + ++(NSDictionary*)dataFieldDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"FieldType"] = [input valueForKey:@"fieldType"]; + + return json; +} + ++(RGLDataField*)dataFieldFromJson:(NSDictionary*)input { + return [RGLDataField initWithJSON:[self dataFieldDictionaryFromJson:input]]; +} + ++(NSDictionary*)generateDataField:(RGLDataField*)input { + NSMutableDictionary *result = [NSMutableDictionary new]; + if(input == nil) return nil; + + result[@"data"] = input.data; + result[@"fieldType"] = @(input.fieldType); + + return result; +} + ++(RGLAuthenticityCheck*)authenticityCheckFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableArray *array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"elements"]) + [array addObject:[self authenticityElementFromJson:item]]; + RGLAuthenticityCheck* result = [[RGLAuthenticityCheck alloc] + initWithAuthenticity:[[input valueForKey:@"type"] integerValue] + elements:array + pageIndex:[[input valueForKey:@"pageIndex"] integerValue]]; + if (input[@"status"]) [result setValue:input[@"status"] forKey:@"status"]; + return result;; +} + ++(NSDictionary*)generateAuthenticityCheck:(RGLAuthenticityCheck*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = @(input.type); + result[@"typeName"] = input.typeName; + result[@"status"] = @(input.status); + if(input.elements != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLAuthenticityElement* item in input.elements) + [array addObject:[self generateAuthenticityElement:item]]; + result[@"elements"] = array; + } + result[@"pageIndex"] = @(input.pageIndex); + + return result; +} + ++(NSDictionary*)pdf417InfoDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"bcErrorLevel"] = [input valueForKey:@"errorLevel"]; + json[@"bcColumn"] = [input valueForKey:@"columns"]; + json[@"bcRow"] = [input valueForKey:@"rows"]; + + return json; +} + ++(RGLPDF417Info*)pdf417InfoFromJson:(NSDictionary*)input { + return [RGLPDF417Info initWithJSON:[self pdf417InfoDictionaryFromJson:input]]; +} + ++(NSDictionary*)generatePDF417Info:(RGLPDF417Info*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"errorLevel"] = @(input.errorLevel); + result[@"columns"] = @(input.columns); + result[@"rows"] = @(input.rows); + + return result; +} + ++(RGLDocumentReaderBarcodeResult*)documentReaderBarcodeResultFromJson:(NSDictionary*)input { + NSMutableArray *array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"fields"]) + [array addObject:[self documentReaderBarcodeFieldFromJson:item]]; + return [[RGLDocumentReaderBarcodeResult alloc] + initWithFields:array]; +} + ++(NSDictionary*)generateDocumentReaderBarcodeResult:(RGLDocumentReaderBarcodeResult*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.fields != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocumentReaderBarcodeField* item in input.fields) + [array addObject:[self generateDocumentReaderBarcodeField:item]]; + result[@"fields"] = array; + } + + return result; +} + ++(RGLDocumentReaderBarcodeField*)documentReaderBarcodeFieldFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"bcType_DECODE"] = [input valueForKey:@"barcodeType"]; + json[@"bcCodeResult"] = [input valueForKey:@"status"]; + json[@"bcPDF417INFO"] = [self pdf417InfoDictionaryFromJson:[input valueForKey:@"pdf417Info"]]; + NSMutableArray* array = [NSMutableArray new]; + NSMutableDictionary* dict = [NSMutableDictionary new]; + dict[@"mData"] = [input valueForKey:@"data"]; + [array addObject:dict]; + json[@"bcDataModule"] = array; + json[@"page_idx"] = [input valueForKey:@"pageIndex"]; + + return [RGLDocumentReaderBarcodeField initWithJSON:json]; +} + ++(NSDictionary*)generateDocumentReaderBarcodeField:(RGLDocumentReaderBarcodeField*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"barcodeType"] = @(input.barcodeType); + result[@"status"] = @(input.status); + result[@"pdf417Info"] = [self generatePDF417Info:input.pdf417Info]; + result[@"data"] = [self base64Encode:input.data]; + result[@"pageIndex"] = @(input.pageIndex); + + return result; +} + ++(RGLDocumentReaderAuthenticityResult*)documentReaderAuthenticityResultFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableArray *array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"checks"]) + [array addObject:[self authenticityCheckFromJson:item]]; + RGLDocumentReaderAuthenticityResult* result = [[RGLDocumentReaderAuthenticityResult alloc] + initWithAuthenticityChecks:array]; + if (input[@"status"]) [result setValue:input[@"status"] forKey:@"_security"]; + return result; +} + ++(NSDictionary*)generateDocumentReaderAuthenticityResult:(RGLDocumentReaderAuthenticityResult*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"status"] = @(input.status); + if(input.checks != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLAuthenticityCheck* item in input.checks) + [array addObject:[self generateAuthenticityCheck:item]]; + result[@"checks"] = array; } + + return result; +} + ++(RGLAuthenticityElement*)authenticityElementFromJson:(NSDictionary*)input { + if(input == nil) return nil; + return [[RGLAuthenticityElement alloc] + initWithStatus:[[input valueForKey:@"status"] integerValue] + elementType:[[input valueForKey:@"elementType"] integerValue] + elementDiagnose:[[input valueForKey:@"elementDiagnose"] integerValue]]; +} + ++(NSDictionary*)generateAuthenticityElement:(RGLAuthenticityElement*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"status"] = @(input.status); result[@"elementType"] = @(input.elementType); result[@"elementTypeName"] = input.elementTypeName; result[@"elementDiagnose"] = @(input.elementDiagnose); result[@"elementDiagnoseName"] = input.elementDiagnoseName; + + return result; +} + ++(NSDictionary*)paResourcesIssuerDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"Data"] = @{@"#text": [input valueForKey:@"data"]}; + json[@"FriendlyName"] = [input valueForKey:@"friendlyName"]; + NSMutableArray *array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"attributes"]) + [array addObject:[self paAttributeDictionaryFromJson:item]]; + json[@"Attributes"] = @{@"RFID_Attribute_Name": array}; + + return json; +} + ++(RGLPAResourcesIssuer*)paResourcesIssuerFromJson:(NSDictionary*)input { + return [RGLPAResourcesIssuer initWithJSON:[self paResourcesIssuerDictionaryFromJson: input]]; +} ++(NSDictionary*)generatePAResourcesIssuer:(RGLPAResourcesIssuer*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = [self base64Encode:input.data]; + result[@"friendlyName"] = input.friendlyName; + if(input.attributes != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLPAAttribute* item in input.attributes) + [array addObject:[self generatePAAttribute:item]]; + result[@"attributes"] = array; + } + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocReaderDocumentsDatabase:(RGLDocReaderDocumentsDatabase* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)paAttributeDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"Value"] = [input valueForKey:@"value"]; + json[@"Type"] = [input valueForKey:@"type"]; + + return json; +} + ++(RGLPAAttribute*)paAttributeFromJson:(NSDictionary*)input { + return [RGLPAAttribute initWithJSON:[self paAttributeDictionaryFromJson: input]]; +} + ++(NSDictionary*)generatePAAttribute:(RGLPAAttribute*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"value"] = input.value; + result[@"type"] = input.type; + + return result; +} + ++(RGLTAChallenge*)taChallengeFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"#text"] = [input valueForKey:@"data"]; + json[@"@auxPCD"] = [input valueForKey:@"auxPCD"]; + json[@"@challengePICC"] = [input valueForKey: @"challengePICC"]; + json[@"@hashPK"] = [input valueForKey:@"hashPK"]; + json[@"@idPICC"] = [input valueForKey:@"idPICC"]; + + return [RGLTAChallenge initWithJSON:json]; +} + ++(NSDictionary*)generateTAChallenge:(RGLTAChallenge*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = [self base64Encode:input.data]; + result[@"auxPCD"] = input.auxPCD; + result[@"challengePICC"] = input.challengePICC; + result[@"hashPK"] = input.hashPK; + result[@"idPICC"] = input.idPICC; + + return result; +} + ++(NSDictionary*)documentReaderResultsStatusDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"detailsRFID"] = [self rfidSessionDataStatusDictionaryFromJson: [input valueForKey:@"detailsRFID"] ]; + + return json; +} + ++(RGLDocumentReaderResultsStatus*)documentReaderResultsStatusFromJson:(NSDictionary*)input { + return [RGLDocumentReaderResultsStatus performSelector:NSSelectorFromString(@"resultsStatusWithJSON:") withObject:[self documentReaderResultsStatusDictionaryFromJson: input]]; +} + ++(NSDictionary*)generateDocumentReaderResultsStatus:(RGLDocumentReaderResultsStatus*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"overallStatus"] = @(input.overallStatus); + result[@"optical"] = @(input.optical); + result[@"detailsOptical"] = [self generateOpticalStatus:input.detailsOptical]; + result[@"rfid"] = @(input.rfid); + result[@"detailsRFID"] = [self generateRFIDSessionDataStatus:input.detailsRFID]; + result[@"portrait"] = @(input.portrait); + result[@"stopList"] = @(input.stopList); + result[@"mDL"] = @(input.mDL); + result[@"age"] = @(input.age); + result[@"captureProcessIntegrity"] = @(input.captureProcessIntegrity); + result[@"detailsAge"] = [self generateDetailsAge:input.detailsAge]; + + return result; +} + ++(RGLOpticalStatus*)opticalStatusFromJson:(NSDictionary*)input { + return [RGLOpticalStatus performSelector:NSSelectorFromString(@"opticalStatusWithJSON:") withObject:input]; +} + ++(NSDictionary*)generateOpticalStatus:(RGLOpticalStatus*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"overallStatus"] = @(input.overallStatus); + result[@"mrz"] = @(input.mrz); + result[@"text"] = @(input.text); + result[@"docType"] = @(input.docType); + result[@"security"] = @(input.security); + result[@"imageQA"] = @(input.imageQA); + result[@"expiry"] = @(input.expiry); + result[@"vds"] = @(input.vds); + result[@"pagesCount"] = @(input.pagesCount); + + return result; +} + ++(NSDictionary*)rfidSessionDataStatusDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"overallStatus"] = [input valueForKey:@"overallStatus"]; + json[@"AA"] = [input valueForKey:@"aa"]; + json[@"BAC"] = [input valueForKey:@"bac"]; + json[@"CA"] = [input valueForKey:@"ca"]; + json[@"PA"] = [input valueForKey:@"pa"]; + json[@"PACE"] = [input valueForKey:@"pace"]; + json[@"TA"] = [input valueForKey:@"ta"]; + + return json; +} + ++(RGLRFIDSessionDataStatus*)rfidSessionDataStatusFromJson:(NSDictionary*)input { + return [RGLRFIDSessionDataStatus performSelector:NSSelectorFromString(@"rfidStatusWithJSON:") withObject:[self rfidSessionDataStatusDictionaryFromJson: input]]; +} + ++(NSDictionary*)generateRFIDSessionDataStatus:(RGLRFIDSessionDataStatus*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"aa"] = @(input.AA); + result[@"bac"] = @(input.BAC); + result[@"ca"] = @(input.CA); + result[@"pa"] = @(input.PA); + result[@"pace"] = @(input.PACE); + result[@"ta"] = @(input.TA); + result[@"overallStatus"] = @(input.overallStatus); + + return result; +} + ++(RGLDetailsAge*)detailsAgeFromJson:(NSDictionary*)input { + return [RGLDetailsAge performSelector:NSSelectorFromString(@"detailsAgeWithJSON:") withObject:input]; +} + ++(NSDictionary*)generateDetailsAge:(RGLDetailsAge*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"threshold"] = input.threshold; + result[@"overThreshold"] = @(input.overThreshold); + result[@"over18"] = @(input.over18); + result[@"over21"] = @(input.over21); + result[@"over25"] = @(input.over25); + result[@"over65"] = @(input.over65); + + return result; +} + ++(NSDictionary*)vdsncDataDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Type"] = [input valueForKey:@"type"]; + json[@"Version"] = [input valueForKey:@"version"]; + json[@"IssuingCountry"] = [input valueForKey:@"issuingCountry"]; + json[@"Message"] = [input valueForKey:@"message"]; + json[@"SignatureAlg"] = [input valueForKey:@"signatureAlgorithm"]; + json[@"Notifications"] = [input valueForKey:@"notifications"]; + json[@"Signature"] = [self bytesDataDictionaryFromJson: [input valueForKey:@"signature"]]; + json[@"Certificate"] = [self bytesDataDictionaryFromJson: [input valueForKey:@"certificate"]]; + NSMutableArray* array = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"certificateChain"]){ + [array addObject:[self certificateChainDictionaryFromJson:item]]; + } + json[@"CertificateChain"] = array; + + return json; +} + ++(RGLVDSNCData*)vdsncDataFromJson:(NSDictionary*)input { + return [RGLVDSNCData performSelector:NSSelectorFromString(@"dataWithJSON:") withObject:[self vdsncDataDictionaryFromJson: input]]; +} + ++(NSDictionary*)generateVDSNCData:(RGLVDSNCData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = input.type; + result[@"version"] = @(input.version); + result[@"issuingCountry"] = input.issuingCountry; + result[@"message"] = input.message; + result[@"signatureAlgorithm"] = input.signatureAlgorithm; + result[@"signature"] = [self generateBytesData:input.signature]; + result[@"certificate"] = [self generateBytesData:input.certificate]; + if(input.certificateChain != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLCertificateChain* item in input.certificateChain) + [array addObject:[self generateCertificateChain:item]]; + result[@"certificateChain"] = array; + } + if(input.notifications != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(NSNumber* item in input.notifications) + [array addObject:item]; + result[@"notifications"] = array; + } + + return result; +} + ++(NSDictionary*)bytesDataDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"Data"] = [input valueForKey:@"data"]; + json[@"Length"] = [input valueForKey:@"length"]; + json[@"Status"] = [input valueForKey:@"status"]; + json[@"Type"] = [input valueForKey:@"type"]; + + return json; +} + ++(RGLBytesData*)bytesDataFromJson:(NSDictionary*)input { + return [RGLBytesData performSelector:NSSelectorFromString(@"bytesDataWithJSON:") withObject:[self bytesDataDictionaryFromJson: input]]; +} + ++(NSDictionary*)generateBytesData:(RGLBytesData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"data"] = input.data; + result[@"length"] = @(input.length); + result[@"status"] = @(input.status); + result[@"type"] = @(input.type); + + return result; +} ++(NSString*)generateLicense:(RGLLicense*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.expiryDate != nil) { + NSDateFormatter *formatter = [NSDateFormatter new]; + [formatter setFormatterBehavior:NSDateFormatterBehaviorDefault]; + [formatter setDateStyle:NSDateFormatterShortStyle]; + [formatter setTimeStyle:NSDateFormatterNoStyle]; + result[@"expiryDate"] = [formatter stringFromDate:input.expiryDate]; + } else result[@"expiryDate"] = nil; + + result[@"countryFilter"] = input.countryFilter; + result[@"isRfidAvailable"] = input.rfidAvailable ? @YES : @NO; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(NSString*)generateDocReaderVersion:(RGLDocReaderVersion*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"api"] = input.api; + result[@"core"] = input.core; + result[@"coreMode"] = input.coreMode; + result[@"database"] = [self generateDocReaderDocumentsDatabase:input.database]; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(RGLDocReaderDocumentsDatabase*)docReaderDocumentsDatabaseFromJson:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableDictionary* json = [NSMutableDictionary new]; + + json[@"id"] = [input valueForKey:@"databaseID"]; + json[@"version"] = [input valueForKey:@"version"]; + json[@"export_date"] = [input valueForKey:@"date"]; + json[@"description"] = [input valueForKey:@"databaseDescription"]; + json[@"countriesNumber"] = [input valueForKey:@"countriesNumber"]; + json[@"documentsNumber"] = [input valueForKey:@"documentsNumber"]; + json[@"size"] = [input valueForKey:@"size"]; + + return [RGLDocReaderDocumentsDatabase initWithJSON:json]; +} + ++(NSDictionary*)generateDocReaderDocumentsDatabase:(RGLDocReaderDocumentsDatabase*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"databaseID"] = input.databaseID; result[@"version"] = input.version; result[@"date"] = input.date; @@ -1190,75 +2206,638 @@ +(NSMutableDictionary* _Nonnull)generateRGLDocReaderDocumentsDatabase:(RGLDocRea result[@"countriesNumber"] = @(input.countriesNumber); result[@"documentsNumber"] = @(input.documentsNumber); result[@"size"] = input.size; - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderComparison:(RGLDocumentReaderComparison* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)documentReaderComparisonDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + json[@"sourceLeft"] = @"sourceTypeLeft"; + json[@"sourceRight"] = @"sourceTypeRight"; + return json; +} ++(RGLDocumentReaderComparison*)documentReaderComparisonFromJson:(NSDictionary*)input { + return [RGLDocumentReaderComparison initWithJSON:[self documentReaderComparisonDictionaryFromJson: input] sourceList:[self documentReaderComparisonDictionaryFromJson: input]]; +} + ++(NSDictionary*)generateDocumentReaderComparison:(RGLDocumentReaderComparison*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"sourceTypeLeft"] = @(input.sourceTypeLeft); result[@"sourceTypeRight"] = @(input.sourceTypeRight); result[@"status"] = @(input.status); + + return result; +} + ++(RGLDocumentReaderRfidOrigin*)documentReaderRfidOriginFromJson:(NSDictionary*)input { + return [RGLDocumentReaderRfidOrigin initWithJSON:input]; +} ++(NSDictionary*)generateDocumentReaderRfidOrigin:(RGLDocumentReaderRfidOrigin*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"dg"] = @(input.dg); + result[@"dgTag"] = @(input.dgTag); + result[@"entryView"] = @(input.entryView); + result[@"tagEntry"] = @(input.tagEntry); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderValidity:(RGLDocumentReaderValidity* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)documentReaderTextSourceDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + json[@"containerType"] = [input valueForKey:@"sourceType"]; + return json; +} - result[@"sourceType"] = @(input.sourceType); - result[@"status"] = @(input.status); ++(RGLDocumentReaderTextSource*)documentReaderTextSourceFromJson:(NSDictionary*)input { + return [RGLDocumentReaderTextSource initWithJSON:[self documentReaderTextSourceDictionaryFromJson: input]]; +} ++(NSDictionary*)generateDocumentReaderTextSource:(RGLDocumentReaderTextSource*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"sourceType"] = @(input.sourceType); + result[@"source"] = input.source; + result[@"validityStatus"] = @(input.validityStatus); + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderSymbol:(RGLDocumentReaderSymbol* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLDocumentReaderSymbol*)documentReaderSymbolFromJson:(NSDictionary*)input { + return [RGLDocumentReaderSymbol initWithJSON:input]; +} ++(NSDictionary*)generateDocumentReaderSymbol:(RGLDocumentReaderSymbol*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"code"] = @(input.code); - result[@"rect"] = [self generateCGRect:input.rect]; + result[@"rect"] = [self generateRect:input.rect]; result[@"probability"] = @(input.probability); - + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderTextSource:(RGLDocumentReaderTextSource* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(NSDictionary*)documentReaderValidityDictionaryFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + json[@"source"] = @"sourceType"; + return json; +} ++(RGLDocumentReaderValidity*)documentReaderValidityFromJson:(NSDictionary*)input { + return [RGLDocumentReaderValidity initWithJSON:[self documentReaderValidityDictionaryFromJson:input] sourceList:[self documentReaderValidityDictionaryFromJson:input]]; +} + ++(NSDictionary*)generateDocumentReaderValidity:(RGLDocumentReaderValidity*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + result[@"sourceType"] = @(input.sourceType); - result[@"source"] = input.source; - result[@"validityStatus"] = @(input.validityStatus); + result[@"status"] = @(input.status); + + return result; +} ++(RGLDocFeature*)docFeatureFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + json[@"Type"] = input[@"type"]; + json[@"Data"] = [self bytesDataDictionaryFromJson: input[@"data"]]; + return [RGLDocFeature initWithJSON: json]; +} + ++(NSDictionary*)generateDocFeature:(RGLDocFeature*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = input.type; + result[@"data"] = [self generateBytesData:input.data]; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLDocumentReaderRfidOrigin:(RGLDocumentReaderRfidOrigin* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLVDSData*)vdsDataFromJson:(NSDictionary*)input { + NSMutableArray* certificateChain = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"certificateChain"]){ + [certificateChain addObject:[self certificateChainFromJson:item]]; + } + NSMutableArray* docFeatures = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"docFeatures"]){ + [docFeatures addObject:[self docFeatureFromJson:item]]; + } + NSMutableArray* notifications = [NSMutableArray new]; + for(NSNumber* item in [input valueForKey:@"notifications"]){ + [notifications addObject:item]; + } + + RGLVDSData* result = [RGLVDSData alloc]; + SEL sel = NSSelectorFromString(@"initWithType:docType:featureRef:version:certificate:issuingCountry:docIssueDate:signature:signatureDate:signer:certificateChain:docFeatures:notifications:"); + IMP imp = [result methodForSelector:sel]; + void (*func)(id, SEL, NSInteger, NSInteger, NSInteger, NSInteger, id, id, id, id, id, id, id, id, id) = (void *)imp; + func(result, + sel, + [input[@"type"] integerValue], + [input[@"docType"] integerValue], + [input[@"featureRef"] integerValue], + [input[@"version"] integerValue], + input[@"certificate"], + input[@"issuingCountry"], + input[@"docIssueDate"], + [self bytesDataFromJson:input[@"signature"]], + input[@"signatureDate"], + input[@"signer"], + certificateChain, + docFeatures, + notifications); + return result; +} - result[@"dg"] = @(input.dg); - result[@"dgTag"] = @(input.dgTag); - result[@"entryView"] = @(input.entryView); - result[@"tagEntry"] = @(input.tagEntry); ++(NSDictionary*)generateVDSData:(RGLVDSData*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = @(input.type); + result[@"docType"] = @(input.docType); + result[@"featureRef"] = @(input.featureRef); + result[@"version"] = @(input.version); + result[@"certificate"] = input.certificate; + result[@"issuingCountry"] = input.issuingCountry; + result[@"docIssueDate"] = input.docIssueDate; + result[@"signature"] = [self generateBytesData:input.signature]; + result[@"signatureDate"] = input.signatureDate; + result[@"signer"] = input.signer; + if(input.certificateChain != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLCertificateChain* item in input.certificateChain) + [array addObject:[self generateCertificateChain:item]]; + result[@"certificateChain"] = array; + } + if(input.docFeatures != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocFeature* item in input.docFeatures) + [array addObject:[self generateDocFeature:item]]; + result[@"docFeatures"] = array; + } + if(input.notifications != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(NSNumber* item in input.notifications) + [array addObject:item]; + result[@"notifications"] = array; + } + + return result; +} + ++(RGLDeviceRetrievalMethod*)deviceRetrievalMethodFromJson:(NSDictionary*)input { + return [[RGLDeviceRetrievalMethod alloc] initWithJSON:input]; +} ++(NSDictionary*)generateDeviceRetrievalMethod:(RGLDeviceRetrievalMethod*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"type"] = @(input.type); + result[@"version"] = input.version; + result[@"cmdMaxLength"] = input.cmdMaxLength; + result[@"respMaxLength"] = input.respMaxLength; + result[@"clientModeSupport"] = input.clientModeSupport; + result[@"clientModeUUID"] = input.clientModeUUID; + result[@"serverModeSupport"] = input.serverModeSupport; + result[@"serverModeUUID"] = input.serverModeUUID; + return result; } -+(NSMutableDictionary* _Nonnull)generateRGLElementRect:(RGLElementRect* _Nullable)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; ++(RGLDeviceEngagement*)deviceEngagementFromJson:(NSDictionary*)input { + RGLDeviceEngagement* result = [RGLDeviceEngagement new]; + + + NSMutableArray* deviceRetrievalMethods = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"deviceRetrievalMethods"]){ + [deviceRetrievalMethods addObject:[self deviceRetrievalMethodFromJson: item]]; + } + result.deviceRetrievalMethods = deviceRetrievalMethods; + + return result; + +} + ++(NSDictionary*)generateDeviceEngagement:(RGLDeviceEngagement*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + NSMutableArray *array = [NSMutableArray new]; + for(RGLDeviceRetrievalMethod* item in input.deviceRetrievalMethods) + [array addObject:[self generateDeviceRetrievalMethod:item]]; + result[@"deviceRetrievalMethods"] = array; + + return result; +} + ++(RGLNameSpaceMDL*)nameSpaceMDLFromJson:(NSDictionary*)input { + RGLNameSpaceMDL* result = [[RGLNameSpaceMDL alloc] initWithName:input[@"name"]]; + + NSDictionary* map = input[@"map"]; + for (NSString* key in map) { + [result addField:key intentToRetain:[map[key] integerValue]]; + } + + return result; + +} + ++(NSDictionary*)generateNameSpaceMDL:(RGLNameSpaceMDL*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"name"] = input.name; + result[@"map"] = [input valueForKey:@"jsonDict"]; + + return result; +} + ++(RGLDocumentRequestMDL*)documentRequestMDLFromJson:(NSDictionary*)input { + NSString* docType = input[@"docType"]; + if([docType isEqual: @"org.iso.18013.5.1.mDL"]) return [self documentRequest18013MDLFromJson: input]; + RGLDocumentRequestMDL* result = [[RGLDocumentRequestMDL alloc] initWithDocType:docType]; + + NSMutableArray* nameSpaces = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"namespaces"]){ + [nameSpaces addObject:[self nameSpaceMDLFromJson: item]]; + } + [result setValue:nameSpaces forKey:@"nameSpaces"]; + + return result; + +} + ++(NSDictionary*)generateDocumentRequestMDL:(RGLDocumentRequestMDL*)input { + if(input == nil) return nil; + NSString* docType = [input valueForKey:@"docType"]; + if([docType isEqual: @"org.iso.18013.5.1.mDL"]) return [self generateDocumentRequest18013MDL: (RGLDocumentRequest18013MDL*)input]; + NSMutableDictionary* result = [NSMutableDictionary new]; + + NSMutableArray *array = [NSMutableArray new]; + for(RGLNameSpaceMDL* item in [input valueForKey:@"nameSpaces"]) + [array addObject:[self generateNameSpaceMDL:item]]; + + result[@"docType"] = docType; + result[@"namespaces"] = array; + + return result; +} + ++(RGLDocumentRequest18013MDL*)documentRequest18013MDLFromJson:(NSDictionary*)input { + if(input == nil) return nil; + RGLDocumentRequest18013MDL* result = [RGLDocumentRequest18013MDL new]; + + if ([input valueForKey:@"docType"] != nil) { + [result setValue:[input valueForKey:@"docType"] forKey:@"docType"]; + } + if ([input valueForKey:@"namespaces"] != nil) { + NSMutableArray* nameSpaces = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"namespaces"]){ + [nameSpaces addObject:[self nameSpaceMDLFromJson: item]]; + } + [result setValue:nameSpaces forKey:@"nameSpaces"]; + } + if (input[@"familyName"]) result.familyName = [input[@"familyName"] integerValue]; + if (input[@"givenName"]) result.givenName = [input[@"givenName"] integerValue]; + if (input[@"birthDate"]) result.birthDate = [input[@"birthDate"] integerValue]; + if (input[@"issueDate"]) result.issueDate = [input[@"issueDate"] integerValue]; + if (input[@"expiryDate"]) result.expiryDate = [input[@"expiryDate"] integerValue]; + if (input[@"issuingCountry"]) result.issuingCountry = [input[@"issuingCountry"] integerValue]; + if (input[@"issuingAuthority"]) result.issuingAuthority = [input[@"issuingAuthority"] integerValue]; + if (input[@"documentNumber"]) result.documentNumber = [input[@"documentNumber"] integerValue]; + if (input[@"portrait"]) result.portrait = [input[@"portrait"] integerValue]; + if (input[@"drivingPrivileges"]) result.drivingPrivileges = [input[@"drivingPrivileges"] integerValue]; + if (input[@"unDistinguishingSign"]) result.unDistinguishingSign = [input[@"unDistinguishingSign"] integerValue]; + if (input[@"administrativeNumber"]) result.administrativeNumber = [input[@"administrativeNumber"] integerValue]; + if (input[@"sex"]) result.sex = [input[@"sex"] integerValue]; + if (input[@"height"]) result.height = [input[@"height"] integerValue]; + if (input[@"weight"]) result.weight = [input[@"weight"] integerValue]; + if (input[@"eyeColour"]) result.eyeColour = [input[@"eyeColour"] integerValue]; + if (input[@"hairColour"]) result.hairColour = [input[@"hairColour"] integerValue]; + if (input[@"birthPlace"]) result.birthPlace = [input[@"birthPlace"] integerValue]; + if (input[@"residentAddress"]) result.residentAddress = [input[@"residentAddress"] integerValue]; + if (input[@"portraitCaptureDate"]) result.portraitCaptureDate = [input[@"portraitCaptureDate"] integerValue]; + if (input[@"ageInYears"]) result.ageInYears = [input[@"ageInYears"] integerValue]; + if (input[@"ageBirthYear"]) result.ageBirthYear = [input[@"ageBirthYear"] integerValue]; + if (input[@"ageOver18"]) result.ageOver18 = [input[@"ageOver18"] integerValue]; + if (input[@"issuingJurisdiction"]) result.issuingJurisdiction = [input[@"issuingJurisdiction"] integerValue]; + if (input[@"nationality"]) result.nationality = [input[@"nationality"] integerValue]; + if (input[@"residentCity"]) result.residentCity = [input[@"residentCity"] integerValue]; + if (input[@"residentState"]) result.residentState = [input[@"residentState"] integerValue]; + if (input[@"residentPostalCode"]) result.residentPostalCode = [input[@"residentPostalCode"] integerValue]; + if (input[@"residentCountry"]) result.residentCountry = [input[@"residentCountry"] integerValue]; + if (input[@"biometricTemplateFace"]) result.biometricTemplateFace = [input[@"biometricTemplateFace"] integerValue]; + if (input[@"biometricTemplateIris"]) result.biometricTemplateIris = [input[@"biometricTemplateIris"] integerValue]; + if (input[@"biometricTemplateFinger"]) result.biometricTemplateFinger = [input[@"biometricTemplateFinger"] integerValue]; + if (input[@"biometricTemplateSignatureSign"]) result.biometricTemplateSignatureSign = [input[@"biometricTemplateSignatureSign"] integerValue]; + if (input[@"familyNameNationalCharacter"]) result.familyNameNationalCharacter = [input[@"familyNameNationalCharacter"] integerValue]; + if (input[@"givenNameNationalCharacter"]) result.givenNameNationalCharacter = [input[@"givenNameNationalCharacter"] integerValue]; + if (input[@"signatureUsualMark"]) result.signatureUsualMark = [input[@"signatureUsualMark"] integerValue]; + + return result; +} + ++(NSDictionary*)generateDocumentRequest18013MDL:(RGLDocumentRequest18013MDL*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + NSMutableArray *array = [NSMutableArray new]; + for(RGLNameSpaceMDL* item in [input valueForKey:@"nameSpaces"]) + [array addObject:[self generateNameSpaceMDL:item]]; + + result[@"docType"] = [input valueForKey:@"docType"]; + result[@"namespaces"] = array; + if (input.familyName != -1) result[@"familyName"] = @(input.familyName); + if (input.givenName != -1) result[@"givenName"] = @(input.givenName); + if (input.birthDate != -1) result[@"birthDate"] = @(input.birthDate); + if (input.issueDate != -1) result[@"issueDate"] = @(input.issueDate); + if (input.expiryDate != -1) result[@"expiryDate"] = @(input.expiryDate); + if (input.issuingCountry != -1) result[@"issuingCountry"] = @(input.issuingCountry); + if (input.issuingAuthority != -1) result[@"issuingAuthority"] = @(input.issuingAuthority); + if (input.documentNumber != -1) result[@"documentNumber"] = @(input.documentNumber); + if (input.portrait != -1) result[@"portrait"] = @(input.portrait); + if (input.drivingPrivileges != -1) result[@"drivingPrivileges"] = @(input.drivingPrivileges); + if (input.unDistinguishingSign != -1) result[@"unDistinguishingSign"] = @(input.unDistinguishingSign); + if (input.administrativeNumber != -1) result[@"administrativeNumber"] = @(input.administrativeNumber); + if (input.sex != -1) result[@"sex"] = @(input.sex); + if (input.height != -1) result[@"height"] = @(input.height); + if (input.weight != -1) result[@"weight"] = @(input.weight); + if (input.eyeColour != -1) result[@"eyeColour"] = @(input.eyeColour); + if (input.hairColour != -1) result[@"hairColour"] = @(input.hairColour); + if (input.birthPlace != -1) result[@"birthPlace"] = @(input.birthPlace); + if (input.residentAddress != -1) result[@"residentAddress"] = @(input.residentAddress); + if (input.portraitCaptureDate != -1) result[@"portraitCaptureDate"] = @(input.portraitCaptureDate); + if (input.ageInYears != -1) result[@"ageInYears"] = @(input.ageInYears); + if (input.ageBirthYear != -1) result[@"ageBirthYear"] = @(input.ageBirthYear); + if (input.ageOver18 != -1) result[@"ageOver18"] = @(input.ageOver18); + if (input.issuingJurisdiction != -1) result[@"issuingJurisdiction"] = @(input.issuingJurisdiction); + if (input.nationality != -1) result[@"nationality"] = @(input.nationality); + if (input.residentCity != -1) result[@"residentCity"] = @(input.residentCity); + if (input.residentState != -1) result[@"residentState"] = @(input.residentState); + if (input.residentPostalCode != -1) result[@"residentPostalCode"] = @(input.residentPostalCode); + if (input.residentCountry != -1) result[@"residentCountry"] = @(input.residentCountry); + if (input.biometricTemplateFace != -1) result[@"biometricTemplateFace"] = @(input.biometricTemplateFace); + if (input.biometricTemplateIris != -1) result[@"biometricTemplateIris"] = @(input.biometricTemplateIris); + if (input.biometricTemplateFinger != -1) result[@"biometricTemplateFinger"] = @(input.biometricTemplateFinger); + if (input.biometricTemplateSignatureSign != -1) result[@"biometricTemplateSignatureSign"] = @(input.biometricTemplateSignatureSign); + if (input.familyNameNationalCharacter != -1) result[@"familyNameNationalCharacter"] = @(input.familyNameNationalCharacter); + if (input.givenNameNationalCharacter != -1) result[@"givenNameNationalCharacter"] = @(input.givenNameNationalCharacter); + if (input.signatureUsualMark != -1) result[@"signatureUsualMark"] = @(input.signatureUsualMark); + + return result; +} + ++(RGLDataRetrieval*)dataRetrievalFromJson:(NSDictionary*)input { + RGLDataRetrieval* result = [[RGLDataRetrieval alloc] initWithDeviceRetrieval:[input[@"deviceRetrieval"] integerValue]]; + + if (input[@"docRequestPreset"]) + [result setDocRequestPreset:[input[@"docRequestPreset"] integerValue] intentToRetain:[input[@"intentToRetain"] integerValue]]; + + NSMutableArray* requests = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"requests"]){ + [requests addObject:[self documentRequestMDLFromJson: item]]; + } + result.requests = requests; + + return result; +} + ++(NSDictionary*)generateDataRetrieval:(RGLDataRetrieval*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"deviceRetrieval"] = [input valueForKey:@"deviceRetrieval"]; + result[@"docRequestPreset"] = [input valueForKey:@"docRequestPreset"]; + result[@"intentToRetain"] = [input valueForKey:@"intentToRetain"]; + + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocumentRequestMDL* item in input.requests) + [array addObject:[self generateDocumentRequestMDL:item]]; + result[@"requests"] = array; + + return result; +} + ++(NSString*)generateDeviceEngagementCompletion:(RGLDeviceEngagement*)deviceEngagement :(NSError*)error { + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"deviceEngagement"] = [self generateDeviceEngagement:deviceEngagement]; + result[@"error"] = [self generateError:error]; + + return [RGLWJSONConstructor dictToString: result]; +} + ++(RGLFinalizeConfig*)finalizeConfigFromJson:(NSDictionary*)input { + if(input == nil) return nil; + RGLFinalizeConfig *result = [RGLFinalizeConfig defaultParams]; + + if (input[@"rawImages"]) result.rawImages = [input[@"rawImages"] boolValue]; + if (input[@"video"]) result.video = [input[@"video"] boolValue]; + if (input[@"rfidSession"]) result.rfidSession = [input[@"rfidSession"] boolValue]; + if (input[@"mdlSession"]) result.mdlSession = [input[@"mdlSession"] boolValue]; + + return result; +} + ++(NSDictionary*)generateFinalizeConfig:(RGLFinalizeConfig*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"rawImages"] = @(input.rawImages); + result[@"video"] = @(input.video); + result[@"rfidSession"] = @(input.rfidSession); + result[@"mdlSession"] = @(input.mdlSession); + + return result; +} + ++(RGLRFIDAccessControlPACE*)paceProtocolFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"Version"] = input[@"version"]; + json[@"StdDomainParams"] = input[@"stdDomainParams"]; + json[@"KeyAlgorithm"] = input[@"keyAlgorithm"]; +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + return [[RGLRFIDAccessControlPACE alloc] performSelector:NSSelectorFromString(@"initWithJSON:") withObject:json]; +#pragma clang diagnostic pop +} - result[@"bottom"] = @(input.bottom); - result[@"left"] = @(input.left); - result[@"right"] = @(input.right); - result[@"top"] = @(input.top); ++(NSDictionary*)generatePaceProtocol:(RGLRFIDAccessControlPACE*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"version"] = [NSString stringWithFormat:@"%ld", (long)input.version]; + result[@"stdDomainParams"] = input.stdDomainParams; + result[@"keyAlgorithm"] = input.keyAlgorithm; + + return result; +} ++(RGLRFIDAccessControlCA*)caProtocolFromJson:(NSDictionary*)input { + NSMutableDictionary* json = input.mutableCopy; + + json[@"Version"] = input[@"version"]; + json[@"Scheme"] = input[@"scheme"]; + json[@"KeyAlgorithm"] = input[@"keyAlgorithm"]; + json[@"ChipIndividual"] = input[@"chipIndividual"]; +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + return [[RGLRFIDAccessControlCA alloc] performSelector:NSSelectorFromString(@"initWithJSON:") withObject:json]; +#pragma clang diagnostic pop +} + ++(NSDictionary*)generateCaProtocol:(RGLRFIDAccessControlCA*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + result[@"version"] = [NSString stringWithFormat:@"%ld", (long)input.version]; + result[@"scheme"] = input.scheme; + result[@"keyAlgorithm"] = input.keyAlgorithm; + result[@"chipIndividual"] = [NSNumber numberWithBool: input.chipIndividual]; + return result; } -@end \ No newline at end of file ++(RGLDocumentReaderResults*)documentReaderResultsFromJson:(NSDictionary*)input { + NSMutableArray* documentType = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"documentType"]){ + [documentType addObject:[self documentReaderDocumentTypeFromJson:item]]; + } + NSMutableArray* documentPosition = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"documentPosition"]){ + [documentPosition addObject:(RGLDocumentPosition*)[self positionFromJson:item]]; + } + NSMutableArray* barcodePosition = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"barcodePosition"]){ + [barcodePosition addObject:(RGLBarcodePosition*)[self positionFromJson:item]]; + } + NSMutableArray* mrzPosition = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"mrzPosition"]){ + [mrzPosition addObject:(RGLMrzPosition*)[self positionFromJson:item]]; + } + NSMutableArray* imageQuality = [NSMutableArray new]; + for(NSDictionary* item in [input valueForKey:@"imageQuality"]){ + [imageQuality addObject:[self imageQualityGroupFromJson:item]]; + } + + RGLDocumentReaderResults* result = [[RGLDocumentReaderResults alloc] + initWithDocumentTypes:documentType + textResult:[self documentReaderTextResultFromJson: [input valueForKey:@"textResult"]] + graphicResult:[self documentReaderGraphicResultFromJson: [input valueForKey:@"graphicResult"]] + rawResult:[input valueForKey:@"rawResult"] + documentPosition:documentPosition + barcodePosition:barcodePosition + mrzPosition:mrzPosition + imageQualityGroup:imageQuality + authenticityResults:[self documentReaderAuthenticityResultFromJson: [input valueForKey:@"authenticityResult"]] + rfidSessionData:[self rfidSessionDataFromJson: [input valueForKey:@"rfidSessionData"]] + chipPage:[[input valueForKey:@"chipPage"] integerValue] + barcodeResult:[self documentReaderBarcodeResultFromJson: [input valueForKey:@"barcodeResult"]] + vdsncData:[self vdsncDataFromJson: [input valueForKey:@"vdsncData"]] + vdsData:[self vdsDataFromJson: [input valueForKey:@"vdsData"]] + status:[self documentReaderResultsStatusFromJson: [input valueForKey:@"status"]] + processingFinished:[[input valueForKey:@"processingFinishedStatus"] integerValue] + morePagesAvailable:[[input valueForKey:@"morePagesAvailable"] integerValue] + elapsedTime:[[input valueForKey:@"elapsedTime"] integerValue] + elapsedTimeRFID:[[input valueForKey:@"elapsedTimeRFID"] integerValue] + transactionInfo:[self transactionInfoFromJson:[input valueForKey:@"transactionInfo"]]]; + + [result setValue:[RGLWJSONConstructor base64Decode:input[@"dtcData"]] forKey:@"dtcData"]; + [result setValue:input[@"bsiTr03135Results"] forKey:@"bsiTr03135Results"]; + + return result; +} + ++(NSDictionary*)generateDocumentReaderResults:(RGLDocumentReaderResults*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + if(input.documentType != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLDocumentReaderDocumentType* item in input.documentType) + [array addObject:[self generateDocumentReaderDocumentType:item]]; + result[@"documentType"] = array; + } + result[@"textResult"] = [self generateDocumentReaderTextResult:input.textResult]; + result[@"graphicResult"] = [self generateDocumentReaderGraphicResult:input.graphicResult]; + if(input.documentPosition != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLPosition* item in input.documentPosition) + [array addObject:[self generatePosition:item]]; + result[@"documentPosition"] = array; + } + if(input.barcodePosition != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLPosition* item in input.barcodePosition) + [array addObject:[self generatePosition:item]]; + result[@"barcodePosition"] = array; + } + if(input.mrzPosition != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLPosition* item in input.mrzPosition) + [array addObject:[self generatePosition:item]]; + result[@"mrzPosition"] = array; + } + if(input.imageQualityGroup != nil){ + NSMutableArray *array = [NSMutableArray new]; + for(RGLImageQualityGroup* item in input.imageQualityGroup) + [array addObject:[self generateImageQualityGroup:item]]; + result[@"imageQuality"] = array; + } + result[@"authenticityResult"] = [self generateDocumentReaderAuthenticityResult:input.authenticityResults]; + result[@"rfidSessionData"] = [self generateRFIDSessionData:input.rfidSessionData]; + result[@"chipPage"] = @(input.chipPage); + result[@"barcodeResult"] = [self generateDocumentReaderBarcodeResult:input.barcodeResult]; + result[@"processingFinishedStatus"] = @(input.processingFinishedStatus); + result[@"morePagesAvailable"] = @(input.morePagesAvailable); + result[@"elapsedTime"] = @(input.elapsedTime); + result[@"elapsedTimeRFID"] = @(input.elapsedTimeRFID); + result[@"rawResult"] = input.rawResult; + result[@"bsiTr03135Results"] = input.bsiTr03135Results; + result[@"status"] = [self generateDocumentReaderResultsStatus:input.status]; + result[@"vdsncData"] = [self generateVDSNCData:input.vdsncData]; + result[@"vdsData"] = [self generateVDSData:input.vdsData]; + result[@"dtcData"] = [self base64Encode: input.dtcData]; + result[@"transactionInfo"] = [self generateTransactionInfo:input.transactionInfo]; + + return result; +} + ++(NSDictionary*)generateDictionary:(NSDictionary*)input { + if(input == nil) return nil; + NSMutableDictionary* result = [NSMutableDictionary new]; + + for(NSNumber* key in input) + result[[key stringValue]] = input[key]; + + return result; +} + +@end + +@implementation RGLWRequestInterceptorProxy { + NSDictionary* _headers; +} + +- (instancetype)initWithHeaders:(NSDictionary*)headers { + self = [super init]; + _headers = [headers copy]; + return self; +} + +-(NSURLRequest*)interceptorPrepareRequest:(NSURLRequest*)request { + NSMutableURLRequest *interceptedRequest = [request mutableCopy]; + for (NSString* key in _headers.allKeys) + [interceptedRequest addValue:[_headers valueForKey:key] forHTTPHeaderField:key]; + return interceptedRequest; +} + +@end diff --git a/ios/Classes/RGLWMain.h b/ios/Classes/RGLWMain.h new file mode 100644 index 0000000000..549705e190 --- /dev/null +++ b/ios/Classes/RGLWMain.h @@ -0,0 +1,34 @@ +#import +#import "RGLWJSONConstructor.h" +#import "RGLWConfig.h" + +typedef void (^RGLWCallback)(id _Nullable response); +typedef void (^RGLWEventSender)(NSString* _Nonnull event, id _Nullable data); +typedef void (^RGLWRFIDSignatureCallback)(NSData * _Nonnull signature); +extern UIViewController*_Nonnull(^ _Nonnull RGLWRootViewController)(void); + +@interface RGLWMain: NSObject + ++(void)methodCall:(NSString* _Nonnull)method + :(NSArray* _Nonnull)args + :(RGLWCallback _Nonnull)callback + :(RGLWEventSender _Nonnull)eventSender; + +@end + +static NSString* _Nonnull completionEvent = @"completion"; +static NSString* _Nonnull databaseProgressEvent = @"database_progress"; +static NSString* _Nonnull rfidOnProgressEvent = @"rfidOnProgressCompletion"; +static NSString* _Nonnull rfidOnChipDetectedEvent = @"rfidOnChipDetectedEvent"; +static NSString* _Nonnull rfidOnRetryReadChipEvent = @"rfidOnRetryReadChipEvent"; +static NSString* _Nonnull paCertificateCompletionEvent = @"pa_certificate_completion"; +static NSString* _Nonnull taCertificateCompletionEvent = @"ta_certificate_completion"; +static NSString* _Nonnull taSignatureCompletionEvent = @"ta_signature_completion"; +static NSString* _Nonnull paceProtocolCompletionEvent = @"paceProtocolCompletionEvent"; +static NSString* _Nonnull caProtocolCompletionEvent = @"caProtocolCompletionEvent"; +static NSString* _Nonnull drVideoEncoderCompletionEvent = @"video_encoder_completion"; +static NSString* _Nonnull drOnCustomButtonTappedEvent = @"onCustomButtonTappedEvent"; diff --git a/ios/Classes/RGLWMain.m b/ios/Classes/RGLWMain.m new file mode 100644 index 0000000000..59d60f55e1 --- /dev/null +++ b/ios/Classes/RGLWMain.m @@ -0,0 +1,706 @@ +#import "RGLWMain.h" + +@implementation RGLWMain + ++(void)methodCall:(NSString*)method :(NSArray*)args :(RGLWCallback)callback :(RGLWEventSender)eventSender { + if(!this) this = [RGLWMain new]; + sendEvent = eventSender; + NSDictionary* Switch = @{ + @"getDocumentReaderIsReady": ^{ [self getDocumentReaderIsReady :callback]; }, + @"getDocumentReaderStatus": ^{ [self getDocumentReaderStatus :callback]; }, + @"getRfidSessionStatus": ^{ [self getRfidSessionStatus :callback]; }, + @"setRfidSessionStatus": ^{ [self setRfidSessionStatus :args[0]]; }, + @"getTag": ^{ [self getTag :callback]; }, + @"setTag": ^{ [self setTag :args[0]]; }, + @"getTenant": ^{ [self getTenant :callback]; }, + @"setTenant": ^{ [self setTenant :args[0]]; }, + @"getEnv": ^{ [self getEnv :callback]; }, + @"setEnv": ^{ [self setEnv :args[0]]; }, + @"getLocale": ^{ [self getLocale :callback]; }, + @"setLocale": ^{ [self setLocale :args[0]]; }, + @"getFunctionality": ^{ [self getFunctionality :callback]; }, + @"setFunctionality": ^{ [self setFunctionality :args[0]]; }, + @"getProcessParams": ^{ [self getProcessParams :callback]; }, + @"setProcessParams": ^{ [self setProcessParams :args[0]]; }, + @"getCustomization": ^{ [self getCustomization :callback]; }, + @"setCustomization": ^{ [self setCustomization :args[0]]; }, + @"getRfidScenario": ^{ [self getRfidScenario :callback]; }, + @"setRfidScenario": ^{ [self setRfidScenario :args[0]]; }, + @"resetConfiguration": ^{ [self resetConfiguration]; }, + @"initialize": ^{ [self initialize :args[0] :callback]; }, + @"initializeReader": ^{ [self initialize :args[0] :callback]; }, // deprecated + @"initializeReaderWithBleDeviceConfig": ^{ [self initializeReaderWithBleDeviceConfig :args[0] :callback]; }, // deprecated + @"deinitializeReader": ^{ [self deinitializeReader]; }, + @"prepareDatabase": ^{ [self prepareDatabase :args[0] :callback]; }, + @"removeDatabase": ^{ [self removeDatabase :callback]; }, + @"runAutoUpdate": ^{ [self runAutoUpdate :args[0] :callback]; }, + @"cancelDBUpdate": ^{ [self cancelDBUpdate :callback]; }, + @"checkDatabaseUpdate": ^{ [self checkDatabaseUpdate :args[0] :callback]; }, + @"scan": ^{ [self startScanner :args[0]]; }, + @"startScanner": ^{ [self startScanner :args[0]]; }, + @"recognize": ^{ [self recognize :args[0]]; }, + @"startNewPage": ^{ [self startNewPage]; }, + @"stopScanner": ^{ [self stopScanner]; }, + @"startRFIDReader": ^{ [self startRFIDReader :args[0]]; }, + @"readRFID": ^{ [self readRFID :args[0]]; }, + @"stopRFIDReader": ^{ [self stopRFIDReader]; }, + @"providePACertificates": ^{ [self providePACertificates :args[0]]; }, + @"provideTACertificates": ^{ [self provideTACertificates :args[0]]; }, + @"provideTASignature": ^{ [self provideTASignature :args[0]]; }, + @"selectPACEProtocol": ^{ [self selectPACEProtocol :args[0]]; }, + @"selectCAProtocol": ^{ [self selectCAProtocol :args[0]]; }, + @"setTCCParams": ^{ [self setTCCParams :args[0] :callback]; }, + @"addPKDCertificates": ^{ [self addPKDCertificates :args[0]]; }, + @"clearPKDCertificates": ^{ [self clearPKDCertificates]; }, + @"startNewSession": ^{ [self startNewSession]; }, + @"connectBluetoothDevice": ^{ [self connectBluetoothDevice :args[0] :callback]; }, + @"btDeviceRequestFlashing": ^{ /* android only */ }, + @"btDeviceRequestFlashingFullIR": ^{ /* android only */ }, + @"btDeviceRequestTurnOffAll": ^{ /* android only */ }, + @"startReadMDl": ^{ [self startReadMDl :args[0] :args[1] :callback]; }, + @"startEngageDevice": ^{ [self startEngageDevice :args[0] :callback]; }, + @"engageDeviceNFC": ^{ [self engageDeviceNFC :callback]; }, + @"engageDeviceData": ^{ [self engageDeviceData :args[0] :callback]; }, + @"startRetrieveData": ^{ [self startRetrieveData :args[0] :args[1] :callback]; }, + @"retrieveDataNFC": ^{ [self retrieveDataNFC :args[0] :callback]; }, + @"retrieveDataBLE": ^{ [self retrieveDataBLE :args[0] :args[0] :callback]; }, + @"setLocalizationDictionary": ^{ [self setLocalizationDictionary :args[0]]; }, + @"getLicense": ^{ [self getLicense :callback]; }, + @"getAvailableScenarios": ^{ [self getAvailableScenarios :callback]; }, + @"getIsRFIDAvailableForUse": ^{ [self getIsRFIDAvailableForUse :callback]; }, + @"isAuthenticatorRFIDAvailableForUse": ^{ [self isAuthenticatorRFIDAvailableForUse :callback]; }, + @"isAuthenticatorAvailableForUse": ^{ [self isAuthenticatorAvailableForUse :callback]; }, + @"getDocReaderVersion": ^{ [self getDocReaderVersion :callback]; }, + @"getDocReaderDocumentsDatabase": ^{ [self getDocReaderDocumentsDatabase :callback]; }, + @"finalizePackage": ^{ [self finalizePackage :callback]; }, + @"finalizePackageWithFinalizeConfig": ^{ [self finalizePackageWithFinalizeConfig :args[0] :callback]; }, + @"endBackendTransaction": ^{ [self endBackendTransaction]; }, + @"textFieldValueByType": ^{ [self textFieldValueByType :args[0] :args[1] :callback]; }, + @"textFieldValueByTypeLcid": ^{ [self textFieldValueByTypeLcid :args[0] :args[1] :args[2] :callback]; }, + @"textFieldValueByTypeSource": ^{ [self textFieldValueByTypeSource :args[0] :args[1] :args[2] :callback]; }, + @"textFieldValueByTypeLcidSource": ^{ [self textFieldValueByTypeLcidSource :args[0] :args[1] :args[2] :args[3] :callback]; }, + @"textFieldValueByTypeSourceOriginal": ^{ [self textFieldValueByTypeSourceOriginal :args[0] :args[1] :args[2] :args[3] :callback]; }, + @"textFieldValueByTypeLcidSourceOriginal": ^{ [self textFieldValueByTypeLcidSourceOriginal :args[0] :args[1] :args[2] :args[3] :args[4] :callback]; }, + @"textFieldByType": ^{ [self textFieldByType :args[0] :args[1] :callback]; }, + @"textFieldByTypeLcid": ^{ [self textFieldByTypeLcid :args[0] :args[1] :args[2] :callback]; }, + @"graphicFieldByTypeSource": ^{ [self graphicFieldByTypeSource :args[0] :args[1] :args[2] :callback]; }, + @"graphicFieldByTypeSourcePageIndex": ^{ [self graphicFieldByTypeSourcePageIndex :args[0] :args[1] :args[2] :args[3] :callback]; }, + @"graphicFieldByTypeSourcePageIndexLight": ^{ [self graphicFieldByTypeSourcePageIndexLight :args[0] :args[1] :args[2] :args[3] :args[4] :callback]; }, + @"graphicFieldImageByType": ^{ [self graphicFieldImageByType :args[0] :args[1] :callback]; }, + @"graphicFieldImageByTypeSource": ^{ [self graphicFieldImageByTypeSource :args[0] :args[1] :args[2] :callback]; }, + @"graphicFieldImageByTypeSourcePageIndex": ^{ [self graphicFieldImageByTypeSourcePageIndex :args[0] :args[1] :args[2] :args[3] :callback]; }, + @"graphicFieldImageByTypeSourcePageIndexLight": ^{ [self graphicFieldImageByTypeSourcePageIndexLight :args[0] :args[1] :args[2] :args[3] :args[4] :callback]; }, + @"containers": ^{ [self containers :args[0] :args[1] :callback]; }, + @"encryptedContainers": ^{ [self encryptedContainers :args[0] :callback]; }, + @"getTranslation": ^{ [self getTranslation :args[0] :args[1] :callback]; }, + }; + ((void(^)(void))Switch[method])(); +} + +static RGLWMain* this; +static RGLWEventSender sendEvent; +static NSDictionary* headers; + ++(void)getDocumentReaderIsReady:(RGLWCallback)callback { + callback([RGLDocReader.shared isDocumentReaderIsReady] ? @YES : @NO); +} + ++(void)getDocumentReaderStatus:(RGLWCallback)callback { + callback(RGLDocReader.shared.documentReaderStatus); +} + ++(void)getRfidSessionStatus:(RGLWCallback)callback { + callback(RGLDocReader.shared.rfidSessionStatus); +} + ++(void)setRfidSessionStatus:(NSString*)status { + RGLDocReader.shared.rfidSessionStatus = status; +} + ++(void)getTag:(RGLWCallback)callback { + callback([RGLDocReader.shared tag]); +} + ++(void)setTag:(NSString*)tag { + [RGLDocReader.shared setTag:tag]; +} + ++(void)getTenant:(RGLWCallback)callback { + callback([RGLDocReader.shared tenant]); +} + ++(void)setTenant:(NSString*)tag { + [RGLDocReader.shared setTenant:tag]; +} + ++(void)getEnv:(RGLWCallback)callback { + callback([RGLDocReader.shared env]); +} + ++(void)setEnv:(NSString*)tag { + [RGLDocReader.shared setEnv:tag]; +} + ++(void)getLocale:(RGLWCallback)callback { + callback([RGLDocReader.shared languageLocaleCode]); +} + ++(void)setLocale:(NSString*)locale { + [RGLDocReader.shared setLanguageLocaleCode:locale]; +} + ++(void)getFunctionality:(RGLWCallback)callback { + callback([RGLWJSONConstructor dictToString: [RGLWConfig getFunctionality: RGLDocReader.shared.functionality]]); +} + ++(void)setFunctionality:(NSDictionary*)functionality { + [RGLWConfig setFunctionality:functionality :RGLDocReader.shared.functionality]; +} + ++(void)getProcessParams:(RGLWCallback)callback { + callback([RGLWJSONConstructor dictToString: [RGLWConfig getProcessParams:RGLDocReader.shared.processParams]]); +} + ++(void)setProcessParams:(NSDictionary*)processParams { + [RGLWConfig setProcessParams:processParams :RGLDocReader.shared.processParams]; +} + ++(void)getCustomization:(RGLWCallback)callback { + callback([RGLWJSONConstructor dictToString: [RGLWConfig getCustomization :RGLDocReader.shared.customization]]); +} + ++(void)setCustomization:(NSDictionary*)customization { + [RGLWConfig setCustomization:customization :RGLDocReader.shared.customization]; +} + ++(void)getRfidScenario:(RGLWCallback)callback { + callback([RGLWJSONConstructor dictToString: [RGLWConfig getRfidScenario:RGLDocReader.shared.rfidScenario]]); +} + ++(void)setRfidScenario:(NSDictionary*)rfidScenario { + [RGLWConfig setRfidScenario:rfidScenario :RGLDocReader.shared.rfidScenario]; +} + ++(void)resetConfiguration { + RGLDocReader.shared.functionality = [RGLFunctionality new]; + RGLDocReader.shared.processParams = [RGLProcessParams new]; + RGLDocReader.shared.customization = [RGLCustomization new]; + RGLDocReader.shared.rfidScenario = [RGLRFIDScenario new]; +} + ++(void)initialize:(NSDictionary*)config :(RGLWCallback)callback { + if (config[@"useBleDevice"] && [config[@"useBleDevice"] boolValue] == true) + [RGLDocReader.shared initializeReaderWithConfig:[RGLWJSONConstructor bleDeviceConfigFromJson:config :bluetooth] completion: [self initCompletion :callback]]; + else + [RGLDocReader.shared initializeReaderWithConfig:[RGLWJSONConstructor configFromJson:config] completion:[self initCompletion :callback]]; +} + +// deprecated ++(void)initializeReaderWithBleDeviceConfig:(NSDictionary*)config :(RGLWCallback)callback { + [RGLDocReader.shared initializeReaderWithConfig:[RGLWJSONConstructor bleDeviceConfigFromJson:config :bluetooth] completion: [self initCompletion :callback]]; +} + ++(void)deinitializeReader { + [RGLDocReader.shared deinitializeReader]; +} + ++(void)prepareDatabase:(NSString*)databaseID :(RGLWCallback)callback { + [RGLDocReader.shared prepareDatabase:databaseID progressHandler:nil completion:[self prepareCompletion :callback]]; +} + ++(void)removeDatabase:(RGLWCallback)callback { + [RGLDocReader.shared removeDatabase:^(BOOL success, NSError * _Nullable error) { + callback(success ? @YES : @NO); + }]; +} + ++(void)runAutoUpdate:(NSString*)databaseID :(RGLWCallback)callback { + [RGLDocReader.shared runAutoUpdate:databaseID progressHandler:nil completion:[self prepareCompletion :callback]]; +} + ++(void)cancelDBUpdate:(RGLWCallback)callback { + [RGLDocReader.shared cancelDBUpdate]; + callback(@YES); +} + ++(void)checkDatabaseUpdate:(NSString*)databaseID :(RGLWCallback)callback { + [RGLDocReader.shared checkDatabaseUpdate:databaseID completion:^(RGLDocReaderDocumentsDatabase* database) { + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocReaderDocumentsDatabase:database]]); + }]; +} + ++(void)startScanner:(NSDictionary*)config { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared startScannerFromPresenter:RGLWRootViewController() config:[RGLWJSONConstructor scannerConfigFromJson:config] completion:[self completion]]; + }); +} + ++(void)recognize:(NSDictionary*)config { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared recognizeImageFromPresenter:RGLWRootViewController() config:[RGLWJSONConstructor recognizeConfigFromJson:config] completion:[self completion]]; + }); +} + ++(void)startNewPage { + [RGLDocReader.shared startNewPage]; +} + ++(void)stopScanner { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared stopScanner:nil]; + }); +} + ++(void)startRFIDReader:(NSDictionary*)config { + rfidReaderRequest = config; + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared startRFIDReaderFromPresenter:RGLWRootViewController() completion:[self completion]]; + }); +} + ++(void)readRFID:(NSDictionary*)config { + rfidReaderRequest = config; + [RGLDocReader.shared readRFID:^(RGLRFIDNotificationAction notificationAction, RGLRFIDNotify* _Nullable notification) { + if (notification != nil) sendEvent(rfidOnProgressEvent, [RGLWJSONConstructor generateDocumentReaderNotification:notification]); + } completion :^(RGLRFIDCompleteAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error, RGLRFIDErrorCodes errorCode) { + sendEvent(completionEvent, [RGLWJSONConstructor generateCompletion:[RGLWConfig generateRFIDCompleteAction: action] :results :error]); + }]; +} + ++(void)stopRFIDReader { + [RGLDocReader.shared stopRFIDReader:nil]; +} + ++(void)providePACertificates:(NSArray*)certificates { + NSMutableArray *certificatesMutable = [NSMutableArray new]; + for(NSDictionary* certificateJSON in certificates) + [certificatesMutable addObject:[RGLWJSONConstructor pkdCertificateFromJson:certificateJSON]]; + paCertificateCompletion(certificatesMutable); +} + ++(void)provideTACertificates:(NSArray*)certificates { + NSMutableArray *certificatesMutable = [NSMutableArray new]; + for(NSDictionary* certificateJSON in certificates) + [certificatesMutable addObject:[RGLWJSONConstructor pkdCertificateFromJson:certificateJSON]]; + taCertificateCompletion(certificatesMutable); +} + ++(void)provideTASignature:(NSString*)signature { + taSignatureCompletion([RGLWJSONConstructor base64Decode:signature]); +} + ++(void)selectPACEProtocol:(NSDictionary*)protocol { + paceProtocolCompletion([RGLWJSONConstructor paceProtocolFromJson:protocol]); +} + ++(void)selectCAProtocol:(NSDictionary*)protocol { + caProtocolCompletion([RGLWJSONConstructor caProtocolFromJson:protocol]); +} + ++(void)setTCCParams:(NSDictionary*)params :(RGLWCallback)callback { + [RGLDocReader.shared setTCCParams:[RGLWJSONConstructor tccParamsFromJson:params] completion:^(BOOL success, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateSuccessCompletion:success :error]); + }]; +} + ++(void)addPKDCertificates:(NSArray*)certificates { + NSMutableArray *certificatesMutable = [NSMutableArray new]; + for(NSDictionary* certificateJSON in certificates) + [certificatesMutable addObject:[RGLWJSONConstructor pkdCertificateFromJson:certificateJSON]]; + [RGLDocReader.shared addPKDCertificates:certificatesMutable]; +} + ++(void)clearPKDCertificates { + [RGLDocReader.shared clearPKDCertificates]; +} + ++(void)startNewSession { + [RGLDocReader.shared startNewSession]; +} + +RGLBluetooth* bluetooth; +RGLWCallback savedCallbackForBluetoothResult; + ++(void)connectBluetoothDevice:(NSString*)deviceName :(RGLWCallback)callback { + // return if already connected + if (bluetooth && bluetooth.state == RGLBluetoothConnectionStateConnected) return; + + // start searching devices + if (!bluetooth) { + bluetooth = [RGLBluetooth new]; + bluetooth.delegate = this; + } + savedCallbackForBluetoothResult = callback; + [bluetooth connectWithDeviceName:deviceName]; +} + +// RGLBluetoothDelegate +- (void)didChangeConnectionState:(RGLBluetooth *)bluetooth state:(RGLBluetoothConnectionState)state { + if (state == RGLBluetoothConnectionStateNone && savedCallbackForBluetoothResult) + [RGLWMain bluetoothDeviceConnectionFailed]; + + // set searching timeout + if (state == RGLBluetoothConnectionStateSearching) + [[self class] performSelector:NSSelectorFromString(@"bluetoothDeviceConnectionFailed") withObject:nil afterDelay:7.0]; + + if (state == RGLBluetoothConnectionStateConnected) { + savedCallbackForBluetoothResult(@YES); + savedCallbackForBluetoothResult = nil; + [NSObject cancelPreviousPerformRequestsWithTarget:[self class] selector:NSSelectorFromString(@"bluetoothDeviceConnectionFailed") object:nil]; + } +} + ++(void)bluetoothDeviceConnectionFailed { + if (savedCallbackForBluetoothResult) { + savedCallbackForBluetoothResult(@NO); + savedCallbackForBluetoothResult = nil; + } + [bluetooth stopSearchDevices]; + [bluetooth disconnect]; +} + ++(void)startReadMDl:(NSNumber*)type :(NSDictionary*)dataRetrieval :(RGLWCallback)callback { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared startReadMDLFromPresenter:RGLWRootViewController() engagementType:[type integerValue] dataRetrieval:[RGLWJSONConstructor dataRetrievalFromJson:dataRetrieval] completion:^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateCompletion:[RGLWConfig generateDocReaderAction: action] :results :error]); + }]; + }); +} + ++(void)startEngageDevice:(NSNumber*)type :(RGLWCallback)callback { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared startEngageDeviceFromPresenter:RGLWRootViewController() type:[type integerValue] completion:^(RGLDeviceEngagement* deviceEngagement, NSError* error) { + callback([RGLWJSONConstructor generateDeviceEngagementCompletion:deviceEngagement :error]); + }]; + }); +} + ++(void)engageDeviceNFC:(RGLWCallback)callback { + dispatch_async(dispatch_get_main_queue(), ^{ + [RGLDocReader.shared engageDeviceNFC:RGLWRootViewController() completion:^(RGLDeviceEngagement * _Nullable deviceEngagement, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateDeviceEngagementCompletion:deviceEngagement :error]); + }]; + }); +} + ++(void)engageDeviceData:(NSString*)data :(RGLWCallback)callback { + [RGLDocReader.shared engageDeviceData:data completion:^(RGLDeviceEngagement * _Nullable deviceEngagement, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateDeviceEngagementCompletion:deviceEngagement :error]); + }]; +} + ++(void)startRetrieveData:(NSDictionary*)dataRetrieval :(NSDictionary*)deviceEngagement :(RGLWCallback)callback { + [RGLDocReader.shared startRetrieveData:[RGLWJSONConstructor deviceEngagementFromJson:deviceEngagement] dataRetrieval:[RGLWJSONConstructor dataRetrievalFromJson:dataRetrieval] completion:^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateCompletion:[RGLWConfig generateDocReaderAction: action] :results :error]); + }]; +} + ++(void)retrieveDataNFC:(NSDictionary*)dataRetrieval :(RGLWCallback)callback { + [RGLDocReader.shared retrieveDataNFC:[RGLWJSONConstructor dataRetrievalFromJson:dataRetrieval] completion:^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateCompletion:[RGLWConfig generateDocReaderAction: action] :results :error]); + }]; +} + ++(void)retrieveDataBLE:(NSDictionary*)dataRetrieval :(NSDictionary*)deviceEngagement :(RGLWCallback)callback { + [RGLDocReader.shared retrieveDataBLE:[RGLWJSONConstructor deviceEngagementFromJson:deviceEngagement] dataRetrieval:[RGLWJSONConstructor dataRetrievalFromJson:dataRetrieval] completion:^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateCompletion:[RGLWConfig generateDocReaderAction: action] :results :error]); + }]; +} + ++(void)setLocalizationDictionary:(NSDictionary*)dictionary { + RGLDocReader.shared.localizationHandler = ^NSString * _Nullable(NSString * _Nonnull localizationKey) { + if(dictionary != nil && ![dictionary isEqual:[NSNull null]] && [dictionary valueForKey:localizationKey] != nil) + return [dictionary valueForKey:localizationKey]; + return nil; + }; +} + ++(void)getLicense :(RGLWCallback)callback { + callback([RGLWJSONConstructor generateLicense:RGLDocReader.shared.license]); +} + ++(void)getAvailableScenarios :(RGLWCallback)callback { + NSMutableArray *availableScenarios = [NSMutableArray new]; + for(RGLScenario *scenario in RGLDocReader.shared.availableScenarios) + [availableScenarios addObject:[RGLWJSONConstructor generateScenario:scenario]]; + callback([RGLWJSONConstructor arrayToString:availableScenarios]); +} + ++(void)getIsRFIDAvailableForUse :(RGLWCallback)callback { + callback(RGLDocReader.shared.isRFIDAvailableForUse ? @YES : @NO); +} + ++(void)getDocReaderVersion :(RGLWCallback)callback { + callback([RGLWJSONConstructor generateDocReaderVersion:RGLDocReader.shared.version]); +} + ++(void)isAuthenticatorRFIDAvailableForUse :(RGLWCallback)callback { + callback(RGLDocReader.shared.isAuthenticatorRFIDAvailableForUse ? @YES : @NO); +} + ++(void)isAuthenticatorAvailableForUse :(RGLWCallback)callback { + callback(RGLDocReader.shared.isAuthenticatorAvailableForUse ? @YES : @NO); +} + ++(void)getDocReaderDocumentsDatabase :(RGLWCallback)callback { + if(RGLDocReader.shared.version != nil) + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocReaderDocumentsDatabase:RGLDocReader.shared.version.database]]); + else callback(nil); +} + ++(void)finalizePackage:(RGLWCallback)callback { + [RGLDocReader.shared finalizePackageWithCompletion:^(RGLDocReaderAction action, RGLTransactionInfo* info, NSError* error) { + callback([RGLWJSONConstructor generateFinalizePackageCompletion:[RGLWConfig generateDocReaderAction: action] :info :error]); + }]; +} + ++(void)finalizePackageWithFinalizeConfig:(NSDictionary*)config :(RGLWCallback)callback { + [RGLDocReader.shared finalizePackageWithFinalizeConfig:[RGLWJSONConstructor finalizeConfigFromJson:config] completion:^(RGLDocReaderAction action, RGLTransactionInfo* info, NSError* error) { + callback([RGLWJSONConstructor generateFinalizePackageCompletion:[RGLWConfig generateDocReaderAction: action] :info :error]); + }]; +} + ++(void)endBackendTransaction { + [RGLDocReader.shared endBackendTransaction]; +} + ++(void)textFieldValueByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue]]); +} + ++(void)textFieldValueByTypeLcid:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue]]); +} + ++(void)textFieldValueByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue] source:[source integerValue]]); +} + ++(void)textFieldValueByTypeLcidSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(NSNumber*)source :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue] source:[source integerValue]]); +} + ++(void)textFieldValueByTypeSourceOriginal:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(BOOL)original :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue] source:[source integerValue] original:original]); +} + ++(void)textFieldValueByTypeLcidSourceOriginal:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(NSNumber*)source :(BOOL)original :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getTextFieldValueByType:[fieldType integerValue] lcid:[lcid integerValue] source:[source integerValue] original:original]); +} + ++(void)textFieldByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + RGLDocumentReaderTextField* result = [results getTextFieldByType:[fieldType integerValue]]; + if (result == nil) callback(nil); + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderTextField:result]]); +} + ++(void)textFieldByTypeLcid:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)lcid :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + RGLDocumentReaderTextField* result = [results getTextFieldByType:[fieldType integerValue] lcid:[lcid integerValue]]; + if (result == nil) callback(nil); + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderTextField:result]]); +} + ++(void)graphicFieldByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue]]; + if (result == nil) callback(nil); + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderGraphicField:result]]); +} + ++(void)graphicFieldByTypeSourcePageIndex:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue]]; + if (result == nil) callback(nil); + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderGraphicField:result]]); +} + ++(void)graphicFieldByTypeSourcePageIndexLight:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(NSNumber*)light :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + RGLDocumentReaderGraphicField* result = [results getGraphicFieldByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue] light:[light integerValue]]; + if (result == nil) callback(nil); + callback([RGLWJSONConstructor dictToString:[RGLWJSONConstructor generateDocumentReaderGraphicField:result]]); +} + ++(void)graphicFieldImageByType:(NSString*)rawResult :(NSNumber*)fieldType :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue]]]); +} + ++(void)graphicFieldImageByTypeSource:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue]]]); +} + ++(void)graphicFieldImageByTypeSourcePageIndex:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue]]]); +} + ++(void)graphicFieldImageByTypeSourcePageIndexLight:(NSString*)rawResult :(NSNumber*)fieldType :(NSNumber*)source :(NSNumber*)pageIndex :(NSNumber*)light :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([RGLWJSONConstructor base64WithImage:[results getGraphicFieldImageByType:[fieldType integerValue] source:[source integerValue] pageIndex:[pageIndex integerValue] light:[light integerValue]]]); +} + ++(void)containers:(NSString*)rawResult :(NSArray*)resultType :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getContainersByResultTypes:resultType]); +} + ++(void)encryptedContainers:(NSString*)rawResult :(RGLWCallback)callback { + RGLDocumentReaderResults* results = [RGLDocumentReaderResults initWithRawString:rawResult]; + callback([results getEncryptedContainers]); +} + ++(void)getTranslation:(NSString*)className :(NSNumber*)value :(RGLWCallback)callback { + if([className isEqualToString:@"RFIDErrorCodes"]) + callback(RGLRFIDErrorCodesGetStringValue([value intValue])); + else if([className isEqualToString:@"LDSParsingErrorCodes"]) + callback(eLDS_ParsingErrorCodesGetStringValue([value intValue])); + else if([className isEqualToString:@"LDSParsingNotificationCodes"]) + callback(eLDS_ParsingNotificationCodesGetStringValue([value intValue])); + else if([className isEqualToString:@"ImageQualityCheckType"]) + callback(RGLImageQualityCheckTypeGetStringValue([RGLWConfig imageQualityCheckTypeWithNumber:value])); + else if([className isEqualToString:@"RFIDDataFileType"]) + callback(RGLRFIDDataFileTypeGetStringValue([value intValue])); + else if([className isEqualToString:@"VisualFieldType"]) + callback(RGLFieldTypeGetStringValue([value intValue])); + else if([className isEqualToString:@"LCID"]) + callback([RGLDocumentReaderTextField lcidName:[value intValue]]); +} + ++(RGLDocumentReaderCompletion _Nonnull)completion { + return ^(RGLDocReaderAction action, RGLDocumentReaderResults * _Nullable results, NSError * _Nullable error) { + sendEvent(completionEvent, [RGLWJSONConstructor generateCompletion:[RGLWConfig generateDocReaderAction: action] :results :error]); + }; +} + ++(RGLDocumentReaderPrepareCompletion _Nonnull)prepareCompletion:(RGLWCallback)callback { + RGLDocReader.shared.databaseFetchDelegate = this; + return ^(BOOL success, NSError * _Nullable error) { + callback([RGLWJSONConstructor generateSuccessCompletion:success :error]); + }; +} + ++(RGLDocumentReaderInitializationCompletion)initCompletion:(RGLWCallback)callback { + return ^(BOOL success, NSError * _Nullable error ) { + if (success) { + RGLDocReader.shared.rfidDelegate = this; + RGLDocReader.shared.functionality.recordScanningProcessDelegate = this; + RGLDocReader.shared.customization.actionDelegate = this; + } + callback([RGLWJSONConstructor generateSuccessCompletion:success :error]); + }; +} + +// RGLDocReaderDatabaseFetchDelegate +- (void)onProgressChanged:(NSNumber *)downloadedBytes totalBytes:(NSNumber *)totalBytes { + int progress = 0; + if (downloadedBytes > 0 && totalBytes > 0) { + double percent = [downloadedBytes doubleValue] / [totalBytes doubleValue]; + progress = (int) (percent * 100); + } + NSDictionary* result = @{ + @"downloadedBytes":downloadedBytes, + @"totalBytes":totalBytes, + @"progress":@(progress) + }; + sendEvent(databaseProgressEvent, [RGLWJSONConstructor dictToString: result]); +} + +// RGLCustomizationActionDelegate +- (void)onCustomButtonTappedWithTag:(NSInteger)tag { + sendEvent(drOnCustomButtonTappedEvent, @(tag)); +} + +// RGLRecordScanningProcessDelegate +- (void)didFinishRecordingToFile:(NSURL *)fileURL { + sendEvent(drVideoEncoderCompletionEvent, fileURL.absoluteString); +} + +- (void)didFailWithError:(NSError *)error { + // ignore error to match android +} + +RGLRFIDCertificatesCallback paCertificateCompletion; +RGLRFIDCertificatesCallback taCertificateCompletion; +RGLWRFIDSignatureCallback taSignatureCompletion; +RGLRFIDAccessControlPACECallback paceProtocolCompletion; +RGLRFIDAccessControlCACallback caProtocolCompletion; + +NSDictionary* rfidReaderRequest; + +- (void)onRequestPACertificatesWithSerial:(NSData *)serialNumber issuer:(RGLPAResourcesIssuer *)issuer callback:(RGLRFIDCertificatesCallback)callback { + if ([rfidReaderRequest isKindOfClass:[NSDictionary class]] && [rfidReaderRequest[@"paCertificates"] boolValue]) { + paCertificateCompletion = callback; + sendEvent(paCertificateCompletionEvent, [RGLWJSONConstructor generatePACertificateCompletion:serialNumber :issuer]); + } else { + paCertificateCompletion = nil; + callback(nil); + } +} + +- (void)onRequestTACertificatesWithKey:(NSString *)keyCAR callback:(RGLRFIDCertificatesCallback)callback { + if ([rfidReaderRequest isKindOfClass:[NSDictionary class]] && [rfidReaderRequest[@"taCertificates"] boolValue]) { + taCertificateCompletion = callback; + sendEvent(taCertificateCompletionEvent, keyCAR); + } else { + taCertificateCompletion = nil; + callback(nil); + } +} + +- (void)onRequestTASignatureWithChallenge:(RGLTAChallenge *)challenge callback:(void(^)(NSData *signature))callback { + if ([rfidReaderRequest isKindOfClass:[NSDictionary class]] && [rfidReaderRequest[@"taSignature"] boolValue]) { + taSignatureCompletion = callback; + sendEvent(taSignatureCompletionEvent, [RGLWJSONConstructor dictToString: [RGLWJSONConstructor generateTAChallenge:challenge]]); + } else { + taSignatureCompletion = nil; + callback(nil); + } +} + +- (void)onRequestPACEProtocolWithOptions:(NSArray*)protocols callback:(RGLRFIDAccessControlPACECallback)callback { + if ([rfidReaderRequest isKindOfClass:[NSDictionary class]] && [rfidReaderRequest[@"paceProtocol"] boolValue]) { + paceProtocolCompletion = callback; + NSMutableArray *array = [NSMutableArray new]; + for(RGLRFIDAccessControlPACE* item in protocols) + [array addObject:[RGLWJSONConstructor generatePaceProtocol:item]]; + sendEvent(paceProtocolCompletionEvent, [RGLWJSONConstructor arrayToString: array]); + } else { + paceProtocolCompletion = nil; + callback(nil); + } +} + +- (void)onRequestCAProtocolWithOptions:(NSArray*)protocols callback:(RGLRFIDAccessControlCACallback)callback { + if ([rfidReaderRequest isKindOfClass:[NSDictionary class]] && [rfidReaderRequest[@"caProtocol"] boolValue]) { + caProtocolCompletion = callback; + NSMutableArray *array = [NSMutableArray new]; + for(RGLRFIDAccessControlCA* item in protocols) + [array addObject:[RGLWJSONConstructor generateCaProtocol:item]]; + sendEvent(caProtocolCompletionEvent, [RGLWJSONConstructor arrayToString: array]); + } else { + caProtocolCompletionEvent = nil; + callback(nil); + } +} + +- (void)didChipConnected { + sendEvent(rfidOnChipDetectedEvent, @""); +} + +- (void)didReceivedError:(RGLRFIDErrorCodes)errorCode { + NSMutableDictionary *result = [NSMutableDictionary new]; + result[@"code"] = [NSNumber numberWithInteger:errorCode]; + sendEvent(rfidOnRetryReadChipEvent, [RGLWJSONConstructor dictToString:result]); +} + +@end diff --git a/ios/Classes/RGLWRegulaConfig.h b/ios/Classes/RGLWRegulaConfig.h deleted file mode 100644 index df5d1412cb..0000000000 --- a/ios/Classes/RGLWRegulaConfig.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef RGLWRegulaConfig_h -#define RGLWRegulaConfig_h -#import -#import "RGLWJSONConstructor.h" -@import CoreGraphics; -@import UIKit; -@import AVFoundation; - -@interface RGLWRegulaConfig : NSObject - -+(void)setConfig:(NSDictionary*) options : (RGLDocReader*) reader; -+(NSMutableDictionary *)getConfig:(RGLDocReader*) reader; -+(void)setRfidScenario:(NSDictionary*) options : (RGLRFIDScenario*) rfidScenario; -+(void)setCustomization:(NSDictionary*) options : (RGLCustomization*) customization; -+(void)setFunctionality:(NSDictionary*) options : (RGLFunctionality*) functionality; -+(void)setProcessParams:(NSDictionary*) options : (RGLProcessParams*) processParams; -+(UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha; -+(unsigned int)intFromHexString:(NSString *)hexStr; -+(RGLePassportDataGroup*)RGLePassportDataGroupFromJson:(NSDictionary *) dict; -+(RGLeIDDataGroup*)RGLeIDDataGroupFromJson:(NSDictionary*) dict; -+(RGLeDLDataGroup*)RGLeDLDataGroupFromJson:(NSDictionary*) dict; -+(RGLImageQA*)ImageQAFromJson:(NSDictionary*) dict; -+(NSDictionary*)ImageQAToJson:(RGLImageQA*) input; -+(RGLOnlineProcessingConfig*)RGLOnlineProcessingConfigFromJSON:(NSDictionary*) dict; -@end -#endif diff --git a/ios/Classes/RGLWRegulaConfig.m b/ios/Classes/RGLWRegulaConfig.m deleted file mode 100644 index 996e091444..0000000000 --- a/ios/Classes/RGLWRegulaConfig.m +++ /dev/null @@ -1,1152 +0,0 @@ -#import -#import "RGLWRegulaConfig.h" - -@implementation RGLWRegulaConfig -+(void)setConfig:(NSDictionary*)options :(RGLDocReader*)reader { - if([options valueForKey:@"customization"] != nil) - [self setCustomization: [options valueForKey:@"customization"]: reader.customization]; - if([options valueForKey:@"functionality"] != nil) - [self setFunctionality: [options valueForKey:@"functionality"]: reader.functionality]; - if([options valueForKey:@"processParams"] != nil) - [self setProcessParams: [options valueForKey:@"processParams"]: reader.processParams]; -} - -+(NSMutableDictionary *)getConfig:(RGLDocReader*)reader{ - NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; - - result[@"customization"] = [self getCustomization: reader.customization]; - result[@"functionality"] = [self getFunctionality: reader.functionality]; - result[@"processParams"] = [self getProcessParams: reader.processParams]; - - return result; -} - -+(AVCaptureSessionPreset)AVCaptureSessionPresetWithNSInteger:(NSInteger)value { - switch(value){ - case 0: - return AVCaptureSessionPresetLow; - case 1: - return AVCaptureSessionPresetMedium; - case 2: - return AVCaptureSessionPresetHigh; - case 3: - return AVCaptureSessionPresetPhoto; - case 4: - return AVCaptureSessionPresetInputPriority; - case 6: - return AVCaptureSessionPreset1280x720; - case 7: - return AVCaptureSessionPreset1920x1080; - case 8: - return AVCaptureSessionPreset3840x2160; - case 9: - return AVCaptureSessionPresetiFrame960x540; - case 10: - return AVCaptureSessionPresetiFrame1280x720; - case 12: - return AVCaptureSessionPreset640x480; - case 13: - return AVCaptureSessionPreset352x288; - default: - return AVCaptureSessionPresetLow; - } -} - -+(NSInteger)NSIntegerWithAVCaptureSessionPreset:(AVCaptureSessionPreset)value { - if(value == AVCaptureSessionPresetLow) - return (NSInteger)0; - else if(value == AVCaptureSessionPresetMedium) - return (NSInteger)1; - else if(value == AVCaptureSessionPresetHigh) - return (NSInteger)2; - else if(value == AVCaptureSessionPresetPhoto) - return (NSInteger)3; - else if(value == AVCaptureSessionPresetInputPriority) - return (NSInteger)4; - else if(value == AVCaptureSessionPreset1280x720) - return (NSInteger)6; - else if(value == AVCaptureSessionPreset1920x1080) - return (NSInteger)7; - else if(value == AVCaptureSessionPreset3840x2160) - return (NSInteger)8; - else if(value == AVCaptureSessionPresetiFrame960x540) - return (NSInteger)9; - else if(value == AVCaptureSessionPresetiFrame1280x720) - return (NSInteger)10; - else if(value == AVCaptureSessionPreset640x480) - return (NSInteger)12; - else if(value == AVCaptureSessionPreset352x288) - return (NSInteger)13; - else - return (NSInteger)0; -} - -+(UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha { - unsigned int hexInt = [self intFromHexString:hexStr]; - UIColor *color = - [UIColor colorWithRed:((CGFloat) ((hexInt & 0xFF0000) >> 16))/255 - green:((CGFloat) ((hexInt & 0xFF00) >> 8))/255 - blue:((CGFloat) (hexInt & 0xFF))/255 - alpha:alpha]; - - return color; -} - -+ (NSString *)hexStringFromUIColor:(UIColor *)color { - const CGFloat *components = CGColorGetComponents(color.CGColor); - - CGFloat r = components[0]; - CGFloat g = components[1]; - CGFloat b = components[2]; - - return [NSString stringWithFormat:@"#%02lX%02lX%02lX", - lroundf(r * 255), - lroundf(g * 255), - lroundf(b * 255)]; -} - -+ (unsigned int)intFromHexString:(NSString *)hexStr { - unsigned int hexInt = 0; - NSScanner *scanner = [NSScanner scannerWithString:hexStr]; - [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; - [scanner scanHexInt:&hexInt]; - - return hexInt; -} - -+(CGLineCap)CGLineCapWithNSInteger:(NSInteger)value { - switch(value){ - case 0: - return kCGLineCapButt; - case 1: - return kCGLineCapRound; - case 2: - return kCGLineCapSquare; - default: - return kCGLineCapButt; - } -} - -+(NSInteger)NSIntegerWithCGLineCap:(CGLineCap)value { - switch(value){ - case kCGLineCapButt: - return (NSInteger)0; - case kCGLineCapRound: - return (NSInteger)1; - case kCGLineCapSquare: - return (NSInteger)2; - default: - return (NSInteger)0; - } -} - -+(UIInterfaceOrientationMask)UIInterfaceOrientationMaskWithNSInteger:(NSInteger)value { - switch(value){ - case 0: - return UIInterfaceOrientationMaskPortrait; - case 1: - return UIInterfaceOrientationMaskLandscapeLeft; - case 2: - return UIInterfaceOrientationMaskLandscapeRight; - case 3: - return UIInterfaceOrientationMaskPortraitUpsideDown; - case 4: - return UIInterfaceOrientationMaskLandscape; - case 5: - return UIInterfaceOrientationMaskAll; - case 6: - return UIInterfaceOrientationMaskAllButUpsideDown; - default: - return UIInterfaceOrientationMaskPortrait; - } -} - -+(NSInteger)NSIntegerWithUIInterfaceOrientationMask:(UIInterfaceOrientationMask)value { - switch(value){ - case UIInterfaceOrientationMaskPortrait: - return (NSInteger)0; - case UIInterfaceOrientationMaskLandscapeLeft: - return (NSInteger)1; - case UIInterfaceOrientationMaskLandscapeRight: - return (NSInteger)2; - case UIInterfaceOrientationMaskPortraitUpsideDown: - return (NSInteger)3; - case UIInterfaceOrientationMaskLandscape: - return (NSInteger)4; - case UIInterfaceOrientationMaskAll: - return (NSInteger)5; - case UIInterfaceOrientationMaskAllButUpsideDown: - return (NSInteger)6; - default: - return (NSInteger)0; - } -} - -+(AVCaptureDevicePosition)AVCaptureDevicePositionWithNSInteger:(NSInteger)value { - switch(value){ - case 0: - return AVCaptureDevicePositionFront; - case 1: - return AVCaptureDevicePositionBack; - case 2: - return AVCaptureDevicePositionUnspecified; - default: - return AVCaptureDevicePositionFront; - } -} - -+(NSNumber*)NSNumberWithRGLTextProcessing:(RGLTextProcessing*)value { - if(value == RGLTextProcessing.noChange) - return @0; - if(value == RGLTextProcessing.uppercase) - return @1; - if(value == RGLTextProcessing.lowercase) - return @2; - if(value == RGLTextProcessing.capital) - return @3; - return @0; -} - -+(RGLTextProcessing*)RGLTextProcessingWithNSInteger:(NSNumber*)value { - switch([value integerValue]){ - case 0: - return RGLTextProcessing.noChange; - case 1: - return RGLTextProcessing.uppercase; - case 2: - return RGLTextProcessing.lowercase; - case 3: - return RGLTextProcessing.capital; - default: - return RGLTextProcessing.noChange; - } -} - -+(NSInteger)NSIntegerWithAVCaptureDevicePosition:(AVCaptureDevicePosition)value { - switch(value){ - case AVCaptureDevicePositionFront: - return (NSInteger)0; - case AVCaptureDevicePositionBack: - return (NSInteger)1; - case AVCaptureDevicePositionUnspecified: - return (NSInteger)2; - default: - return (NSInteger)0; - } -} - -+(UIViewContentMode)UIViewContentModeWithNSInteger:(NSInteger)value { - switch(value){ - case 0: - return UIViewContentModeScaleToFill; - case 1: - return UIViewContentModeScaleAspectFit; - case 2: - return UIViewContentModeScaleAspectFill; - case 3: - return UIViewContentModeRedraw; - case 4: - return UIViewContentModeCenter; - case 5: - return UIViewContentModeTop; - case 6: - return UIViewContentModeBottom; - case 7: - return UIViewContentModeLeft; - case 8: - return UIViewContentModeRight; - case 9: - return UIViewContentModeTopLeft; - case 10: - return UIViewContentModeTopRight; - case 11: - return UIViewContentModeBottomLeft; - case 12: - return UIViewContentModeBottomRight; - default: - return UIViewContentModeScaleToFill; - } -} - -+(NSInteger)NSIntegerWithUIViewContentMode:(UIViewContentMode)value { - switch(value){ - case UIViewContentModeScaleToFill: - return (NSInteger)0; - case UIViewContentModeScaleAspectFit: - return (NSInteger)1; - case UIViewContentModeScaleAspectFill: - return (NSInteger)2; - case UIViewContentModeRedraw: - return (NSInteger)3; - case UIViewContentModeCenter: - return (NSInteger)4; - case UIViewContentModeTop: - return (NSInteger)5; - case UIViewContentModeBottom: - return (NSInteger)6; - case UIViewContentModeLeft: - return (NSInteger)7; - case UIViewContentModeRight: - return (NSInteger)8; - case UIViewContentModeTopLeft: - return (NSInteger)9; - case UIViewContentModeTopRight: - return (NSInteger)10; - case UIViewContentModeBottomLeft: - return (NSInteger)11; - case UIViewContentModeBottomRight: - return (NSInteger)12; - default: - return (NSInteger)0; - } -} - -+(RGLImageQA*)ImageQAFromJson:(NSDictionary*)dict { - RGLImageQA *image = [RGLImageQA new]; - - if([dict valueForKey:@"dpiThreshold"] != nil) - image.dpiThreshold = [dict valueForKey:@"dpiThreshold"]; - if([dict valueForKey:@"angleThreshold"] != nil) - image.angleThreshold = [dict valueForKey:@"angleThreshold"]; - if([dict valueForKey:@"focusCheck"] != nil) - image.focusCheck = [dict valueForKey:@"focusCheck"]; - if([dict valueForKey:@"glaresCheck"] != nil) - image.glaresCheck = [dict valueForKey:@"glaresCheck"]; - if([dict valueForKey:@"colornessCheck"] != nil) - image.colornessCheck = [dict valueForKey:@"colornessCheck"]; - if([dict valueForKey:@"moireCheck"] != nil) - image.moireCheck = [dict valueForKey:@"moireCheck"]; - if([dict valueForKey:@"expectedPass"] != nil){ - NSMutableArray *expectedPass = [NSMutableArray new]; - for(NSNumber* item in [dict valueForKey:@"expectedPass"]) - [expectedPass addObject:[self RGLImageQualityCheckTypeWithNSNumber: item]]; - image.expectedPass = expectedPass; - } - if([dict valueForKey:@"documentPositionIndent"] != nil) - image.documentPositionIndent = [dict valueForKey:@"documentPositionIndent"]; - - return image; -} - -+(NSDictionary*)ImageQAToJson:(RGLImageQA*)input { - NSMutableDictionary *result = [NSMutableDictionary new]; - if(input == nil) return result; - - result[@"dpiThreshold"] = input.dpiThreshold; - result[@"angleThreshold"] = input.angleThreshold; - result[@"focusCheck"] = input.focusCheck; - result[@"glaresCheck"] = input.glaresCheck; - result[@"colornessCheck"] = input.colornessCheck; - result[@"moireCheck"] = input.moireCheck; - if(input.expectedPass != nil) { - NSMutableArray* array = [NSMutableArray new]; - for(RGLImageQualityCheckType item in input.expectedPass) - [array addObject:[self NSNumberWithRGLImageQualityCheckType:item]]; - result[@"expectedPass"] = array; - } else result[@"expectedPass"] = nil; - result[@"documentPositionIndent"] = input.documentPositionIndent; - - return result; -} - -+(NSNumber*)NSNumberWithRGLImageQualityCheckType:(RGLImageQualityCheckType)value { - if(value == RGLImageQualityCheckTypeImageGlares) return @0; - if(value == RGLImageQualityCheckTypeImageFocus) return @1; - if(value == RGLImageQualityCheckTypeImageResolution) return @2; - if(value == RGLImageQualityCheckTypeImageColorness) return @3; - if(value == RGLImageQualityCheckTypeImagePerspective) return @4; - if(value == RGLImageQualityCheckTypeImageBounds) return @5; - if(value == RGLImageQualityCheckTypeScreenCapture) return @6; - if(value == RGLImageQualityCheckTypePortrait) return @7; - if(value == RGLImageQualityCheckTypeHandwritten) return @8; - return 0; -} - -+(RGLImageQualityCheckType)RGLImageQualityCheckTypeWithNSNumber:(NSNumber*)input { - int value = [input intValue]; - if(value == 0) return RGLImageQualityCheckTypeImageGlares; - if(value == 1) return RGLImageQualityCheckTypeImageFocus; - if(value == 2) return RGLImageQualityCheckTypeImageResolution; - if(value == 3) return RGLImageQualityCheckTypeImageColorness; - if(value == 4) return RGLImageQualityCheckTypeImagePerspective; - if(value == 5) return RGLImageQualityCheckTypeImageBounds; - if(value == 6) return RGLImageQualityCheckTypeScreenCapture; - if(value == 7) return RGLImageQualityCheckTypePortrait; - if(value == 8) return RGLImageQualityCheckTypeHandwritten; - return RGLImageQualityCheckTypeImageGlares; -} - -+(RGLePassportDataGroup*)RGLePassportDataGroupFromJson:(NSDictionary*)dict { - RGLePassportDataGroup *group = [[RGLePassportDataGroup alloc] init]; - - if([dict valueForKey:@"DG1"] != nil) - group.dG1 = [[dict valueForKey:@"DG1"] boolValue]; - if([dict valueForKey:@"DG2"] != nil) - group.dG2 = [[dict valueForKey:@"DG2"] boolValue]; - if([dict valueForKey:@"DG3"] != nil) - group.dG3 = [[dict valueForKey:@"DG3"] boolValue]; - if([dict valueForKey:@"DG4"] != nil) - group.dG4 = [[dict valueForKey:@"DG4"] boolValue]; - if([dict valueForKey:@"DG5"] != nil) - group.dG5 = [[dict valueForKey:@"DG5"] boolValue]; - if([dict valueForKey:@"DG6"] != nil) - group.dG6 = [[dict valueForKey:@"DG6"] boolValue]; - if([dict valueForKey:@"DG7"] != nil) - group.dG7 = [[dict valueForKey:@"DG7"] boolValue]; - if([dict valueForKey:@"DG8"] != nil) - group.dG8 = [[dict valueForKey:@"DG8"] boolValue]; - if([dict valueForKey:@"DG9"] != nil) - group.dG9 = [[dict valueForKey:@"DG9"] boolValue]; - if([dict valueForKey:@"DG10"] != nil) - group.dG10 = [[dict valueForKey:@"DG10"] boolValue]; - if([dict valueForKey:@"DG11"] != nil) - group.dG11 = [[dict valueForKey:@"DG11"] boolValue]; - if([dict valueForKey:@"DG12"] != nil) - group.dG12 = [[dict valueForKey:@"DG12"] boolValue]; - if([dict valueForKey:@"DG13"] != nil) - group.dG13 = [[dict valueForKey:@"DG13"] boolValue]; - if([dict valueForKey:@"DG14"] != nil) - group.dG14 = [[dict valueForKey:@"DG14"] boolValue]; - if([dict valueForKey:@"DG15"] != nil) - group.dG15 = [[dict valueForKey:@"DG15"] boolValue]; - if([dict valueForKey:@"DG16"] != nil) - group.dG16 = [[dict valueForKey:@"DG16"] boolValue]; - - return group; -} - -+(RGLeIDDataGroup*)RGLeIDDataGroupFromJson:(NSDictionary*)dict { - RGLeIDDataGroup *group = [[RGLeIDDataGroup alloc] init]; - - if([dict valueForKey:@"DG1"] != nil) - group.dG1 = [[dict valueForKey:@"DG1"] boolValue]; - if([dict valueForKey:@"DG2"] != nil) - group.dG2 = [[dict valueForKey:@"DG2"] boolValue]; - if([dict valueForKey:@"DG3"] != nil) - group.dG3 = [[dict valueForKey:@"DG3"] boolValue]; - if([dict valueForKey:@"DG4"] != nil) - group.dG4 = [[dict valueForKey:@"DG4"] boolValue]; - if([dict valueForKey:@"DG5"] != nil) - group.dG5 = [[dict valueForKey:@"DG5"] boolValue]; - if([dict valueForKey:@"DG6"] != nil) - group.dG6 = [[dict valueForKey:@"DG6"] boolValue]; - if([dict valueForKey:@"DG7"] != nil) - group.dG7 = [[dict valueForKey:@"DG7"] boolValue]; - if([dict valueForKey:@"DG8"] != nil) - group.dG8 = [[dict valueForKey:@"DG8"] boolValue]; - if([dict valueForKey:@"DG9"] != nil) - group.dG9 = [[dict valueForKey:@"DG9"] boolValue]; - if([dict valueForKey:@"DG10"] != nil) - group.dG10 = [[dict valueForKey:@"DG10"] boolValue]; - if([dict valueForKey:@"DG11"] != nil) - group.dG11 = [[dict valueForKey:@"DG11"] boolValue]; - if([dict valueForKey:@"DG12"] != nil) - group.dG12 = [[dict valueForKey:@"DG12"] boolValue]; - if([dict valueForKey:@"DG13"] != nil) - group.dG13 = [[dict valueForKey:@"DG13"] boolValue]; - if([dict valueForKey:@"DG14"] != nil) - group.dG14 = [[dict valueForKey:@"DG14"] boolValue]; - if([dict valueForKey:@"DG15"] != nil) - group.dG15 = [[dict valueForKey:@"DG15"] boolValue]; - if([dict valueForKey:@"DG16"] != nil) - group.dG16 = [[dict valueForKey:@"DG16"] boolValue]; - if([dict valueForKey:@"DG17"] != nil) - group.dG17 = [[dict valueForKey:@"DG17"] boolValue]; - if([dict valueForKey:@"DG18"] != nil) - group.dG18 = [[dict valueForKey:@"DG18"] boolValue]; - if([dict valueForKey:@"DG19"] != nil) - group.dG19 = [[dict valueForKey:@"DG19"] boolValue]; - if([dict valueForKey:@"DG20"] != nil) - group.dG20 = [[dict valueForKey:@"DG20"] boolValue]; - if([dict valueForKey:@"DG21"] != nil) - group.dG21 = [[dict valueForKey:@"DG21"] boolValue]; - - return group; -} - -+(RGLeDLDataGroup*)RGLeDLDataGroupFromJson:(NSDictionary*)dict { - RGLeDLDataGroup *group = [[RGLeDLDataGroup alloc] init]; - - if([dict valueForKey:@"DG1"] != nil) - group.dG1 = [[dict valueForKey:@"DG1"] boolValue]; - if([dict valueForKey:@"DG2"] != nil) - group.dG2 = [[dict valueForKey:@"DG2"] boolValue]; - if([dict valueForKey:@"DG3"] != nil) - group.dG3 = [[dict valueForKey:@"DG3"] boolValue]; - if([dict valueForKey:@"DG4"] != nil) - group.dG4 = [[dict valueForKey:@"DG4"] boolValue]; - if([dict valueForKey:@"DG5"] != nil) - group.dG5 = [[dict valueForKey:@"DG5"] boolValue]; - if([dict valueForKey:@"DG6"] != nil) - group.dG6 = [[dict valueForKey:@"DG6"] boolValue]; - if([dict valueForKey:@"DG7"] != nil) - group.dG7 = [[dict valueForKey:@"DG7"] boolValue]; - if([dict valueForKey:@"DG8"] != nil) - group.dG8 = [[dict valueForKey:@"DG8"] boolValue]; - if([dict valueForKey:@"DG9"] != nil) - group.dG9 = [[dict valueForKey:@"DG9"] boolValue]; - if([dict valueForKey:@"DG10"] != nil) - group.dG10 = [[dict valueForKey:@"DG10"] boolValue]; - if([dict valueForKey:@"DG11"] != nil) - group.dG11 = [[dict valueForKey:@"DG11"] boolValue]; - if([dict valueForKey:@"DG12"] != nil) - group.dG12 = [[dict valueForKey:@"DG12"] boolValue]; - if([dict valueForKey:@"DG13"] != nil) - group.dG13 = [[dict valueForKey:@"DG13"] boolValue]; - if([dict valueForKey:@"DG14"] != nil) - group.dG14 = [[dict valueForKey:@"DG14"] boolValue]; - - return group; -} - -+(RGLOnlineProcessingConfig*)RGLOnlineProcessingConfigFromJSON:(NSDictionary*)dict { - if(dict == nil) return nil; - if([dict valueForKey:@"mode"] == nil) return nil; - - RGLOnlineProcessingConfig *result = [[RGLOnlineProcessingConfig alloc] initWithMode:[[dict valueForKey:@"mode"] integerValue]]; - if([dict valueForKey:@"url"] != nil) - result.serviceURL = [dict valueForKey:@"url"]; - - if([dict valueForKey:@"imageFormat"] != nil) - result.imageFormat = [[dict valueForKey:@"imageFormat"] integerValue]; - if([dict valueForKey:@"url"] != nil) - result.serviceURL = [dict valueForKey:@"url"]; - if([dict valueForKey:@"imageCompressionQuality"] != nil) - result.imageCompressionQuality = [[dict valueForKey:@"imageCompressionQuality"] floatValue]; - if([dict valueForKey:@"processParams"] != nil) { - RGLProcessParams *params = [RGLProcessParams new]; - [self setProcessParams:[dict valueForKey:@"processParams"] :params]; - result.processParams = params; - } - - return result; -} - -+(RGLReprocParams*)RGLReprocParamsFromJSON:(NSDictionary*)dict { - RGLReprocParams *result = [RGLReprocParams new]; - - if([dict valueForKey:@"serviceUrl"] != nil) - result.serviceURL = [dict valueForKey:@"serviceUrl"]; - if([dict valueForKey:@"failIfNoService"] != nil) - result.failIfNoService = [dict valueForKey:@"failIfNoService"]; - if([dict valueForKey:@"httpHeaders"] != nil) - result.httpHeaders = [dict valueForKey:@"httpHeaders"]; - - return result; -} - -+(void)setCustomization:(NSDictionary*)options :(RGLCustomization*)customization { - if([options valueForKey:@"cameraFrameBorderWidth"] != nil) - customization.cameraFrameBorderWidth = [[options valueForKey:@"cameraFrameBorderWidth"] floatValue]; - if([options valueForKey:@"cameraFrameDefaultColor"] != nil) - customization.cameraFrameDefaultColor = [self getUIColorObjectFromHexString:[options valueForKey:@"cameraFrameDefaultColor"] alpha:1]; - if([options valueForKey:@"cameraFrameActiveColor"] != nil) - customization.cameraFrameActiveColor = [self getUIColorObjectFromHexString:[options valueForKey:@"cameraFrameActiveColor"] alpha:1]; - if([options valueForKey:@"cameraFrameShapeType"] != nil) - customization.cameraFrameShapeType = [[options valueForKey:@"cameraFrameShapeType"] integerValue]; - if([options valueForKey:@"cameraFrameLineLength"] != nil) - customization.cameraFrameLineLength = [[options valueForKey:@"cameraFrameLineLength"] integerValue]; - if([options valueForKey:@"status"] != nil) - customization.status = [options valueForKey:@"status"]; - if([options valueForKey:@"showStatusMessages"] != nil) - customization.showStatusMessages = [[options valueForKey:@"showStatusMessages"] boolValue]; - if([options valueForKey:@"statusTextFont"] != nil) - customization.statusTextFont = [UIFont fontWithName:[options valueForKey:@"statusTextFont"] size:[options valueForKey:@"statusTextSize"] == nil ? 17 : [[options valueForKey:@"statusTextSize"] floatValue]]; - if([options valueForKey:@"statusTextColor"] != nil) - customization.statusTextColor = [self getUIColorObjectFromHexString:[options valueForKey:@"statusTextColor"] alpha:1]; - if([options valueForKey:@"statusPositionMultiplier"] != nil) - customization.statusPositionMultiplier = [[options valueForKey:@"statusPositionMultiplier"] doubleValue]; - if([options valueForKey:@"showResultStatusMessages"] != nil) - customization.showResultStatusMessages = [[options valueForKey:@"showResultStatusMessages"] boolValue]; - if([options valueForKey:@"resultStatus"] != nil) - customization.resultStatus = [options valueForKey:@"resultStatus"]; - if([options valueForKey:@"resultStatusTextFont"] != nil) - customization.resultStatusTextFont = [UIFont fontWithName:[options valueForKey:@"resultStatusTextFont"] size:[options valueForKey:@"resultStatusTextSize"] == nil ? 17 : [[options valueForKey:@"resultStatusTextSize"] floatValue]]; - if([options valueForKey:@"resultStatusTextColor"] != nil) - customization.resultStatusTextColor = [self getUIColorObjectFromHexString:[options valueForKey:@"resultStatusTextColor"] alpha:1]; - if([options valueForKey:@"resultStatusBackgroundColor"] != nil) - customization.resultStatusBackgroundColor = [self getUIColorObjectFromHexString:[options valueForKey:@"resultStatusBackgroundColor"] alpha:1]; - if([options valueForKey:@"resultStatusPositionMultiplier"] != nil) - customization.resultStatusPositionMultiplier = [[options valueForKey:@"resultStatusPositionMultiplier"] doubleValue]; - if([options valueForKey:@"showHelpAnimation"] != nil) - customization.showHelpAnimation = [[options valueForKey:@"showHelpAnimation"] boolValue]; - if([options valueForKey:@"showNextPageAnimation"] != nil) - customization.showNextPageAnimation = [[options valueForKey:@"showNextPageAnimation"] boolValue]; - if([options valueForKey:@"helpAnimationImage"] != nil) - customization.helpAnimationImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"helpAnimationImage"]]; - if([options valueForKey:@"multipageAnimationFrontImage"] != nil) - customization.multipageAnimationFrontImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"multipageAnimationFrontImage"]]; - if([options valueForKey:@"multipageAnimationBackImage"] != nil) - customization.multipageAnimationBackImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"multipageAnimationBackImage"]]; - if([options valueForKey:@"tintColor"] != nil) - customization.tintColor = [self getUIColorObjectFromHexString:[options valueForKey:@"tintColor"] alpha:1]; - if([options valueForKey:@"multipageButtonBackgroundColor"] != nil) - customization.multipageButtonBackgroundColor = [self getUIColorObjectFromHexString:[options valueForKey:@"multipageButtonBackgroundColor"] alpha:1]; - if([options valueForKey:@"activityIndicatorColor"] != nil) - customization.activityIndicatorColor = [self getUIColorObjectFromHexString:[options valueForKey:@"activityIndicatorColor"] alpha:1]; - if([options valueForKey:@"showBackgroundMask"] != nil) - customization.showBackgroundMask = [[options valueForKey:@"showBackgroundMask"] boolValue]; - if([options valueForKey:@"borderBackgroundImage"] != nil) - customization.borderBackgroundImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"borderBackgroundImage"]]; - if([options valueForKey:@"backgroundMaskAlpha"] != nil) - customization.backgroundMaskAlpha = [[options valueForKey:@"backgroundMaskAlpha"] floatValue]; - if([options valueForKey:@"helpAnimationImageContentMode"] != nil) - customization.helpAnimationImageContentMode = [self UIViewContentModeWithNSInteger:[[options valueForKey:@"helpAnimationImageContentMode"] integerValue]]; - if([options valueForKey:@"multipageAnimationFrontImageContentMode"] != nil) - customization.multipageAnimationFrontImageContentMode = [self UIViewContentModeWithNSInteger:[[options valueForKey:@"multipageAnimationFrontImageContentMode"] integerValue]]; - if([options valueForKey:@"multipageAnimationBackImageContentMode"] != nil) - customization.multipageAnimationBackImageContentMode = [self UIViewContentModeWithNSInteger:[[options valueForKey:@"multipageAnimationBackImageContentMode"] integerValue]]; - if([options valueForKey:@"borderBackgroundImageContentMode"] != nil) - customization.borderBackgroundImageContentMode = [self UIViewContentModeWithNSInteger:[[options valueForKey:@"borderBackgroundImageContentMode"] integerValue]]; - if([options valueForKey:@"cameraFrameVerticalPositionMultiplier"] != nil) - customization.cameraFrameVerticalPositionMultiplier = [[options valueForKey:@"cameraFrameVerticalPositionMultiplier"] floatValue]; - if([options valueForKey:@"customStatusPositionMultiplier"] != nil) - customization.customStatusPositionMultiplier = [[options valueForKey:@"customStatusPositionMultiplier"] floatValue]; - if([options valueForKey:@"customLabelStatus"] != nil) - customization.customLabelStatus = [[NSAttributedString alloc]initWithString:[options valueForKey:@"customLabelStatus"]]; - if([options valueForKey:@"cameraFrameCornerRadius"] != nil) - customization.cameraFrameCornerRadius = [[options valueForKey:@"cameraFrameCornerRadius"] floatValue]; - if([options valueForKey:@"torchButtonOnImage"] != nil) - customization.torchButtonOnImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"torchButtonOnImage"]]; - if([options valueForKey:@"torchButtonOffImage"] != nil) - customization.torchButtonOffImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"torchButtonOffImage"]]; - if([options valueForKey:@"closeButtonImage"] != nil) - customization.closeButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"closeButtonImage"]]; - if([options valueForKey:@"captureButtonImage"] != nil) - customization.captureButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"captureButtonImage"]]; - if([options valueForKey:@"changeFrameButtonCollapseImage"] != nil) - customization.changeFrameButtonCollapseImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"changeFrameButtonCollapseImage"]]; - if([options valueForKey:@"changeFrameButtonExpandImage"] != nil) - customization.changeFrameButtonExpandImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"changeFrameButtonExpandImage"]]; - if([options valueForKey:@"cameraSwitchButtonImage"] != nil) - customization.cameraSwitchButtonImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"cameraSwitchButtonImage"]]; - if([options valueForKey:@"cameraFrameLineCap"] != nil) - customization.cameraFrameLineCap = [self CGLineCapWithNSInteger:[[options valueForKey:@"cameraFrameLineCap"] integerValue]]; - if([options valueForKey:@"cameraFrameOffsetWidth"] != nil) - customization.cameraFrameOffsetWidth = [[options valueForKey:@"cameraFrameOffsetWidth"] floatValue]; - if([options valueForKey:@"cameraFramePortraitAspectRatio"] != nil) - customization.cameraFramePortraitAspectRatio = [[options valueForKey:@"cameraFramePortraitAspectRatio"] floatValue]; - if([options valueForKey:@"cameraFrameLandscapeAspectRatio"] != nil) - customization.cameraFrameLandscapeAspectRatio = [[options valueForKey:@"cameraFrameLandscapeAspectRatio"] floatValue]; - if([options valueForKey:@"toolbarSize"] != nil) - customization.toolbarSize = [[options valueForKey:@"toolbarSize"] floatValue]; - if([options valueForKey:@"statusBackgroundColor"] != nil) - customization.statusBackgroundColor = [self getUIColorObjectFromHexString:[options valueForKey:@"statusBackgroundColor"] alpha:1]; - if([options valueForKey:@"cameraPreviewBackgroundColor"] != nil) - customization.cameraPreviewBackgroundColor = [self getUIColorObjectFromHexString:[options valueForKey:@"cameraPreviewBackgroundColor"] alpha:1]; - if([options valueForKey:@"hologramAnimationImageContentMode"] != nil) - customization.hologramAnimationImageContentMode = [self UIViewContentModeWithNSInteger:[[options valueForKey:@"hologramAnimationImageContentMode"] integerValue]]; - if([options valueForKey:@"hologramAnimationPositionMultiplier"] != nil) - customization.hologramAnimationPositionMultiplier = [[options valueForKey:@"hologramAnimationPositionMultiplier"] floatValue]; - if([options valueForKey:@"hologramAnimationImage"] != nil) - customization.hologramAnimationImage = [RGLWJSONConstructor imageWithBase64:[options valueForKey:@"hologramAnimationImage"]]; - if([options valueForKey:@"uiCustomizationLayer"] != nil) - customization.customUILayerJSON = [options valueForKey:@"uiCustomizationLayer"]; -} - -+(void)setFunctionality:(NSDictionary*)options :(RGLFunctionality*)functionality { - if([options valueForKey:@"cameraFrame"] != nil){ - NSString *enumFromAndroid = [options valueForKey:@"cameraFrame"]; - if([enumFromAndroid isEqual: @"id1"]) - functionality.cameraFrame = 0; - if([enumFromAndroid isEqual: @"max"]) - functionality.cameraFrame = 1; - if([enumFromAndroid isEqual: @"none"]) - functionality.cameraFrame = 2; - if([enumFromAndroid isEqual: @"document"]) - functionality.cameraFrame = 3; - } - if([options valueForKey:@"showTorchButton"] != nil) - functionality.showTorchButton = [[options valueForKey:@"showTorchButton"] boolValue]; - if([options valueForKey:@"showCloseButton"] != nil) - functionality.showCloseButton = [[options valueForKey:@"showCloseButton"] boolValue]; - if([options valueForKey:@"showCaptureButton"] != nil) - functionality.showCaptureButton = [[options valueForKey:@"showCaptureButton"] boolValue]; - if([options valueForKey:@"showChangeFrameButton"] != nil) - functionality.showChangeFrameButton = [[options valueForKey:@"showChangeFrameButton"] boolValue]; - if([options valueForKey:@"showSkipNextPageButton"] != nil) - functionality.showSkipNextPageButton = [[options valueForKey:@"showSkipNextPageButton"] boolValue]; - if([options valueForKey:@"showCameraSwitchButton"] != nil) - functionality.showCameraSwitchButton = [[options valueForKey:@"showCameraSwitchButton"] boolValue]; - if([options valueForKey:@"videoCaptureMotionControl"] != nil) - functionality.videoCaptureMotionControl = [[options valueForKey:@"videoCaptureMotionControl"] boolValue]; - if([options valueForKey:@"skipFocusingFrames"] != nil) - functionality.skipFocusingFrames = [[options valueForKey:@"skipFocusingFrames"] boolValue]; - if([options valueForKey:@"orientation"] != nil) - functionality.orientation = [self UIInterfaceOrientationMaskWithNSInteger:[[options valueForKey:@"orientation"] integerValue]]; - if([options valueForKey:@"videoSessionPreset"] != nil) - functionality.videoSessionPreset = [self AVCaptureSessionPresetWithNSInteger:[[options valueForKey:@"videoSessionPreset"] integerValue]]; - if([options valueForKey:@"singleResult"] != nil) - functionality.singleResult = [[options valueForKey:@"singleResult"] boolValue]; - if([options valueForKey:@"cameraPosition"] != nil) - functionality.cameraPosition = [self AVCaptureDevicePositionWithNSInteger:[[options valueForKey:@"cameraPosition"] integerValue]]; - if([options valueForKey:@"btDeviceName"] != nil) - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - functionality.btDeviceName = [options valueForKey:@"btDeviceName"]; - #pragma clang diagnostic pop - if([options valueForKey:@"useAuthenticator"] != nil) - functionality.useAuthenticator = [[options valueForKey:@"useAuthenticator"] boolValue]; - if([options valueForKey:@"showCaptureButtonDelayFromDetect"] != nil) - functionality.showCaptureButtonDelayFromDetect = [[options valueForKey:@"showCaptureButtonDelayFromDetect"] doubleValue]; - if([options valueForKey:@"showCaptureButtonDelayFromStart"] != nil) - functionality.showCaptureButtonDelayFromStart = [[options valueForKey:@"showCaptureButtonDelayFromStart"] doubleValue]; - if([options valueForKey:@"captureMode"] != nil) - functionality.captureMode = [[options valueForKey:@"captureMode"] intValue]; - if([options valueForKey:@"displayMetadata"] != nil) - functionality.showMetadataInfo = [[options valueForKey:@"displayMetadata"] boolValue]; - if([options valueForKey:@"isZoomEnabled"] != nil) - functionality.isZoomEnabled = [[options valueForKey:@"isZoomEnabled"] boolValue]; - if([options valueForKey:@"zoomFactor"] != nil) - functionality.zoomFactor = [[options valueForKey:@"zoomFactor"] floatValue]; - if([options valueForKey:@"recordScanningProcess"] != nil) - functionality.recordScanningProcess = [[options valueForKey:@"recordScanningProcess"] boolValue]; - if([options valueForKey:@"manualMultipageMode"] != nil) - functionality.manualMultipageMode = [[options valueForKey:@"manualMultipageMode"] boolValue]; - if([options valueForKey:@"videoOutputSettings"] != nil) - functionality.videoOutputSettings = [options valueForKey:@"videoOutputSettings"]; - if([options valueForKey:@"onlineProcessingConfiguration"] != nil) - functionality.onlineProcessingConfig = [self RGLOnlineProcessingConfigFromJSON:[options valueForKey:@"onlineProcessingConfiguration"]];; -} - -+(void)setProcessParams:(NSDictionary*)options :(RGLProcessParams*)processParams { - if([options valueForKey:@"multipageProcessing"] != nil) - processParams.multipageProcessing = [NSNumber numberWithBool:[[options valueForKey:@"multipageProcessing"] boolValue]]; - if([options valueForKey:@"dateFormat"] != nil) - processParams.dateFormat = [options valueForKey:@"dateFormat"]; - if([options valueForKey:@"logs"] != nil) - processParams.logs = [NSNumber numberWithBool:[[options valueForKey:@"logs"] boolValue]]; - if([options valueForKey:@"debugSaveImages"] != nil) - processParams.debugSaveImages = [NSNumber numberWithBool:[[options valueForKey:@"debugSaveImages"] boolValue]]; - if([options valueForKey:@"debugSaveCroppedImages"] != nil) - processParams.debugSaveCroppedImages = [NSNumber numberWithBool:[[options valueForKey:@"debugSaveCroppedImages"] boolValue]]; - if([options valueForKey:@"debugSaveLogs"] != nil) - processParams.debugSaveLogs = [NSNumber numberWithBool:[[options valueForKey:@"debugSaveLogs"] boolValue]]; - if([options valueForKey:@"scenario"] != nil) - processParams.scenario = [options valueForKey:@"scenario"]; - if([options valueForKey:@"barcodeTypes"] != nil) - processParams.barcodeTypes = [options valueForKey:@"barcodeTypes"]; - if([options valueForKey:@"documentIDList"] != nil) - processParams.documentIDList = [options valueForKey:@"documentIDList"]; - if([options valueForKey:@"fieldTypesFilter"] != nil) - processParams.fieldTypesFilter = [options valueForKey:@"fieldTypesFilter"]; - if([options valueForKey:@"disableFocusingCheck"] != nil) - processParams.disableFocusingCheck = [NSNumber numberWithBool:[[options valueForKey:@"disableFocusingCheck"] boolValue]]; - if([options valueForKey:@"captureButtonScenario"] != nil) - processParams.captureButtonScenario = [options valueForKey:@"captureButtonScenario"]; - if([options valueForKey:@"measureSystem"] != nil) - processParams.measureSystem = [[options valueForKey:@"measureSystem"] integerValue]; - if([options valueForKey:@"returnUncroppedImage"] != nil) - processParams.returnUncroppedImage = [NSNumber numberWithBool:[[options valueForKey:@"returnUncroppedImage"] boolValue]]; - if([options valueForKey:@"customParams"] != nil) - processParams.customParams = [options objectForKey:@"customParams"]; - if([options valueForKey:@"debugSaveRFIDSession"] != nil) - processParams.debugSaveRFIDSession = [NSNumber numberWithBool:[[options valueForKey:@"debugSaveRFIDSession"] boolValue]]; - if([options valueForKey:@"doublePageSpread"] != nil) - processParams.doublePageSpread = [NSNumber numberWithBool:[[options valueForKey:@"doublePageSpread"] boolValue]]; - if([options valueForKey:@"barcodeParserType"] != nil) - processParams.barcodeParserType = [NSNumber numberWithInteger:[[options valueForKey:@"barcodeParserType"] integerValue]]; - if([options valueForKey:@"timeout"] != nil) - processParams.timeout = [NSNumber numberWithDouble:[[options valueForKey:@"timeout"] doubleValue]]; - if([options valueForKey:@"timeoutFromFirstDetect"] != nil) - processParams.timeoutFromFirstDetect = [NSNumber numberWithDouble:[[options valueForKey:@"timeoutFromFirstDetect"] doubleValue]]; - if([options valueForKey:@"timeoutFromFirstDocType"] != nil) - processParams.timeoutFromFirstDocType = [NSNumber numberWithDouble:[[options valueForKey:@"timeoutFromFirstDocType"] doubleValue]]; - if([options valueForKey:@"manualCrop"] != nil) - processParams.manualCrop = [NSNumber numberWithBool:[[options valueForKey:@"manualCrop"] boolValue]]; - if([options valueForKey:@"perspectiveAngle"] != nil) - processParams.perspectiveAngle = [NSNumber numberWithInteger:[[options valueForKey:@"perspectiveAngle"] integerValue]]; - if([options valueForKey:@"minDPI"] != nil) - processParams.minDPI = [NSNumber numberWithInteger:[[options valueForKey:@"minDPI"] integerValue]]; - if([options valueForKey:@"integralImage"] != nil) - processParams.integralImage = [NSNumber numberWithBool:[[options valueForKey:@"integralImage"] boolValue]]; - if([options valueForKey:@"returnCroppedBarcode"] != nil) - processParams.returnCroppedBarcode = [NSNumber numberWithBool:[[options valueForKey:@"returnCroppedBarcode"] boolValue]]; - if([options valueForKey:@"checkHologram"] != nil) - processParams.checkHologram = [NSNumber numberWithBool:[[options valueForKey:@"checkHologram"] boolValue]]; - if([options valueForKey:@"checkRequiredTextFields"] != nil) - processParams.checkRequiredTextFields = [NSNumber numberWithBool:[[options valueForKey:@"checkRequiredTextFields"] boolValue]]; - if([options valueForKey:@"depersonalizeLog"] != nil) - processParams.depersonalizeLog = [options valueForKey:@"depersonalizeLog"]; - if([options valueForKey:@"resultTypeOutput"] != nil) - processParams.resultTypeOutput = [options valueForKey:@"resultTypeOutput"]; - if([options valueForKey:@"generateDoublePageSpreadImage"] != nil) - processParams.generateDoublePageSpreadImage = [options valueForKey:@"generateDoublePageSpreadImage"]; - if([options valueForKey:@"imageDpiOutMax"] != nil) - processParams.imageDpiOutMax = [options valueForKey:@"imageDpiOutMax"]; - if([options valueForKey:@"alreadyCropped"] != nil) - processParams.alreadyCropped = [options valueForKey:@"alreadyCropped"]; - if([options valueForKey:@"forceDocID"] != nil) - processParams.forceDocID = [options valueForKey:@"forceDocID"]; - if([options valueForKey:@"matchTextFieldMask"] != nil) - processParams.matchTextFieldMask = [options valueForKey:@"matchTextFieldMask"]; - if([options valueForKey:@"fastDocDetect"] != nil) - processParams.fastDocDetect = [options valueForKey:@"fastDocDetect"]; - if([options valueForKey:@"updateOCRValidityByGlare"] != nil) - processParams.updateOCRValidityByGlare = [options valueForKey:@"updateOCRValidityByGlare"]; - if([options valueForKey:@"imageQA"] != nil) - processParams.imageQA = [RGLWRegulaConfig ImageQAFromJson:[options valueForKey:@"imageQA"]]; - if([options valueForKey:@"forceDocFormat"] != nil) - processParams.forceDocFormat = [options valueForKey:@"forceDocFormat"]; - if([options valueForKey:@"noGraphics"] != nil) - processParams.noGraphics = [options valueForKey:@"noGraphics"]; - if([options valueForKey:@"documentAreaMin"] != nil) - processParams.documentAreaMin = [options valueForKey:@"documentAreaMin"]; - if([options valueForKey:@"multiDocOnImage"] != nil) - processParams.multiDocOnImage = [options valueForKey:@"multiDocOnImage"]; - if([options valueForKey:@"shiftExpiryDate"] != nil) - processParams.shiftExpiryDate = [options valueForKey:@"shiftExpiryDate"]; - if([options valueForKey:@"minimalHolderAge"] != nil) - processParams.minimalHolderAge = [options valueForKey:@"minimalHolderAge"]; - if([options valueForKey:@"mrzFormatsFilter"] != nil) - processParams.mrzFormatsFilter = [options valueForKey:@"mrzFormatsFilter"]; - if([options valueForKey:@"forceReadMrzBeforeLocate"] != nil) - processParams.forceReadMrzBeforeLocate = [options valueForKey:@"forceReadMrzBeforeLocate"]; - if([options valueForKey:@"parseBarcodes"] != nil) - processParams.parseBarcodes = [options valueForKey:@"parseBarcodes"]; - if([options valueForKey:@"shouldReturnPackageForReprocess"] != nil) - processParams.shouldReturnPackageForReprocess = [options valueForKey:@"shouldReturnPackageForReprocess"]; - if([options valueForKey:@"imageOutputMaxWidth"] != nil) - processParams.imageOutputMaxWidth = [options valueForKey:@"imageOutputMaxWidth"]; - if([options valueForKey:@"imageOutputMaxHeight"] != nil) - processParams.imageOutputMaxHeight = [options valueForKey:@"imageOutputMaxHeight"]; - if([options valueForKey:@"disablePerforationOCR"] != nil) - processParams.disablePerforationOCR = [options valueForKey:@"disablePerforationOCR"]; - if([options valueForKey:@"respectImageQuality"] != nil) - processParams.respectImageQuality = [options valueForKey:@"respectImageQuality"]; - if([options valueForKey:@"splitNames"] != nil) - processParams.splitNames = [options valueForKey:@"splitNames"]; - if([options valueForKey:@"processAuth"] != nil) - processParams.processAuth = [options valueForKey:@"processAuth"]; - if([options valueForKey:@"documentGroupFilter"] != nil) - processParams.documentGroupFilter = [options valueForKey:@"documentGroupFilter"]; - if([options valueForKey:@"convertCase"] != nil) - processParams.convertCase = [RGLWRegulaConfig RGLTextProcessingWithNSInteger:[options valueForKey:@"convertCase"]]; - if([options valueForKey:@"rfidParams"] != nil) - processParams.rfidParams = [self RGLRFIDParamsFromJSON:[options valueForKey:@"rfidParams"]]; - if([options valueForKey:@"doDetectCan"] != nil) - processParams.doDetectCan = [NSNumber numberWithBool:[[options valueForKey:@"doDetectCan"] boolValue]]; - if([options valueForKey:@"useFaceApi"] != nil) - processParams.useFaceApi = [NSNumber numberWithBool:[[options valueForKey:@"useFaceApi"] boolValue]]; - if([options valueForKey:@"faceApiParams"] != nil) - processParams.faceApiParams = [self RGLFaceAPIParamsFromJSON:[options valueForKey:@"faceApiParams"]]; -} - -+(NSMutableDictionary *)getCustomization:(RGLCustomization*)customization { - NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; - - result[@"showHelpAnimation"] = [NSNumber numberWithBool:customization.showHelpAnimation]; - result[@"helpAnimationImage"] = [RGLWJSONConstructor base64WithImage:customization.helpAnimationImage]; - result[@"showStatusMessages"] = [NSNumber numberWithBool:customization.showStatusMessages]; - result[@"status"] = customization.status; - result[@"resultStatus"] = customization.resultStatus; - result[@"statusPositionMultiplier"] = [NSNumber numberWithFloat:customization.statusPositionMultiplier]; - result[@"resultStatusPositionMultiplier"] = [NSNumber numberWithFloat:customization.resultStatusPositionMultiplier]; - result[@"cameraFrameShapeType"] = [NSNumber numberWithFloat:customization.cameraFrameShapeType]; - result[@"resultStatusTextFont"] = customization.resultStatusTextFont.fontName; - result[@"cameraFrameBorderWidth"] = [NSNumber numberWithFloat:customization.cameraFrameBorderWidth]; - result[@"statusTextFont"] = customization.statusTextFont.fontName; - result[@"multipageAnimationFrontImage"] = [RGLWJSONConstructor base64WithImage:customization.multipageAnimationFrontImage]; - result[@"multipageAnimationBackImage"] = [RGLWJSONConstructor base64WithImage:customization.multipageAnimationBackImage]; - result[@"cameraFrameLineLength"] = [NSNumber numberWithFloat:customization.cameraFrameLineLength]; - result[@"showNextPageAnimation"] = [NSNumber numberWithBool:customization.showNextPageAnimation]; - result[@"showBackgroundMask"] = [NSNumber numberWithBool:customization.showBackgroundMask]; - result[@"borderBackgroundImage"] = [RGLWJSONConstructor base64WithImage:customization.borderBackgroundImage]; - result[@"backgroundMaskAlpha"] = [NSNumber numberWithFloat:customization.backgroundMaskAlpha]; - result[@"helpAnimationImageContentMode"] = [NSNumber numberWithInteger:[self NSIntegerWithUIViewContentMode:customization.helpAnimationImageContentMode]]; - result[@"multipageAnimationFrontImageContentMode"] = [NSNumber numberWithInteger:[self NSIntegerWithUIViewContentMode:customization.multipageAnimationFrontImageContentMode]]; - result[@"multipageAnimationBackImageContentMode"] = [NSNumber numberWithInteger:[self NSIntegerWithUIViewContentMode:customization.multipageAnimationBackImageContentMode]]; - result[@"borderBackgroundImageContentMode"] = [NSNumber numberWithInteger:[self NSIntegerWithUIViewContentMode:customization.borderBackgroundImageContentMode]]; - result[@"cameraFrameVerticalPositionMultiplier"] = [NSNumber numberWithFloat:customization.cameraFrameVerticalPositionMultiplier]; - result[@"customStatusPositionMultiplier"] = [NSNumber numberWithFloat:customization.customStatusPositionMultiplier]; - result[@"cameraFrameCornerRadius"] = [NSNumber numberWithFloat:customization.cameraFrameCornerRadius]; - result[@"torchButtonOnImage"] = [RGLWJSONConstructor base64WithImage:customization.torchButtonOnImage]; - result[@"torchButtonOffImage"] = [RGLWJSONConstructor base64WithImage:customization.torchButtonOffImage]; - result[@"closeButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.closeButtonImage]; - result[@"captureButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.captureButtonImage]; - result[@"changeFrameButtonCollapseImage"] = [RGLWJSONConstructor base64WithImage:customization.changeFrameButtonCollapseImage]; - result[@"changeFrameButtonExpandImage"] = [RGLWJSONConstructor base64WithImage:customization.changeFrameButtonExpandImage]; - result[@"cameraSwitchButtonImage"] = [RGLWJSONConstructor base64WithImage:customization.cameraSwitchButtonImage]; - result[@"cameraFrameLineCap"] = [NSNumber numberWithInteger:[self NSIntegerWithCGLineCap:customization.cameraFrameLineCap]]; - result[@"cameraFrameOffsetWidth"] = [NSNumber numberWithFloat:customization.cameraFrameOffsetWidth]; - result[@"cameraFramePortraitAspectRatio"] = [NSNumber numberWithFloat:customization.cameraFramePortraitAspectRatio]; - result[@"cameraFrameLandscapeAspectRatio"] = [NSNumber numberWithFloat:customization.cameraFrameLandscapeAspectRatio]; - result[@"toolbarSize"] = [NSNumber numberWithFloat:customization.toolbarSize]; - result[@"hologramAnimationImageContentMode"] = [NSNumber numberWithInteger:[self NSIntegerWithUIViewContentMode:customization.hologramAnimationImageContentMode]]; - result[@"hologramAnimationPositionMultiplier"] = [NSNumber numberWithFloat:customization.hologramAnimationPositionMultiplier]; - result[@"uiCustomizationLayer"] = customization.customUILayerJSON; - result[@"hologramAnimationImage"] = [RGLWJSONConstructor base64WithImage:customization.hologramAnimationImage]; - if(customization.customLabelStatus != nil) - result[@"customLabelStatus"] = customization.customLabelStatus.string; - if(customization.activityIndicatorColor != nil) - result[@"activityIndicatorColor"] = [self hexStringFromUIColor:customization.activityIndicatorColor]; - if(customization.multipageButtonBackgroundColor != nil) - result[@"multipageButtonBackgroundColor"] = [self hexStringFromUIColor:customization.multipageButtonBackgroundColor]; - if(customization.statusTextColor != nil) - result[@"statusTextColor"] = [self hexStringFromUIColor:customization.statusTextColor]; - if(customization.resultStatusBackgroundColor != nil) - result[@"resultStatusBackgroundColor"] = [self hexStringFromUIColor:customization.resultStatusBackgroundColor]; - if(customization.cameraPreviewBackgroundColor != nil) - result[@"cameraPreviewBackgroundColor"] = [self hexStringFromUIColor:customization.cameraPreviewBackgroundColor]; - if(customization.cameraFrameDefaultColor != nil) - result[@"cameraFrameDefaultColor"] = [self hexStringFromUIColor:customization.cameraFrameDefaultColor]; - if(customization.cameraFrameActiveColor != nil) - result[@"cameraFrameActiveColor"] = [self hexStringFromUIColor:customization.cameraFrameActiveColor]; - if(customization.tintColor != nil) - result[@"tintColor"] = [self hexStringFromUIColor:customization.tintColor]; - if(customization.resultStatusTextColor != nil) - result[@"resultStatusTextColor"] = [self hexStringFromUIColor:customization.resultStatusTextColor]; - if(customization.statusBackgroundColor != nil) - result[@"statusBackgroundColor"] = [self hexStringFromUIColor:customization.statusBackgroundColor]; - - return result; -} - -+(NSMutableDictionary *)getFunctionality:(RGLFunctionality*)functionality { - NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; - - result[@"cameraFrame"] = [NSNumber numberWithInteger:functionality.cameraFrame]; - result[@"showTorchButton"] = [NSNumber numberWithBool:functionality.showTorchButton]; - result[@"showCloseButton"] = [NSNumber numberWithBool:functionality.showCloseButton]; - result[@"showCaptureButton"] = [NSNumber numberWithBool:functionality.showCaptureButton]; - result[@"showChangeFrameButton"] = [NSNumber numberWithBool:functionality.showChangeFrameButton]; - result[@"showCameraSwitchButton"] = [NSNumber numberWithBool:functionality.showCameraSwitchButton]; - result[@"showSkipNextPageButton"] = [NSNumber numberWithBool:functionality.showSkipNextPageButton]; - result[@"skipFocusingFrames"] = [NSNumber numberWithBool:functionality.skipFocusingFrames]; - result[@"videoSessionPreset"] = [NSNumber numberWithInteger:[self NSIntegerWithAVCaptureSessionPreset:functionality.videoSessionPreset]]; - result[@"videoCaptureMotionControl"] = [NSNumber numberWithBool:functionality.videoCaptureMotionControl]; - result[@"orientation"] = [NSNumber numberWithInteger:[self NSIntegerWithUIInterfaceOrientationMask:functionality.orientation]]; - result[@"cameraPosition"] = [NSNumber numberWithInteger:[self NSIntegerWithAVCaptureDevicePosition:functionality.cameraPosition]]; - #pragma clang diagnostic ignored "-Wdeprecated-declarations" - result[@"btDeviceName"] = functionality.btDeviceName; - #pragma clang diagnostic pop - result[@"useAuthenticator"] = [NSNumber numberWithBool:functionality.isUseAuthenticator]; - result[@"showCaptureButtonDelayFromDetect"] = [NSNumber numberWithDouble:functionality.showCaptureButtonDelayFromDetect]; - result[@"showCaptureButtonDelayFromStart"] = [NSNumber numberWithDouble:functionality.showCaptureButtonDelayFromStart]; - result[@"captureMode"] = [NSNumber numberWithInteger:functionality.captureMode]; - result[@"displayMetadata"] = [NSNumber numberWithBool:functionality.showMetadataInfo]; - result[@"isZoomEnabled"] = [NSNumber numberWithBool:functionality.isZoomEnabled]; - result[@"zoomFactor"] = [NSNumber numberWithBool:functionality.zoomFactor]; - result[@"recordScanningProcess"] = [NSNumber numberWithBool:functionality.recordScanningProcess]; - result[@"manualMultipageMode"] = [NSNumber numberWithBool:functionality.manualMultipageMode]; - result[@"videoOutputSettings"] = functionality.videoOutputSettings; - - return result; -} - -+(NSMutableDictionary *)getProcessParams:(RGLProcessParams*)processParams { - NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; - - result[@"scenario"] = processParams.scenario; - result[@"captureButtonScenario"] = processParams.captureButtonScenario; - result[@"logs"] = [NSNumber numberWithBool:processParams.logs]; - result[@"multipageProcessing"] = [NSNumber numberWithBool:processParams.multipageProcessing]; - result[@"disableFocusingCheck"] = [NSNumber numberWithBool:processParams.disableFocusingCheck]; - result[@"debugSaveImages"] = [NSNumber numberWithBool:processParams.debugSaveImages]; - result[@"debugSaveCroppedImages"] = [NSNumber numberWithBool:processParams.debugSaveCroppedImages]; - result[@"debugSaveLogs"] = [NSNumber numberWithBool:processParams.debugSaveLogs]; - result[@"dateFormat"] = processParams.dateFormat; - result[@"documentIDList"] = processParams.documentIDList; - result[@"sessionLogFolder"] = processParams.sessionLogFolder; - result[@"fieldTypesFilter"] = processParams.fieldTypesFilter; - result[@"barcodeTypes"] = processParams.barcodeTypes; - result[@"measureSystem"] = [NSNumber numberWithInteger:processParams.measureSystem]; - result[@"returnUncroppedImage"] = [NSNumber numberWithBool:processParams.returnUncroppedImage]; - result[@"customParams"] = processParams.customParams; - result[@"debugSaveRFIDSession"] = [NSNumber numberWithBool:processParams.debugSaveRFIDSession]; - result[@"doublePageSpread"] = [NSNumber numberWithBool:processParams.doublePageSpread]; - result[@"barcodeParserType"] = processParams.barcodeParserType; - result[@"timeout"] = processParams.timeout; - result[@"timeoutFromFirstDetect"] = processParams.timeoutFromFirstDetect; - result[@"timeoutFromFirstDocType"] = processParams.timeoutFromFirstDocType; - result[@"manualCrop"] = [NSNumber numberWithBool:processParams.manualCrop]; - result[@"perspectiveAngle"] = processParams.perspectiveAngle; - result[@"minDPI"] = processParams.minDPI; - result[@"integralImage"] = [NSNumber numberWithBool:processParams.integralImage]; - result[@"returnCroppedBarcode"] = [NSNumber numberWithBool:processParams.returnCroppedBarcode]; - result[@"checkHologram"] = [NSNumber numberWithBool:processParams.checkHologram]; - result[@"checkRequiredTextFields"] = [NSNumber numberWithBool:processParams.checkRequiredTextFields]; - result[@"depersonalizeLog"] = processParams.depersonalizeLog; - result[@"resultTypeOutput"] = processParams.resultTypeOutput; - result[@"generateDoublePageSpreadImage"] = processParams.generateDoublePageSpreadImage; - result[@"imageDpiOutMax"] = processParams.imageDpiOutMax; - result[@"alreadyCropped"] = processParams.alreadyCropped; - result[@"forceDocID"] = processParams.forceDocID; - result[@"matchTextFieldMask"] = processParams.matchTextFieldMask; - result[@"fastDocDetect"] = processParams.fastDocDetect; - result[@"updateOCRValidityByGlare"] = processParams.updateOCRValidityByGlare; - result[@"imageQA"] = [RGLWRegulaConfig ImageQAToJson:processParams.imageQA]; - result[@"forceDocFormat"] = processParams.forceDocFormat; - result[@"noGraphics"] = processParams.noGraphics; - result[@"documentAreaMin"] = processParams.documentAreaMin; - result[@"multiDocOnImage"] = processParams.multiDocOnImage; - result[@"shiftExpiryDate"] = processParams.shiftExpiryDate; - result[@"minimalHolderAge"] = processParams.minimalHolderAge; - result[@"mrzFormatsFilter"] = processParams.mrzFormatsFilter; - result[@"forceReadMrzBeforeLocate"] = processParams.forceReadMrzBeforeLocate; - result[@"parseBarcodes"] = processParams.parseBarcodes; - result[@"shouldReturnPackageForReprocess"] = processParams.shouldReturnPackageForReprocess; - result[@"imageOutputMaxWidth"] = processParams.imageOutputMaxWidth; - result[@"imageOutputMaxHeight"] = processParams.imageOutputMaxHeight; - result[@"disablePerforationOCR"] = processParams.disablePerforationOCR; - result[@"respectImageQuality"] = processParams.respectImageQuality; - result[@"splitNames"] = processParams.splitNames; - result[@"processAuth"] = processParams.processAuth; - result[@"documentGroupFilter"] = processParams.documentGroupFilter; - result[@"convertCase"] = [RGLWRegulaConfig NSNumberWithRGLTextProcessing:processParams.convertCase]; - result[@"doDetectCan"] = [NSNumber numberWithBool:processParams.doDetectCan]; - result[@"useFaceApi"] = [NSNumber numberWithBool:processParams.useFaceApi]; - - return result; -} - -+(void)setRfidScenario:(NSDictionary*)options :(RGLRFIDScenario*)rfidScenario { - if([options valueForKey:@"autoSettings"] != nil) - rfidScenario.autoSettings = [[options valueForKey:@"autoSettings"] boolValue]; - if([options valueForKey:@"signManagementAction"] != nil) - rfidScenario.signManagementAction = [[options valueForKey:@"signManagementAction"] integerValue]; - if([options valueForKey:@"readingBuffer"] != nil) - rfidScenario.readingBuffer = [[options valueForKey:@"readingBuffer"] intValue]; - if([options valueForKey:@"onlineTAToSignDataType"] != nil) - rfidScenario.onlineTAToSignDataType = [[options valueForKey:@"onlineTAToSignDataType"] intValue]; - if([options valueForKey:@"onlineTA"] != nil) - rfidScenario.onlineTA = [[options valueForKey:@"onlineTA"] boolValue]; - if([options valueForKey:@"writeEid"] != nil) - rfidScenario.writeEid = [[options valueForKey:@"writeEid"] boolValue]; - if([options valueForKey:@"profilerType"] != nil) - rfidScenario.profilerType = [[options valueForKey:@"profilerType"] intValue]; - if([options valueForKey:@"authProcType"] != nil) - rfidScenario.authProcType = [[options valueForKey:@"authProcType"] integerValue]; - if([options valueForKey:@"baseSMProcedure"] != nil) - rfidScenario.baseSMProcedure = [[options valueForKey:@"baseSMProcedure"] integerValue]; - if([options valueForKey:@"pacePasswordType"] != nil) - rfidScenario.pacePasswordType = [[options valueForKey:@"pacePasswordType"] integerValue]; - if([options valueForKey:@"terminalType"] != nil) - rfidScenario.terminalType = [[options valueForKey:@"terminalType"] integerValue]; - if([options valueForKey:@"universalAccessRights"] != nil) - rfidScenario.universalAccessRights = [[options valueForKey:@"universalAccessRights"] boolValue]; - if([options valueForKey:@"authorizedRestrictedIdentification"] != nil) - rfidScenario.authorizedRestrictedIdentification = [[options valueForKey:@"authorizedRestrictedIdentification"] boolValue]; - if([options valueForKey:@"auxVerificationCommunityID"] != nil) - rfidScenario.auxVerificationCommunityID = [[options valueForKey:@"auxVerificationCommunityID"] boolValue]; - if([options valueForKey:@"auxVerificationDateOfBirth"] != nil) - rfidScenario.auxVerificationDateOfBirth = [[options valueForKey:@"auxVerificationDateOfBirth"] boolValue]; - if([options valueForKey:@"skipAA"] != nil) - rfidScenario.skipAA = [[options valueForKey:@"skipAA"] boolValue]; - if([options valueForKey:@"strictProcessing"] != nil) - rfidScenario.strictProcessing = [[options valueForKey:@"strictProcessing"] boolValue]; - if([options valueForKey:@"pkdDSCertPriority"] != nil) - rfidScenario.pkdDSCertPriority = [[options valueForKey:@"pkdDSCertPriority"] boolValue]; - if([options valueForKey:@"pkdUseExternalCSCA"] != nil) - rfidScenario.pkdUseExternalCSCA = [[options valueForKey:@"pkdUseExternalCSCA"] boolValue]; - if([options valueForKey:@"trustedPKD"] != nil) - rfidScenario.trustedPKD = [[options valueForKey:@"trustedPKD"] boolValue]; - if([options valueForKey:@"passiveAuth"] != nil) - rfidScenario.passiveAuth = [[options valueForKey:@"passiveAuth"] boolValue]; - if([options valueForKey:@"paceStaticBinding"] != nil) - rfidScenario.paceStaticBinding = [[options valueForKey:@"paceStaticBinding"] boolValue]; - if([options valueForKey:@"password"] != nil) - rfidScenario.password = [options valueForKey:@"password"]; - if([options valueForKey:@"useSFI"] != nil) - rfidScenario.useSFI = [[options valueForKey:@"useSFI"] boolValue]; - if([options valueForKey:@"pkdPA"] != nil) - rfidScenario.pkdPA = [options valueForKey:@"pkdPA"]; - if([options valueForKey:@"pkdEAC"] != nil) - rfidScenario.pkdEAC = [options valueForKey:@"pkdEAC"]; - if([options valueForKey:@"readEPassport"] != nil) - rfidScenario.readEPassport = [[options valueForKey:@"readEPassport"] boolValue]; - if([options valueForKey:@"readEID"] != nil) - rfidScenario.readEID = [[options valueForKey:@"readEID"] boolValue]; - if([options valueForKey:@"readEDL"] != nil) - rfidScenario.readEDL = [[options valueForKey:@"readEDL"] boolValue]; - if([options valueForKey:@"ePassportDataGroups"] != nil) - rfidScenario.ePassportDataGroups = [self RGLePassportDataGroupFromJson:[options valueForKey:@"ePassportDataGroups"]]; - if([options valueForKey:@"eIDDataGroups"] != nil) - rfidScenario.eIDDataGroups = [self RGLeIDDataGroupFromJson:[options valueForKey:@"eIDDataGroups"]]; - if([options valueForKey:@"eDLDataGroups"] != nil) - rfidScenario.eDLDataGroups = [self RGLeDLDataGroupFromJson:[options valueForKey:@"eDLDataGroups"]]; - if([options valueForKey:@"mrz"] != nil) - rfidScenario.mrz = [options valueForKey:@"mrz"]; - if([options valueForKey:@"eSignPINDefault"] != nil) - rfidScenario.eSignPINDefault = [options valueForKey:@"eSignPINDefault"]; - if([options valueForKey:@"eSignPINNewValue"] != nil) - rfidScenario.eSignPINNewValue = [options valueForKey:@"eSignPINNewValue"]; - if([options valueForKey:@"authorizedSTSignature"] != nil) - rfidScenario.authorizedSTSignature = [[options valueForKey:@"authorizedSTSignature"] boolValue]; - if([options valueForKey:@"authorizedSTQSignature"] != nil) - rfidScenario.authorizedSTQSignature = [[options valueForKey:@"authorizedSTQSignature"] boolValue]; - if([options valueForKey:@"authorizedWriteDG17"] != nil) - rfidScenario.authorizedWriteDG17 = [[options valueForKey:@"authorizedWriteDG17"] boolValue]; - if([options valueForKey:@"authorizedWriteDG18"] != nil) - rfidScenario.authorizedWriteDG18 = [[options valueForKey:@"authorizedWriteDG18"] boolValue]; - if([options valueForKey:@"authorizedWriteDG19"] != nil) - rfidScenario.authorizedWriteDG19 = [[options valueForKey:@"authorizedWriteDG19"] boolValue]; - if([options valueForKey:@"authorizedWriteDG20"] != nil) - rfidScenario.authorizedWriteDG20 = [[options valueForKey:@"authorizedWriteDG20"] boolValue]; - if([options valueForKey:@"authorizedWriteDG21"] != nil) - rfidScenario.authorizedWriteDG21 = [[options valueForKey:@"authorizedWriteDG21"] boolValue]; - if([options valueForKey:@"authorizedVerifyAge"] != nil) - rfidScenario.authorizedVerifyAge = [[options valueForKey:@"authorizedVerifyAge"] boolValue]; - if([options valueForKey:@"authorizedVerifyCommunityID"] != nil) - rfidScenario.authorizedVerifyCommunityID = [[options valueForKey:@"authorizedVerifyCommunityID"] boolValue]; - if([options valueForKey:@"authorizedPrivilegedTerminal"] != nil) - rfidScenario.authorizedPrivilegedTerminal = [[options valueForKey:@"authorizedPrivilegedTerminal"] boolValue]; - if([options valueForKey:@"authorizedCANAllowed"] != nil) - rfidScenario.authorizedCANAllowed = [[options valueForKey:@"authorizedCANAllowed"] boolValue]; - if([options valueForKey:@"authorizedPINManagment"] != nil) - rfidScenario.authorizedPINManagment = [[options valueForKey:@"authorizedPINManagment"] boolValue]; - if([options valueForKey:@"authorizedInstallCert"] != nil) - rfidScenario.authorizedInstallCert = [[options valueForKey:@"authorizedInstallCert"] boolValue]; - if([options valueForKey:@"authorizedInstallQCert"] != nil) - rfidScenario.authorizedInstallQCert = [[options valueForKey:@"authorizedInstallQCert"] boolValue]; - if([options valueForKey:@"reprocessParams"] != nil) - rfidScenario.reprocParams = [self RGLReprocParamsFromJSON:[options valueForKey:@"reprocessParams"]]; - if([options valueForKey:@"defaultReadingBufferSize"] != nil) - rfidScenario.defaultReadingBufferSize = [[options valueForKey:@"defaultReadingBufferSize"] intValue]; -} - -+(RGLRFIDParams*)RGLRFIDParamsFromJSON:(NSDictionary*)input { - RGLRFIDParams* result = [RGLRFIDParams new]; - - if([input valueForKey:@"paIgnoreNotificationCodes"] != nil) - result.paIgnoreNotificationCodes = [input valueForKey:@"paIgnoreNotificationCodes"]; - - return result; -} - -+(RGLFaceAPIParams*)RGLFaceAPIParamsFromJSON:(NSDictionary*)input { - RGLFaceAPIParams* result = [RGLFaceAPIParams new]; - - if([input valueForKey:@"url"] != nil) - result.url = [input valueForKey:@"url"]; - if([input valueForKey:@"mode"] != nil) - result.mode = [input valueForKey:@"mode"]; - if([input valueForKey:@"threshold"] != nil) - result.threshold = [input valueForKey:@"threshold"]; - if([input valueForKey:@"searchParams"] != nil) - result.searchParams = [self RGLFaceAPISearchParamsFromJSON:[input valueForKey:@"searchParams"]]; - if([input valueForKey:@"serviceTimeout"] != nil) - result.serviceTimeout = [input valueForKey:@"serviceTimeout"]; - if([input valueForKey:@"proxy"] != nil) - result.proxy = [input valueForKey:@"proxy"]; - if([input valueForKey:@"proxyPassword"] != nil) - result.proxyPassword = [input valueForKey:@"proxyPassword"]; - if([input valueForKey:@"proxyType"] != nil) - result.proxyType = [input valueForKey:@"proxyType"]; - - return result; -} - -+(RGLFaceAPISearchParams*)RGLFaceAPISearchParamsFromJSON:(NSDictionary*)input { - RGLFaceAPISearchParams* result = [RGLFaceAPISearchParams new]; - - if([input valueForKey:@"limit"] != nil) - result.limit = [input valueForKey:@"limit"]; - if([input valueForKey:@"threshold"] != nil) - result.threshold = [input valueForKey:@"threshold"]; - if([input valueForKey:@"groupIds"] != nil) - result.groupIDs = [input valueForKey:@"groupIds"]; - - return result; -} - -@end diff --git a/ios/flutter_document_reader_api.podspec b/ios/flutter_document_reader_api.podspec index b72b1a4c83..26d7584a91 100644 --- a/ios/flutter_document_reader_api.podspec +++ b/ios/flutter_document_reader_api.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'flutter_document_reader_api' - s.version = '6.9.2' + s.version = '9.5.1277-rc' s.summary = 'A new flutter plugin project.' s.description = <<-DESC A new flutter plugin project. @@ -12,8 +12,8 @@ A new flutter plugin project. s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' - s.platform = :ios, '11.0' - s.dependency 'DocumentReader', '6.9.3102' + s.platform = :ios, '13.0' + s.dependency 'DocumentReaderStage', '9.6.6498' # Flutter.framework does not contain a i386 slice. Only x86_64 simulators are supported. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' } end diff --git a/lib/document_reader.dart b/lib/document_reader.dart deleted file mode 100644 index e176a8b643..0000000000 --- a/lib/document_reader.dart +++ /dev/null @@ -1,5130 +0,0 @@ -import 'dart:async'; -import 'package:flutter/services.dart'; -import 'dart:convert'; - -// Classes - -class DocumentReaderScenario { - String? name; - String? caption; - String? description; - bool? multiPageOff; - double? frameKWHLandscape; - double? frameKWHPortrait; - double? frameKWHDoublePageSpreadPortrait; - double? frameKWHDoublePageSpreadLandscape; - int? frameOrientation; - bool? uvTorch; - bool? faceExt; - bool? seriesProcessMode; - bool? manualCrop; - - static DocumentReaderScenario? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderScenario(); - - result.name = jsonObject["name"]; - result.caption = jsonObject["caption"]; - result.description = jsonObject["description"]; - result.multiPageOff = jsonObject["multiPageOff"]; - result.frameKWHLandscape = jsonObject["frameKWHLandscape"] == null ? null : jsonObject["frameKWHLandscape"].toDouble(); - result.frameKWHPortrait = jsonObject["frameKWHPortrait"] == null ? null : jsonObject["frameKWHPortrait"].toDouble(); - result.frameKWHDoublePageSpreadPortrait = jsonObject["frameKWHDoublePageSpreadPortrait"] == null ? null : jsonObject["frameKWHDoublePageSpreadPortrait"].toDouble(); - result.frameKWHDoublePageSpreadLandscape = jsonObject["frameKWHDoublePageSpreadLandscape"] == null ? null : jsonObject["frameKWHDoublePageSpreadLandscape"].toDouble(); - result.frameOrientation = jsonObject["frameOrientation"]; - result.uvTorch = jsonObject["uvTorch"]; - result.faceExt = jsonObject["faceExt"]; - result.seriesProcessMode = jsonObject["seriesProcessMode"]; - result.manualCrop = jsonObject["manualCrop"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (name != null) _result.addAll({"name": name}); - if (caption != null) _result.addAll({"caption": caption}); - if (description != null) _result.addAll({"description": description}); - if (multiPageOff != null) _result.addAll({"multiPageOff": multiPageOff}); - if (frameKWHLandscape != null) _result.addAll({"frameKWHLandscape": frameKWHLandscape}); - if (frameKWHPortrait != null) _result.addAll({"frameKWHPortrait": frameKWHPortrait}); - if (frameKWHDoublePageSpreadPortrait != null) _result.addAll({"frameKWHDoublePageSpreadPortrait": frameKWHDoublePageSpreadPortrait}); - if (frameKWHDoublePageSpreadLandscape != null) _result.addAll({"frameKWHDoublePageSpreadLandscape": frameKWHDoublePageSpreadLandscape}); - if (frameOrientation != null) _result.addAll({"frameOrientation": frameOrientation}); - if (uvTorch != null) _result.addAll({"uvTorch": uvTorch}); - if (faceExt != null) _result.addAll({"faceExt": faceExt}); - if (seriesProcessMode != null) _result.addAll({"seriesProcessMode": seriesProcessMode}); - if (manualCrop != null) _result.addAll({"manualCrop": manualCrop}); - - return _result; - } -} - -class Rect { - int? bottom; - int? top; - int? left; - int? right; - - static Rect? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Rect(); - - result.bottom = jsonObject["bottom"]; - result.top = jsonObject["top"]; - result.left = jsonObject["left"]; - result.right = jsonObject["right"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (bottom != null) _result.addAll({"bottom": bottom}); - if (top != null) _result.addAll({"top": top}); - if (left != null) _result.addAll({"left": left}); - if (right != null) _result.addAll({"right": right}); - - return _result; - } -} - -class DocReaderFieldRect { - int? bottom; - int? top; - int? left; - int? right; - - static DocReaderFieldRect? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocReaderFieldRect(); - - result.bottom = jsonObject["bottom"]; - result.top = jsonObject["top"]; - result.left = jsonObject["left"]; - result.right = jsonObject["right"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (bottom != null) _result.addAll({"bottom": bottom}); - if (top != null) _result.addAll({"top": top}); - if (left != null) _result.addAll({"left": left}); - if (right != null) _result.addAll({"right": right}); - - return _result; - } -} - -class DocumentReaderGraphicField { - int? sourceType; - int? fieldType; - int? light; - int? pageIndex; - int? originalPageIndex; - String? fieldName; - String? lightName; - String? value; - DocReaderFieldRect? fieldRect; - - static DocumentReaderGraphicField? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderGraphicField(); - - result.sourceType = jsonObject["sourceType"]; - result.fieldType = jsonObject["fieldType"]; - result.light = jsonObject["light"]; - result.pageIndex = jsonObject["pageIndex"]; - result.originalPageIndex = jsonObject["originalPageIndex"]; - result.fieldName = jsonObject["fieldName"]; - result.lightName = jsonObject["lightName"]; - result.value = jsonObject["value"]; - result.fieldRect = DocReaderFieldRect.fromJson(jsonObject["fieldRect"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (sourceType != null) _result.addAll({"sourceType": sourceType}); - if (fieldType != null) _result.addAll({"fieldType": fieldType}); - if (light != null) _result.addAll({"light": light}); - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (originalPageIndex != null) _result.addAll({"originalPageIndex": originalPageIndex}); - if (fieldName != null) _result.addAll({"fieldName": fieldName}); - if (lightName != null) _result.addAll({"lightName": lightName}); - if (value != null) _result.addAll({"value": value}); - if (fieldRect != null) _result.addAll({"fieldRect": fieldRect}); - - return _result; - } -} - -class DocumentReaderGraphicResult { - List fields = []; - - static DocumentReaderGraphicResult? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderGraphicResult(); - - if (jsonObject["fields"] != null) - for (var item in jsonObject["fields"]) - result.fields.add(DocumentReaderGraphicField.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - _result.addAll({"fields": fields}); - - return _result; - } -} - -class DocumentReaderValue { - int? pageIndex; - int? sourceType; - int? validity; - int? probability; - String? value; - String? originalValue; - Rect? boundRect; - Map comparison = {}; - List originalSymbols = []; - DocumentReaderRfidOrigin? rfidOrigin; - - static DocumentReaderValue? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderValue(); - - result.pageIndex = jsonObject["pageIndex"]; - result.sourceType = jsonObject["sourceType"]; - result.validity = jsonObject["validity"]; - result.probability = jsonObject["probability"]; - result.value = jsonObject["value"]; - result.originalValue = jsonObject["originalValue"]; - result.boundRect = Rect.fromJson(jsonObject["boundRect"]); - if (jsonObject["comparison"] != null) - jsonObject["comparison"].forEach((k, v) => result.comparison[int.parse(k)] = v); - if (jsonObject["originalSymbols"] != null) - for (var item in jsonObject["originalSymbols"]) - result.originalSymbols.add(DocumentReaderSymbol.fromJson(item)); - result.rfidOrigin = DocumentReaderRfidOrigin.fromJson(jsonObject["rfidOrigin"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (sourceType != null) _result.addAll({"sourceType": sourceType}); - if (validity != null) _result.addAll({"validity": validity}); - if (probability != null) _result.addAll({"probability": probability}); - if (value != null) _result.addAll({"value": value}); - if (originalValue != null) _result.addAll({"originalValue": originalValue}); - if (boundRect != null) _result.addAll({"boundRect": boundRect}); - _result.addAll({"comparison": comparison}); - _result.addAll({"originalSymbols": originalSymbols}); - if (rfidOrigin != null) _result.addAll({"rfidOrigin": rfidOrigin}); - - return _result; - } -} - -class DocumentReaderTextField { - int? fieldType; - int? lcid; - int? status; - String? lcidName; - String? fieldName; - String? value; - DocumentReaderValue? getValue; - List values = []; - List comparisonList = []; - List validityList = []; - int? comparisonStatus; - int? validityStatus; - - static DocumentReaderTextField? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderTextField(); - - result.fieldType = jsonObject["fieldType"]; - result.lcid = jsonObject["lcid"]; - result.status = jsonObject["status"]; - result.lcidName = jsonObject["lcidName"]; - result.fieldName = jsonObject["fieldName"]; - result.value = jsonObject["value"]; - result.getValue = DocumentReaderValue.fromJson(jsonObject["getValue"]); - if (jsonObject["values"] != null) - for (var item in jsonObject["values"]) - result.values.add(DocumentReaderValue.fromJson(item)); - if (jsonObject["comparisonList"] != null) - for (var item in jsonObject["comparisonList"]) - result.comparisonList.add(DocumentReaderComparison.fromJson(item)); - if (jsonObject["validityList"] != null) - for (var item in jsonObject["validityList"]) - result.validityList.add(DocumentReaderValidity.fromJson(item)); - result.comparisonStatus = jsonObject["comparisonStatus"]; - result.validityStatus = jsonObject["validityStatus"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (fieldType != null) _result.addAll({"fieldType": fieldType}); - if (lcid != null) _result.addAll({"lcid": lcid}); - if (status != null) _result.addAll({"status": status}); - if (lcidName != null) _result.addAll({"lcidName": lcidName}); - if (fieldName != null) _result.addAll({"fieldName": fieldName}); - if (value != null) _result.addAll({"value": value}); - if (getValue != null) _result.addAll({"getValue": getValue}); - _result.addAll({"values": values}); - _result.addAll({"comparisonList": comparisonList}); - _result.addAll({"validityList": validityList}); - if (comparisonStatus != null) _result.addAll({"comparisonStatus": comparisonStatus}); - if (validityStatus != null) _result.addAll({"validityStatus": validityStatus}); - - return _result; - } -} - -class DocumentReaderTextResult { - int? status; - int? comparisonStatus; - int? validityStatus; - List availableSourceList = []; - List fields = []; - - static DocumentReaderTextResult? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderTextResult(); - - result.status = jsonObject["status"]; - result.comparisonStatus = jsonObject["comparisonStatus"]; - result.validityStatus = jsonObject["validityStatus"]; - if (jsonObject["availableSourceList"] != null) - for (var item in jsonObject["availableSourceList"]) - result.availableSourceList.add(DocumentReaderTextSource.fromJson(item)); - if (jsonObject["fields"] != null) - for (var item in jsonObject["fields"]) - result.fields.add(DocumentReaderTextField.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (status != null) _result.addAll({"status": status}); - if (comparisonStatus != null) _result.addAll({"comparisonStatus": comparisonStatus}); - if (validityStatus != null) _result.addAll({"validityStatus": validityStatus}); - _result.addAll({"availableSourceList": availableSourceList}); - _result.addAll({"fields": fields}); - - return _result; - } -} - -class Coordinate { - int? x; - int? y; - - static Coordinate? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Coordinate(); - - result.x = jsonObject["x"]; - result.y = jsonObject["y"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (x != null) _result.addAll({"x": x}); - if (y != null) _result.addAll({"y": y}); - - return _result; - } -} - -class ElementPosition { - int? docFormat; - int? width; - int? height; - int? dpi; - int? pageIndex; - int? inverse; - int? perspectiveTr; - int? objArea; - int? objIntAngleDev; - int? resultStatus; - double? angle; - Coordinate? center; - Coordinate? leftTop; - Coordinate? leftBottom; - Coordinate? rightTop; - Coordinate? rightBottom; - - static ElementPosition? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ElementPosition(); - - result.docFormat = jsonObject["docFormat"]; - result.width = jsonObject["width"]; - result.height = jsonObject["height"]; - result.dpi = jsonObject["dpi"]; - result.pageIndex = jsonObject["pageIndex"]; - result.inverse = jsonObject["inverse"]; - result.perspectiveTr = jsonObject["perspectiveTr"]; - result.objArea = jsonObject["objArea"]; - result.objIntAngleDev = jsonObject["objIntAngleDev"]; - result.resultStatus = jsonObject["resultStatus"]; - result.angle = jsonObject["angle"] == null ? null : jsonObject["angle"].toDouble(); - result.center = Coordinate.fromJson(jsonObject["center"]); - result.leftTop = Coordinate.fromJson(jsonObject["leftTop"]); - result.leftBottom = Coordinate.fromJson(jsonObject["leftBottom"]); - result.rightTop = Coordinate.fromJson(jsonObject["rightTop"]); - result.rightBottom = Coordinate.fromJson(jsonObject["rightBottom"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (docFormat != null) _result.addAll({"docFormat": docFormat}); - if (width != null) _result.addAll({"width": width}); - if (height != null) _result.addAll({"height": height}); - if (dpi != null) _result.addAll({"dpi": dpi}); - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (inverse != null) _result.addAll({"inverse": inverse}); - if (perspectiveTr != null) _result.addAll({"perspectiveTr": perspectiveTr}); - if (objArea != null) _result.addAll({"objArea": objArea}); - if (objIntAngleDev != null) _result.addAll({"objIntAngleDev": objIntAngleDev}); - if (resultStatus != null) _result.addAll({"resultStatus": resultStatus}); - if (angle != null) _result.addAll({"angle": angle}); - if (center != null) _result.addAll({"center": center}); - if (leftTop != null) _result.addAll({"leftTop": leftTop}); - if (leftBottom != null) _result.addAll({"leftBottom": leftBottom}); - if (rightTop != null) _result.addAll({"rightTop": rightTop}); - if (rightBottom != null) _result.addAll({"rightBottom": rightBottom}); - - return _result; - } -} - -class ImageQuality { - int? featureType; - int? result; - int? type; - - static ImageQuality? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ImageQuality(); - - result.featureType = jsonObject["featureType"]; - result.result = jsonObject["result"]; - result.type = jsonObject["type"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (featureType != null) _result.addAll({"featureType": featureType}); - if (result != null) _result.addAll({"result": result}); - if (type != null) _result.addAll({"type": type}); - - return _result; - } -} - -class ImageQualityGroup { - int? count; - int? result; - List imageQualityList = []; - int? pageIndex; - - static ImageQualityGroup? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ImageQualityGroup(); - - result.count = jsonObject["count"]; - result.result = jsonObject["result"]; - if (jsonObject["imageQualityList"] != null) - for (var item in jsonObject["imageQualityList"]) - result.imageQualityList.add(ImageQuality.fromJson(item)); - result.pageIndex = jsonObject["pageIndex"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (count != null) _result.addAll({"count": count}); - if (result != null) _result.addAll({"result": result}); - _result.addAll({"imageQualityList": imageQualityList}); - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - - return _result; - } -} - -class DocumentReaderDocumentType { - int? pageIndex; - int? documentID; - int? dType; - int? dFormat; - bool? dMRZ; - bool? isDeprecated; - String? name; - String? iCAOCode; - String? dDescription; - String? dYear; - String? dCountryName; - List fDSID = []; - - static DocumentReaderDocumentType? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderDocumentType(); - - result.pageIndex = jsonObject["pageIndex"]; - result.documentID = jsonObject["documentID"]; - result.dType = jsonObject["dType"]; - result.dFormat = jsonObject["dFormat"]; - result.dMRZ = jsonObject["dMRZ"]; - result.isDeprecated = jsonObject["isDeprecated"]; - result.name = jsonObject["name"]; - result.iCAOCode = jsonObject["ICAOCode"]; - result.dDescription = jsonObject["dDescription"]; - result.dYear = jsonObject["dYear"]; - result.dCountryName = jsonObject["dCountryName"]; - if (jsonObject["FDSID"] != null) - for (var item in jsonObject["FDSID"]) - result.fDSID.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (documentID != null) _result.addAll({"documentID": documentID}); - if (dType != null) _result.addAll({"dType": dType}); - if (dFormat != null) _result.addAll({"dFormat": dFormat}); - if (dMRZ != null) _result.addAll({"dMRZ": dMRZ}); - if (isDeprecated != null) _result.addAll({"isDeprecated": isDeprecated}); - if (name != null) _result.addAll({"name": name}); - if (iCAOCode != null) _result.addAll({"ICAOCode": iCAOCode}); - if (dDescription != null) _result.addAll({"dDescription": dDescription}); - if (dYear != null) _result.addAll({"dYear": dYear}); - if (dCountryName != null) _result.addAll({"dCountryName": dCountryName}); - _result.addAll({"FDSID": fDSID}); - - return _result; - } -} - -class DocumentReaderNotification { - int? notificationCode; - int? dataFileType; - int? progress; - - static DocumentReaderNotification? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderNotification(); - - result.notificationCode = jsonObject["notificationCode"]; - result.dataFileType = jsonObject["dataFileType"]; - result.progress = jsonObject["progress"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (notificationCode != null) _result.addAll({"notificationCode": notificationCode}); - if (dataFileType != null) _result.addAll({"dataFileType": dataFileType}); - if (progress != null) _result.addAll({"progress": progress}); - - return _result; - } -} - -class AccessControlProcedureType { - int? activeOptionIdx; - int? type; - int? status; - List notifications = []; - - static AccessControlProcedureType? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new AccessControlProcedureType(); - - result.activeOptionIdx = jsonObject["activeOptionIdx"]; - result.type = jsonObject["type"]; - result.status = jsonObject["status"]; - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (activeOptionIdx != null) _result.addAll({"activeOptionIdx": activeOptionIdx}); - if (type != null) _result.addAll({"type": type}); - if (status != null) _result.addAll({"status": status}); - _result.addAll({"notifications": notifications}); - - return _result; - } -} - -class FileData { - int? length; - int? type; - int? status; - String? data; - - static FileData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new FileData(); - - result.length = jsonObject["length"]; - result.type = jsonObject["type"]; - result.status = jsonObject["status"]; - result.data = jsonObject["data"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (length != null) _result.addAll({"length": length}); - if (type != null) _result.addAll({"type": type}); - if (status != null) _result.addAll({"status": status}); - if (data != null) _result.addAll({"data": data}); - - return _result; - } -} - -class CertificateData { - int? length; - String? data; - - static CertificateData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new CertificateData(); - - result.length = jsonObject["length"]; - result.data = jsonObject["data"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (length != null) _result.addAll({"length": length}); - if (data != null) _result.addAll({"data": data}); - - return _result; - } -} - -class SecurityObjectCertificates { - CertificateData? securityObject; - - static SecurityObjectCertificates? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new SecurityObjectCertificates(); - - result.securityObject = CertificateData.fromJson(jsonObject["securityObject"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (securityObject != null) _result.addAll({"securityObject": securityObject}); - - return _result; - } -} - -class File { - int? readingTime; - int? type; - int? pAStatus; - int? readingStatus; - String? fileID; - FileData? fileData; - SecurityObjectCertificates? certificates; - List docFieldsText = []; - List docFieldsGraphics = []; - List docFieldsOriginals = []; - List notifications = []; - - static File? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new File(); - - result.readingTime = jsonObject["readingTime"]; - result.type = jsonObject["type"]; - result.pAStatus = jsonObject["pAStatus"]; - result.readingStatus = jsonObject["readingStatus"]; - result.fileID = jsonObject["fileID"]; - result.fileData = FileData.fromJson(jsonObject["fileData"]); - result.certificates = SecurityObjectCertificates.fromJson(jsonObject["certificates"]); - if (jsonObject["docFieldsText"] != null) - for (var item in jsonObject["docFieldsText"]) - result.docFieldsText.add(item); - if (jsonObject["docFieldsGraphics"] != null) - for (var item in jsonObject["docFieldsGraphics"]) - result.docFieldsGraphics.add(item); - if (jsonObject["docFieldsOriginals"] != null) - for (var item in jsonObject["docFieldsOriginals"]) - result.docFieldsOriginals.add(item); - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (readingTime != null) _result.addAll({"readingTime": readingTime}); - if (type != null) _result.addAll({"type": type}); - if (pAStatus != null) _result.addAll({"pAStatus": pAStatus}); - if (readingStatus != null) _result.addAll({"readingStatus": readingStatus}); - if (fileID != null) _result.addAll({"fileID": fileID}); - if (fileData != null) _result.addAll({"fileData": fileData}); - if (certificates != null) _result.addAll({"certificates": certificates}); - _result.addAll({"docFieldsText": docFieldsText}); - _result.addAll({"docFieldsGraphics": docFieldsGraphics}); - _result.addAll({"docFieldsOriginals": docFieldsOriginals}); - _result.addAll({"notifications": notifications}); - - return _result; - } -} - -class Application { - int? type; - int? status; - String? applicationID; - String? dataHashAlgorithm; - String? unicodeVersion; - String? version; - List files = []; - - static Application? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Application(); - - result.type = jsonObject["type"]; - result.status = jsonObject["status"]; - result.applicationID = jsonObject["applicationID"]; - result.dataHashAlgorithm = jsonObject["dataHashAlgorithm"]; - result.unicodeVersion = jsonObject["unicodeVersion"]; - result.version = jsonObject["version"]; - if (jsonObject["files"] != null) - for (var item in jsonObject["files"]) - result.files.add(File.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (type != null) _result.addAll({"type": type}); - if (status != null) _result.addAll({"status": status}); - if (applicationID != null) _result.addAll({"applicationID": applicationID}); - if (dataHashAlgorithm != null) _result.addAll({"dataHashAlgorithm": dataHashAlgorithm}); - if (unicodeVersion != null) _result.addAll({"unicodeVersion": unicodeVersion}); - if (version != null) _result.addAll({"version": version}); - _result.addAll({"files": files}); - - return _result; - } -} - -class Value { - int? length; - int? type; - int? status; - String? data; - String? format; - - static Value? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Value(); - - result.length = jsonObject["length"]; - result.type = jsonObject["type"]; - result.status = jsonObject["status"]; - result.data = jsonObject["data"]; - result.format = jsonObject["format"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (length != null) _result.addAll({"length": length}); - if (type != null) _result.addAll({"type": type}); - if (status != null) _result.addAll({"status": status}); - if (data != null) _result.addAll({"data": data}); - if (format != null) _result.addAll({"format": format}); - - return _result; - } -} - -class Attribute { - String? type; - Value? value; - - static Attribute? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Attribute(); - - result.type = jsonObject["type"]; - result.value = Value.fromJson(jsonObject["value"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (type != null) _result.addAll({"type": type}); - if (value != null) _result.addAll({"value": value}); - - return _result; - } -} - -class Authority { - String? data; - Value? friendlyName; - List attributes = []; - - static Authority? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Authority(); - - result.data = jsonObject["data"]; - result.friendlyName = Value.fromJson(jsonObject["friendlyName"]); - if (jsonObject["attributes"] != null) - for (var item in jsonObject["attributes"]) - result.attributes.add(Attribute.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (friendlyName != null) _result.addAll({"friendlyName": friendlyName}); - _result.addAll({"attributes": attributes}); - - return _result; - } -} - -class Extension { - String? data; - String? type; - - static Extension? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Extension(); - - result.data = jsonObject["data"]; - result.type = jsonObject["type"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (type != null) _result.addAll({"type": type}); - - return _result; - } -} - -class Validity { - Value? notAfter; - Value? notBefore; - - static Validity? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Validity(); - - result.notAfter = Value.fromJson(jsonObject["notAfter"]); - result.notBefore = Value.fromJson(jsonObject["notBefore"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (notAfter != null) _result.addAll({"notAfter": notAfter}); - if (notBefore != null) _result.addAll({"notBefore": notBefore}); - - return _result; - } -} - -class CertificateChain { - int? origin; - int? type; - int? version; - int? paStatus; - String? serialNumber; - String? signatureAlgorithm; - String? subjectPKAlgorithm; - Value? fileName; - Validity? validity; - Authority? issuer; - Authority? subject; - List notifications = []; - List extensions = []; - - static CertificateChain? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new CertificateChain(); - - result.origin = jsonObject["origin"]; - result.type = jsonObject["type"]; - result.version = jsonObject["version"]; - result.paStatus = jsonObject["paStatus"]; - result.serialNumber = jsonObject["serialNumber"]; - result.signatureAlgorithm = jsonObject["signatureAlgorithm"]; - result.subjectPKAlgorithm = jsonObject["subjectPKAlgorithm"]; - result.fileName = Value.fromJson(jsonObject["fileName"]); - result.validity = Validity.fromJson(jsonObject["validity"]); - result.issuer = Authority.fromJson(jsonObject["issuer"]); - result.subject = Authority.fromJson(jsonObject["subject"]); - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - if (jsonObject["extensions"] != null) - for (var item in jsonObject["extensions"]) - result.extensions.add(Extension.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (origin != null) _result.addAll({"origin": origin}); - if (type != null) _result.addAll({"type": type}); - if (version != null) _result.addAll({"version": version}); - if (paStatus != null) _result.addAll({"paStatus": paStatus}); - if (serialNumber != null) _result.addAll({"serialNumber": serialNumber}); - if (signatureAlgorithm != null) _result.addAll({"signatureAlgorithm": signatureAlgorithm}); - if (subjectPKAlgorithm != null) _result.addAll({"subjectPKAlgorithm": subjectPKAlgorithm}); - if (fileName != null) _result.addAll({"fileName": fileName}); - if (validity != null) _result.addAll({"validity": validity}); - if (issuer != null) _result.addAll({"issuer": issuer}); - if (subject != null) _result.addAll({"subject": subject}); - _result.addAll({"notifications": notifications}); - _result.addAll({"extensions": extensions}); - - return _result; - } -} - -class SignerInfo { - int? version; - int? paStatus; - String? dataToHash; - String? digestAlgorithm; - String? signatureAlgorithm; - Value? serialNumber; - Value? signature; - Value? subjectKeyIdentifier; - Authority? issuer; - List notifications = []; - List signedAttributes = []; - List certificateChain = []; - - static SignerInfo? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new SignerInfo(); - - result.version = jsonObject["version"]; - result.paStatus = jsonObject["paStatus"]; - result.dataToHash = jsonObject["dataToHash"]; - result.digestAlgorithm = jsonObject["digestAlgorithm"]; - result.signatureAlgorithm = jsonObject["signatureAlgorithm"]; - result.serialNumber = Value.fromJson(jsonObject["serialNumber"]); - result.signature = Value.fromJson(jsonObject["signature"]); - result.subjectKeyIdentifier = Value.fromJson(jsonObject["subjectKeyIdentifier"]); - result.issuer = Authority.fromJson(jsonObject["issuer"]); - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - if (jsonObject["signedAttributes"] != null) - for (var item in jsonObject["signedAttributes"]) - result.signedAttributes.add(Extension.fromJson(item)); - if (jsonObject["certificateChain"] != null) - for (var item in jsonObject["certificateChain"]) - result.certificateChain.add(CertificateChain.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (version != null) _result.addAll({"version": version}); - if (paStatus != null) _result.addAll({"paStatus": paStatus}); - if (dataToHash != null) _result.addAll({"dataToHash": dataToHash}); - if (digestAlgorithm != null) _result.addAll({"digestAlgorithm": digestAlgorithm}); - if (signatureAlgorithm != null) _result.addAll({"signatureAlgorithm": signatureAlgorithm}); - if (serialNumber != null) _result.addAll({"serialNumber": serialNumber}); - if (signature != null) _result.addAll({"signature": signature}); - if (subjectKeyIdentifier != null) _result.addAll({"subjectKeyIdentifier": subjectKeyIdentifier}); - if (issuer != null) _result.addAll({"issuer": issuer}); - _result.addAll({"notifications": notifications}); - _result.addAll({"signedAttributes": signedAttributes}); - _result.addAll({"certificateChain": certificateChain}); - - return _result; - } -} - -class SecurityObject { - int? fileReference; - int? version; - String? objectType; - List notifications = []; - List signerInfos = []; - - static SecurityObject? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new SecurityObject(); - - result.fileReference = jsonObject["fileReference"]; - result.version = jsonObject["version"]; - result.objectType = jsonObject["objectType"]; - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - if (jsonObject["signerInfos"] != null) - for (var item in jsonObject["signerInfos"]) - result.signerInfos.add(SignerInfo.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (fileReference != null) _result.addAll({"fileReference": fileReference}); - if (version != null) _result.addAll({"version": version}); - if (objectType != null) _result.addAll({"objectType": objectType}); - _result.addAll({"notifications": notifications}); - _result.addAll({"signerInfos": signerInfos}); - - return _result; - } -} - -class CardProperties { - int? aTQA; - int? bitRateR; - int? bitRateS; - int? chipTypeA; - int? mifareMemory; - int? rfidType; - int? sAK; - bool? support4; - bool? supportMifare; - String? aTQB; - String? aTR; - String? baudrate1; - String? baudrate2; - String? uID; - - static CardProperties? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new CardProperties(); - - result.aTQA = jsonObject["aTQA"]; - result.bitRateR = jsonObject["bitRateR"]; - result.bitRateS = jsonObject["bitRateS"]; - result.chipTypeA = jsonObject["chipTypeA"]; - result.mifareMemory = jsonObject["mifareMemory"]; - result.rfidType = jsonObject["rfidType"]; - result.sAK = jsonObject["sAK"]; - result.support4 = jsonObject["support4"]; - result.supportMifare = jsonObject["supportMifare"]; - result.aTQB = jsonObject["aTQB"]; - result.aTR = jsonObject["aTR"]; - result.baudrate1 = jsonObject["baudrate1"]; - result.baudrate2 = jsonObject["baudrate2"]; - result.uID = jsonObject["uID"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (aTQA != null) _result.addAll({"aTQA": aTQA}); - if (bitRateR != null) _result.addAll({"bitRateR": bitRateR}); - if (bitRateS != null) _result.addAll({"bitRateS": bitRateS}); - if (chipTypeA != null) _result.addAll({"chipTypeA": chipTypeA}); - if (mifareMemory != null) _result.addAll({"mifareMemory": mifareMemory}); - if (rfidType != null) _result.addAll({"rfidType": rfidType}); - if (sAK != null) _result.addAll({"sAK": sAK}); - if (support4 != null) _result.addAll({"support4": support4}); - if (supportMifare != null) _result.addAll({"supportMifare": supportMifare}); - if (aTQB != null) _result.addAll({"aTQB": aTQB}); - if (aTR != null) _result.addAll({"aTR": aTR}); - if (baudrate1 != null) _result.addAll({"baudrate1": baudrate1}); - if (baudrate2 != null) _result.addAll({"baudrate2": baudrate2}); - if (uID != null) _result.addAll({"uID": uID}); - - return _result; - } -} - -class RFIDSessionData { - int? totalBytesReceived; - int? totalBytesSent; - int? status; - int? extLeSupport; - int? processTime; - CardProperties? cardProperties; - List accessControls = []; - List applications = []; - List securityObjects = []; - List dataGroups = []; - List dataFields = []; - - static RFIDSessionData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new RFIDSessionData(); - - result.totalBytesReceived = jsonObject["totalBytesReceived"]; - result.totalBytesSent = jsonObject["totalBytesSent"]; - result.status = jsonObject["status"]; - result.extLeSupport = jsonObject["extLeSupport"]; - result.processTime = jsonObject["processTime"]; - result.cardProperties = CardProperties.fromJson(jsonObject["cardProperties"]); - if (jsonObject["accessControls"] != null) - for (var item in jsonObject["accessControls"]) - result.accessControls.add(AccessControlProcedureType.fromJson(item)); - if (jsonObject["applications"] != null) - for (var item in jsonObject["applications"]) - result.applications.add(Application.fromJson(item)); - if (jsonObject["securityObjects"] != null) - for (var item in jsonObject["securityObjects"]) - result.securityObjects.add(SecurityObject.fromJson(item)); - if (jsonObject["dataGroups"] != null) - for (var item in jsonObject["dataGroups"]) - result.dataGroups.add(item); - if (jsonObject["dataFields"] != null) - for (var item in jsonObject["dataFields"]) - result.dataFields.add(DataField.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (totalBytesReceived != null) _result.addAll({"totalBytesReceived": totalBytesReceived}); - if (totalBytesSent != null) _result.addAll({"totalBytesSent": totalBytesSent}); - if (status != null) _result.addAll({"status": status}); - if (extLeSupport != null) _result.addAll({"extLeSupport": extLeSupport}); - if (processTime != null) _result.addAll({"processTime": processTime}); - if (cardProperties != null) _result.addAll({"cardProperties": cardProperties}); - _result.addAll({"accessControls": accessControls}); - _result.addAll({"applications": applications}); - _result.addAll({"securityObjects": securityObjects}); - _result.addAll({"dataGroups": dataGroups}); - _result.addAll({"dataFields": dataFields}); - - return _result; - } -} - -class DataField { - String? data; - int? fieldType; - - static DataField? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DataField(); - - result.data = jsonObject["data"]; - result.fieldType = jsonObject["fieldType"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (fieldType != null) _result.addAll({"fieldType": fieldType}); - - return _result; - } -} - -class DocumentReaderAuthenticityCheck { - int? type; - int? status; - String? typeName; - int? pageIndex; - List elements = []; - - static DocumentReaderAuthenticityCheck? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderAuthenticityCheck(); - - result.type = jsonObject["type"]; - result.status = jsonObject["status"]; - result.typeName = jsonObject["typeName"]; - result.pageIndex = jsonObject["pageIndex"]; - if (jsonObject["elements"] != null) - for (var item in jsonObject["elements"]) - result.elements.add(DocumentReaderAuthenticityElement.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (type != null) _result.addAll({"type": type}); - if (status != null) _result.addAll({"status": status}); - if (typeName != null) _result.addAll({"typeName": typeName}); - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - _result.addAll({"elements": elements}); - - return _result; - } -} - -class PDF417Info { - int? errorLevel; - int? columns; - int? rows; - - static PDF417Info? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new PDF417Info(); - - result.errorLevel = jsonObject["errorLevel"]; - result.columns = jsonObject["columns"]; - result.rows = jsonObject["rows"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (errorLevel != null) _result.addAll({"errorLevel": errorLevel}); - if (columns != null) _result.addAll({"columns": columns}); - if (rows != null) _result.addAll({"rows": rows}); - - return _result; - } -} - -class DocumentReaderBarcodeResult { - List fields = []; - - static DocumentReaderBarcodeResult? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderBarcodeResult(); - - if (jsonObject["fields"] != null) - for (var item in jsonObject["fields"]) - result.fields.add(DocumentReaderBarcodeField.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - _result.addAll({"fields": fields}); - - return _result; - } -} - -class DocumentReaderBarcodeField { - int? barcodeType; - int? status; - int? pageIndex; - PDF417Info? pdf417Info; - List? data; - - static DocumentReaderBarcodeField? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderBarcodeField(); - - result.barcodeType = jsonObject["barcodeType"]; - result.status = jsonObject["status"]; - result.pageIndex = jsonObject["pageIndex"]; - result.pdf417Info = PDF417Info.fromJson(jsonObject["pdf417Info"]); - result.data = jsonObject["data"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (barcodeType != null) _result.addAll({"barcodeType": barcodeType}); - if (status != null) _result.addAll({"status": status}); - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (pdf417Info != null) _result.addAll({"pdf417Info": pdf417Info}); - if (data != null) _result.addAll({"data": data}); - - return _result; - } -} - -class DocumentReaderAuthenticityResult { - int? status; - List checks = []; - - static DocumentReaderAuthenticityResult? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderAuthenticityResult(); - - result.status = jsonObject["status"]; - if (jsonObject["checks"] != null) - for (var item in jsonObject["checks"]) - result.checks.add(DocumentReaderAuthenticityCheck.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (status != null) _result.addAll({"status": status}); - _result.addAll({"checks": checks}); - - return _result; - } -} - -class DocumentReaderAuthenticityElement { - int? status; - int? elementType; - int? elementDiagnose; - String? elementTypeName; - String? elementDiagnoseName; - - static DocumentReaderAuthenticityElement? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderAuthenticityElement(); - - result.status = jsonObject["status"]; - result.elementType = jsonObject["elementType"]; - result.elementDiagnose = jsonObject["elementDiagnose"]; - result.elementTypeName = jsonObject["elementTypeName"]; - result.elementDiagnoseName = jsonObject["elementDiagnoseName"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (status != null) _result.addAll({"status": status}); - if (elementType != null) _result.addAll({"elementType": elementType}); - if (elementDiagnose != null) _result.addAll({"elementDiagnose": elementDiagnose}); - if (elementTypeName != null) _result.addAll({"elementTypeName": elementTypeName}); - if (elementDiagnoseName != null) _result.addAll({"elementDiagnoseName": elementDiagnoseName}); - - return _result; - } -} - -class DocumentReaderCompletion { - int? action; - DocumentReaderResults? results; - RegulaException? error; - - static DocumentReaderCompletion? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderCompletion(); - - result.action = jsonObject["action"]; - result.results = DocumentReaderResults.fromJson(jsonObject["results"]); - result.error = RegulaException.fromJson(jsonObject["error"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (action != null) _result.addAll({"action": action}); - if (results != null) _result.addAll({"results": results}); - if (error != null) _result.addAll({"error": error}); - - return _result; - } -} - -class RfidNotificationCompletion { - int? notification; - int? value; - - static RfidNotificationCompletion? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new RfidNotificationCompletion(); - - result.notification = jsonObject["notification"]; - result.value = jsonObject["value"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (notification != null) _result.addAll({"notification": notification}); - if (value != null) _result.addAll({"value": value}); - - return _result; - } -} - -class RegulaException { - int? errorCode; - String? message; - - static RegulaException? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new RegulaException(); - - result.errorCode = jsonObject["errorCode"]; - result.message = jsonObject["message"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (errorCode != null) _result.addAll({"errorCode": errorCode}); - if (message != null) _result.addAll({"message": message}); - - return _result; - } -} - -class PKDCertificate { - String? binaryData; - int? resourceType; - String? privateKey; - - static PKDCertificate? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new PKDCertificate(); - - result.binaryData = jsonObject["binaryData"]; - result.resourceType = jsonObject["resourceType"]; - result.privateKey = jsonObject["privateKey"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (binaryData != null) _result.addAll({"binaryData": binaryData}); - if (resourceType != null) _result.addAll({"resourceType": resourceType}); - if (privateKey != null) _result.addAll({"privateKey": privateKey}); - - return _result; - } -} - -class ImageInputParam { - int? width; - int? height; - int? type; - bool? disableFrameShiftIR; - bool? doFlipYAxis; - - static ImageInputParam? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ImageInputParam(); - - result.width = jsonObject["width"]; - result.height = jsonObject["height"]; - result.type = jsonObject["type"]; - result.disableFrameShiftIR = jsonObject["disableFrameShiftIR"]; - result.doFlipYAxis = jsonObject["doFlipYAxis"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (width != null) _result.addAll({"width": width}); - if (height != null) _result.addAll({"height": height}); - if (type != null) _result.addAll({"type": type}); - if (disableFrameShiftIR != null) _result.addAll({"disableFrameShiftIR": disableFrameShiftIR}); - if (doFlipYAxis != null) _result.addAll({"doFlipYAxis": doFlipYAxis}); - - return _result; - } -} - -class PAResourcesIssuer { - List? data; - String? friendlyName; - List attributes = []; - - static PAResourcesIssuer? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new PAResourcesIssuer(); - - result.data = jsonObject["data"]; - result.friendlyName = jsonObject["friendlyName"]; - if (jsonObject["attributes"] != null) - for (var item in jsonObject["attributes"]) - result.attributes.add(PAAttribute.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (friendlyName != null) _result.addAll({"friendlyName": friendlyName}); - _result.addAll({"attributes": attributes}); - - return _result; - } -} - -class PAAttribute { - String? type; - String? value; - - static PAAttribute? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new PAAttribute(); - - result.type = jsonObject["type"]; - result.value = jsonObject["value"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (type != null) _result.addAll({"type": type}); - if (value != null) _result.addAll({"value": value}); - - return _result; - } -} - -class TAChallenge { - List? data; - String? auxPCD; - String? challengePICC; - String? hashPK; - String? idPICC; - - static TAChallenge? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new TAChallenge(); - - result.data = jsonObject["data"]; - result.auxPCD = jsonObject["auxPCD"]; - result.challengePICC = jsonObject["challengePICC"]; - result.hashPK = jsonObject["hashPK"]; - result.idPICC = jsonObject["idPICC"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (auxPCD != null) _result.addAll({"auxPCD": auxPCD}); - if (challengePICC != null) _result.addAll({"challengePICC": challengePICC}); - if (hashPK != null) _result.addAll({"hashPK": hashPK}); - if (idPICC != null) _result.addAll({"idPICC": idPICC}); - - return _result; - } -} - -class DocumentReaderResultsStatus { - int? overallStatus; - int? optical; - DetailsOptical? detailsOptical; - int? rfid; - DetailsRFID? detailsRFID; - int? portrait; - int? stopList; - - static DocumentReaderResultsStatus? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderResultsStatus(); - - result.overallStatus = jsonObject["overallStatus"]; - result.optical = jsonObject["optical"]; - result.detailsOptical = DetailsOptical.fromJson(jsonObject["detailsOptical"]); - result.rfid = jsonObject["rfid"]; - result.detailsRFID = DetailsRFID.fromJson(jsonObject["detailsRFID"]); - result.portrait = jsonObject["portrait"]; - result.stopList = jsonObject["stopList"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (overallStatus != null) _result.addAll({"overallStatus": overallStatus}); - if (optical != null) _result.addAll({"optical": optical}); - if (detailsOptical != null) _result.addAll({"detailsOptical": detailsOptical}); - if (rfid != null) _result.addAll({"rfid": rfid}); - if (detailsRFID != null) _result.addAll({"detailsRFID": detailsRFID}); - if (portrait != null) _result.addAll({"portrait": portrait}); - if (stopList != null) _result.addAll({"stopList": stopList}); - - return _result; - } -} - -class DetailsOptical { - int? overallStatus; - int? mrz; - int? text; - int? docType; - int? security; - int? imageQA; - int? expiry; - int? vds; - int? pagesCount; - - static DetailsOptical? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DetailsOptical(); - - result.overallStatus = jsonObject["overallStatus"]; - result.mrz = jsonObject["mrz"]; - result.text = jsonObject["text"]; - result.docType = jsonObject["docType"]; - result.security = jsonObject["security"]; - result.imageQA = jsonObject["imageQA"]; - result.expiry = jsonObject["expiry"]; - result.vds = jsonObject["vds"]; - result.pagesCount = jsonObject["pagesCount"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (overallStatus != null) _result.addAll({"overallStatus": overallStatus}); - if (mrz != null) _result.addAll({"mrz": mrz}); - if (text != null) _result.addAll({"text": text}); - if (docType != null) _result.addAll({"docType": docType}); - if (security != null) _result.addAll({"security": security}); - if (imageQA != null) _result.addAll({"imageQA": imageQA}); - if (expiry != null) _result.addAll({"expiry": expiry}); - if (vds != null) _result.addAll({"vds": vds}); - if (pagesCount != null) _result.addAll({"pagesCount": pagesCount}); - - return _result; - } -} - -class DetailsRFID { - int? pa; - int? ca; - int? aa; - int? ta; - int? bac; - int? pace; - int? overallStatus; - - static DetailsRFID? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DetailsRFID(); - - result.pa = jsonObject["pa"]; - result.ca = jsonObject["ca"]; - result.aa = jsonObject["aa"]; - result.ta = jsonObject["ta"]; - result.bac = jsonObject["bac"]; - result.pace = jsonObject["pace"]; - result.overallStatus = jsonObject["overallStatus"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (pa != null) _result.addAll({"pa": pa}); - if (ca != null) _result.addAll({"ca": ca}); - if (aa != null) _result.addAll({"aa": aa}); - if (ta != null) _result.addAll({"ta": ta}); - if (bac != null) _result.addAll({"bac": bac}); - if (pace != null) _result.addAll({"pace": pace}); - if (overallStatus != null) _result.addAll({"overallStatus": overallStatus}); - - return _result; - } -} - -class VDSNCData { - String? type; - int? version; - String? issuingCountry; - dynamic message; - String? signatureAlgorithm; - BytesData? signature; - BytesData? certificate; - List certificateChain = []; - List notifications = []; - - static VDSNCData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new VDSNCData(); - - result.type = jsonObject["type"]; - result.version = jsonObject["version"]; - result.issuingCountry = jsonObject["issuingCountry"]; - result.message = jsonObject["message"]; - result.signatureAlgorithm = jsonObject["signatureAlgorithm"]; - result.signature = BytesData.fromJson(jsonObject["signature"]); - result.certificate = BytesData.fromJson(jsonObject["certificate"]); - if (jsonObject["certificateChain"] != null) - for (var item in jsonObject["certificateChain"]) - result.certificateChain.add(CertificateChain.fromJson(item)); - if (jsonObject["notifications"] != null) - for (var item in jsonObject["notifications"]) - result.notifications.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (type != null) _result.addAll({"type": type}); - if (version != null) _result.addAll({"version": version}); - if (issuingCountry != null) _result.addAll({"issuingCountry": issuingCountry}); - if (message != null) _result.addAll({"message": message}); - if (signatureAlgorithm != null) _result.addAll({"signatureAlgorithm": signatureAlgorithm}); - if (signature != null) _result.addAll({"signature": signature}); - if (certificate != null) _result.addAll({"certificate": certificate}); - _result.addAll({"certificateChain": certificateChain}); - _result.addAll({"notifications": notifications}); - - return _result; - } -} - -class BytesData { - String? data; - int? length; - int? status; - int? type; - - static BytesData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new BytesData(); - - result.data = jsonObject["data"]; - result.length = jsonObject["length"]; - result.status = jsonObject["status"]; - result.type = jsonObject["type"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (data != null) _result.addAll({"data": data}); - if (length != null) _result.addAll({"length": length}); - if (status != null) _result.addAll({"status": status}); - if (type != null) _result.addAll({"type": type}); - - return _result; - } -} - -class ImageInputData { - int? pageIndex; - int? light; - int? type; - int? width; - int? height; - String? bitmap; - List? imgBytes; - - static ImageInputData? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ImageInputData(); - - result.pageIndex = jsonObject["pageIndex"]; - result.light = jsonObject["light"]; - result.type = jsonObject["type"]; - result.width = jsonObject["width"]; - result.height = jsonObject["height"]; - result.bitmap = jsonObject["bitmap"]; - result.imgBytes = jsonObject["imgBytes"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (pageIndex != null) _result.addAll({"pageIndex": pageIndex}); - if (light != null) _result.addAll({"light": light}); - if (type != null) _result.addAll({"type": type}); - if (width != null) _result.addAll({"width": width}); - if (height != null) _result.addAll({"height": height}); - if (bitmap != null) _result.addAll({"bitmap": bitmap}); - if (imgBytes != null) _result.addAll({"imgBytes": imgBytes}); - - return _result; - } -} - -class DocReaderDocumentsDatabase { - String? databaseID; - String? version; - String? date; - String? databaseDescription; - int? countriesNumber; - int? documentsNumber; - int? size; - - static DocReaderDocumentsDatabase? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocReaderDocumentsDatabase(); - - result.databaseID = jsonObject["databaseID"]; - result.version = jsonObject["version"]; - result.date = jsonObject["date"]; - result.databaseDescription = jsonObject["databaseDescription"]; - result.countriesNumber = jsonObject["countriesNumber"]; - result.documentsNumber = jsonObject["documentsNumber"]; - result.size = jsonObject["size"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (databaseID != null) _result.addAll({"databaseID": databaseID}); - if (version != null) _result.addAll({"version": version}); - if (date != null) _result.addAll({"date": date}); - if (databaseDescription != null) _result.addAll({"databaseDescription": databaseDescription}); - if (countriesNumber != null) _result.addAll({"countriesNumber": countriesNumber}); - if (documentsNumber != null) _result.addAll({"documentsNumber": documentsNumber}); - if (size != null) _result.addAll({"size": size}); - - return _result; - } -} - -class DocumentReaderComparison { - int? sourceTypeLeft; - int? sourceTypeRight; - int? status; - - static DocumentReaderComparison? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderComparison(); - - result.sourceTypeLeft = jsonObject["sourceTypeLeft"]; - result.sourceTypeRight = jsonObject["sourceTypeRight"]; - result.status = jsonObject["status"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (sourceTypeLeft != null) _result.addAll({"sourceTypeLeft": sourceTypeLeft}); - if (sourceTypeRight != null) _result.addAll({"sourceTypeRight": sourceTypeRight}); - if (status != null) _result.addAll({"status": status}); - - return _result; - } -} - -class DocumentReaderRfidOrigin { - int? dg; - int? dgTag; - int? entryView; - int? tagEntry; - - static DocumentReaderRfidOrigin? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderRfidOrigin(); - - result.dg = jsonObject["dg"]; - result.dgTag = jsonObject["dgTag"]; - result.entryView = jsonObject["entryView"]; - result.tagEntry = jsonObject["tagEntry"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (dg != null) _result.addAll({"dg": dg}); - if (dgTag != null) _result.addAll({"dgTag": dgTag}); - if (entryView != null) _result.addAll({"entryView": entryView}); - if (tagEntry != null) _result.addAll({"tagEntry": tagEntry}); - - return _result; - } -} - -class DocumentReaderTextSource { - int? sourceType; - String? source; - int? validityStatus; - - static DocumentReaderTextSource? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderTextSource(); - - result.sourceType = jsonObject["sourceType"]; - result.source = jsonObject["source"]; - result.validityStatus = jsonObject["validityStatus"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (sourceType != null) _result.addAll({"sourceType": sourceType}); - if (source != null) _result.addAll({"source": source}); - if (validityStatus != null) _result.addAll({"validityStatus": validityStatus}); - - return _result; - } -} - -class DocumentReaderSymbol { - int? code; - Rect? rect; - int? probability; - - static DocumentReaderSymbol? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderSymbol(); - - result.code = jsonObject["code"]; - result.rect = Rect.fromJson(jsonObject["rect"]); - result.probability = jsonObject["probability"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (code != null) _result.addAll({"code": code}); - if (rect != null) _result.addAll({"rect": rect}); - if (probability != null) _result.addAll({"probability": probability}); - - return _result; - } -} - -class DocumentReaderValidity { - int? sourceType; - int? status; - - static DocumentReaderValidity? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderValidity(); - - result.sourceType = jsonObject["sourceType"]; - result.status = jsonObject["status"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (sourceType != null) _result.addAll({"sourceType": sourceType}); - if (status != null) _result.addAll({"status": status}); - - return _result; - } -} - -class FaceApiParams { - String? url; - String? mode; - Search? searchParams; - int? threshold; - int? serviceTimeout; - String? proxy; - String? proxyPassword; - int? proxyType; - - static FaceApiParams? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new FaceApiParams(); - - result.url = jsonObject["url"]; - result.mode = jsonObject["mode"]; - result.searchParams = Search.fromJson(jsonObject["searchParams"]); - result.threshold = jsonObject["threshold"]; - result.serviceTimeout = jsonObject["serviceTimeout"]; - result.proxy = jsonObject["proxy"]; - result.proxyPassword = jsonObject["proxyPassword"]; - result.proxyType = jsonObject["proxyType"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (url != null) _result.addAll({"url": url}); - if (mode != null) _result.addAll({"mode": mode}); - if (searchParams != null) _result.addAll({"searchParams": searchParams}); - if (threshold != null) _result.addAll({"threshold": threshold}); - if (serviceTimeout != null) _result.addAll({"serviceTimeout": serviceTimeout}); - if (proxy != null) _result.addAll({"proxy": proxy}); - if (proxyPassword != null) _result.addAll({"proxyPassword": proxyPassword}); - if (proxyType != null) _result.addAll({"proxyType": proxyType}); - - return _result; - } -} - -class Search { - int? limit; - double? threshold; - List groupIds = []; - - static Search? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new Search(); - - result.limit = jsonObject["limit"]; - result.threshold = jsonObject["threshold"] == null ? null : jsonObject["threshold"].toDouble(); - if (jsonObject["groupIds"] != null) - for (var item in jsonObject["groupIds"]) - result.groupIds.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (limit != null) _result.addAll({"limit": limit}); - if (threshold != null) _result.addAll({"threshold": threshold}); - _result.addAll({"groupIds": groupIds}); - - return _result; - } -} - -class ImageQA { - int? dpiThreshold; - int? angleThreshold; - bool? focusCheck; - bool? glaresCheck; - bool? colornessCheck; - bool? moireCheck; - List expectedPass = []; - GlaresCheckParams? glaresCheckParams; - int? documentPositionIndent; - - static ImageQA? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ImageQA(); - - result.dpiThreshold = jsonObject["dpiThreshold"]; - result.angleThreshold = jsonObject["angleThreshold"]; - result.focusCheck = jsonObject["focusCheck"]; - result.glaresCheck = jsonObject["glaresCheck"]; - result.colornessCheck = jsonObject["colornessCheck"]; - result.moireCheck = jsonObject["moireCheck"]; - if (jsonObject["expectedPass"] != null) - for (var item in jsonObject["expectedPass"]) - result.expectedPass.add(item); - result.glaresCheckParams = GlaresCheckParams.fromJson(jsonObject["glaresCheckParams"]); - result.documentPositionIndent = jsonObject["documentPositionIndent"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (dpiThreshold != null) _result.addAll({"dpiThreshold": dpiThreshold}); - if (angleThreshold != null) _result.addAll({"angleThreshold": angleThreshold}); - if (focusCheck != null) _result.addAll({"focusCheck": focusCheck}); - if (glaresCheck != null) _result.addAll({"glaresCheck": glaresCheck}); - if (colornessCheck != null) _result.addAll({"colornessCheck": colornessCheck}); - if (moireCheck != null) _result.addAll({"moireCheck": moireCheck}); - _result.addAll({"expectedPass": expectedPass}); - if (glaresCheckParams != null) _result.addAll({"glaresCheckParams": glaresCheckParams}); - if (documentPositionIndent != null) _result.addAll({"documentPositionIndent": documentPositionIndent}); - - return _result; - } -} - -class GlaresCheckParams { - double? imgMarginPart; - double? maxGlaringPart; - - static GlaresCheckParams? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new GlaresCheckParams(); - - result.imgMarginPart = jsonObject["imgMarginPart"] == null ? null : jsonObject["imgMarginPart"].toDouble(); - result.maxGlaringPart = jsonObject["maxGlaringPart"] == null ? null : jsonObject["maxGlaringPart"].toDouble(); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (imgMarginPart != null) _result.addAll({"imgMarginPart": imgMarginPart}); - if (maxGlaringPart != null) _result.addAll({"maxGlaringPart": maxGlaringPart}); - - return _result; - } -} - -class RFIDParams { - List paIgnoreNotificationCodes = []; - - static RFIDParams? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new RFIDParams(); - - if (jsonObject["paIgnoreNotificationCodes"] != null) - for (var item in jsonObject["paIgnoreNotificationCodes"]) - result.paIgnoreNotificationCodes.add(item); - - return result; - } - - Map toJson(){ - Map _result = {}; - - _result.addAll({"paIgnoreNotificationCodes": paIgnoreNotificationCodes}); - - return _result; - } -} - -class OnlineProcessingConfig { - int? mode; - String? url; - dynamic processParam; - int? imageFormat; - double? imageCompressionQuality; - - static OnlineProcessingConfig? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new OnlineProcessingConfig(); - - result.mode = jsonObject["mode"]; - result.url = jsonObject["url"]; - result.processParam = jsonObject["processParam"]; - result.imageFormat = jsonObject["imageFormat"]; - result.imageCompressionQuality = jsonObject["imageCompressionQuality"] == null ? null : jsonObject["imageCompressionQuality"].toDouble(); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (mode != null) _result.addAll({"mode": mode}); - if (url != null) _result.addAll({"url": url}); - if (processParam != null) _result.addAll({"processParam": processParam}); - if (imageFormat != null) _result.addAll({"imageFormat": imageFormat}); - if (imageCompressionQuality != null) _result.addAll({"imageCompressionQuality": imageCompressionQuality}); - - return _result; - } -} - -class ScannerConfig { - String? scenario; - String? livePortrait; - String? extPortrait; - OnlineProcessingConfig? onlineProcessingConfig; - int? cameraId; - - static ScannerConfig? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new ScannerConfig(); - - result.scenario = jsonObject["scenario"]; - result.livePortrait = jsonObject["livePortrait"]; - result.extPortrait = jsonObject["extPortrait"]; - result.onlineProcessingConfig = OnlineProcessingConfig.fromJson(jsonObject["onlineProcessingConfig"]); - result.cameraId = jsonObject["cameraId"]; - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (scenario != null) _result.addAll({"scenario": scenario}); - if (livePortrait != null) _result.addAll({"livePortrait": livePortrait}); - if (extPortrait != null) _result.addAll({"extPortrait": extPortrait}); - if (onlineProcessingConfig != null) _result.addAll({"onlineProcessingConfig": onlineProcessingConfig}); - if (cameraId != null) _result.addAll({"cameraId": cameraId}); - - return _result; - } -} - -class RecognizeConfig { - String? scenario; - String? livePortrait; - String? extPortrait; - OnlineProcessingConfig? onlineProcessingConfig; - String? image; - bool? oneShotIdentification; - List images = []; - List imageInputData = []; - - static RecognizeConfig? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new RecognizeConfig(); - - result.scenario = jsonObject["scenario"]; - result.livePortrait = jsonObject["livePortrait"]; - result.extPortrait = jsonObject["extPortrait"]; - result.onlineProcessingConfig = OnlineProcessingConfig.fromJson(jsonObject["onlineProcessingConfig"]); - result.image = jsonObject["image"]; - result.oneShotIdentification = jsonObject["oneShotIdentification"]; - if (jsonObject["images"] != null) - for (var item in jsonObject["images"]) - result.images.add(item); - if (jsonObject["imageInputData"] != null) - for (var item in jsonObject["imageInputData"]) - result.imageInputData.add(ImageInputData.fromJson(item)); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (scenario != null) _result.addAll({"scenario": scenario}); - if (livePortrait != null) _result.addAll({"livePortrait": livePortrait}); - if (extPortrait != null) _result.addAll({"extPortrait": extPortrait}); - if (onlineProcessingConfig != null) _result.addAll({"onlineProcessingConfig": onlineProcessingConfig}); - if (image != null) _result.addAll({"image": image}); - if (oneShotIdentification != null) _result.addAll({"oneShotIdentification": oneShotIdentification}); - _result.addAll({"images": images}); - _result.addAll({"imageInputData": imageInputData}); - - return _result; - } -} - -class DocumentReaderResults { - String? videoCaptureSessionId; - int? chipPage; - int? irElapsedTime; - int? processingFinishedStatus; - int? elapsedTime; - int? elapsedTimeRFID; - int? morePagesAvailable; - int? rfidResult; - bool? highResolution; - DocumentReaderGraphicResult? graphicResult; - DocumentReaderTextResult? textResult; - List documentPosition = []; - List barcodePosition = []; - List mrzPosition = []; - List imageQuality = []; - String? rawResult; - DocumentReaderNotification? documentReaderNotification; - RFIDSessionData? rfidSessionData; - DocumentReaderAuthenticityResult? authenticityResult; - DocumentReaderBarcodeResult? barcodeResult; - int? ppmIn; - List documentType = []; - DocumentReaderResultsStatus? status; - VDSNCData? vdsncData; - - Future textFieldValueByType(int fieldType) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByType", [rawResult, fieldType]); - } - - Future textFieldValueByTypeLcid(int fieldType, int lcid) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByTypeLcid", [rawResult, fieldType, lcid]); - } - - Future textFieldValueByTypeSource(int fieldType, int source) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByTypeSource", [rawResult, fieldType, source]); - } - - Future textFieldValueByTypeLcidSource(int fieldType, int lcid, int source) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByTypeLcidSource", [rawResult, fieldType, lcid, source]); - } - - Future textFieldValueByTypeSourceOriginal(int fieldType, int source, bool original) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByTypeSourceOriginal", [rawResult, fieldType, source, original]); - } - - Future textFieldValueByTypeLcidSourceOriginal(int fieldType, int lcid, int source, bool original) async { - return await DocumentReader._channel.invokeMethod("textFieldValueByTypeLcidSourceOriginal", [rawResult, fieldType, lcid, source, original]); - } - - Future textFieldByType(int fieldType) async { - String? result = await DocumentReader._channel.invokeMethod("textFieldByType", [rawResult, fieldType]); - if (result == null) return null; - return DocumentReaderTextField.fromJson(json.decode(result)); - } - - Future textFieldByTypeLcid(int fieldType, int lcid) async { - String? result = await DocumentReader._channel.invokeMethod("textFieldByTypeLcid", [rawResult, fieldType, lcid]); - if (result == null) return null; - return DocumentReaderTextField.fromJson(json.decode(result)); - } - - Future graphicFieldByTypeSource(int fieldType, int source) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldByTypeSource", [rawResult, fieldType, source]); - if (result == null) return null; - return DocumentReaderGraphicField.fromJson(json.decode(result)); - } - - Future graphicFieldByTypeSourcePageIndex(int fieldType, int source, int pageIndex) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldByTypeSourcePageIndex", [rawResult, fieldType, source, pageIndex]); - if (result == null) return null; - return DocumentReaderGraphicField.fromJson(json.decode(result)); - } - - Future graphicFieldByTypeSourcePageIndexLight(int fieldType, int source, int pageIndex, int light) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldByTypeSourcePageIndex", [rawResult, fieldType, source, pageIndex, light]); - if (result == null) return null; - return DocumentReaderGraphicField.fromJson(json.decode(result)); - } - - Future graphicFieldImageByType(int fieldType) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldImageByType", [rawResult, fieldType]); - if (result == null) return null; - return Uri.parse("data:image/png;base64," + result.replaceAll('\n', '')); - } - - Future graphicFieldImageByTypeSource(int fieldType, int source) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldImageByTypeSource", [rawResult, fieldType, source]); - if (result == null) return null; - return Uri.parse("data:image/png;base64," + result.replaceAll('\n', '')); - } - - Future graphicFieldImageByTypeSourcePageIndex(int fieldType, int source, int pageIndex) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldImageByTypeSourcePageIndex", [rawResult, fieldType, source, pageIndex]); - if (result == null) return null; - return Uri.parse("data:image/png;base64," + result.replaceAll('\n', '')); - } - - Future graphicFieldImageByTypeSourcePageIndexLight(int fieldType, int source, int pageIndex, int light) async { - String? result = await DocumentReader._channel.invokeMethod("graphicFieldImageByTypeSourcePageIndexLight", [rawResult, fieldType, source, pageIndex, light]); - if (result == null) return null; - return Uri.parse("data:image/png;base64," + result.replaceAll('\n', '')); - } - - Future containers(List resultType) async { - return await DocumentReader._channel.invokeMethod("containers", [rawResult, resultType]); - } - - Future encryptedContainers() async { - return await DocumentReader._channel.invokeMethod("encryptedContainers", [rawResult]); - } - - static DocumentReaderResults? fromJson(jsonObject) { - if (jsonObject == null) return null; - var result = new DocumentReaderResults(); - - result.videoCaptureSessionId = jsonObject["videoCaptureSessionId"]; - result.chipPage = jsonObject["chipPage"]; - result.irElapsedTime = jsonObject["irElapsedTime"]; - result.processingFinishedStatus = jsonObject["processingFinishedStatus"]; - result.elapsedTime = jsonObject["elapsedTime"]; - result.elapsedTimeRFID = jsonObject["elapsedTimeRFID"]; - result.morePagesAvailable = jsonObject["morePagesAvailable"]; - result.rfidResult = jsonObject["rfidResult"]; - result.highResolution = jsonObject["highResolution"]; - result.graphicResult = DocumentReaderGraphicResult.fromJson(jsonObject["graphicResult"]); - result.textResult = DocumentReaderTextResult.fromJson(jsonObject["textResult"]); - if (jsonObject["documentPosition"] != null) - for (var item in jsonObject["documentPosition"]) - result.documentPosition.add(ElementPosition.fromJson(item)); - if (jsonObject["barcodePosition"] != null) - for (var item in jsonObject["barcodePosition"]) - result.barcodePosition.add(ElementPosition.fromJson(item)); - if (jsonObject["mrzPosition"] != null) - for (var item in jsonObject["mrzPosition"]) - result.mrzPosition.add(ElementPosition.fromJson(item)); - if (jsonObject["imageQuality"] != null) - for (var item in jsonObject["imageQuality"]) - result.imageQuality.add(ImageQualityGroup.fromJson(item)); - result.rawResult = jsonObject["rawResult"]; - result.documentReaderNotification = DocumentReaderNotification.fromJson(jsonObject["documentReaderNotification"]); - result.rfidSessionData = RFIDSessionData.fromJson(jsonObject["rfidSessionData"]); - result.authenticityResult = DocumentReaderAuthenticityResult.fromJson(jsonObject["authenticityResult"]); - result.barcodeResult = DocumentReaderBarcodeResult.fromJson(jsonObject["barcodeResult"]); - result.ppmIn = jsonObject["ppmIn"]; - if (jsonObject["documentType"] != null) - for (var item in jsonObject["documentType"]) - result.documentType.add(DocumentReaderDocumentType.fromJson(item)); - result.status = DocumentReaderResultsStatus.fromJson(jsonObject["status"]); - result.vdsncData = VDSNCData.fromJson(jsonObject["vdsncData"]); - - return result; - } - - Map toJson(){ - Map _result = {}; - - if (videoCaptureSessionId != null) _result.addAll({"videoCaptureSessionId": videoCaptureSessionId}); - if (chipPage != null) _result.addAll({"chipPage": chipPage}); - if (irElapsedTime != null) _result.addAll({"irElapsedTime": irElapsedTime}); - if (processingFinishedStatus != null) _result.addAll({"processingFinishedStatus": processingFinishedStatus}); - if (elapsedTime != null) _result.addAll({"elapsedTime": elapsedTime}); - if (elapsedTimeRFID != null) _result.addAll({"elapsedTimeRFID": elapsedTimeRFID}); - if (morePagesAvailable != null) _result.addAll({"morePagesAvailable": morePagesAvailable}); - if (rfidResult != null) _result.addAll({"rfidResult": rfidResult}); - if (highResolution != null) _result.addAll({"highResolution": highResolution}); - if (graphicResult != null) _result.addAll({"graphicResult": graphicResult}); - if (textResult != null) _result.addAll({"textResult": textResult}); - _result.addAll({"documentPosition": documentPosition}); - _result.addAll({"barcodePosition": barcodePosition}); - _result.addAll({"mrzPosition": mrzPosition}); - _result.addAll({"imageQuality": imageQuality}); - if (rawResult != null) _result.addAll({"rawResult": rawResult}); - if (documentReaderNotification != null) _result.addAll({"documentReaderNotification": documentReaderNotification}); - if (rfidSessionData != null) _result.addAll({"rfidSessionData": rfidSessionData}); - if (authenticityResult != null) _result.addAll({"authenticityResult": authenticityResult}); - if (barcodeResult != null) _result.addAll({"barcodeResult": barcodeResult}); - if (ppmIn != null) _result.addAll({"ppmIn": ppmIn}); - _result.addAll({"documentType": documentType}); - if (status != null) _result.addAll({"status": status}); - if (vdsncData != null) _result.addAll({"vdsncData": vdsncData}); - - return _result; - } -} - -// Enum - -class FontStyle { - static const int NORMAL = 0; - static const int BOLD = 1; - static const int ITALIC = 2; - static const int BOLD_ITALIC = 3; -} - -class ERPRMAuthenticity { - static const int NONE = 0; - static const int UV_LUMINESCENCE = 1; - static const int IR_B900 = 2; - static const int IMAGE_PATTERN = 4; - static const int AXIAL_PROTECTION = 8; - static const int UV_FIBERS = 16; - static const int IR_VISIBILITY = 32; - static const int OCR_SECURITY_TEXT = 64; - static const int IPI = 128; - static const int PHOTO_EMBED_TYPE = 512; - static const int HOLOGRAMS = 4096; - static const int PHOTO_AREA = 8192; - static const int PORTRAIT_COMPARISON = 32768; - static const int BARCODE_FORMAT_CHECK = 65536; - static const int KINEGRAM = 131072; - static const int HOLOGRAMS_DETECTION = 524288; - static const int MRZ = 8388608; - static const int STATUS_ONLY = 0x80000000; - static const int OVI = 1024; - static const int LIVENESS = 2097152; - static const int OCR = 4194304; -} - -class ERFIDErrorCodes { - static const int RFID_ERROR_NO_ERROR = 0x00000001; - static const int RFID_ERROR_ALREADY_DONE = 0x00000002; - static const int RFID_ERROR_FAILED = 0xffffffff; - static const int RFID_ERROR_NO_CHIP_DETECTED = 0x80010001; - static const int RFID_ERROR_NOT_AVAILABLE = 0x80010002; - static const int RFID_ERROR_INVALID_PARAMETER = 0x80010004; - static const int RFID_ERROR_NOT_INITIALIZED = 0x80010005; - static const int RFID_ERROR_NOT_ENOUGH_MEMORY = 0x80010006; - static const int RFID_ERROR_INVALID_DIRECTORY = 0x80010008; - static const int RFID_ERROR_UNKNOWN_COMMAND = 0x80010009; - static const int RFID_ERROR_FILE_IO_ERROR = 0x8001000A; - static const int RFID_ERROR_BUSY = 0x8001000B; - static const int RFID_ERROR_OLD_FIRMWARE = 0x8001000C; - static const int RFID_ERROR_PCSC_FAILED = 0x80020000; - static const int RFID_ERROR_PCSC_READER_NOT_AVAILABLE = 0x80020001; - static const int RFID_ERROR_PCSC_CANT_CONNECT_CARD = 0x80020002; - static const int RFID_ERROR_PCSC_CARD_IS_NOT_CONNECTED = 0x80020003; - static const int RFID_ERROR_PCSC_OPERATION_CANCELLED = 0x80020004; - static const int RFID_ERROR_PCSC_CARD_IS_BUSY = 0x80020005; - static const int RFID_ERROR_PCSC_FAILED_SCARD = 0x80020006; - static const int RFID_ERROR_PCSC_EXT_LE_FAILED = 0x80020010; - static const int RFID_ERROR_LAYER6_SECURITY_MANAGER = 0x86000000; - static const int RFID_ERROR_LAYER6_APP_SELECTION_FAILURE = 0x86000001; - static const int RFID_ERROR_LAYER6_MUTUAL_AUTH_MAC_FAIL = 0x86000100; - static const int RFID_ERROR_LAYER6_MUTUAL_AUTH_ENC_FAIL = 0x86000101; - static const int RFID_ERROR_LAYER6_MUTUAL_AUTH_FAILURE = 0x86000102; - static const int RFID_ERROR_LAYER6_MUTUAL_AUTH_FAILURE_DATA = 0x86000103; - static const int RFID_ERROR_LAYER6_SM_DO_8E_MISSING = 0x86000200; - static const int RFID_ERROR_LAYER6_SM_DO_87_MISSING = 0x86000201; - static const int RFID_ERROR_LAYER6_SM_DO_99_MISSING = 0x86000202; - static const int RFID_ERROR_LAYER6_SM_MAC_INCORRECT = 0x86000203; - static const int RFID_ERROR_LAYER6_SM_DO_87_INCORRECT = 0x86000204; - static const int RFID_ERROR_LAYER6_NON_TLV_RESPONSE_DATA = 0x86000300; - static const int RFID_ERROR_LAYER6_WRONG_RND_ICC_LENGTH = 0x86000301; - static const int RFID_ERROR_LAYER6_INT_AUTH_FAILURE = 0x86000302; - static const int RFID_ERROR_LAYER6_MSE_SET_KAT_FAILURE = 0x86000303; - static const int RFID_ERROR_LAYER6_MSE_SET_DST_FAILURE = 0x86000304; - static const int RFID_ERROR_LAYER6_PSO_CERTIFICATE_FAILURE = 0x86000305; - static const int RFID_ERROR_LAYER6_MSE_SET_AT_FAILURE = 0x86000306; - static const int RFID_ERROR_LAYER6_GET_CHALLENGE_FAILURE = 0x86000307; - static const int RFID_ERROR_LAYER6_EXT_AUTH_FAILURE = 0x86000308; - static const int RFID_ERROR_LAYER6_GENERAL_AUTH_FAILURE = 0x86000309; - static const int RFID_ERROR_LAYER6_FILE_NOT_FOUND = 0x80006A82; - static const int RFID_ERROR_LAYER6_FILE_EOF1 = 0x80006282; - static const int RFID_ERROR_LAYER6_FILE_EOF2 = 0x80006B00; - static const int RFID_ERROR_LAYER6_INCORRECT_PARAMS = 0x80006A80; - static const int RFID_ERROR_LAYER6_NO_REFERENCE_DATA = 0x80006A88; - static const int RFID_ERROR_LAYER6_PWD_SUSPEND = 0x800063C1; - static const int RFID_ERROR_LAYER6_PWD_BLOCKED = 0x800063C0; - static const int RFID_ERROR_LAYER6_PWD_DEACTIVATED = 0x80006283; - static const int RFID_ERROR_LAYER6_PWD_BLOCKED2 = 0x80006983; - static const int RFID_ERROR_LAYER6_PWD_DEACTIVATED2 = 0x80006984; - static const int RFID_ERROR_LAYER6_PWD_SUSPEND2 = 0x80006985; - static const int RFID_ERROR_LAYER6_PWD_FAILED = 0x801063C0; - static const int RFID_ERROR_NOT_PERFORMED = 0x83000000; - static const int RFID_ERROR_SESSION_IS_CLOSED = 0x83000001; - static const int RFID_ERROR_SESSION_TERMINAL_UNSUPPORTED_OPERATION = 0x83000002; - static const int RFID_ERROR_SESSION_TERMINAL_TYPE_UNKNOWN = 0x83000010; - static const int RFID_ERROR_SESSION_TERMINAL_TYPE_BAD_CERTIFICATE = 0x83000011; - static const int RFID_ERROR_SESSION_TERMINAL_TYPE_NOT_SET = 0x83000012; - static const int RFID_ERROR_SESSION_PROCEDURE_TYPE_UNKNOWN = 0x83000013; - static const int RFID_ERROR_Session_Procedure_Type_Unsupported = 0x83000014; - static const int RFID_ERROR_SESSION_PROCEDURE_TYPE_NOT_SET = 0x83000015; - static const int RFID_ERROR_SESSION_ACCESS_KEY_UNKNOWN_TYPE = 0x83000016; - static const int RFID_ERROR_SESSION_ACCESS_KEY_UNSUPPORTED_SM_TYPE = 0x83000017; - static const int RFID_ERROR_SESSION_ACCESS_KEY_INCORRECT_SM_TYPE = 0x83000018; - static const int RFID_ERROR_SESSION_ACCESS_KEY_RESTRICTED = 0x83000019; - static const int RFID_ERROR_SESSION_ACCESS_KEY_INCORRECT_DATA = 0x8300001A; - static const int RFID_ERROR_SESSION_ACCESS_KEY_NOT_SET = 0x8300001B; - static const int RFID_ERROR_SESSION_PWD_MANAGEMENT_NOT_AUTHORIZED = 0x8300001C; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_UNKNOWN_TYPE = 0x83000020; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_REQUIRES_SM = 0x83000021; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_REQUIRES_PACE = 0x83000022; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_REQUIRES_CA_KEYS = 0x83000023; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_REQUIRES_TA = 0x83000024; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_REQUIRES_CA = 0x83000025; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_INCORRECT_OPTION_CA = 0x83000026; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_CA_FAILED = 0x83000027; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_TA_FAILED = 0x83000028; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_AA_FAILED = 0x83000029; - static const int RFID_ERROR_SESSION_ACCESS_CONTROL_RI_FAILED = 0x8300002A; - static const int RFID_ERROR_SESSION_PA_SIGNATURE_CHECK_FAILED = 0x83000030; - static const int RFID_ERROR_SESSION_PA_HASH_CHECK_FAILED = 0x83000031; - static const int RFID_ERROR_SESSION_INVALID_AUX_DATA_DATE_OF_EXPIRY = 0x83000040; - static const int RFID_ERROR_SESSION_INVALID_AUX_DATA_DATE_OF_BIRTH = 0x83000041; - static const int RFID_ERROR_SESSION_INVALID_AUX_DATA_COMMUNITY_ID = 0x83000042; - static const int RFID_ERROR_SESSION_E_SIGN_REQUIRES_APP_SELECTION = 0x83000050; - static const int RFID_ERROR_SESSION_E_SIGN_PIN_NOT_SET = 0x83000051; - static const int RFID_ERROR_SESSION_E_SIGN_PIN_NOT_VERIFIED = 0x83000052; - static const int RFID_ERROR_SESSION_INCORRECT_DATA = 0x83000060; - static const int RFID_ERROR_SESSION_FILE_NOT_ENOUGH_DATA = 0x83010000; - static const int RFID_ERROR_SESSION_FILE_INCORRECT_DATA = 0x83020000; - static const int RFID_ERROR_SESSION_FILE_UNEXPECTED_DATA = 0x83030000; - static const int RFID_ERROR_SESSION_FILE_CONTENTS_UNEXPECTED_DATA = 0x83040000; - static const int RFID_ERROR_SESSION_FILE_WRONG_TAG = 0x83050000; - static const int RFID_ERROR_SESSION_FILE_CANT_USE_DATA = 0x83060000; - static const int RFID_ERROR_SESSION_FILE_CANT_READ_DATA = 0x83070000; - static const int RFID_ERROR_SESSION_FILE_ACCESS_DENIED = 0x83080000; - static const int RFID_ERROR_LAYER34_NO_ERROR = 0x84000000; - static const int RFID_ERROR_LAYER34_TIME_OUT = 0x84010000; - static const int RFID_ERROR_LAYER34_COLLISION = 0x84020000; - static const int RFID_ERROR_LAYER34_CRC = 0x84030000; - static const int RFID_ERROR_LAYER34_DATA_INTEGRITY = 0x84040000; - static const int RFID_ERROR_LAYER34_DATA_LENGTH = 0x84050000; - static const int RFID_ERROR_Layer34_RFU = 0x84060000; - static const int RFID_ERROR_LAYER34_COLLISION_TOO_MANY = 0x84070000; - static const int RFID_ERROR_LAYER34_PROTOCOL_B = 0x84080000; - static const int RFID_ERROR_LAYER34_DATA_CONTENTS = 0x84090000; - static const int RFID_ERROR_LAYER34_PROTOCOL = 0x840A0000; - static const int RFID_ERROR_LAYER34_GLOBAL_TIME_OUT = 0x840B0000; - static const int RFID_ERROR_LAYER34_MIFARE_AUTH = 0x840C0000; - static const int RFID_ERROR_LAYER34_SAM_ERROR = 0x840D0000; - static const int RFID_ERROR_LAYER34_SAM_COLLISION = 0x840E0000; - static const int RFID_ERROR_LAYER34_SAM_ACKNOWLEDGE = 0x840F0000; -} - -class ELDSParsingErrorCodes { - static const int ERR_LDS_OK = 0x00000001; - static const int ERR_LDS_ASN_INCORRECT_DATA = 0x80000001; - static const int RR_LDS_ASN_NOT_ENOUGH_DATA = 0x80000002; - static const int ERR_LDS_ASN_CONTENTS_UNEXPECTED_DATA = 0x80000003; - static const int ERR_LDS_ASN_SIGNED_DATA_INCORRECT_DATA = 0x80000008; - static const int ERR_LDS_ASN_SIGNED_DATA_ENCAP_CONTENTS_INCORRECT_DATA = 0x80000009; - static const int ERR_LDS_ASN_SIGNED_DATA_VERSION_INCORRECT_DATA = 0x8000000A; - static const int ERR_LDS_ASN_SIGNED_DATA_DIGEST_ALGORITHMS_INCORRECT_DATA = 0x80000011; - static const int ERR_LDS_ASN_LDS_OBJECT_INCORRECT_DATA = 0x80000013; - static const int ERR_LDS_ASN_LDS_OBJECT_VERSION_INCORRECT_DATA = 0x80000014; - static const int ERR_LDS_ASN_LDS_OBJECT_DIGEST_ALGORITHM_INCORRECT_DATA = 0x80000015; - static const int ERR_LDS_ASN_LDS_OBJECT_DG_HASHES_INCORRECT_DATA = 0x80000016; - static const int ERR_LDS_ASN_LDS_OBJECT_VERSION_INFO_INCORRECT_DATA = 0x80000012; - static const int ERR_LDS_ASN_CERTIFICATE_INCORRECT_DATA = 0x80000017; - static const int ERR_LDS_ASN_CERTIFICATE_VERSION_INCORRECT_DATA = 0x80000018; - static const int ERR_LDS_ASN_CERTIFICATE_SN_INCORRECT_DATA = 0x80000019; - static const int ERR_LDS_ASN_CERTIFICATE_SIGNATURE_INCORRECT_DATA = 0x8000001A; - static const int ERR_LDS_ASN_CERTIFICATE_ISSUER_INCORRECT_DATA = 0x8000001B; - static const int ERR_LDS_ASN_CERTIFICATE_VALIDITY_INCORRECT_DATA = 0x8000001C; - static const int ERR_LDS_ASN_CERTIFICATE_SUBJECT_INCORRECT_DATA = 0x8000001D; - static const int ERR_LDS_ASN_CERTIFICATE_SUBJECT_PK_INCORRECT_DATA = 0x8000001E; - static const int ERR_LDS_ASN_CERTIFICATE_EXTENSIONS_INCORRECT_DATA = 0x8000001F; - static const int ERR_LDS_ASN_SIGNER_INFO_INCORRECT_DATA = 0x80000020; - static const int ERR_LDS_ASN_SIGNER_INFO_VERSION_INCORRECT_DATA = 0x80000021; - static const int ERR_LDS_ASN_SIGNER_INFO_SID_INCORRECT_DATA = 0x80000022; - static const int ERR_LDS_ASN_SIGNER_INFO_DIGEST_ALG_INCORRECT_DATA = 0x80000023; - static const int ERR_LDS_ASN_SIGNER_INFO_SIGNED_ATTRS_INCORRECT_DATA = 0x80000024; - static const int ERR_LDS_ASN_SIGNER_INFO_SIGN_ALG_INCORRECT_DATA = 0x80000025; - static const int ERR_LDS_ASN_SIGNER_INFO_SIGNATURE_INCORRECT_DATA = 0x80000026; - static const int ERR_LDS_ASN_SIGNER_INFO_UNSIGNED_ATTRS_INCORRECT_DATA = 0x80000027; - static const int ERR_LDS_ICAO_LDS_OBJECT_UNSUPPORTED_DIGEST_ALGORITHM = 0x80000030; - static const int ERR_LDS_ICAO_SIGNED_DATA_SIGNER_INFOS_EMPTY = 0x80000031; - static const int ERR_LDS_ICAO_SIGNER_INFO_UNSUPPORTED_DIGEST_ALGORITHM = 0x80000032; - static const int ERR_LDS_ICAO_SIGNER_INFO_UNSUPPORTED_SIGNATURE_ALGORITHM = 0x80000033; - static const int ERR_LDS_ICAO_SIGNER_INFO_MESSAGE_DIGEST_ERROR = 0x80000034; - static const int ERR_LDS_ICAO_SIGNER_INFO_SIGNED_ATTRS_MISSED = 0x80000036; - static const int ERR_LDS_AUTH_SIGNER_INFO_CANT_FIND_CERTIFICATE = 0x80000035; - static const int ERR_LDS_AUTH_ERROR = 0x80000050; - static const int ERR_LDS_AUTH_UNSUPPORTED_SIGNATURE_ALGORITHM = 0x80000051; - static const int ERR_LDS_AUTH_UNSUPPORTED_PUBLIC_KEY_ALGORITHM = 0x80000052; - static const int ERR_LDS_AUTH_MESSED_ALGORITHMS = 0x80000053; - static const int ERR_LDS_AUTH_PUBLIC_KEY_DATA_INVALID = 0x80000054; - static const int ERR_LDS_AUTH_ALGORITHM_PARAMETERS_DATA_INVALID = 0x80000055; - static const int ERR_LDS_AUTH_SIGNATURE_DATA_INVALID = 0x80000056; - static const int ERR_LDS_AUTH_UNSUPPORTED_DIGEST_ALGORITHM = 0x80000057; - static const int ERR_LDS_AUTH_SIGNATURE_DATA_INCORRECT = 0x80000058; - static const int ERR_LDS_AUTH_ALGORITHM_PARAMETERS_NOT_DEFINED = 0x80000059; - static const int ERR_LDS_AUTH_SIGNATURE_CHECK_FAILED = 0x8000005A; - static const int ERR_LDS_DG_WRONG_TAH = 0x80000070; - static const int ERR_LDS_DG_CONTENTS_UNEXPECTED_DATA = 0x80000071; - static const int ERR_LDS_BAP_SYMMETRIC_CYPHER_CANT_INITIALIZE = 0x81000011; - static const int ERR_LDS_PACE_INFO_NOT_AVAILABLE = 0x81000020; - static const int ERR_LDS_PACE_SYMMETRIC_CYPHER_CANT_INITIALIZE = 0x81000021; - static const int ERR_LDS_PACE_KEY_AGREEMENT_CANT_INITIALIZE = 0x81000022; - static const int ERR_LDS_PACE_EPHEMERAL_KEYS_CANT_CREATE = 0x81000023; - static const int ERR_LDS_PACE_MAPPING_CANT_DECODE_NONCE = 0x81000024; - static const int ERR_LDS_PACE_SHARED_SECRET_CANT_CREATE = 0x81000025; - static const int ERR_LDS_PACE_DOMAIN_PARAMS_UNSUPPORTED_FORMAT = 0x81000026; - static const int ERR_LDS_PACE_EPHEMERAL_KEYS_INCORRECT = 0x81000027; - static const int ERR_LDS_PACE_MAPPING_EPHEMERAL_KEYS_INCORRECT = 0x81000028; - static const int ERR_LDS_PACE_MAPPING_CANT_PERFORM = 0x81000029; - static const int ERR_LDS_PACE_NON_MATCHING_AUTH_TOKENS = 0x8100002A; - static const int ERR_LDS_PACE_CAM_DATA_INCORRECT = 0x8100002B; - static const int ERR_LDS_PACE_CAM_DATA_CANT_VERIFY = 0x8100002C; - static const int ERR_LDS_PACE_CAM_DATA_NON_MATCHING = 0x8100002D; - static const int ERR_LDS_PACE_IM_SCHEME_INCORRECT = 0x8100002E; - static const int ERR_LDS_PACE_IM_RANDOM_MAPPING_FAILED = 0x8100002F; - static const int ERR_LDS_CA_CANT_FIND_PUBLIC_KEY = 0x81000030; - static const int ERR_LDS_CA_CANT_FIND_INFO = 0x81000031; - static const int ERR_LDS_CA_INCORRECT_VERSION = 0x81000032; - static const int ERR_LDS_CA_CANT_FIND_DOMAIN_PARAMETERS = 0x81000033; - static const int ERR_LDS_CA_KEY_AGREEMENT_CANT_INITIALIZE = 0x81000034; - static const int ERR_LDS_CA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM = 0x81000035; - static const int ERR_LDS_CA_EPHEMERAL_KEYS_CANT_CREATE = 0x81000036; - static const int ERR_LDS_CA_SHARED_SECRET_CANT_CREATE = 0x81000037; - static const int ERR_LDS_CA_NON_MATCHING_AUTH_TOKENS = 0x81000038; - static const int ERR_LDS_TA_INCORRECT_VERSION = 0x81000040; - static const int ERR_LDS_TA_CANT_BUILD_CERTIFICATE_CHAIN = 0x81000041; - static const int ERR_LDS_TA_CANT_FIND_IS_PRIVATE_KEY = 0x81000042; - static const int ERR_LDS_TA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM = 0x81000043; - static const int ERR_LDS_TA_SIGNATURE_BUILDING_ERROR = 0x81000044; - static const int ERR_LDS_TA_INVALID_KEY_ALGORITHM_PARAMETERS = 0x81000045; - static const int ERR_LDS_AA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM = 0x81000050; - static const int ERR_LDS_AA_PUBLIC_KEY_INCORRECT_DATA = 0x81000051; - static const int ERR_LDS_AA_PUBLIC_KEY_INCORRECT_PARAMETERS = 0x81000052; - static const int ERR_LDS_AA_PUBLIC_KEY_UNDEFINED_PARAMETERS = 0x81000053; - static const int ERR_LDS_AA_SIGNATURE_INCORRECT_DATA = 0x81000054; - static const int ERR_LDS_AA_UNSUPPORTED_RECOVERY_SCHEME = 0x81000055; - static const int ERR_LDS_AA_INCORRECT_TRAILER = 0x81000056; - static const int ERR_LDS_AA_UNSUPPORTED_DIGEST_ALGORITHM = 0x81000057; - static const int ERR_LDS_RI_SECTOR_KEY_CANT_FIND = 0x81000070; - static const int ERR_LDS_RI_SECTOR_KEY_INCORRECT_DATA = 0x81000071; - static const int ERR_LDS_RI_SECTOR_KEY_INCOMPLETE_DATA = 0x81000072; - static const int ERR_LDS_CV_CERTIFICATE_MISSING_MANDATORY_DATA_PK = 0x81000060; - static const int ERR_LDS_CV_CERTIFICATE_PUBLIC_KEY_UNSUPPORTED = 0x81000062; - static const int ERR_LDS_CV_CERTIFICATE_CHAT_UNSUPPORTED_TERMINAL_TYPE = 0x81000063; - static const int ERR_LDS_CV_CERTIFICATE_PRIVATE_KEY_UNSUPPORTED = 0x8100006; - static const int ERR_LDS_CV_CERTIFICATE_PRIVATE_KEY_INVALID_PARAMS = 0x81000065; - static const int ERR_LDS_CV_CERTIFICATE_INCORRECT_DATA = 0x81000160; - static const int ERR_LDS_CV_CERTIFICATE_CPI_INCORRECT_DATA = 0x81000161; - static const int ERR_LDS_CV_CERTIFICATE_CAR_INCORRECT_DATA = 0x81000162; - static const int ERR_LDS_CV_CERTIFICATE_PUBLIC_KEY_INCORRECT_DATA = 0x81000163; - static const int ERR_LDS_CV_CERTIFICATE_CHR_INCORRECT_DATA = 0x81000164; - static const int ERR_LDS_CV_CERTIFICATE_CHAT_INCORRECT_DATA = 0x81000165; - static const int ERR_LDS_CV_CERTIFICATE_VALID_FROM_INCORRECT_DATA = 0x81000166; - static const int ERR_LDS_CV_CERTIFICATE_VALID_TO_INCORRECT_DATA = 0x81000167; - static const int ERR_LDS_CV_CERTIFICATE_EXTENSIONS_INCORRECT_DATA = 0x81000168; - static const int ERR_LDS_CV_CERTIFICATE_PRIVATE_KEY_INCORRECT_DATA = 0x81000169; - static const int ERR_LDS_CV_CERTIFICATE_PRIVATE_KEY_MISSING = 0x8100016A; - static const int ERR_LDS_VDS_UNSUPPORTED_VERSION = 0x81000200; - static const int ERR_LDS_VDS_ISSUING_COUNTRY_SIZE = 0x81000201; - static const int ERR_LDS_VDS_ISSUING_COUNTRY_INCORRECT_DATA = 0x81000202; - static const int ERR_LDS_VDS_SIGNER_CERTIFICATE_SIZE = 0x81000203; - static const int ERR_LDS_VDS_SIGNER_CERTIFICATE_DATA = 0x81000204; - static const int ERR_LDS_VDS_SIGNATURE_INCORRECT_DATA = 0x81000205; - static const int ERR_LDS_VDS_NC_INCORRECT_DATA = 0x81000300; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_DATA = 0x81000301; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_HEADER = 0x81000302; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_TYPE = 0x81000303; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_VERSION = 0x81000304; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_ISSUING_COUNTRY = 0x81000305; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_MESSAGE = 0x81000306; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_SIGNATURE = 0x81000307; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_SIG_ALGORITHM = 0x81000308; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_CERTIFICATE = 0x81000309; - static const int ERR_LDS_VDS_NC_MISSING_OR_INCORRECT_SIG_VALUE = 0x8100030A; -} - -class ERFIDCertificateType { - static const int CT_UNDEFINED = 0; - static const int CT_CSCA = 1; - static const int CT_CSCA_LINK = 2; - static const int CT_DS = 3; - static const int CT_MLS = 4; - static const int CT_DEV_LS = 5; - static const int CT_DEF_LS = 6; - static const int CT_BLS = 7; - static const int CT_LDS2 = 8; - static const int CT_BCS = 9; - static const int CT_BCSNC = 10; -} - -class RGLMeasureSystem { - static const int METRIC = 0; - static const int IMPERIAL = 1; -} - -class ERPRMResultType { - static const int NONE = -1; - static const int RPRM_RESULT_TYPE_EMPTY = 0; - static const int RPRM_RESULT_TYPE_RAW_IMAGE = 1; - static const int RPRM_RESULT_TYPE_FILE_IMAGE = 2; - static const int RPRM_RESULT_TYPE_MRZ_OCR_EXTENDED = 3; - static const int RPRM_RESULT_TYPE_BARCODES = 5; - static const int RPRM_RESULT_TYPE_GRAPHICS = 6; - static const int RPRM_RESULT_TYPE_MRZ_TEST_QUALITY = 7; - static const int RPRM_RESULT_TYPE_DOCUMENT_TYPES_CANDIDATES = 8; - static const int RPRM_RESULT_TYPE_CHOSEN_DOCUMENT_TYPE_CANDIDATE = 9; - static const int RPRM_RESULT_TYPE_DOCUMENTS_INFO_LIST = 10; - static const int RPRM_RESULT_TYPE_OCR_LEXICAL_ANALYZE = 15; - static const int RPRM_RESULT_TYPE_RAW_UNCROPPED_IMAGE = 16; - static const int RPRM_RESULT_TYPE_VISUAL_OCR_EXTENDED = 17; - static const int RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA = 18; - static const int RPRM_RESULT_TYPE_BAR_CODES_IMAGE_DATA = 19; - static const int RPRM_RESULT_TYPE_AUTHENTICITY = 20; - static const int RPRM_RESULT_TYPE_EOS_IMAGE = 23; - static const int RPRM_RESULT_TYPE_BAYER_IMAGE = 24; - static const int RPRM_RESULT_TYPE_MAGNETIC_STRIPE = 25; - static const int RPRM_RESULT_TYPE_MAGNETIC_STRIPE_TEXT_DATA = 26; - static const int RPRM_RESULT_TYPE_FIELD_FILE_IMAGE = 27; - static const int RPRM_RESULT_TYPE_DATABASE_CHECK = 28; - static const int RPRM_RESULT_TYPE_FINGERPRINT_TEMPLATE_ISO = 29; - static const int RPRM_RESULT_TYPE_INPUT_IMAGE_QUALITY = 30; - static const int RPRM_RESULT_TYPE_INTERNAL_RFID_SESSION = 48; - static const int RPRM_RESULT_TYPE_INTERNAL_ENCRYPTED_RCL = 49; - static const int RPRM_RESULT_TYPE_INTERNAL_LICENSE = 50; - static const int RPRM_RESULT_TYPE_TEXT = 36; - static const int RPRM_RESULT_TYPE_IMAGES = 37; - static const int RPRM_RESULT_TYPE_HOLO_PARAMS = 47; - static const int RPRM_RESULT_TYPE_DOCUMENT_POSITION = 85; - static const int RPRM_RESULT_TYPE_CUSTOM = 100; - static const int RFID_RESULT_TYPE_RFID_RAW_DATA = 101; - static const int RFID_RESULT_TYPE_RFID_TEXT_DATA = 102; - static const int RFID_RESULT_TYPE_RFID_IMAGE_DATA = 103; - static const int RFID_RESULT_TYPE_RFID_BINARY_DATA = 104; - static const int RFID_RESULT_TYPE_RFID_ORIGINAL_GRAPHICS = 105; - static const int RPRM_RESULT_TYPE_BARCODE_POSITION = 62; - static const int RPRM_RESULT_TYPE_MRZ_POSITION = 61; - static const int RPRM_RESULT_TYPE_LIVE_PORTRAIT = 32; - static const int RPRM_RESULT_TYPE_STATUS = 33; - static const int RPRM_RESULT_TYPE_PORTRAIT_COMPARISON = 34; - static const int RPRM_RESULT_TYPE_EXT_PORTRAIT = 35; -} - -class CameraTypes { - static const String FRONT = "front"; - static const String BACK = "back"; -} - -class FrameShapeType { - static const int LINE = 0; - static const int CORNER = 1; -} - -class ERFIDBaudRate { - static const int rfbr_106 = 1; - static const int rfbr_212 = 2; - static const int rfbr_424 = 4; - static const int rfbr_848 = 8; -} - -class ERPRMFieldVerificationResult { - static const int RCF_DISABLED = 0; - static const int RCF_VERIFIED = 1; - static const int RCF_NOT_VERIFIED = 2; - static const int RCF_COMPARE_TRUE = 3; - static const int RCF_COMPARE_FALSE = 4; -} - -class DocReaderAction { - static const int COMPLETE = 0; - static const int PROCESS = 1; - static const int MORE_PAGES_AVAILABLE = 2; - static const int CANCEL = 3; - static const int ERROR = 4; - static const int PROCESS_WHITE_FLASHLIGHT = 5; - static const int TIMEOUT = 6; - static const int PROCESSING_ON_SERVICE = 7; - static const int NOTIFICATION = 101; - static const int PROCESS_WHITE_UV_IMAGES = 102; - static const int PROCESS_IR_FRAME = 103; -} - -class EProcessGLCommands { - static const int ePC_ProcMgr_SetLicense = 12100; - static const int ePC_ProcMgr_Process = 12101; - static const int ePC_ProcMgr_ProcessAsync = 12102; - static const int ePC_ProcMgr_Init = 12103; - static const int ePC_ProcMgr_ProcessImage = 12104; - static const int ePC_ProcMgr_StartNewDocument = 12105; - static const int ePC_ProcMgr_StartNewPage = 12106; - static const int ePC_ProcMgr_Unload = 12107; - static const int ePC_ProcMgr_CheckDatabase = 12109; - static const int ePC_ProcMgr_ComparePortraits = 12111; - static const int ePC_RFID_SetTCCParams = 12522; - static const int ePC_RFID_SetReprocessingParams = 12523; -} - -class PKDResourceType { - static const int CERTIFICATE_PA = 0; - static const int CERTIFICATE_TA = 1; - static const int LDIF = 2; - static const int CRL = 3; - static const int ML = 4; - static const int DEFL = 5; - static const int DEVL = 6; - static const int BL = 7; - - static int getType(String value) { - switch (value) { - case "pa": - return CERTIFICATE_PA; - case "ta": - return CERTIFICATE_TA; - case "ldif": - return LDIF; - case "crl": - return CRL; - case "ml": - return ML; - case "defl": - return DEFL; - case "devl": - return DEVL; - case "bl": - return BL; - default: - return CERTIFICATE_PA; - } - } -} - -class ERFIDAuthenticationProcedureType { - static const int aptUndefined = 0; - static const int aptStandard = 1; - static const int aptAdvanced = 2; - static const int aptGeneral = 3; -} - -class DocumentReaderErrorCodes { - static const int INITIALIZATION_CORE_ABSENT = 0; - static const int INITIALIZATION_FAILED = 1; - static const int INCORRECT_SCENARIO = 2; - static const int NO_RESULT = 3; - static const int REMOVE_DATABASE = 4; - static const int FETCHING_DATABASE = 5; - static const int DB_ID_NOT_FOUND = 6; - static const int DB_DESCRIPTION_NOT_FOUND = 7; - static const int SAVE_DB = 8; - static const int DOWNLOAD_DB_INCORRECT_CHECKSUM = 9; - static const int DB_DOWNLOAD = 10; - static const int LICENSE_ABSENT_OR_CORRUPTED = 13; - static const int LICENSE_INVALID_DATE = 14; - static const int LICENSE_INVALID_VERSION = 15; - static const int LICENSE_INVALID_DEVICE_ID = 16; - static const int LICENSE_INVALID_SYSTEM_OR_APP_ID = 17; - static const int LICENSE_NO_CAPABILITIES = 18; - static const int LICENSE_NO_AUTHENTICITY = 19; - static const int RECORD_PROCESS_INVALID_OUTPUT_URL = 20; - static const int LICENSE_ONLINE_ERROR = 21; - static const int LICENSE_NO_DATABASE = 22; - static const int LICENSE_DATABASE_INCORRECT = 23; - static const int INVALID_TCC_PARAMS = 24; - static const int RFID_IN_PROGRESS = 25; - static const int NATIVE_JAVA_EXCEPTION = 1000; - static const int BACKEND_ONLINE_PROCESSING = 303; - static const int WRONG_INPUT = 400; - static const int STATE_EXCEPTION = 500; - static const int BLE_EXCEPTION = 600; - static const int FEATURE_BLUETOOTH_LE_NOT_SUPPORTED = 601; - static const int APP_BACKGROUND = 700; - static const int ONLINE_PROCESSING_WRONG_INPUT = 800; -} - -class ScenarioIdentifier { - static const String SCENARIO_MRZ = "Mrz"; - static const String SCENARIO_BARCODE = "Barcode"; - static const String SCENARIO_LOCATE = "Locate"; - static const String SCENARIO_OCR = "Ocr"; - static const String SCENARIO_DOCTYPE = "DocType"; - static const String SCENARIO_MRZ_OR_BARCODE = "MrzOrBarcode"; - static const String SCENARIO_MRZ_OR_LOCATE = "MrzOrLocate"; - static const String SCENARIO_MRZ_AND_LOCATE = "MrzAndLocate"; - static const String SCENARIO_MRZ_OR_OCR = "MrzOrOcr"; - static const String SCENARIO_MRZ_OR_BARCODE_OR_OCR = "MrzOrBarcodeOrOcr"; - static const String SCENARIO_LOCATE_VISUAL_AND_MRZ_OR_OCR = "LocateVisual_And_MrzOrOcr"; - static const String SCENARIO_FULL_PROCESS = "FullProcess"; - static const String SCENARIO_FULL_AUTH = "FullAuth"; - static const String SCENARIO_ID3RUS = "Id3Rus"; - static const String SCENARIO_RUS_STAMP = "RusStamp"; - static const String SCENARIO_OCR_FREE = "OcrFree"; - static const String SCENARIO_CREDIT_CARD = "CreditCard"; - static const String SCENARIO_CAPTURE = "Capture"; - static const String SCENARIO_BARCODE_AND_LOCATE = "BarcodeAndLocate"; -} - -class ERFIDAccessControlProcedureType { - static const int ACPT_UNDEFINED = 0; - static const int ACPT_BAC = 1; - static const int ACPT_PACE = 2; - static const int ACPT_CA = 3; - static const int ACPT_TA = 4; - static const int ACPT_AA = 5; - static const int ACPT_RI = 6; - static const int ACPT_CARD_INFO = 10; -} - -class ERFIDNotificationCodes { - static const int RFID_NOTIFICATION_ERROR = 0x00010000; - static const int RFID_NOTIFICATION_DOCUMENT_READY = 0x00010001; - static const int RFID_NOTIFICATION_READ_PROTOCOL4 = 0x00010003; - static const int RFID_NOTIFICATION_READ_PROTOCOL3 = 0x0001000A; - static const int RFID_NOTIFICATION_PROGRESS = 0x0001000B; - static const int RFID_NOTIFICATION_TA_STEP = 0x0001000E; - static const int RFID_NOTIFICATION_SM_REQUIRED = 0x0001000F; - static const int RFID_NOTIFICATION_ISO_ERROR = 0x00011000; - static const int RFID_NOTIFICATION_PA_REQUEST = 0x00013000; - static const int RFID_NOTIFICATION_SM_ESTABLISHED = 0x0001400F; - static const int RFID_NOTIFICATION_PCSC_READER_DISCONNECTED = 0x00020000; - static const int RFID_NOTIFICATION_PCSC_READER_LIST_CHANGED = 0x00020001; - static const int RFID_NOTIFICATION_PCSC_BYTES_RECEIVED = 0x00020002; - static const int RFID_NOTIFICATION_PCSC_TOTAL_READING_TIME = 0x00020003; - static const int RFID_NOTIFICATION_PCSC_DATA_RECEIVED = 0x00020004; - static const int RFID_NOTIFICATION_PCSC_BYTES_SENT = 0x00020005; - static const int RFID_NOTIFICATION_PCSC_TOTAL_READING_SPEED = 0x00020006; - static const int RFID_NOTIFICATION_PCSC_TOTAL_PROCESS_TIME = 0x00020007; - static const int RFID_NOTIFICATION_PCSC_READER_LIST_CHANGING = 0x00020008; - static const int RFID_NOTIFICATION_PCSC_EXT_LENGTH_SUPPORT = 0x00020010; - static const int RFID_NOTIFICATION_PA_CERTIFICATE_CHAIN = 0x00020011; - static const int RFID_NOTIFICATION_PA_CERTIFICATE_CHAIN_ITEM = 0x00020012; - static const int RFID_NOTIFICATION_SCENARIO = 0x00020020; - static const int RFID_NOTIFICATION_PCSC_READING_DATAGROUP = 0x00030000; - static const int RFID_NOTIFICATION_PCSC_FILE_NOT_FOUND = 0x00040000; - static const int RFID_NOTIFICATION_PCSC_END_OF_FILE = 0x00050000; - static const int RFID_NOTIFICATION_PCSC_FILE_ACCESS_DENIED = 0x00060000; - static const int RFID_NOTIFICATION_PCSC_APPLICATION_SELECTED = 0x00070000; - static const int RFID_NOTIFICATION_AC_PROCEDURE_START = 0x00080000; - static const int RFID_NOTIFICATION_AC_PROCEDURE_FINISH = 0x00090000; - static const int RFID_NOTIFICATION_PA_SECURITY_OBJECT_CHECK = 0x000A0000; - static const int RFID_NOTIFICATION_PA_FILE_CHECK = 0x000B0000; - static const int RFID_NOTIFICATION_PCSC_UPDATING_DATAGROUP = 0x000C0000; - static const int RFID_NOTIFICATION_AUXILIARY_DATA_VALIDATION = 0x000D0000; - static const int RFID_NOTIFICATION_RI_SECTOR_ID = 0x000E0000; - static const int RFID_NOTIFICATION_BIOMETRICS_EMPTY_PLACEHOLDER = 0x000F0000; -} - -class ERFIDPasswordType { - static const int PPT_UNKNOWN = 0; - static const int PPT_MRZ = 1; - static const int PPT_CAN = 2; - static const int PPT_PIN = 3; - static const int PPT_PUK = 4; - static const int PPT_PIN_ESIGN = 5; - static const int PPT_SAI = 6; -} - -class BarcodeResult { - static const int NO_ERR = 0; - static const int NULL_PTR_ERR = -6001; - static const int BAD_ARG_ERR = -6002; - static const int SIZE_ERR = -6003; - static const int RANGE_ERR = -6004; - static const int INTERNAL_ERR = -6005; - static const int TRY_EXCEPT_ERR = -6006; - static const int BAR_CODE_NOT_FOUND = -6008; - static const int BAR_CODE_DECODE_ERR = -6010; - static const int NO_USER_DLL_FOUND = -6019; - static const int NO_IPP_DLL_FOUND = -6020; - static const int IPP_EXEC_ERR = -6024; - static const int IPP_TRY_EXCEPT_ERR = -6025; - static const int BARCODE_ERROR_INPUT_PARAM = -11001; - static const int BARCODE_ERROR_FINIT = -11006; - static const int BARCODE_ERROR_NOT_LOAD_IP_DECODED_LL = -11012; - static const int BARCODE_ERROR_INNER_PROBLEM = -11100; - static const int BARCODE_ERROR_DECODE_1D_BAD_DECODE = -11200; - static const int BARCODE_ERROR_FIND_ROW_OR_COLUMN = -11201; - static const int BARCODE_ERROR_FIND_3X8_2D_X = -11202; - static const int BARCODE_ERROR_FIND_3X8_2D_Y = -11203; - static const int BARCODE_ERROR_2D_UGOL_MAX = -11204; - static const int BARCODE_ERROR_INDEFINITELY_DECODED = -11210; - static const int BARCODE_ERROR_DLL_NOT_INIT = -11300; - static const int BARCODE_ERROR_IP_DECODE_DLL_Try_Except = -11400; - static const int IPDECODE_ERROR_LARGEERRORS = -4503; - static const int IPDECODE_ERROR_FAULTCOLUMNS = -4504; - static const int IPDECODE_ERROR_FAULTROWS = -4505; - static const int IPDECODE_ERROR_INCORRECT_ERROR_LEVEL = -4511; - static const int IPDECODE_ERROR_LOADING_DEV_TABLE = -4512; -} - -class ESignManagementAction { - static const int smaUndefined = 0; - static const int smaCreatePIN = 1; - static const int smaChangePIN = 2; - static const int smaUnblockPIN = 3; - static const int smaTerminatePIN = 4; - static const int smaGenerateKeys = 5; - static const int smaTerminateKeys = 6; - static const int smaSignData = 7; -} - -class ECheckDiagnose { - static const int UNKNOWN = 0; - static const int PASS = 1; - static const int INVALID_INPUT_DATA = 2; - static const int INTERNAL_ERROR = 3; - static const int EXCEPTION_IN_MODULE = 4; - static const int UNCERTAIN_VERIFICATION = 5; - static const int NECESSARY_IMAGE_NOT_FOUND = 7; - static const int PHOTO_SIDES_NOT_FOUND = 8; - static const int INVALID_CHECKSUM = 10; - static const int SYNTAX_ERROR = 11; - static const int LOGIC_ERROR = 12; - static const int SOURCES_COMPARISON_ERROR = 13; - static const int FIELDS_COMPARISON_LOGIC_ERROR = 14; - static const int INVALID_FIELD_FORMAT = 15; - static const int TRUE_LUMINISCENCE_ERROR = 20; - static const int FALSE_LUMINISCENCE_ERROR = 21; - static const int FIXED_PATTERN_ERROR = 22; - static const int LOW_CONTRAST_IN_IR_LIGHT = 23; - static const int INCORRECT_BACKGROUND_LIGHT = 24; - static const int BACKGROUND_COMPARISON_ERROR = 25; - static const int INCORRECT_TEXT_COLOR = 26; - static const int PHOTO_FALSE_LUMINISCENCE = 27; - static const int TOO_MUCH_SHIFT = 28; - static const int FIBERS_NOT_FOUND = 30; - static const int TOO_MANY_OBJECTS = 31; - static const int SPECKS_IN_UV = 33; - static const int TOO_LOW_RESOLUTION = 34; - static const int INVISIBLE_ELEMENT_PRESENT = 40; - static const int VISIBLE_ELEMENT_ABSENT = 41; - static const int ELEMENT_SHOULD_BE_COLORED = 42; - static const int ELEMENT_SHOULD_BE_GRAYSCALE = 43; - static const int PHOTO_WHITE_IR_DONT_MATCH = 44; - static const int UV_DULL_PAPER_MRZ = 50; - static const int FALSE_LUMINISCENCE_IN_MRZ = 51; - static const int UV_DULL_PAPER_PHOTO = 52; - static const int UV_DULL_PAPER_BLANK = 53; - static const int UV_DULL_PAPER_ERROR = 54; - static const int FALSE_LUMINISCENCE_IN_BLANK = 55; - static const int BAD_AREA_IN_AXIAL = 60; - static const int FALSE_IPI_PARAMETERS = 65; - static const int FIELD_POS_CORRECTOR_HIGHLIGHT_IR = 80; - static const int FIELD_POS_CORRECTOR_GLARES_IN_PHOTO_AREA = 81; - static const int FIELD_POS_CORRECTOR_PHOTO_REPLACED = 82; - static const int OVI_IR_INVISIBLE = 90; - static const int OVI_INSUFFICIENT_AREA = 91; - static const int OVI_COLOR_INVARIABLE = 92; - static const int OVI_BAD_COLOR_FRONT = 93; - static const int OVI_BAD_COLOR_SIDE = 94; - static const int OVI_WIDE_COLOR_SPREAD = 95; - static const int OVI_BAD_COLOR_PERCENT = 96; - static const int HOLOGRAM_ELEMENT_ABSENT = 100; - static const int HOLOGRAM_SIDE_TOP_IMAGES_ABSENT = 101; - static const int HOLOGRAM_ELEMENT_PRESENT = 102; - static const int HOLOGRAM_FRAMES_IS_ABSENT = 103; - static const int HOLOGRAM_HOLO_FIELD_IS_ABSENT = 104; - static const int PHOTO_PATTERN_INTERRUPTED = 110; - static const int PHOTO_PATTERN_SHIFTED = 111; - static const int PHOTO_PATTERN_DIFFERENT_COLORS = 112; - static const int PHOTO_PATTERN_IR_VISIBLE = 113; - static const int PHOTO_PATTERN_NOT_INTERSECT = 114; - static const int PHOTO_SIZE_IS_WRONG = 115; - static const int PHOTO_PATTERN_INVALID_COLOR = 116; - static const int PHOTO_PATTERN_SHIFTED_VERT = 117; - static const int PHOTO_PATTERN_PATTERN_NOT_FOUND = 118; - static const int PHOTO_PATTERN_DIFFERENT_LINES_THICKNESS = 119; - static const int PHOTO_IS_NOT_RECTANGLE = 120; - static const int PHOTO_CORNERS_IS_WRONG = 121; - static const int DOCUMENT_IS_CANCELLING = 122; - static const int TEXT_COLOR_SHOULD_BE_BLUE = 130; - static const int TEXT_COLOR_SHOULD_BE_GREEN = 131; - static const int TEXT_COLOR_SHOULD_BE_RED = 132; - static const int TEXT_SHOULD_BE_BLACK = 133; - static const int BARCODE_WAS_READ_WITH_ERRORS = 140; - static const int BARCODE_DATA_FORMAT_ERROR = 141; - static const int BARCODE_SIZE_PARAMS_ERROR = 142; - static const int NOT_ALL_BARCODES_READ = 143; - static const int GLARES_IN_BARCODE_AREA = 144; - static const int PORTRAIT_COMPARISON_PORTRAITS_DIFFER = 150; - static const int PORTRAIT_COMPARISON_NO_SERVICE_REPLY = 151; - static const int PORTRAIT_COMPARISON_SERVICE_ERROR = 152; - static const int PORTRAIT_COMPARISON_NOT_ENOUGH_IMAGES = 153; - static const int PORTRAIT_COMPARISON_NO_LIVE_PHOTO = 154; - static const int PORTRAIT_COMPARISON_NO_SERVICE_LICENSE = 155; - static const int PORTRAIT_COMPARISON_NO_PORTRAIT_DETECTED = 156; - static const int MOBILE_IMAGES_UNSUITABLE_LIGHT_CONDITIONS = 160; - static const int MOBILE_IMAGES_WHITE_UV_NO_DIFFERENCE = 161; - static const int FINGERPRINTS_COMPARISON_MISMATCH = 170; - static const int HOLO_PHOTO_FACE_NOT_DETECTED = 180; - static const int HOLO_PHOTO_FACE_COMPARISON_FAILED = 181; - static const int HOLO_PHOTO_FACE_GLARE_IN_CENTER_ABSENT = 182; - static const int HOLO_ELEMENT_SHAPE_ERROR = 183; - static const int ALGORITHM_STEPS_ERROR = 184; - static const int HOLO_AREAS_NOT_LOADED = 185; - static const int FINISHED_BY_TIMEOUT = 186; - static const int HOLO_PHOTO_DOCUMENT_OUTSIDE_FRAME = 187; - static const int LIVENESS_DEPTH_CHECK_FAILED = 190; - static const int MRZ_QUALITY_WRONG_SYMBOL_POSITION = 200; - static const int MRZ_QUALITY_WRONG_BACKGROUND = 201; - static const int MRZ_QUALITY_WRONG_MRZ_WIDTH = 202; - static const int MRZ_QUALITY_WRONG_MRZ_HEIGHT = 203; - static const int MRZ_QUALITY_WRONG_LINE_POSITION = 204; - static const int MRZ_QUALITY_WRONG_FONT_TYPE = 205; - static const int OCR_QUALITY_TEXT_POSITION = 220; - static const int OCR_QUALITY_INVALID_FONT = 221; - static const int OCR_QUALITY_INVALID_BACKGROUND = 222; - static const int LAS_INK_INVALID_LINES_FREQUENCY = 230; - static const int DOC_LIVENESS_ELECTRONIC_DEVICE_DETECTED = 240; - static const int DOC_LIVENESS_INVALID_BARCODE_BACKGROUND = 241; - static const int LAST_DIAGNOSE_VALUE = 250; -} - -class RFIDDelegate { - static const int NULL = 0; - static const int NO_PA = 1; - static const int FULL = 2; -} - -class TextProcessing { - static const int ocNoChange = 0; - static const int ocUppercase = 1; - static const int ocLowercase = 2; - static const int ocCapital = 3; -} - -class ProcessingFinishedStatus { - static const int NOT_READY = 0; - static const int READY = 1; - static const int TIMEOUT = 2; -} - -class DocFormat { - static const int ID1 = 0; - static const int ID2 = 1; - static const int ID3 = 2; - static const int NON = 3; - static const int A4 = 4; - static const int ID3_x2 = 5; - static const int ID2_TURKEY = 6; - static const int ID1_90 = 10; - static const int ID1_180 = 11; - static const int ID1_270 = 12; - static const int ID2_180 = 13; - static const int ID3_180 = 14; - static const int CUSTOM = 1000; - static const int PHOTO = 1001; - static const int FLEXIBLE = 1002; - static const int UNKNOWN = -1; -} - -class ELDSParsingNotificationCodes { - static const int NTF_LDS_ASN_CERTIFICATE_INCORRECT_VERSION = 0x90000001; - static const int NTF_LDS_ASN_CERTIFICATE_NON_MATCHING_SIGNATURE_ALGORITHM = 0x90000002; - static const int NTF_LDS_ASN_CERTIFICATE_INCORRECT_TIME_CODING = 0x90000003; - static const int NTF_LDS_ASN_CERTIFICATE_INCORRECT_USE_OF_GENERALIZED_TIME = 0x90000004; - static const int NTF_LDS_ASN_CERTIFICATE_EMPTY_ISSUER = 0x90000005; - static const int NTF_LDS_ASN_CERTIFICATE_EMPTY_SUBJECT = 0x90000006; - static const int NTF_LDS_ASN_CERTIFICATE_UNSUPPORTED_CRITICAL_EXTENSION = 0x90000008; - static const int NTF_LDS_ASN_CERTIFICATE_FORCED_DEFAULT_CSCA_ROLE = 0x9000000E; - static const int NTF_LDS_ASN_CERTIFICATE_FORCED_DEFAULT_DS_ROLE = 0x9000000F; - static const int NTF_LDS_ASN_CERTIFICATE_INCORRECT_ISSUER_SUBJECT_DS = 0x90000010; - static const int NTF_LDS_ASN_CERTIFICATE_DUPLICATING_EXTENSIONS = 0x90000017; - static const int NTF_LDS_ICAO_CERTIFICATE_VERSION_MISSED = 0x90000200; - static const int NTF_LDS_ICAO_CERTIFICATE_VERSION_INCORRECT = 0x90000201; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_COUNTRY_MISSED = 0x90000202; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_COMMON_NAME_MISSED = 0x90000203; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_COUNTRY_NON_COMPLIANT = 0x90000204; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_COUNTRY_MISSED = 0x90000205; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_COMMON_NAME_MISSED = 0x90000206; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_COUNTRY_NON_COMPLIANT = 0x90000207; - static const int NTF_LDS_ICAO_CERTIFICATE_USING_NON_COMPLIANT_DATA = 0x90000208; - static const int NTF_LDS_ICAO_CERTIFICATE_UNSUPPORTED_SIGNATURE_ALGORITHM = 0x90000209; - static const int NTF_LDS_ICAO_CERTIFICATE_UNSUPPORTED_PUBLIC_KEY_ALGORITHM = 0x9000020A; - static const int NTF_LDS_ICAO_CERTIFICATE_MISSED_EXTENSIONS = 0x9000020B; - static const int NTF_LDS_ICAO_CERTIFICATE_VALIDITY = 0x9000020C; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_USING_NON_COMPLIANT_DATA = 0x9000020D; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_KEY_USAGE_MISSED = 0x9000020E; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_KEY_USAGE_NOT_CRITICAL = 0x9000020F; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_KEY_USAGE_INCORRECT_DATA = 0x90000210; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_MISSED = 0x90000211; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_USAGE1 = 0x90000212; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_USAGE2 = 0x90000213; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_NOT_CRITICAL = 0x90000214; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_DATA = 0x90000215; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_PATH_LEN_C_MISSED = 0x90000216; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_BASIC_C_PATH_LEN_C_INCORRECT = 0x90000217; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_NOT_CRITICAL = 0x90000218; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_INCORRECT_USAGE = 0x90000219; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_INCORRECT_DATA = 0x9000021A; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_MISSED = 0x9000021B; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_INCORRECT_DATA = 0x9000021C; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_KEY_ID_MISSED = 0x9000021D; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_KEY_ID_MISSED = 0x9000021E; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_KEY_ID_INCORRECT_DATA = 0x9000021F; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_MISSED = 0x90000220; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_INCORRECT_DATA = 0x90000221; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_EMPTY = 0x90000222; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_MISSED = 0x90000223; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_INCORRECT_DATA = 0x90000224; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_EMPTY = 0x90000225; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_NON_COMPLIANT = 0x90000226; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_CRITICAL = 0x90000228; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_EMPTY = 0x90000229; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_INCORRECT = 0x9000022A; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_NON_COMPLIANT = 0x9000022B; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_MISSED = 0x9000022C; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_INCORRECT_DATA = 0x9000022D; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_EMPTY = 0x9000022E; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_NON_COMPLIANT = 0x9000022F; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_CRITICAL = 0x90000231; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_EMPTY = 0x90000232; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_INCORRECT = 0x90000233; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_NON_COMPLIANT = 0x90000234; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_MISSED = 0x90000235; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_INCORRECT_DATA = 0x90000236; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_VERSION = 0x90000237; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_DOC_TYPES = 0x90000238; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_DOC_TYPES_EMPTY = 0x90000239; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CERT_POLICIES_INCORRECT_DATA = 0x9000023A; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CERT_POLICIES_EMPTY = 0x9000023B; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CERT_POLICIES_POLICY_ID_MISSED = 0x9000023C; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_MISSED = 0x9000023D; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_INCORRECT_DATA = 0x9000023E; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_EMPTY = 0x9000023F; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_POINT_MISSED = 0x90000240; - static const int NTF_LDS_ICAO_CERTIFICATE_SN_NON_COMPLIANT = 0x90000241; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_SN_NON_COMPLIANT = 0x90000242; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_SN_NON_COMPLIANT = 0x90000243; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_ATTRIBUTE_NON_COMPLIANT = 0x90000244; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_ATTRIBUTE_NON_COMPLIANT = 0x90000245; - static const int NTF_LDS_ICAO_CERTIFICATE_ISSUER_SUBJECT_COUNTRY_NON_MATCHING = 0x90000246; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_CSCA_ALT_NAMES_NON_MATCHING = 0x90000247; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_NAME_CHANGE_INCORRECT_DATA = 0x90000248; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_NAME_CHANGE_NON_COMPLIANT = 0x90000249; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_NAME_CHANGE_CRITICAL = 0x9000024A; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_NON_COMPLIANT = 0x9000024B; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_CRITICAL = 0x9000024C; - static const int NTF_LDS_ICAO_CERTIFICATE_EXT_OPTIONAL_CRITICAL = 0x9000024D; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_NON_COMPLIANT = 0x9000024E; - static const int NTF_LDS_ICAO_CERTIFICATE_SUBJECT_COMMON_NAME_NON_COMPLIANT = 0x9000024F; - static const int NTF_LDS_ICAO_COM_LDS_VERSION_INCORRECT = 0x90000020; - static const int NTF_LDS_ICAO_COM_LDS_VERSION_MISSING = 0x90000021; - static const int NTF_LDS_ICAO_COM_UNICODE_VERSION_INCORRECT = 0x90000022; - static const int NTF_LDS_ICAO_COM_UNICODE_VERSION_MISSING = 0x90000023; - static const int NTF_LDS_ICAO_COM_DGPM_INCORRECT = 0x90000024; - static const int NTF_LDS_ICAO_COM_DGPM_MISSING = 0x90000025; - static const int NTF_LDS_ICAO_COM_DGPM_UNEXPECTED = 0x90000026; - static const int NTF_LDS_ICAO_APPLICATION_LDS_VERSION_UNSUPPORTED = 0x90000030; - static const int NTF_LDS_ICAO_APPLICATION_UNICODE_VERSION_UNSUPPORTED = 0x90000031; - static const int NTF_LDS_ICAO_APPLICATION_LDS_VERSION_INCONSISTENT = 0x90000032; - static const int NTF_LDS_ICAO_APPLICATION_UNICODE_VERSION_INCONSISTENT = 0x90000033; - static const int NTF_LDS_ASN_SIGNED_DATA_OID_INCORRECT = 0x90000100; - static const int NTF_LDS_ASN_SIGNED_DATA_VERSION_INCORRECT = 0x900001A0; - static const int NTF_LDS_ASN_SIGNED_DATA_CONTENT_OID_INCORRECT = 0x900001A1; - static const int NTF_LDS_ICAO_SIGNED_DATA_VERSION_INCORRECT = 0x90000101; - static const int NTF_LDS_ICAO_SIGNED_DATA_DIGEST_ALGORITHMS_EMPTY = 0x90000102; - static const int NTF_LDS_ICAO_SIGNED_DATA_DIGEST_ALGORITHMS_UNSUPPORTED = 0x90000103; - static const int NTF_LDS_ICAO_SIGNED_DATA_SIGNER_INFOS_MULTIPLE_ENTRIES = 0x90000109; - static const int NTF_LDS_ICAO_SIGNED_DATA_CERTIFICATES_MISSED = 0x900001B0; - static const int NTF_LDS_ICAO_SIGNED_DATA_CERTIFICATES_EMPTY = 0x900001B1; - static const int NTF_LDS_ICAO_SIGNED_DATA_CRLS_INCORRECT_USAGE = 0x900001B2; - static const int NTF_LDS_ICAO_LDS_OBJECT_INCORRECT_CONTENT_OID = 0x90000104; - static const int NTF_LDS_ICAO_LDS_OBJECT_DG_NUMBER_INCORRECT = 0x90000105; - static const int NTF_LDS_ICAO_LDS_OBJECT_DG_HASH_MISSING = 0x90000106; - static const int NTF_LDS_ICAO_LDS_OBJECT_DG_HASH_EXTRA = 0x90000107; - static const int NTF_LDS_ICAO_LDS_OBJECT_VERSION_INCORRECT = 0x90000108; - static const int NTF_LDS_ICAO_MASTER_LIST_VERSION_INCORRECT = 0x900001C0; - static const int NTF_LDS_ICAO_DEVIATION_LIST_VERSION_INCORRECT = 0x900001C8; - static const int NTF_LDS_BSI_DEFECT_LIST_VERSION_INCORRECT = 0x900001D0; - static const int NTF_LDS_BSI_BLACK_LIST_VERSION_INCORRECT = 0x900001D8; - static const int NTF_LDS_ASN_SIGNER_INFO_VERSION_INCORRECT = 0x9000010A; - static const int NTF_LDS_ASN_SIGNER_INFO_SID_INCORRECT_CHOICE = 0x9000010B; - static const int NTF_LDS_ASN_SIGNER_INFO_SID_DIGEST_ALGORITHM_NOT_LISTED = 0x9000010C; - static const int NTF_LDS_ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_MISSING = 0x9000010D; - static const int NTF_LDS_ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_DATA = 0x9000010E; - static const int NTF_LDS_ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_Value = 0x9000010F; - static const int NTF_LDS_ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_MISSING = 0x90000110; - static const int NTF_LDS_ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_DATA = 0x90000111; - static const int NTF_LDS_ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_VALUE = 0x90000112; - static const int NTF_LDS_ASN_SIGNER_INFO_SIGNING_TIME_ATTR_MISSING = 0x9000011B; - static const int NTF_LDS_ASN_SIGNER_INFO_SIGNING_TIME_ATTR_DATA = 0x9000011C; - static const int NTF_LDS_ASN_SIGNER_INFO_SIGNING_TIME_ATTR_VALUE = 0x9000011D; - static const int NTF_LDS_ASN_SIGNER_INFO_LIST_CONTENT_DESCRIPTION_ATTR_MISSING = 0x9000011E; - static const int NTF_LDS_ASN_SIGNER_INFO_LIST_CONTENT_DESCRIPTION_ATTR_DATA = 0x9000011F; - static const int NTF_LDS_AUTH_SIGNER_INFO_CERTIFICATE_VALIDITY = 0x90000115; - static const int NTF_LDS_AUTH_SIGNER_INFO_CERTIFICATE_ROOT_IS_NOT_TRUSTED = 0x90000116; - static const int NTF_LDS_AUTH_SIGNER_INFO_CERTIFICATE_CANT_FIND_CSCA = 0x90000117; - static const int NTF_LDS_AUTH_SIGNER_INFO_CERTIFICATE_REVOKED = 0x90000118; - static const int NTF_LDS_AUTH_SIGNER_INFO_CERTIFICATE_SIGNATURE_INVALID = 0x90000119; - static const int NTF_LDS_UNSUPPORTED_IMAGE_FORMAT = 0x9000011A; - static const int NTF_LDS_MRZ_DOCUMENT_TYPE_UNKNOWN = 0x00022008; - static const int NTF_LDS_MRZ_ISSUING_STATE_SYNTAX_ERROR = 0x00022009; - static const int NTF_LDS_MRZ_NAME_IS_VOID = 0x0002200A; - static const int NTF_LDS_MRZ_NUMBER_INCORRECT_CHECKSUM = 0x0002200D; - static const int NTF_LDS_MRZ_NATIONALITY_SYNTAX_ERROR = 0x0002200E; - static const int NTF_LDS_MRZ_DOB_SYNTAX_ERROR = 0x0002200F; - static const int NTF_LDS_MRZ_DOB_ERROR = 0x00022010; - static const int NTF_LDS_MRZ_DOB_INCORRECT_CHECKSUM = 0x00022011; - static const int NTF_LDS_MRZ_SEX_INCORRECT = 0x00022012; - static const int NTF_LDS_MRZ_DOE_SYNTAX_ERROR = 0x00022013; - static const int NTF_LDS_MRZ_DOE_ERROR = 0x00022014; - static const int NTF_LDS_MRZ_DOE_INCORRECT_CHECKSUM = 0x00022015; - static const int NTF_LDS_MRZ_OPTIONAL_DATA_INCORRECT_CHECKSUM = 0x00022016; - static const int NTF_LDS_MRZ_INCORRECT_CHECKSUM = 0x00022017; - static const int NTF_LDS_MRZ_INCORRECT = 0x00022018; - static const int NTF_LDS_BIOMETRICS_FORMAT_OWNER_MISSING = 0x90010000; - static const int NTF_LDS_BIOMETRICS_FORMAT_OWNER_INCORRECT = 0x90020000; - static const int NTF_LDS_BIOMETRICS_FORMAT_TYPE_MISSING = 0x90030000; - static const int NTF_LDS_BIOMETRICS_FORMAT_TYPE_INCORRECT = 0x90040000; - static const int NTF_LDS_BIOMETRICS_TYPE_INCORRECT = 0x90050000; - static const int NTF_LDS_BIOMETRICS_SUB_TYPE_MISSING = 0x90060000; - static const int NTF_LDS_BIOMETRICS_SUB_TYPE_INCORRECT = 0x90070000; - static const int NTF_LDS_BIOMETRICS_BDB_IMAGE_MISSING = 0x90080000; - static const int NTF_LDS_BIOMETRICS_BDB_FORMAT_ID_INCORRECT = 0x90090000; - static const int NTF_LDS_BIOMETRICS_BDB_VERSION_INCORRECT = 0x900A0000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_LENGTH_INCORRECT = 0x900B0000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_GENDER = 0x90100000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_EYE_COLOR = 0x90110000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_HAIR_COLOR = 0x90120000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_YAW = 0x90130000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_PITCH = 0x90140000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_ROLL = 0x90150000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_U_YAW = 0x90160000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_U_PITCH = 0x90170000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_POSE_ANGLE_U_ROLL = 0x90180000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_FACE_IMAGE_TYPE = 0x90190000; - static const int NTF_LDS_BIOMETRICS_BDB_DATA_IMAGE_DATA_TYPE = 0x901A0000; - static const int NTF_LDS_SI_PACE_INFO_UNSUPPORTED_STD_PARAMETERS = 0x91000000; - static const int NTF_LDS_SI_PACE_INFO_DEPRECATED_VERSION = 0x91000001; - static const int NTF_LDS_SI_PACE_DOMAIN_PARAMS_USING_STD_REF = 0x91000002; - static const int NTF_LDS_SI_PACE_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM = 0x91000003; - static const int NTF_LDS_SI_CA_INFO_INCORRECT_VERSION = 0x91000004; - static const int NTF_LDS_SI_CA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM = 0x91000005; - static const int NTF_LDS_SI_CA_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM = 0x91000006; - static const int NTF_LDS_SI_TA_INFO_INCORRECT_VERSION = 0x91000007; - static const int NTF_LDS_SI_TA_INFO_FILE_ID_FOR_VERSION2 = 0x91000008; - static const int NTF_LDS_SI_EID_SECURITY_UNSUPPORTED_DIGEST_ALGORITHM = 0x91000009; - static const int NTF_LDS_SI_RI_INFO_INCORRECT_VERSION = 0x9100000A; - static const int NTF_LDS_SI_RI_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM = 0x9100000B; - static const int NTF_LDS_SI_AA_INFO_INCORRECT_VERSION = 0x9100000C; - static const int NTF_LDS_SI_AA_INFO_UNSUPPORTED_ALGORITHM = 0x9100000D; - static const int NTF_LDS_SI_AA_INFO_INCONSISTENT_ALGORITHM_REFERENCE = 0x9100000E; - static const int NTF_LDS_SI_STORAGE_PACE_INFO_NOT_AVAILABLE = 0x91000100; - static const int NTF_LDS_SI_STORAGE_PACE_INFO_NO_STD_PARAMETERS = 0x91000101; - static const int NTF_LDS_SI_STORAGE_PACE_INFO_NO_MATCHING_DOMAIN_PARAMS = 0x91000102; - static const int NTF_LDS_SI_STORAGE_CA_INFO_NOT_AVAILABLE = 0x91000103; - static const int NTF_LDS_SI_STORAGE_CA_DOMAIN_PARAMS_NO_REQUIRED_OPTION = 0x91000104; - static const int NTF_LDS_SI_STORAGE_CA_DOMAIN_PARAMS_NOT_AVAILABLE = 0x91000105; - static const int NTF_LDS_SI_STORAGE_CA_ANONYMOUS_INFOS = 0x91000106; - static const int NTF_LDS_SI_STORAGE_CA_INFO_NO_MATCHING_DOMAIN_PARAMS = 0x91000107; - static const int NTF_LDS_SI_STORAGE_CA_INFO_NO_MATCHING_PUBLIC_KEY = 0x91000108; - static const int NTF_LDS_SI_STORAGE_CA_INCORRECT_INFOS_QUANTITY = 0x91000109; - static const int NTF_LDS_SI_STORAGE_TA_INFO_NOT_AVAILABLE = 0x9100010A; - static const int NTF_LDS_SI_STORAGE_CARD_INFO_LOCATOR_MULTIPLE_ENTRIES = 0x9100010B; - static const int NTF_LDS_SI_STORAGE_EID_SECURITY_INFO_MULTIPLE_ENTRIES = 0x9100010C; - static const int NTF_LDS_SI_STORAGE_PRIVILEGED_TI_MULTIPLE_ENTRIES = 0x9100010D; - static const int NTF_LDS_SI_STORAGE_PRIVILEGED_TI_INCORRECT_USAGE = 0x9100010E; - static const int NTF_LDS_SI_STORAGE_RI_DOMAIN_PARAMS_MULTIPLE_ENTRIES = 0x9100010F; - static const int NTF_LDS_SI_STORAGE_PACE_INFOS_NON_CONSISTANT = 0x91000110; - static const int NTF_LDS_CV_CERTIFICATE_PROFILE_INCORRECT_VERSION = 0x91000201; - static const int NTF_LDS_CV_CERTIFICATE_VALIDITY = 0x91000202; - static const int NTF_LDS_CV_CERTIFICATE_NON_CV_CA_DOMAIN_PARAMETERS = 0x91000203; - static const int NTF_LDS_CV_CERTIFICATE_PRIVATE_KEY_INCORRECT_VERSION = 0x91000204; - static const int NTF_LDS_TA_PACE_STATIC_BINDING_USED = 0x91000300; - static const int NTF_LDS_AUTH_ML_SIGNER_INFO_CERTIFICATE_VALIDITY = 0x92000115; - static const int NTF_LDS_AUTH_ML_SIGNER_INFO_CERTIFICATE_ROOT_IS_NOT_TRUSTED = 0x92000116; - static const int NTF_LDS_AUTH_ML_SIGNER_INFO_CERTIFICATE_CANT_FIND_CSCA = 0x92000117; - static const int NTF_LDS_AUTH_ML_SIGNER_INFO_CERTIFICATE_REVOKED = 0x92000118; - static const int NTF_LDS_AUTH_ML_SIGNER_INFO_CERTIFICATE_SIGNATURE_INVALID = 0x92000119; -} - -class EImageQualityCheckType { - static const int IQC_IMAGE_GLARES = 0; - static const int IQC_IMAGE_FOCUS = 1; - static const int IQC_IMAGE_RESOLUTION = 2; - static const int IQC_IMAGE_COLORNESS = 3; - static const int IQC_PERSPECTIVE = 4; - static const int IQC_BOUNDS = 5; - static const int IQC_SCREEN_CAPTURE = 6; - static const int IQC_PORTRAIT = 7; - static const int IQC_HANDWRITTEN = 8; -} - -class MRZFormat { - static const String FORMAT_1X30 = "1x30"; - static const String FORMAT_3X30 = "3x30"; - static const String FORMAT_2X36 = "2x36"; - static const String FORMAT_2X44 = "2x44"; - static const String FORMAT_1X6 = "1x6"; - static const String FORMAT_2X30 = "2x30"; -} - -class BarcodeType { - static const int UNKNOWN = 0; - static const int BCT_CODE128 = 1; - static const int CODE39 = 2; - static const int EAN8 = 3; - static const int ITF = 4; - static const int PDF417 = 5; - static const int STF = 6; - static const int MTF = 7; - static const int IATA = 8; - static const int CODABAR = 9; - static const int UPCA = 10; - static const int CODE93 = 11; - static const int UPCE = 12; - static const int EAN13 = 13; - static const int QRCODE = 14; - static const int AZTEC = 15; - static const int DATAMATRIX = 16; - static const int ALL_1D = 17; - static const int CODE11 = 18; - static const int JABCODE = 19; -} - -class ERPRMSecurityFeatureType { - static const int NONE = -1; - static const int SECURITY_FEATURE_TYPE_BLANK = 0; - static const int SECURITY_FEATURE_TYPE_FILL = 1; - static const int SECURITY_FEATURE_TYPE_PHOTO = 2; - static const int SECURITY_FEATURE_TYPE_MRZ = 3; - static const int SECURITY_FEATURE_TYPE_FALSE_LUMINESCENCE = 4; - static const int SECURITY_FEATURE_TYPE_HOLO_SIMPLE = 5; - static const int SECURITY_FEATURE_TYPE_HOLO_VERIFY_STATIC = 6; - static const int SECURITY_FEATURE_TYPE_HOLO_VERIFY_MULTI_STATIC = 7; - static const int SECURITY_FEATURE_TYPE_HOLO_VERIFY_DINAMIC = 8; - static const int SECURITY_FEATURE_TYPE_PATTERN_NOT_INTERRUPTED = 9; - static const int SECURITY_FEATURE_TYPE_PATTERN_NOT_SHIFTED = 10; - static const int SECURITY_FEATURE_TYPE_PATTERN_SAME_COLORS = 11; - static const int SECURITY_FEATURE_TYPE_PATTERN_IR_INVISIBLE = 12; - static const int SECURITY_FEATURE_TYPE_PHOTO_SIZE_CHECK = 13; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_VS_GHOST = 14; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_VS_RFID = 15; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_VS_VISUAL = 16; - static const int SECURITY_FEATURE_TYPE_BARCODE = 17; - static const int SECURITY_FEATURE_TYPE_PATTERN_DIFFERENT_LINES_THICKNESS = 18; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_VS_CAMERA = 19; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_RFID_VS_CAMERA = 20; - static const int SECURITY_FEATURE_TYPE_GHOST_PHOTO = 21; - static const int SECURITY_FEATURE_TYPE_CLEAR_GHOST_PHOTO = 22; - static const int SECURITY_FEATURE_TYPE_INVISIBLE_OBJECT = 23; - static const int SECURITY_FEATURE_TYPE_LOW_CONTRAST_OBJECT = 24; - static const int SECURITY_FEATURE_TYPE_PHOTO_COLOR = 25; - static const int SECURITY_FEATURE_TYPE_PHOTO_SHAPE = 26; - static const int SECURITY_FEATURE_TYPE_PHOTO_CORNERS = 27; - static const int SECURITY_FEATURE_TYPE_OCR = 28; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_EXTVS_VISUAL = 29; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_EXTVS_RFID = 30; - static const int SECURITY_FEATURE_TYPE_PORTRAIT_COMPARISON_EXTVS_LIVE = 31; - static const int SECURITY_FEATURE_TYPE_LIVENESS_DEPTH = 32; - static const int SECURITY_FEATURE_TYPE_MICROTEXT = 33; - static const int SECURITY_FEATURE_TYPE_FLUORESCENT_OBJECT = 34; - static const int SECURITY_FEATURE_TYPE_LANDMARKS_CHECK = 35; - static const int SECURITY_FEATURE_TYPE_FACE_PRESENCE = 36; - static const int SECURITY_FEATURE_TYPE_FACE_ABSENCE = 38; - static const int SECURITY_FEATURE_TYPE_LIVENESS_SCREEN_CAPTURE = 39; - static const int SECURITY_FEATURE_TYPE_LIVENESS_ELECTRONIC_DEVICE = 40; - static const int SECURITY_FEATURE_TYPE_LIVENESS_OVI = 41; - static const int SECURITY_FEATURE_TYPE_BARCODE_SIZE_CHECK = 42; - static const int SECURITY_FEATURE_TYPE_LAS_INK = 43; - static const int SECURITY_FEATURE_TYPE_LIVENESS_MLI = 44; - static const int SECURITY_FEATURE_TYPE_LIVENESS_BARCODE_BACKGROUND = 45; -} - -class OnlineMode { - static const int MANUAL = 0; - static const int AUTO = 1; -} - -class ERFIDSDKProfilerType { - static const int SPT_DOC_9303_EDITION_2006 = 0x00000001; - static const int SPT_DOC_9303_LDS_PKI_MAINTENANCE = 0x00000002; -} - -class DiDocType { - static const int dtNotDefined = 0; - static const int dtPassport = 11; - static const int dtIdentityCard = 12; - static const int dtDiplomaticPassport = 13; - static const int dtServicePassport = 14; - static const int dtSeamanIdentityDocument = 15; - static const int dtIdentityCardForResidence = 16; - static const int dtTravelDocument = 17; - static const int dtOther = 99; - static const int dtVisaID2 = 29; - static const int dtVisaID3 = 30; - static const int dtRegistrationCertificate = 206; - static const int dtNationalIdentityCard = 20; - static const int dtSocialIdentityCard = 21; - static const int dtAliensIdentityCard = 22; - static const int dtPrivilegedIdentityCard = 23; - static const int dtResidencePermitIdentityCard = 24; - static const int dtOriginCard = 25; - static const int dtEmergencyPassport = 26; - static const int dtAliensPassport = 27; - static const int dtAlternativeIdentityCard = 28; - static const int dtAuthorizationCard = 32; - static const int dtBeginnerPermit = 33; - static const int dtBorderCrossingCard = 34; - static const int dtChauffeurLicense = 35; - static const int dtChauffeurLicenseUnder18 = 36; - static const int dtChauffeurLicenseUnder21 = 37; - static const int dtCommercialDrivingLicense = 38; - static const int dtCommercialDrivingLicenseInstructionalPermit = 39; - static const int dtCommercialDrivingLicenseUnder18 = 40; - static const int dtCommercialDrivingLicenseUnder21 = 41; - static const int dtCommercialInstructionPermit = 42; - static const int dtCommercialNewPermit = 43; - static const int dtConcealedCarryLicense = 44; - static const int dtConcealedFirearmPermit = 45; - static const int dtConditionalDrivingLicense = 46; - static const int dtDepartmentOfVeteransAffairsIdentityCard = 47; - static const int dtDiplomaticDrivingLicense = 48; - static const int dtDrivingLicense = 49; - static const int dtDrivingLicenseInstructionalPermit = 50; - static const int dtDrivingLicenseInstructionalPermitUnder18 = 51; - static const int dtDrivingLicenseInstructionalPermitUnder21 = 52; - static const int dtDrivingLicenseLearnersPermit = 53; - static const int dtDrivingLicenseLearnersPermitUnder18 = 54; - static const int dtDrivingLicenseLearnersPermitUnder21 = 55; - static const int dtDrivingLicenseNovice = 56; - static const int dtDrivingLicenseNoviceUnder18 = 57; - static const int dtDrivingLicenseNoviceUnder21 = 58; - static const int dtDrivingLicenseRegisteredOffender = 59; - static const int dtDrivingLicenseRestrictedUnder18 = 60; - static const int dtDrivingLicenseRestrictedUnder21 = 61; - static const int dtDrivingLicenseTemporaryVisitor = 62; - static const int dtDrivingLicenseTemporaryVisitorUnder18 = 63; - static const int dtDrivingLicenseTemporaryVisitorUnder21 = 64; - static const int dtDrivingLicenseUnder18 = 65; - static const int dtDrivingLicenseUnder21 = 66; - static const int dtEmploymentDrivingPermit = 67; - static const int dtEnhancedChauffeurLicense = 68; - static const int dtEnhancedChauffeurLicenseUnder18 = 69; - static const int dtEnhancedChauffeurLicenseUnder21 = 70; - static const int dtEnhancedCommercialDrivingLicense = 71; - static const int dtEnhancedDrivingLicense = 72; - static const int dtEnhancedDrivingLicenseUnder18 = 73; - static const int dtEnhancedDrivingLicenseUnder21 = 74; - static const int dtEnhancedIdentityCard = 75; - static const int dtEnhancedIdentityCardUnder18 = 76; - static const int dtEnhancedIdentityCardUnder21 = 77; - static const int dtEnhancedOperatorsLicense = 78; - static const int dtFirearmsPermit = 79; - static const int dtFullProvisionalLicense = 80; - static const int dtFullProvisionalLicenseUnder18 = 81; - static const int dtFullProvisionalLicenseUnder21 = 82; - static const int dtGenevaConventionsIdentityCard = 83; - static const int dtGraduatedDrivingLicenseUnder18 = 84; - static const int dtGraduatedDrivingLicenseUnder21 = 85; - static const int dtGraduatedInstructionPermitUnder18 = 86; - static const int dtGraduatedInstructionPermitUnder21 = 87; - static const int dtGraduatedLicenseUnder18 = 88; - static const int dtGraduatedLicenseUnder21 = 89; - static const int dtHandgunCarryPermit = 90; - static const int dtIdentityAndPrivilegeCard = 91; - static const int dtIdentityCardMobilityImpaired = 92; - static const int dtIdentityCardRegisteredOffender = 93; - static const int dtIdentityCardTemporaryVisitor = 94; - static const int dtIdentityCardTemporaryVisitorUnder18 = 95; - static const int dtIdentityCardTemporaryVisitorUnder21 = 96; - static const int dtIdentityCardUnder18 = 97; - static const int dtIdentityCardUnder21 = 98; - static const int dtIgnitionInterlockPermit = 100; - static const int dtImmigrantVisa = 101; - static const int dtInstructionPermit = 102; - static const int dtInstructionPermitUnder18 = 103; - static const int dtInstructionPermitUnder21 = 104; - static const int dtInterimDrivingLicense = 105; - static const int dtInterimIdentityCard = 106; - static const int dtIntermediateDrivingLicense = 107; - static const int dtIntermediateDrivingLicenseUnder18 = 108; - static const int dtIntermediateDrivingLicenseUnder21 = 109; - static const int dtJuniorDrivingLicense = 110; - static const int dtLearnerInstructionalPermit = 111; - static const int dtLearnerLicense = 112; - static const int dtLearnerLicenseUnder18 = 113; - static const int dtLearnerLicenseUnder21 = 114; - static const int dtLearnerPermit = 115; - static const int dtLearnerPermitUnder18 = 116; - static const int dtLearnerPermitUnder21 = 117; - static const int dtLimitedLicense = 118; - static const int dtLimitedPermit = 119; - static const int dtLimitedTermDrivingLicense = 120; - static const int dtLimitedTermIdentityCard = 121; - static const int dtLiquorIdentityCard = 122; - static const int dtNewPermit = 123; - static const int dtNewPermitUnder18 = 124; - static const int dtNewPermitUnder21 = 125; - static const int dtNonUsCitizenDrivingLicense = 126; - static const int dtOccupationalDrivingLicense = 127; - static const int dtOneidaTribeOfIndiansIdentityCard = 128; - static const int dtOperatorLicense = 129; - static const int dtOperatorLicenseUnder18 = 130; - static const int dtOperatorLicenseUnder21 = 131; - static const int dtPermanentDrivingLicense = 132; - static const int dtPermitToReEnter = 133; - static const int dtProbationaryAutoLicense = 134; - static const int dtProbationaryDrivingLicenseUnder18 = 135; - static const int dtProbationaryDrivingLicenseUnder21 = 136; - static const int dtProbationaryVehicleSalespersonLicense = 137; - static const int dtProvisionalDrivingLicense = 138; - static const int dtProvisionalDrivingLicenseUnder18 = 139; - static const int dtProvisionalDrivingLicenseUnder21 = 140; - static const int dtProvisionalLicense = 141; - static const int dtProvisionalLicenseUnder18 = 142; - static const int dtProvisionalLicenseUnder21 = 143; - static const int dtPublicPassengerChauffeurLicense = 144; - static const int dtRacingAndGamingComissionCard = 145; - static const int dtRefugeeTravelDocument = 146; - static const int dtRenewalPermit = 147; - static const int dtRestrictedCommercialDrivingLicense = 148; - static const int dtRestrictedDrivingLicense = 149; - static const int dtRestrictedPermit = 150; - static const int dtSeasonalPermit = 151; - static const int dtSeasonalResidentIdentityCard = 152; - static const int dtSeniorCitizenIdentityCard = 153; - static const int dtSexOffender = 154; - static const int dtSocialSecurityCard = 155; - static const int dtTemporaryDrivingLicense = 156; - static const int dtTemporaryDrivingLicenseUnder18 = 157; - static const int dtTemporaryDrivingLicenseUnder21 = 158; - static const int dtTemporaryIdentityCard = 159; - static const int dtTemporaryInstructionPermitIdentityCard = 160; - static const int dtTemporaryInstructionPermitIdentityCardUnder18 = 161; - static const int dtTemporaryInstructionPermitIdentityCardUnder21 = 162; - static const int dtTemporaryVisitorDrivingLicense = 163; - static const int dtTemporaryVisitorDrivingLicenseUnder18 = 164; - static const int dtTemporaryVisitorDrivingLicenseUnder21 = 165; - static const int dtUniformedServicesIdentityCard = 166; - static const int dtVehicleSalespersonLicense = 167; - static const int dtWorkerIdentificationCredential = 168; - static const int dtCommercialDrivingLicenseNovice = 169; - static const int dtCommercialDrivingLicenseNoviceUnder18 = 170; - static const int dtCommercialDrivingLicenseNoviceUnder21 = 171; - static const int dtPassportCard = 172; - static const int dtPermanentResidentCard = 173; - static const int dtPersonalIdentificationVerification = 174; - static const int dtTemporaryOperatorLicense = 175; - static const int dtDrivingLicenseUnder19 = 176; - static const int dtIdentityCardUnder19 = 177; - static const int dtVisa = 178; - static const int dtTemporaryPassport = 179; - static const int dtVotingCard = 180; - static const int dtHealthCard = 181; - static const int dtCertificateOfCitizenship = 182; - static const int dtAddressCard = 183; - static const int dtAirportImmigrationCard = 184; - static const int dtAlienRegistrationCard = 185; - static const int dtAPEHCard = 186; - static const int dtCouponToDrivingLicense = 187; - static const int dtCrewMemberCertificate = 188; - static const int dtDocumentForReturn = 189; - static const int dtECard = 190; - static const int dtEmploymentCard = 191; - static const int dtHKSARImmigrationForm = 192; - static const int dtImmigrantCard = 193; - static const int dtLabourCard = 194; - static const int dtLaissezPasser = 195; - static const int dtLawyerIdentityCertificate = 196; - static const int dtLicenseCard = 197; - static const int dtPassportStateless = 198; - static const int dtPassportChild = 199; - static const int dtPassportConsular = 200; - static const int dtPassportDiplomaticService = 201; - static const int dtPassportOfficial = 202; - static const int dtPassportProvisional = 203; - static const int dtPassportSpecial = 204; - static const int dtPermissionToTheLocalBorderTraffic = 205; - static const int dtSEDESOLCard = 207; - static const int dtSocialCard = 208; - static const int dtTBCard = 209; - static const int dtVehiclePassport = 210; - static const int dtWDocument = 211; - static const int dtDiplomaticIdentityCard = 212; - static const int dtConsularIdentityCard = 213; - static const int dtIncomeTaxCard = 214; - static const int dtResidencePermit = 215; - static const int dtDocumentOfIdentity = 216; - static const int dtBorderCrossingPermit = 217; - static const int dtPassportLimitedValidity = 218; - static const int dtSIMCard = 219; - static const int dtTaxCard = 220; - static const int dtCompanyCard = 221; - static const int dtDomesticPassport = 222; - static const int dtIdentityCertificate = 223; - static const int dtResidentIdCard = 224; - static const int dtArmedForcesIdentityCard = 225; - static const int dtProfessionalCard = 226; - static const int dtRegistrationStamp = 227; - static const int dtDriverCard = 228; - static const int dtDriverTrainingCertificate = 229; - static const int dtQualificationDrivingLicense = 230; - static const int dtMembershipCard = 231; - static const int dtPublicVehicleDriverAuthorityCard = 232; - static const int dtMarineLicense = 233; - static const int dtTemporaryLearnerDrivingLicense = 234; - static const int dtTemporaryCommercialDrivingLicense = 235; - static const int dtInterimInstructionalPermit = 236; - static const int dtCertificateOfCompetency = 237; - static const int dtCertificateOfProficiency = 238; - static const int dtTradeLicense = 239; - static const int dtPassportPage = 240; - static const int dtInvoice = 241; - static const int dtPassengerLocatorForm = 242; -} - -class HoloAnimationType { - static const int DocumentHoloAnimationUnknown = 0; - static const int DocumentHoloAnimationTypeHorizontal = 1; - static const int DocumentHoloAnimationTypeVertical = 2; - static const int DocumentHoloAnimationTypeLeftBottomRightTop = 4; - static const int DocumentHoloAnimationTypeRightBottomLeftTop = 8; -} - -class ERequestCommand { - static const int eReqCmd_RFid_SendData = 100; - static const int eReqCmd_RFid_Notify = 101; - static const int eReqCmd_RFid_GetDataForScenario = 102; - static const int eReqCmd_Torch_GetUVFoto = 200; - static const int eReqCmd_InternetSend = 300; - static const int eReqCmd_GetGuid = 400; - static const int eReqCmd_WltToImage = 401; -} - -class ImageFormat { - static const int PNG = 0; - static const int JPG = 1; -} - -class EGraphicFieldType { - static const int GF_PORTRAIT = 201; - static const int GF_FINGERPR = 202; - static const int GF_EYE = 203; - static const int GF_SIGNATURE = 204; - static const int GF_BAR_CODE = 205; - static const int GF_PROOF_OF_CITIZENSHIP = 206; - static const int GF_DOCUMENT_IMAGE = 207; - static const int GF_COLOR_DYNAMIC = 209; - static const int GF_GHOST_PORTRAIT = 210; - static const int GF_STAMP = 211; - static const int GF_PORTRAIT_OF_CHILD = 212; - static const int GF_OTHER = 250; - static const int GF_FINGER_LEFT_THUMB = 300; - static const int GF_FINGER_LEFT_INDEX = 301; - static const int GF_FINGER_LEFT_MIDDLE = 302; - static const int GF_FINGER_LEFT_RING = 303; - static const int GF_FINGER_LEFT_LITTLE = 304; - static const int GF_FINGER_RIGHT_THUMB = 305; - static const int GF_FINGER_RIGHT_INDEX = 306; - static const int GF_FINGER_RIGHT_MIDDLE = 307; - static const int GF_FINGER_RIGHT_RING = 308; - static const int GF_FINGER_RIGHT_LITTLE = 309; -} - -class RegDeviceConfigType { - static const int DEVICE_7310 = 1; -} - -class CameraMode { - static const int AUTO = 0; - static const int CAMERA1 = 1; - static const int CAMERA2 = 2; -} - -class CaptureMode { - static const int AUTO = 0; - static const int CAPTURE_VIDEO = 1; - static const int CAPTURE_FRAME = 2; -} - -class ECheckResult { - static const int CH_CHECK_ERROR = 0; - static const int CH_CHECK_OK = 1; - static const int CH_CHECK_WAS_NOT_DONE = 2; -} - -class ERFIDTerminalType { - static const int TET_UNDEFINED = 0; - static const int TET_INSPECTION_SYSTEM = 1; - static const int TET_AUTHENTICATION_TERMINAL = 2; - static const int TET_SIGNATURE_TERMINAL = 3; - static const int TET_UNAUTHENTICATED_TERMINAL = 4; -} - -class ERFIDDataFileType { - static const int DFT_UNSPECIFIED = 0; - static const int DFT_PASSPORT_DG1 = 1; - static const int DFT_PASSPORT_DG2 = 2; - static const int DFT_PASSPORT_DG3 = 3; - static const int DFT_PASSPORT_DG4 = 4; - static const int DFT_PASSPORT_DG5 = 5; - static const int DFT_PASSPORT_DG6 = 6; - static const int DFT_PASSPORT_DG7 = 7; - static const int DFT_PASSPORT_DG8 = 8; - static const int DFT_PASSPORT_DG9 = 9; - static const int DFT_PASSPORT_DG10 = 10; - static const int DFT_PASSPORT_DG11 = 11; - static const int DFT_PASSPORT_DG12 = 12; - static const int DFT_PASSPORT_DG13 = 13; - static const int DFT_PASSPORT_DG14 = 14; - static const int DFT_PASSPORT_DG15 = 15; - static const int DFT_PASSPORT_DG16 = 16; - static const int DFT_PASSPORT_DG17 = 17; - static const int DFT_PASSPORT_DG18 = 18; - static const int DFT_PASSPORT_DG19 = 19; - static const int DFT_PASSPORT_DG20 = 20; - static const int DFT_PASSPORT_SOD = 21; - static const int DFT_PASSPORT_CVCA = 22; - static const int DFT_PASSPORT_COM = 23; - static const int DFT_ID_DG1 = 101; - static const int DFT_ID_DG2 = 102; - static const int DFT_ID_DG3 = 103; - static const int DFT_ID_DG4 = 104; - static const int DFT_ID_DG5 = 105; - static const int DFT_ID_DG6 = 106; - static const int DFT_ID_DG7 = 107; - static const int DFT_ID_DG8 = 108; - static const int DFT_ID_DG9 = 109; - static const int DFT_ID_DG10 = 110; - static const int DFT_ID_DG11 = 111; - static const int DFT_ID_DG12 = 112; - static const int DFT_ID_DG13 = 113; - static const int DFT_ID_DG14 = 114; - static const int DFT_ID_DG15 = 115; - static const int DFT_ID_DG16 = 116; - static const int DFT_ID_DG17 = 117; - static const int DFT_ID_DG18 = 118; - static const int DFT_ID_DG19 = 119; - static const int DFT_ID_DG20 = 120; - static const int DFT_ID_DG21 = 121; - static const int DFT_DL_COM = 150; - static const int DFT_DL_DG1 = 151; - static const int DFT_DL_DG2 = 152; - static const int DFT_DL_DG3 = 153; - static const int DFT_DL_DG4 = 154; - static const int DFT_DL_DG5 = 155; - static const int DFT_DL_DG6 = 156; - static const int DFT_DL_DG7 = 157; - static const int DFT_DL_DG8 = 158; - static const int DFT_DL_DG9 = 159; - static const int DFT_DL_DG10 = 160; - static const int DFT_DL_DG11 = 161; - static const int DFT_DL_DG12 = 162; - static const int DFT_DL_DG13 = 163; - static const int DFT_DL_DG14 = 164; - static const int DFT_DL_SOD = 165; - static const int DFT_DL_CE = 166; - static const int DFT_DL_CVCA = 167; - static const int DFT_PACE_CARDACCESS = 200; - static const int DFT_PACE_CARDSECURITY = 201; - static const int DFT_PACE_CHIPSECURITY = 202; - static const int DFT_MIFARE_DATA = 300; - static const int DFT_MIFARE_VALIDITY = 301; - static const int DFT_AUTHENTICITYV2 = 302; - static const int DFT_ATR = 400; - static const int DFT_ESIGN_PK = 500; - static const int DFT_ESIGN_SIGNEDDATA = 501; - static const int DFT_CERTIFICATE = 600; - static const int DFT_MASTERLIST = 601; - static const int DFT_DEFECTLIST = 602; - static const int DFT_DEVIATIONLIST = 603; - static const int DFT_APP_DIRECTORY = 700; - static const int DFT_SESSION = 701; - static const int DFT_LOGDATA = 702; - static const int DFT_CHIP_PROPERTIES = 703; - static const int DFT_SAM_DATA = 800; - static const int DFT_SAM_DATA_MAX = 800 + 32; - static const int DFT_VDS = 900; - static const int DFT_VDSNC = 901; - static const int DFT_USERDEFINED = 1000; -} - -class EVisualFieldType { - static const int FT_DOCUMENT_CLASS_CODE = 0; - static const int FT_ISSUING_STATE_CODE = 1; - static const int FT_DOCUMENT_NUMBER = 2; - static const int FT_DATE_OF_EXPIRY = 3; - static const int FT_DATE_OF_ISSUE = 4; - static const int FT_DATE_OF_BIRTH = 5; - static const int FT_PLACE_OF_BIRTH = 6; - static const int FT_PERSONAL_NUMBER = 7; - static const int FT_SURNAME = 8; - static const int FT_GIVEN_NAMES = 9; - static const int FT_MOTHERS_NAME = 10; - static const int FT_NATIONALITY = 11; - static const int FT_SEX = 12; - static const int FT_HEIGHT = 13; - static const int FT_WEIGHT = 14; - static const int FT_EYES_COLOR = 15; - static const int FT_HAIR_COLOR = 16; - static const int FT_ADDRESS = 17; - static const int FT_DONOR = 18; - static const int FT_SOCIAL_SECURITY_NUMBER = 19; - static const int FT_DL_CLASS = 20; - static const int FT_DL_ENDORSED = 21; - static const int FT_DL_RESTRICTION_CODE = 22; - static const int FT_DL_UNDER_21_DATE = 23; - static const int FT_AUTHORITY = 24; - static const int FT_SURNAME_AND_GIVEN_NAMES = 25; - static const int FT_NATIONALITY_CODE = 26; - static const int FT_PASSPORT_NUMBER = 27; - static const int FT_INVITATION_NUMBER = 28; - static const int FT_VISA_ID = 29; - static const int FT_VISA_CLASS = 30; - static const int FT_VISA_SUB_CLASS = 31; - static const int FT_MRZ_STRING_1 = 32; - static const int FT_MRZ_STRING_2 = 33; - static const int FT_MRZ_STRING_3 = 34; - static const int FT_MRZ_TYPE = 35; - static const int FT_OPTIONAL_DATA = 36; - static const int FT_DOCUMENT_CLASS_NAME = 37; - static const int FT_ISSUING_STATE_NAME = 38; - static const int FT_PLACE_OF_ISSUE = 39; - static const int FT_DOCUMENT_NUMBER_CHECKSUM = 40; - static const int FT_DATE_OF_BIRTH_CHECKSUM = 41; - static const int FT_DATE_OF_EXPIRY_CHECKSUM = 42; - static const int FT_PERSONAL_NUMBER_CHECKSUM = 43; - static const int FT_FINAL_CHECKSUM = 44; - static const int FT_PASSPORT_NUMBER_CHECKSUM = 45; - static const int FT_INVITATION_NUMBER_CHECKSUM = 46; - static const int FT_VISA_ID_CHECKSUM = 47; - static const int FT_SURNAME_AND_GIVEN_NAMES_CHECKSUM = 48; - static const int FT_VISA_VALID_UNTIL_CHECKSUM = 49; - static const int FT_OTHER = 50; - static const int FT_MRZ_STRINGS = 51; - static const int FT_NAME_SUFFIX = 52; - static const int FT_NAME_PREFIX = 53; - static const int FT_DATE_OF_ISSUE_CHECKSUM = 54; - static const int FT_DATE_OF_ISSUE_CHECK_DIGIT = 55; - static const int FT_DOCUMENT_SERIES = 56; - static const int FT_REG_CERT_REG_NUMBER = 57; - static const int FT_REG_CERT_CAR_MODEL = 58; - static const int FT_REG_CERT_CAR_COLOR = 59; - static const int FT_REG_CERT_BODY_NUMBER = 60; - static const int FT_REG_CERT_CAR_TYPE = 61; - static const int FT_REG_CERT_MAX_WEIGHT = 62; - static const int FT_REG_CERT_WEIGHT = 63; - static const int FT_ADDRESS_AREA = 64; - static const int FT_ADDRESS_STATE = 65; - static const int FT_ADDRESS_BUILDING = 66; - static const int FT_ADDRESS_HOUSE = 67; - static const int FT_ADDRESS_FLAT = 68; - static const int FT_PLACE_OF_REGISTRATION = 69; - static const int FT_DATE_OF_REGISTRATION = 70; - static const int FT_RESIDENT_FROM = 71; - static const int FT_RESIDENT_UNTIL = 72; - static const int FT_AUTHORITY_CODE = 73; - static const int FT_PLACE_OF_BIRTH_AREA = 74; - static const int FT_PLACE_OF_BIRTH_STATE_CODE = 75; - static const int FT_ADDRESS_STREET = 76; - static const int FT_ADDRESS_CITY = 77; - static const int FT_ADDRESS_JURISDICTION_CODE = 78; - static const int FT_ADDRESS_POSTAL_CODE = 79; - static const int FT_DOCUMENT_NUMBER_CHECK_DIGIT = 80; - static const int FT_DATE_OF_BIRTH_CHECK_DIGIT = 81; - static const int FT_DATE_OF_EXPIRY_CHECK_DIGIT = 82; - static const int FT_PERSONAL_NUMBER_CHECK_DIGIT = 83; - static const int FT_FINAL_CHECK_DIGIT = 84; - static const int FT_PASSPORT_NUMBER_CHECK_DIGIT = 85; - static const int FT_INVITATION_NUMBER_CHECK_DIGIT = 86; - static const int FT_VISA_ID_CHECK_DIGIT = 87; - static const int FT_SURNAME_AND_GIVEN_NAMES_CHECK_DIGIT = 88; - static const int FT_VISA_VALID_UNTIL_CHECK_DIGIT = 89; - static const int FT_PERMIT_DL_CLASS = 90; - static const int FT_PERMIT_DATE_OF_EXPIRY = 91; - static const int FT_PERMIT_IDENTIFIER = 92; - static const int FT_PERMIT_DATE_OF_ISSUE = 93; - static const int FT_PERMIT_RESTRICTION_CODE = 94; - static const int FT_PERMIT_ENDORSED = 95; - static const int FT_ISSUE_TIMESTAMP = 96; - static const int FT_NUMBER_OF_DUPLICATES = 97; - static const int FT_MEDICAL_INDICATOR_CODES = 98; - static const int FT_NON_RESIDENT_INDICATOR = 99; - static const int FT_VISA_TYPE = 100; - static const int FT_VISA_VALID_FROM = 101; - static const int FT_VISA_VALID_UNTIL = 102; - static const int FT_DURATION_OF_STAY = 103; - static const int FT_NUMBER_OF_ENTRIES = 104; - static const int FT_DAY = 105; - static const int FT_MONTH = 106; - static const int FT_YEAR = 107; - static const int FT_UNIQUE_CUSTOMER_IDENTIFIER = 108; - static const int FT_COMMERCIAL_VEHICLE_CODES = 109; - static const int FT_AKA_DATE_OF_BIRTH = 110; - static const int FT_AKA_SOCIAL_SECURITY_NUMBER = 111; - static const int FT_AKA_SURNAME = 112; - static const int FT_AKA_GIVEN_NAMES = 113; - static const int FT_AKA_NAME_SUFFIX = 114; - static const int FT_AKA_NAME_PREFIX = 115; - static const int FT_MAILING_ADDRESS_STREET = 116; - static const int FT_MAILING_ADDRESS_CITY = 117; - static const int FT_MAILING_ADDRESS_JURISDICTION_CODE = 118; - static const int FT_MAILING_ADDRESS_POSTAL_CODE = 119; - static const int FT_AUDIT_INFORMATION = 120; - static const int FT_INVENTORY_NUMBER = 121; - static const int FT_RACE_ETHNICITY = 122; - static const int FT_JURISDICTION_VEHICLE_CLASS = 123; - static const int FT_JURISDICTION_ENDORSEMENT_CODE = 124; - static const int FT_JURISDICTION_RESTRICTION_CODE = 125; - static const int FT_FAMILY_NAME = 126; - static const int FT_GIVEN_NAMES_RUS = 127; - static const int FT_VISA_ID_RUS = 128; - static const int FT_FATHERS_NAME = 129; - static const int FT_FATHERS_NAME_RUS = 130; - static const int FT_SURNAME_AND_GIVEN_NAMES_RUS = 131; - static const int FT_PLACE_OF_BIRTH_RUS = 132; - static const int FT_AUTHORITY_RUS = 133; - static const int FT_ISSUING_STATE_CODE_NUMERIC = 134; - static const int FT_NATIONALITY_CODE_NUMERIC = 135; - static const int FT_ENGINE_POWER = 136; - static const int FT_ENGINE_VOLUME = 137; - static const int FT_CHASSIS_NUMBER = 138; - static const int FT_ENGINE_NUMBER = 139; - static const int FT_ENGINE_MODEL = 140; - static const int FT_VEHICLE_CATEGORY = 141; - static const int FT_IDENTITY_CARD_NUMBER = 142; - static const int FT_CONTROL_NO = 143; - static const int FT_PARRENTS_GIVEN_NAMES = 144; - static const int FT_SECOND_SURNAME = 145; - static const int FT_MIDDLE_NAME = 146; - static const int FT_REG_CERT_VIN = 147; - static const int FT_REG_CERT_VIN_CHECK_DIGIT = 148; - static const int FT_REG_CERT_VIN_CHECKSUM = 149; - static const int FT_LINE_1_CHECK_DIGIT = 150; - static const int FT_LINE_2_CHECK_DIGIT = 151; - static const int FT_LINE_3_CHECK_DIGIT = 152; - static const int FT_LINE_1_CHECKSUM = 153; - static const int FT_LINE_2_CHECKSUM = 154; - static const int FT_LINE_3_CHECKSUM = 155; - static const int FT_REG_CERT_REG_NUMBER_CHECK_DIGIT = 156; - static const int FT_REG_CERT_REG_NUMBER_CHECKSUM = 157; - static const int FT_REG_CERT_VEHICLE_ITS_CODE = 158; - static const int FT_CARD_ACCESS_NUMBER = 159; - static const int FT_MARITAL_STATUS = 160; - static const int FT_COMPANY_NAME = 161; - static const int FT_SPECIAL_NOTES = 162; - static const int FT_SURNAME_OF_SPOSE = 163; - static const int FT_TRACKING_NUMBER = 164; - static const int FT_BOOKLET_NUMBER = 165; - static const int FT_CHILDREN = 166; - static const int FT_COPY = 167; - static const int FT_SERIAL_NUMBER = 168; - static const int FT_DOSSIER_NUMBER = 169; - static const int FT_AKA_SURNAME_AND_GIVEN_NAMES = 170; - static const int FT_TERRITORIAL_VALIDITY = 171; - static const int FT_MRZ_STRINGS_WITH_CORRECT_CHECK_SUMS = 172; - static const int FT_DL_CDL_RESTRICTION_CODE = 173; - static const int FT_DL_UNDER_18_DATE = 174; - static const int FT_DL_RECORD_CREATED = 175; - static const int FT_DL_DUPLICATE_DATE = 176; - static const int FT_DL_ISS_TYPE = 177; - static const int FT_MILITARY_BOOK_NUMBER = 178; - static const int FT_DESTINATION = 179; - static const int FT_BLOOD_GROUP = 180; - static const int FT_SEQUENCE_NUMBER = 181; - static const int FT_REG_CERT_BODY_TYPE = 182; - static const int FT_REG_CERT_CAR_MARK = 183; - static const int FT_TRANSACTION_NUMBER = 184; - static const int FT_AGE = 185; - static const int FT_FOLIO_NUMBER = 186; - static const int FT_VOTER_KEY = 187; - static const int FT_ADDRESS_MUNICIPALITY = 188; - static const int FT_ADDRESS_LOCATION = 189; - static const int FT_SECTION = 190; - static const int FT_OCR_NUMBER = 191; - static const int FT_FEDERAL_ELECTIONS = 192; - static const int FT_REFERENCE_NUMBER = 193; - static const int FT_OPTIONAL_DATA_CHECKSUM = 194; - static const int FT_OPTIONAL_DATA_CHECK_DIGIT = 195; - static const int FT_VISA_NUMBER = 196; - static const int FT_VISA_NUMBER_CHECKSUM = 197; - static const int FT_VISA_NUMBER_CHECK_DIGIT = 198; - static const int FT_VOTER = 199; - static const int FT_PREVIOUS_TYPE = 200; - static const int FT_FIELD_FROM_MRZ = 220; - static const int FT_CURRENT_DATE = 221; - static const int FT_STATUS_DATE_OF_EXPIRY = 251; - static const int FT_BANKNOTE_NUMBER = 252; - static const int FT_CSC_CODE = 253; - static const int FT_ARTISTIC_NAME = 254; - static const int FT_ACADEMIC_TITLE = 255; - static const int FT_ADDRESS_COUNTRY = 256; - static const int FT_ADDRESS_ZIPCODE = 257; - static const int FT_E_ID_RESIDENCE_PERMIT_1 = 258; - static const int FT_E_ID_RESIDENCE_PERMIT_2 = 259; - static const int FT_E_ID_PLACE_OF_BIRTH_STREET = 260; - static const int FT_E_ID_PLACE_OF_BIRTH_CITY = 261; - static const int FT_E_ID_PLACE_OF_BIRTH_STATE = 262; - static const int FT_E_ID_PLACE_OF_BIRTH_COUNTRY = 263; - static const int FT_E_ID_PLACE_OF_BIRTH_ZIPCODE = 264; - static const int FT_CDL_CLASS = 265; - static const int FT_DL_UNDER_19_DATE = 266; - static const int FT_WEIGHT_POUNDS = 267; - static const int FT_LIMITED_DURATION_DOCUMENT_INDICATOR = 268; - static const int FT_ENDORSEMENT_EXPIRATION_DATE = 269; - static const int FT_REVISION_DATE = 270; - static const int FT_COMPLIANCE_TYPE = 271; - static const int FT_FAMILY_NAME_TRUNCATION = 272; - static const int FT_FIRST_NAME_TRUNCATION = 273; - static const int FT_MIDDLE_NAME_TRUNCATION = 274; - static const int FT_EXAM_DATE = 275; - static const int FT_ORGANIZATION = 276; - static const int FT_DEPARTMENT = 277; - static const int FT_PAY_GRADE = 278; - static const int FT_RANK = 279; - static const int FT_BENEFITS_NUMBER = 280; - static const int FT_SPONSOR_SERVICE = 281; - static const int FT_SPONSOR_STATUS = 282; - static const int FT_SPONSOR = 283; - static const int FT_RELATIONSHIP = 284; - static const int FT_USCIS = 285; - static const int FT_CATEGORY = 286; - static const int FT_CONDITIONS = 287; - static const int FT_IDENTIFIER = 288; - static const int FT_CONFIGURATION = 289; - static const int FT_DISCRETIONARY_DATA = 290; - static const int FT_LINE_1_OPTIONAL_DATA = 291; - static const int FT_LINE_2_OPTIONAL_DATA = 292; - static const int FT_LINE_3_OPTIONAL_DATA = 293; - static const int FT_EQV_CODE = 294; - static const int FT_ALT_CODE = 295; - static const int FT_BINARY_CODE = 296; - static const int FT_PSEUDO_CODE = 297; - static const int FT_FEE = 298; - static const int FT_STAMP_NUMBER = 299; - static const int FT_SBH_SECURITYOPTIONS = 300; - static const int FT_SBH_INTEGRITYOPTIONS = 301; - static const int FT_DATE_OF_CREATION = 302; - static const int FT_VALIDITY_PERIOD = 303; - static const int FT_PATRON_HEADER_VERSION = 304; - static const int FT_BDB_TYPE = 305; - static const int FT_BIOMETRIC_TYPE = 306; - static const int FT_BIOMETRIC_SUBTYPE = 307; - static const int FT_BIOMETRIC_PRODUCTID = 308; - static const int FT_BIOMETRIC_FORMAT_OWNER = 309; - static const int FT_BIOMETRIC_FORMAT_TYPE = 310; - static const int FT_PHONE = 311; - static const int FT_PROFESSION = 312; - static const int FT_TITLE = 313; - static const int FT_PERSONAL_SUMMARY = 314; - static const int FT_OTHER_VALID_ID = 315; - static const int FT_CUSTODY_INFO = 316; - static const int FT_OTHER_NAME = 317; - static const int FT_OBSERVATIONS = 318; - static const int FT_TAX = 319; - static const int FT_DATE_OF_PERSONALIZATION = 320; - static const int FT_PERSONALIZATION_SN = 321; - static const int FT_OTHERPERSON_NAME = 322; - static const int FT_PERSONTONOTIFY_DATE_OF_RECORD = 323; - static const int FT_PERSONTONOTIFY_NAME = 324; - static const int FT_PERSONTONOTIFY_PHONE = 325; - static const int FT_PERSONTONOTIFY_ADDRESS = 326; - static const int FT_DS_CERTIFICATE_ISSUER = 327; - static const int FT_DS_CERTIFICATE_SUBJECT = 328; - static const int FT_DS_CERTIFICATE_VALIDFROM = 329; - static const int FT_DS_CERTIFICATE_VALIDTO = 330; - static const int FT_VRC_DATAOBJECT_ENTRY = 331; - static const int FT_TYPE_APPROVAL_NUMBER = 332; - static const int FT_ADMINISTRATIVE_NUMBER = 333; - static const int FT_DOCUMENT_DISCRIMINATOR = 334; - static const int FT_DATA_DISCRIMINATOR = 335; - static const int FT_ISO_ISSUER_ID_NUMBER = 336; - static const int FT_GNIB_NUMBER = 340; - static const int FT_DEPT_NUMBER = 341; - static const int FT_TELEX_CODE = 342; - static const int FT_ALLERGIES = 343; - static const int FT_SP_CODE = 344; - static const int FT_COURT_CODE = 345; - static const int FT_CTY = 346; - static const int FT_SPONSOR_SSN = 347; - static const int FT_DO_D_NUMBER = 348; - static const int FT_MC_NOVICE_DATE = 349; - static const int FT_DUF_NUMBER = 350; - static const int FT_AGY = 351; - static const int FT_PNR_CODE = 352; - static const int FT_FROM_AIRPORT_CODE = 353; - static const int FT_TO_AIRPORT_CODE = 354; - static const int FT_FLIGHT_NUMBER = 355; - static const int FT_DATE_OF_FLIGHT = 356; - static const int FT_SEAT_NUMBER = 357; - static const int FT_DATE_OF_ISSUE_BOARDING_PASS = 358; - static const int FT_CCW_UNTIL = 359; - static const int FT_REFERENCE_NUMBER_CHECKSUM = 360; - static const int FT_REFERENCE_NUMBER_CHECK_DIGIT = 361; - static const int FT_ROOM_NUMBER = 362; - static const int FT_RELIGION = 363; - static const int FT_REMAINDER_TERM = 364; - static const int FT_ELECTRONIC_TICKET_INDICATOR = 365; - static const int FT_COMPARTMENT_CODE = 366; - static const int FT_CHECK_IN_SEQUENCE_NUMBER = 367; - static const int FT_AIRLINE_DESIGNATOR_OF_BOARDING_PASS_ISSUER = 368; - static const int FT_AIRLINE_NUMERIC_CODE = 369; - static const int FT_TICKET_NUMBER = 370; - static const int FT_FREQUENT_FLYER_AIRLINE_DESIGNATOR = 371; - static const int FT_FREQUENT_FLYER_NUMBER = 372; - static const int FT_FREE_BAGGAGE_ALLOWANCE = 373; - static const int FT_PDF_417_CODEC = 374; - static const int FT_IDENTITY_CARD_NUMBER_CHECKSUM = 375; - static const int FT_IDENTITY_CARD_NUMBER_CHECK_DIGIT = 376; - static const int FT_VETERAN = 377; - static const int FT_DL_CLASS_CODE_A_1_FROM = 378; - static const int FT_DL_CLASS_CODE_A_1_TO = 379; - static const int FT_DL_CLASS_CODE_A_1_NOTES = 380; - static const int FT_DL_CLASS_CODE_A_FROM = 381; - static const int FT_DL_CLASS_CODE_A_TO = 382; - static const int FT_DL_CLASS_CODE_A_NOTES = 383; - static const int FT_DL_CLASS_CODE_B_FROM = 384; - static const int FT_DL_CLASS_CODE_B_TO = 385; - static const int FT_DL_CLASS_CODE_B_NOTES = 386; - static const int FT_DL_CLASS_CODE_C_1_FROM = 387; - static const int FT_DL_CLASS_CODE_C_1_TO = 388; - static const int FT_DL_CLASS_CODE_C_1_NOTES = 389; - static const int FT_DL_CLASS_CODE_C_FROM = 390; - static const int FT_DL_CLASS_CODE_C_TO = 391; - static const int FT_DL_CLASS_CODE_C_NOTES = 392; - static const int FT_DL_CLASS_CODE_D_1_FROM = 393; - static const int FT_DL_CLASS_CODE_D_1_TO = 394; - static const int FT_DL_CLASS_CODE_D_1_NOTES = 395; - static const int FT_DL_CLASS_CODE_D_FROM = 396; - static const int FT_DL_CLASS_CODE_D_TO = 397; - static const int FT_DL_CLASS_CODE_D_NOTES = 398; - static const int FT_DL_CLASS_CODE_BE_FROM = 399; - static const int FT_DL_CLASS_CODE_BE_TO = 400; - static const int FT_DL_CLASS_CODE_BE_NOTES = 401; - static const int FT_DL_CLASS_CODE_C_1_E_FROM = 402; - static const int FT_DL_CLASS_CODE_C_1_E_TO = 403; - static const int FT_DL_CLASS_CODE_C_1_E_NOTES = 404; - static const int FT_DL_CLASS_CODE_CE_FROM = 405; - static const int FT_DL_CLASS_CODE_CE_TO = 406; - static const int FT_DL_CLASS_CODE_CE_NOTES = 407; - static const int FT_DL_CLASS_CODE_D_1_E_FROM = 408; - static const int FT_DL_CLASS_CODE_D_1_E_TO = 409; - static const int FT_DL_CLASS_CODE_D_1_E_NOTES = 410; - static const int FT_DL_CLASS_CODE_DE_FROM = 411; - static const int FT_DL_CLASS_CODE_DE_TO = 412; - static const int FT_DL_CLASS_CODE_DE_NOTES = 413; - static const int FT_DL_CLASS_CODE_M_FROM = 414; - static const int FT_DL_CLASS_CODE_M_TO = 415; - static const int FT_DL_CLASS_CODE_M_NOTES = 416; - static const int FT_DL_CLASS_CODE_L_FROM = 417; - static const int FT_DL_CLASS_CODE_L_TO = 418; - static const int FT_DL_CLASS_CODE_L_NOTES = 419; - static const int FT_DL_CLASS_CODE_T_FROM = 420; - static const int FT_DL_CLASS_CODE_T_TO = 421; - static const int FT_DL_CLASS_CODE_T_NOTES = 422; - static const int FT_DL_CLASS_CODE_AM_FROM = 423; - static const int FT_DL_CLASS_CODE_AM_TO = 424; - static const int FT_DL_CLASS_CODE_AM_NOTES = 425; - static const int FT_DL_CLASS_CODE_A_2_FROM = 426; - static const int FT_DL_CLASS_CODE_A_2_TO = 427; - static const int FT_DL_CLASS_CODE_A_2_NOTES = 428; - static const int FT_DL_CLASS_CODE_B_1_FROM = 429; - static const int FT_DL_CLASS_CODE_B_1_TO = 430; - static const int FT_DL_CLASS_CODE_B_1_NOTES = 431; - static const int FT_SURNAME_AT_BIRTH = 432; - static const int FT_CIVIL_STATUS = 433; - static const int FT_NUMBER_OF_SEATS = 434; - static const int FT_NUMBER_OF_STANDING_PLACES = 435; - static const int FT_MAX_SPEED = 436; - static const int FT_FUEL_TYPE = 437; - static const int FT_EC_ENVIRONMENTAL_TYPE = 438; - static const int FT_POWER_WEIGHT_RATIO = 439; - static const int FT_MAX_MASS_OF_TRAILER_BRAKED = 440; - static const int FT_MAX_MASS_OF_TRAILER_UNBRAKED = 441; - static const int FT_TRANSMISSION_TYPE = 442; - static const int FT_TRAILER_HITCH = 443; - static const int FT_ACCOMPANIED_BY = 444; - static const int FT_POLICE_DISTRICT = 445; - static const int FT_FIRST_ISSUE_DATE = 446; - static const int FT_PAYLOAD_CAPACITY = 447; - static const int FT_NUMBER_OF_AXELS = 448; - static const int FT_PERMISSIBLE_AXLE_LOAD = 449; - static const int FT_PRECINCT = 450; - static const int FT_INVITED_BY = 451; - static const int FT_PURPOSE_OF_ENTRY = 452; - static const int FT_SKIN_COLOR = 453; - static const int FT_COMPLEXION = 454; - static const int FT_AIRPORT_FROM = 455; - static const int FT_AIRPORT_TO = 456; - static const int FT_AIRLINE_NAME = 457; - static const int FT_AIRLINE_NAME_FREQUENT_FLYER = 458; - static const int FT_LICENSE_NUMBER = 459; - static const int FT_IN_TANKS = 460; - static const int FT_EXEPT_IN_TANKS = 461; - static const int FT_FAST_TRACK = 462; - static const int FT_OWNER = 463; - static const int FT_MRZ_STRINGS_ICAO_RFID = 464; - static const int FT_NUMBER_OF_CARD_ISSUANCE = 465; - static const int FT_NUMBER_OF_CARD_ISSUANCE_CHECKSUM = 466; - static const int FT_NUMBER_OF_CARD_ISSUANCE_CHECK_DIGIT = 467; - static const int FT_CENTURY_DATE_OF_BIRTH = 468; - static const int FT_DL_CLASSCODE_A3_FROM = 469; - static const int FT_DL_CLASSCODE_A3_TO = 470; - static const int FT_DL_CLASSCODE_A3_NOTES = 471; - static const int FT_DL_CLASSCODE_C2_FROM = 472; - static const int FT_DL_CLASSCODE_C2_TO = 473; - static const int FT_DL_CLASSCODE_C2_NOTES = 474; - static const int FT_DL_CLASSCODE_B2_FROM = 475; - static const int FT_DL_CLASSCODE_B2_TO = 476; - static const int FT_DL_CLASSCODE_B2_NOTES = 477; - static const int FT_DL_CLASSCODE_D2_FROM = 478; - static const int FT_DL_CLASSCODE_D2_TO = 479; - static const int FT_DL_CLASSCODE_D2_NOTES = 480; - static const int FT_DL_CLASSCODE_B2E_FROM = 481; - static const int FT_DL_CLASSCODE_B2E_TO = 482; - static const int FT_DL_CLASSCODE_B2E_NOTES = 483; - static const int FT_DL_CLASSCODE_G_FROM = 484; - static const int FT_DL_CLASSCODE_G_TO = 485; - static const int FT_DL_CLASSCODE_G_NOTES = 486; - static const int FT_DL_CLASSCODE_J_FROM = 487; - static const int FT_DL_CLASSCODE_J_TO = 488; - static const int FT_DL_CLASSCODE_J_NOTES = 489; - static const int FT_DL_CLASSCODE_LC_FROM = 490; - static const int FT_DL_CLASSCODE_LC_TO = 491; - static const int FT_DLC_LASSCODE_LC_NOTES = 492; - static const int FT_BANKCARDNUMBER = 493; - static const int FT_BANKCARDVALIDTHRU = 494; - static const int FT_TAX_NUMBER = 495; - static const int FT_HEALTH_NUMBER = 496; - static const int FT_GRANDFATHERNAME = 497; - static const int FT_SELECTEE_INDICATOR = 498; - static const int FT_MOTHER_SURNAME = 499; - static const int FT_MOTHER_GIVENNAME = 500; - static const int FT_FATHER_SURNAME = 501; - static const int FT_FATHER_GIVENNAME = 502; - static const int FT_MOTHER_DATEOFBIRTH = 503; - static const int FT_FATHER_DATEOFBIRTH = 504; - static const int FT_MOTHER_PERSONALNUMBER = 505; - static const int FT_FATHER_PERSONALNUMBER = 506; - static const int FT_MOTHER_PLACEOFBIRTH = 507; - static const int FT_FATHER_PLACEOFBIRTH = 508; - static const int FT_MOTHER_COUNTRYOFBIRTH = 509; - static const int FT_FATHER_COUNTRYOFBIRTH = 510; - static const int FT_DATE_FIRST_RENEWAL = 511; - static const int FT_DATE_SECOND_RENEWAL = 512; - static const int FT_PLACE_OF_EXAMINATION = 513; - static const int FT_APPLICATION_NUMBER = 514; - static const int FT_VOUCHER_NUMBER = 515; - static const int FT_AUTHORIZATION_NUMBER = 516; - static const int FT_FACULTY = 517; - static const int FT_FORM_OF_EDUCATION = 518; - static const int FT_DNI_NUMBER = 519; - static const int FT_RETIREMENT_NUMBER = 520; - static const int FT_PROFESSIONAL_ID_NUMBER = 521; - static const int FT_AGE_AT_ISSUE = 522; - static const int FT_YEARS_SINCE_ISSUE = 523; - static const int FT_DLCLASSCODE_BTP_FROM = 524; - static const int FT_DLCLASSCODE_BTP_NOTES = 525; - static const int FT_DLCLASSCODE_BTP_TO = 526; - static const int FT_DLCLASSCODE_C3_FROM = 527; - static const int FT_DLCLASSCODE_C3_NOTES = 528; - static const int FT_DLCLASSCODE_C3_TO = 529; - static const int FT_DLCLASSCODE_E_FROM = 530; - static const int FT_DLCLASSCODE_E_NOTES = 531; - static const int FT_DLCLASSCODE_E_TO = 532; - static const int FT_DLCLASSCODE_F_FROM = 533; - static const int FT_DLCLASSCODE_F_NOTES = 534; - static const int FT_DLCLASSCODE_F_TO = 535; - static const int FT_DLCLASSCODE_FA_FROM = 536; - static const int FT_DLCLASSCODE_FA_NOTES = 537; - static const int FT_DLCLASSCODE_FA_TO = 538; - static const int FT_DLCLASSCODE_FA1_FROM = 539; - static const int FT_DLCLASSCODE_FA1_NOTES = 540; - static const int FT_DLCLASSCODE_FA1_TO = 541; - static const int FT_DLCLASSCODE_FB_FROM = 542; - static const int FT_DLCLASSCODE_FB_NOTES = 543; - static const int FT_DLCLASSCODE_FB_TO = 544; - static const int FT_DLCLASSCODE_G1_FROM = 545; - static const int FT_DLCLASSCODE_G1_NOTES = 546; - static const int FT_DLCLASSCODE_G1_TO = 547; - static const int FT_DLCLASSCODE_H_FROM = 548; - static const int FT_DLCLASSCODE_H_NOTES = 549; - static const int FT_DLCLASSCODE_H_TO = 550; - static const int FT_DLCLASSCODE_I_FROM = 551; - static const int FT_DLCLASSCODE_I_NOTES = 552; - static const int FT_DLCLASSCODE_I_TO = 553; - static const int FT_DLCLASSCODE_K_FROM = 554; - static const int FT_DLCLASSCODE_K_NOTES = 555; - static const int FT_DLCLASSCODE_K_TO = 556; - static const int FT_DLCLASSCODE_LK_FROM = 557; - static const int FT_DLCLASSCODE_LK_NOTES = 558; - static const int FT_DLCLASSCODE_LK_TO = 559; - static const int FT_DLCLASSCODE_N_FROM = 560; - static const int FT_DLCLASSCODE_N_NOTES = 561; - static const int FT_DLCLASSCODE_N_TO = 562; - static const int FT_DLCLASSCODE_S_FROM = 563; - static const int FT_DLCLASSCODE_S_NOTES = 564; - static const int FT_DLCLASSCODE_S_TO = 565; - static const int FT_DLCLASSCODE_TB_FROM = 566; - static const int FT_DLCLASSCODE_TB_NOTES = 567; - static const int FT_DLCLASSCODE_TB_TO = 568; - static const int FT_DLCLASSCODE_TM_FROM = 569; - static const int FT_DLCLASSCODE_TM_NOTES = 570; - static const int FT_DLCLASSCODE_TM_TO = 571; - static const int FT_DLCLASSCODE_TR_FROM = 572; - static const int FT_DLCLASSCODE_TR_NOTES = 573; - static const int FT_DLCLASSCODE_TR_TO = 574; - static const int FT_DLCLASSCODE_TV_FROM = 575; - static const int FT_DLCLASSCODE_TV_NOTES = 576; - static const int FT_DLCLASSCODE_TV_TO = 577; - static const int FT_DLCLASSCODE_V_FROM = 578; - static const int FT_DLCLASSCODE_V_NOTES = 579; - static const int FT_DLCLASSCODE_V_TO = 580; - static const int FT_DLCLASSCODE_W_FROM = 581; - static const int FT_DLCLASSCODE_W_NOTES = 582; - static const int FT_DLCLASSCODE_W_TO = 583; - static const int FT_URL = 584; - static const int FT_CALIBER = 585; - static const int FT_MODEL = 586; - static const int FT_MAKE = 587; - static const int FT_NUMBER_OF_CYLINDERS = 588; - static const int FT_SURNAME_OF_HUSBAND_AFTER_REGISTRATION = 589; - static const int FT_SURNAME_OF_WIFE_AFTER_REGISTRATION = 590; - static const int FT_DATE_OF_BIRTH_OF_WIFE = 591; - static const int FT_DATE_OF_BIRTH_OF_HUSBAND = 592; - static const int FT_CITIZENSHIP_OF_FIRST_PERSON = 593; - static const int FT_CITIZENSHIP_OF_SECOND_PERSON = 594; - static const int FT_CVV = 595; - static const int FT_DATE_OF_INSURANCE_EXPIRY = 596; - static const int FT_MORTGAGE_BY = 597; - static const int FT_OLD_DOCUMENT_NUMBER = 598; - static const int FT_OLD_DATE_OF_ISSUE = 599; - static const int FT_OLD_PLACE_OF_ISSUE = 600; - static const int FT_DLCLASSCODE_LR_FROM = 601; - static const int FT_DLCLASSCODE_LR_TO = 602; - static const int FT_DLCLASSCODE_LR_NOTES = 603; - static const int FT_DLCLASSCODE_MR_FROM = 604; - static const int FT_DLCLASSCODE_MR_TO = 605; - static const int FT_DLCLASSCODE_MR_NOTES = 606; - static const int FT_DLCLASSCODE_HR_FROM = 607; - static const int FT_DLCLASSCODE_HR_TO = 608; - static const int FT_DLCLASSCODE_HR_NOTES = 609; - static const int FT_DLCLASSCODE_HC_FROM = 610; - static const int FT_DLCLASSCODE_HC_TO = 611; - static const int FT_DLCLASSCODE_HC_NOTES = 612; - static const int FT_DLCLASSCODE_MC_FROM = 613; - static const int FT_DLCLASSCODE_MC_TO = 614; - static const int FT_DLCLASSCODE_MC_NOTES = 615; - static const int FT_DLCLASSCODE_RE_FROM = 616; - static const int FT_DLCLASSCODE_RE_TO = 617; - static const int FT_DLCLASSCODE_RE_NOTES = 618; - static const int FT_DLCLASSCODE_R_FROM = 619; - static const int FT_DLCLASSCODE_R_TO = 620; - static const int FT_DLCLASSCODE_R_NOTES = 621; - static const int FT_DLCLASSCODE_CA_FROM = 622; - static const int FT_DLCLASSCODE_CA_TO = 623; - static const int FT_DLCLASSCODE_CA_NOTES = 624; - static const int FT_CITIZENSHIP_STATUS = 625; - static const int FT_MILITARY_SERVICE_FROM = 626; - static const int FT_MILITARY_SERVICE_TO = 627; - static const int FT_DLCLASSCODE_NT_FROM = 628; - static const int FT_DLCLASSCODE_NT_TO = 629; - static const int FT_DLCLASSCODE_NT_NOTES = 630; - static const int FT_DLCLASSCODE_TN_FROM = 631; - static const int FT_DLCLASSCODE_TN_TO = 632; - static const int FT_DLCLASSCODE_TN_NOTES = 633; - static const int FT_DLCLASSCODE_D3_FROM = 634; - static const int FT_DLCLASSCODE_D3_TO = 635; - static const int FT_DLCLASSCODE_D3_NOTES = 636; - static const int FT_ALT_DATE_OF_EXPIRY = 637; - static const int FT_DLCLASSCODE_CD_FROM = 638; - static const int FT_DLCLASSCODE_CD_TO = 639; - static const int FT_DLCLASSCODE_CD_NOTES = 640; - static const int FT_PAYMENT_PERIOD_TO = 643; - static const int FT_PAYMENT_PERIOD_FROM = 642; - static const int FT_ISSUER_IDENTIFICATION_NUMBER = 641; - static const int FT_VACCINATION_CERTIFICATE_IDENTIFIER = 644; - static const int FT_FIRST_NAME = 645; - static const int FT_DATE_OF_ARRIVAL = 646; - static const int FT_SECOND_NAME = 647; - static const int FT_THIRD_NAME = 648; - static const int FT_FOURTH_NAME = 649; - static const int FT_LAST_NAME = 650; - static const int FT_DLCLASSCODE_RM_FROM = 651; - static const int FT_DLCLASSCODE_RM_NOTES = 652; - static const int FT_DLCLASSCODE_RM_TO = 653; - static const int FT_DLCLASSCODE_PW_FROM = 654; - static const int FT_DLCLASSCODE_PW_NOTES = 655; - static const int FT_DLCLASSCODE_PW_TO = 656; - static const int FT_DLCLASSCODE_EB_FROM = 657; - static const int FT_DLCLASSCODE_EB_NOTES = 658; - static const int FT_DLCLASSCODE_EB_TO = 659; - static const int FT_DLCLASSCODE_EC_FROM = 660; - static const int FT_DLCLASSCODE_EC_NOTES = 661; - static const int FT_DLCLASSCODE_EC_TO = 662; - static const int FT_DLCLASSCODE_EC1_FROM = 663; - static const int FT_DLCLASSCODE_EC1_NOTES = 664; - static const int FT_DLCLASSCODE_EC1_TO = 665; - static const int FT_PLACE_OF_BIRTH_CITY = 666; - static const int FT_YEAR_OF_BIRTH = 667; - static const int FT_YEAR_OF_EXPIRY = 668; - static const int FT_GRANDFATHER_NAME_MATERNAL = 669; - static const int FT_FIRST_SURNAME = 670; - static const int FT_MONTH_OF_BIRTH = 671; - static const int FT_ADDRESS_FLOOR_NUMBER = 672; - static const int FT_ADDRESS_ENTRANCE = 673; - static const int FT_ADDRESS_BLOCK_NUMBER = 674; - static const int FT_ADDRESS_STREET_NUMBER = 675; - static const int FT_ADDRESS_STREET_TYPE = 676; - static const int FT_ADDRESS_CITY_SECTOR = 677; - static const int FT_ADDRESS_COUNTY_TYPE = 678; - static const int FT_ADDRESS_CITY_TYPE = 679; - static const int FT_ADDRESS_BUILDING_TYPE = 680; -} - -class DocReaderOrientation { - static const int ALL = 0; - static const int PORTRAIT = 1; - static const int LANDSCAPE = 2; - static const int LANDSCAPE_LEFT = 3; - static const int LANDSCAPE_RIGHT = 4; -} - -class LCID { - static const int LATIN = 0; - static const int ABKHAZIAN_CYRILLIC = 10011; - static const int AFRIKAANS = 1078; - static const int ALBANIAN = 1052; - static const int AMHARIC = 1118; - static const int ARABIC_ALGERIA = 5121; - static const int ARABIC_BAHRAIN = 15361; - static const int ARABIC_EGYPT = 3073; - static const int ARABIC_IRAQ = 2049; - static const int ARABIC_JORDAN = 11265; - static const int ARABIC_KUWAIT = 13313; - static const int ARABIC_LEBANON = 12289; - static const int ARABIC_LIBYA = 4097; - static const int ARABIC_MOROCCO = 6145; - static const int ARABIC_OMAN = 8193; - static const int ARABIC_QATAR = 16385; - static const int ARABIC_SAUDI_ARABIA = 1025; - static const int ARABIC_SYRIA = 10241; - static const int ARABIC_TUNISIA = 7169; - static const int ARABIC_UAE = 14337; - static const int ARABIC_YEMEN = 9217; - static const int ARABIC_ARMENIAN = 1067; - static const int ARABIC_WORLD = 4096; - static const int AZERI_CYRILIC = 2092; - static const int AZERI_LATIN = 1068; - static const int BASQUE = 1069; - static const int BANK_CARD = 10003; - static const int BANK_CARD_CVV2 = 10004; - static const int BANK_CARD_NAME = 10002; - static const int BANK_CARD_NUMBER = 10000; - static const int BANK_CARD_VALID_THRU = 10001; - static const int BELARUSIAN = 1059; - static const int BENGALI = 2117; - static const int BULGARIAN = 1026; - static const int CATALAN = 1027; - static const int CHINESE_HONGKONG_SAR = 3076; - static const int CHINESE_MACAO_SAR = 5124; - static const int CHINESE = 2052; - static const int CHINESE_SINGAPORE = 4100; - static const int CHINESE_TAIWAN = 1028; - static const int CROATIAN = 1050; - static const int CZECH = 1029; - static const int DANISH = 1030; - static const int DIVEHI = 1125; - static const int DUTCH_BELGIUM = 2067; - static const int DUTCH_NETHERLANDS = 1043; - static const int ENGLISH_AUSTRALIA = 3081; - static const int ENGLISH_BELIZE = 10249; - static const int ENGLISH_CANADA = 4105; - static const int ENGLISH_CARRIBEAN = 9225; - static const int ENGLISH_IRELAND = 6153; - static const int ENGLISH_JAMAICA = 8201; - static const int ENGLISH_NEW_ZEALAND = 5129; - static const int ENGLISH_PHILIPPINES = 13321; - static const int ENGLISH_SOUTH_AFRICA = 7177; - static const int ENGLISH_TRINIDAD = 11273; - static const int ENGLISH_UK = 2057; - static const int ENGLISH_US = 1033; - static const int ENGLISH_ZIMBABWE = 12297; - static const int ESTONIAN = 1061; - static const int FAEROESE = 1080; - static const int FARSI = 1065; - static const int FINNISH = 1035; - static const int FRENCH_BELGIUM = 2060; - static const int FRENCH_CANADA = 3084; - static const int FRENCH_FRANCE = 1036; - static const int FRENCH_LUXEMBOURG = 5132; - static const int FRENCH_MONACO = 6156; - static const int FRENCH_SWITZERLAND = 4108; - static const int FYRO_MACEDONIAN = 1071; - static const int GALICIAN = 1110; - static const int GEORGIAN = 1079; - static const int GERMAN_AUSTRIA = 3079; - static const int GERMAN_GERMANY = 1031; - static const int GERMAN_LIECHTENSTEIN = 5127; - static const int GERMAN_LUXEMBOURG = 4103; - static const int GERMAN_SWITZERLAND = 2055; - static const int GREEK = 1032; - static const int GUJARATI = 1095; - static const int HEBREW = 1037; - static const int HINDI_INDIA = 1081; - static const int HUNGARIAN = 1038; - static const int ICELANDIC = 1039; - static const int INDONESIAN = 1057; - static const int ITALIAN_ITALY = 1040; - static const int ITALIAN_SWITZERLAND = 2064; - static const int JAPANESE = 1041; - static const int KANNADA = 1099; - static const int KASHMIRI = 1120; - static const int KAZAKH = 1087; - static const int KONKANI = 1111; - static const int KOREAN = 1042; - static const int KYRGYZ_CYRILICK = 1088; - static const int LAO = 1108; - static const int LATVIAN = 1062; - static const int LITHUANIAN = 1063; - static const int MALAY_MALAYSIA = 1086; - static const int MALAY_BRUNEI_DARUSSALAM = 2110; - static const int MARATHI = 1102; - static const int MONGOLIAN_CYRILIC = 1104; - static const int NORWEGIAN_BOKMAL = 1044; - static const int NORWEGIAN_NYORSK = 2068; - static const int PASHTO = 1123; - static const int POLISH = 1045; - static const int PORTUGUESE_BRAZIL = 1046; - static const int PORTUGUESE_PORTUGAL = 2070; - static const int PUNJABI = 1094; - static const int RHAETO_ROMANIC = 1047; - static const int ROMANIAN = 1048; - static const int RUSSIAN = 1049; - static const int SANSKRIT = 1103; - static const int SERBIAN_CYRILIC = 3098; - static const int SERBIAN_LATIN = 2074; - static const int SINDHI = 2137; - static const int SINDHI_INDIA = 1113; - static const int SINHALA = 1115; - static const int SLOVAK = 1051; - static const int SLOVENIAN = 1060; - static const int SPANISH_ARGENTINA = 11274; - static const int SPANISH_BOLIVIA = 16394; - static const int SPANISH_CHILE = 13322; - static const int SPANICH_COLOMBIA = 9226; - static const int SPANISH_COSTA_RICA = 5130; - static const int SPANISH_DOMINICAN_REPUBLIC = 7178; - static const int SPANISH_ECUADOR = 12298; - static const int SPANISH_EL_SALVADOR = 17418; - static const int SPANISH_GUATEMALA = 4106; - static const int SPANISH_HONDURAS = 18442; - static const int SPANISH_MEXICO = 2058; - static const int SPANISH_NICARAGUA = 19466; - static const int SPANISH_PANAMA = 6154; - static const int SPANISH_PARAGUAY = 15370; - static const int SPANISH_PERU = 10250; - static const int SPANISH_PUERTO_RICO = 20490; - static const int SPANISH_TRADITIONAL_SORT = 1034; - static const int SPANISH_INTERNATIONAL_SORT = 3082; - static const int SPANISH_URUGUAY = 14346; - static const int SPANISH_VENEZUELA = 8202; - static const int SWAHILI = 1089; - static const int SWEDISH = 1053; - static const int SWEDISH_FINLAND = 2077; - static const int SYRIAC = 1114; - static const int TAMIL = 1097; - static const int TATAR = 1092; - static const int TELUGU = 1098; - static const int THAI_THAILAND = 1054; - static const int TURKISH = 1055; - static const int TAJIK_CYRILLIC = 1064; - static const int TURKMEN = 1090; - static const int UKRAINIAN = 1058; - static const int URDU = 1056; - static const int UZBEK_CYRILIC = 2115; - static const int UZBEK_LATIN = 1091; - static const int VIETNAMESE = 1066; - static const int CTC_SIMPLIFIED = 50001; - static const int CTC_TRADITIONAL = 50002; -} - -class DocReaderFrame { - static const String MAX = "max"; - static const String SCENARIO_DEFAULT = "id1"; - static const String NONE = "none"; - static const String DOCUMENT = "document"; -} - -class ERPRMLights { - static const int NONE = 0; - static const int RPRM_LIGHT_UV = 128; - static const int RPRM_LIGHT_WHITE_FULL = 6; - static const int RPRM_LIGHT_IR = 16777216; - static const int RPRM_Light_IR_TOP = 8; - static const int RPRM_Light_IR_SIDE = 16; - static const int RPRM_Light_IR_Full = (8 | 16); - static const int RPRM_LIGHT_OVD = 67108864; - static const int RPRM_LIGHT_WHITE_FULL_OVD = (6 | 67108864); -} - -class LineCap { - static const int Butt = 0; - static const int Round = 1; - static const int Square = 2; -} - -class UIInterfaceOrientationMask { - static const int Portrait = 0; - static const int LandscapeLeft = 1; - static const int LandscapeRight = 2; - static const int PortraitUpsideDown = 3; - static const int Landscape = 4; - static const int All = 5; - static const int AllButUpsideDown = 6; -} - -class AVCaptureSessionPreset { - static const int Low = 0; - static const int Medium = 1; - static const int High = 2; - static const int Photo = 3; - static const int InputPriority = 4; - static const int QHD960x540 = 5; - static const int Hd1280x720 = 6; - static const int Hd1920x1080 = 7; - static const int Hd4K3840x2160 = 8; - static const int IFrame960x540 = 9; - static const int IFrame1280x720 = 10; - static const int Qvga320x240 = 11; - static const int Vga640x480 = 12; - static const int Cif352x288 = 13; -} - -class AVCaptureDevicePosition { - static const int Front = 0; - static const int Back = 1; - static const int Unspecified = 2; -} - -class UIViewContentMode { - static const int ScaleToFill = 0; - static const int ScaleAspectFit = 1; - static const int ScaleAspectFill = 2; - static const int Redraw = 3; - static const int Center = 4; - static const int Top = 5; - static const int Bottom = 6; - static const int Left = 7; - static const int Right = 8; - static const int TopLeft = 9; - static const int TopRight = 10; - static const int BottomLeft = 11; - static const int BottomRight = 12; -} - -class DocumentReader { - static const MethodChannel _channel = const MethodChannel('flutter_document_reader_api/method'); - - static Future initializeReaderAutomatically() async { - return await _channel.invokeMethod("initializeReaderAutomatically", []); - } - - static Future isBlePermissionsGranted() async { - return await _channel.invokeMethod("isBlePermissionsGranted", []); - } - - static Future startBluetoothService() async { - return await _channel.invokeMethod("startBluetoothService", []); - } - - static Future initializeReaderBleDeviceConfig() async { - return await _channel.invokeMethod("initializeReaderBleDeviceConfig", []); - } - - static Future getTag() async { - return await _channel.invokeMethod("getTag", []); - } - - static Future getAPIVersion() async { - return await _channel.invokeMethod("getAPIVersion", []); - } - - static Future getAvailableScenarios() async { - return await _channel.invokeMethod("getAvailableScenarios", []); - } - - static Future isRFIDAvailableForUse() async { - return await _channel.invokeMethod("isRFIDAvailableForUse", []); - } - - static Future getCoreMode() async { - return await _channel.invokeMethod("getCoreMode", []); - } - - static Future getCoreVersion() async { - return await _channel.invokeMethod("getCoreVersion", []); - } - - static Future getDatabaseDate() async { - return await _channel.invokeMethod("getDatabaseDate", []); - } - - static Future getDatabaseID() async { - return await _channel.invokeMethod("getDatabaseID", []); - } - - static Future getDatabaseVersion() async { - return await _channel.invokeMethod("getDatabaseVersion", []); - } - - static Future getDocumentReaderIsReady() async { - return await _channel.invokeMethod("getDocumentReaderIsReady", []); - } - - static Future getDocumentReaderStatus() async { - return await _channel.invokeMethod("getDocumentReaderStatus", []); - } - - static Future getDatabaseCountriesNumber() async { - return await _channel.invokeMethod("getDatabaseCountriesNumber", []); - } - - static Future getDatabaseDocumentsNumber() async { - return await _channel.invokeMethod("getDatabaseDocumentsNumber", []); - } - - static Future selectedScenario() async { - return await _channel.invokeMethod("selectedScenario", []); - } - - static Future getSessionLogFolder() async { - return await _channel.invokeMethod("getSessionLogFolder", []); - } - - static Future getDatabaseDescription() async { - return await _channel.invokeMethod("getDatabaseDescription", []); - } - - @deprecated - static Future showScanner() async { - return await _channel.invokeMethod("showScanner", []); - } - - static Future startNewPage() async { - return await _channel.invokeMethod("startNewPage", []); - } - - static Future startNewSession() async { - return await _channel.invokeMethod("startNewSession", []); - } - - static Future startRFIDReader() async { - return await _channel.invokeMethod("startRFIDReader", []); - } - - static Future stopRFIDReader() async { - return await _channel.invokeMethod("stopRFIDReader", []); - } - - static Future stopRFIDReaderWithErrorMessage(message) async { - return await _channel.invokeMethod("stopRFIDReaderWithErrorMessage", [message]); - } - - static Future stopScanner() async { - return await _channel.invokeMethod("stopScanner", []); - } - - static Future deinitializeReader() async { - return await _channel.invokeMethod("deinitializeReader", []); - } - - static Future isAuthenticatorAvailableForUse() async { - return await _channel.invokeMethod("isAuthenticatorAvailableForUse", []); - } - - static Future getConfig() async { - return await _channel.invokeMethod("getConfig", []); - } - - static Future getRfidScenario() async { - return await _channel.invokeMethod("getRfidScenario", []); - } - - static Future getLicenseExpiryDate() async { - return await _channel.invokeMethod("getLicenseExpiryDate", []); - } - - static Future getLicenseCountryFilter() async { - return await _channel.invokeMethod("getLicenseCountryFilter", []); - } - - static Future licenseIsRfidAvailable() async { - return await _channel.invokeMethod("licenseIsRfidAvailable", []); - } - - static Future getCameraSessionIsPaused() async { - return await _channel.invokeMethod("getCameraSessionIsPaused", []); - } - - static Future removeDatabase() async { - return await _channel.invokeMethod("removeDatabase", []); - } - - static Future cancelDBUpdate() async { - return await _channel.invokeMethod("cancelDBUpdate", []); - } - - static Future resetConfiguration() async { - return await _channel.invokeMethod("resetConfiguration", []); - } - - static Future clearPKDCertificates() async { - return await _channel.invokeMethod("clearPKDCertificates", []); - } - - static Future readRFID() async { - return await _channel.invokeMethod("readRFID", []); - } - - static Future getRfidSessionStatus() async { - return await _channel.invokeMethod("getRfidSessionStatus", []); - } - - static Future setRfidDelegate(delegate) async { - return await _channel.invokeMethod("setRfidDelegate", [delegate]); - } - - static Future setEnableCoreLogs(logs) async { - return await _channel.invokeMethod("setEnableCoreLogs", [logs]); - } - - static Future addPKDCertificates(certificates) async { - return await _channel.invokeMethod("addPKDCertificates", [certificates]); - } - - static Future setCameraSessionIsPaused(paused) async { - return await _channel.invokeMethod("setCameraSessionIsPaused", [paused]); - } - - static Future setTag(tag) async { - return await _channel.invokeMethod("setTag", [tag]); - } - - static Future checkDatabaseUpdate(databaseId) async { - return await _channel.invokeMethod("checkDatabaseUpdate", [databaseId]); - } - - static Future scan(config) async { - return await _channel.invokeMethod("scan", [config]); - } - - static Future recognize(config) async { - return await _channel.invokeMethod("recognize", [config]); - } - - @deprecated - static Future recognizeImages(images) async { - return await _channel.invokeMethod("recognizeImages", [images]); - } - - @deprecated - static Future showScannerWithCameraID(cameraID) async { - return await _channel.invokeMethod("showScannerWithCameraID", [cameraID]); - } - - static Future runAutoUpdate(databaseType) async { - return await _channel.invokeMethod("runAutoUpdate", [databaseType]); - } - - static Future setConfig(config) async { - return await _channel.invokeMethod("setConfig", [config]); - } - - static Future setRfidScenario(scenario) async { - return await _channel.invokeMethod("setRfidScenario", [scenario]); - } - - static Future initializeReader(config) async { - return await _channel.invokeMethod("initializeReader", [config]); - } - - static Future prepareDatabase(databaseType) async { - return await _channel.invokeMethod("prepareDatabase", [databaseType]); - } - - @deprecated - static Future recognizeImage(image) async { - return await _channel.invokeMethod("recognizeImage", [image]); - } - - @deprecated - static Future recognizeData(data) async { - return await _channel.invokeMethod("recognizeData", [data]); - } - - static Future setRfidSessionStatus(status) async { - return await _channel.invokeMethod("setRfidSessionStatus", [status]); - } - - static Future providePACertificates(certificates) async { - return await _channel.invokeMethod("providePACertificates", [certificates]); - } - - static Future provideTACertificates(certificates) async { - return await _channel.invokeMethod("provideTACertificates", [certificates]); - } - - static Future provideTASignature(signature) async { - return await _channel.invokeMethod("provideTASignature", [signature]); - } - - static Future parseCoreResults(json) async { - return await _channel.invokeMethod("parseCoreResults", [json]); - } - - static Future setTCCParams(params) async { - return await _channel.invokeMethod("setTCCParams", [params]); - } - - @deprecated - static Future recognizeImageWithOpts(image, options) async { - return await _channel.invokeMethod("recognizeImageWithOpts", [image, options]); - } - - static Future recognizeVideoFrame(byteString, params) async { - return await _channel.invokeMethod("recognizeVideoFrame", [byteString, params]); - } - - @deprecated - static Future showScannerWithCameraIDAndOpts(cameraID, options) async { - return await _channel.invokeMethod("showScannerWithCameraIDAndOpts", [cameraID, options]); - } - - static Future recognizeImageWithCameraMode(image, mode) async { - return await _channel.invokeMethod("recognizeImageWithCameraMode", [image, mode]); - } - - @deprecated - static Future recognizeImagesWithImageInputs(images) async { - return await _channel.invokeMethod("recognizeImagesWithImageInputs", [images]); - } - - static Future setLanguage(language) async { - return await _channel.invokeMethod("setLanguage", [language]); - } -} \ No newline at end of file diff --git a/lib/flutter_document_reader_api.dart b/lib/flutter_document_reader_api.dart new file mode 100644 index 0000000000..4333873855 --- /dev/null +++ b/lib/flutter_document_reader_api.dart @@ -0,0 +1,849 @@ +// +// document_reader.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +/// Regula Document Reader SDK +library document_reader; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +part 'src/internal/utils.dart'; +part 'src/internal/bridge.dart'; +part 'src/internal/event_channels.dart'; + +part 'src/params/process_params/process_params.dart'; +part 'src/params/process_params/image_qa.dart'; +part 'src/params/process_params/glares_check_params.dart'; +part 'src/params/process_params/face_api_search_params.dart'; +part 'src/params/process_params/face_api_params.dart'; +part 'src/params/process_params/liveness_params.dart'; +part 'src/params/process_params/authenticity_params.dart'; +part 'src/params/process_params/rfid_params.dart'; +part 'src/params/process_params/backend_processing_config.dart'; +part 'src/params/process_params/bsi.dart'; +part 'src/params/rfid_scenario/rfid_scenario.dart'; +part 'src/params/rfid_scenario/edl_data_groups.dart'; +part 'src/params/rfid_scenario/eid_data_groups.dart'; +part 'src/params/rfid_scenario/e_passport_data_groups.dart'; +part 'src/params/rfid_scenario/dtc_data_groups.dart'; +part 'src/params/customization/customization.dart'; +part 'src/params/customization/customization_colors.dart'; +part 'src/params/customization/customization_fonts.dart'; +part 'src/params/customization/customization_images.dart'; +part 'src/params/customization/customization_timings.dart'; +part 'src/params/customization/customization_content_modes.dart'; +part 'src/params/customization/customization_matrices.dart'; +part 'src/params/functionality.dart'; + +part 'src/rfid/rfid_notification.dart'; +part 'src/rfid/pkd_certificate.dart'; +part 'src/rfid/tcc_params.dart'; +part 'src/rfid/pa_attribute.dart'; +part 'src/rfid/pa_resources_issuer.dart'; +part 'src/rfid/ta_challenge.dart'; +part 'src/rfid/rfid_error_codes.dart'; +part 'src/rfid/pace_protocol.dart'; +part 'src/rfid/ca_protocol.dart'; + +part 'src/config/init_config.dart'; +part 'src/config/scanner_config.dart'; +part 'src/config/recognize_config.dart'; +part 'src/config/online_processing_config.dart'; +part 'src/config/rfid_config.dart'; +part 'src/config/finalize_config.dart'; + +part 'src/info/doc_reader_exception.dart'; +part 'src/info/rfid_exception.dart'; +part 'src/info/license.dart'; +part 'src/info/doc_reader_scenario.dart'; +part 'src/info/doc_reader_version.dart'; +part 'src/info/documents_database.dart'; +part 'src/info/prepare_progress.dart'; + +part 'src/results/authenticity/authenticity_check.dart'; +part 'src/results/authenticity/authenticity_element.dart'; +part 'src/results/authenticity/authenticity_result.dart'; +part 'src/results/authenticity/authenticity.dart'; +part 'src/results/authenticity/check_diagnose.dart'; +part 'src/results/authenticity/security_feature_type.dart'; + +part 'src/results/barcode/barcode_field.dart'; +part 'src/results/barcode/barcode_result.dart'; +part 'src/results/barcode/pdf417_info.dart'; +part 'src/results/barcode/barcode_status.dart'; +part 'src/results/barcode/barcode_type.dart'; + +part 'src/results/image_quality/image_quality.dart'; +part 'src/results/image_quality/image_quality_group.dart'; +part 'src/results/image_quality/image_quality_check_type.dart'; + +part 'src/results/rfid/access_control_procedure_type.dart'; +part 'src/results/rfid/application.dart'; +part 'src/results/rfid/attribute.dart'; +part 'src/results/rfid/authority.dart'; +part 'src/results/rfid/card_properties.dart'; +part 'src/results/rfid/certificate_chain.dart'; +part 'src/results/rfid/certificate_data.dart'; +part 'src/results/rfid/extension.dart'; +part 'src/results/rfid/file.dart'; +part 'src/results/rfid/file_data.dart'; +part 'src/results/rfid/rfid_session_data.dart'; +part 'src/results/rfid/security_object.dart'; +part 'src/results/rfid/security_object_certificates.dart'; +part 'src/results/rfid/signer_info.dart'; +part 'src/results/rfid/rfid_validity.dart'; +part 'src/results/rfid/rfid_value.dart'; +part 'src/results/rfid/data_field.dart'; +part 'src/results/rfid/rfid_data_file_type.dart'; +part 'src/results/rfid/rfid_access_control_procedure_type.dart'; +part 'src/results/rfid/rfid_certificate_type.dart'; + +part 'src/results/status/optical_status.dart'; +part 'src/results/status/age_status.dart'; +part 'src/results/status/rfid_status.dart'; +part 'src/results/status/results_status.dart'; +part 'src/results/status/check_result.dart'; + +part 'src/results/visible_digital_seals/vdsnc_data.dart'; +part 'src/results/visible_digital_seals/bytes_data.dart'; +part 'src/results/visible_digital_seals/doc_feature.dart'; +part 'src/results/visible_digital_seals/vds_data.dart'; +part 'src/results/visible_digital_seals/lds_parsing_error_codes.dart'; +part 'src/results/visible_digital_seals/lds_parsing_notification_codes.dart'; + +part 'src/results/visual_results/comparison.dart'; +part 'src/results/visual_results/graphic_field.dart'; +part 'src/results/visual_results/graphic_result.dart'; +part 'src/results/visual_results/rfid_origin.dart'; +part 'src/results/visual_results/symbol.dart'; +part 'src/results/visual_results/text_field.dart'; +part 'src/results/visual_results/text_result.dart'; +part 'src/results/visual_results/text_source.dart'; +part 'src/results/visual_results/validity.dart'; +part 'src/results/visual_results/value.dart'; +part 'src/results/visual_results/rect.dart'; +part 'src/results/visual_results/lights.dart'; +part 'src/results/visual_results/graphic_field_type.dart'; +part 'src/results/visual_results/field_type.dart'; +part 'src/results/visual_results/lcid.dart'; + +part 'src/results/results.dart'; +part 'src/results/position.dart'; +part 'src/results/document_type.dart'; +part 'src/results/transaction_info.dart'; + +part 'src/mdl/data_retrieval.dart'; +part 'src/mdl/name_space_mdl.dart'; +part 'src/mdl/document_request_mdl.dart'; +part 'src/mdl/device_retrieval_method.dart'; +part 'src/mdl/document_request_18013_mdl.dart'; +part 'src/mdl/device_engagement.dart'; + +/// Entry point of the Regula DocumentReader SDK. +class DocumentReader { + DocumentReader._privateConstructor(); + + /// The only instanse of singleton class [DocumentReader]. + static DocumentReader get instance => _instance; + static final DocumentReader _instance = DocumentReader._privateConstructor(); + + /// A list of scenarios that can be used for documents recognition based on + /// your license and Core framework capabilities. + List get availableScenarios => _availableScenarios; + List _availableScenarios = []; + + /// Information about the SDK. + DocReaderVersion? get version => _version; + DocReaderVersion? _version; + + /// Information about your license. + License get license => _license; + License _license = License(); + + /// Allows you to check if native RFID chip reading can be performed + /// based on your license and Core framework capabilities. + /// + /// Returns `true` if native RFID chip reading is supported. + Future isRFIDAvailableForUse() async { + return await _bridge.invokeMethod("getIsRFIDAvailableForUse", []); + } + + /// Allows you to check if you can use external Regula Bluetooth devices + /// based on your license and Core framework capabilities. + /// + /// Returns `true` if external Regula Bluetooth is supported. + Future get isAuthenticatorRFIDAvailableForUse async { + return await _bridge.invokeMethod("isAuthenticatorRFIDAvailableForUse", []); + } + + /// Allows you to check if you can use external Regula Bluetooth devices + /// based on your license, available scenarios and Core framework capabilities. + /// + /// Returns `true` if available. + Future get isAuthenticatorAvailableForUse async { + return await _bridge.invokeMethod("isAuthenticatorAvailableForUse", []); + } + + /// Allows you to get a status of the RFID chip reading process. + /// + /// IOS only. + String? get rfidSessionStatus { + if (!Platform.isIOS) { + throw PlatformException( + code: "ios-only", + message: "rfidSessionStatus is accessible only on iOS", + ); + } + return _rfidSessionStatus; + } + + String? _rfidSessionStatus; + set rfidSessionStatus(String? val) { + if (!Platform.isIOS) { + throw PlatformException( + code: "ios-only", + message: "rfidSessionStatus is accessible only on iOS", + ); + } + _rfidSessionStatus = val; + _setRfidSessionStatus(val); + } + + /// Current Session identifier. + String? get tag => _tag; + String? _tag; + set tag(String? val) { + _tag = val; + _setTag(val); + } + + /// Customer name. + String? get tenant => _tenant; + String? _tenant; + set tenant(String? val) { + _tenant = val; + _setTenant(val); + } + + /// Environment type. + String? get env => _env; + String? _env; + set env(String? val) { + _env = val; + _setEnv(val); + } + + /// Custom language locale code of DocumentReaderSDK. + /// If empty or doesn't exist - app language is used. Format "en-US" or "en". + String? get locale => _locale; + String? _locale; + set locale(String? val) { + _locale = val; + _setLocale(val); + } + + /// A localization dictionary to override default localization logic. + /// Allows to replace any string of DocumentReader SDK with an arbitrary string. + /// + /// To see all the localization keys, look up the `RegulaSDK.strings` file at + /// `ios/Pods/DocumentReader/DocumentReader.xcframework/ios-arm64/DocumentReader.framework/en.lproj/RegulaSDK.strings`. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + Map? get localizationDictionary => _localizationDictionary; + Map? _localizationDictionary; + set localizationDictionary(Map? val) { + if (val != null) val = Map.unmodifiable(val); + _localizationDictionary = val; + _setLocalizationDictionary(val); + } + + /// Params that influence the scanning process, camera view controller + /// customization and etc. + Functionality get functionality => _functionality; + Functionality _functionality = Functionality(); + set functionality(Functionality val) { + _functionality = val; + _functionality._apply(); + } + + /// Params that influence the scanning process. + ProcessParams get processParams => _processParams; + ProcessParams _processParams = ProcessParams(); + set processParams(ProcessParams val) { + _processParams = val; + _processParams._apply(); + } + + /// Params that relate to the camera view controller customization and etc. + Customization get customization => _customization; + Customization _customization = Customization(); + set customization(Customization val) { + _customization = val; + _customization._apply(); + } + + /// Params that influence the RFID chip processing. + RFIDScenario get rfidScenario => _rfidScenario; + RFIDScenario _rfidScenario = RFIDScenario(); + set rfidScenario(RFIDScenario val) { + _rfidScenario = val; + _rfidScenario._apply(); + } + + /// Allows you to check if Document Reader is ready for use. + Future get isReady async { + return await _bridge.invokeMethod("getDocumentReaderIsReady", []); + } + + /// Allows you to get a status of Document Reader. + Future get status async { + return await _bridge.invokeMethod("getDocumentReaderStatus", []); + } + + /// Use this method to reset all parameters to their default values. + void resetConfiguration() { + _bridge.invokeMethod("resetConfiguration", []); + _functionality = Functionality(); + _processParams = ProcessParams(); + _customization = Customization(); + _rfidScenario = RFIDScenario(); + } + + // Set click listener for buttons from the UI customization layer. + set onCustomButtonTapped(CustomButtonTappedCompletion completion) => + _setCustomButtonTappedCompletion(completion); + + /// Allows user to receive a video file of current session + set videoEncoderCompletion(VideoEncoderCompletion completion) => + _setVideoEncoderCompletion(completion); + + @Deprecated("Use `initialize` instead.") + Future initializeReader(InitConfig config) async { + return await initialize(config); + } + + /// Allows you to initialize Document Reader. + /// + /// [config] - configuration file for DocumentReader initialization. + /// + /// Check out [SuccessOrError] documentation for handling return type. + Future initialize(InitConfig config) async { + var response = await _bridge.invokeMethod("initialize", [config.toJson()]); + var (success, error) = _successOrErrorFromJson(response); + if (success) await _onInit(); + return (success, error); + } + + /// Used to connect to the ble device. + /// + /// Requires [btdevice plugin](https://pub.dev/packages/flutter_document_reader_btdevice_beta). + Future connectBluetoothDevice(String deviceName) async { + return await _bridge.invokeMethod("connectBluetoothDevice", [deviceName]); + } + + /// Used to deinitialize Document Reader and free up RAM as a + /// consequence of this. + void deinitializeReader() { + _bridge.invokeMethod("deinitializeReader", []); + } + + /// Allows you to download a database from the Regula server. If it exists + /// in your app and compatible with the SDK, it won't be downloaded. + /// + /// [databaseID] - identifier of the database. + /// + /// [prepareCompletion] - callback that returns downloading progress. + /// + /// Check out [SuccessOrError] documentation for handling return type. + /// + /// Requires `android.permission.INTERNET` android permission. + Future prepareDatabase( + String databaseID, + DocumentReaderPrepareCompletion prepareCompletion, + ) async { + _setDocumentReaderPrepareCompletion(prepareCompletion); + var response = await _bridge.invokeMethod("prepareDatabase", [databaseID]); + return _successOrErrorFromJson(response); + } + + /// Allows you to download a database from the Regula server. + /// Each new update of the database will be downloaded. + /// + /// [databaseID] - identifier of the database. + /// + /// [prepareCompletion] - callback that returns downloading progress. + /// + /// Check out [SuccessOrError] documentation for handling return type. + /// + /// Requires `android.permission.INTERNET` android permission. + Future runAutoUpdate( + String databaseID, + DocumentReaderPrepareCompletion prepareCompletion, + ) async { + _setDocumentReaderPrepareCompletion(prepareCompletion); + var response = await _bridge.invokeMethod("runAutoUpdate", [databaseID]); + return _successOrErrorFromJson(response); + } + + /// Allows you to to check database update. + /// + /// [databaseID] - identifier of the database. + /// + /// Requires `android.permission.INTERNET` android permission. + Future checkDatabaseUpdate(String databaseID) async { + String? response = await _bridge.invokeMethod("checkDatabaseUpdate", [ + databaseID, + ]); + return DocumentsDatabase.fromJson(_decode(response)); + } + + /// Allows you to cancel the database update. + Future cancelDBUpdate() async { + return await _bridge.invokeMethod("cancelDBUpdate", []); + } + + /// Allows you to remove the database from your app. + Future removeDatabase() async { + return await _bridge.invokeMethod("removeDatabase", []); + } + + /// Used to start the processing of the next page of the document once the + /// current one is processed. + void startNewPage() { + _bridge.invokeMethod("startNewPage", []); + } + + /// Used to start a scanning process. + void startNewSession() { + _bridge.invokeMethod("startNewSession", []); + } + + /// Used for multiple frames processing which are captured from the camera. + /// + /// [config] - scanning configuration. + /// + /// [completion] - block to execute after the recognition process finishes. + void scan(ScannerConfig config, DocumentReaderCompletion completion) { + _setDocumentReaderCompletion(completion); + _bridge.invokeMethod("scan", [config.toJson()]); + } + + /// Used for multiple frames processing which are captured from the camera. + /// + /// [config] - scanning configuration. + /// + /// [completion] - block to execute after the recognition process finishes. + void startScanner(ScannerConfig config, DocumentReaderCompletion completion) { + _setDocumentReaderCompletion(completion); + _bridge.invokeMethod("startScanner", [config.toJson()]); + } + + /// Used for proccessing predefined images. + /// + /// [config] - scanning configuration. + /// + /// [completion] - block to execute after the recognition process finishes. + void recognize(RecognizeConfig config, DocumentReaderCompletion completion) { + _setDocumentReaderCompletion(completion); + _bridge.invokeMethod("recognize", [config.toJson()]); + } + + /// Used for the RFID chip processing. + /// + /// [config] - chip reading configuration. + /// + /// Requires `android.permission.NFC` android permission. + void rfid(RFIDConfig config) { + config._disableUI + ? _setRFIDCompletion(config._rfidCompletion!) + : _setDocumentReaderCompletion(config._completion!); + + _setRFIDProgressCompletion(config.onProgress); + _setChipDetectedCompletion(config.onChipDetected); + _setRetryReadChipCompletion(config.onRetryReadChip); + + _setPaCertificateCompletion(config.onRequestPACertificates); + _setTaCertificateCompletion(config.onRequestTACertificates); + _setTaSignatureCompletion(config.onRequestTASignature); + + _setPACEProtocolCompletion(config.onRequestPACEProtocol); + _setCAProtocolCompletion(config.onRequestCAProtocol); + + _bridge.invokeMethod( + config._disableUI ? "readRFID" : "startRFIDReader", [config.toJson()]); + } + + /// Used to stop the scanning process. + void stopScanner() { + _bridge.invokeMethod("stopScanner", []); + } + + /// Used to stop the scanning process. + void stopRFIDReader() { + _bridge.invokeMethod("stopRFIDReader", []); + } + + /// Used to pass certificates to Document Reader that will be used during the + /// RFID chip processing. + /// + /// [certificates] - PKD certificates. + void addPKDCertificates(List certificates) { + List json = []; + for (PKDCertificate cert in certificates) { + json.add(cert.toJson()); + } + _bridge.invokeMethod("addPKDCertificates", [json]); + } + + /// It's used to remove certificates from your app that are used during the + /// RFID chip processing. + void clearPKDCertificates() { + _bridge.invokeMethod("clearPKDCertificates", []); + } + + /// Sets the given `TCCParams` to the RFID session. + /// The parameters are required to be set before starting RFID session. + /// + /// [params] - TCC related parameters. + /// + /// Check out [SuccessOrError] documentation for handling return type. + Future setTCCParams(TccParams params) async { + var response = await _bridge.invokeMethod("setTCCParams", [ + params.toJson(), + ]); + return _successOrErrorFromJson(response); + } + + /// It's used to finalize package during backend processing. + Future finalizePackage({ + FinalizeConfig? config, + }) async { + var funcName = "finalizePackage"; + if (config != null) funcName = "finalizePackageWithFinalizeConfig"; + var response = await _bridge.invokeMethod(funcName, [config?.toJson()]); + + var jsonObject = json.decode(response); + var action = DocReaderAction.getByValue(jsonObject["action"])!; + var info = TransactionInfo.fromJson(jsonObject["info"]); + var error = DocReaderException.fromJson(jsonObject["error"]); + + return (action, info, error); + } + + /// It's used to end transaction during backend processing. + void endBackendTransaction() { + _bridge.invokeMethod("endBackendTransaction", []); + } + + (bool, DocReaderException?) _successOrErrorFromJson(String jsonString) { + var jsonObject = json.decode(jsonString); + var success = jsonObject["success"]; + var error = DocReaderException.fromJson(jsonObject["error"]); + return (success, error); + } + + /// Used to read MDL. + Future<(DocReaderAction action, Results? results, DocReaderException? error)> + readMDL(MDLDeviceEngagement type, DataRetrieval retrieval) async { + var response = await _bridge.invokeMethod("startReadMDl", [ + type.value, + retrieval.toJson(), + ]); + var jsonObject = json.decode(response); + return ( + DocReaderAction.getByValue(jsonObject["action"])!, + Results.fromJson(jsonObject["results"]), + DocReaderException.fromJson(jsonObject["error"]), + ); + } + + /// Used to engage device. + /// + /// [withoutUI] - If `true`, then Regula's UI will not be shown and user is supposed to implement the UI himself. + /// + /// [data] - Required if [type] = [MDLDeviceEngagement.QR] and [withoutUI] = `true`. + Future<(DeviceEngagement? engagement, DocReaderException? error)> + engageDevice( + MDLDeviceEngagement type, { + bool withoutUI = false, + String? data, + }) async { + String response = ""; + if (withoutUI == false) { + response = await _bridge.invokeMethod("startEngageDevice", [type.value]); + } else if (type == MDLDeviceEngagement.NFC) { + response = await _bridge.invokeMethod("engageDeviceNFC", []); + } else if (type == MDLDeviceEngagement.QR && data != null) { + response = await _bridge.invokeMethod("engageDeviceData", [data]); + } + var jsonObject = json.decode(response); + return ( + DeviceEngagement.fromJson(jsonObject["deviceEngagement"]), + DocReaderException.fromJson(jsonObject["error"]), + ); + } + + /// Used to retrieve data. + /// + /// [withoutUI] - If set, then Regula's UI will not be shown and user is supposed to implement the UI himself. + /// + /// [engagement] - Required for [withoutUI] = `null` or [MDLDeviceRetrieval.BLE]. Not needed for [MDLDeviceRetrieval.NFC]. + Future<(DocReaderAction action, Results? results, DocReaderException? error)> + retrieveData( + DataRetrieval retrieval, { + MDLDeviceRetrieval? withoutUI, + DeviceEngagement? engagement, + }) async { + var function = "startRetrieveData"; + if (withoutUI == MDLDeviceRetrieval.NFC) function = "engageDeviceNFC"; + if (withoutUI == MDLDeviceRetrieval.BLE) function = "engageDeviceBLE"; + + var jsonObject = json.decode(await _bridge.invokeMethod(function, [ + retrieval.toJson(), + engagement?.toJson(), + ])); + return ( + DocReaderAction.getByValue(jsonObject["action"])!, + Results.fromJson(jsonObject["results"]), + DocReaderException.fromJson(jsonObject["error"]), + ); + } + + Future _onInit() async { + _version = await _getDocReaderVersion(); + _availableScenarios = await _getAvailableScenarios(); + _license = await _getLicense(); + _tag = await _getTag(); + _tenant = await _getTenant(); + _env = await _getEnv(); + _locale = await _getLocale(); + if (Platform.isIOS) _rfidSessionStatus = await _getRfidSessionStatus(); + _functionality = await _getFunctionality(); + _processParams = await _getProcessParams(); + _customization = await _getCustomization(); + _rfidScenario = await _getRfidScenario(); + } + + Future _getProcessParams() async { + String response = await _bridge.invokeMethod("getProcessParams", []); + return ProcessParams.fromJson(_decode(response)); + } + + Future _getFunctionality() async { + String response = await _bridge.invokeMethod("getFunctionality", []); + return Functionality.fromJson(_decode(response)); + } + + Future _getCustomization() async { + String response = await _bridge.invokeMethod("getCustomization", []); + return Customization.fromJson(_decode(response)); + } + + Future _getRfidScenario() async { + String response = await _bridge.invokeMethod("getRfidScenario", []); + return RFIDScenario.fromJson(_decode(response)); + } + + Future _getLicense() async { + String? response = await _bridge.invokeMethod("getLicense", []); + return License.fromJson(_decode(response) ?? {})!; + } + + Future> _getAvailableScenarios() async { + String response = await _bridge.invokeMethod("getAvailableScenarios", []); + List scenarios = []; + for (var s in json.decode(response)) { + scenarios.add(DocReaderScenario.fromJson(s)!); + } + return scenarios; + } + + Future _getDocReaderVersion() async { + String? response = await _bridge.invokeMethod("getDocReaderVersion", []); + return DocReaderVersion.fromJson(_decode(response)); + } + + Future _getRfidSessionStatus() async { + return await _bridge.invokeMethod("getRfidSessionStatus", []); + } + + void _setRfidSessionStatus(String? status) { + _bridge.invokeMethod("setRfidSessionStatus", [status]); + } + + Future _getTag() async { + return await _bridge.invokeMethod("getTag", []); + } + + void _setTag(String? tag) { + _bridge.invokeMethod("setTag", [tag]); + } + + Future _getTenant() async { + return await _bridge.invokeMethod("getTenant", []); + } + + void _setTenant(String? tag) { + _bridge.invokeMethod("setTenant", [tag]); + } + + Future _getEnv() async { + return await _bridge.invokeMethod("getEnv", []); + } + + void _setEnv(String? tag) { + _bridge.invokeMethod("setEnv", [tag]); + } + + Future _getLocale() async { + return await _bridge.invokeMethod("getLocale", []); + } + + void _setLocale(String? locale) { + _bridge.invokeMethod("setLocale", [locale]); + } + + void _setLocalizationDictionary(Map? dictionary) { + _bridge.invokeMethod("setLocalizationDictionary", [dictionary]); + } +} + +/// A type specifically made for receiving answer from any function +/// which does not return anything, but we need to know whether the function +/// has succeeded or not. +/// +/// [bool] - indicates success status. +/// +/// [DocReaderException] - in case success status is `false` - brief message for developer, +/// `null` otherwise. +/// +/// Examples(`myFunction` returns [SuccessOrError]): +/// +/// With error handling: +/// ```dart +/// var (success, error) = await myFunction(); +/// if (success) { +/// print("success!"); +/// } else { +/// print("Error: ${error!.message}"); +/// } +/// ``` +/// +/// Using then: +/// ```dart +/// myFunction().then((response) { +/// var (success, error) = response; +/// if (success) { +/// print("success!"); +/// } else { +/// print("Error: ${error!.message}"); +/// } +/// }); +/// ``` +/// Without error handling: +/// ```dart +/// var (success, _) = await myFunction(); +/// if (success) { +/// print("success!"); +/// } +/// ``` +/// +/// Most compact: +/// ```dart +/// if ((await myFunction()).$1) print("success"); +/// ``` +typedef SuccessOrError = (bool, DocReaderException?); + +/// Callback for receiving answer from processing engine. +/// +/// [action] defines current processing status. +/// +/// [results] defines current processing results. +/// +/// [error] in case of anything is wrong - brief message for developer, `null` otherwise. +typedef DocumentReaderCompletion = void Function( + DocReaderAction action, + Results? results, + DocReaderException? error, +); + +/// Callback for receiving signal, when a custom button, +/// configured in [Customization.uiCustomizationLayer], is pressed. +/// +/// [tag] button id, indication which button was pressed. +typedef CustomButtonTappedCompletion = void Function(int tag); + +/// Callback that allows user to receive a video file of current session. +/// Called by DocumentReader when recording process finished. +/// +/// [filePath] The output file URL. Contains URL to recording output for every scanning session. +typedef VideoEncoderCompletion = void Function(String filePath); + +/// Type for receiving answer after backend processing has finished. +/// +/// [DocReaderAction] defines processing status. +/// +/// [TransactionInfo] contains transactionId and tag. +/// +/// [DocReaderException] in case of anything is wrong - brief message for developer, `null` otherwise. +typedef FinalizePackageCompletion = ( + DocReaderAction action, + TransactionInfo? info, + DocReaderException? error, +); + +/// Contains all possible DocumentReaderNotification callback codes +enum DocReaderAction { + /// Processing finished, the results were received + COMPLETE(0), + + /// Processing didn't finish, intermediate results may be obtained + PROCESS(1), + + /// Processing of a page is completed, the next one can be processed + MORE_PAGES_AVAILABLE(2), + + /// Processing was cancelled, incomplete results may be obtained + CANCEL(3), + + /// An error occurred during processing, incomplete results may be obtained + ERROR(4), + + /// Processing of a hologram is started + PROCESS_WHITE_FLASHLIGHT(5), + + /// Processing is finished by timeout, intermediate results can be received. Processing finishes due to non-compliance with the image quality requirements + TIMEOUT(6), + + /// Online processing is started + PROCESSING_ON_SERVICE(7), + + /// Processing didn't finish, intermediate results may be obtained, UV images may be obtained + PROCESS_WHITE_UV_IMAGES(102), + + /// Processing didn't finish, intermediate results may be obtained, IR images may be obtained + PROCESS_IR_FRAME(103); + + const DocReaderAction(this.value); + final int value; + + static DocReaderAction? getByValue(int? i) { + if (i == null) return null; + return DocReaderAction.values.firstWhere((x) => x.value == i); + } + + bool finished() => this == COMPLETE || this == TIMEOUT; + + bool interrupted() => this == CANCEL || this == ERROR; + + bool stopped() => finished() || interrupted(); +} diff --git a/lib/src/config/finalize_config.dart b/lib/src/config/finalize_config.dart new file mode 100644 index 0000000000..df11ab2e8f --- /dev/null +++ b/lib/src/config/finalize_config.dart @@ -0,0 +1,39 @@ +part of "../../flutter_document_reader_api.dart"; + +class FinalizeConfig { + bool? _rawImages; + bool? _video; + bool? _rfidSession; + bool? _mdlSession; + + FinalizeConfig({ + bool? rawImages, + bool? video, + bool? rfidSession, + bool? mdlSession, + }) : _rawImages = rawImages, + _video = video, + _rfidSession = rfidSession, + _mdlSession = mdlSession; + + @visibleForTesting + static FinalizeConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = FinalizeConfig(); + + result._rawImages = jsonObject["rawImages"]; + result._video = jsonObject["video"]; + result._rfidSession = jsonObject["rfidSession"]; + result._mdlSession = jsonObject["mdlSession"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "rawImages": _rawImages, + "video": _video, + "rfidSession": _rfidSession, + "mdlSession": _mdlSession, + }.clearNulls(); +} diff --git a/lib/src/config/init_config.dart b/lib/src/config/init_config.dart new file mode 100644 index 0000000000..1efbc6cae3 --- /dev/null +++ b/lib/src/config/init_config.dart @@ -0,0 +1,88 @@ +// +// InitConfig.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// A configuration file for DocumentReader initialization. +/// Controls initialization time properties such as licenseUpdate and delayedNNLoad. +class InitConfig { + /// The license binary file. + ByteData get license => _license; + ByteData _license; + + /// Enables automatic license update check during [DocumentReader] initialization. + bool licenseUpdate = true; + + /// Allows you to configure the maximum time needed for a license update (in seconds). + double? licenseUpdateTimeout; + + /// Defines whether the [DocumentReader] delays loading of neural networks. + /// + /// When set to `true` the initialization starts in the background thread after + /// the method [DocumentReader.initialize] is called. If the document + /// processing is initiated before all the networks are loaded, + /// the [DocumentReader] will wait for it before starting the handling. + /// + /// When set to `false` the initialization is performed during + /// [DocumentReader.initialize] method. + bool delayedNNLoad = false; + + /// The path to the database file. + /// + /// IOS only. For Android use [customDb]. + String? databasePath; + + /// Custom database binary. + /// + /// Android only. For iOS use [databasePath]. + ByteData? customDb; + + /// Android only. + Map? blackList; + + /// Constructor for initialization using a license binary. + InitConfig(ByteData license) : _license = license; + + bool _useBleDevice = false; + + /// Constructor for initialization using a ble device. + /// Doesn't need a license file, it will be fetched automatically from your ble device. + /// + /// Requires [btdevice plugin](https://pub.dev/packages/flutter_document_reader_btdevice_beta). + InitConfig.withBleDevice() : _license = ByteData(0) { + _useBleDevice = true; + } + + @visibleForTesting + static InitConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = InitConfig(_dataFromBase64(jsonObject["license"])!); + + result.customDb = _dataFromBase64(jsonObject["customDb"]); + result.delayedNNLoad = jsonObject["delayedNNLoad"]; + result.licenseUpdate = jsonObject["licenseUpdate"]; + result.licenseUpdateTimeout = _toDouble(jsonObject["licenseUpdateTimeout"]); + result.blackList = jsonObject["blackList"]; + result.databasePath = jsonObject["databasePath"]; + result._useBleDevice = jsonObject["useBleDevice"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "license": _dataToBase64(license), + "delayedNNLoad": delayedNNLoad, + "licenseUpdate": licenseUpdate, + "licenseUpdateTimeout": licenseUpdateTimeout, + "blackList": blackList, + "customDb": _dataToBase64(customDb), + "databasePath": databasePath, + "useBleDevice": _useBleDevice, + }.clearNulls(); +} diff --git a/lib/src/config/online_processing_config.dart b/lib/src/config/online_processing_config.dart new file mode 100644 index 0000000000..90b045be01 --- /dev/null +++ b/lib/src/config/online_processing_config.dart @@ -0,0 +1,82 @@ +// +// OnlineProcessingConfig.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class OnlineProcessingConfig { + OnlineMode mode; + + String url = "https://api.regulaforensics.com"; + + ProcessParams processParams = ProcessParams(); + + ImageFormat imageFormat = ImageFormat.JPG; + + double imageCompressionQuality = 0.8; + + Map? requestHeaders; + + OnlineProcessingConfig(this.mode) { + processParams = ProcessParams(); + processParams.scenario = Scenario.FULL_PROCESS; + } + + @visibleForTesting + static OnlineProcessingConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + OnlineMode mode = OnlineMode.getByValue(jsonObject["mode"])!; + var result = OnlineProcessingConfig(mode); + + result.url = jsonObject["url"]; + result.imageFormat = ImageFormat.getByValue(jsonObject["imageFormat"])!; + result.imageCompressionQuality = + jsonObject["imageCompressionQuality"].toDouble(); + result.processParams = ProcessParams.fromJson(jsonObject["processParams"]); + result.requestHeaders = jsonObject["requestHeaders"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "mode": mode.value, + "url": url, + "imageFormat": imageFormat.value, + "imageCompressionQuality": imageCompressionQuality, + "processParams": processParams.toJson(), + "requestHeaders": requestHeaders, + }.clearNulls(); +} + +enum ImageFormat { + PNG(0), + + JPG(1); + + const ImageFormat(this.value); + final int value; + + static ImageFormat? getByValue(int? i) { + if (i == null) return null; + return ImageFormat.values.firstWhere((x) => x.value == i); + } +} + +enum OnlineMode { + MANUAL(0), + + AUTO(1); + + const OnlineMode(this.value); + final int value; + + static OnlineMode? getByValue(int? i) { + if (i == null) return null; + return OnlineMode.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/config/recognize_config.dart b/lib/src/config/recognize_config.dart new file mode 100644 index 0000000000..ca91a81b54 --- /dev/null +++ b/lib/src/config/recognize_config.dart @@ -0,0 +1,188 @@ +part of "../../flutter_document_reader_api.dart"; + +/// Image processing configuration. +class RecognizeConfig { + /// Documents processing scenario. + Scenario? get scenario => _scenario; + Scenario? _scenario; + + /// Configuration class for online processing. + /// + /// /// Requires network connection. + OnlineProcessingConfig? get onlineProcessingConfig => _onlineProcessingConfig; + OnlineProcessingConfig? _onlineProcessingConfig; + + /// Image for processing. + Uint8List? image; + + /// Images for processing. + List? images; + + /// Binary for processing. + Uint8List? data; + + /// Binaries for processing. + List? dataList; + + /// Images(with input data) for processing. + List? imageInputData; + + /// DTC file for processing. + Uint8List? dtc; + + /// Live portrait photo. + /// + /// Requires network connection. + Uint8List? livePortrait; + + /// Portrait photo from an external source. + /// + /// Requires network connection. + Uint8List? extPortrait; + + /// This parameter is for processing an image that contains a person and + /// a document and compare the portrait photo from the document with + /// the person's face. It works only in the single-frame processing, + /// but not in the video frame processing. Requires network connection. + bool oneShotIdentification = false; + + RecognizeConfig.withScenario( + Scenario scenario, { + Uint8List? image, + List? images, + Uint8List? data, + List? dataList, + List? imageInputData, + Uint8List? dtc, + Uint8List? livePortrait, + Uint8List? extPortrait, + bool oneShotIdentification = false, + }) : _scenario = scenario, + _onlineProcessingConfig = null, + livePortrait = livePortrait, + extPortrait = extPortrait, + oneShotIdentification = oneShotIdentification, + image = image, + images = images, + data = data, + dataList = dataList, + imageInputData = imageInputData, + dtc = dtc; + + RecognizeConfig.withOnlineProcessingConfig( + OnlineProcessingConfig onlineProcessingConfig, { + Uint8List? image, + List? images, + Uint8List? data, + List? dataList, + List? imageInputData, + Uint8List? dtc, + Uint8List? livePortrait, + Uint8List? extPortrait, + bool oneShotIdentification = false, + }) : _scenario = null, + _onlineProcessingConfig = onlineProcessingConfig, + livePortrait = livePortrait, + extPortrait = extPortrait, + oneShotIdentification = oneShotIdentification, + image = image, + images = images, + data = data, + dataList = dataList, + imageInputData = imageInputData, + dtc = dtc; + + RecognizeConfig._empty(); + + @visibleForTesting + static RecognizeConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RecognizeConfig._empty(); + + result._scenario = Scenario.getByValue(jsonObject["scenario"]); + result._onlineProcessingConfig = OnlineProcessingConfig.fromJson( + jsonObject["onlineProcessingConfig"], + ); + result.image = _bytesFromBase64(jsonObject["image"]); + if (jsonObject["images"] != null) { + result.images = []; + for (var item in jsonObject["images"]) { + result.images!.addSafe(_bytesFromBase64(item)); + } + } + result.data = _bytesFromBase64(jsonObject["data"]); + if (jsonObject["dataList"] != null) { + result.dataList = []; + for (var item in jsonObject["dataList"]) { + result.dataList!.addSafe(_bytesFromBase64(item)); + } + } + if (jsonObject["imageInputData"] != null) { + result.imageInputData = []; + for (var item in jsonObject["imageInputData"]) { + result.imageInputData!.addSafe(ImageInputData.fromJson(item)); + } + } + result.dtc = _bytesFromBase64(jsonObject["dtc"]); + result.livePortrait = _bytesFromBase64(jsonObject["livePortrait"]); + result.extPortrait = _bytesFromBase64(jsonObject["extPortrait"]); + result.oneShotIdentification = jsonObject["oneShotIdentification"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "scenario": scenario?.value, + "onlineProcessingConfig": onlineProcessingConfig?.toJson(), + "image": _bytesToBase64(image), + "images": images?.map((e) => _bytesToBase64(e)).toList(), + "data": _bytesToBase64(data), + "dataList": dataList?.map((e) => _bytesToBase64(e)).toList(), + "imageInputData": imageInputData?.map((e) => e.toJson()).toList(), + "dtc": _bytesToBase64(dtc), + "oneShotIdentification": oneShotIdentification, + "livePortrait": _bytesToBase64(livePortrait), + "extPortrait": _bytesToBase64(extPortrait), + }.clearNulls(); +} + +class ImageInputData { + /// An image. + Uint8List get image => _image; + Uint8List _image; + + /// Light type, one of RGLGraphicFieldLight values. + Lights get light => _light; + Lights _light; + + /// An index of the document page whence the graphic field is extracted. + int get pageIndex => _pageIndex; + int _pageIndex; + + ImageInputData( + Uint8List image, { + Lights light = Lights.WHITE_FULL, + int pageIndex = 0, + }) : _image = image, + _light = light, + _pageIndex = pageIndex; + + @visibleForTesting + Map toJson() => { + "image": _bytesToBase64(image), + "light": light.value, + "pageIndex": pageIndex, + }; + + @visibleForTesting + static ImageInputData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = ImageInputData(_bytesFromBase64(jsonObject["image"])!); + + result._pageIndex = jsonObject["pageIndex"]; + result._light = Lights.getByValue(jsonObject["light"])!; + + return result; + } +} diff --git a/lib/src/config/rfid_config.dart b/lib/src/config/rfid_config.dart new file mode 100644 index 0000000000..19d5e40759 --- /dev/null +++ b/lib/src/config/rfid_config.dart @@ -0,0 +1,146 @@ +// +// RFIDConfig.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// A configuration file for the RFID chip processing. +class RFIDConfig { + DocumentReaderCompletion? _completion; + RFIDCompletion? _rfidCompletion; + bool _disableUI = false; + + /// Callback for reveiving notification about RFID reading process. + RFIDProgressCompletion? onProgress; + + /// Callback for receiving signal when RFID chip is recognized + /// by a phone and chip reading is started. + /// + /// Only used with default constructor. If [RFIDConfig.withoutUI] was used, + /// you will receive this update via [DocumentReaderCompletion]. + ChipDetectedCompletion? onChipDetected; + + /// Fires when RFID chip reading was interrupted with no severe reasons + /// (for example connection to the chip was lost) and will be reestablished automatically. + /// + /// Only used with default constructor. If [RFIDConfig.withoutUI] was used, + /// you will receive this update via [DocumentReaderCompletion] + /// and chip reading will not be reestablished. + RetryReadChipCompletion? onRetryReadChip; + + /// Callback for receiving RFID request data + PaCertificateCompletion? onRequestPACertificates; + + /// Callback for receiving RFID request data + TaCertificateCompletion? onRequestTACertificates; + + /// Callback for receiving RFID request data + TaSignatureCompletion? onRequestTASignature; + + /// Callback for receiving RFID request data + PACEProtocolCompletion? onRequestPACEProtocol; + + /// Callback for receiving RFID request data + CAProtocolCompletion? onRequestCAProtocol; + + /// Regular RFID chip reading. + /// + /// [completion] - block to execute after the chip reading process finishes. + RFIDConfig(DocumentReaderCompletion completion) : _completion = completion; + + /// RFID chip reading with no UI. + /// + /// User is supposed to implement the UI. + /// + /// Since this constructor accepts [RFIDCompletion] + /// instead of [DocumentReaderCompletion], user will be provided + /// with more in-depth error information. + /// + /// [completion] - block to execute after the chip reading process finishes. + RFIDConfig.withoutUI(RFIDCompletion completion) + : _rfidCompletion = completion, + _disableUI = true; + + Map toJson() => { + "paCertificates": onRequestPACertificates != null, + "taCertificates": onRequestTACertificates != null, + "taSignature": onRequestTASignature != null, + "paceProtocol": onRequestPACEProtocol != null, + "caProtocol": onRequestCAProtocol != null, + }; +} + +/// Callback for receiving answer from processing engine. +/// +/// [action] defines current processing status. +/// +/// [results] defines current processing results. +/// +/// [error] in case of anything is wrong - brief message for developer, `null` otherwise. +typedef RFIDCompletion = void Function( + DocReaderAction action, + Results? results, + RFIDException? error, +); + +/// Completion for reveiving notification about RFID reading process. +typedef RFIDProgressCompletion = void Function(RFIDNotification notification); + +/// Callback for receiving signal when RFID chip is recognized +/// by a phone and chip reading is started. +/// +/// Only used with default constructor. If [RFIDConfig.withoutUI] was used, +/// you will receive this update via [DocumentReaderCompletion]. +typedef ChipDetectedCompletion = void Function(); + +/// Fires when RFID chip reading was interrupted with no severe reasons +/// (for example connection to the chip was lost) and will be reestablished automatically. +/// +/// Only used with default constructor. If [RFIDConfig.withoutUI] was used, +/// you will receive this update via [DocumentReaderCompletion] +/// and chip reading will not be reestablished. +/// +/// [error] a brief message for developer. +typedef RetryReadChipCompletion = void Function(RFIDException error); + +/// Callback for receiving RFID request data. +typedef PaCertificateCompletion = void Function( + Uint8List serialNumber, + PAResourcesIssuer? issuer, + PKDCertificateRequest request, +); + +/// Callback for receiving RFID request data. +typedef TaCertificateCompletion = void Function( + String? keyCAR, PKDCertificateRequest request); + +/// Provided to a user for passing PKDCertificates +/// to the native part of DocumentReader. +typedef PKDCertificateRequest = Future Function( + List? certificates); + +/// Callback for receiving RFID request data. +typedef TaSignatureCompletion = void Function( + TAChallenge? challenge, TASignatureRequest request); + +/// Provided to a user for passing TASignature +/// to the native part of DocumentReader. +typedef TASignatureRequest = Future Function(ByteData? signature); + +/// Callback for receiving RFID request data. +typedef PACEProtocolCompletion = void Function( + List protocols, PACEProtocolRequest request); + +/// Provided to a user for choosing PACEProtocol. +typedef PACEProtocolRequest = Future Function(PACEProtocol protocol); + +/// Callback for receiving RFID request data. +typedef CAProtocolCompletion = void Function( + List protocols, CAProtocolRequest request); + +/// Provided to a user for choosing CAProtocol. +typedef CAProtocolRequest = Future Function(CAProtocol protocol); diff --git a/lib/src/config/scanner_config.dart b/lib/src/config/scanner_config.dart new file mode 100644 index 0000000000..9fb56cf7d4 --- /dev/null +++ b/lib/src/config/scanner_config.dart @@ -0,0 +1,79 @@ +// +// ScannerConfig.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class ScannerConfig { + /// Documents processing scenario. + Scenario? get scenario => _scenario; + Scenario? _scenario; + + /// Configuration class for online processing. + /// + /// /// Requires network connection. + OnlineProcessingConfig? get onlineProcessingConfig => _onlineProcessingConfig; + OnlineProcessingConfig? _onlineProcessingConfig; + + /// Live portrait photo. + /// + /// Requires network connection. + Uint8List? livePortrait; + + /// Portrait photo from an external source. + /// + /// Requires network connection. + Uint8List? extPortrait; + + /// Camera id. + /// + /// Android only. + int? cameraId; + + ScannerConfig( + Scenario scenario, + OnlineProcessingConfig onlineProcessingConfig, + ) : _scenario = scenario, + _onlineProcessingConfig = onlineProcessingConfig; + + ScannerConfig.withScenario(Scenario scenario) + : _scenario = scenario, + _onlineProcessingConfig = null; + + ScannerConfig.withOnlineProcessingConfig( + OnlineProcessingConfig onlineProcessingConfig, + ) : _scenario = null, + _onlineProcessingConfig = onlineProcessingConfig; + + ScannerConfig._empty(); + + @visibleForTesting + static ScannerConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + + var result = ScannerConfig._empty(); + + result._scenario = Scenario.getByValue(jsonObject["scenario"]); + result._onlineProcessingConfig = OnlineProcessingConfig.fromJson( + jsonObject["onlineProcessingConfig"], + ); + result.livePortrait = _bytesFromBase64(jsonObject["livePortrait"]); + result.extPortrait = _bytesFromBase64(jsonObject["extPortrait"]); + result.cameraId = jsonObject["cameraId"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "scenario": scenario?.value, + "onlineProcessingConfig": onlineProcessingConfig?.toJson(), + "livePortrait": _bytesToBase64(livePortrait), + "extPortrait": _bytesToBase64(extPortrait), + "cameraId": cameraId, + }.clearNulls(); +} diff --git a/lib/src/info/License.dart b/lib/src/info/License.dart new file mode 100644 index 0000000000..cffe068a37 --- /dev/null +++ b/lib/src/info/License.dart @@ -0,0 +1,45 @@ +// +// License.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class contains properties to get the information about the license. +class License { + /// Allows you to get an expiration date of your license. + String? get expiryDate => _expiryDate; + String? _expiryDate; + + /// Allows you to get a list of country identifiers which are defined for + /// processing in the license. If the array is empty, there are no + /// restrictions for processing. + List? get countryFilter => _countryFilter; + List? _countryFilter; + + /// Allows you to verify that RFID chip reading capabilities are added to your license. + bool get isRfidAvailable => _isRfidAvailable; + late bool _isRfidAvailable; + + @visibleForTesting + static License? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = License(); + + result._expiryDate = jsonObject["expiryDate"]; + result._countryFilter = _stringListFrom(jsonObject["countryFilter"]); + result._isRfidAvailable = jsonObject["isRfidAvailable"] ?? false; + + return result; + } + + @visibleForTesting + Map toJson() => { + "expiryDate": expiryDate, + "countryFilter": countryFilter, + "isRfidAvailable": isRfidAvailable, + }.clearNulls(); +} diff --git a/lib/src/info/doc_reader_exception.dart b/lib/src/info/doc_reader_exception.dart new file mode 100644 index 0000000000..564a4c32a8 --- /dev/null +++ b/lib/src/info/doc_reader_exception.dart @@ -0,0 +1,174 @@ +// +// DocReaderException.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class DocReaderException { + ErrorCodes get code => _code; + late ErrorCodes _code; + + String get message => _message; + late String _message; + + DocReaderException.unknown() { + _code = ErrorCodes.UNKNOWN; + _message = "Unknown exception"; + } + + @visibleForTesting + static DocReaderException? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocReaderException.unknown(); + + result._code = ErrorCodes.getByValue(jsonObject["code"])!; + result._message = jsonObject["message"] ?? ""; + + return result; + } + + @visibleForTesting + Map toJson() => + {"code": code.value, "message": message}.clearNulls(); +} + +/// Enum contains all possible error codes +enum ErrorCodes { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// A Core framework is absent. + INITIALIZATION_CORE_ABSENT(0), + + /// The reader is not initialized or an unknown initialization error occured. + INITIALIZATION_FAILED(1), + + /// This scenario is not supported based on your license and Core framework + /// capabilities. + INCORRECT_SCENARIO(2), + + /// There are no results after recognition of camera frames. + NO_RESULT(3), + + /// An error is encountered during database removal. + REMOVE_DATABASE(4), + + /// An error is encountered during database download. + FETCHING_DATABASE(5), + + /// An incorrect database ID. + DB_ID_NOT_FOUND(6), + + /// An incorrect database ID. + DB_DESCRIPTION_NOT_FOUND(7), + + /// An error is encountered during database save on your device. + SAVE_DB(8), + + /// A database is corrupted. + DOWNLOAD_DB_INCORRECT_CHECKSUM(9), + + /// A database is corrupted. + DB_DOWNLOAD(10), + + /// Deprecated. + DB_CREATION(11), + + /// An RFID error. + RFID_ERROR(12), + + /// A license is absent or corrupted. + LICENSE_ABSENT_OR_CORRUPTED(13), + + /// An invalid date, i.e. the license may be expired, or the date and time of + /// set on the device doesn't correspond to reality. + LICENSE_INVALID_DATE(14), + + /// An invalid version. + LICENSE_INVALID_VERSION(15), + + /// An invalid device ID. + LICENSE_INVALID_DEVICE_ID(16), + + /// An invalid OS or application ID. + LICENSE_INVALID_SYSTEM_OR_APP_ID(17), + + /// There are no capabilities for this functionality in your license. + LICENSE_NO_CAPABILITIES(18), + + /// There are no authenticity capabilities in your license. + LICENSE_NO_AUTHENTICITY(19), + + /// An invalid URL of the video during its generating. + RECORD_PROCESS_INVALID_OUTPUT_URL(20), + + /// Something went wrong with online license processing. + LICENSE_ONLINE_ERROR(21), + + /// db.dat is absent. + LICENSE_NO_DATABASE(22), + + /// db.dat is incorrect. + LICENSE_DATABASE_INCORRECT(23), + + /// Failed to set TCC params. + INVALID_TCC_PARAMS(24), + + /// The operation failed due to RFID reading has already started. + RFID_IN_PROGRESS(25), + + START_BACKEND_PROCESSING(26), + + ADD_DATA_TO_PACKAGE(27), + + FINALIZE_FAILED(28), + + CAMERA_NO_PERMISSION(29), + + CAMERA_NOT_AVAILABLE(30), + + /// The camera not supported in this scenario. + CANNOT_USE_CAMERA_IN_SCENARIO(40), + + BLUETOOTH_NO_PERMISSION(41), + + BACKEND_ONLINE_PROCESSING(303), + + WRONG_INPUT(400), + + /// Missing output result. + RESULT_UNAVAILABLE(410), + + /// Incorrect result output. + RESULT_WRONG_OUTPUT(411), + + STATE_EXCEPTION(500), + + BLE_EXCEPTION(600), + + FEATURE_BLUETOOTH_LE_NOT_SUPPORTED(601), + + APP_BACKGROUND(700), + + ONLINE_PROCESSING_WRONG_INPUT(800), + + MDL_EXCEPTION(900), + + NATIVE_JAVA_EXCEPTION(1000); + + const ErrorCodes(this.value); + final int value; + + static ErrorCodes? getByValue(int? i) { + if (i == null) return null; + try { + return ErrorCodes.values.firstWhere((x) => x.value == i); + } catch (_) { + return ErrorCodes.UNKNOWN; + } + } +} diff --git a/lib/src/info/doc_reader_scenario.dart b/lib/src/info/doc_reader_scenario.dart new file mode 100644 index 0000000000..2a6f1a018e --- /dev/null +++ b/lib/src/info/doc_reader_scenario.dart @@ -0,0 +1,207 @@ +// +// DocReaderScenario.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class DocReaderScenario { + /// ID of the scenario. + String get name => _name; + late String _name; + + /// string representation of scenario ID. + String get caption => _caption; + late String _caption; + + /// Description of the scenario. + String get description => _description; + late String _description; + + /// Available orientation for scenario. + DocReaderOrientation get frameOrientation => _frameOrientation; + late DocReaderOrientation _frameOrientation; + + bool get uvTorch => _uvTorch; + late bool _uvTorch; + + bool get faceExt => _faceExt; + late bool _faceExt; + + bool get multiPageOff => _multiPageOff; + late bool _multiPageOff; + + bool get seriesProcessMode => _seriesProcessMode; + late bool _seriesProcessMode; + + double get frameKWHLandscape => _frameKWHLandscape; + late double _frameKWHLandscape; + + double get frameKWHPortrait => _frameKWHPortrait; + late double _frameKWHPortrait; + + double get frameKWHDoublePageSpreadLandscape => + _frameKWHDoublePageSpreadLandscape; + late double _frameKWHDoublePageSpreadLandscape; + + double get frameKWHDoublePageSpreadPortrait => + _frameKWHDoublePageSpreadPortrait; + late double _frameKWHDoublePageSpreadPortrait; + + bool get manualCrop => _manualCrop; + late bool _manualCrop; + + @visibleForTesting + static DocReaderScenario? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocReaderScenario(); + + result._uvTorch = jsonObject["uvTorch"]; + result._frameOrientation = + DocReaderOrientation.getByValue(jsonObject["frameOrientation"])!; + result._faceExt = jsonObject["faceExt"]; + result._multiPageOff = jsonObject["multiPageOff"]; + result._seriesProcessMode = jsonObject["seriesProcessMode"]; + result._frameKWHLandscape = jsonObject["frameKWHLandscape"].toDouble(); + result._frameKWHPortrait = jsonObject["frameKWHPortrait"].toDouble(); + result._frameKWHDoublePageSpreadPortrait = + jsonObject["frameKWHDoublePageSpreadPortrait"].toDouble(); + result._frameKWHDoublePageSpreadLandscape = + jsonObject["frameKWHDoublePageSpreadLandscape"].toDouble(); + result._name = jsonObject["name"]; + result._caption = jsonObject["caption"]; + result._description = jsonObject["description"]; + result._manualCrop = jsonObject["manualCrop"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "uvTorch": uvTorch, + "frameOrientation": frameOrientation.value, + "faceExt": faceExt, + "multiPageOff": multiPageOff, + "seriesProcessMode": seriesProcessMode, + "frameKWHLandscape": frameKWHLandscape, + "frameKWHPortrait": frameKWHPortrait, + "frameKWHDoublePageSpreadPortrait": frameKWHDoublePageSpreadPortrait, + "frameKWHDoublePageSpreadLandscape": frameKWHDoublePageSpreadLandscape, + "name": name, + "caption": caption, + "description": description, + "manualCrop": manualCrop, + }.clearNulls(); +} + +enum Scenario { + /// Processing scenario for obtaining MRZ data. + MRZ("Mrz"), + + /// Processing scenario for obtaining barcode data. + BARCODE("Barcode"), + + /// Processing scenario for detecting document boundaries. + LOCATE("Locate"), + + /// Processing scenario for obtaining visual zone OCR results. + OCR("Ocr"), + + /// Processing scenario for document type recognition. + DOCTYPE("DocType"), + + /// Processing scenario for obtaining MRZ and/or barcode data. + MRZ_OR_BARCODE("MrzOrBarcode"), + + /// Processing scenario for detecting document boundaries and/or obtaining MRZ data. + MRZ_OR_LOCATE("MrzOrLocate"), + + /// Processing scenario for detecting document boundaries and obtaining MRZ data. + MRZ_AND_LOCATE("MrzAndLocate"), + + /// Processing scenario for detecting document boundaries and obtaining barcode data. + BARCODE_AND_LOCATE("BarcodeAndLocate"), + + /// Processing scenario for obtaining MRZ data or visual zone OCR results. + MRZ_OR_OCR("MrzOrOcr"), + + /// Processing scenario for obtaining MRZ or barcode or visual zone OCR results. + MRZ_OR_BARCODE_OR_OCR("MrzOrBarcodeOrOcr"), + + /// Processing scenario for detecting document boundaries and obtaining + /// MRZ data or visual zone OCR results. + LOCATE_VISUAL_AND_MRZ_OR_OCR("LocateVisual_And_MrzOrOcr"), + + /// Processing scenario for obtaining all document data. + FULL_PROCESS("FullProcess"), + + /// Processing scenario for obtaining all document data and document authentication. + FULL_AUTH("FullAuth"), + + /// Processing scenario for obtaining visual zone OCR results from + /// Russian National Passport and MRZ data from any document. + ID3RUS("Id3Rus"), + + /// Processing scenario for obtaining data from registration stamps in + /// Russian passports. + RUS_STAMP("RusStamp"), + + /// Processing scenario for obtaining OCR results of any image. + OCR_FREE("OcrFree"), + + /// Processing scenario for obtaining bank card data. + CREDIT_CARD("CreditCard"), + + /// Scenario for obtaining an original image without any processing. + CAPTURE("Capture"), + + /// Scenario for Digital Travel Credentials (DTC) processing. + DTC("DTC"), + + /// Processing scenario for RFID reading. + RFID("RFID"); + + const Scenario(this.value); + final String value; + + static Scenario? getByValue(String? i) { + if (i == null || i == "") return null; + return Scenario.values.firstWhere((x) => x.value == i); + } +} + +/// Contains set of values of the application's orientation. +enum DocReaderOrientation { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// All interface orientations - orientation not set, activities will rotate. + ALL(0), + + /// A portrait interface orientation. + PORTRAIT(1), + + /// Both landscape-left and landscape-right interface orientation. + LANDSCAPE(2), + + /// A landscape-left interface orientation. + LANDSCAPE_LEFT(3), + + /// A landscape-right interface orientation. + LANDSCAPE_RIGHT(4); + + const DocReaderOrientation(this.value); + final int value; + + static DocReaderOrientation? getByValue(int? i) { + if (i == null) return null; + try { + return DocReaderOrientation.values.firstWhere((x) => x.value == i); + } catch (_) { + return DocReaderOrientation.UNKNOWN; + } + } +} diff --git a/lib/src/info/doc_reader_version.dart b/lib/src/info/doc_reader_version.dart new file mode 100644 index 0000000000..4c3d71da78 --- /dev/null +++ b/lib/src/info/doc_reader_version.dart @@ -0,0 +1,49 @@ +// +// DocReaderVersion.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class contains properties to get the information about the SDK. +class DocReaderVersion { + /// A version of the API framework. + String? get api => _api; + String? _api; + + /// A version of the Core framework. + String? get core => _core; + String? _core; + + /// A type of the Core framework. + String? get coreMode => _coreMode; + String? _coreMode; + + /// A version of the database. + DocumentsDatabase? get database => _database; + DocumentsDatabase? _database; + + @visibleForTesting + static DocReaderVersion? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocReaderVersion(); + + result._api = jsonObject["api"]; + result._core = jsonObject["core"]; + result._coreMode = jsonObject["coreMode"]; + result._database = DocumentsDatabase.fromJson(jsonObject["database"]); + + return result; + } + + @visibleForTesting + Map toJson() => { + "api": api, + "core": core, + "coreMode": coreMode, + "database": database?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/info/documents_database.dart b/lib/src/info/documents_database.dart new file mode 100644 index 0000000000..b786ad1191 --- /dev/null +++ b/lib/src/info/documents_database.dart @@ -0,0 +1,68 @@ +// +// DocumentsDatabase.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class contains properties to get the information about the database. +class DocumentsDatabase { + /// An ID of the database, e.g. BLR, RUS. + String? get databaseID => _databaseID; + String? _databaseID; + + /// A version of the database. + String? get version => _version; + String? _version; + + /// A date when the database was created. + String? get date => _date; + String? _date; + + /// A list of supported documents in the database. + String? get databaseDescription => _databaseDescription; + String? _databaseDescription; + + /// A number of countries included in the database. + int get countriesNumber => _countriesNumber; + late int _countriesNumber; + + /// A number of documents included in the database. + int get documentsNumber => _documentsNumber; + late int _documentsNumber; + + /// Database size. In bytes. + /// Available for database update check. + int? get size => _size; + int? _size; + + @visibleForTesting + static DocumentsDatabase? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocumentsDatabase(); + + result._databaseID = jsonObject["databaseID"]; + result._version = jsonObject["version"]; + result._date = jsonObject["date"]; + result._databaseDescription = jsonObject["databaseDescription"]; + result._countriesNumber = jsonObject["countriesNumber"]; + result._documentsNumber = jsonObject["documentsNumber"]; + result._size = jsonObject["size"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "databaseID": databaseID, + "version": version, + "date": date, + "databaseDescription": databaseDescription, + "countriesNumber": countriesNumber, + "documentsNumber": documentsNumber, + "size": size, + }.clearNulls(); +} diff --git a/lib/src/info/prepare_progress.dart b/lib/src/info/prepare_progress.dart new file mode 100644 index 0000000000..3a425e0bfc --- /dev/null +++ b/lib/src/info/prepare_progress.dart @@ -0,0 +1,47 @@ +// +// DocReaderVersion.dart +// DocumentReader +// +// Created by Pavel Masiuk on 15.04.2024. +// Copyright © 2024 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class contains info about database preparation progress. +class PrepareProgress { + int get downloadedBytes => _downloadedBytes; + int _downloadedBytes; + + int get totalBytes => _totalBytes; + int _totalBytes; + + int get progress => _progress; + int _progress; + + PrepareProgress(int downloadedBytes, int totalBytes, int progress) + : _downloadedBytes = downloadedBytes, + _totalBytes = totalBytes, + _progress = progress; + + @visibleForTesting + static PrepareProgress? fromJson(jsonObject) { + if (jsonObject == null) return null; + return PrepareProgress( + jsonObject["downloadedBytes"], + jsonObject["totalBytes"], + jsonObject["progress"], + ); + } + + @visibleForTesting + Map toJson() => { + "downloadedBytes": downloadedBytes, + "totalBytes": totalBytes, + "progress": progress, + }.clearNulls(); +} + +/// Callback for receiving notifications on Documents Database preparation. +typedef DocumentReaderPrepareCompletion = void Function( + PrepareProgress progress); diff --git a/lib/src/info/rfid_exception.dart b/lib/src/info/rfid_exception.dart new file mode 100644 index 0000000000..fbbe2da44c --- /dev/null +++ b/lib/src/info/rfid_exception.dart @@ -0,0 +1,32 @@ +// +// RFIDException.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class RFIDException { + RFIDErrorCodes get code => _code; + late RFIDErrorCodes _code; + + String get message => _message; + late String _message; + + @visibleForTesting + static RFIDException? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDException(); + + result._code = RFIDErrorCodes.getByValue(jsonObject["code"])!; + result._message = jsonObject["message"] ?? ""; + + return result; + } + + @visibleForTesting + Map toJson() => + {"code": code.value, "message": message}.clearNulls(); +} diff --git a/lib/src/internal/Bridge.dart b/lib/src/internal/Bridge.dart new file mode 100644 index 0000000000..dd57a2f25c --- /dev/null +++ b/lib/src/internal/Bridge.dart @@ -0,0 +1,21 @@ +// +// Bridge.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +const _methodChannelID = 'flutter_document_reader_api/method'; +const MethodChannel _bridge = const MethodChannel(_methodChannelID); + +String _eventPrefix = 'flutter_document_reader_api/event/'; +List _eventChannels = []; + +void _eventChannel(String id, listen(msg)) { + if (_eventChannels.contains(id)) return; + _eventChannels.add(id); + EventChannel(_eventPrefix + id).receiveBroadcastStream().listen(listen); +} diff --git a/lib/src/internal/Utils.dart b/lib/src/internal/Utils.dart new file mode 100644 index 0000000000..d494c9fb8f --- /dev/null +++ b/lib/src/internal/Utils.dart @@ -0,0 +1,56 @@ +// +// Utils.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +double? _toDouble(value) => value?.toDouble(); + +dynamic _decode(String? value) => value == null ? null : jsonDecode(value); + +ByteData? _dataFromBase64(String? value) => + value == null ? null : ByteData.view(base64Decode(value).buffer); + +String? _dataToBase64(ByteData? value) => + value == null ? null : base64Encode(value.buffer.asUint8List()); + +Uint8List? _bytesFromBase64(String? value) => + value == null ? null : base64Decode(value); + +String? _bytesToBase64(Uint8List? value) => + value == null ? null : base64Encode(value); + +Color? _intToColor(int? value) => value == null ? null : Color(value); + +// ignore: deprecated_member_use +int? _intFromColor(Color? value) => value?.value; + +List? _intListFrom(List? value) { + if (value == null) return null; + return List.from(value); +} + +List? _stringListFrom(List? value) { + if (value == null) return null; + return List.from(value); +} + +extension _NullSafety on List { + void addSafe(E value) { + if (value != null) add(value); + } +} + +extension _ClearNulls on Map { + Map clearNulls() { + Map result = {}; + forEach((key, value) { + if (value != null) result[key] = value; + }); + return result; + } +} diff --git a/lib/src/internal/event_channels.dart b/lib/src/internal/event_channels.dart new file mode 100644 index 0000000000..fc881c8d98 --- /dev/null +++ b/lib/src/internal/event_channels.dart @@ -0,0 +1,162 @@ +part of "../../flutter_document_reader_api.dart"; + +// DocumentReaderCompletion and RFIDCompletion use the same eventChannel so +// they need to have sommon eventChannel function. +// Because of they way it is implemented, one of the _documentReaderCompletion +// and _rfidCompletion always has to be null, to when setting one completion, +// we have to set the other one to null. +DocumentReaderCompletion? _documentReaderCompletion; +void _setDocumentReaderCompletion(DocumentReaderCompletion completion) { + _documentReaderCompletion = completion; + _rfidCompletion = null; + + _eventChannel('completion', (msg) { + var jsonObject = json.decode(msg); + var action = DocReaderAction.getByValue(jsonObject["action"])!; + var results = Results.fromJson(jsonObject["results"]); + var error = DocReaderException.fromJson(jsonObject["error"]); + var rfidError = RFIDException.fromJson(jsonObject["error"]); + + // We need ELSE instead of 2 ifs besause if _documentReaderCompletion?.call + // will run rfid, then it will run _setRFIDCompletion, and only after that + // it will check if _rfidCompletion is null, so it will run instantly + // both _documentReaderCompletion and _rfidCompletion + // with the same parameters. + if (_documentReaderCompletion != null) { + _documentReaderCompletion!(action, results, error); + } else { + _rfidCompletion!(action, results, rfidError); + } + }); +} + +RFIDCompletion? _rfidCompletion; +void _setRFIDCompletion(RFIDCompletion rfidCompletion) { + _documentReaderCompletion = null; + _rfidCompletion = rfidCompletion; +} + +late DocumentReaderPrepareCompletion _documentReaderPrepareCompletion; +void _setDocumentReaderPrepareCompletion( + DocumentReaderPrepareCompletion completion, +) { + _documentReaderPrepareCompletion = completion; + _eventChannel('database_progress', (msg) { + var progress = PrepareProgress.fromJson(json.decode(msg))!; + _documentReaderPrepareCompletion(progress); + }); +} + +late CustomButtonTappedCompletion _customButtonTappedCompletion; +void _setCustomButtonTappedCompletion(CustomButtonTappedCompletion completion) { + _customButtonTappedCompletion = completion; + _eventChannel( + 'onCustomButtonTappedEvent', + (msg) => _customButtonTappedCompletion(msg), + ); +} + +late VideoEncoderCompletion _videoEncoderCompletion; +void _setVideoEncoderCompletion(VideoEncoderCompletion completion) { + _videoEncoderCompletion = completion; + _eventChannel( + 'video_encoder_completion', + (msg) => _videoEncoderCompletion(msg), + ); +} + +RFIDProgressCompletion? _rfidProgressCompletion; +void _setRFIDProgressCompletion(RFIDProgressCompletion? completion) { + _rfidProgressCompletion = completion; + _eventChannel('rfidOnProgressCompletion', (msg) { + var notify = RFIDNotification.fromJson(json.decode(msg))!; + _rfidProgressCompletion?.call(notify); + }); +} + +ChipDetectedCompletion? _chipDetectedCompletion; +void _setChipDetectedCompletion(ChipDetectedCompletion? completion) { + _chipDetectedCompletion = completion; + _eventChannel( + 'rfidOnChipDetectedEvent', + (_) => _chipDetectedCompletion?.call(), + ); +} + +RetryReadChipCompletion? _retryReadChipCompletion; +void _setRetryReadChipCompletion(RetryReadChipCompletion? completion) { + _retryReadChipCompletion = completion; + _eventChannel('rfidOnRetryReadChipEvent', (msg) { + var error = RFIDException.fromJson(json.decode(msg))!; + _retryReadChipCompletion?.call(error); + }); +} + +PaCertificateCompletion? _paCertificateCompletion; +void _setPaCertificateCompletion(PaCertificateCompletion? completion) { + _paCertificateCompletion = completion; + _eventChannel('pa_certificate_completion', (msg) { + var jsonObject = json.decode(msg); + var serialNumber = _bytesFromBase64(jsonObject["serialNumber"])!; + var issuer = PAResourcesIssuer.fromJson(jsonObject["issuer"]); + + _paCertificateCompletion?.call(serialNumber, issuer, (certificates) async { + await _bridge.invokeMethod("providePACertificates", [ + certificates?.map((e) => e.toJson()).toList(), + ]); + }); + }); +} + +TaCertificateCompletion? _taCertificateCompletion; +void _setTaCertificateCompletion(TaCertificateCompletion? completion) { + _taCertificateCompletion = completion; + _eventChannel('ta_certificate_completion', (msg) { + _taCertificateCompletion?.call(msg, (certificates) async { + await _bridge.invokeMethod("provideTACertificates", [ + certificates?.map((e) => e.toJson()).toList(), + ]); + }); + }); +} + +TaSignatureCompletion? _taSignatureCompletion; +void _setTaSignatureCompletion(TaSignatureCompletion? completion) { + _taSignatureCompletion = completion; + _eventChannel('ta_signature_completion', (msg) { + _taSignatureCompletion?.call( + TAChallenge.fromJson(json.decode(msg)), + (signature) async { + await _bridge.invokeMethod("provideTASignature", [ + _dataToBase64(signature), + ]); + }, + ); + }); +} + +PACEProtocolCompletion? _paceProtocolCompletion; +void _setPACEProtocolCompletion(PACEProtocolCompletion? completion) { + _paceProtocolCompletion = completion; + _eventChannel('paceProtocolCompletionEvent', (msg) { + _paceProtocolCompletion?.call( + (msg as List).map((item) => PACEProtocol.fromJson(item)!).toList(), + (protocol) async { + await _bridge.invokeMethod("selectPACEProtocol", [protocol.toJson()]); + }, + ); + }); +} + +CAProtocolCompletion? _caProtocolCompletion; +void _setCAProtocolCompletion(CAProtocolCompletion? completion) { + _caProtocolCompletion = completion; + _eventChannel('caProtocolCompletionEvent', (msg) { + _caProtocolCompletion?.call( + (msg as List).map((item) => CAProtocol.fromJson(item)!).toList(), + (protocol) async { + await _bridge.invokeMethod("selectCAProtocol", [protocol.toJson()]); + }, + ); + }); +} diff --git a/lib/src/mdl/data_retrieval.dart b/lib/src/mdl/data_retrieval.dart new file mode 100644 index 0000000000..e21f6411d7 --- /dev/null +++ b/lib/src/mdl/data_retrieval.dart @@ -0,0 +1,82 @@ +part of "../../flutter_document_reader_api.dart"; + +class DataRetrieval { + MDLDeviceRetrieval _deviceRetrieval; + MDLDocRequestPreset? _docRequestPreset; + MDLIntentToRetain _intentToRetain = MDLIntentToRetain.TRUE; + List _requests = []; + + DataRetrieval(this._deviceRetrieval); + + setDocRequestPreset( + MDLDocRequestPreset docRequestPreset, + MDLIntentToRetain intentToRetain, + ) { + _docRequestPreset = docRequestPreset; + _intentToRetain = intentToRetain; + } + + addDocRequest(DocumentRequestMDL request) { + _requests.add(request); + } + + /// Allows you to deserialize object. + static DataRetrieval? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DataRetrieval( + MDLDeviceRetrieval.getByValue(jsonObject["deviceRetrieval"])!); + + result._docRequestPreset = + MDLDocRequestPreset.getByValue(jsonObject["docRequestPreset"]); + result._intentToRetain = + MDLIntentToRetain.getByValue(jsonObject["intentToRetain"])!; + result._requests = (jsonObject["requests"] as List) + .map((item) => DocumentRequestMDL.fromJson(item)!) + .toList(); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "deviceRetrieval": _deviceRetrieval.value, + "docRequestPreset": _docRequestPreset?.value, + "intentToRetain": _intentToRetain.value, + "requests": _requests.map((item) => item.toJson()).toList(), + }.clearNulls(); +} + +enum MDLDocRequestPreset { + ALL(0), + + AGE(1), + + STANDARD_ID(2), + + TRAVEL(3), + + DRIVERS_LICENSE(4); + + const MDLDocRequestPreset(this.value); + final int value; + + static MDLDocRequestPreset? getByValue(int? i) { + if (i == null) return null; + return MDLDocRequestPreset.values.firstWhere((x) => x.value == i); + } +} + +/// Contains device retrieval types. +enum MDLDeviceRetrieval { + NFC(1), + + BLE(2); + + const MDLDeviceRetrieval(this.value); + final int value; + + static MDLDeviceRetrieval? getByValue(int? i) { + if (i == null) return null; + return MDLDeviceRetrieval.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/mdl/device_engagement.dart b/lib/src/mdl/device_engagement.dart new file mode 100644 index 0000000000..0b4cab7976 --- /dev/null +++ b/lib/src/mdl/device_engagement.dart @@ -0,0 +1,39 @@ +part of "../../flutter_document_reader_api.dart"; + +class DeviceEngagement { + List deviceRetrievalMethods = []; + + /// Allows you to deserialize object. + static DeviceEngagement? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DeviceEngagement(); + + result.deviceRetrievalMethods = + (jsonObject["deviceRetrievalMethods"] as List) + .map((item) => DeviceRetrievalMethod.fromJson(item)!) + .toList(); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "deviceRetrievalMethods": + deviceRetrievalMethods.map((e) => e.toJson()).toList() + }.clearNulls(); +} + +/// Contains device engagement types. +enum MDLDeviceEngagement { + QR(0), + + NFC(1); + + const MDLDeviceEngagement(this.value); + final int value; + + static MDLDeviceEngagement? getByValue(int? i) { + if (i == null) return null; + return MDLDeviceEngagement.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/mdl/device_retrieval_method.dart b/lib/src/mdl/device_retrieval_method.dart new file mode 100644 index 0000000000..fc5e34f873 --- /dev/null +++ b/lib/src/mdl/device_retrieval_method.dart @@ -0,0 +1,56 @@ +part of "../../flutter_document_reader_api.dart"; + +class DeviceRetrievalMethod { + MDLDeviceRetrieval get type => _type; + late MDLDeviceRetrieval _type; + + int? get version => _version; + int? _version; + + int? get cmdMaxLength => _cmdMaxLength; + int? _cmdMaxLength; + + int? get respMaxLength => _respMaxLength; + int? _respMaxLength; + + bool? get clientModeSupport => _clientModeSupport; + bool? _clientModeSupport; + + String? get clientModeUUID => _clientModeUUID; + String? _clientModeUUID; + + bool? get serverModeSupport => _serverModeSupport; + bool? _serverModeSupport; + + String? get serverModeUUID => _serverModeUUID; + String? _serverModeUUID; + + /// Allows you to deserialize object. + static DeviceRetrievalMethod? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DeviceRetrievalMethod(); + + result._type = MDLDeviceRetrieval.getByValue(jsonObject["type"])!; + result._version = jsonObject["version"]; + result._cmdMaxLength = jsonObject["cmdMaxLength"]; + result._respMaxLength = jsonObject["respMaxLength"]; + result._clientModeSupport = jsonObject["clientModeSupport"]; + result._clientModeUUID = jsonObject["clientModeUUID"]; + result._serverModeSupport = jsonObject["serverModeSupport"]; + result._serverModeUUID = jsonObject["serverModeUUID"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type.value, + "version": version, + "cmdMaxLength": cmdMaxLength, + "respMaxLength": respMaxLength, + "clientModeSupport": clientModeSupport, + "clientModeUUID": clientModeUUID, + "serverModeSupport": serverModeSupport, + "serverModeUUID": serverModeUUID, + }.clearNulls(); +} diff --git a/lib/src/mdl/document_request_18013_mdl.dart b/lib/src/mdl/document_request_18013_mdl.dart new file mode 100644 index 0000000000..39a656dc4d --- /dev/null +++ b/lib/src/mdl/document_request_18013_mdl.dart @@ -0,0 +1,201 @@ +part of "../../flutter_document_reader_api.dart"; + +class DocumentRequest18013MDL extends DocumentRequestMDL { + DocumentRequest18013MDL() : super("org.iso.18013.5.1.mDL"); + + MDLIntentToRetain? familyName; + MDLIntentToRetain? givenName; + MDLIntentToRetain? birthDate; + MDLIntentToRetain? issueDate; + MDLIntentToRetain? expiryDate; + MDLIntentToRetain? issuingCountry; + MDLIntentToRetain? issuingAuthority; + MDLIntentToRetain? documentNumber; + MDLIntentToRetain? portrait; + MDLIntentToRetain? drivingPrivileges; + MDLIntentToRetain? unDistinguishingSign; + MDLIntentToRetain? administrativeNumber; + MDLIntentToRetain? sex; + MDLIntentToRetain? height; + MDLIntentToRetain? weight; + MDLIntentToRetain? eyeColour; + MDLIntentToRetain? hairColour; + MDLIntentToRetain? birthPlace; + MDLIntentToRetain? residentAddress; + MDLIntentToRetain? portraitCaptureDate; + MDLIntentToRetain? ageInYears; + MDLIntentToRetain? ageBirthYear; + MDLIntentToRetain? ageOver18; + MDLIntentToRetain? issuingJurisdiction; + MDLIntentToRetain? nationality; + MDLIntentToRetain? residentCity; + MDLIntentToRetain? residentState; + MDLIntentToRetain? residentPostalCode; + MDLIntentToRetain? residentCountry; + MDLIntentToRetain? biometricTemplateFace; + MDLIntentToRetain? biometricTemplateIris; + MDLIntentToRetain? biometricTemplateFinger; + MDLIntentToRetain? biometricTemplateSignatureSign; + MDLIntentToRetain? familyNameNationalCharacter; + MDLIntentToRetain? givenNameNationalCharacter; + MDLIntentToRetain? signatureUsualMark; + + disableIntentToRetainValues() { + _setAll(MDLIntentToRetain.FALSE); + } + + enableIntentToRetainValues() { + _setAll(MDLIntentToRetain.TRUE); + } + + _setAll(MDLIntentToRetain? value) { + familyName = value; + givenName = value; + birthDate = value; + issueDate = value; + expiryDate = value; + issuingCountry = value; + issuingAuthority = value; + documentNumber = value; + portrait = value; + drivingPrivileges = value; + unDistinguishingSign = value; + administrativeNumber = value; + sex = value; + height = value; + weight = value; + eyeColour = value; + hairColour = value; + birthPlace = value; + residentAddress = value; + portraitCaptureDate = value; + ageInYears = value; + ageBirthYear = value; + ageOver18 = value; + issuingJurisdiction = value; + nationality = value; + residentCity = value; + residentState = value; + residentPostalCode = value; + residentCountry = value; + biometricTemplateFace = value; + biometricTemplateIris = value; + biometricTemplateFinger = value; + biometricTemplateSignatureSign = value; + familyNameNationalCharacter = value; + givenNameNationalCharacter = value; + signatureUsualMark = value; + } + + /// Allows you to deserialize object. + static DocumentRequest18013MDL? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocumentRequest18013MDL(); + + result._namespaces = (jsonObject["namespaces"] as List) + .map((item) => NameSpaceMDL.fromJson(item)!) + .toList(); + result.familyName = MDLIntentToRetain.getByValue(jsonObject["familyName"]); + result.givenName = MDLIntentToRetain.getByValue(jsonObject["givenName"]); + result.birthDate = MDLIntentToRetain.getByValue(jsonObject["birthDate"]); + result.issueDate = MDLIntentToRetain.getByValue(jsonObject["issueDate"]); + result.expiryDate = MDLIntentToRetain.getByValue(jsonObject["expiryDate"]); + result.issuingCountry = + MDLIntentToRetain.getByValue(jsonObject["issuingCountry"]); + result.issuingAuthority = + MDLIntentToRetain.getByValue(jsonObject["issuingAuthority"]); + result.documentNumber = + MDLIntentToRetain.getByValue(jsonObject["documentNumber"]); + result.portrait = MDLIntentToRetain.getByValue(jsonObject["portrait"]); + result.drivingPrivileges = + MDLIntentToRetain.getByValue(jsonObject["drivingPrivileges"]); + result.unDistinguishingSign = + MDLIntentToRetain.getByValue(jsonObject["unDistinguishingSign"]); + result.administrativeNumber = + MDLIntentToRetain.getByValue(jsonObject["administrativeNumber"]); + result.sex = MDLIntentToRetain.getByValue(jsonObject["sex"]); + result.height = MDLIntentToRetain.getByValue(jsonObject["height"]); + result.weight = MDLIntentToRetain.getByValue(jsonObject["weight"]); + result.eyeColour = MDLIntentToRetain.getByValue(jsonObject["eyeColour"]); + result.hairColour = MDLIntentToRetain.getByValue(jsonObject["hairColour"]); + result.birthPlace = MDLIntentToRetain.getByValue(jsonObject["birthPlace"]); + result.residentAddress = + MDLIntentToRetain.getByValue(jsonObject["residentAddress"]); + result.portraitCaptureDate = + MDLIntentToRetain.getByValue(jsonObject["portraitCaptureDate"]); + result.ageInYears = MDLIntentToRetain.getByValue(jsonObject["ageInYears"]); + result.ageBirthYear = + MDLIntentToRetain.getByValue(jsonObject["ageBirthYear"]); + result.ageOver18 = MDLIntentToRetain.getByValue(jsonObject["ageOver18"]); + result.issuingJurisdiction = + MDLIntentToRetain.getByValue(jsonObject["issuingJurisdiction"]); + result.nationality = + MDLIntentToRetain.getByValue(jsonObject["nationality"]); + result.residentCity = + MDLIntentToRetain.getByValue(jsonObject["residentCity"]); + result.residentState = + MDLIntentToRetain.getByValue(jsonObject["residentState"]); + result.residentPostalCode = + MDLIntentToRetain.getByValue(jsonObject["residentPostalCode"]); + result.residentCountry = + MDLIntentToRetain.getByValue(jsonObject["residentCountry"]); + result.biometricTemplateFace = + MDLIntentToRetain.getByValue(jsonObject["biometricTemplateFace"]); + result.biometricTemplateIris = + MDLIntentToRetain.getByValue(jsonObject["biometricTemplateIris"]); + result.biometricTemplateFinger = + MDLIntentToRetain.getByValue(jsonObject["biometricTemplateFinger"]); + result.biometricTemplateSignatureSign = MDLIntentToRetain.getByValue( + jsonObject["biometricTemplateSignatureSign"]); + result.familyNameNationalCharacter = + MDLIntentToRetain.getByValue(jsonObject["familyNameNationalCharacter"]); + result.givenNameNationalCharacter = + MDLIntentToRetain.getByValue(jsonObject["givenNameNationalCharacter"]); + result.signatureUsualMark = + MDLIntentToRetain.getByValue(jsonObject["signatureUsualMark"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "docType": _docType, + "namespaces": _namespaces.map((item) => item.toJson()).toList(), + "familyName": familyName?.value, + "givenName": givenName?.value, + "birthDate": birthDate?.value, + "issueDate": issueDate?.value, + "expiryDate": expiryDate?.value, + "issuingCountry": issuingCountry?.value, + "issuingAuthority": issuingAuthority?.value, + "documentNumber": documentNumber?.value, + "portrait": portrait?.value, + "drivingPrivileges": drivingPrivileges?.value, + "unDistinguishingSign": unDistinguishingSign?.value, + "administrativeNumber": administrativeNumber?.value, + "sex": sex?.value, + "height": height?.value, + "weight": weight?.value, + "eyeColour": eyeColour?.value, + "hairColour": hairColour?.value, + "birthPlace": birthPlace?.value, + "residentAddress": residentAddress?.value, + "portraitCaptureDate": portraitCaptureDate?.value, + "ageInYears": ageInYears?.value, + "ageBirthYear": ageBirthYear?.value, + "ageOver18": ageOver18?.value, + "issuingJurisdiction": issuingJurisdiction?.value, + "nationality": nationality?.value, + "residentCity": residentCity?.value, + "residentState": residentState?.value, + "residentPostalCode": residentPostalCode?.value, + "residentCountry": residentCountry?.value, + "biometricTemplateFace": biometricTemplateFace?.value, + "biometricTemplateIris": biometricTemplateIris?.value, + "biometricTemplateFinger": biometricTemplateFinger?.value, + "biometricTemplateSignatureSign": biometricTemplateSignatureSign?.value, + "familyNameNationalCharacter": familyNameNationalCharacter?.value, + "givenNameNationalCharacter": givenNameNationalCharacter?.value, + "signatureUsualMark": signatureUsualMark?.value, + }.clearNulls(); +} diff --git a/lib/src/mdl/document_request_mdl.dart b/lib/src/mdl/document_request_mdl.dart new file mode 100644 index 0000000000..e3e48f0e4e --- /dev/null +++ b/lib/src/mdl/document_request_mdl.dart @@ -0,0 +1,41 @@ +part of "../../flutter_document_reader_api.dart"; + +class DocumentRequestMDL { + late String _docType; + List _namespaces = []; + + DocumentRequestMDL(String docType) : _docType = docType; + + addNameSpace(NameSpaceMDL namespace) { + _namespaces.add(namespace); + } + + /// Allows you to deserialize object. + static DocumentRequestMDL? fromJson(jsonObject) { + if (jsonObject == null) return null; + var docType = jsonObject["docType"]; + if (docType == "org.iso.18013.5.1.mDL") { + return DocumentRequest18013MDL.fromJson(jsonObject); + } + var result = DocumentRequestMDL(docType); + + result._namespaces = (jsonObject["namespaces"] as List) + .map((item) => NameSpaceMDL.fromJson(item)!) + .toList(); + + return result; + } + + /// Allows you to serialize object. + Map toJson() { + if (_docType == "org.iso.18013.5.1.mDL") { + try { + return (this as DocumentRequest18013MDL).toJson(); + } catch (_) {} + } + return { + "docType": _docType, + "namespaces": _namespaces.map((item) => item.toJson()).toList(), + }.clearNulls(); + } +} diff --git a/lib/src/mdl/name_space_mdl.dart b/lib/src/mdl/name_space_mdl.dart new file mode 100644 index 0000000000..58990eeff5 --- /dev/null +++ b/lib/src/mdl/name_space_mdl.dart @@ -0,0 +1,43 @@ +part of "../../flutter_document_reader_api.dart"; + +class NameSpaceMDL { + late String _name; + Map _map = {}; + + NameSpaceMDL(this._name); + + addField(String name, MDLIntentToRetain intentToRetain) { + _map[name] = intentToRetain; + } + + /// Allows you to deserialize object. + static NameSpaceMDL? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = NameSpaceMDL(jsonObject["name"]); + + result._map = (jsonObject["map"] as Map).map( + (key, value) => MapEntry(key, MDLIntentToRetain.getByValue(value)!)); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "name": _name, + "map": _map.map((key, value) => MapEntry(key, value.value)), + }.clearNulls(); +} + +enum MDLIntentToRetain { + FALSE(0), + + TRUE(1); + + const MDLIntentToRetain(this.value); + final int value; + + static MDLIntentToRetain? getByValue(int? i) { + if (i == null) return null; + return MDLIntentToRetain.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/params/Functionality.dart b/lib/src/params/Functionality.dart new file mode 100644 index 0000000000..80b03ab7d0 --- /dev/null +++ b/lib/src/params/Functionality.dart @@ -0,0 +1,699 @@ +part of "../../flutter_document_reader_api.dart"; + +/// Params that influence the scanning process, camera view controller +/// customization and etc. +class Functionality { + /// If set to `true`, as soon as document is located during video mode, + /// picture wil be taken and processed as single frame. + /// + /// Used for devices with poor-quality video preview. + /// + /// Android only. + bool? get pictureOnBoundsReady => _pictureOnBoundsReady; + bool? _pictureOnBoundsReady; + set pictureOnBoundsReady(bool? val) { + _pictureOnBoundsReady = val; + _set({"pictureOnBoundsReady": val}); + } + + /// If it's set to `true`, the button that allows you to turn on/off + /// the torch will be displayed. + /// + /// Default: `true`. + bool? get showTorchButton => _showTorchButton; + bool? _showTorchButton; + set showTorchButton(bool? val) { + _showTorchButton = val; + _set({"showTorchButton": val}); + } + + /// If it's set to `true`, the button that allows you to close the scanner + /// will be displayed. + /// + /// Default: `true`. + bool? get showCloseButton => _showCloseButton; + bool? _showCloseButton; + set showCloseButton(bool? val) { + _showCloseButton = val; + _set({"showCloseButton": val}); + } + + /// If it's set to `true`, camera frames won't be taken for recognition + /// while a device is moving based on motion sensors. + /// + /// Default: `true`. + bool? get videoCaptureMotionControl => _videoCaptureMotionControl; + bool? _videoCaptureMotionControl; + set videoCaptureMotionControl(bool? val) { + _videoCaptureMotionControl = val; + _set({"videoCaptureMotionControl": val}); + } + + /// If it's set to `true`, the button that allows you to take a picture + /// and process it as a single frame will be displayed. + /// + /// Default: `false`. + bool? get showCaptureButton => _showCaptureButton; + bool? _showCaptureButton; + set showCaptureButton(bool? val) { + _showCaptureButton = val; + _set({"showCaptureButton": val}); + } + + /// If it's set to `true`, the button that allows you to change the camera + /// frame type will be displayed. + /// + /// Default: `false`. + @Deprecated("Not used in new UI") + bool? get showChangeFrameButton => _showChangeFrameButton; + bool? _showChangeFrameButton; + set showChangeFrameButton(bool? val) { + _showChangeFrameButton = val; + _set({"showChangeFrameButton": val}); + } + + /// If it's set to `true`, the button that allows you to skip processing + /// of the next page of a document will be displayed. + /// + /// Default: `true`. + bool? get showSkipNextPageButton => _showSkipNextPageButton; + bool? _showSkipNextPageButton; + set showSkipNextPageButton(bool? val) { + _showSkipNextPageButton = val; + _set({"showSkipNextPageButton": val}); + } + + /// If it's set to `true`, allows you to connect to the external + /// Regula Bluetooth devices like Regula 1120 and others. + bool? get useAuthenticator => _useAuthenticator; + bool? _useAuthenticator; + set useAuthenticator(bool? val) { + _useAuthenticator = val; + _set({"useAuthenticator": val}); + } + + /// If it's set to `true`, camera frames won't be taken for recognition + /// while a camera is focusing. + /// + /// Default: `true`. + bool? get skipFocusingFrames => _skipFocusingFrames; + bool? _skipFocusingFrames; + set skipFocusingFrames(bool? val) { + _skipFocusingFrames = val; + _set({"skipFocusingFrames": val}); + } + + /// If it's set to `true`, the button that allows you to change a position + /// of a capture device for the video session will be displayed. + /// + /// Default: `false`. + bool? get showCameraSwitchButton => _showCameraSwitchButton; + bool? _showCameraSwitchButton; + set showCameraSwitchButton(bool? val) { + _showCameraSwitchButton = val; + _set({"showCameraSwitchButton": val}); + } + + /// If it's set to `true`, the metadata will be displayed over the camera + /// preview during document processing, namely the perspective angle value. + /// + /// Default: `false`. + bool? get displayMetadata => _displayMetadata; + bool? _displayMetadata; + set displayMetadata(bool? val) { + _displayMetadata = val; + _set({"displayMetadata": val}); + } + + /// If it's set to `true`, allows you to adjust a zoom level using the pinch + /// gesture (its range is from 1x to 10x). + /// + /// Default: `false`. + bool? get isZoomEnabled => _isZoomEnabled; + bool? _isZoomEnabled; + set isZoomEnabled(bool? val) { + _isZoomEnabled = val; + _set({"isZoomEnabled": val}); + } + + /// Allows you to disable all validations of having a torch in case Android + /// returns that it's not available, but it can be used when checks are skipped. + /// + /// Default: `false`. + /// + /// Android only. + bool? get isCameraTorchCheckDisabled => _isCameraTorchCheckDisabled; + bool? _isCameraTorchCheckDisabled; + set isCameraTorchCheckDisabled(bool? val) { + _isCameraTorchCheckDisabled = val; + _set({"isCameraTorchCheckDisabled": val}); + } + + /// If set to `true`, video during processing of the document will be recorded. + /// This can be used later for debugging and troubleshooting. + /// + /// Default: `false`. + bool? get recordScanningProcess => _recordScanningProcess; + bool? _recordScanningProcess; + set recordScanningProcess(bool? val) { + _recordScanningProcess = val; + _set({"recordScanningProcess": val}); + } + + /// If it's set to `true`, scanner operate in manual multipage scanning mode. + /// Set this flag to true, if you wanna create for example, custom logic + /// (or UI) between scanning document pages. + /// + /// Default: `false`. + bool? get manualMultipageMode => _manualMultipageMode; + bool? _manualMultipageMode; + set manualMultipageMode(bool? val) { + _manualMultipageMode = val; + _set({"manualMultipageMode": val}); + } + + /// If it's set to `true`, once the scanning process is finished, + /// the scanner will be dismissed. + /// + /// Default: `true`. + /// + /// iOS only. + bool? get singleResult => _singleResult; + bool? _singleResult; + set singleResult(bool? val) { + _singleResult = val; + _set({"singleResult": val}); + } + + /// If set, torch (if available) will turn on immediately on camera preview start. + /// + /// Default: `false`. + bool? get torchTurnedOn => _torchTurnedOn; + bool? _torchTurnedOn; + set torchTurnedOn(bool? val) { + _torchTurnedOn = val; + _set({"torchTurnedOn": val}); + } + + /// When enabled, the SDK prevents both screen recording and screenshots. + /// + /// Default: `false`. + bool? get preventScreenRecording => _preventScreenRecording; + bool? _preventScreenRecording; + set preventScreenRecording(bool? val) { + _preventScreenRecording = val; + _set({"preventScreenRecording": val}); + } + + /// If it's set to true, system is allowed to hide the visual indicator for returning to the Home Screen in landscape mode. + /// + /// Default: `true`. + bool? get homeIndicatorAutoHide => _homeIndicatorAutoHide; + bool? _homeIndicatorAutoHide; + set homeIndicatorAutoHide(bool? val) { + _homeIndicatorAutoHide = val; + _set({"homeIndicatorAutoHide": val}); + } + + /// Android only. + bool? get hideStatusBar => _hideStatusBar; + bool? _hideStatusBar; + set hideStatusBar(bool? val) { + _hideStatusBar = val; + _set({"hideStatusBar": val}); + } + + /// Allows you to specify a time interval when the Capture button + /// has to be displayed after the document is detected. + /// Don't forget to set the [showCaptureButton] to `true`, + /// otherwise, it won't be displayed. + /// + /// Default: 5. + int? get showCaptureButtonDelayFromDetect => + _showCaptureButtonDelayFromDetect; + int? _showCaptureButtonDelayFromDetect; + set showCaptureButtonDelayFromDetect(int? val) { + _showCaptureButtonDelayFromDetect = val; + _set({"showCaptureButtonDelayFromDetect": val}); + } + + /// Allows you to specify a time interval when the Capture button + /// has to be displayed after the scanning process is started. + /// Don't forget to set the [showCaptureButton] to `true`, + /// otherwise, it won't be displayed. + /// + /// Default: 10. + int? get showCaptureButtonDelayFromStart => _showCaptureButtonDelayFromStart; + int? _showCaptureButtonDelayFromStart; + set showCaptureButtonDelayFromStart(int? val) { + _showCaptureButtonDelayFromStart = val; + _set({"showCaptureButtonDelayFromStart": val}); + } + + /// Use the parameter to set the time limit (in seconds) for the RFID chip reading, + /// beyond which it does not continue regardless of its result. + /// + /// Android only. + int? get rfidTimeout => _rfidTimeout; + int? _rfidTimeout; + set rfidTimeout(int? val) { + _rfidTimeout = val; + _set({"rfidTimeout": val}); + } + + /// Sets a limit on the number of pages to be processed. + int? get forcePagesCount => _forcePagesCount; + int? _forcePagesCount; + set forcePagesCount(int? val) { + _forcePagesCount = val; + _set({"forcePagesCount": val}); + } + + /// Allows you to specify an orientation of the camera view controller. + /// + /// Default: [DocReaderOrientation.ALL]. + DocReaderOrientation? get orientation => _orientation; + DocReaderOrientation? _orientation; + set orientation(DocReaderOrientation? val) { + _orientation = val; + _set({"orientation": val?.value}); + } + + /// Allows you to specify the video processing mode. + /// + /// Default: [CaptureMode.AUTO]. + CaptureMode? get captureMode => _captureMode; + CaptureMode? _captureMode; + set captureMode(CaptureMode? val) { + _captureMode = val; + _set({"captureMode": val?.value}); + } + + /// Allows you to specify the camera API. + /// + /// Default: [CameraMode.AUTO]. + /// + /// Android only. + CameraMode? get cameraMode => _cameraMode; + CameraMode? _cameraMode; + set cameraMode(CameraMode? val) { + _cameraMode = val; + _set({"cameraMode": val?.value}); + } + + /// Allows you to specify a position of a capture device for the video session. + /// + /// Default: [CameraPosition.UNSPECIFIED]. + /// + /// IOS only. + CameraPosition? get cameraPositionIOS => _cameraPositionIOS; + CameraPosition? _cameraPositionIOS; + set cameraPositionIOS(CameraPosition? val) { + _cameraPositionIOS = val; + _set({"cameraPositionIOS": val?.value}); + } + + /// Set this setting to override the default cropping frame provided by scenarios. + /// + /// Default: [DocReaderFrame.SCENARIO_DEFAULT]. + DocReaderFrame? get cameraFrame => _cameraFrame; + DocReaderFrame? _cameraFrame; + set cameraFrame(DocReaderFrame? val) { + _cameraFrame = val; + _set({"cameraFrame": val?.value}); + } + + /// Allows you to specify a name of a Regula device that will be used + /// with Document Reader SDK. + String? get btDeviceName => _btDeviceName; + String? _btDeviceName; + set btDeviceName(String? val) { + _btDeviceName = val; + _set({"btDeviceName": val}); + } + + /// Allows you to set the desired zoom level (its range from 1x to 10x). + /// + /// Default: 1.0. + double? get zoomFactor => _zoomFactor; + double? _zoomFactor; + set zoomFactor(double? val) { + _zoomFactor = val; + _set({"zoomFactor": val}); + } + + /// Allows you to control exposure. + /// + /// Android only. + double? get exposure => _exposure; + double? _exposure; + set exposure(double? val) { + _exposure = val; + _set({"exposure": val}); + } + + /// Android only. + double? get videoRecordingSizeDownscaleFactor => + _videoRecordingSizeDownscaleFactor; + double? _videoRecordingSizeDownscaleFactor; + set videoRecordingSizeDownscaleFactor(double? val) { + _videoRecordingSizeDownscaleFactor = val; + _set({"videoRecordingSizeDownscaleFactor": val}); + } + + double? get mdlTimeout => _mdlTimeout; + double? _mdlTimeout; + set mdlTimeout(double? val) { + _mdlTimeout = val; + _set({"mdlTimeout": val}); + } + + /// A list of devices that must not use the camera2 API. + /// + /// Android only. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get excludedCamera2Models => _excludedCamera2Models; + List? _excludedCamera2Models; + set excludedCamera2Models(List? val) { + if (val != null) val = List.unmodifiable(val); + _excludedCamera2Models = val; + _set({"excludedCamera2Models": val}); + } + + /// Allows you to specify the frame resolution. + /// + /// Android only. For iOS use [cameraResolutionIOS] + CameraSize? get cameraResolutionAndroid => _cameraResolutionAndroid; + CameraSize? _cameraResolutionAndroid; + set cameraResolutionAndroid(CameraSize? val) { + _cameraResolutionAndroid = val; + _set({"cameraSize": val?.toJson()}); + } + + /// Allows you to specify the frame resolution. + /// + /// iOS only. For Android use [cameraResolutionAndroid] + CaptureSessionPreset? get cameraResolutionIOS => _cameraResolutionIOS; + CaptureSessionPreset? _cameraResolutionIOS; + set cameraResolutionIOS(CaptureSessionPreset? val) { + _cameraResolutionIOS = val; + _set({"videoSessionPreset": val?.value}); + } + + /// Allows you to deserialize object. + static Functionality fromJson(jsonObject) { + var result = Functionality(); + result.testSetters = {}; + + result.pictureOnBoundsReady = jsonObject["pictureOnBoundsReady"]; + result.showTorchButton = jsonObject["showTorchButton"]; + result.showCloseButton = jsonObject["showCloseButton"]; + result.videoCaptureMotionControl = jsonObject["videoCaptureMotionControl"]; + result.showCaptureButton = jsonObject["showCaptureButton"]; + result.showChangeFrameButton = jsonObject["showChangeFrameButton"]; + result.showSkipNextPageButton = jsonObject["showSkipNextPageButton"]; + result.useAuthenticator = jsonObject["useAuthenticator"]; + result.skipFocusingFrames = jsonObject["skipFocusingFrames"]; + result.showCameraSwitchButton = jsonObject["showCameraSwitchButton"]; + result.displayMetadata = jsonObject["displayMetadata"]; + result.isZoomEnabled = jsonObject["isZoomEnabled"]; + result.isCameraTorchCheckDisabled = + jsonObject["isCameraTorchCheckDisabled"]; + result.recordScanningProcess = jsonObject["recordScanningProcess"]; + result.manualMultipageMode = jsonObject["manualMultipageMode"]; + result.singleResult = jsonObject["singleResult"]; + result.torchTurnedOn = jsonObject["torchTurnedOn"]; + result.preventScreenRecording = jsonObject["preventScreenRecording"]; + result.homeIndicatorAutoHide = jsonObject["homeIndicatorAutoHide"]; + result.hideStatusBar = jsonObject["hideStatusBar"]; + + result.showCaptureButtonDelayFromDetect = + jsonObject["showCaptureButtonDelayFromDetect"]; + result.showCaptureButtonDelayFromStart = + jsonObject["showCaptureButtonDelayFromStart"]; + result.rfidTimeout = jsonObject["rfidTimeout"]; + result.forcePagesCount = jsonObject["forcePagesCount"]; + result.orientation = DocReaderOrientation.getByValue( + jsonObject["orientation"], + ); + result.captureMode = CaptureMode.getByValue(jsonObject["captureMode"]); + result.cameraMode = CameraMode.getByValue(jsonObject["cameraMode"]); + result.cameraPositionIOS = CameraPosition.getByValue( + jsonObject["cameraPositionIOS"], + ); + + result.cameraFrame = DocReaderFrame.getByValue(jsonObject["cameraFrame"]); + result.btDeviceName = jsonObject["btDeviceName"]; + + result.zoomFactor = _toDouble(jsonObject["zoomFactor"]); + result.exposure = _toDouble(jsonObject["exposure"]); + result.videoRecordingSizeDownscaleFactor = + _toDouble(jsonObject["videoRecordingSizeDownscaleFactor"]); + result.mdlTimeout = _toDouble(jsonObject["mdlTimeout"]); + + result.excludedCamera2Models = _stringListFrom( + jsonObject["excludedCamera2Models"], + ); + + result.cameraResolutionAndroid = CameraSize.fromJson( + jsonObject["cameraSize"], + ); + result.cameraResolutionIOS = CaptureSessionPreset.getByValue( + jsonObject["videoSessionPreset"], + ); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "pictureOnBoundsReady": pictureOnBoundsReady, + "showTorchButton": showTorchButton, + "showCloseButton": showCloseButton, + "videoCaptureMotionControl": videoCaptureMotionControl, + "showCaptureButton": showCaptureButton, + "showChangeFrameButton": showChangeFrameButton, + "showSkipNextPageButton": showSkipNextPageButton, + "useAuthenticator": useAuthenticator, + "skipFocusingFrames": skipFocusingFrames, + "showCameraSwitchButton": showCameraSwitchButton, + "displayMetadata": displayMetadata, + "isZoomEnabled": isZoomEnabled, + "isCameraTorchCheckDisabled": isCameraTorchCheckDisabled, + "recordScanningProcess": recordScanningProcess, + "manualMultipageMode": manualMultipageMode, + "singleResult": singleResult, + "torchTurnedOn": torchTurnedOn, + "preventScreenRecording": preventScreenRecording, + "homeIndicatorAutoHide": homeIndicatorAutoHide, + "hideStatusBar": hideStatusBar, + "showCaptureButtonDelayFromDetect": showCaptureButtonDelayFromDetect, + "showCaptureButtonDelayFromStart": showCaptureButtonDelayFromStart, + "rfidTimeout": rfidTimeout, + "forcePagesCount": forcePagesCount, + "orientation": orientation?.value, + "captureMode": captureMode?.value, + "cameraMode": cameraMode?.value, + "cameraPositionIOS": cameraPositionIOS?.value, + "cameraFrame": cameraFrame?.value, + "btDeviceName": btDeviceName, + "zoomFactor": zoomFactor, + "exposure": exposure, + "videoRecordingSizeDownscaleFactor": videoRecordingSizeDownscaleFactor, + "mdlTimeout": mdlTimeout, + "excludedCamera2Models": excludedCamera2Models, + "cameraSize": cameraResolutionAndroid?.toJson(), + "videoSessionPreset": cameraResolutionIOS?.value, + }.clearNulls(); + + void _set(Map json) { + if (identical(this, DocumentReader.instance.functionality)) { + _bridge.invokeMethod("setFunctionality", [json]); + } + testSetters.addAll(json); + } + + void _apply() => _set(toJson()); + + @visibleForTesting + Map testSetters = {}; +} + +enum CameraPosition { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + UNSPECIFIED(0), + + BACK(1), + + FRONT(2); + + const CameraPosition(this.value); + final int value; + + static CameraPosition? getByValue(int? i) { + if (i == null) return null; + try { + return CameraPosition.values.firstWhere((x) => x.value == i); + } catch (_) { + return CameraPosition.UNKNOWN; + } + } +} + +enum CaptureMode { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// A flow of frames is taken for recognition right after a scenario is started. + AUTO(0), + + /// A flow of frames is taken for recognition right after the Capture button is pushed. + CAPTURE_VIDEO(1), + + /// A single frame is taken for recognition right after the Capture button is pushed. + CAPTURE_FRAME(2); + + const CaptureMode(this.value); + final int value; + + static CaptureMode? getByValue(int? i) { + if (i == null) return null; + try { + return CaptureMode.values.firstWhere((x) => x.value == i); + } catch (_) { + return CaptureMode.UNKNOWN; + } + } +} + +enum CameraMode { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + AUTO(0), + + CAMERA1(1), + + CAMERA2(2); + + const CameraMode(this.value); + final int value; + + static CameraMode? getByValue(int? i) { + if (i == null) return null; + try { + return CameraMode.values.firstWhere((x) => x.value == i); + } catch (_) { + return CameraMode.UNKNOWN; + } + } +} + +enum CaptureSessionPreset { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// An AVCaptureSession preset suitable for low quality output. + LOW(0), + + /// An AVCaptureSession preset suitable for medium quality output. + MEDIUM(1), + + /// An AVCaptureSession preset suitable for high quality video and audio output. + HIGH(2), + // An AVCaptureSession preset suitable for high resolution photo quality output. + PHOTO(3), + + /// An AVCaptureSession preset indicating that the formats of the session's + /// inputs are being given priority. + INPUT_PRIORITY(4), + + /// An AVCaptureSession preset suitable for 1280x720 video output. + PRESET_1280x720(6), + + /// An AVCaptureSession preset suitable for 1920x1080 video output. + PRESET_1920x1080(7), + + /// An AVCaptureSession preset suitable for 3840x2160 (UHD 4K) video output. + PRESET_3840x2160(8), + + /// An AVCaptureSession preset producing 960x540 Apple iFrame video and audio content. + FRAME_960x540(9), + + /// An AVCaptureSession preset producing 1280x720 Apple iFrame video and audio content. + FRAME_1280x720(10), + + /// An AVCaptureSession preset suitable for 640x480 video output. + PRESET_640x480(12), + + /// An AVCaptureSession preset suitable for 352x288 video output. + PRESET_352x288(13); + + const CaptureSessionPreset(this.value); + final int value; + + static CaptureSessionPreset? getByValue(int? i) { + if (i == null) return null; + try { + return CaptureSessionPreset.values.firstWhere((x) => x.value == i); + } catch (_) { + return CaptureSessionPreset.UNKNOWN; + } + } +} + +enum DocReaderFrame { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(""), + + /// Size of the frame depends on the scenario, that means default values are used. + SCENARIO_DEFAULT("id1"), + + /// Full frame. + MAX("max"), + + /// No frame. + NONE("none"), + + /// Size of the frame corresponds to the ID-3 format in the portrait mode + /// and to the ID-1 in the landscape mode. + DOCUMENT("document"); + + const DocReaderFrame(this.value); + final String value; + + static DocReaderFrame? getByValue(String? i) { + if (i == null) return null; + try { + return DocReaderFrame.values.firstWhere((x) => x.value == i); + } catch (_) { + return DocReaderFrame.UNKNOWN; + } + } +} + +class CameraSize { + int get width => _width; + int _width; + + int get height => _height; + int _height; + + CameraSize(int width, int height) + : _width = width, + _height = height; + + /// Allows you to deserialize object. + static CameraSize? fromJson(jsonObject) { + if (jsonObject == null) return null; + return CameraSize(jsonObject["width"], jsonObject["height"]); + } + + /// Allows you to serialize object. + Map toJson() { + return {"width": width, "height": height}.clearNulls(); + } +} diff --git a/lib/src/params/customization/Customization.dart b/lib/src/params/customization/Customization.dart new file mode 100644 index 0000000000..4bc0cfa155 --- /dev/null +++ b/lib/src/params/customization/Customization.dart @@ -0,0 +1,1214 @@ +part of "../../../flutter_document_reader_api.dart"; + +/// Params that relate to the camera view controller customization and etc. +class Customization { + /// If it's set to `true`, status messages during the document processing + /// will be shown. + /// + /// Default: `true`. + bool? get showStatusMessages => _showStatusMessages; + bool? _showStatusMessages; + set showStatusMessages(bool? val) { + _showStatusMessages = val; + _set({"showStatusMessages": val}); + } + + /// If it's set to `true`, result status messages during the document processing + /// will be shown. + /// + /// Default: `true`. + @Deprecated("Not used in new UI") + bool? get showResultStatusMessages => _showResultStatusMessages; + bool? _showResultStatusMessages; + set showResultStatusMessages(bool? val) { + _showResultStatusMessages = val; + _set({"showResultStatusMessages": val}); + } + + /// If it's set to `true`, the animation showing how to position a document + /// will be displayed. + /// + /// Default: `false`. + bool? get showHelpAnimation => _showHelpAnimation; + bool? _showHelpAnimation; + set showHelpAnimation(bool? val) { + _showHelpAnimation = val; + _set({"showHelpAnimation": val}); + } + + /// If it's set to `true`, the animation asking for processing + /// the next page will be displayed. + /// + /// Default: `true`. + bool? get showNextPageAnimation => _showNextPageAnimation; + bool? _showNextPageAnimation; + set showNextPageAnimation(bool? val) { + _showNextPageAnimation = val; + _set({"showNextPageAnimation": val}); + } + + /// If it's set to `true`, the background mask next to the camera frame + /// will be displayed. + /// + /// Default: `true`. + bool? get showBackgroundMask => _showBackgroundMask; + bool? _showBackgroundMask; + set showBackgroundMask(bool? val) { + _showBackgroundMask = val; + _set({"showBackgroundMask": val}); + } + + /// Allows you to set thickness of the camera frame borders. + /// + /// Default: 3. + int? get cameraFrameBorderWidth => _cameraFrameBorderWidth; + int? _cameraFrameBorderWidth; + set cameraFrameBorderWidth(int? val) { + _cameraFrameBorderWidth = val; + _set({"cameraFrameBorderWidth": val}); + } + + /// Allows you to set length of the lines of the camera frame. + /// + /// It's applied once you change the [cameraFrameShapeType] property to + /// [FrameShapeType.CORNER]. + /// + /// Default: 25. + int? get cameraFrameLineLength => _cameraFrameLineLength; + int? _cameraFrameLineLength; + set cameraFrameLineLength(int? val) { + _cameraFrameLineLength = val; + _set({"cameraFrameLineLength": val}); + } + + /// Allows you to set an offset for the camera frame (portrait orientation). + /// + /// Default: 23. + int? get cameraFrameOffsetWidth => _cameraFrameOffsetWidth; + int? _cameraFrameOffsetWidth; + set cameraFrameOffsetWidth(int? val) { + _cameraFrameOffsetWidth = val; + _set({"cameraFrameOffsetWidth": val}); + } + + /// Allows you to set a shape type for the camera frame. + /// + /// Default: [FrameShapeType.LINE]. + FrameShapeType? get cameraFrameShapeType => _cameraFrameShapeType; + FrameShapeType? _cameraFrameShapeType; + set cameraFrameShapeType(FrameShapeType? val) { + _cameraFrameShapeType = val; + _set({"cameraFrameShapeType": val?.value}); + } + + /// Allows you to set any string to the status. + String? get status => _status; + String? _status; + set status(String? val) { + _status = val; + _set({"status": val}); + } + + /// Allows you to set any string to the result status. + @Deprecated("Not used in new UI") + String? get resultStatus => _resultStatus; + String? _resultStatus; + set resultStatus(String? val) { + _resultStatus = val; + _set({"resultStatus": val}); + } + + String? get multipageButtonText => _multipageButtonText; + String? _multipageButtonText; + set multipageButtonText(String? val) { + _multipageButtonText = val; + _set({"multipageButtonText": val}); + } + + /// Allows you to set a color for the camera frame when a document is out + /// of the camera frame or is not detected. + /// + /// Default: Colors.white. + Color? get cameraFrameDefaultColor => _cameraFrameDefaultColor; + Color? _cameraFrameDefaultColor; + set cameraFrameDefaultColor(Color? val) { + _cameraFrameDefaultColor = val; + _set({"cameraFrameDefaultColor": _intFromColor(val)}); + } + + /// Allows you to set a color for the camera frame when a document is detected. + /// + /// Default: Colors.green. + Color? get cameraFrameActiveColor => _cameraFrameActiveColor; + Color? _cameraFrameActiveColor; + set cameraFrameActiveColor(Color? val) { + _cameraFrameActiveColor = val; + _set({"cameraFrameActiveColor": _intFromColor(val)}); + } + + /// Allows you to set a color for the status messages. + /// + /// Default: Colors.white. + Color? get statusTextColor => _statusTextColor; + Color? _statusTextColor; + set statusTextColor(Color? val) { + _statusTextColor = val; + _set({"statusTextColor": _intFromColor(val)}); + } + + /// Allows you to set a color for the result status messages. + /// + /// Default: Colors.white. + @Deprecated("Not used in new UI") + Color? get resultStatusTextColor => _resultStatusTextColor; + Color? _resultStatusTextColor; + set resultStatusTextColor(Color? val) { + _resultStatusTextColor = val; + _set({"resultStatusTextColor": _intFromColor(val)}); + } + + /// Allows you to set a color of the background for the result status messages. + @Deprecated("Not used in new UI") + Color? get resultStatusBackgroundColor => _resultStatusBackgroundColor; + Color? _resultStatusBackgroundColor; + set resultStatusBackgroundColor(Color? val) { + _resultStatusBackgroundColor = val; + _set({"resultStatusBackgroundColor": _intFromColor(val)}); + } + + /// Allows you to set a color for the "Skip next page" button. + Color? get multipageButtonBackgroundColor => _multipageButtonBackgroundColor; + Color? _multipageButtonBackgroundColor; + set multipageButtonBackgroundColor(Color? val) { + _multipageButtonBackgroundColor = val; + _set({"multipageButtonBackgroundColor": _intFromColor(val)}); + } + + /// Allows you to set a color for all visual elements. + Color? get tintColor => _tintColor; + Color? _tintColor; + set tintColor(Color? val) { + _tintColor = val; + _set({"tintColor": _intFromColor(val)}); + } + + /// Allows you to set a color for the activity indicator. + Color? get activityIndicatorColor => _activityIndicatorColor; + Color? _activityIndicatorColor; + set activityIndicatorColor(Color? val) { + _activityIndicatorColor = val; + _set({"activityIndicatorColor": _intFromColor(val)}); + } + + /// Allows you to set a background color for the status messages. + /// + /// Default: Colors.transparent. + Color? get statusBackgroundColor => _statusBackgroundColor; + Color? _statusBackgroundColor; + set statusBackgroundColor(Color? val) { + _statusBackgroundColor = val; + _set({"statusBackgroundColor": _intFromColor(val)}); + } + + /// Allows you to set a background color for the camera preview + /// (top and bottom frames). + /// + /// Default: Colors.black. + Color? get cameraPreviewBackgroundColor => _cameraPreviewBackgroundColor; + Color? _cameraPreviewBackgroundColor; + set cameraPreviewBackgroundColor(Color? val) { + _cameraPreviewBackgroundColor = val; + _set({"cameraPreviewBackgroundColor": _intFromColor(val)}); + } + + /// Allows you to set color for background mask area. + Color? get backgroundMaskColor => _backgroundMaskColor; + Color? _backgroundMaskColor; + set backgroundMaskColor(Color? val) { + _backgroundMaskColor = val; + _set({"backgroundMaskColor": _intFromColor(val)}); + } + + Color? get multipageButtonTextColor => _multipageButtonTextColor; + Color? _multipageButtonTextColor; + set multipageButtonTextColor(Color? val) { + _multipageButtonTextColor = val; + _set({"multipageButtonTextColor": _intFromColor(val)}); + } + + /// Allows you to change the location of the status. + /// + /// For example, if you set the multiplier to 0.5 and the number of pixels + /// by vertical is equal to 800, your message will be centralized and located + /// at 200 px from the top, i.e. (800 / 2) * 0.5 = 200 px. If the multiplier + /// is equal to 1, the message will be centered. If the multiplier is equal + /// to zero, the default location will be used. + /// + /// Default: 0. + double? get statusPositionMultiplier => _statusPositionMultiplier; + double? _statusPositionMultiplier; + set statusPositionMultiplier(double? val) { + _statusPositionMultiplier = val; + _set({"statusPositionMultiplier": val}); + } + + /// Allows you to change the location of the result status. + /// + /// For example, if you set the multiplier to 0.5 and the number of pixels + /// by vertical is equal to 800, your message will be centralized and located + /// at 200 px from the top, i.e. (800 / 2) * 0.5 = 200 px. If the multiplier + /// is equal to 1, the message will be centered. If the multiplier is equal + /// to zero, the default location will be used. + /// + /// Default: 0. + @Deprecated("Not used in new UI") + double? get resultStatusPositionMultiplier => _resultStatusPositionMultiplier; + double? _resultStatusPositionMultiplier; + set resultStatusPositionMultiplier(double? val) { + _resultStatusPositionMultiplier = val; + _set({"resultStatusPositionMultiplier": val}); + } + + /// Allows you to set a size for the toolbar + /// (it's where all buttons are located). + double? get toolbarSize => _toolbarSize; + double? _toolbarSize; + set toolbarSize(double? val) { + _toolbarSize = val; + _set({"toolbarSize": val}); + } + + /// Allows you to set intensity of the background mask. + /// + /// Default: 1.0. + double? get backgroundMaskAlpha => _backgroundMaskAlpha; + double? _backgroundMaskAlpha; + set backgroundMaskAlpha(double? val) { + _backgroundMaskAlpha = val; + _set({"backgroundMaskAlpha": val}); + } + + /// Allows you to change the location of the custom status. + /// + /// For example, if you set the multiplier to 0.5 and the number of pixels + /// by vertical is equal to 800, your message will be centralized and located + /// at 200 px from the top, i.e. (800 / 2) * 0.5 = 200 px. If the multiplier + /// is equal to 1, the message will be centered. If the multiplier is equal + /// to zero, the default location will be used. + /// + /// Default: 1. + double? get customStatusPositionMultiplier => _customStatusPositionMultiplier; + double? _customStatusPositionMultiplier; + set customStatusPositionMultiplier(double? val) { + _customStatusPositionMultiplier = val; + _set({"customStatusPositionMultiplier": val}); + } + + /// Allows you to change the location of the camera frame vertically. Default: 1. + double? get cameraFrameVerticalPositionMultiplier => + _cameraFrameVerticalPositionMultiplier; + double? _cameraFrameVerticalPositionMultiplier; + set cameraFrameVerticalPositionMultiplier(double? val) { + _cameraFrameVerticalPositionMultiplier = val; + _set({"cameraFrameVerticalPositionMultiplier": val}); + } + + /// Allows you to set an aspect ratio of the camera frame (landscape orientation). + /// Default: 0. + double? get cameraFrameLandscapeAspectRatio => + _cameraFrameLandscapeAspectRatio; + double? _cameraFrameLandscapeAspectRatio; + set cameraFrameLandscapeAspectRatio(double? val) { + _cameraFrameLandscapeAspectRatio = val; + _set({"cameraFrameLandscapeAspectRatio": val}); + } + + /// Allows you to set an aspect ratio of the camera frame (portrait orientation). + /// + /// Default: 0. + double? get cameraFramePortraitAspectRatio => _cameraFramePortraitAspectRatio; + double? _cameraFramePortraitAspectRatio; + set cameraFramePortraitAspectRatio(double? val) { + _cameraFramePortraitAspectRatio = val; + _set({"cameraFramePortraitAspectRatio": val}); + } + + /// Allows you to set a corner radius of the camera frame. + /// + /// Default: 10. + double? get cameraFrameCornerRadius => _cameraFrameCornerRadius; + double? _cameraFrameCornerRadius; + set cameraFrameCornerRadius(double? val) { + _cameraFrameCornerRadius = val; + _set({"cameraFrameCornerRadius": val}); + } + + /// Allows you to change the location of the liveness animation. + /// + /// For example, if you set the multiplier to 0.5 and the number of pixels + /// by vertical is equal to 800, the animation will be centralized and located + /// at 200 px from the top, i.e. (800 / 2) * 0.5 = 200 px. If the multiplier + /// is set to 1, the animation will be centered. If the multiplier is + /// set to 0, the default value will be used. + /// + /// Defaults to 1. + double? get livenessAnimationPositionMultiplier => + _livenessAnimationPositionMultiplier; + double? _livenessAnimationPositionMultiplier; + set livenessAnimationPositionMultiplier(double? val) { + _livenessAnimationPositionMultiplier = val; + _set({"livenessAnimationPositionMultiplier": val}); + } + + /// Animation delay before flip. + /// + /// Default: 0. + @Deprecated("Use `timings.nextPageIdCardStartDelay` instead.") + double? get nextPageAnimationStartDelay => _nextPageAnimationStartDelay; + double? _nextPageAnimationStartDelay; + set nextPageAnimationStartDelay(double? val) { + _nextPageAnimationStartDelay = val; + _set({"nextPageAnimationStartDelay": val}); + } + + /// Animation delay after flip. + /// + /// Default: 0. + @Deprecated("Use `timings.nextPageIdCardEndDelay` instead.") + double? get nextPageAnimationEndDelay => _nextPageAnimationEndDelay; + double? _nextPageAnimationEndDelay; + set nextPageAnimationEndDelay(double? val) { + _nextPageAnimationEndDelay = val; + _set({"nextPageAnimationEndDelay": val}); + } + + /// Allows you to set an offset for the activity indicator (portrait orientation). + /// If not set, activity indicator always centered in the camera border. + double? get activityIndicatorPortraitPositionMultiplier => + _activityIndicatorPortraitPositionMultiplier; + double? _activityIndicatorPortraitPositionMultiplier; + set activityIndicatorPortraitPositionMultiplier(double? val) { + _activityIndicatorPortraitPositionMultiplier = val; + _set({"activityIndicatorPortraitPositionMultiplier": val}); + } + + /// Allows you to set an offset for the activity indicator (landscape orientation). + /// If not set, activity indicator always centered in the camera border. + double? get activityIndicatorLandscapePositionMultiplier => + _activityIndicatorLandscapePositionMultiplier; + double? _activityIndicatorLandscapePositionMultiplier; + set activityIndicatorLandscapePositionMultiplier(double? val) { + _activityIndicatorLandscapePositionMultiplier = val; + _set({"activityIndicatorLandscapePositionMultiplier": val}); + } + + /// Allows you to change the vertical offset of the camera preview layer. + /// If you need to raise the layer 50% of its height up, then you specify 0.5. + /// If you need to lower the layer 75% of its height, then enter 1.75. + /// Valid values: from 0 (the layer will be raised completely up) to 2 (the layer will be completely lowered down). + double? get cameraPreviewVerticalPositionMultiplier => + _cameraPreviewVerticalPositionMultiplier; + double? _cameraPreviewVerticalPositionMultiplier; + set cameraPreviewVerticalPositionMultiplier(double? val) { + _cameraPreviewVerticalPositionMultiplier = val; + _set({"cameraPreviewVerticalPositionMultiplier": val}); + } + + /// Allows you to change the location of the multipage button. + double? get multipageButtonPositionMultiplier => + _multipageButtonPositionMultiplier; + double? _multipageButtonPositionMultiplier; + set multipageButtonPositionMultiplier(double? val) { + _multipageButtonPositionMultiplier = val; + _set({"multipageButtonPositionMultiplier": val}); + } + + /// Allows you to set any image for the multipage animation (front side). + ByteData? get multipageAnimationFrontImage => _multipageAnimationFrontImage; + ByteData? _multipageAnimationFrontImage; + set multipageAnimationFrontImage(ByteData? val) { + _multipageAnimationFrontImage = val; + _set({"multipageAnimationFrontImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the multipage animation (back side). + ByteData? get multipageAnimationBackImage => _multipageAnimationBackImage; + ByteData? _multipageAnimationBackImage; + set multipageAnimationBackImage(ByteData? val) { + _multipageAnimationBackImage = val; + _set({"multipageAnimationBackImage": _dataToBase64(val)}); + } + + /// Allows you to set any image within the camera frame. + @Deprecated("Use `images.borderBackground` instead.") + ByteData? get borderBackgroundImage => _borderBackgroundImage; + ByteData? _borderBackgroundImage; + set borderBackgroundImage(ByteData? val) { + _borderBackgroundImage = val; + _set({"borderBackgroundImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the help animation. + ByteData? get helpAnimationImage => _helpAnimationImage; + ByteData? _helpAnimationImage; + set helpAnimationImage(ByteData? val) { + _helpAnimationImage = val; + _set({"helpAnimationImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the close button. + @Deprecated("Use `images.closeButton` instead.") + ByteData? get closeButtonImage => _closeButtonImage; + ByteData? _closeButtonImage; + set closeButtonImage(ByteData? val) { + _closeButtonImage = val; + _set({"closeButtonImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the capture button. + @Deprecated("Use `images.captureButton` instead.") + ByteData? get captureButtonImage => _captureButtonImage; + ByteData? _captureButtonImage; + set captureButtonImage(ByteData? val) { + _captureButtonImage = val; + _set({"captureButtonImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the button that allows + /// changing positions of the capture device. + @Deprecated("Use `images.switchButton` instead.") + ByteData? get cameraSwitchButtonImage => _cameraSwitchButtonImage; + ByteData? _cameraSwitchButtonImage; + set cameraSwitchButtonImage(ByteData? val) { + _cameraSwitchButtonImage = val; + _set({"cameraSwitchButtonImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the torch button when its state is ON. + @Deprecated("Use `images.torchButtonOn` instead.") + ByteData? get torchButtonOnImage => _torchButtonOnImage; + ByteData? _torchButtonOnImage; + set torchButtonOnImage(ByteData? val) { + _torchButtonOnImage = val; + _set({"torchButtonOnImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the torch button when its state is OFF. + @Deprecated("Use `images.torchButtonOff` instead.") + ByteData? get torchButtonOffImage => _torchButtonOffImage; + ByteData? _torchButtonOffImage; + set torchButtonOffImage(ByteData? val) { + _torchButtonOffImage = val; + _set({"torchButtonOffImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the button that allows changing + /// shapes of the camera (expanded state). + @Deprecated("Not used in new UI") + ByteData? get changeFrameButtonExpandImage => _changeFrameButtonExpandImage; + ByteData? _changeFrameButtonExpandImage; + set changeFrameButtonExpandImage(ByteData? val) { + _changeFrameButtonExpandImage = val; + _set({"changeFrameButtonExpandImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the button that allows changing + /// shapes of the camera (collapsed state). + @Deprecated("Not used in new UI") + ByteData? get changeFrameButtonCollapseImage => + _changeFrameButtonCollapseImage; + ByteData? _changeFrameButtonCollapseImage; + set changeFrameButtonCollapseImage(ByteData? val) { + _changeFrameButtonCollapseImage = val; + _set({"changeFrameButtonCollapseImage": _dataToBase64(val)}); + } + + /// Allows you to set any image for the liveness animation. + /// + /// When set to `null` the default image will be used. + /// This property can be set during the scanning process to tailor + /// the user experiese for different types of documents. + @Deprecated("Use `images.livenessAnimation` instead.") + ByteData? get livenessAnimationImage => _livenessAnimationImage; + ByteData? _livenessAnimationImage; + set livenessAnimationImage(ByteData? val) { + _livenessAnimationImage = val; + _set({"livenessAnimationImage": _dataToBase64(val)}); + } + + /// Allows you to set any UIImage for the "Skip next page" button. + @Deprecated("Use `images.multipageButton` instead.") + ByteData? get multipageButtonImage => _multipageButtonImage; + ByteData? _multipageButtonImage; + set multipageButtonImage(ByteData? val) { + _multipageButtonImage = val; + _set({"multipageButtonImage": _dataToBase64(val)}); + } + + /// Allows you to set a font for the status messages. + Font? get statusTextFont => _statusTextFont; + Font? _statusTextFont; + set statusTextFont(Font? val) { + _statusTextFont = val; + _set({"statusTextFont": val?.toJson()}); + } + + /// Allows you to set a font for the result status messages. + @Deprecated("Not used in new UI") + Font? get resultStatusTextFont => _resultStatusTextFont; + Font? _resultStatusTextFont; + set resultStatusTextFont(Font? val) { + _resultStatusTextFont = val; + _set({"resultStatusTextFont": val?.toJson()}); + } + + Font? get multipageButtonTextFont => _multipageButtonTextFont; + Font? _multipageButtonTextFont; + set multipageButtonTextFont(Font? val) { + _multipageButtonTextFont = val; + _set({"multipageButtonTextFont": val?.toJson()}); + } + + /// Allows you to create a custom status. + String? get customLabelStatus => _customLabelStatus; + String? _customLabelStatus; + set customLabelStatus(String? val) { + _customLabelStatus = val; + _set({"customLabelStatus": val}); + } + + /// Allows you to customize the beginning and ending of stroked lines + /// of the camera frame. + /// + /// Default: [Cap.BUTT]. + Cap? get cameraFrameLineCap => _cameraFrameLineCap; + Cap? _cameraFrameLineCap; + set cameraFrameLineCap(Cap? val) { + _cameraFrameLineCap = val; + _set({"cameraFrameLineCap": val?.value}); + } + + /// JSON structure defining labels and graphic elements + /// to be added to the Camera UI. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + Map? get uiCustomizationLayer => _uiCustomizationLayer; + Map? _uiCustomizationLayer; + set uiCustomizationLayer(Map? val) { + if (val != null) val = Map.unmodifiable(val); + _uiCustomizationLayer = val; + _set({"uiCustomizationLayer": val}); + } + + /// Allows you to specify how a view of the help animation adjusts + /// its content when its size changes. + /// + /// Default: [ViewContentMode.SCALE_ASPECT_FIT]. + /// + /// IOS only. For Android use [helpAnimationImageTransformsAndroid]. + @Deprecated("Use `images.helpAnimation` instead.") + ViewContentMode? get helpAnimationImageTransformsIOS => + _helpAnimationImageTransformsIOS; + ViewContentMode? _helpAnimationImageTransformsIOS; + set helpAnimationImageTransformsIOS(ViewContentMode? val) { + _helpAnimationImageTransformsIOS = val; + _set({"helpAnimationImageContentMode": val?.value}); + } + + /// Allows you to specify how a view of the multipage animation (front side) + /// adjusts its content when its size changes. + /// + /// Default: [ViewContentMode.SCALE_TO_FILL]. + /// + /// IOS only. For Android use [multipageAnimationFrontImageTransformsAndroid]. + @Deprecated("Use `contentModes.nextPageIdCardFront` instead.") + ViewContentMode? get multipageAnimationFrontImageTransformsIOS => + _multipageAnimationFrontImageTransformsIOS; + ViewContentMode? _multipageAnimationFrontImageTransformsIOS; + set multipageAnimationFrontImageTransformsIOS(ViewContentMode? val) { + _multipageAnimationFrontImageTransformsIOS = val; + _set({"multipageAnimationFrontImageContentMode": val?.value}); + } + + /// Allows you to specify how a view of the multipage animation (back side) + /// adjusts its content when its size changes. + /// + /// Default: [ViewContentMode.SCALE_TO_FILL]. + /// + /// IOS only. For Android use [multipageAnimationBackImageTransformsAndroid]. + @Deprecated("Use `contentModes.nextPageIdCardBack` instead.") + ViewContentMode? get multipageAnimationBackImageTransformsIOS => + _multipageAnimationBackImageTransformsIOS; + ViewContentMode? _multipageAnimationBackImageTransformsIOS; + set multipageAnimationBackImageTransformsIOS(ViewContentMode? val) { + _multipageAnimationBackImageTransformsIOS = val; + _set({"multipageAnimationBackImageContentMode": val?.value}); + } + + /// Allows you to specify how a view of the liveness animation + /// adjusts its content when its size changes. + /// + /// Default: [ViewContentMode.SCALE_ASPECT_FIT]. + /// + /// IOS only. For Android use [livenessAnimationImageTransformsAndroid]. + ViewContentMode? get livenessAnimationImageTransformsIOS => + _livenessAnimationImageTransformsIOS; + ViewContentMode? _livenessAnimationImageTransformsIOS; + set livenessAnimationImageTransformsIOS(ViewContentMode? val) { + _livenessAnimationImageTransformsIOS = val; + _set({"livenessAnimationImageContentMode": val?.value}); + } + + /// Allows you to specify how a view within the camera frame adjusts + /// its content when its size changes. + /// + /// Default: [ViewContentMode.SCALE_ASPECT_FIT]. + /// + /// IOS only. For Android use [borderBackgroundImageTransformsAndroid]. + ViewContentMode? get borderBackgroundImageTransformsIOS => + _borderBackgroundImageTransformsIOS; + ViewContentMode? _borderBackgroundImageTransformsIOS; + set borderBackgroundImageTransformsIOS(ViewContentMode? val) { + _borderBackgroundImageTransformsIOS = val; + _set({"borderBackgroundImageContentMode": val?.value}); + } + + /// Matrix used to scale help animation. + /// + /// Android class `android.graphics.Matrix`. + /// Passed as `Matrix.setValues()` + /// + /// Android only. For iOS use [helpAnimationImageTransformsIOS]. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get helpAnimationImageTransformsAndroid => + _helpAnimationImageTransformsAndroid; + List? _helpAnimationImageTransformsAndroid; + set helpAnimationImageTransformsAndroid(List? val) { + if (val != null) val = List.unmodifiable(val); + _helpAnimationImageTransformsAndroid = val; + _set({"helpAnimationImageMatrix": val}); + } + + /// Matrix used to scale multipage animation (front side). + /// + /// Android class `android.graphics.Matrix`. + /// Passed as `Matrix.setValues()` + /// + /// Android only. For iOS use [multipageAnimationFrontImageTransformsIOS]. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + @Deprecated("Use `matrices.nextPageIdCardFront` instead.") + List? get multipageAnimationFrontImageTransformsAndroid => + _multipageAnimationFrontImageTransformsAndroid; + List? _multipageAnimationFrontImageTransformsAndroid; + set multipageAnimationFrontImageTransformsAndroid(List? val) { + if (val != null) val = List.unmodifiable(val); + _multipageAnimationFrontImageTransformsAndroid = val; + _set({"multipageAnimationFrontImageMatrix": val}); + } + + /// Matrix used to scale multipage animation (back side). + /// + /// Android class `android.graphics.Matrix`. + /// Passed as `Matrix.setValues()` + /// + /// Android only. For iOS use [multipageAnimationBackImageTransformsIOS]. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + @Deprecated("Use `matrices.nextPageIdCardBack` instead.") + List? get multipageAnimationBackImageTransformsAndroid => + _multipageAnimationBackImageTransformsAndroid; + List? _multipageAnimationBackImageTransformsAndroid; + set multipageAnimationBackImageTransformsAndroid(List? val) { + if (val != null) val = List.unmodifiable(val); + _multipageAnimationBackImageTransformsAndroid = val; + _set({"multipageAnimationBackImageMatrix": val}); + } + + /// Matrix used to scale liveness animation. + /// + /// Android class `android.graphics.Matrix`. + /// Passed as `Matrix.setValues()` + /// + /// Android only. For iOS use [livenessAnimationImageTransformsIOS]. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get livenessAnimationImageTransformsAndroid => + _livenessAnimationImageTransformsAndroid; + List? _livenessAnimationImageTransformsAndroid; + set livenessAnimationImageTransformsAndroid(List? val) { + if (val != null) val = List.unmodifiable(val); + _livenessAnimationImageTransformsAndroid = val; + _set({"livenessAnimationImageMatrix": val}); + } + + /// Matrix used to scale the view within the camera frame. + /// + /// Android class `android.graphics.Matrix`. + /// Passed as `Matrix.setValues()` + /// + /// Android only. For iOS use [borderBackgroundImageTransformsIOS]. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get borderBackgroundImageTransformsAndroid => + _borderBackgroundImageTransformsAndroid; + List? _borderBackgroundImageTransformsAndroid; + set borderBackgroundImageTransformsAndroid(List? val) { + if (val != null) val = List.unmodifiable(val); + _borderBackgroundImageTransformsAndroid = val; + _set({"borderBackgroundImageMatrix": val}); + } + + CustomizationColors get colors => _colors; + CustomizationColors _colors = CustomizationColors(); + set colors(CustomizationColors val) { + (_colors = val)._apply(this); + } + + CustomizationFonts get fonts => _fonts; + CustomizationFonts _fonts = CustomizationFonts(); + set fonts(CustomizationFonts val) { + (_fonts = val)._apply(this); + } + + CustomizationImages get images => _images; + CustomizationImages _images = CustomizationImages(); + set images(CustomizationImages val) { + (_images = val)._apply(this); + } + + CustomizationTimings get timings => _timings; + CustomizationTimings _timings = CustomizationTimings(); + set timings(CustomizationTimings val) { + (_timings = val)._apply(this); + } + + CustomizationContentModes get contentModes => _contentModes; + CustomizationContentModes _contentModes = CustomizationContentModes(); + set contentModes(CustomizationContentModes val) { + (_contentModes = val)._apply(this); + } + + CustomizationMatrices get matrices => _matrices; + CustomizationMatrices _matrices = CustomizationMatrices(); + set matrices(CustomizationMatrices val) { + (_matrices = val)._apply(this); + } + + /// Allows you to deserialize object. + static Customization fromJson(jsonObject) { + var result = Customization(); + result.testSetters = {}; + + result.showStatusMessages = jsonObject["showStatusMessages"]; + result.showResultStatusMessages = jsonObject["showResultStatusMessages"]; + result.showHelpAnimation = jsonObject["showHelpAnimation"]; + result.showNextPageAnimation = jsonObject["showNextPageAnimation"]; + result.showBackgroundMask = jsonObject["showBackgroundMask"]; + + result.cameraFrameBorderWidth = jsonObject["cameraFrameBorderWidth"]; + result.cameraFrameLineLength = jsonObject["cameraFrameLineLength"]; + result.cameraFrameShapeType = FrameShapeType.getByValue( + jsonObject["cameraFrameShapeType"], + ); + result.cameraFrameOffsetWidth = jsonObject["cameraFrameOffsetWidth"]; + + result.status = jsonObject["status"]; + result.resultStatus = jsonObject["resultStatus"]; + result.multipageButtonText = jsonObject["multipageButtonText"]; + + result.cameraFrameDefaultColor = _intToColor( + jsonObject["cameraFrameDefaultColor"], + ); + result.cameraFrameActiveColor = _intToColor( + jsonObject["cameraFrameActiveColor"], + ); + result.statusTextColor = _intToColor(jsonObject["statusTextColor"]); + result.resultStatusTextColor = _intToColor( + jsonObject["resultStatusTextColor"], + ); + result.resultStatusBackgroundColor = _intToColor( + jsonObject["resultStatusBackgroundColor"], + ); + result.multipageButtonBackgroundColor = _intToColor( + jsonObject["multipageButtonBackgroundColor"], + ); + result.tintColor = _intToColor(jsonObject["tintColor"]); + result.activityIndicatorColor = _intToColor( + jsonObject["activityIndicatorColor"], + ); + result.statusBackgroundColor = _intToColor( + jsonObject["statusBackgroundColor"], + ); + result.cameraPreviewBackgroundColor = _intToColor( + jsonObject["cameraPreviewBackgroundColor"], + ); + result.backgroundMaskColor = _intToColor(jsonObject["backgroundMaskColor"]); + result.multipageButtonTextColor = _intToColor( + jsonObject["multipageButtonTextColor"], + ); + + result.statusPositionMultiplier = _toDouble( + jsonObject["statusPositionMultiplier"], + ); + result.resultStatusPositionMultiplier = _toDouble( + jsonObject["resultStatusPositionMultiplier"], + ); + result.toolbarSize = _toDouble(jsonObject["toolbarSize"]); + result.backgroundMaskAlpha = _toDouble(jsonObject["backgroundMaskAlpha"]); + result.customStatusPositionMultiplier = _toDouble( + jsonObject["customStatusPositionMultiplier"], + ); + result.cameraFrameVerticalPositionMultiplier = _toDouble( + jsonObject["cameraFrameVerticalPositionMultiplier"], + ); + result.cameraFrameLandscapeAspectRatio = _toDouble( + jsonObject["cameraFrameLandscapeAspectRatio"], + ); + result.cameraFrameCornerRadius = _toDouble( + jsonObject["cameraFrameCornerRadius"], + ); + result.cameraFramePortraitAspectRatio = _toDouble( + jsonObject["cameraFramePortraitAspectRatio"], + ); + result.livenessAnimationPositionMultiplier = _toDouble( + jsonObject["livenessAnimationPositionMultiplier"], + ); + result.nextPageAnimationStartDelay = _toDouble( + jsonObject["nextPageAnimationStartDelay"], + ); + result.nextPageAnimationEndDelay = _toDouble( + jsonObject["nextPageAnimationEndDelay"], + ); + result.activityIndicatorPortraitPositionMultiplier = _toDouble( + jsonObject["activityIndicatorPortraitPositionMultiplier"], + ); + result.activityIndicatorLandscapePositionMultiplier = _toDouble( + jsonObject["activityIndicatorLandscapePositionMultiplier"], + ); + result.cameraPreviewVerticalPositionMultiplier = _toDouble( + jsonObject["cameraPreviewVerticalPositionMultiplier"], + ); + result.multipageButtonPositionMultiplier = _toDouble( + jsonObject["multipageButtonPositionMultiplier"], + ); + + result.multipageAnimationFrontImage = _dataFromBase64( + jsonObject["multipageAnimationFrontImage"], + ); + result.multipageAnimationBackImage = _dataFromBase64( + jsonObject["multipageAnimationBackImage"], + ); + result.borderBackgroundImage = _dataFromBase64( + jsonObject["borderBackgroundImage"], + ); + result.helpAnimationImage = _dataFromBase64( + jsonObject["helpAnimationImage"], + ); + result.closeButtonImage = _dataFromBase64(jsonObject["closeButtonImage"]); + result.captureButtonImage = _dataFromBase64( + jsonObject["captureButtonImage"], + ); + result.cameraSwitchButtonImage = _dataFromBase64( + jsonObject["cameraSwitchButtonImage"], + ); + result.torchButtonOnImage = _dataFromBase64( + jsonObject["torchButtonOnImage"], + ); + result.torchButtonOffImage = _dataFromBase64( + jsonObject["torchButtonOffImage"], + ); + result.changeFrameButtonExpandImage = _dataFromBase64( + jsonObject["changeFrameButtonExpandImage"], + ); + result.changeFrameButtonCollapseImage = _dataFromBase64( + jsonObject["changeFrameButtonCollapseImage"], + ); + result.livenessAnimationImage = _dataFromBase64( + jsonObject["livenessAnimationImage"], + ); + result.multipageButtonImage = _dataFromBase64( + jsonObject["multipageButtonImage"], + ); + + result.customLabelStatus = jsonObject["customLabelStatus"]; + result.cameraFrameLineCap = Cap.getByValue( + jsonObject["cameraFrameLineCap"], + ); + result.uiCustomizationLayer = jsonObject["uiCustomizationLayer"]; + result.statusTextFont = Font.fromJson(jsonObject["statusTextFont"]); + result.resultStatusTextFont = Font.fromJson( + jsonObject["resultStatusTextFont"], + ); + result.multipageButtonTextFont = Font.fromJson( + jsonObject["multipageButtonTextFont"], + ); + + result.helpAnimationImageTransformsIOS = ViewContentMode.getByValue( + jsonObject["helpAnimationImageContentMode"], + ); + result.multipageAnimationFrontImageTransformsIOS = + ViewContentMode.getByValue( + jsonObject["multipageAnimationFrontImageContentMode"], + ); + result.multipageAnimationBackImageTransformsIOS = + ViewContentMode.getByValue( + jsonObject["multipageAnimationBackImageContentMode"], + ); + result.livenessAnimationImageTransformsIOS = ViewContentMode.getByValue( + jsonObject["livenessAnimationImageContentMode"], + ); + result.borderBackgroundImageTransformsIOS = ViewContentMode.getByValue( + jsonObject["borderBackgroundImageContentMode"], + ); + + if (jsonObject["helpAnimationImageMatrix"] != null) { + List array = []; + for (var value in jsonObject["helpAnimationImageMatrix"]) { + array.add(value.toDouble()); + } + result.helpAnimationImageTransformsAndroid = array; + } else { + result.helpAnimationImageTransformsAndroid = null; + } + if (jsonObject["multipageAnimationFrontImageMatrix"] != null) { + List array = []; + for (var value in jsonObject["multipageAnimationFrontImageMatrix"]) { + array.add(value.toDouble()); + } + result.multipageAnimationFrontImageTransformsAndroid = array; + } else { + result.multipageAnimationFrontImageTransformsAndroid = null; + } + if (jsonObject["multipageAnimationBackImageMatrix"] != null) { + List array = []; + for (var value in jsonObject["multipageAnimationBackImageMatrix"]) { + array.add(value.toDouble()); + } + result.multipageAnimationBackImageTransformsAndroid = array; + } else { + result.multipageAnimationBackImageTransformsAndroid = null; + } + if (jsonObject["livenessAnimationImageMatrix"] != null) { + List array = []; + for (var value in jsonObject["livenessAnimationImageMatrix"]) { + array.add(value.toDouble()); + } + result.livenessAnimationImageTransformsAndroid = array; + } else { + result.livenessAnimationImageTransformsAndroid = null; + } + if (jsonObject["borderBackgroundImageMatrix"] != null) { + List array = []; + for (var value in jsonObject["borderBackgroundImageMatrix"]) { + array.add(value.toDouble()); + } + result.borderBackgroundImageTransformsAndroid = array; + } else { + result.borderBackgroundImageTransformsAndroid = null; + } + + result.colors = CustomizationColors.fromJson(jsonObject["colors"]); + result.fonts = CustomizationFonts.fromJson(jsonObject["fonts"]); + result.images = CustomizationImages.fromJson(jsonObject["images"]); + result.timings = CustomizationTimings.fromJson(jsonObject["timings"]); + result.contentModes = + CustomizationContentModes.fromJson(jsonObject["contentModes"]); + result.matrices = CustomizationMatrices.fromJson(jsonObject["matrices"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "showStatusMessages": showStatusMessages, + "showResultStatusMessages": showResultStatusMessages, + "showHelpAnimation": showHelpAnimation, + "showNextPageAnimation": showNextPageAnimation, + "showBackgroundMask": showBackgroundMask, + "cameraFrameBorderWidth": cameraFrameBorderWidth, + "cameraFrameLineLength": cameraFrameLineLength, + "cameraFrameShapeType": cameraFrameShapeType?.value, + "cameraFrameOffsetWidth": cameraFrameOffsetWidth, + "status": status, + "resultStatus": resultStatus, + "multipageButtonText": multipageButtonText, + "cameraFrameDefaultColor": _intFromColor(cameraFrameDefaultColor), + "cameraFrameActiveColor": _intFromColor(cameraFrameActiveColor), + "statusTextColor": _intFromColor(statusTextColor), + "resultStatusBackgroundColor": _intFromColor( + resultStatusBackgroundColor, + ), + "multipageButtonBackgroundColor": _intFromColor( + multipageButtonBackgroundColor, + ), + "tintColor": _intFromColor(tintColor), + "activityIndicatorColor": _intFromColor(activityIndicatorColor), + "statusBackgroundColor": _intFromColor(statusBackgroundColor), + "cameraPreviewBackgroundColor": _intFromColor( + cameraPreviewBackgroundColor, + ), + "backgroundMaskColor": _intFromColor(backgroundMaskColor), + "resultStatusTextColor": _intFromColor(resultStatusTextColor), + "multipageButtonTextColor": _intFromColor(multipageButtonTextColor), + "statusPositionMultiplier": statusPositionMultiplier, + "resultStatusPositionMultiplier": resultStatusPositionMultiplier, + "toolbarSize": toolbarSize, + "backgroundMaskAlpha": backgroundMaskAlpha, + "customStatusPositionMultiplier": customStatusPositionMultiplier, + "cameraFrameVerticalPositionMultiplier": + cameraFrameVerticalPositionMultiplier, + "cameraFrameLandscapeAspectRatio": cameraFrameLandscapeAspectRatio, + "cameraFramePortraitAspectRatio": cameraFramePortraitAspectRatio, + "cameraFrameCornerRadius": cameraFrameCornerRadius, + "livenessAnimationPositionMultiplier": + livenessAnimationPositionMultiplier, + "nextPageAnimationStartDelay": nextPageAnimationStartDelay, + "nextPageAnimationEndDelay": nextPageAnimationEndDelay, + "activityIndicatorPortraitPositionMultiplier": + activityIndicatorPortraitPositionMultiplier, + "activityIndicatorLandscapePositionMultiplier": + activityIndicatorLandscapePositionMultiplier, + "cameraPreviewVerticalPositionMultiplier": + cameraPreviewVerticalPositionMultiplier, + "multipageButtonPositionMultiplier": multipageButtonPositionMultiplier, + "multipageAnimationFrontImage": _dataToBase64( + multipageAnimationFrontImage, + ), + "multipageAnimationBackImage": _dataToBase64( + multipageAnimationBackImage, + ), + "borderBackgroundImage": _dataToBase64(borderBackgroundImage), + "helpAnimationImage": _dataToBase64(helpAnimationImage), + "closeButtonImage": _dataToBase64(closeButtonImage), + "captureButtonImage": _dataToBase64(captureButtonImage), + "cameraSwitchButtonImage": _dataToBase64(cameraSwitchButtonImage), + "torchButtonOnImage": _dataToBase64(torchButtonOnImage), + "torchButtonOffImage": _dataToBase64(torchButtonOffImage), + "changeFrameButtonExpandImage": _dataToBase64( + changeFrameButtonExpandImage, + ), + "changeFrameButtonCollapseImage": _dataToBase64( + changeFrameButtonCollapseImage, + ), + "livenessAnimationImage": _dataToBase64(livenessAnimationImage), + "multipageButtonImage": _dataToBase64(multipageButtonImage), + "customLabelStatus": customLabelStatus, + "cameraFrameLineCap": cameraFrameLineCap?.value, + "uiCustomizationLayer": uiCustomizationLayer, + "statusTextFont": statusTextFont?.toJson(), + "resultStatusTextFont": resultStatusTextFont?.toJson(), + "multipageButtonTextFont": multipageButtonTextFont?.toJson(), + "helpAnimationImageContentMode": helpAnimationImageTransformsIOS?.value, + "multipageAnimationFrontImageContentMode": + multipageAnimationFrontImageTransformsIOS?.value, + "multipageAnimationBackImageContentMode": + multipageAnimationBackImageTransformsIOS?.value, + "livenessAnimationImageContentMode": + livenessAnimationImageTransformsIOS?.value, + "borderBackgroundImageContentMode": + borderBackgroundImageTransformsIOS?.value, + "helpAnimationImageMatrix": helpAnimationImageTransformsAndroid, + "multipageAnimationFrontImageMatrix": + multipageAnimationFrontImageTransformsAndroid, + "multipageAnimationBackImageMatrix": + multipageAnimationBackImageTransformsAndroid, + "livenessAnimationImageMatrix": livenessAnimationImageTransformsAndroid, + "borderBackgroundImageMatrix": borderBackgroundImageTransformsAndroid, + "colors": colors.toJson(), + "fonts": fonts.toJson(), + "images": images.toJson(), + "timings": timings.toJson(), + "contentModes": contentModes.toJson(), + "matrices": matrices.toJson(), + }.clearNulls(); + + void _set(Map json) { + if (identical(this, DocumentReader.instance.customization)) { + _bridge.invokeMethod("setCustomization", [json]); + } + testSetters.addAll(json); + } + + void _apply() => _set(toJson()); + + @visibleForTesting + Map testSetters = {}; +} + +enum Cap { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + BUTT(0), + + ROUND(1), + + SQUARE(2); + + const Cap(this.value); + final int value; + + static Cap? getByValue(int? i) { + if (i == null) return null; + try { + return Cap.values.firstWhere((x) => x.value == i); + } catch (_) { + return Cap.UNKNOWN; + } + } +} + +enum FrameShapeType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Camera frame is rectangle. + LINE(0), + + /// Camera frame only consists of corners of the rectangle. + CORNER(1); + + const FrameShapeType(this.value); + final int value; + + static FrameShapeType? getByValue(int? i) { + if (i == null) return null; + try { + return FrameShapeType.values.firstWhere((x) => x.value == i); + } catch (_) { + return FrameShapeType.UNKNOWN; + } + } +} + +/// Button tags for UI customization. +enum CustomButtonTag { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + CLOSE(1001), + + TORCH(1002), + + CAPTURE(1003), + + CHANGE_FRAME(1004), + + SKIP(1005), + + CAMERA_SWITCH(1006); + + const CustomButtonTag(this.value); + final int value; + + static CustomButtonTag? getByValue(int? i) { + if (i == null) return null; + try { + return CustomButtonTag.values.firstWhere((x) => x.value == i); + } catch (_) { + return CustomButtonTag.UNKNOWN; + } + } +} diff --git a/lib/src/params/customization/customization_colors.dart b/lib/src/params/customization/customization_colors.dart new file mode 100644 index 0000000000..24a93bcb00 --- /dev/null +++ b/lib/src/params/customization/customization_colors.dart @@ -0,0 +1,365 @@ +// +// CustomizationColors.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationColors { + Color? get rfidProcessingScreenBackground => _rfidProcessingScreenBackground; + Color? _rfidProcessingScreenBackground; + set rfidProcessingScreenBackground(Color? val) { + _rfidProcessingScreenBackground = val; + _set({"rfidProcessingScreenBackground": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenHintLabelText => + _rfidProcessingScreenHintLabelText; + Color? _rfidProcessingScreenHintLabelText; + set rfidProcessingScreenHintLabelText(Color? val) { + _rfidProcessingScreenHintLabelText = val; + _set({"rfidProcessingScreenHintLabelText": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenHintLabelBackground => + _rfidProcessingScreenHintLabelBackground; + Color? _rfidProcessingScreenHintLabelBackground; + set rfidProcessingScreenHintLabelBackground(Color? val) { + _rfidProcessingScreenHintLabelBackground = val; + _set({"rfidProcessingScreenHintLabelBackground": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenProgressLabelText => + _rfidProcessingScreenProgressLabelText; + Color? _rfidProcessingScreenProgressLabelText; + set rfidProcessingScreenProgressLabelText(Color? val) { + _rfidProcessingScreenProgressLabelText = val; + _set({"rfidProcessingScreenProgressLabelText": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenProgressBar => + _rfidProcessingScreenProgressBar; + Color? _rfidProcessingScreenProgressBar; + set rfidProcessingScreenProgressBar(Color? val) { + _rfidProcessingScreenProgressBar = val; + _set({"rfidProcessingScreenProgressBar": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenProgressBarBackground => + _rfidProcessingScreenProgressBarBackground; + Color? _rfidProcessingScreenProgressBarBackground; + set rfidProcessingScreenProgressBarBackground(Color? val) { + _rfidProcessingScreenProgressBarBackground = val; + _set({"rfidProcessingScreenProgressBarBackground": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenResultLabelText => + _rfidProcessingScreenResultLabelText; + Color? _rfidProcessingScreenResultLabelText; + set rfidProcessingScreenResultLabelText(Color? val) { + _rfidProcessingScreenResultLabelText = val; + _set({"rfidProcessingScreenResultLabelText": _intFromColor(val)}); + } + + Color? get rfidProcessingScreenLoadingBar => _rfidProcessingScreenLoadingBar; + Color? _rfidProcessingScreenLoadingBar; + set rfidProcessingScreenLoadingBar(Color? val) { + _rfidProcessingScreenLoadingBar = val; + _set({"rfidProcessingScreenLoadingBar": _intFromColor(val)}); + } + + /// Android only. + Color? get rfidEnableNfcTitleText => _rfidEnableNfcTitleText; + Color? _rfidEnableNfcTitleText; + set rfidEnableNfcTitleText(Color? val) { + _rfidEnableNfcTitleText = val; + _set({"rfidEnableNfcTitleText": _intFromColor(val)}); + } + + /// Android only. + Color? get rfidEnableNfcDescriptionText => _rfidEnableNfcDescriptionText; + Color? _rfidEnableNfcDescriptionText; + set rfidEnableNfcDescriptionText(Color? val) { + _rfidEnableNfcDescriptionText = val; + _set({"rfidEnableNfcDescriptionText": _intFromColor(val)}); + } + + /// Android only. + Color? get rfidEnableNfcButtonText => _rfidEnableNfcButtonText; + Color? _rfidEnableNfcButtonText; + set rfidEnableNfcButtonText(Color? val) { + _rfidEnableNfcButtonText = val; + _set({"rfidEnableNfcButtonText": _intFromColor(val)}); + } + + /// Android only. + Color? get rfidEnableNfcButtonBackground => _rfidEnableNfcButtonBackground; + Color? _rfidEnableNfcButtonBackground; + set rfidEnableNfcButtonBackground(Color? val) { + _rfidEnableNfcButtonBackground = val; + _set({"rfidEnableNfcButtonBackground": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenBackground => _mdlProcessingScreenBackground; + Color? _mdlProcessingScreenBackground; + set mdlProcessingScreenBackground(Color? val) { + _mdlProcessingScreenBackground = val; + _set({"mdlProcessingScreenBackground": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenHintLabelText => + _mdlProcessingScreenHintLabelText; + Color? _mdlProcessingScreenHintLabelText; + set mdlProcessingScreenHintLabelText(Color? val) { + _mdlProcessingScreenHintLabelText = val; + _set({"mdlProcessingScreenHintLabelText": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenHintLabelBackground => + _mdlProcessingScreenHintLabelBackground; + Color? _mdlProcessingScreenHintLabelBackground; + set mdlProcessingScreenHintLabelBackground(Color? val) { + _mdlProcessingScreenHintLabelBackground = val; + _set({"mdlProcessingScreenHintLabelBackground": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenProgressLabelText => + _mdlProcessingScreenProgressLabelText; + Color? _mdlProcessingScreenProgressLabelText; + set mdlProcessingScreenProgressLabelText(Color? val) { + _mdlProcessingScreenProgressLabelText = val; + _set({"mdlProcessingScreenProgressLabelText": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenResultLabelText => + _mdlProcessingScreenResultLabelText; + Color? _mdlProcessingScreenResultLabelText; + set mdlProcessingScreenResultLabelText(Color? val) { + _mdlProcessingScreenResultLabelText = val; + _set({"mdlProcessingScreenResultLabelText": _intFromColor(val)}); + } + + Color? get mdlProcessingScreenLoadingBar => _mdlProcessingScreenLoadingBar; + Color? _mdlProcessingScreenLoadingBar; + set mdlProcessingScreenLoadingBar(Color? val) { + _mdlProcessingScreenLoadingBar = val; + _set({"mdlProcessingScreenLoadingBar": _intFromColor(val)}); + } + + /// Android only. + Color? get mdlEnableNfcTitleText => _mdlEnableNfcTitleText; + Color? _mdlEnableNfcTitleText; + set mdlEnableNfcTitleText(Color? val) { + _mdlEnableNfcTitleText = val; + _set({"mdlEnableNfcTitleText": _intFromColor(val)}); + } + + /// Android only. + Color? get mdlEnableNfcDescriptionText => _mdlEnableNfcDescriptionText; + Color? _mdlEnableNfcDescriptionText; + set mdlEnableNfcDescriptionText(Color? val) { + _mdlEnableNfcDescriptionText = val; + _set({"mdlEnableNfcDescriptionText": _intFromColor(val)}); + } + + /// Android only. + Color? get mdlEnableNfcButtonText => _mdlEnableNfcButtonText; + Color? _mdlEnableNfcButtonText; + set mdlEnableNfcButtonText(Color? val) { + _mdlEnableNfcButtonText = val; + _set({"mdlEnableNfcButtonText": _intFromColor(val)}); + } + + /// Android only. + Color? get mdlEnableNfcButtonBackground => _mdlEnableNfcButtonBackground; + Color? _mdlEnableNfcButtonBackground; + set mdlEnableNfcButtonBackground(Color? val) { + _mdlEnableNfcButtonBackground = val; + _set({"mdlEnableNfcButtonBackground": _intFromColor(val)}); + } + + Color? get nextPageIdCardFront => _nextPageIdCardFront; + Color? _nextPageIdCardFront; + set nextPageIdCardFront(Color? val) { + _nextPageIdCardFront = val; + _set({"nextPageIdCardFront": _intFromColor(val)}); + } + + Color? get nextPageIdCardBack => _nextPageIdCardBack; + Color? _nextPageIdCardBack; + set nextPageIdCardBack(Color? val) { + _nextPageIdCardBack = val; + _set({"nextPageIdCardBack": _intFromColor(val)}); + } + + Color? get nextPagePassportShift => _nextPagePassportShift; + Color? _nextPagePassportShift; + set nextPagePassportShift(Color? val) { + _nextPagePassportShift = val; + _set({"nextPagePassportShift": _intFromColor(val)}); + } + + Color? get nextPagePassportFlip => _nextPagePassportFlip; + Color? _nextPagePassportFlip; + set nextPagePassportFlip(Color? val) { + _nextPagePassportFlip = val; + _set({"nextPagePassportFlip": _intFromColor(val)}); + } + + /// Allows you to deserialize object. + static CustomizationColors fromJson(jsonObject) { + var result = CustomizationColors(); + result.testSetters = {}; + + result.rfidProcessingScreenBackground = + _intToColor(jsonObject["rfidProcessingScreenBackground"]); + result.rfidProcessingScreenHintLabelText = + _intToColor(jsonObject["rfidProcessingScreenHintLabelText"]); + result.rfidProcessingScreenHintLabelBackground = + _intToColor(jsonObject["rfidProcessingScreenHintLabelBackground"]); + result.rfidProcessingScreenProgressLabelText = + _intToColor(jsonObject["rfidProcessingScreenProgressLabelText"]); + result.rfidProcessingScreenProgressBar = + _intToColor(jsonObject["rfidProcessingScreenProgressBar"]); + result.rfidProcessingScreenProgressBarBackground = + _intToColor(jsonObject["rfidProcessingScreenProgressBarBackground"]); + result.rfidProcessingScreenResultLabelText = + _intToColor(jsonObject["rfidProcessingScreenResultLabelText"]); + result.rfidProcessingScreenLoadingBar = + _intToColor(jsonObject["rfidProcessingScreenLoadingBar"]); + result.rfidEnableNfcTitleText = + _intToColor(jsonObject["rfidEnableNfcTitleText"]); + result.rfidEnableNfcDescriptionText = + _intToColor(jsonObject["rfidEnableNfcDescriptionText"]); + result.rfidEnableNfcButtonText = + _intToColor(jsonObject["rfidEnableNfcButtonText"]); + result.rfidEnableNfcButtonBackground = + _intToColor(jsonObject["rfidEnableNfcButtonBackground"]); + result.mdlProcessingScreenBackground = + _intToColor(jsonObject["mdlProcessingScreenBackground"]); + result.mdlProcessingScreenHintLabelText = + _intToColor(jsonObject["mdlProcessingScreenHintLabelText"]); + result.mdlProcessingScreenHintLabelBackground = + _intToColor(jsonObject["mdlProcessingScreenHintLabelBackground"]); + result.mdlProcessingScreenProgressLabelText = + _intToColor(jsonObject["mdlProcessingScreenProgressLabelText"]); + result.mdlProcessingScreenResultLabelText = + _intToColor(jsonObject["mdlProcessingScreenResultLabelText"]); + result.mdlProcessingScreenLoadingBar = + _intToColor(jsonObject["mdlProcessingScreenLoadingBar"]); + result.mdlEnableNfcTitleText = + _intToColor(jsonObject["mdlEnableNfcTitleText"]); + result.mdlEnableNfcDescriptionText = + _intToColor(jsonObject["mdlEnableNfcDescriptionText"]); + result.mdlEnableNfcButtonText = + _intToColor(jsonObject["mdlEnableNfcButtonText"]); + result.mdlEnableNfcButtonBackground = + _intToColor(jsonObject["mdlEnableNfcButtonBackground"]); + result.nextPageIdCardFront = _intToColor(jsonObject["nextPageIdCardFront"]); + result.nextPageIdCardBack = _intToColor(jsonObject["nextPageIdCardBack"]); + result.nextPagePassportShift = + _intToColor(jsonObject["nextPagePassportShift"]); + result.nextPagePassportFlip = + _intToColor(jsonObject["nextPagePassportFlip"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "rfidProcessingScreenBackground": _intFromColor( + rfidProcessingScreenBackground, + ), + "rfidProcessingScreenHintLabelText": _intFromColor( + rfidProcessingScreenHintLabelText, + ), + "rfidProcessingScreenHintLabelBackground": _intFromColor( + rfidProcessingScreenHintLabelBackground, + ), + "rfidProcessingScreenProgressLabelText": _intFromColor( + rfidProcessingScreenProgressLabelText, + ), + "rfidProcessingScreenProgressBar": _intFromColor( + rfidProcessingScreenProgressBar, + ), + "rfidProcessingScreenProgressBarBackground": _intFromColor( + rfidProcessingScreenProgressBarBackground, + ), + "rfidProcessingScreenResultLabelText": _intFromColor( + rfidProcessingScreenResultLabelText, + ), + "rfidProcessingScreenLoadingBar": _intFromColor( + rfidProcessingScreenLoadingBar, + ), + "rfidEnableNfcTitleText": _intFromColor( + rfidEnableNfcTitleText, + ), + "rfidEnableNfcDescriptionText": _intFromColor( + rfidEnableNfcDescriptionText, + ), + "rfidEnableNfcButtonText": _intFromColor( + rfidEnableNfcButtonText, + ), + "rfidEnableNfcButtonBackground": _intFromColor( + rfidEnableNfcButtonBackground, + ), + "mdlProcessingScreenBackground": _intFromColor( + mdlProcessingScreenBackground, + ), + "mdlProcessingScreenHintLabelText": _intFromColor( + mdlProcessingScreenHintLabelText, + ), + "mdlProcessingScreenHintLabelBackground": _intFromColor( + mdlProcessingScreenHintLabelBackground, + ), + "mdlProcessingScreenProgressLabelText": _intFromColor( + mdlProcessingScreenProgressLabelText, + ), + "mdlProcessingScreenResultLabelText": _intFromColor( + mdlProcessingScreenResultLabelText, + ), + "mdlProcessingScreenLoadingBar": _intFromColor( + mdlProcessingScreenLoadingBar, + ), + "mdlEnableNfcTitleText": _intFromColor( + mdlEnableNfcTitleText, + ), + "mdlEnableNfcDescriptionText": _intFromColor( + mdlEnableNfcDescriptionText, + ), + "mdlEnableNfcButtonText": _intFromColor( + mdlEnableNfcButtonText, + ), + "mdlEnableNfcButtonBackground": _intFromColor( + mdlEnableNfcButtonBackground, + ), + "nextPageIdCardFront": _intFromColor( + nextPageIdCardFront, + ), + "nextPageIdCardBack": _intFromColor( + nextPageIdCardBack, + ), + "nextPagePassportShift": _intFromColor( + nextPagePassportShift, + ), + "nextPagePassportFlip": _intFromColor( + nextPagePassportFlip, + ), + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"colors": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.colors)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/customization/customization_content_modes.dart b/lib/src/params/customization/customization_content_modes.dart new file mode 100644 index 0000000000..23cb373779 --- /dev/null +++ b/lib/src/params/customization/customization_content_modes.dart @@ -0,0 +1,98 @@ +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationContentModes { + ViewContentMode? get nextPageIdCardFront => _nextPageIdCardFront; + ViewContentMode? _nextPageIdCardFront; + set nextPageIdCardFront(ViewContentMode? val) { + _nextPageIdCardFront = val; + _set({"nextPageIdCardFront": val?.value}); + } + + ViewContentMode? get nextPageIdCardBack => _nextPageIdCardBack; + ViewContentMode? _nextPageIdCardBack; + set nextPageIdCardBack(ViewContentMode? val) { + _nextPageIdCardBack = val; + _set({"nextPageIdCardBack": val?.value}); + } + + /// Allows you to deserialize object. + static CustomizationContentModes fromJson(jsonObject) { + var result = CustomizationContentModes(); + if (jsonObject == null) return result; + result.testSetters = {}; + + result.nextPageIdCardFront = + ViewContentMode.getByValue(jsonObject["nextPageIdCardFront"]); + result.nextPageIdCardBack = + ViewContentMode.getByValue(jsonObject["nextPageIdCardBack"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "nextPageIdCardFront": nextPageIdCardFront?.value, + "nextPageIdCardBack": nextPageIdCardBack?.value, + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"contentModes": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.contentModes)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} + +/// Clone of iOS native enum `UIViewContentMode` +enum ViewContentMode { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + SCALE_TO_FILL(0), + + /// Contents scaled to fit with fixed aspect. remainder is transparent. + SCALE_ASPECT_FIT(1), + + /// Contents scaled to fill with fixed aspect. some portion of content may be clipped. + SCALE_ASPECT_FILL(2), + + /// redraw on bounds change (calls -setNeedsDisplay). + REDRAW(3), + + /// contents remain same size. positioned adjusted. + CENTER(4), + + TOP(5), + + BOTTOM(6), + + LEFT(7), + + RIGHT(8), + + TOP_LEFT(9), + + TOP_RIGHT(10), + + BOTTOM_LEFT(11), + + BOTTOM_RIGHT(12); + + const ViewContentMode(this.value); + final int value; + + static ViewContentMode? getByValue(int? i) { + if (i == null) return null; + try { + return ViewContentMode.values.firstWhere((x) => x.value == i); + } catch (_) { + return ViewContentMode.UNKNOWN; + } + } +} diff --git a/lib/src/params/customization/customization_fonts.dart b/lib/src/params/customization/customization_fonts.dart new file mode 100644 index 0000000000..c2e9e94f80 --- /dev/null +++ b/lib/src/params/customization/customization_fonts.dart @@ -0,0 +1,238 @@ +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationFonts { + Font? get rfidProcessingScreenHintLabel => _rfidProcessingScreenHintLabel; + Font? _rfidProcessingScreenHintLabel; + set rfidProcessingScreenHintLabel(Font? val) { + _rfidProcessingScreenHintLabel = val; + _set({"rfidProcessingScreenHintLabel": val?.toJson()}); + } + + Font? get rfidProcessingScreenProgressLabel => + _rfidProcessingScreenProgressLabel; + Font? _rfidProcessingScreenProgressLabel; + set rfidProcessingScreenProgressLabel(Font? val) { + _rfidProcessingScreenProgressLabel = val; + _set({"rfidProcessingScreenProgressLabel": val?.toJson()}); + } + + Font? get rfidProcessingScreenResultLabel => _rfidProcessingScreenResultLabel; + Font? _rfidProcessingScreenResultLabel; + set rfidProcessingScreenResultLabel(Font? val) { + _rfidProcessingScreenResultLabel = val; + _set({"rfidProcessingScreenResultLabel": val?.toJson()}); + } + + /// Android only. + Font? get rfidEnableNfcTitleText => _rfidEnableNfcTitleText; + Font? _rfidEnableNfcTitleText; + set rfidEnableNfcTitleText(Font? val) { + _rfidEnableNfcTitleText = val; + _set({"rfidEnableNfcTitleText": val?.toJson()}); + } + + /// Android only. + Font? get rfidEnableNfcDescriptionText => _rfidEnableNfcDescriptionText; + Font? _rfidEnableNfcDescriptionText; + set rfidEnableNfcDescriptionText(Font? val) { + _rfidEnableNfcDescriptionText = val; + _set({"rfidEnableNfcDescriptionText": val?.toJson()}); + } + + /// Android only. + Font? get rfidEnableNfcButtonText => _rfidEnableNfcButtonText; + Font? _rfidEnableNfcButtonText; + set rfidEnableNfcButtonText(Font? val) { + _rfidEnableNfcButtonText = val; + _set({"rfidEnableNfcButtonText": val?.toJson()}); + } + + Font? get mdlProcessingScreenHintLabel => _mdlProcessingScreenHintLabel; + Font? _mdlProcessingScreenHintLabel; + set mdlProcessingScreenHintLabel(Font? val) { + _mdlProcessingScreenHintLabel = val; + _set({"mdlProcessingScreenHintLabel": val?.toJson()}); + } + + Font? get mdlProcessingScreenProgressLabel => + _mdlProcessingScreenProgressLabel; + Font? _mdlProcessingScreenProgressLabel; + set mdlProcessingScreenProgressLabel(Font? val) { + _mdlProcessingScreenProgressLabel = val; + _set({"mdlProcessingScreenProgressLabel": val?.toJson()}); + } + + Font? get mdlProcessingScreenResultLabel => _mdlProcessingScreenResultLabel; + Font? _mdlProcessingScreenResultLabel; + set mdlProcessingScreenResultLabel(Font? val) { + _mdlProcessingScreenResultLabel = val; + _set({"mdlProcessingScreenResultLabel": val?.toJson()}); + } + + /// Android only. + Font? get mdlEnableNfcTitleText => _mdlEnableNfcTitleText; + Font? _mdlEnableNfcTitleText; + set mdlEnableNfcTitleText(Font? val) { + _mdlEnableNfcTitleText = val; + _set({"mdlEnableNfcTitleText": val?.toJson()}); + } + + /// Android only. + Font? get mdlEnableNfcDescriptionText => _mdlEnableNfcDescriptionText; + Font? _mdlEnableNfcDescriptionText; + set mdlEnableNfcDescriptionText(Font? val) { + _mdlEnableNfcDescriptionText = val; + _set({"mdlEnableNfcDescriptionText": val?.toJson()}); + } + + /// Android only. + Font? get mdlEnableNfcButtonText => _mdlEnableNfcButtonText; + Font? _mdlEnableNfcButtonText; + set mdlEnableNfcButtonText(Font? val) { + _mdlEnableNfcButtonText = val; + _set({"mdlEnableNfcButtonText": val?.toJson()}); + } + + /// Allows you to deserialize object. + static CustomizationFonts fromJson(jsonObject) { + var result = CustomizationFonts(); + result.testSetters = {}; + + result.rfidProcessingScreenHintLabel = Font.fromJson( + jsonObject["rfidProcessingScreenHintLabel"], + ); + result.rfidProcessingScreenProgressLabel = Font.fromJson( + jsonObject["rfidProcessingScreenProgressLabel"], + ); + result.rfidProcessingScreenResultLabel = Font.fromJson( + jsonObject["rfidProcessingScreenResultLabel"], + ); + result.rfidEnableNfcTitleText = Font.fromJson( + jsonObject["rfidEnableNfcTitleText"], + ); + result.rfidEnableNfcDescriptionText = Font.fromJson( + jsonObject["rfidEnableNfcDescriptionText"], + ); + result.rfidEnableNfcButtonText = Font.fromJson( + jsonObject["rfidEnableNfcButtonText"], + ); + result.mdlProcessingScreenHintLabel = Font.fromJson( + jsonObject["mdlProcessingScreenHintLabel"], + ); + result.mdlProcessingScreenProgressLabel = Font.fromJson( + jsonObject["mdlProcessingScreenProgressLabel"], + ); + result.mdlProcessingScreenResultLabel = Font.fromJson( + jsonObject["mdlProcessingScreenResultLabel"], + ); + result.mdlEnableNfcTitleText = Font.fromJson( + jsonObject["mdlEnableNfcTitleText"], + ); + result.mdlEnableNfcDescriptionText = Font.fromJson( + jsonObject["mdlEnableNfcDescriptionText"], + ); + result.mdlEnableNfcButtonText = Font.fromJson( + jsonObject["mdlEnableNfcButtonText"], + ); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "rfidProcessingScreenHintLabel": + rfidProcessingScreenHintLabel?.toJson(), + "rfidProcessingScreenProgressLabel": + rfidProcessingScreenProgressLabel?.toJson(), + "rfidProcessingScreenResultLabel": + rfidProcessingScreenResultLabel?.toJson(), + "rfidEnableNfcTitleText": rfidEnableNfcTitleText?.toJson(), + "rfidEnableNfcDescriptionText": rfidEnableNfcDescriptionText?.toJson(), + "rfidEnableNfcButtonText": rfidEnableNfcButtonText?.toJson(), + "mdlProcessingScreenHintLabel": mdlProcessingScreenHintLabel?.toJson(), + "mdlProcessingScreenProgressLabel": + mdlProcessingScreenProgressLabel?.toJson(), + "mdlProcessingScreenResultLabel": + mdlProcessingScreenResultLabel?.toJson(), + "mdlEnableNfcTitleText": mdlEnableNfcTitleText?.toJson(), + "mdlEnableNfcDescriptionText": mdlEnableNfcDescriptionText?.toJson(), + "mdlEnableNfcButtonText": mdlEnableNfcButtonText?.toJson(), + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"fonts": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.fonts)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} + +class Font { + /// Font family. + /// + /// Beware that Android and iOS have diffrent font names, + /// so you will have to use if condition. + String get name => _name; + String _name; + + /// Font size. + int? get size => _size; + int? _size; + + /// Font style. + /// + /// Android only. + FontStyle? get style => _style; + FontStyle? _style; + + Font(String name, {int? size, FontStyle? style}) + : _name = name, + _size = size, + _style = style; + + /// Allows you to deserialize object. + static Font? fromJson(jsonObject) { + if (jsonObject == null) return null; + + var result = Font(jsonObject["name"]); + result._size = jsonObject["size"]; + result._style = FontStyle.getByValue(jsonObject["style"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"name": name, "size": size, "style": style?.value}.clearNulls(); +} + +enum FontStyle { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + NORMAL(0), + + BOLD(1), + + ITALIC(2), + + BOLD_ITALIC(3); + + const FontStyle(this.value); + final int value; + + static FontStyle? getByValue(int? i) { + if (i == null) return null; + try { + return FontStyle.values.firstWhere((x) => x.value == i); + } catch (_) { + return FontStyle.UNKNOWN; + } + } +} diff --git a/lib/src/params/customization/customization_images.dart b/lib/src/params/customization/customization_images.dart new file mode 100644 index 0000000000..58ce1411f5 --- /dev/null +++ b/lib/src/params/customization/customization_images.dart @@ -0,0 +1,297 @@ +// +// CustomizationImages.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationImages { + ByteData? get helpAnimation => _helpAnimation; + ByteData? _helpAnimation; + set helpAnimation(ByteData? val) { + _helpAnimation = val; + _set({"helpAnimation": _dataToBase64(val)}); + } + + ByteData? get livenessAnimation => _livenessAnimation; + ByteData? _livenessAnimation; + set livenessAnimation(ByteData? val) { + _livenessAnimation = val; + _set({"livenessAnimation": _dataToBase64(val)}); + } + + ByteData? get borderBackground => _borderBackground; + ByteData? _borderBackground; + set borderBackground(ByteData? val) { + _borderBackground = val; + _set({"borderBackground": _dataToBase64(val)}); + } + + ByteData? get torchButtonOn => _torchButtonOn; + ByteData? _torchButtonOn; + set torchButtonOn(ByteData? val) { + _torchButtonOn = val; + _set({"torchButtonOn": _dataToBase64(val)}); + } + + ByteData? get torchButtonOff => _torchButtonOff; + ByteData? _torchButtonOff; + set torchButtonOff(ByteData? val) { + _torchButtonOff = val; + _set({"torchButtonOff": _dataToBase64(val)}); + } + + ByteData? get captureButton => _captureButton; + ByteData? _captureButton; + set captureButton(ByteData? val) { + _captureButton = val; + _set({"captureButton": _dataToBase64(val)}); + } + + ByteData? get switchButton => _switchButton; + ByteData? _switchButton; + set switchButton(ByteData? val) { + _switchButton = val; + _set({"switchButton": _dataToBase64(val)}); + } + + ByteData? get closeButton => _closeButton; + ByteData? _closeButton; + set closeButton(ByteData? val) { + _closeButton = val; + _set({"closeButton": _dataToBase64(val)}); + } + + ByteData? get multipageButton => _multipageButton; + ByteData? _multipageButton; + set multipageButton(ByteData? val) { + _multipageButton = val; + _set({"multipageButton": _dataToBase64(val)}); + } + + ByteData? get rfidProcessingScreenFailureImage => + _rfidProcessingScreenFailureImage; + ByteData? _rfidProcessingScreenFailureImage; + set rfidProcessingScreenFailureImage(ByteData? val) { + _rfidProcessingScreenFailureImage = val; + _set({"rfidProcessingScreenFailureImage": _dataToBase64(val)}); + } + + /// Android only. + ByteData? get rfidEnableNfcImage => _rfidEnableNfcImage; + ByteData? _rfidEnableNfcImage; + set rfidEnableNfcImage(ByteData? val) { + _rfidEnableNfcImage = val; + _set({"rfidEnableNfcImage": _dataToBase64(val)}); + } + + /// Android only. + ByteData? get rfidDisableNfcImage => _rfidDisableNfcImage; + ByteData? _rfidDisableNfcImage; + set rfidDisableNfcImage(ByteData? val) { + _rfidDisableNfcImage = val; + _set({"rfidDisableNfcImage": _dataToBase64(val)}); + } + + ByteData? get mdlProcessingScreenFailureImage => + _mdlProcessingScreenFailureImage; + ByteData? _mdlProcessingScreenFailureImage; + set mdlProcessingScreenFailureImage(ByteData? val) { + _mdlProcessingScreenFailureImage = val; + _set({"mdlProcessingScreenFailureImage": _dataToBase64(val)}); + } + + /// Android only. + ByteData? get mdlEnableNfcImage => _mdlEnableNfcImage; + ByteData? _mdlEnableNfcImage; + set mdlEnableNfcImage(ByteData? val) { + _mdlEnableNfcImage = val; + _set({"mdlEnableNfcImage": _dataToBase64(val)}); + } + + /// Android only. + ByteData? get mdlDisableNfcImage => _mdlDisableNfcImage; + ByteData? _mdlDisableNfcImage; + set mdlDisableNfcImage(ByteData? val) { + _mdlDisableNfcImage = val; + _set({"mdlDisableNfcImage": _dataToBase64(val)}); + } + + ByteData? get nextPageIdCardFront => _nextPageIdCardFront; + ByteData? _nextPageIdCardFront; + set nextPageIdCardFront(ByteData? val) { + _nextPageIdCardFront = val; + _set({"nextPageIdCardFront": _dataToBase64(val)}); + } + + ByteData? get nextPageIdCardBack => _nextPageIdCardBack; + ByteData? _nextPageIdCardBack; + set nextPageIdCardBack(ByteData? val) { + _nextPageIdCardBack = val; + _set({"nextPageIdCardBack": _dataToBase64(val)}); + } + + ByteData? get nextPagePassportShift => _nextPagePassportShift; + ByteData? _nextPagePassportShift; + set nextPagePassportShift(ByteData? val) { + _nextPagePassportShift = val; + _set({"nextPagePassportShift": _dataToBase64(val)}); + } + + ByteData? get nextPagePassportFlipStart => _nextPagePassportFlipStart; + ByteData? _nextPagePassportFlipStart; + set nextPagePassportFlipStart(ByteData? val) { + _nextPagePassportFlipStart = val; + _set({"nextPagePassportFlipStart": _dataToBase64(val)}); + } + + ByteData? get nextPagePassportFlipClean => _nextPagePassportFlipClean; + ByteData? _nextPagePassportFlipClean; + set nextPagePassportFlipClean(ByteData? val) { + _nextPagePassportFlipClean = val; + _set({"nextPagePassportFlipClean": _dataToBase64(val)}); + } + + ByteData? get nextPagePassportFlipTop => _nextPagePassportFlipTop; + ByteData? _nextPagePassportFlipTop; + set nextPagePassportFlipTop(ByteData? val) { + _nextPagePassportFlipTop = val; + _set({"nextPagePassportFlipTop": _dataToBase64(val)}); + } + + ByteData? get nextPagePassportFlipBottom => _nextPagePassportFlipBottom; + ByteData? _nextPagePassportFlipBottom; + set nextPagePassportFlipBottom(ByteData? val) { + _nextPagePassportFlipBottom = val; + _set({"nextPagePassportFlipBottom": _dataToBase64(val)}); + } + + /// Allows you to deserialize object. + static CustomizationImages fromJson(jsonObject) { + var result = CustomizationImages(); + result.testSetters = {}; + + result.helpAnimation = _dataFromBase64(jsonObject["helpAnimation"]); + result.livenessAnimation = _dataFromBase64(jsonObject["livenessAnimation"]); + result.borderBackground = _dataFromBase64(jsonObject["borderBackground"]); + result.torchButtonOn = _dataFromBase64(jsonObject["torchButtonOn"]); + result.torchButtonOff = _dataFromBase64(jsonObject["torchButtonOff"]); + result.captureButton = _dataFromBase64(jsonObject["captureButton"]); + result.switchButton = _dataFromBase64(jsonObject["switchButton"]); + result.closeButton = _dataFromBase64(jsonObject["closeButton"]); + result.multipageButton = _dataFromBase64(jsonObject["multipageButton"]); + result.rfidProcessingScreenFailureImage = + _dataFromBase64(jsonObject["rfidProcessingScreenFailureImage"]); + result.rfidEnableNfcImage = + _dataFromBase64(jsonObject["rfidEnableNfcImage"]); + result.rfidDisableNfcImage = + _dataFromBase64(jsonObject["rfidDisableNfcImage"]); + result.mdlProcessingScreenFailureImage = + _dataFromBase64(jsonObject["mdlProcessingScreenFailureImage"]); + result.mdlEnableNfcImage = _dataFromBase64(jsonObject["mdlEnableNfcImage"]); + result.mdlDisableNfcImage = + _dataFromBase64(jsonObject["mdlDisableNfcImage"]); + result.nextPageIdCardFront = + _dataFromBase64(jsonObject["nextPageIdCardFront"]); + result.nextPageIdCardBack = + _dataFromBase64(jsonObject["nextPageIdCardBack"]); + result.nextPagePassportShift = + _dataFromBase64(jsonObject["nextPagePassportShift"]); + result.nextPagePassportFlipStart = + _dataFromBase64(jsonObject["nextPagePassportFlipStart"]); + result.nextPagePassportFlipClean = + _dataFromBase64(jsonObject["nextPagePassportFlipClean"]); + result.nextPagePassportFlipTop = + _dataFromBase64(jsonObject["nextPagePassportFlipTop"]); + result.nextPagePassportFlipBottom = + _dataFromBase64(jsonObject["nextPagePassportFlipBottom"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "helpAnimation": _dataToBase64( + helpAnimation, + ), + "livenessAnimation": _dataToBase64( + livenessAnimation, + ), + "borderBackground": _dataToBase64( + borderBackground, + ), + "torchButtonOn": _dataToBase64( + torchButtonOn, + ), + "torchButtonOff": _dataToBase64( + torchButtonOff, + ), + "captureButton": _dataToBase64( + captureButton, + ), + "switchButton": _dataToBase64( + switchButton, + ), + "closeButton": _dataToBase64( + closeButton, + ), + "multipageButton": _dataToBase64( + rfidDisableNfcImage, + ), + "rfidProcessingScreenFailureImage": _dataToBase64( + rfidProcessingScreenFailureImage, + ), + "rfidEnableNfcImage": _dataToBase64( + rfidEnableNfcImage, + ), + "rfidDisableNfcImage": _dataToBase64( + rfidDisableNfcImage, + ), + "mdlProcessingScreenFailureImage": _dataToBase64( + mdlProcessingScreenFailureImage, + ), + "mdlEnableNfcImage": _dataToBase64( + mdlEnableNfcImage, + ), + "mdlDisableNfcImage": _dataToBase64( + mdlDisableNfcImage, + ), + "nextPageIdCardFront": _dataToBase64( + nextPageIdCardFront, + ), + "nextPageIdCardBack": _dataToBase64( + nextPageIdCardBack, + ), + "nextPagePassportShift": _dataToBase64( + nextPagePassportShift, + ), + "nextPagePassportFlipStart": _dataToBase64( + nextPagePassportFlipStart, + ), + "nextPagePassportFlipClean": _dataToBase64( + nextPagePassportFlipClean, + ), + "nextPagePassportFlipTop": _dataToBase64( + nextPagePassportFlipTop, + ), + "nextPagePassportFlipBottom": _dataToBase64( + nextPagePassportFlipBottom, + ), + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"images": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.images)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/customization/customization_matrices.dart b/lib/src/params/customization/customization_matrices.dart new file mode 100644 index 0000000000..7ad196d1fd --- /dev/null +++ b/lib/src/params/customization/customization_matrices.dart @@ -0,0 +1,65 @@ +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationMatrices { + List? get nextPageIdCardFront => _nextPageIdCardFront; + List? _nextPageIdCardFront; + set nextPageIdCardFront(List? val) { + _nextPageIdCardFront = val; + _set({"nextPageIdCardFront": val}); + } + + List? get nextPageIdCardBack => _nextPageIdCardBack; + List? _nextPageIdCardBack; + set nextPageIdCardBack(List? val) { + _nextPageIdCardBack = val; + _set({"nextPageIdCardBack": val}); + } + + /// Allows you to deserialize object. + static CustomizationMatrices fromJson(jsonObject) { + var result = CustomizationMatrices(); + if (jsonObject == null) return result; + result.testSetters = {}; + + if (jsonObject["nextPageIdCardFront"] != null) { + List array = []; + for (var value in jsonObject["nextPageIdCardFront"]) { + array.add(value.toDouble()); + } + result.nextPageIdCardFront = array; + } else { + result.nextPageIdCardFront = null; + } + + if (jsonObject["nextPageIdCardBack"] != null) { + List array = []; + for (var value in jsonObject["nextPageIdCardBack"]) { + array.add(value.toDouble()); + } + result.nextPageIdCardBack = array; + } else { + result.nextPageIdCardBack = null; + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "nextPageIdCardFront": nextPageIdCardFront, + "nextPageIdCardBack": nextPageIdCardBack, + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"matrices": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.matrices)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/customization/customization_timings.dart b/lib/src/params/customization/customization_timings.dart new file mode 100644 index 0000000000..72eb517bde --- /dev/null +++ b/lib/src/params/customization/customization_timings.dart @@ -0,0 +1,87 @@ +part of "../../../flutter_document_reader_api.dart"; + +class CustomizationTimings { + int? get nextPageIdCardStartDelay => _nextPageIdCardStartDelay; + int? _nextPageIdCardStartDelay; + set nextPageIdCardStartDelay(int? val) { + _nextPageIdCardStartDelay = val; + _set({"nextPageIdCardStartDelay": val}); + } + + int? get nextPageIdCardEndDelay => _nextPageIdCardEndDelay; + int? _nextPageIdCardEndDelay; + set nextPageIdCardEndDelay(int? val) { + _nextPageIdCardEndDelay = val; + _set({"nextPageIdCardEndDelay": val}); + } + + int? get nextPagePassportShiftStartDelay => _nextPagePassportShiftStartDelay; + int? _nextPagePassportShiftStartDelay; + set nextPagePassportShiftStartDelay(int? val) { + _nextPagePassportShiftStartDelay = val; + _set({"nextPagePassportShiftStartDelay": val}); + } + + int? get nextPagePassportShiftEndDelay => _nextPagePassportShiftEndDelay; + int? _nextPagePassportShiftEndDelay; + set nextPagePassportShiftEndDelay(int? val) { + _nextPagePassportShiftEndDelay = val; + _set({"nextPagePassportShiftEndDelay": val}); + } + + int? get nextPagePassportFlipStartDelay => _nextPagePassportFlipStartDelay; + int? _nextPagePassportFlipStartDelay; + set nextPagePassportFlipStartDelay(int? val) { + _nextPagePassportFlipStartDelay = val; + _set({"nextPagePassportFlipStartDelay": val}); + } + + int? get nextPagePassportFlipEndDelay => _nextPagePassportFlipEndDelay; + int? _nextPagePassportFlipEndDelay; + set nextPagePassportFlipEndDelay(int? val) { + _nextPagePassportFlipEndDelay = val; + _set({"nextPagePassportFlipEndDelay": val}); + } + + /// Allows you to deserialize object. + static CustomizationTimings fromJson(jsonObject) { + var result = CustomizationTimings(); + result.testSetters = {}; + + result.nextPageIdCardStartDelay = jsonObject["nextPageIdCardStartDelay"]; + result.nextPageIdCardEndDelay = jsonObject["nextPageIdCardEndDelay"]; + result.nextPagePassportShiftStartDelay = + jsonObject["nextPagePassportShiftStartDelay"]; + result.nextPagePassportShiftEndDelay = + jsonObject["nextPagePassportShiftEndDelay"]; + result.nextPagePassportFlipStartDelay = + jsonObject["nextPagePassportFlipStartDelay"]; + result.nextPagePassportFlipEndDelay = + jsonObject["nextPagePassportFlipEndDelay"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "nextPageIdCardStartDelay": nextPageIdCardStartDelay, + "nextPageIdCardEndDelay": nextPageIdCardEndDelay, + "nextPagePassportShiftStartDelay": nextPagePassportShiftStartDelay, + "nextPagePassportShiftEndDelay": nextPagePassportShiftEndDelay, + "nextPagePassportFlipStartDelay": nextPagePassportFlipStartDelay, + "nextPagePassportFlipEndDelay": nextPagePassportFlipEndDelay, + }.clearNulls(); + + void _set(Map json, {Customization? directParent}) { + var parentJson = {"timings": json}; + var parent = DocumentReader.instance.customization; + if (identical(this, parent.timings)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(Customization parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/process_params/authenticity_params.dart b/lib/src/params/process_params/authenticity_params.dart new file mode 100644 index 0000000000..f58c8de7d2 --- /dev/null +++ b/lib/src/params/process_params/authenticity_params.dart @@ -0,0 +1,184 @@ +// +// AuthenticityParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class AuthenticityParams { + /// This parameter is used to enable document liveness check. + bool? get useLivenessCheck => _useLivenessCheck; + bool? _useLivenessCheck; + set useLivenessCheck(bool? val) { + _useLivenessCheck = val; + _set({"useLivenessCheck": val}); + } + + LivenessParams get livenessParams => _livenessParams; + LivenessParams _livenessParams = LivenessParams(); + set livenessParams(LivenessParams val) { + (_livenessParams = val)._apply(this); + } + + bool? get checkUVLuminiscence => _checkUVLuminiscence; + bool? _checkUVLuminiscence; + set checkUVLuminiscence(bool? val) { + _checkUVLuminiscence = val; + _set({"checkUVLuminiscence": val}); + } + + bool? get checkIRB900 => _checkIRB900; + bool? _checkIRB900; + set checkIRB900(bool? val) { + _checkIRB900 = val; + _set({"checkIRB900": val}); + } + + bool? get checkImagePatterns => _checkImagePatterns; + bool? _checkImagePatterns; + set checkImagePatterns(bool? val) { + _checkImagePatterns = val; + _set({"checkImagePatterns": val}); + } + + bool? get checkFibers => _checkFibers; + bool? _checkFibers; + set checkFibers(bool? val) { + _checkFibers = val; + _set({"checkFibers": val}); + } + + bool? get checkExtMRZ => _checkExtMRZ; + bool? _checkExtMRZ; + set checkExtMRZ(bool? val) { + _checkExtMRZ = val; + _set({"checkExtMRZ": val}); + } + + bool? get checkExtOCR => _checkExtOCR; + bool? _checkExtOCR; + set checkExtOCR(bool? val) { + _checkExtOCR = val; + _set({"checkExtOCR": val}); + } + + bool? get checkAxial => _checkAxial; + bool? _checkAxial; + set checkAxial(bool? val) { + _checkAxial = val; + _set({"checkAxial": val}); + } + + bool? get checkBarcodeFormat => _checkBarcodeFormat; + bool? _checkBarcodeFormat; + set checkBarcodeFormat(bool? val) { + _checkBarcodeFormat = val; + _set({"checkBarcodeFormat": val}); + } + + bool? get checkIRVisibility => _checkIRVisibility; + bool? _checkIRVisibility; + set checkIRVisibility(bool? val) { + _checkIRVisibility = val; + _set({"checkIRVisibility": val}); + } + + bool? get checkIPI => _checkIPI; + bool? _checkIPI; + set checkIPI(bool? val) { + _checkIPI = val; + _set({"checkIPI": val}); + } + + bool? get checkPhotoEmbedding => _checkPhotoEmbedding; + bool? _checkPhotoEmbedding; + set checkPhotoEmbedding(bool? val) { + _checkPhotoEmbedding = val; + _set({"checkPhotoEmbedding": val}); + } + + bool? get checkPhotoComparison => _checkPhotoComparison; + bool? _checkPhotoComparison; + set checkPhotoComparison(bool? val) { + _checkPhotoComparison = val; + _set({"checkPhotoComparison": val}); + } + + bool? get checkLetterScreen => _checkLetterScreen; + bool? _checkLetterScreen; + set checkLetterScreen(bool? val) { + _checkLetterScreen = val; + _set({"checkLetterScreen": val}); + } + + bool? get checkSecurityText => _checkSecurityText; + bool? _checkSecurityText; + set checkSecurityText(bool? val) { + _checkSecurityText = val; + _set({"checkSecurityText": val}); + } + + /// Allows you to deserialize object. + static AuthenticityParams fromJson(jsonObject) { + if (jsonObject == null) return AuthenticityParams(); + var result = AuthenticityParams(); + result.testSetters = {}; + + result.useLivenessCheck = jsonObject["useLivenessCheck"]; + result.livenessParams = LivenessParams.fromJson( + jsonObject["livenessParams"], + ); + result.checkUVLuminiscence = jsonObject["checkUVLuminiscence"]; + result.checkIRB900 = jsonObject["checkIRB900"]; + result.checkImagePatterns = jsonObject["checkImagePatterns"]; + result.checkFibers = jsonObject["checkFibers"]; + result.checkExtMRZ = jsonObject["checkExtMRZ"]; + result.checkExtOCR = jsonObject["checkExtOCR"]; + result.checkAxial = jsonObject["checkAxial"]; + result.checkBarcodeFormat = jsonObject["checkBarcodeFormat"]; + result.checkIRVisibility = jsonObject["checkIRVisibility"]; + result.checkIPI = jsonObject["checkIPI"]; + result.checkPhotoEmbedding = jsonObject["checkPhotoEmbedding"]; + result.checkPhotoComparison = jsonObject["checkPhotoComparison"]; + result.checkLetterScreen = jsonObject["checkLetterScreen"]; + result.checkSecurityText = jsonObject["checkSecurityText"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "useLivenessCheck": useLivenessCheck, + "livenessParams": livenessParams.toJson(), + "checkUVLuminiscence": checkUVLuminiscence, + "checkIRB900": checkIRB900, + "checkImagePatterns": checkImagePatterns, + "checkFibers": checkFibers, + "checkExtMRZ": checkExtMRZ, + "checkExtOCR": checkExtOCR, + "checkAxial": checkAxial, + "checkBarcodeFormat": checkBarcodeFormat, + "checkIRVisibility": checkIRVisibility, + "checkIPI": checkIPI, + "checkPhotoEmbedding": checkPhotoEmbedding, + "checkPhotoComparison": checkPhotoComparison, + "checkLetterScreen": checkLetterScreen, + "checkSecurityText": checkSecurityText, + }.clearNulls(); + + void _set(Map json, {ProcessParams? directParent}) { + var parentJson = {"authenticityParams": json}; + var parent = DocumentReader.instance.processParams; + if (identical(this, parent.authenticityParams)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(ProcessParams parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/process_params/backend_processing_config.dart b/lib/src/params/process_params/backend_processing_config.dart new file mode 100644 index 0000000000..ff9e02bfab --- /dev/null +++ b/lib/src/params/process_params/backend_processing_config.dart @@ -0,0 +1,64 @@ +// +// BackendProcessingConfig.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class BackendProcessingConfig { + String get url => _url; + String _url; + + Map? get httpHeaders => _httpHeaders; + Map? _httpHeaders; + + bool? get rfidServerSideChipVerification => _rfidServerSideChipVerification; + bool? _rfidServerSideChipVerification; + + bool? get mdlVerification => _mdlVerification; + bool? _mdlVerification; + + /// Timeout in seconds that can be configured for backend transaction creation and package finalization. + double? get timeoutConnection => _timeoutConnection; + double? _timeoutConnection; + + BackendProcessingConfig( + String url, { + bool? rfidServerSideChipVerification, + bool? mdlVerification, + Map? httpHeaders, + double? timeoutConnection, + }) : _url = url, + _rfidServerSideChipVerification = rfidServerSideChipVerification, + _mdlVerification = mdlVerification, + _httpHeaders = httpHeaders, + _timeoutConnection = timeoutConnection; + + /// Allows you to deserialize object. + static BackendProcessingConfig? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = BackendProcessingConfig(jsonObject["url"]); + + result._rfidServerSideChipVerification = + jsonObject["rfidServerSideChipVerification"]; + result._mdlVerification = jsonObject["mdlVerification"]; + if (jsonObject["httpHeaders"] != null) { + result._httpHeaders = Map.from(jsonObject["httpHeaders"]); + } + result._timeoutConnection = _toDouble(jsonObject["timeoutConnection"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "url": url, + "rfidServerSideChipVerification": rfidServerSideChipVerification, + "mdlVerification": mdlVerification, + "httpHeaders": httpHeaders, + "timeoutConnection": timeoutConnection, + }.clearNulls(); +} diff --git a/lib/src/params/process_params/bsi.dart b/lib/src/params/process_params/bsi.dart new file mode 100644 index 0000000000..843215cb35 --- /dev/null +++ b/lib/src/params/process_params/bsi.dart @@ -0,0 +1,22 @@ +part of "../../../flutter_document_reader_api.dart"; + +class Bsi { + bool? _generateResult; + + Bsi({ + bool? generateResult, + }) : _generateResult = generateResult; + + /// Allows you to deserialize object. + static Bsi? fromJson(jsonObject) { + if (jsonObject == null) return null; + return Bsi( + generateResult: jsonObject["generateResult"], + ); + } + + /// Allows you to serialize object. + Map toJson() => { + "generateResult": _generateResult, + }.clearNulls(); +} diff --git a/lib/src/params/process_params/face_api_params.dart b/lib/src/params/process_params/face_api_params.dart new file mode 100644 index 0000000000..6713b505d8 --- /dev/null +++ b/lib/src/params/process_params/face_api_params.dart @@ -0,0 +1,90 @@ +// +// FaceApiParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class FaceApiParams { + /// The URL of the Regula Face SDK service instance to be used. + String get url => _url; + String _url = "https://faceapi.regulaforensics.com"; + + /// The processing mode: "match" or "match+search". + String get mode => _mode; + String _mode = "match"; + + /// The similarity threshold, 0-100. Above 75 means that the faces' similarity + /// is verified, below 75 is not. + int get threshold => _threshold; + int _threshold = 75; + + /// A search filter that can be applied if the "match+search" mode is enabled. + FaceApiSearchParams? get searchParams => _searchParams; + FaceApiSearchParams? _searchParams; + + /// The service request timeout, ms. + int get serviceTimeout => _serviceTimeout; + int _serviceTimeout = 3000; + + /// Proxy to use, should be set according to the cURL standart. + String? get proxy => _proxy; + String? _proxy; + + /// Username and password to use for proxy authentication, + /// should be set according to the cURL standart. + String? get proxyPassword => _proxyPassword; + String? _proxyPassword; + + /// Proxy protocol type, should be set according to the cURL standart. + int? get proxyType => _proxyType; + int? _proxyType; + + FaceApiParams({ + String url = "https://faceapi.regulaforensics.com", + String mode = "match", + int threshold = 75, + FaceApiSearchParams? searchParams, + int serviceTimeout = 3000, + String? proxy, + String? proxyPassword, + int? proxyType, + }) : _url = url, + _mode = mode, + _threshold = threshold, + _searchParams = searchParams, + _serviceTimeout = serviceTimeout, + _proxy = proxy, + _proxyPassword = proxyPassword, + _proxyType = proxyType; + + /// Allows you to deserialize object. + static FaceApiParams? fromJson(jsonObject) { + if (jsonObject == null) return null; + return FaceApiParams( + url: jsonObject["url"], + mode: jsonObject["mode"], + searchParams: FaceApiSearchParams.fromJson(jsonObject["searchParams"]), + threshold: jsonObject["threshold"], + serviceTimeout: jsonObject["serviceTimeout"], + proxy: jsonObject["proxy"], + proxyPassword: jsonObject["proxyPassword"], + proxyType: jsonObject["proxyType"], + ); + } + + /// Allows you to serialize object. + Map toJson() => { + "url": url, + "mode": mode, + "threshold": threshold, + "serviceTimeout": serviceTimeout, + "proxy": proxy, + "proxyPassword": proxyPassword, + "proxyType": proxyType, + "searchParams": searchParams?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/params/process_params/face_api_search_params.dart b/lib/src/params/process_params/face_api_search_params.dart new file mode 100644 index 0000000000..59fa459929 --- /dev/null +++ b/lib/src/params/process_params/face_api_search_params.dart @@ -0,0 +1,51 @@ +// +// FaceApiSearchParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class FaceApiSearchParams { + /// The number of returned Persons limit. + int get limit => _limit; + int _limit; + + /// The similarity distance threshold, should be between 0.0 and 2.0, + /// where 0.0 is for returning results for only the most similar persons + /// and 2.0 is for all the persons, even the dissimilar ones. + /// If not set, the default 1.0 value is used. + double get threshold => _threshold; + double _threshold; + + /// The IDs of the groups in which the search is performed. + List? get groupIds => _groupIds; + List? _groupIds; + + FaceApiSearchParams({ + int limit = 100, + double threshold = 1, + List? groupIds, + }) : _limit = limit, + _threshold = threshold, + _groupIds = groupIds; + + /// Allows you to deserialize object. + static FaceApiSearchParams? fromJson(jsonObject) { + if (jsonObject == null) return null; + return FaceApiSearchParams( + limit: jsonObject["limit"], + threshold: _toDouble(jsonObject["threshold"])!, + groupIds: _stringListFrom(jsonObject["groupIds"]), + ); + } + + /// Allows you to serialize object. + Map toJson() => { + "limit": limit, + "threshold": threshold, + "groupIds": groupIds, + }.clearNulls(); +} diff --git a/lib/src/params/process_params/glares_check_params.dart b/lib/src/params/process_params/glares_check_params.dart new file mode 100644 index 0000000000..f4c3185966 --- /dev/null +++ b/lib/src/params/process_params/glares_check_params.dart @@ -0,0 +1,40 @@ +// +// GlaresCheckParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class GlaresCheckParams { + /// Part of margin from the edges of the image that is ignored by glares check. + /// Example: value 0.07 is 7% of image area is ignored. + double? get imgMarginPart => _imgMarginPart; + double? _imgMarginPart; + + /// The maximum allowable part of glared area. + /// Example: value 0.1 is 10% allowed. + double? get maxGlaringPart => _maxGlaringPart; + double? _maxGlaringPart; + + GlaresCheckParams({double? imgMarginPart, double? maxGlaringPart}) + : _imgMarginPart = imgMarginPart, + _maxGlaringPart = maxGlaringPart; + + /// Allows you to deserialize object. + static GlaresCheckParams? fromJson(jsonObject) { + if (jsonObject == null) return null; + return GlaresCheckParams( + imgMarginPart: _toDouble(jsonObject["imgMarginPart"]), + maxGlaringPart: _toDouble(jsonObject["maxGlaringPart"]), + ); + } + + /// Allows you to serialize object. + Map toJson() => { + "imgMarginPart": imgMarginPart, + "maxGlaringPart": maxGlaringPart, + }.clearNulls(); +} diff --git a/lib/src/params/process_params/image_qa.dart b/lib/src/params/process_params/image_qa.dart new file mode 100644 index 0000000000..fe579d5114 --- /dev/null +++ b/lib/src/params/process_params/image_qa.dart @@ -0,0 +1,164 @@ +// +// ImageQA.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Class contains properties to configure image quality. +class ImageQA { + /// This parameter sets threshold for Image QA check of the presented + /// document physical dpi. If actual document dpi is below this threshold, + /// check will fail. + int? get dpiThreshold => _dpiThreshold; + int? _dpiThreshold; + set dpiThreshold(int? val) { + _dpiThreshold = val; + _set({"dpiThreshold": val}); + } + + /// This parameter sets threshold for Image QA check of the presented + /// document perspective angle in degrees. If actual document perspective + /// angle is above this threshold, check will fail. + int? get angleThreshold => _angleThreshold; + int? _angleThreshold; + set angleThreshold(int? val) { + _angleThreshold = val; + _set({"angleThreshold": val}); + } + + /// This option disabled focus check during performing image quality validation. + bool? get focusCheck => _focusCheck; + bool? _focusCheck; + set focusCheck(bool? val) { + _focusCheck = val; + _set({"focusCheck": val}); + } + + /// This option disabled glares check during performing image quality validation. + bool? get glaresCheck => _glaresCheck; + bool? _glaresCheck; + set glaresCheck(bool? val) { + _glaresCheck = val; + _set({"glaresCheck": val}); + } + + /// Parameters for glares image quality validation. + GlaresCheckParams? get glaresCheckParams => _glaresCheckParams; + GlaresCheckParams? _glaresCheckParams; + set glaresCheckParams(GlaresCheckParams? val) { + _glaresCheckParams = val; + _set({"glaresCheckParams": val?.toJson()}); + } + + /// This option disabled colorness check during performing image quality validation. + bool? get colornessCheck => _colornessCheck; + bool? _colornessCheck; + set colornessCheck(bool? val) { + _colornessCheck = val; + _set({"colornessCheck": val}); + } + + /// This option disabled moire patterns check during performing image quality validation. + bool? get screenCapture => _screenCapture; + bool? _screenCapture; + set screenCapture(bool? val) { + _screenCapture = val; + _set({"screenCapture": val}); + } + + /// This option controls the quality checks that the image should pass + /// in order to be considered a valid input during the scanning process. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get expectedPass => _expectedPass; + List? _expectedPass; + set expectedPass(List? val) { + if (val != null) val = List.unmodifiable(val); + _expectedPass = val; + _set({"expectedPass": val?.map((e) => e.value).toList()}); + } + + /// Specify the minimum indent from the corners of the document to the borders + /// of the image. The value reflects the allowed percentage for the indent + /// relative to the width of the document. If it is detected that the corners + /// of the document are closer than the specified value, the status will contain + /// an error in the `DocumentReaderResults.imageQuality.imageQualityList.result` field. + int? get documentPositionIndent => _documentPositionIndent; + int? _documentPositionIndent; + set documentPositionIndent(int? val) { + _documentPositionIndent = val; + _set({"documentPositionIndent": val}); + } + + /// Set the threshold for an actual document brightness below which the check fails. + double? get brightnessThreshold => _brightnessThreshold; + double? _brightnessThreshold; + set brightnessThreshold(double? val) { + _brightnessThreshold = val; + _set({"brightnessThreshold": val}); + } + + /// This option checks document image occlusion. + bool? get occlusionCheck => _occlusionCheck; + bool? _occlusionCheck; + set occlusionCheck(bool? val) { + _occlusionCheck = val; + _set({"occlusionCheck": val}); + } + + /// Allows you to deserialize object. + static ImageQA fromJson(jsonObject) { + var result = ImageQA(); + result.testSetters = {}; + + result.dpiThreshold = jsonObject["dpiThreshold"]; + result.angleThreshold = jsonObject["angleThreshold"]; + result.focusCheck = jsonObject["focusCheck"]; + result.glaresCheck = jsonObject["glaresCheck"]; + result.colornessCheck = jsonObject["colornessCheck"]; + result.screenCapture = jsonObject["screenCapture"]; + result.expectedPass = ImageQualityCheckType.fromIntList( + jsonObject["expectedPass"], + ); + result.glaresCheckParams = GlaresCheckParams.fromJson( + jsonObject["glaresCheckParams"], + ); + result.documentPositionIndent = jsonObject["documentPositionIndent"]; + result.brightnessThreshold = _toDouble(jsonObject["brightnessThreshold"]); + result.occlusionCheck = jsonObject["occlusionCheck"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "dpiThreshold": dpiThreshold, + "angleThreshold": angleThreshold, + "documentPositionIndent": documentPositionIndent, + "focusCheck": focusCheck, + "glaresCheck": glaresCheck, + "colornessCheck": colornessCheck, + "screenCapture": screenCapture, + "expectedPass": expectedPass?.map((e) => e.value).toList(), + "glaresCheckParams": glaresCheckParams?.toJson(), + "brightnessThreshold": brightnessThreshold, + "occlusionCheck": occlusionCheck, + }.clearNulls(); + + void _set(Map json, {ProcessParams? directParent}) { + var parentJson = {"imageQA": json}; + var parent = DocumentReader.instance.processParams; + if (identical(this, parent.imageQA)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(ProcessParams parent) => _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/process_params/liveness_params.dart b/lib/src/params/process_params/liveness_params.dart new file mode 100644 index 0000000000..cc2d2c3a5e --- /dev/null +++ b/lib/src/params/process_params/liveness_params.dart @@ -0,0 +1,105 @@ +part of "../../../flutter_document_reader_api.dart"; + +class LivenessParams { + bool? get checkOVI => _checkOVI; + bool? _checkOVI; + set checkOVI(bool? val) { + _checkOVI = val; + _set({"checkOVI": val}); + } + + bool? get checkMLI => _checkMLI; + bool? _checkMLI; + set checkMLI(bool? val) { + _checkMLI = val; + _set({"checkMLI": val}); + } + + bool? get checkHolo => _checkHolo; + bool? _checkHolo; + set checkHolo(bool? val) { + _checkHolo = val; + _set({"checkHolo": val}); + } + + bool? get checkED => _checkED; + bool? _checkED; + set checkED(bool? val) { + _checkED = val; + _set({"checkED": val}); + } + + bool? get checkBlackAndWhiteCopy => _checkBlackAndWhiteCopy; + bool? _checkBlackAndWhiteCopy; + set checkBlackAndWhiteCopy(bool? val) { + _checkBlackAndWhiteCopy = val; + _set({"checkBlackAndWhiteCopy": val}); + } + + /// This parameter is used to enable Dynaprint detection. + bool? get checkDynaprint => _checkDynaprint; + bool? _checkDynaprint; + set checkDynaprint(bool? val) { + _checkDynaprint = val; + _set({"checkDynaprint": val}); + } + + bool? get checkGeometry => _checkGeometry; + bool? _checkGeometry; + set checkGeometry(bool? val) { + _checkGeometry = val; + _set({"checkGeometry": val}); + } + + /// This parameter is used to enable Barcode background check as part of the Liveness checks. + bool? get checkBarcodeBackground => _checkBarcodeBackground; + bool? _checkBarcodeBackground; + set checkBarcodeBackground(bool? val) { + _checkBarcodeBackground = val; + _set({"checkBarcodeBackground": val}); + } + + /// Allows you to deserialize object. + static LivenessParams fromJson(jsonObject) { + if (jsonObject == null) return LivenessParams(); + var result = LivenessParams(); + result.testSetters = {}; + + result.checkOVI = jsonObject["checkOVI"]; + result.checkMLI = jsonObject["checkMLI"]; + result.checkHolo = jsonObject["checkHolo"]; + result.checkED = jsonObject["checkED"]; + result.checkBlackAndWhiteCopy = jsonObject["checkBlackAndWhiteCopy"]; + result.checkDynaprint = jsonObject["checkDynaprint"]; + result.checkGeometry = jsonObject["checkGeometry"]; + result.checkBarcodeBackground = jsonObject["checkBarcodeBackground"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "checkOVI": checkOVI, + "checkMLI": checkMLI, + "checkHolo": checkHolo, + "checkED": checkED, + "checkBlackAndWhiteCopy": checkBlackAndWhiteCopy, + "checkDynaprint": checkDynaprint, + "checkGeometry": checkGeometry, + "checkBarcodeBackground": checkBarcodeBackground, + }.clearNulls(); + + void _set(Map json, {AuthenticityParams? directParent}) { + var parentJson = {"livenessParams": json}; + var parent = DocumentReader.instance.processParams.authenticityParams; + if (identical(this, parent.livenessParams)) parent._set(parentJson); + directParent?.testSetters.addAll(parentJson); + testSetters.addAll(json); + } + + void _apply(AuthenticityParams parent) => + _set(toJson(), directParent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/process_params/process_params.dart b/lib/src/params/process_params/process_params.dart new file mode 100644 index 0000000000..7932314f78 --- /dev/null +++ b/lib/src/params/process_params/process_params.dart @@ -0,0 +1,1117 @@ +part of "../../../flutter_document_reader_api.dart"; + +/// Params that influence the scanning process. +class ProcessParams { + /// If set to `true`, processing of more than one page of the document + /// (if they exist) will be triggered, otherwise, only one page will be processed. + bool? get multipageProcessing => _multipageProcessing; + bool? _multipageProcessing; + set multipageProcessing(bool? val) { + _multipageProcessing = val; + _set({"multipageProcessing": val}); + } + + /// If set to `true`, the DocumentReader logs will be shown in the console. + bool? get logs => _logs; + bool? _logs; + set logs(bool? val) { + _logs = val; + _set({"logs": val}); + } + + /// If set to `true`, images will be saved to the application's directory. + bool? get debugSaveImages => _debugSaveImages; + bool? _debugSaveImages; + set debugSaveImages(bool? val) { + _debugSaveImages = val; + _set({"debugSaveImages": val}); + } + + /// If set to `true`, text logs will be saved to the application's directory. + bool? get debugSaveLogs => _debugSaveLogs; + bool? _debugSaveLogs; + set debugSaveLogs(bool? val) { + _debugSaveLogs = val; + _set({"debugSaveLogs": val}); + } + + /// If set to `true`, an original (uncropped) image will be received, + /// which is sent for recognition. + bool? get returnUncroppedImage => _returnUncroppedImage; + bool? _returnUncroppedImage; + set returnUncroppedImage(bool? val) { + _returnUncroppedImage = val; + _set({"returnUncroppedImage": val}); + } + + /// Set to `true` when torch is connected and enabled by user. + /// + /// Android only. + bool? get uvTorchEnabled => _uvTorchEnabled; + bool? _uvTorchEnabled; + set uvTorchEnabled(bool? val) { + _uvTorchEnabled = val; + _set({"uvTorchEnabled": val}); + } + + /// If set to `true`, cropped images will be saved to the application's directory. + bool? get debugSaveCroppedImages => _debugSaveCroppedImages; + bool? _debugSaveCroppedImages; + set debugSaveCroppedImages(bool? val) { + _debugSaveCroppedImages = val; + _set({"debugSaveCroppedImages": val}); + } + + /// If set to `true`, document focus check will be omitted. + bool? get disableFocusingCheck => _disableFocusingCheck; + bool? _disableFocusingCheck; + set disableFocusingCheck(bool? val) { + _disableFocusingCheck = val; + _set({"disableFocusingCheck": val}); + } + + /// If set to `true`, RFID sessions will be saved to the application's directory. + bool? get debugSaveRFIDSession => _debugSaveRFIDSession; + bool? _debugSaveRFIDSession; + set debugSaveRFIDSession(bool? val) { + _debugSaveRFIDSession = val; + _set({"debugSaveRFIDSession": val}); + } + + /// If set to `true`, allows to process up to two pages of the document + /// (so-called "a double-page spread") for one-shot if they are presented + /// on the frame (image). + bool? get doublePageSpread => _doublePageSpread; + bool? _doublePageSpread; + set doublePageSpread(bool? val) { + _doublePageSpread = val; + _set({"doublePageSpread": val}); + } + + /// If set to `true`, allows you to manually set the document's bounds + /// after it is detected. + bool? get manualCrop => _manualCrop; + bool? _manualCrop; + set manualCrop(bool? val) { + _manualCrop = val; + _set({"manualCrop": val}); + } + + /// Allows to build an integral image, taking into account the quality of + /// fixation of each of the individual images. + bool? get integralImage => _integralImage; + bool? _integralImage; + set integralImage(bool? val) { + _integralImage = val; + _set({"integralImage": val}); + } + + /// If set to `true`, an image with cropped barcode will be returned. + bool? get returnCroppedBarcode => _returnCroppedBarcode; + bool? _returnCroppedBarcode; + set returnCroppedBarcode(bool? val) { + _returnCroppedBarcode = val; + _set({"returnCroppedBarcode": val}); + } + + /// If set to `true`, in case required fields are not read, their values + /// will be empty. + bool? get checkRequiredTextFields => _checkRequiredTextFields; + bool? _checkRequiredTextFields; + set checkRequiredTextFields(bool? val) { + _checkRequiredTextFields = val; + _set({"checkRequiredTextFields": val}); + } + + /// If set to `true`, personal information will be removed from logs. + bool? get depersonalizeLog => _depersonalizeLog; + bool? _depersonalizeLog; + set depersonalizeLog(bool? val) { + _depersonalizeLog = val; + _set({"depersonalizeLog": val}); + } + + /// When enabled together with [doublePageSpread] and there is a passport + /// with two pages spread in the image, pages will be cropped, straightened + /// and aligned together, as if the document was captured on a flatbed scanner. + bool? get generateDoublePageSpreadImage => _generateDoublePageSpreadImage; + bool? _generateDoublePageSpreadImage; + set generateDoublePageSpreadImage(bool? val) { + _generateDoublePageSpreadImage = val; + _set({"generateDoublePageSpreadImage": val}); + } + + /// This option can be set to `true` if you know for sure that the image you + /// provide contains already cropped document by its edges. This was designed + /// to process on the server side images captured and cropped on mobile. + bool? get alreadyCropped => _alreadyCropped; + bool? _alreadyCropped; + set alreadyCropped(bool? val) { + _alreadyCropped = val; + _set({"alreadyCropped": val}); + } + + /// When disabled, text field OCR will be done as is and then the recognized + /// value will be matched to the field mask for validity. If enabled, we + /// are trying to read a field value with maximum efforts to match the mask + /// and provide a correctly formatted value, making assumptions based on the + /// provided field mask in the template. + bool? get matchTextFieldMask => _matchTextFieldMask; + bool? _matchTextFieldMask; + set matchTextFieldMask(bool? val) { + _matchTextFieldMask = val; + _set({"matchTextFieldMask": val}); + } + + /// When enabled, fail OCR field validity, if there is a glare over the text + /// ƒfield on the image. + bool? get updateOCRValidityByGlare => _updateOCRValidityByGlare; + bool? _updateOCRValidityByGlare; + set updateOCRValidityByGlare(bool? val) { + _updateOCRValidityByGlare = val; + _set({"updateOCRValidityByGlare": val}); + } + + /// When enabled no graphic fields will be cropped from document image. + bool? get noGraphics => _noGraphics; + bool? _noGraphics; + set noGraphics(bool? val) { + _noGraphics = val; + _set({"noGraphics": val}); + } + + /// This option allows locating and cropping multiple documents + /// from one image if enabled. + bool? get multiDocOnImage => _multiDocOnImage; + bool? _multiDocOnImage; + set multiDocOnImage(bool? val) { + _multiDocOnImage = val; + _set({"multiDocOnImage": val}); + } + + /// When set to `false`, the Barcode code parsing will be skipped + /// and the raw information from the code will be returned instead. + bool? get parseBarcodes => _parseBarcodes; + bool? _parseBarcodes; + set parseBarcodes(bool? val) { + _parseBarcodes = val; + _set({"parseBarcodes": val}); + } + + /// When set to `true`, the `rawResults` property of the [Results] + /// will contain the encrypted containers of scanning results + /// that may be used for later reprocessing. + bool? get shouldReturnPackageForReprocess => _shouldReturnPackageForReprocess; + bool? _shouldReturnPackageForReprocess; + set shouldReturnPackageForReprocess(bool? val) { + _shouldReturnPackageForReprocess = val; + _set({"shouldReturnPackageForReprocess": val}); + } + + /// When enabled, OCR of perforated fields in the document template + /// will not be performed. + bool? get disablePerforationOCR => _disablePerforationOCR; + bool? _disablePerforationOCR; + set disablePerforationOCR(bool? val) { + _disablePerforationOCR = val; + _set({"disablePerforationOCR": val}); + } + + /// When enabled, image quality checks status affects document optical + /// and overall status. + @Deprecated("Use `strictImageQuality` instead.") + bool? get respectImageQuality => _respectImageQuality; + bool? _respectImageQuality; + @Deprecated("Use `strictImageQuality` instead.") + set respectImageQuality(bool? val) { + _respectImageQuality = val; + _set({"respectImageQuality": val}); + } + + /// When enabled, the image quality check status affects the document optical and overall status. + bool? get strictImageQuality => _strictImageQuality; + bool? _strictImageQuality; + set strictImageQuality(bool? val) { + _strictImageQuality = val; + _set({"strictImageQuality": val}); + } + + /// When enabled, the Surname and GivenNames field ([TextField]) + /// will be divided into fields with fieldTypes [FieldType.FIRST_NAME], + /// [FieldType.SECOND_NAME], [FieldType.THIRD_NAME], [FieldType.LAST_NAME]. + bool? get splitNames => _splitNames; + bool? _splitNames; + set splitNames(bool? val) { + _splitNames = val; + _set({"splitNames": val}); + } + + /// Use this property to set up the Face API integration. + bool? get useFaceApi => _useFaceApi; + bool? _useFaceApi; + set useFaceApi(bool? val) { + _useFaceApi = val; + _set({"useFaceApi": val}); + } + + /// This parameter is used to enable document authenticity check. + bool? get useAuthenticityCheck => _useAuthenticityCheck; + bool? _useAuthenticityCheck; + set useAuthenticityCheck(bool? val) { + _useAuthenticityCheck = val; + _set({"useAuthenticityCheck": val}); + } + + @Deprecated("Use `authenticityParams.checkLiveness` instead.") + bool? get checkHologram => _checkHologram; + bool? _checkHologram; + @Deprecated("Use `authenticityParams.checkLiveness` instead.") + set checkHologram(bool? val) { + _checkHologram = val; + _set({"checkHologram": val}); + } + + /// This parameter is used to generate numeric representation for issuing state and nationality codes. + bool? get generateNumericCodes => _generateNumericCodes; + bool? _generateNumericCodes; + set generateNumericCodes(bool? val) { + _generateNumericCodes = val; + _set({"generateNumericCodes": val}); + } + + /// If the certificates required for performing the Digital signature check are missing, + /// this parameter if enabled will make the Barcode format check failed. + bool? get strictBarcodeDigitalSignatureCheck => + _strictBarcodeDigitalSignatureCheck; + bool? _strictBarcodeDigitalSignatureCheck; + set strictBarcodeDigitalSignatureCheck(bool? val) { + _strictBarcodeDigitalSignatureCheck = val; + _set({"strictBarcodeDigitalSignatureCheck": val}); + } + + /// Select the longest value from the different value sources and write it to the value field + /// if comparison is done successfully. The parameter applies this logic to the personal names, + /// such as given name, surname, surname and given name, middle name and etc. + bool? get selectLongestNames => _selectLongestNames; + bool? _selectLongestNames; + set selectLongestNames(bool? val) { + _selectLongestNames = val; + _set({"selectLongestNames": val}); + } + + /// This parameter is used to generate DTCVC data. + bool? get generateDTCVC => _generateDTCVC; + bool? _generateDTCVC; + set generateDTCVC(bool? val) { + _generateDTCVC = val; + _set({"generateDTCVC": val}); + } + + /// Set to force DL categories expiry date status to either valid or not. By default, + /// if the DL category expiry date is correct, its status will be wasNotDone, otherwise error. + bool? get strictDLCategoryExpiry => _strictDLCategoryExpiry; + bool? _strictDLCategoryExpiry; + set strictDLCategoryExpiry(bool? val) { + _strictDLCategoryExpiry = val; + _set({"strictDLCategoryExpiry": val}); + } + + bool? get generateAlpha2Codes => _generateAlpha2Codes; + bool? _generateAlpha2Codes; + set generateAlpha2Codes(bool? val) { + _generateAlpha2Codes = val; + _set({"generateAlpha2Codes": val}); + } + + /// This parameter if enabled will ignore the minimum barcode resolution needed to start processing. + bool? get disableAuthResolutionFilter => _disableAuthResolutionFilter; + bool? _disableAuthResolutionFilter; + set disableAuthResolutionFilter(bool? val) { + _disableAuthResolutionFilter = val; + _set({"disableAuthResolutionFilter": val}); + } + + /// When enabled, this parameter marks security checks that don’t meet minimum requirements as 'Failed' (instead of 'WasNotDone'), which causes the overall security status to be 'Failed'. + bool? get strictSecurityChecks => _strictSecurityChecks; + bool? _strictSecurityChecks; + set strictSecurityChecks(bool? val) { + _strictSecurityChecks = val; + _set({"strictSecurityChecks": val}); + } + + /// Allows transliteration to be turned on or off. + /// Default: `true`. + bool? get returnTransliteratedFields => _returnTransliteratedFields; + bool? _returnTransliteratedFields; + set returnTransliteratedFields(bool? val) { + _returnTransliteratedFields = val; + _set({"returnTransliteratedFields": val}); + } + + bool? get checkCaptureProcessIntegrity => _checkCaptureProcessIntegrity; + bool? _checkCaptureProcessIntegrity; + set checkCaptureProcessIntegrity(bool? val) { + _checkCaptureProcessIntegrity = val; + _set({"checkCaptureProcessIntegrity": val}); + } + + /// When disabled, date of expiry doesn't affect the mrz and text statuses. + bool? get strictExpiryDate => _strictExpiryDate; + bool? _strictExpiryDate; + set strictExpiryDate(bool? val) { + _strictExpiryDate = val; + _set({"strictExpiryDate": val}); + } + + bool? get debugSaveBinarySession => _debugSaveBinarySession; + bool? _debugSaveBinarySession; + set debugSaveBinarySession(bool? val) { + _debugSaveBinarySession = val; + _set({"debugSaveBinarySession": val}); + } + + /// This parameter is used to enable Visible Digital Seal check. + bool? get checkVDS => _checkVDS; + bool? _checkVDS; + set checkVDS(bool? val) { + _checkVDS = val; + _set({"checkVDS": val}); + } + + /// When enabled, the age check status affects the overall status. + bool? get strictAgeCheck => _strictAgeCheck; + bool? _strictAgeCheck; + set strictAgeCheck(bool? val) { + _strictAgeCheck = val; + _set({"strictAgeCheck": val}); + } + + /// There are documents that contain barcodes which data can be parsed only + /// if document type verification is performed. The following property allows + /// setting the barcode parser type which should be used during recognition. + /// It allows parsing barcode data without performing document type verification. + int? get barcodeParserType => _barcodeParserType; + int? _barcodeParserType; + set barcodeParserType(int? val) { + _barcodeParserType = val; + _set({"barcodeParserType": val}); + } + + /// Allows you to set the maximum value of the deviation of the corners + /// of the document from the value of `90` degrees. + @Deprecated("since 7.6") + int? get perspectiveAngle => _perspectiveAngle; + int? _perspectiveAngle; + set perspectiveAngle(int? val) { + _perspectiveAngle = val; + _set({"perspectiveAngle": val}); + } + + /// Allows you to set the minimum acceptable DPI value of the camera frame + /// that is passed for recognition. Camera frames the DPI of which are less + /// than you set won't be passed for recognition. + int? get minDPI => _minDPI; + int? _minDPI; + set minDPI(int? val) { + _minDPI = val; + _set({"minDPI": val}); + } + + /// This option controls maximum resolution in dpi of output images. + /// Resolution will remain original in case `0` is set. + int? get imageDpiOutMax => _imageDpiOutMax; + int? _imageDpiOutMax; + set imageDpiOutMax(int? val) { + _imageDpiOutMax = val; + _set({"imageDpiOutMax": val}); + } + + /// Force use of specified document format when locating and recognizing + /// document to reduce the number of candidates. + DocFormat? get forceDocFormat => _forceDocFormat; + DocFormat? _forceDocFormat; + set forceDocFormat(DocFormat? val) { + _forceDocFormat = val; + _set({"forceDocFormat": val?.value}); + } + + /// This option allows shifting the date of expiry into the future or past + /// for number of months specified. This is useful, for example, in some cases + /// when document might be still valid for some period after original + /// expiration date to prevent negative validity status for such documents. + /// Or by shifting the date to the past will set negative validity + /// for the documents that is about to expire in a specified number of months. + int? get shiftExpiryDate => _shiftExpiryDate; + int? _shiftExpiryDate; + set shiftExpiryDate(int? val) { + _shiftExpiryDate = val; + _set({"shiftExpiryDate": val}); + } + + /// This options allows specifying the minimal age in years of the document + /// holder for the document to be considered valid. + int? get minimalHolderAge => _minimalHolderAge; + int? _minimalHolderAge; + set minimalHolderAge(int? val) { + _minimalHolderAge = val; + _set({"minimalHolderAge": val}); + } + + /// Maximum height of output images. In pixels. + int? get imageOutputMaxHeight => _imageOutputMaxHeight; + int? _imageOutputMaxHeight; + set imageOutputMaxHeight(int? val) { + _imageOutputMaxHeight = val; + _set({"imageOutputMaxHeight": val}); + } + + /// Maximum width of output images. In pixels. + int? get imageOutputMaxWidth => _imageOutputMaxWidth; + int? _imageOutputMaxWidth; + set imageOutputMaxWidth(int? val) { + _imageOutputMaxWidth = val; + _set({"imageOutputMaxWidth": val}); + } + + /// Accepts sum of [Authenticity] values. + int? get processAuth => _processAuth; + int? _processAuth; + set processAuth(int? val) { + _processAuth = val; + _set({"processAuth": val}); + } + + /// This option allows output text case transformation. + /// No changes applied by default to original values. + int? get convertCase => _convertCase; + int? _convertCase; + set convertCase(int? val) { + _convertCase = val; + _set({"convertCase": val}); + } + + /// Sets the level of logs detalization when used together with [logs] parameter. + LogLevel? get logLevel => _logLevel; + LogLevel? _logLevel; + set logLevel(LogLevel? val) { + _logLevel = val; + _set({"logLevel": val?.value}); + } + + /// Make better MRZ detection on complex noisy backgrounds, like BW photocopy of some documents. + /// Works only in the single-frame processing. + MrzDetectionModes? get mrzDetectMode => _mrzDetectMode; + MrzDetectionModes? _mrzDetectMode; + set mrzDetectMode(MrzDetectionModes? val) { + _mrzDetectMode = val; + _set({"mrzDetectMode": val?.value}); + } + + /// Measure system of fields' values that are presented in results. + /// Default: If the country code is `US` or `LR` or `MM`, the + /// [MeasureSystem.IMPERIAL] system of measurement, otherwise, the [MeasureSystem.METRIC]. + MeasureSystem? get measureSystem => _measureSystem; + MeasureSystem? _measureSystem; + set measureSystem(MeasureSystem? val) { + _measureSystem = val; + _set({"measureSystem": val?.value}); + } + + /// Force use of specific template ID and skip document type identification step. + int? get forceDocID => _forceDocID; + int? _forceDocID; + set forceDocID(int? val) { + _forceDocID = val; + _set({"forceDocID": val}); + } + + /// Maximum number of pages to be processed in a PDF document. + /// If set, only the specified number of pages will be analyzed. + int? get pdfPagesLimit => _pdfPagesLimit; + int? _pdfPagesLimit; + set pdfPagesLimit(int? val) { + _pdfPagesLimit = val; + _set({"pdfPagesLimit": val}); + } + + /// Change the format string of displayed dates in the results. + /// + /// Mask examples: `dd/mm/yyyy`, `mm/dd/yyyy`, `dd-mm-yyyy`, `mm-dd-yyyy`, `dd/mm/yy`. + /// Set to `null` to revert default value. + /// + /// Default: depends on the device's locale. + String? get dateFormat => _dateFormat; + String? _dateFormat; + set dateFormat(String? val) { + _dateFormat = val; + _set({"dateFormat": val}); + } + + /// Documents processing scenario. + Scenario? get scenario => _scenario; + Scenario? _scenario; + set scenario(Scenario? val) { + _scenario = val; + _set({"scenario": val?.value}); + } + + /// Documents processing scenario for the Capture button. + Scenario? get captureButtonScenario => _captureButtonScenario; + Scenario? _captureButtonScenario; + set captureButtonScenario(Scenario? val) { + _captureButtonScenario = val; + _set({"captureButtonScenario": val?.value}); + } + + /// Allows you to set the time limit for document recognition (in seconds), + /// beyond which the recognition does not continue regardless of its result. + /// The countdown starts from the moment the scenario starts. + /// Setting value to `0` means infinity. + double? get timeout => _timeout; + double? _timeout; + set timeout(double? val) { + _timeout = val; + _set({"timeout": val}); + } + + /// Allows you to set the time limit for document recognition (in seconds), + /// beyond which the recognition does not continue regardless of its result. + /// The countdown starts from the moment the document is detected. + /// Setting value to `0` means infinity. + double? get timeoutFromFirstDetect => _timeoutFromFirstDetect; + double? _timeoutFromFirstDetect; + set timeoutFromFirstDetect(double? val) { + _timeoutFromFirstDetect = val; + _set({"timeoutFromFirstDetect": val}); + } + + /// Allows you to set the time limit for document recognition (in seconds), + /// beyond which the recognition does not continue regardless of its result. + /// The countdown starts from the moment the document type is recognized. + /// Setting value to `0` means infinity. + double? get timeoutFromFirstDocType => _timeoutFromFirstDocType; + double? _timeoutFromFirstDocType; + set timeoutFromFirstDocType(double? val) { + _timeoutFromFirstDocType = val; + _set({"timeoutFromFirstDocType": val}); + } + + /// Specifies minimal area of the image that document should cover to be treated + /// as candidate when locating. Value should be in range from `0` to `1`, + /// where `1` is when document should fully cover the image. + double? get documentAreaMin => _documentAreaMin; + double? _documentAreaMin; + set documentAreaMin(double? val) { + _documentAreaMin = val; + _set({"documentAreaMin": val}); + } + + /// Start the countdown from the moment the document liveness authenticity check is started (in seconds). + /// Setting value to `0` means infinity. + double? get timeoutLiveness => _timeoutLiveness; + double? _timeoutLiveness; + set timeoutLiveness(double? val) { + _timeoutLiveness = val; + _set({"timeoutLiveness": val}); + } + + /// Takes the list of the document IDs to process. + /// All documents will be processed if it's empty. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get documentIDList => _documentIDList; + List? _documentIDList; + set documentIDList(List? val) { + if (val != null) val = List.unmodifiable(val); + _documentIDList = val; + _set({"documentIDList": val}); + } + + /// Set types of barcodes that you wish to recognize. + /// All barcodes will be recognized if it's empty. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get barcodeTypes => _barcodeTypes; + List? _barcodeTypes; + set barcodeTypes(List? val) { + if (val != null) val = List.unmodifiable(val); + _barcodeTypes = val; + _set({"barcodeTypes": val?.map((e) => e.value).toList()}); + } + + /// If you recognize the MRZ of documents, all fields will be extracted. + /// If you recognize the Visual zone of documents, you can set the list + /// of field types that you wish to extract, other fields will be skipped + /// during processing. All fields will be extracted if it is empty. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get fieldTypesFilter => _fieldTypesFilter; + List? _fieldTypesFilter; + set fieldTypesFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _fieldTypesFilter = val; + _set({"fieldTypesFilter": val?.map((e) => e.value).toList()}); + } + + /// Types of results to return in response. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get resultTypeOutput => _resultTypeOutput; + List? _resultTypeOutput; + set resultTypeOutput(List? val) { + if (val != null) val = List.unmodifiable(val); + _resultTypeOutput = val; + _set({"resultTypeOutput": val?.map((e) => e.value).toList()}); + } + + /// This option allows limiting MRZ formats to be recognized by specifying + /// them in array. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get mrzFormatsFilter => _mrzFormatsFilter; + List? _mrzFormatsFilter; + set mrzFormatsFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _mrzFormatsFilter = val; + _set({"mrzFormatsFilter": val?.map((e) => e.value).toList()}); + } + + /// Array of specific eligible document types to recognize from. You may, + /// for example, specify only passports to be recognized by setting this property. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get documentGroupFilter => _documentGroupFilter; + List? _documentGroupFilter; + set documentGroupFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _documentGroupFilter = val; + _set({"documentGroupFilter": val?.map((e) => e.value).toList()}); + } + + /// The list of LCID types to ignore during the recognition. + /// If empty, values with all LCID types will be extracted. + /// Narrowing down the list can reduce processing time. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get lcidIgnoreFilter => _lcidIgnoreFilter; + List? _lcidIgnoreFilter; + set lcidIgnoreFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _lcidIgnoreFilter = val; + _set({"lcidIgnoreFilter": val?.map((e) => e.value).toList()}); + } + + /// The whitelist of LCID types to use during the recognition. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get lcidFilter => _lcidFilter; + List? _lcidFilter; + set lcidFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _lcidFilter = val; + _set({"lcidFilter": val?.map((e) => e.value).toList()}); + } + + /// If a document contains a Visual zone, you can specify a list of field types that should be excluded from extraction. + /// All field types listed in this array are skipped during processing, while the remaining fields are recognized. + /// This filter is not applicable to the MRZ, barcode or RFID. If the fieldTypesIgnoreFilter is empty, all fields are extracted. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + List? get fieldTypesIgnoreFilter => _fieldTypesIgnoreFilter; + List? _fieldTypesIgnoreFilter; + set fieldTypesIgnoreFilter(List? val) { + if (val != null) val = List.unmodifiable(val); + _fieldTypesIgnoreFilter = val; + _set({"fieldTypesIgnoreFilter": val?.map((e) => e.value).toList()}); + } + + /// Controls properties of [ImageQA] checks. + ImageQA get imageQA => _imageQA; + ImageQA _imageQA = ImageQA(); + set imageQA(ImageQA val) { + (_imageQA = val)._apply(this); + } + + /// Custom RFID params. + RFIDParams? get rfidParams => _rfidParams; + RFIDParams? _rfidParams; + set rfidParams(RFIDParams? val) { + _rfidParams = val; + _set({"rfidParams": val?.toJson()}); + } + + /// Custom Face API integration params. + FaceApiParams? get faceApiParams => _faceApiParams; + FaceApiParams? _faceApiParams; + set faceApiParams(FaceApiParams? val) { + _faceApiParams = val; + _set({"faceApiParams": val?.toJson()}); + } + + /// Set up the backend processing service parameters. + BackendProcessingConfig? get backendProcessingConfig => + _backendProcessingConfig; + BackendProcessingConfig? _backendProcessingConfig; + set backendProcessingConfig(BackendProcessingConfig? val) { + _backendProcessingConfig = val; + _set({"backendProcessingConfig": val?.toJson()}); + } + + Bsi? get bsiTr03135 => _bsiTr03135; + Bsi? _bsiTr03135; + set bsiTr03135(Bsi? val) { + _bsiTr03135 = val; + _set({"bsiTr03135": val?.toJson()}); + } + + AuthenticityParams get authenticityParams => _authenticityParams; + AuthenticityParams _authenticityParams = AuthenticityParams(); + set authenticityParams(AuthenticityParams val) { + (_authenticityParams = val)._apply(this); + } + + /// Takes JSON with parameters that are not presented in the DocumentReader. + /// + /// Unmodifiable property. Use setter instead of `.remove()`, `.addAll()`, etc. + Map? get customParams => _customParams; + Map? _customParams; + set customParams(Map? val) { + if (val != null) val = Map.unmodifiable(val); + _customParams = val; + _set({"customParams": val}); + } + + /// Allows you to deserialize object. + static ProcessParams fromJson(jsonObject) { + var result = ProcessParams(); + result.testSetters = {}; + + result.multipageProcessing = jsonObject["multipageProcessing"]; + result.logs = jsonObject["logs"]; + result.debugSaveImages = jsonObject["debugSaveImages"]; + result.debugSaveLogs = jsonObject["debugSaveLogs"]; + result.returnUncroppedImage = jsonObject["returnUncroppedImage"]; + result.uvTorchEnabled = jsonObject["uvTorchEnabled"]; + result.debugSaveCroppedImages = jsonObject["debugSaveCroppedImages"]; + result.disableFocusingCheck = jsonObject["disableFocusingCheck"]; + result.debugSaveRFIDSession = jsonObject["debugSaveRFIDSession"]; + result.doublePageSpread = jsonObject["doublePageSpread"]; + result.manualCrop = jsonObject["manualCrop"]; + result.integralImage = jsonObject["integralImage"]; + result.returnCroppedBarcode = jsonObject["returnCroppedBarcode"]; + result.checkRequiredTextFields = jsonObject["checkRequiredTextFields"]; + result.depersonalizeLog = jsonObject["depersonalizeLog"]; + result.generateDoublePageSpreadImage = + jsonObject["generateDoublePageSpreadImage"]; + result.alreadyCropped = jsonObject["alreadyCropped"]; + result.matchTextFieldMask = jsonObject["matchTextFieldMask"]; + result.updateOCRValidityByGlare = jsonObject["updateOCRValidityByGlare"]; + result.noGraphics = jsonObject["noGraphics"]; + result.multiDocOnImage = jsonObject["multiDocOnImage"]; + result.parseBarcodes = jsonObject["parseBarcodes"]; + result.shouldReturnPackageForReprocess = + jsonObject["shouldReturnPackageForReprocess"]; + result.disablePerforationOCR = jsonObject["disablePerforationOCR"]; + result.respectImageQuality = jsonObject["respectImageQuality"]; + result.strictImageQuality = jsonObject["strictImageQuality"]; + result.splitNames = jsonObject["splitNames"]; + result.useFaceApi = jsonObject["useFaceApi"]; + result.useAuthenticityCheck = jsonObject["useAuthenticityCheck"]; + result.checkHologram = jsonObject["checkHologram"]; + result.generateNumericCodes = jsonObject["generateNumericCodes"]; + result.strictBarcodeDigitalSignatureCheck = + jsonObject["strictBarcodeDigitalSignatureCheck"]; + result.selectLongestNames = jsonObject["selectLongestNames"]; + result.generateDTCVC = jsonObject["generateDTCVC"]; + result.strictDLCategoryExpiry = jsonObject["strictDLCategoryExpiry"]; + result.generateAlpha2Codes = jsonObject["generateAlpha2Codes"]; + result.disableAuthResolutionFilter = + jsonObject["disableAuthResolutionFilter"]; + result.strictSecurityChecks = jsonObject["strictSecurityChecks"]; + result.returnTransliteratedFields = + jsonObject["returnTransliteratedFields"]; + result.checkCaptureProcessIntegrity = + jsonObject["checkCaptureProcessIntegrity"]; + result.strictExpiryDate = jsonObject["strictExpiryDate"]; + result.debugSaveBinarySession = jsonObject["debugSaveBinarySession"]; + result.checkVDS = jsonObject["checkVDS"]; + result.strictAgeCheck = jsonObject["strictAgeCheck"]; + + result.measureSystem = MeasureSystem.getByValue( + jsonObject["measureSystem"], + ); + result.barcodeParserType = jsonObject["barcodeParserType"]; + result.perspectiveAngle = jsonObject["perspectiveAngle"]; + result.minDPI = jsonObject["minDPI"]; + result.imageDpiOutMax = jsonObject["imageDpiOutMax"]; + result.forceDocID = jsonObject["forceDocID"]; + result.pdfPagesLimit = jsonObject["pdfPagesLimit"]; + result.forceDocFormat = DocFormat.getByValue(jsonObject["forceDocFormat"]); + result.shiftExpiryDate = jsonObject["shiftExpiryDate"]; + result.minimalHolderAge = jsonObject["minimalHolderAge"]; + result.imageOutputMaxHeight = jsonObject["imageOutputMaxHeight"]; + result.imageOutputMaxWidth = jsonObject["imageOutputMaxWidth"]; + result.processAuth = jsonObject["processAuth"]; + result.convertCase = jsonObject["convertCase"]; + result.logLevel = LogLevel.getByValue(jsonObject["logLevel"]); + result.mrzDetectMode = MrzDetectionModes.getByValue( + jsonObject["mrzDetectMode"], + ); + + result.dateFormat = jsonObject["dateFormat"]; + result.scenario = Scenario.getByValue(jsonObject["scenario"]); + result.captureButtonScenario = Scenario.getByValue( + jsonObject["captureButtonScenario"], + ); + + result.timeout = _toDouble(jsonObject["timeout"]); + result.timeoutFromFirstDetect = _toDouble( + jsonObject["timeoutFromFirstDetect"], + ); + result.timeoutFromFirstDocType = _toDouble( + jsonObject["timeoutFromFirstDocType"], + ); + result.documentAreaMin = _toDouble(jsonObject["documentAreaMin"]); + result.timeoutLiveness = _toDouble(jsonObject["timeoutLiveness"]); + + result.documentIDList = _intListFrom(jsonObject["documentIDList"]); + result.barcodeTypes = BarcodeType.fromIntList(jsonObject["barcodeTypes"]); + + result.fieldTypesFilter = FieldType.fromIntList( + jsonObject["fieldTypesFilter"], + ); + result.resultTypeOutput = ResultType.fromIntList( + jsonObject["resultTypeOutput"], + ); + result.mrzFormatsFilter = MRZFormat.fromStringList( + jsonObject["mrzFormatsFilter"], + ); + result.documentGroupFilter = DocType.fromIntList( + jsonObject["documentGroupFilter"], + ); + result.lcidIgnoreFilter = LCID.fromIntList(jsonObject["lcidIgnoreFilter"]); + result.lcidFilter = LCID.fromIntList(jsonObject["lcidFilter"]); + result.fieldTypesIgnoreFilter = + FieldType.fromIntList(jsonObject["fieldTypesIgnoreFilter"]); + + result.imageQA = ImageQA.fromJson(jsonObject["imageQA"]); + result.rfidParams = RFIDParams.fromJson(jsonObject["rfidParams"]); + result.faceApiParams = FaceApiParams.fromJson(jsonObject["faceApiParams"]); + result.backendProcessingConfig = BackendProcessingConfig.fromJson( + jsonObject["backendProcessingConfig"], + ); + result.bsiTr03135 = Bsi.fromJson(jsonObject["bsiTr03135"]); + result.authenticityParams = AuthenticityParams.fromJson( + jsonObject["authenticityParams"], + ); + + result.customParams = jsonObject["customParams"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "multipageProcessing": multipageProcessing, + "debugSaveImages": debugSaveImages, + "debugSaveLogs": debugSaveLogs, + "returnUncroppedImage": returnUncroppedImage, + "uvTorchEnabled": uvTorchEnabled, + "debugSaveCroppedImages": debugSaveCroppedImages, + "disableFocusingCheck": disableFocusingCheck, + "debugSaveRFIDSession": debugSaveRFIDSession, + "doublePageSpread": doublePageSpread, + "manualCrop": manualCrop, + "integralImage": integralImage, + "returnCroppedBarcode": returnCroppedBarcode, + "checkRequiredTextFields": checkRequiredTextFields, + "depersonalizeLog": depersonalizeLog, + "generateDoublePageSpreadImage": generateDoublePageSpreadImage, + "alreadyCropped": alreadyCropped, + "matchTextFieldMask": matchTextFieldMask, + "updateOCRValidityByGlare": updateOCRValidityByGlare, + "noGraphics": noGraphics, + "multiDocOnImage": multiDocOnImage, + "parseBarcodes": parseBarcodes, + "shouldReturnPackageForReprocess": shouldReturnPackageForReprocess, + "disablePerforationOCR": disablePerforationOCR, + "respectImageQuality": respectImageQuality, + "strictImageQuality": strictImageQuality, + "splitNames": splitNames, + "useFaceApi": useFaceApi, + "useAuthenticityCheck": useAuthenticityCheck, + "checkHologram": checkHologram, + "generateNumericCodes": generateNumericCodes, + "strictBarcodeDigitalSignatureCheck": + strictBarcodeDigitalSignatureCheck, + "selectLongestNames": selectLongestNames, + "generateDTCVC": generateDTCVC, + "strictDLCategoryExpiry": strictDLCategoryExpiry, + "generateAlpha2Codes": generateAlpha2Codes, + "disableAuthResolutionFilter": disableAuthResolutionFilter, + "strictSecurityChecks": strictSecurityChecks, + "returnTransliteratedFields": returnTransliteratedFields, + "checkCaptureProcessIntegrity": checkCaptureProcessIntegrity, + "strictExpiryDate": strictExpiryDate, + "debugSaveBinarySession": debugSaveBinarySession, + "checkVDS": checkVDS, + "strictAgeCheck": strictAgeCheck, + "measureSystem": measureSystem?.value, + "barcodeParserType": barcodeParserType, + "perspectiveAngle": perspectiveAngle, + "minDPI": minDPI, + "imageDpiOutMax": imageDpiOutMax, + "forceDocID": forceDocID, + "pdfPagesLimit": pdfPagesLimit, + "forceDocFormat": forceDocFormat?.value, + "shiftExpiryDate": shiftExpiryDate, + "minimalHolderAge": minimalHolderAge, + "imageOutputMaxHeight": imageOutputMaxHeight, + "imageOutputMaxWidth": imageOutputMaxWidth, + "processAuth": processAuth, + "convertCase": convertCase, + "logLevel": logLevel?.value, + "mrzDetectMode": mrzDetectMode?.value, + "dateFormat": dateFormat, + "scenario": scenario?.value, + "captureButtonScenario": captureButtonScenario?.value, + "timeout": timeout, + "timeoutFromFirstDetect": timeoutFromFirstDetect, + "timeoutFromFirstDocType": timeoutFromFirstDocType, + "documentAreaMin": documentAreaMin, + "timeoutLiveness": timeoutLiveness, + "documentIDList": documentIDList, + "barcodeTypes": barcodeTypes?.map((e) => e.value).toList(), + "fieldTypesFilter": fieldTypesFilter?.map((e) => e.value).toList(), + "resultTypeOutput": resultTypeOutput?.map((e) => e.value).toList(), + "mrzFormatsFilter": mrzFormatsFilter?.map((e) => e.value).toList(), + "documentGroupFilter": + documentGroupFilter?.map((e) => e.value).toList(), + "lcidIgnoreFilter": lcidIgnoreFilter?.map((e) => e.value).toList(), + "lcidFilter": lcidFilter?.map((e) => e.value).toList(), + "fieldTypesIgnoreFilter": + fieldTypesIgnoreFilter?.map((e) => e.value).toList(), + "imageQA": imageQA.toJson(), + "rfidParams": rfidParams?.toJson(), + "faceApiParams": faceApiParams?.toJson(), + "backendProcessingConfig": backendProcessingConfig?.toJson(), + "bsiTr03135": bsiTr03135?.toJson(), + "authenticityParams": authenticityParams.toJson(), + "customParams": customParams, + }.clearNulls(); + + void _set(Map json) { + if (identical(this, DocumentReader.instance.processParams)) { + _bridge.invokeMethod("setProcessParams", [json]); + } + testSetters.addAll(json); + } + + void _apply() => _set(toJson()); + + @visibleForTesting + Map testSetters = {}; +} + +/// The constants of the enumeration identify the system +/// for measuring distances and weight. +enum MeasureSystem { + /// The Metric System of Measurement, which uses the measuring units + /// such as meters and grams and adds prefixes like kilo, milli + /// and centi to count orders of magnitude. + METRIC(0), + + /// The Imperial System of Measurement, where things are measured in feet, + /// inches and pounds. + IMPERIAL(1); + + const MeasureSystem(this.value); + final int value; + + static MeasureSystem? getByValue(int? i) { + if (i == null) return null; + return MeasureSystem.values.firstWhere((x) => x.value == i); + } +} + +enum MRZFormat { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(""), + + FORMAT_1X30("1x30"), + + FORMAT_3X30("3x30"), + + FORMAT_2X36("2x36"), + + FORMAT_2X44("2x44"), + + FORMAT_1X6("1x6"), + + FORMAT_2X30("2x30"); + + const MRZFormat(this.value); + final String value; + + static MRZFormat? getByValue(String? i) { + if (i == null) return null; + try { + return MRZFormat.values.firstWhere((x) => x.value == i); + } catch (_) { + return MRZFormat.UNKNOWN; + } + } + + static List? fromStringList(List? input) { + if (input == null) return null; + List list = []; + for (String item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} + +enum LogLevel { + /// Fatal error. + FatalError("FatalError"), + + /// Error. + Error("Error"), + + /// Warning. + Warning("Warning"), + + /// Info. + Info("Info"), + + /// Debug. + Debug("Debug"); + + const LogLevel(this.value); + final String value; + + static LogLevel? getByValue(String? i) { + if (i == null) return null; + try { + return LogLevel.values.firstWhere((x) => x.value == i); + } catch (_) { + return null; + } + } +} + +/// Enumeration contains the types of barcodes that can be processed. +enum MrzDetectionModes { + DEFAULT(0), + RESIZE_BINARIZE_WINDOW(1), + BLUR_BEFORE_BINARIZATION(2); + + const MrzDetectionModes(this.value); + final int value; + + static MrzDetectionModes? getByValue(int? i) { + if (i == null) return null; + return MrzDetectionModes.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/params/process_params/rfid_params.dart b/lib/src/params/process_params/rfid_params.dart new file mode 100644 index 0000000000..84af35f14f --- /dev/null +++ b/lib/src/params/process_params/rfid_params.dart @@ -0,0 +1,33 @@ +// +// RfidParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class RFIDParams { + /// A list of notification codes that should be ignored during + /// passive authentication (PA). + List? get paIgnoreNotificationCodes => _paIgnoreNotificationCodes; + List? _paIgnoreNotificationCodes; + + RFIDParams({List? paIgnoreNotificationCodes}) + : _paIgnoreNotificationCodes = paIgnoreNotificationCodes; + + /// Allows you to deserialize object. + static RFIDParams? fromJson(jsonObject) { + if (jsonObject == null) return null; + return RFIDParams( + paIgnoreNotificationCodes: _intListFrom( + jsonObject["paIgnoreNotificationCodes"], + ), + ); + } + + /// Allows you to serialize object. + Map toJson() => + {"paIgnoreNotificationCodes": paIgnoreNotificationCodes}.clearNulls(); +} diff --git a/lib/src/params/rfid_scenario/dtc_data_groups.dart b/lib/src/params/rfid_scenario/dtc_data_groups.dart new file mode 100644 index 0000000000..c8594cb2aa --- /dev/null +++ b/lib/src/params/rfid_scenario/dtc_data_groups.dart @@ -0,0 +1,76 @@ +part of "../../../flutter_document_reader_api.dart"; + +class DTCDataGroup { + bool get dg17 => _dg17; + bool _dg17 = true; + set dg17(bool val) { + _dg17 = val; + _set({"DG17": val}); + } + + bool get dg18 => _dg18; + bool _dg18 = true; + set dg18(bool val) { + _dg18 = val; + _set({"DG18": val}); + } + + bool get dg22 => _dg22; + bool _dg22 = true; + set dg22(bool val) { + _dg22 = val; + _set({"DG22": val}); + } + + bool get dg23 => _dg23; + bool _dg23 = true; + set dg23(bool val) { + _dg23 = val; + _set({"DG23": val}); + } + + bool get dg24 => _dg24; + bool _dg24 = true; + set dg24(bool val) { + _dg24 = val; + _set({"DG24": val}); + } + + /// Allows you to deserialize object. + static DTCDataGroup fromJson(jsonObject) { + var result = DTCDataGroup(); + result.testSetters = {}; + + result.dg17 = jsonObject["DG17"]; + result.dg18 = jsonObject["DG18"]; + result.dg22 = jsonObject["DG22"]; + result.dg23 = jsonObject["DG23"]; + result.dg24 = jsonObject["DG24"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "DG17": dg17, + "DG18": dg18, + "DG22": dg22, + "DG23": dg23, + "DG24": dg24, + }.clearNulls(); + + void _set(Map json, {RFIDScenario? parent}) { + var rfidScenarioJson = {"dtcDataGroups": json}; + var rfidScenario = DocumentReader.instance.rfidScenario; + if (identical(this, rfidScenario.dtcDataGroups)) { + rfidScenario._set(rfidScenarioJson); + } + parent?.testSetters.addAll(rfidScenarioJson); + testSetters.addAll(json); + } + + void _apply(RFIDScenario parent) => _set(toJson(), parent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/rfid_scenario/e_passport_data_groups.dart b/lib/src/params/rfid_scenario/e_passport_data_groups.dart new file mode 100644 index 0000000000..2a09b528bf --- /dev/null +++ b/lib/src/params/rfid_scenario/e_passport_data_groups.dart @@ -0,0 +1,183 @@ +// +// EPassportDataGroups.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class EPassportDataGroups { + bool get dg1 => _dg1; + bool _dg1 = true; + set dg1(bool val) { + _dg1 = val; + _set({"DG1": val}); + } + + bool get dg2 => _dg2; + bool _dg2 = true; + set dg2(bool val) { + _dg2 = val; + _set({"DG2": val}); + } + + bool get dg3 => _dg3; + bool _dg3 = false; + set dg3(bool val) { + _dg3 = val; + _set({"DG3": val}); + } + + bool get dg4 => _dg4; + bool _dg4 = false; + set dg4(bool val) { + _dg4 = val; + _set({"DG4": val}); + } + + bool get dg5 => _dg5; + bool _dg5 = true; + set dg5(bool val) { + _dg5 = val; + _set({"DG5": val}); + } + + bool get dg6 => _dg6; + bool _dg6 = false; + set dg6(bool val) { + _dg6 = val; + _set({"DG6": val}); + } + + bool get dg7 => _dg7; + bool _dg7 = true; + set dg7(bool val) { + _dg7 = val; + _set({"DG7": val}); + } + + bool get dg8 => _dg8; + bool _dg8 = false; + set dg8(bool val) { + _dg8 = val; + _set({"DG8": val}); + } + + bool get dg9 => _dg9; + bool _dg9 = false; + set dg9(bool val) { + _dg9 = val; + _set({"DG9": val}); + } + + bool get dg10 => _dg10; + bool _dg10 = false; + set dg10(bool val) { + _dg10 = val; + _set({"DG10": val}); + } + + bool get dg11 => _dg11; + bool _dg11 = true; + set dg11(bool val) { + _dg11 = val; + _set({"DG11": val}); + } + + bool get dg12 => _dg12; + bool _dg12 = true; + set dg12(bool val) { + _dg12 = val; + _set({"DG12": val}); + } + + bool get dg13 => _dg13; + bool _dg13 = true; + set dg13(bool val) { + _dg13 = val; + _set({"DG13": val}); + } + + bool get dg14 => _dg14; + bool _dg14 = true; + set dg14(bool val) { + _dg14 = val; + _set({"DG14": val}); + } + + bool get dg15 => _dg15; + bool _dg15 = true; + set dg15(bool val) { + _dg15 = val; + _set({"DG15": val}); + } + + bool get dg16 => _dg16; + bool _dg16 = false; + set dg16(bool val) { + _dg16 = val; + _set({"DG16": val}); + } + + /// Allows you to deserialize object. + static EPassportDataGroups fromJson(jsonObject) { + var result = EPassportDataGroups(); + result.testSetters = {}; + + result.dg1 = jsonObject["DG1"]; + result.dg2 = jsonObject["DG2"]; + result.dg3 = jsonObject["DG3"]; + result.dg4 = jsonObject["DG4"]; + result.dg5 = jsonObject["DG5"]; + result.dg6 = jsonObject["DG6"]; + result.dg7 = jsonObject["DG7"]; + result.dg8 = jsonObject["DG8"]; + result.dg9 = jsonObject["DG9"]; + result.dg10 = jsonObject["DG10"]; + result.dg11 = jsonObject["DG11"]; + result.dg12 = jsonObject["DG12"]; + result.dg13 = jsonObject["DG13"]; + result.dg14 = jsonObject["DG14"]; + result.dg15 = jsonObject["DG15"]; + result.dg16 = jsonObject["DG16"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "DG1": dg1, + "DG2": dg2, + "DG3": dg3, + "DG4": dg4, + "DG5": dg5, + "DG6": dg6, + "DG7": dg7, + "DG8": dg8, + "DG9": dg9, + "DG10": dg10, + "DG11": dg11, + "DG12": dg12, + "DG13": dg13, + "DG14": dg14, + "DG15": dg15, + "DG16": dg16, + }.clearNulls(); + + void _set(Map json, {RFIDScenario? parent}) { + var rfidScenarioJson = {"ePassportDataGroups": json}; + var rfidScenario = DocumentReader.instance.rfidScenario; + if (identical(this, rfidScenario.ePassportDataGroups)) { + rfidScenario._set(rfidScenarioJson); + } + parent?.testSetters.addAll(rfidScenarioJson); + testSetters.addAll(json); + } + + void _apply(RFIDScenario parent) => _set(toJson(), parent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/rfid_scenario/edl_data_groups.dart b/lib/src/params/rfid_scenario/edl_data_groups.dart new file mode 100644 index 0000000000..07ff6c1388 --- /dev/null +++ b/lib/src/params/rfid_scenario/edl_data_groups.dart @@ -0,0 +1,164 @@ +// +// EDLDataGroups.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class EDLDataGroups { + bool get dg1 => _dg1; + bool _dg1 = true; + set dg1(bool val) { + _dg1 = val; + _set({"DG1": val}); + } + + bool get dg2 => _dg2; + bool _dg2 = true; + set dg2(bool val) { + _dg2 = val; + _set({"DG2": val}); + } + + bool get dg3 => _dg3; + bool _dg3 = true; + set dg3(bool val) { + _dg3 = val; + _set({"DG3": val}); + } + + bool get dg4 => _dg4; + bool _dg4 = true; + set dg4(bool val) { + _dg4 = val; + _set({"DG4": val}); + } + + bool get dg5 => _dg5; + bool _dg5 = true; + set dg5(bool val) { + _dg5 = val; + _set({"DG5": val}); + } + + bool get dg6 => _dg6; + bool _dg6 = true; + set dg6(bool val) { + _dg6 = val; + _set({"DG6": val}); + } + + bool get dg7 => _dg7; + bool _dg7 = false; + set dg7(bool val) { + _dg7 = val; + _set({"DG7": val}); + } + + bool get dg8 => _dg8; + bool _dg8 = false; + set dg8(bool val) { + _dg8 = val; + _set({"DG8": val}); + } + + bool get dg9 => _dg9; + bool _dg9 = false; + set dg9(bool val) { + _dg9 = val; + _set({"DG9": val}); + } + + bool get dg10 => _dg10; + bool _dg10 = false; + set dg10(bool val) { + _dg10 = val; + _set({"DG10": val}); + } + + bool get dg11 => _dg11; + bool _dg11 = true; + set dg11(bool val) { + _dg11 = val; + _set({"DG11": val}); + } + + bool get dg12 => _dg12; + bool _dg12 = true; + set dg12(bool val) { + _dg12 = val; + _set({"DG12": val}); + } + + bool get dg13 => _dg13; + bool _dg13 = true; + set dg13(bool val) { + _dg13 = val; + _set({"DG13": val}); + } + + bool get dg14 => _dg14; + bool _dg14 = true; + set dg14(bool val) { + _dg14 = val; + _set({"DG14": val}); + } + + /// Allows you to deserialize object. + static EDLDataGroups fromJson(jsonObject) { + var result = EDLDataGroups(); + result.testSetters = {}; + + result.dg1 = jsonObject["DG1"]; + result.dg2 = jsonObject["DG2"]; + result.dg3 = jsonObject["DG3"]; + result.dg4 = jsonObject["DG4"]; + result.dg5 = jsonObject["DG5"]; + result.dg6 = jsonObject["DG6"]; + result.dg7 = jsonObject["DG7"]; + result.dg8 = jsonObject["DG8"]; + result.dg9 = jsonObject["DG9"]; + result.dg10 = jsonObject["DG10"]; + result.dg11 = jsonObject["DG11"]; + result.dg12 = jsonObject["DG12"]; + result.dg13 = jsonObject["DG13"]; + result.dg14 = jsonObject["DG14"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "DG1": dg1, + "DG2": dg2, + "DG3": dg3, + "DG4": dg4, + "DG5": dg5, + "DG6": dg6, + "DG7": dg7, + "DG8": dg8, + "DG9": dg9, + "DG10": dg10, + "DG11": dg11, + "DG12": dg12, + "DG13": dg13, + "DG14": dg14, + }.clearNulls(); + + void _set(Map json, {RFIDScenario? parent}) { + var rfidScenarioJson = {"eDLDataGroups": json}; + var rfidScenario = DocumentReader.instance.rfidScenario; + if (identical(this, rfidScenario.eDLDataGroups)) { + rfidScenario._set(rfidScenarioJson); + } + parent?.testSetters.addAll(rfidScenarioJson); + testSetters.addAll(json); + } + + void _apply(RFIDScenario parent) => _set(toJson(), parent: parent); + + Map testSetters = {}; +} diff --git a/lib/src/params/rfid_scenario/eid_data_groups.dart b/lib/src/params/rfid_scenario/eid_data_groups.dart new file mode 100644 index 0000000000..2fc7599654 --- /dev/null +++ b/lib/src/params/rfid_scenario/eid_data_groups.dart @@ -0,0 +1,228 @@ +// +// EIDDataGroups.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class EIDDataGroups { + bool get dg1 => _dg1; + bool _dg1 = true; + set dg1(bool val) { + _dg1 = val; + _set({"DG1": val}); + } + + bool get dg2 => _dg2; + bool _dg2 = true; + set dg2(bool val) { + _dg2 = val; + _set({"DG2": val}); + } + + bool get dg3 => _dg3; + bool _dg3 = true; + set dg3(bool val) { + _dg3 = val; + _set({"DG3": val}); + } + + bool get dg4 => _dg4; + bool _dg4 = true; + set dg4(bool val) { + _dg4 = val; + _set({"DG4": val}); + } + + bool get dg5 => _dg5; + bool _dg5 = true; + set dg5(bool val) { + _dg5 = val; + _set({"DG5": val}); + } + + bool get dg6 => _dg6; + bool _dg6 = true; + set dg6(bool val) { + _dg6 = val; + _set({"DG6": val}); + } + + bool get dg7 => _dg7; + bool _dg7 = true; + set dg7(bool val) { + _dg7 = val; + _set({"DG7": val}); + } + + bool get dg8 => _dg8; + bool _dg8 = true; + set dg8(bool val) { + _dg8 = val; + _set({"DG8": val}); + } + + bool get dg9 => _dg9; + bool _dg9 = true; + set dg9(bool val) { + _dg9 = val; + _set({"DG9": val}); + } + + bool get dg10 => _dg10; + bool _dg10 = true; + set dg10(bool val) { + _dg10 = val; + _set({"DG10": val}); + } + + bool get dg11 => _dg11; + bool _dg11 = true; + set dg11(bool val) { + _dg11 = val; + _set({"DG11": val}); + } + + bool get dg12 => _dg12; + bool _dg12 = true; + set dg12(bool val) { + _dg12 = val; + _set({"DG12": val}); + } + + bool get dg13 => _dg13; + bool _dg13 = false; + set dg13(bool val) { + _dg13 = val; + _set({"DG13": val}); + } + + bool get dg14 => _dg14; + bool _dg14 = false; + set dg14(bool val) { + _dg14 = val; + _set({"DG14": val}); + } + + bool get dg15 => _dg15; + bool _dg15 = false; + set dg15(bool val) { + _dg15 = val; + _set({"DG15": val}); + } + + bool get dg16 => _dg16; + bool _dg16 = false; + set dg16(bool val) { + _dg16 = val; + _set({"DG16": val}); + } + + bool get dg17 => _dg17; + bool _dg17 = true; + set dg17(bool val) { + _dg17 = val; + _set({"DG17": val}); + } + + bool get dg18 => _dg18; + bool _dg18 = true; + set dg18(bool val) { + _dg18 = val; + _set({"DG18": val}); + } + + bool get dg19 => _dg19; + bool _dg19 = true; + set dg19(bool val) { + _dg19 = val; + _set({"DG19": val}); + } + + bool get dg20 => _dg20; + bool _dg20 = true; + set dg20(bool val) { + _dg20 = val; + _set({"DG20": val}); + } + + bool get dg21 => _dg21; + bool _dg21 = true; + set dg21(bool val) { + _dg21 = val; + _set({"DG21": val}); + } + + /// Allows you to deserialize object. + static EIDDataGroups fromJson(jsonObject) { + var result = EIDDataGroups(); + result.testSetters = {}; + + result.dg1 = jsonObject["DG1"]; + result.dg2 = jsonObject["DG2"]; + result.dg3 = jsonObject["DG3"]; + result.dg4 = jsonObject["DG4"]; + result.dg5 = jsonObject["DG5"]; + result.dg6 = jsonObject["DG6"]; + result.dg7 = jsonObject["DG7"]; + result.dg8 = jsonObject["DG8"]; + result.dg9 = jsonObject["DG9"]; + result.dg10 = jsonObject["DG10"]; + result.dg11 = jsonObject["DG11"]; + result.dg12 = jsonObject["DG12"]; + result.dg13 = jsonObject["DG13"]; + result.dg14 = jsonObject["DG14"]; + result.dg15 = jsonObject["DG15"]; + result.dg16 = jsonObject["DG16"]; + result.dg17 = jsonObject["DG17"]; + result.dg18 = jsonObject["DG18"]; + result.dg19 = jsonObject["DG19"]; + result.dg20 = jsonObject["DG20"]; + result.dg21 = jsonObject["DG21"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "DG1": dg1, + "DG2": dg2, + "DG3": dg3, + "DG4": dg4, + "DG5": dg5, + "DG6": dg6, + "DG7": dg7, + "DG8": dg8, + "DG9": dg9, + "DG10": dg10, + "DG11": dg11, + "DG12": dg12, + "DG13": dg13, + "DG14": dg14, + "DG15": dg15, + "DG16": dg16, + "DG17": dg17, + "DG18": dg18, + "DG19": dg19, + "DG20": dg20, + "DG21": dg21, + }.clearNulls(); + + void _set(Map json, {RFIDScenario? parent}) { + var rfidScenarioJson = {"eIDDataGroups": json}; + var rfidScenario = DocumentReader.instance.rfidScenario; + if (identical(this, rfidScenario.eIDDataGroups)) { + rfidScenario._set(rfidScenarioJson); + } + parent?.testSetters.addAll(rfidScenarioJson); + testSetters.addAll(json); + } + + void _apply(RFIDScenario parent) => _set(toJson(), parent: parent); + + @visibleForTesting + Map testSetters = {}; +} diff --git a/lib/src/params/rfid_scenario/rfid_scenario.dart b/lib/src/params/rfid_scenario/rfid_scenario.dart new file mode 100644 index 0000000000..29e57fdefb --- /dev/null +++ b/lib/src/params/rfid_scenario/rfid_scenario.dart @@ -0,0 +1,793 @@ +// +// RfidScenario.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Params that influence the RFID chip processing. +class RFIDScenario { + bool? get paceStaticBinding => _paceStaticBinding; + bool? _paceStaticBinding; + set paceStaticBinding(bool? val) { + _paceStaticBinding = val; + _set({"paceStaticBinding": val}); + } + + bool? get onlineTA => _onlineTA; + bool? _onlineTA; + set onlineTA(bool? val) { + _onlineTA = val; + _set({"onlineTA": val}); + } + + bool? get writeEid => _writeEid; + bool? _writeEid; + set writeEid(bool? val) { + _writeEid = val; + _set({"writeEid": val}); + } + + bool? get universalAccessRights => _universalAccessRights; + bool? _universalAccessRights; + set universalAccessRights(bool? val) { + _universalAccessRights = val; + _set({"universalAccessRights": val}); + } + + bool? get authorizedRestrictedIdentification => + _authorizedRestrictedIdentification; + bool? _authorizedRestrictedIdentification; + set authorizedRestrictedIdentification(bool? val) { + _authorizedRestrictedIdentification = val; + _set({"authorizedRestrictedIdentification": val}); + } + + bool? get auxVerificationCommunityID => _auxVerificationCommunityID; + bool? _auxVerificationCommunityID; + set auxVerificationCommunityID(bool? val) { + _auxVerificationCommunityID = val; + _set({"auxVerificationCommunityID": val}); + } + + bool? get auxVerificationDateOfBirth => _auxVerificationDateOfBirth; + bool? _auxVerificationDateOfBirth; + set auxVerificationDateOfBirth(bool? val) { + _auxVerificationDateOfBirth = val; + _set({"auxVerificationDateOfBirth": val}); + } + + bool? get skipAA => _skipAA; + bool? _skipAA; + set skipAA(bool? val) { + _skipAA = val; + _set({"skipAA": val}); + } + + bool? get strictProcessing => _strictProcessing; + bool? _strictProcessing; + set strictProcessing(bool? val) { + _strictProcessing = val; + _set({"strictProcessing": val}); + } + + bool? get pkdDSCertPriority => _pkdDSCertPriority; + bool? _pkdDSCertPriority; + set pkdDSCertPriority(bool? val) { + _pkdDSCertPriority = val; + _set({"pkdDSCertPriority": val}); + } + + bool? get pkdUseExternalCSCA => _pkdUseExternalCSCA; + bool? _pkdUseExternalCSCA; + set pkdUseExternalCSCA(bool? val) { + _pkdUseExternalCSCA = val; + _set({"pkdUseExternalCSCA": val}); + } + + bool? get trustedPKD => _trustedPKD; + bool? _trustedPKD; + set trustedPKD(bool? val) { + _trustedPKD = val; + _set({"trustedPKD": val}); + } + + bool? get passiveAuth => _passiveAuth; + bool? _passiveAuth; + set passiveAuth(bool? val) { + _passiveAuth = val; + _set({"passiveAuth": val}); + } + + bool? get useSFI => _useSFI; + bool? _useSFI; + set useSFI(bool? val) { + _useSFI = val; + _set({"useSFI": val}); + } + + bool? get readEPassport => _readEPassport; + bool? _readEPassport; + set readEPassport(bool? val) { + _readEPassport = val; + _set({"readEPassport": val}); + } + + bool? get readEID => _readEID; + bool? _readEID; + set readEID(bool? val) { + _readEID = val; + _set({"readEID": val}); + } + + bool? get readEDL => _readEDL; + bool? _readEDL; + set readEDL(bool? val) { + _readEDL = val; + _set({"readEDL": val}); + } + + bool? get authorizedSTSignature => _authorizedSTSignature; + bool? _authorizedSTSignature; + set authorizedSTSignature(bool? val) { + _authorizedSTSignature = val; + _set({"authorizedSTSignature": val}); + } + + bool? get authorizedSTQSignature => _authorizedSTQSignature; + bool? _authorizedSTQSignature; + set authorizedSTQSignature(bool? val) { + _authorizedSTQSignature = val; + _set({"authorizedSTQSignature": val}); + } + + bool? get authorizedWriteDG17 => _authorizedWriteDG17; + bool? _authorizedWriteDG17; + set authorizedWriteDG17(bool? val) { + _authorizedWriteDG17 = val; + _set({"authorizedWriteDG17": val}); + } + + bool? get authorizedWriteDG18 => _authorizedWriteDG18; + bool? _authorizedWriteDG18; + set authorizedWriteDG18(bool? val) { + _authorizedWriteDG18 = val; + _set({"authorizedWriteDG18": val}); + } + + bool? get authorizedWriteDG19 => _authorizedWriteDG19; + bool? _authorizedWriteDG19; + set authorizedWriteDG19(bool? val) { + _authorizedWriteDG19 = val; + _set({"authorizedWriteDG19": val}); + } + + bool? get authorizedWriteDG20 => _authorizedWriteDG20; + bool? _authorizedWriteDG20; + set authorizedWriteDG20(bool? val) { + _authorizedWriteDG20 = val; + _set({"authorizedWriteDG20": val}); + } + + bool? get authorizedWriteDG21 => _authorizedWriteDG21; + bool? _authorizedWriteDG21; + set authorizedWriteDG21(bool? val) { + _authorizedWriteDG21 = val; + _set({"authorizedWriteDG21": val}); + } + + bool? get authorizedVerifyAge => _authorizedVerifyAge; + bool? _authorizedVerifyAge; + set authorizedVerifyAge(bool? val) { + _authorizedVerifyAge = val; + _set({"authorizedVerifyAge": val}); + } + + bool? get authorizedVerifyCommunityID => _authorizedVerifyCommunityID; + bool? _authorizedVerifyCommunityID; + set authorizedVerifyCommunityID(bool? val) { + _authorizedVerifyCommunityID = val; + _set({"authorizedVerifyCommunityID": val}); + } + + bool? get authorizedPrivilegedTerminal => _authorizedPrivilegedTerminal; + bool? _authorizedPrivilegedTerminal; + set authorizedPrivilegedTerminal(bool? val) { + _authorizedPrivilegedTerminal = val; + _set({"authorizedPrivilegedTerminal": val}); + } + + bool? get authorizedCANAllowed => _authorizedCANAllowed; + bool? _authorizedCANAllowed; + set authorizedCANAllowed(bool? val) { + _authorizedCANAllowed = val; + _set({"authorizedCANAllowed": val}); + } + + bool? get authorizedPINManagement => _authorizedPINManagement; + bool? _authorizedPINManagement; + set authorizedPINManagement(bool? val) { + _authorizedPINManagement = val; + _set({"authorizedPINManagement": val}); + } + + bool? get authorizedInstallCert => _authorizedInstallCert; + bool? _authorizedInstallCert; + set authorizedInstallCert(bool? val) { + _authorizedInstallCert = val; + _set({"authorizedInstallCert": val}); + } + + bool? get authorizedInstallQCert => _authorizedInstallQCert; + bool? _authorizedInstallQCert; + set authorizedInstallQCert(bool? val) { + _authorizedInstallQCert = val; + _set({"authorizedInstallQCert": val}); + } + + bool? get applyAmendments => _applyAmendments; + bool? _applyAmendments; + set applyAmendments(bool? val) { + _applyAmendments = val; + _set({"applyAmendments": val}); + } + + bool? get autoSettings => _autoSettings; + bool? _autoSettings; + set autoSettings(bool? val) { + _autoSettings = val; + _set({"autoSettings": val}); + } + + // If set to `true`, continue RFID chip processing, despite ICAO critical errors. + bool? get proceedReadingAlways => _proceedReadingAlways; + bool? _proceedReadingAlways; + set proceedReadingAlways(bool? val) { + _proceedReadingAlways = val; + _set({"proceedReadingAlways": val}); + } + + bool? get readDTC => _readDTC; + bool? _readDTC; + set readDTC(bool? val) { + _readDTC = val; + _set({"readDTC": val}); + } + + /// Perform check MRZ according to standard described in + /// BSI TR - 03105: ePassport Conformity Testing(v 1.0 04.04.2008). + bool? get mrzStrictCheck => _mrzStrictCheck; + bool? _mrzStrictCheck; + set mrzStrictCheck(bool? val) { + _mrzStrictCheck = val; + _set({"mrzStrictCheck": val}); + } + + /// If enabled, Certificate Revoke List(s) (CRL) will be loaded from remote and verified. + bool? get loadCRLFromRemote => _loadCRLFromRemote; + bool? _loadCRLFromRemote; + set loadCRLFromRemote(bool? val) { + _loadCRLFromRemote = val; + _set({"loadCRLFromRemote": val}); + } + + bool? get independentSODStatus => _independentSODStatus; + bool? _independentSODStatus; + set independentSODStatus(bool? val) { + _independentSODStatus = val; + _set({"independentSODStatus": val}); + } + + RFIDReadingBufferSize? get readingBuffer => _readingBuffer; + RFIDReadingBufferSize? _readingBuffer; + set readingBuffer(RFIDReadingBufferSize? val) { + _readingBuffer = val; + _set({"readingBuffer": val?.value}); + } + + int? get onlineTAToSignDataType => _onlineTAToSignDataType; + int? _onlineTAToSignDataType; + set onlineTAToSignDataType(int? val) { + _onlineTAToSignDataType = val; + _set({"onlineTAToSignDataType": val}); + } + + static final int _coreDefaultReadingBufferSize = 231; + + int get defaultReadingBufferSize => _defaultReadingBufferSize; + int _defaultReadingBufferSize = _coreDefaultReadingBufferSize; + set defaultReadingBufferSize(int val) { + _defaultReadingBufferSize = val; + _set({"defaultReadingBufferSize": val}); + } + + SignManagementAction? get signManagementAction => _signManagementAction; + SignManagementAction? _signManagementAction; + set signManagementAction(SignManagementAction? val) { + _signManagementAction = val; + _set({"signManagementAction": val?.value}); + } + + RFIDSDKProfilerType? get profilerType => _profilerType; + RFIDSDKProfilerType? _profilerType; + set profilerType(RFIDSDKProfilerType? val) { + _profilerType = val; + _set({"profilerType": val?.value}); + } + + RFIDAuthenticationProcedureType? get authProcType => _authProcType; + RFIDAuthenticationProcedureType? _authProcType; + set authProcType(RFIDAuthenticationProcedureType? val) { + _authProcType = val; + _set({"authProcType": val?.value}); + } + + RFIDAccessControlProcedureType? get baseSMProcedure => _baseSMProcedure; + RFIDAccessControlProcedureType? _baseSMProcedure; + set baseSMProcedure(RFIDAccessControlProcedureType? val) { + _baseSMProcedure = val; + _set({"baseSMProcedure": val?.value}); + } + + RFIDPasswordType? get pacePasswordType => _pacePasswordType; + RFIDPasswordType? _pacePasswordType; + set pacePasswordType(RFIDPasswordType? val) { + _pacePasswordType = val; + _set({"pacePasswordType": val?.value}); + } + + RFIDTerminalType? get terminalType => _terminalType; + RFIDTerminalType? _terminalType; + set terminalType(RFIDTerminalType? val) { + _terminalType = val; + _set({"terminalType": val?.value}); + } + + String? get password => _password; + String? _password; + set password(String? val) { + _password = val; + _set({"password": val}); + } + + String? get pkdPA => _pkdPA; + String? _pkdPA; + set pkdPA(String? val) { + _pkdPA = val; + _set({"pkdPA": val}); + } + + String? get pkdEAC => _pkdEAC; + String? _pkdEAC; + set pkdEAC(String? val) { + _pkdEAC = val; + _set({"pkdEAC": val}); + } + + String? get mrz => _mrz; + String? _mrz; + set mrz(String? val) { + _mrz = val; + _set({"mrz": val}); + } + + String? get eSignPINDefault => _eSignPINDefault; + String? _eSignPINDefault; + set eSignPINDefault(String? val) { + _eSignPINDefault = val; + _set({"eSignPINDefault": val}); + } + + String? get eSignPINNewValue => _eSignPINNewValue; + String? _eSignPINNewValue; + set eSignPINNewValue(String? val) { + _eSignPINNewValue = val; + _set({"eSignPINNewValue": val}); + } + + String? get cardAccess => _cardAccess; + String? _cardAccess; + set cardAccess(String? val) { + _cardAccess = val; + _set({"cardAccess": val}); + } + + String? get mrzHash => _mrzHash; + String? _mrzHash; + set mrzHash(String? val) { + _mrzHash = val; + _set({"mrzHash": val}); + } + + String? get documentNumber => _documentNumber; + String? _documentNumber; + set documentNumber(String? val) { + _documentNumber = val; + _set({"documentNumber": val}); + } + + String? get dateOfBirth => _dateOfBirth; + String? _dateOfBirth; + set dateOfBirth(String? val) { + _dateOfBirth = val; + _set({"dateOfBirth": val}); + } + + String? get dateOfExpiry => _dateOfExpiry; + String? _dateOfExpiry; + set dateOfExpiry(String? val) { + _dateOfExpiry = val; + _set({"dateOfExpiry": val}); + } + + EDLDataGroups get eDLDataGroups => _eDLDataGroups; + EDLDataGroups _eDLDataGroups = EDLDataGroups(); + set eDLDataGroups(EDLDataGroups val) { + (_eDLDataGroups = val)._apply(this); + } + + EPassportDataGroups get ePassportDataGroups => _ePassportDataGroups; + EPassportDataGroups _ePassportDataGroups = EPassportDataGroups(); + set ePassportDataGroups(EPassportDataGroups val) { + (_ePassportDataGroups = val)._apply(this); + } + + EIDDataGroups get eIDDataGroups => _eIDDataGroups; + EIDDataGroups _eIDDataGroups = EIDDataGroups(); + set eIDDataGroups(EIDDataGroups val) { + (_eIDDataGroups = val)._apply(this); + } + + DTCDataGroup get dtcDataGroups => _dtcDataGroups; + DTCDataGroup _dtcDataGroups = DTCDataGroup(); + set dtcDataGroups(DTCDataGroup val) { + (_dtcDataGroups = val)._apply(this); + } + + /// Allows you to deserialize object. + static RFIDScenario fromJson(jsonObject) { + var result = RFIDScenario(); + result.testSetters = {}; + + result.paceStaticBinding = jsonObject["paceStaticBinding"]; + result.onlineTA = jsonObject["onlineTA"]; + result.writeEid = jsonObject["writeEid"]; + result.universalAccessRights = jsonObject["universalAccessRights"]; + result.authorizedRestrictedIdentification = + jsonObject["authorizedRestrictedIdentification"]; + result.auxVerificationCommunityID = + jsonObject["auxVerificationCommunityID"]; + result.auxVerificationDateOfBirth = + jsonObject["auxVerificationDateOfBirth"]; + result.skipAA = jsonObject["skipAA"]; + result.strictProcessing = jsonObject["strictProcessing"]; + result.pkdDSCertPriority = jsonObject["pkdDSCertPriority"]; + result.pkdUseExternalCSCA = jsonObject["pkdUseExternalCSCA"]; + result.trustedPKD = jsonObject["trustedPKD"]; + result.passiveAuth = jsonObject["passiveAuth"]; + result.useSFI = jsonObject["useSFI"]; + result.readEPassport = jsonObject["readEPassport"]; + result.readEID = jsonObject["readEID"]; + result.readEDL = jsonObject["readEDL"]; + result.authorizedSTSignature = jsonObject["authorizedSTSignature"]; + result.authorizedSTQSignature = jsonObject["authorizedSTQSignature"]; + result.authorizedWriteDG17 = jsonObject["authorizedWriteDG17"]; + result.authorizedWriteDG18 = jsonObject["authorizedWriteDG18"]; + result.authorizedWriteDG19 = jsonObject["authorizedWriteDG19"]; + result.authorizedWriteDG20 = jsonObject["authorizedWriteDG20"]; + result.authorizedWriteDG21 = jsonObject["authorizedWriteDG21"]; + result.authorizedVerifyAge = jsonObject["authorizedVerifyAge"]; + result.authorizedVerifyCommunityID = + jsonObject["authorizedVerifyCommunityID"]; + result.authorizedPrivilegedTerminal = + jsonObject["authorizedPrivilegedTerminal"]; + result.authorizedCANAllowed = jsonObject["authorizedCANAllowed"]; + result.authorizedPINManagement = jsonObject["authorizedPINManagement"]; + result.authorizedInstallCert = jsonObject["authorizedInstallCert"]; + result.authorizedInstallQCert = jsonObject["authorizedInstallQCert"]; + result.applyAmendments = jsonObject["applyAmendments"]; + result.autoSettings = jsonObject["autoSettings"]; + result.proceedReadingAlways = jsonObject["proceedReadingAlways"]; + result.readDTC = jsonObject["readDTC"]; + result.mrzStrictCheck = jsonObject["mrzStrictCheck"]; + result.loadCRLFromRemote = jsonObject["loadCRLFromRemote"]; + result.independentSODStatus = jsonObject["independentSODStatus"]; + + result.readingBuffer = + RFIDReadingBufferSize.getByValue(jsonObject["readingBuffer"]); + result.onlineTAToSignDataType = jsonObject["onlineTAToSignDataType"]; + result.defaultReadingBufferSize = jsonObject["defaultReadingBufferSize"]; + result.signManagementAction = + SignManagementAction.getByValue(jsonObject["signManagementAction"]); + result.profilerType = + RFIDSDKProfilerType.getByValue(jsonObject["profilerType"]); + result.authProcType = + RFIDAuthenticationProcedureType.getByValue(jsonObject["authProcType"]); + result.baseSMProcedure = RFIDAccessControlProcedureType.getByValue( + jsonObject["baseSMProcedure"]); + result.pacePasswordType = + RFIDPasswordType.getByValue(jsonObject["pacePasswordType"]); + result.terminalType = + RFIDTerminalType.getByValue(jsonObject["terminalType"]); + + result.password = jsonObject["password"]; + result.pkdPA = jsonObject["pkdPA"]; + result.pkdEAC = jsonObject["pkdEAC"]; + result.mrz = jsonObject["mrz"]; + result.eSignPINDefault = jsonObject["eSignPINDefault"]; + result.eSignPINNewValue = jsonObject["eSignPINNewValue"]; + result.cardAccess = jsonObject["cardAccess"]; + result.mrzHash = jsonObject["mrzHash"]; + result.documentNumber = jsonObject["documentNumber"]; + result.dateOfBirth = jsonObject["dateOfBirth"]; + result.dateOfExpiry = jsonObject["dateOfExpiry"]; + + result.eDLDataGroups = EDLDataGroups.fromJson(jsonObject["eDLDataGroups"]); + result.ePassportDataGroups = + EPassportDataGroups.fromJson(jsonObject["ePassportDataGroups"]); + result.eIDDataGroups = EIDDataGroups.fromJson(jsonObject["eIDDataGroups"]); + result.dtcDataGroups = DTCDataGroup.fromJson(jsonObject["dtcDataGroups"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "paceStaticBinding": paceStaticBinding, + "onlineTA": onlineTA, + "writeEid": writeEid, + "universalAccessRights": universalAccessRights, + "authorizedRestrictedIdentification": + authorizedRestrictedIdentification, + "auxVerificationCommunityID": auxVerificationCommunityID, + "auxVerificationDateOfBirth": auxVerificationDateOfBirth, + "skipAA": skipAA, + "strictProcessing": strictProcessing, + "pkdDSCertPriority": pkdDSCertPriority, + "pkdUseExternalCSCA": pkdUseExternalCSCA, + "trustedPKD": trustedPKD, + "passiveAuth": passiveAuth, + "useSFI": useSFI, + "readEPassport": readEPassport, + "readEID": readEID, + "readEDL": readEDL, + "authorizedSTSignature": authorizedSTSignature, + "authorizedSTQSignature": authorizedSTQSignature, + "authorizedWriteDG17": authorizedWriteDG17, + "authorizedWriteDG18": authorizedWriteDG18, + "authorizedWriteDG19": authorizedWriteDG19, + "authorizedWriteDG20": authorizedWriteDG20, + "authorizedWriteDG21": authorizedWriteDG21, + "authorizedVerifyAge": authorizedVerifyAge, + "authorizedVerifyCommunityID": authorizedVerifyCommunityID, + "authorizedPrivilegedTerminal": authorizedPrivilegedTerminal, + "authorizedCANAllowed": authorizedCANAllowed, + "authorizedPINManagement": authorizedPINManagement, + "authorizedInstallCert": authorizedInstallCert, + "authorizedInstallQCert": authorizedInstallQCert, + "applyAmendments": applyAmendments, + "autoSettings": autoSettings, + "proceedReadingAlways": proceedReadingAlways, + "readDTC": readDTC, + "mrzStrictCheck": mrzStrictCheck, + "loadCRLFromRemote": loadCRLFromRemote, + "independentSODStatus": independentSODStatus, + "readingBuffer": readingBuffer?.value, + "onlineTAToSignDataType": onlineTAToSignDataType, + "defaultReadingBufferSize": defaultReadingBufferSize, + "signManagementAction": signManagementAction?.value, + "profilerType": profilerType?.value, + "authProcType": authProcType?.value, + "baseSMProcedure": baseSMProcedure?.value, + "pacePasswordType": pacePasswordType?.value, + "terminalType": terminalType?.value, + "password": password, + "pkdPA": pkdPA, + "pkdEAC": pkdEAC, + "mrz": mrz, + "eSignPINDefault": eSignPINDefault, + "eSignPINNewValue": eSignPINNewValue, + "cardAccess": cardAccess, + "mrzHash": mrzHash, + "documentNumber": documentNumber, + "dateOfBirth": dateOfBirth, + "dateOfExpiry": dateOfExpiry, + "eDLDataGroups": eDLDataGroups.toJson(), + "ePassportDataGroups": ePassportDataGroups.toJson(), + "eIDDataGroups": eIDDataGroups.toJson(), + "dtcDataGroups": dtcDataGroups.toJson(), + }.clearNulls(); + + void _set(Map json) { + if (identical(this, DocumentReader.instance.rfidScenario)) { + _bridge.invokeMethod("setRfidScenario", [json]); + } + testSetters.addAll(json); + } + + void _apply() => _set(toJson()); + + @visibleForTesting + Map testSetters = {}; +} + +enum RFIDAuthenticationProcedureType { + /// Not defined. + UNDEFINED(0), + + /// Standard authentication procedure. + STANDARD(1), + + /// Advanced authentication procedure. + ADVANCED(2), + + /// General authentication procedure. + GENERAL(3); + + const RFIDAuthenticationProcedureType(this.value); + final int value; + + static RFIDAuthenticationProcedureType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDAuthenticationProcedureType.values.firstWhere( + (x) => x.value == i, + ); + } catch (_) { + return RFIDAuthenticationProcedureType.UNDEFINED; + } + } +} + +enum RFIDPasswordType { + /// Unknown type. + UNDEFINED(0), + + /// MRZ. + MRZ(1), + + /// CAN. + CAN(2), + + /// PIN. + PIN(3), + + /// PUK. + PUK(4), + + /// eSign-PIN. + PIN_ESIGN(5), + + /// Scanning Area Identifier (for eDL application). + SAI(6), + + /// MRZHash. + MRZ_HASH(7); + + const RFIDPasswordType(this.value); + final int value; + + static RFIDPasswordType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDPasswordType.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDPasswordType.UNDEFINED; + } + } +} + +enum RFIDSDKProfilerType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Doc 9303, 6th edition, 2006. + DOC_9303_EDITION_2006(0x00000001), + + /// LDS and PKI Maintenance, v2.0, May 21, 2014. + DOC_9303_LDS_PKI_MAINTENANCE(0x00000002); + + const RFIDSDKProfilerType(this.value); + final int value; + + static RFIDSDKProfilerType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDSDKProfilerType.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDSDKProfilerType.UNKNOWN; + } + } +} + +enum RFIDTerminalType { + /// Not defined. + UNDEFINED(0), + + /// Inspection system. + INSPECTION_SYSTEM(1), + + /// Authentication terminal + AUTHENTICATION_TERMINAL(2), + + /// Signature terminal. + SIGNATURE_TERMINAL(3), + + /// Unauthenticated terminal. + UNAUTHENTICATED_TERMINAL(4); + + const RFIDTerminalType(this.value); + final int value; + + static RFIDTerminalType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDTerminalType.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDTerminalType.UNDEFINED; + } + } +} + +enum SignManagementAction { + /// Not identified. + UNDEFINED(0), + + /// Create PIN. + CREATE_PIN(1), + + /// Change PIN. + CHANGE_PIN(2), + + /// Unblock PIN + UNBLOCK_PIN(3), + + /// Terminate PIN. + TERMINATE_PIN(4), + + /// Generate keys. + GENERATE_KEYS(5), + + /// Terminate keys. + TERMINATE_KEYS(6), + + /// Sign data. + SIGN_DATA(7); + + const SignManagementAction(this.value); + final int value; + + static SignManagementAction? getByValue(int? i) { + if (i == null) return null; + try { + return SignManagementAction.values.firstWhere((x) => x.value == i); + } catch (_) { + return SignManagementAction.UNDEFINED; + } + } +} + +enum RFIDReadingBufferSize { + /// Standard length. + STANDARD_LENGTH(0), + + /// Extended length. + EXTENDED_LENGTH(-1); + + const RFIDReadingBufferSize(this.value); + final int value; + + static RFIDReadingBufferSize? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDReadingBufferSize.values.firstWhere( + (x) => x.value == i, + ); + } catch (_) { + return RFIDReadingBufferSize.EXTENDED_LENGTH; + } + } +} diff --git a/lib/src/results/Position.dart b/lib/src/results/Position.dart new file mode 100644 index 0000000000..1ddf147648 --- /dev/null +++ b/lib/src/results/Position.dart @@ -0,0 +1,151 @@ +// +// Position.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Structure is used for storing element bounds detection result._ +class Position { + /// Document format. + DocFormat get docFormat => _docFormat; + late DocFormat _docFormat; + + /// Document width. + int get width => _width; + late int _width; + + /// Document height. + int get height => _height; + late int _height; + + /// Document rotation angle. + double get angle => _angle; + late double _angle; + + /// Resolution in dots per inch. + int get dpi => _dpi; + late int _dpi; + + /// Internal use parameter. + int get inverse => _inverse; + late int _inverse; + + /// Internal use parameter. + int get perspectiveTr => _perspectiveTr; + late int _perspectiveTr; + + /// Internal use parameter. + int get objArea => _objArea; + late int _objArea; + + /// Internal use parameter. + int get objIntAngleDev => _objIntAngleDev; + late int _objIntAngleDev; + + /// Internal use parameter. + CheckResult get resultStatus => _resultStatus; + late CheckResult _resultStatus; + + /// Document center coordinates. + Coordinate? get center => _center; + Coordinate? _center; + + /// Document left top corner coordinates. + Coordinate? get leftTop => _leftTop; + Coordinate? _leftTop; + + /// Document left bottom corner coordinates. + Coordinate? get leftBottom => _leftBottom; + Coordinate? _leftBottom; + + /// Document right top corner coordinates. + Coordinate? get rightTop => _rightTop; + Coordinate? _rightTop; + + /// Document right bottom corner coordinates. + Coordinate? get rightBottom => _rightBottom; + Coordinate? _rightBottom; + + /// Index of the document page, whence the result is received. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Allows you to deserialize object. + static Position? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Position(); + + result._docFormat = DocFormat.getByValue(jsonObject["docFormat"])!; + result._width = jsonObject["width"]; + result._height = jsonObject["height"]; + result._dpi = jsonObject["dpi"]; + result._pageIndex = jsonObject["pageIndex"]; + result._inverse = jsonObject["inverse"]; + result._perspectiveTr = jsonObject["perspectiveTr"]; + result._objArea = jsonObject["objArea"]; + result._objIntAngleDev = jsonObject["objIntAngleDev"]; + result._resultStatus = CheckResult.getByValue(jsonObject["resultStatus"])!; + result._angle = _toDouble(jsonObject["angle"])!; + result._center = Coordinate.fromJson(jsonObject["center"]); + result._leftTop = Coordinate.fromJson(jsonObject["leftTop"]); + result._leftBottom = Coordinate.fromJson(jsonObject["leftBottom"]); + result._rightTop = Coordinate.fromJson(jsonObject["rightTop"]); + result._rightBottom = Coordinate.fromJson(jsonObject["rightBottom"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "docFormat": docFormat.value, + "resultStatus": resultStatus.value, + "width": width, + "height": height, + "angle": angle, + "dpi": dpi, + "inverse": inverse, + "perspectiveTr": perspectiveTr, + "objArea": objArea, + "objIntAngleDev": objIntAngleDev, + "pageIndex": pageIndex, + "center": center?.toJson(), + "leftTop": leftTop?.toJson(), + "leftBottom": leftBottom?.toJson(), + "rightTop": rightTop?.toJson(), + "rightBottom": rightBottom?.toJson(), + }.clearNulls(); +} + +/// Structure describing point coordinate. +class Coordinate { + int get x => _x; + late int _x; + + int get y => _y; + late int _y; + + /// Allows you to deserialize object. + static Coordinate? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Coordinate(); + + result._x = jsonObject["x"]; + result._y = jsonObject["y"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() { + Map result = {}; + + result["x"] = x; + result["y"] = y; + + return result; + } +} diff --git a/lib/src/results/Results.dart b/lib/src/results/Results.dart new file mode 100644 index 0000000000..26ab758be2 --- /dev/null +++ b/lib/src/results/Results.dart @@ -0,0 +1,626 @@ +// +// Results.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class describing results returned on completion of Document Reader work. +class Results { + /// Document type results. + List? get documentType => _documentType; + List? _documentType; + + /// Textual results. + TextResult? get textResult => _textResult; + TextResult? _textResult; + + /// Graphic results. + GraphicResult? get graphicResult => _graphicResult; + GraphicResult? _graphicResult; + + /// Position of a document. + List? get documentPosition => _documentPosition; + List? _documentPosition; + + /// Position of a barcode. + List? get barcodePosition => _barcodePosition; + List? _barcodePosition; + + /// Position of MRZ. + List? get mrzPosition => _mrzPosition; + List? _mrzPosition; + + /// Image quality results. + List? get imageQuality => _imageQuality; + List? _imageQuality; + + /// Status information for each operation. + ResultsStatus get status => _status; + late ResultsStatus _status; + + /// Authenticity results. + AuthenticityResult? get authenticityResult => _authenticityResult; + AuthenticityResult? _authenticityResult; + + /// RFID session data. + RFIDSessionData? get rfidSessionData => _rfidSessionData; + RFIDSessionData? _rfidSessionData; + + /// Indicates which page of the document contains an RFID chip (0 if there's + /// no page containing it). Requires document type recognition, otherwise 1 by default. + int get chipPage => _chipPage; + late int _chipPage; + + /// Barcode results. + BarcodeResult? get barcodeResult => _barcodeResult; + BarcodeResult? _barcodeResult; + + /// Visible Digital Seal data. + VDSNCData? get vdsncData => _vdsncData; + VDSNCData? _vdsncData; + + /// Visible Digital Seal data. + VDSData? get vdsData => _vdsData; + VDSData? _vdsData; + + /// DTCVC data. + Uint8List? get dtcData => _dtcData; + Uint8List? _dtcData; + + /// Document processing finish status, one of RGLProcessingFinishedStatus values. + ProcessingFinishedStatus get processingFinishedStatus => + _processingFinishedStatus; + late ProcessingFinishedStatus _processingFinishedStatus; + + /// Indicates how many pages of a document remains to process. + /// Requires Document Type recognition, otherwise 0 by default. + int get morePagesAvailable => _morePagesAvailable; + late int _morePagesAvailable; + + /// Indicates how much time has been required for document processing, milliseconds. + int get elapsedTime => _elapsedTime; + late int _elapsedTime; + + /// Indicates how much time has been required for RFID chip processing, milliseconds. + int get elapsedTimeRFID => _elapsedTimeRFID; + late int _elapsedTimeRFID; + + /// Raw results, i.e. in their initial view. + String get rawResult => _rawResult; + late String _rawResult; + + /// Contains results in accordance with the BSI TR-03135 standard. + String? get bsiTr03135Results => _bsiTr03135Results; + String? _bsiTr03135Results; + + TransactionInfo? get transactionInfo => _transactionInfo; + TransactionInfo? _transactionInfo; + + /// Allows you to get a value of a text field. + Future textFieldValueByType(FieldType fieldType) async { + return await _bridge.invokeMethod("textFieldValueByType", [ + rawResult, + fieldType.value, + ]); + } + + /// Allows you to get a value of a text field based on LCID. + Future textFieldValueByTypeLcid( + FieldType fieldType, + LCID lcid, + ) async { + return await _bridge.invokeMethod("textFieldValueByTypeLcid", [ + rawResult, + fieldType.value, + lcid.value, + ]); + } + + /// Allows you to get a value of a text field based on a source type. + Future textFieldValueByTypeSource( + FieldType fieldType, + ResultType source, + ) async { + return await _bridge.invokeMethod("textFieldValueByTypeSource", [ + rawResult, + fieldType.value, + source.value, + ]); + } + + /// Allows you to get a value of a text field based on LCID and a source type. + Future textFieldValueByTypeLcidSource( + FieldType fieldType, + LCID lcid, + ResultType source, + ) async { + return await _bridge.invokeMethod("textFieldValueByTypeLcidSource", [ + rawResult, + fieldType.value, + lcid.value, + source.value, + ]); + } + + /// Allows you to get a value of a text field based on a source type and + /// its originality. + Future textFieldValueByTypeSourceOriginal( + FieldType fieldType, + ResultType source, + bool original, + ) async { + return await _bridge.invokeMethod("textFieldValueByTypeSourceOriginal", [ + rawResult, + fieldType.value, + source.value, + original, + ]); + } + + /// Allows you to get a value of a text field based on LCID, a source type + /// and its originality. + Future textFieldValueByTypeLcidSourceOriginal( + FieldType fieldType, + LCID lcid, + ResultType source, + bool original, + ) async { + return await _bridge.invokeMethod( + "textFieldValueByTypeLcidSourceOriginal", + [rawResult, fieldType.value, lcid.value, source.value, original], + ); + } + + /// Allows you to get an instance of a text field. + Future textFieldByType(FieldType fieldType) async { + String? result = await _bridge.invokeMethod("textFieldByType", [ + rawResult, + fieldType.value, + ]); + if (result == null) return null; + return TextField.fromJson(json.decode(result)); + } + + /// Allows you to get an instance of a text field based on LCID. + Future textFieldByTypeLcid(FieldType fieldType, LCID lcid) async { + String? result = await _bridge.invokeMethod("textFieldByTypeLcid", [ + rawResult, + fieldType.value, + lcid.value, + ]); + if (result == null) return null; + return TextField.fromJson(json.decode(result)); + } + + /// Allows you to get an image of a graphic field based on a source type + /// and page index. + Future graphicFieldByTypeSource( + GraphicFieldType fieldType, + ResultType source, + ) async { + String? result = await _bridge.invokeMethod("graphicFieldByTypeSource", [ + rawResult, + fieldType.value, + source.value, + ]); + if (result == null) return null; + return GraphicField.fromJson(json.decode(result)); + } + + /// Allows you to get an image of a graphic field based on a source type + /// and page index. + Future graphicFieldByTypeSourcePageIndex( + GraphicFieldType fieldType, + ResultType source, + int pageIndex, + ) async { + String? result = await _bridge.invokeMethod( + "graphicFieldByTypeSourcePageIndex", + [rawResult, fieldType.value, source.value, pageIndex], + ); + if (result == null) return null; + return GraphicField.fromJson(json.decode(result)); + } + + /// Allows you to get an image of a graphic field based on a source type, + /// page index and light type. + Future graphicFieldByTypeSourcePageIndexLight( + GraphicFieldType fieldType, + ResultType source, + int pageIndex, + Lights light, + ) async { + String? result = await _bridge.invokeMethod( + "graphicFieldByTypeSourcePageIndex", + [rawResult, fieldType.value, source.value, pageIndex, light.value], + ); + if (result == null) return null; + return GraphicField.fromJson(json.decode(result)); + } + + /// Allows you to get an image of a graphic field. + Future graphicFieldImageByType(GraphicFieldType fieldType) async { + String? result = await _bridge.invokeMethod("graphicFieldImageByType", [ + rawResult, + fieldType.value, + ]); + if (result == null) return null; + // return Uri.parse("data:image/png;base64," + result); + return _bytesFromBase64(result); + } + + /// Allows you to get an image of a graphic field based on a source type. + Future graphicFieldImageByTypeSource( + GraphicFieldType fieldType, + ResultType source, + ) async { + String? result = await _bridge.invokeMethod( + "graphicFieldImageByTypeSource", + [rawResult, fieldType.value, source.value], + ); + if (result == null) return null; + return _bytesFromBase64(result); + } + + /// Allows you to get an image of a graphic field based on a source type + /// and page index. + Future graphicFieldImageByTypeSourcePageIndex( + GraphicFieldType fieldType, + ResultType source, + int pageIndex, + ) async { + String? result = await _bridge.invokeMethod( + "graphicFieldImageByTypeSourcePageIndex", + [rawResult, fieldType.value, source.value, pageIndex], + ); + if (result == null) return null; + return _bytesFromBase64(result); + } + + /// Allows you to get an image of a graphic field based on a source type, + /// page index and light type. + Future graphicFieldImageByTypeSourcePageIndexLight( + GraphicFieldType fieldType, + ResultType source, + int pageIndex, + Lights light, + ) async { + String? result = await _bridge.invokeMethod( + "graphicFieldImageByTypeSourcePageIndexLight", + [rawResult, fieldType.value, source.value, pageIndex, light.value], + ); + if (result == null) return null; + return _bytesFromBase64(result); + } + + /// Method returns containers by result type. If result type doesn't exist, + /// the result of the search will be null. + /// + /// Returns original containers from rawResult including information about the transaction. + Future containers(List resultType) async { + List converted = []; + for (ResultType item in resultType) { + converted.add(item.value); + } + return await _bridge.invokeMethod("containers", [rawResult, converted]); + } + + /// Method returns only containers for [ResultType.INTERNAL_RFID_SESSION], + /// [ResultType.INTERNAL_ENCRYPTED_RCL] and [ResultType.INTERNAL_LICENSE] values. + /// + /// For more details, see [containers] method. + /// Returns all encrypted containers from rawResult to reprocess data on the server side. + Future encryptedContainers() async { + return await _bridge.invokeMethod("encryptedContainers", [rawResult]); + } + + /// Allows you to deserialize object. + static Results? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Results(); + + result._chipPage = jsonObject["chipPage"]; + result._processingFinishedStatus = ProcessingFinishedStatus.getByValue( + jsonObject["processingFinishedStatus"], + )!; + result._elapsedTime = jsonObject["elapsedTime"]; + result._elapsedTimeRFID = jsonObject["elapsedTimeRFID"]; + result._morePagesAvailable = jsonObject["morePagesAvailable"]; + result._graphicResult = GraphicResult.fromJson(jsonObject["graphicResult"]); + result._textResult = TextResult.fromJson(jsonObject["textResult"]); + if (jsonObject["documentPosition"] != null) { + result._documentPosition = []; + for (var item in jsonObject["documentPosition"]) { + result._documentPosition!.addSafe(Position.fromJson(item)); + } + } + if (jsonObject["barcodePosition"] != null) { + result._barcodePosition = []; + for (var item in jsonObject["barcodePosition"]) { + result._barcodePosition!.addSafe(Position.fromJson(item)); + } + } + if (jsonObject["mrzPosition"] != null) { + result._mrzPosition = []; + for (var item in jsonObject["mrzPosition"]) { + result._mrzPosition!.addSafe(Position.fromJson(item)); + } + } + if (jsonObject["imageQuality"] != null) { + result._imageQuality = []; + for (var item in jsonObject["imageQuality"]) { + result._imageQuality!.addSafe(ImageQualityGroup.fromJson(item)); + } + } + if (jsonObject["documentType"] != null) { + result._documentType = []; + for (var item in jsonObject["documentType"]) { + result._documentType!.addSafe(DocumentType.fromJson(item)); + } + } + result._rawResult = jsonObject["rawResult"]; + result._bsiTr03135Results = jsonObject["bsiTr03135Results"]; + result._rfidSessionData = RFIDSessionData.fromJson( + jsonObject["rfidSessionData"], + ); + result._authenticityResult = AuthenticityResult.fromJson( + jsonObject["authenticityResult"], + ); + result._barcodeResult = BarcodeResult.fromJson(jsonObject["barcodeResult"]); + result._status = ResultsStatus.fromJson(jsonObject["status"])!; + result._vdsncData = VDSNCData.fromJson(jsonObject["vdsncData"]); + result._vdsData = VDSData.fromJson(jsonObject["vdsData"]); + result._dtcData = _bytesFromBase64(jsonObject["dtcData"]); + result._transactionInfo = TransactionInfo.fromJson( + jsonObject["transactionInfo"], + ); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "documentType": documentType?.map((e) => e.toJson()).toList(), + "documentPosition": documentPosition?.map((e) => e.toJson()).toList(), + "barcodePosition": barcodePosition?.map((e) => e.toJson()).toList(), + "mrzPosition": mrzPosition?.map((e) => e.toJson()).toList(), + "imageQuality": imageQuality?.map((e) => e.toJson()).toList(), + "textResult": textResult?.toJson(), + "graphicResult": graphicResult?.toJson(), + "status": status.toJson(), + "authenticityResult": authenticityResult?.toJson(), + "rfidSessionData": rfidSessionData?.toJson(), + "barcodeResult": barcodeResult?.toJson(), + "vdsncData": vdsncData?.toJson(), + "vdsData": vdsData?.toJson(), + "dtcData": _bytesToBase64(dtcData), + "chipPage": chipPage, + "processingFinishedStatus": processingFinishedStatus.value, + "morePagesAvailable": morePagesAvailable, + "elapsedTime": elapsedTime, + "elapsedTimeRFID": elapsedTimeRFID, + "rawResult": rawResult, + "bsiTr03135Results": bsiTr03135Results, + "transactionInfo": transactionInfo?.toJson(), + }.clearNulls(); +} + +/// Enumeration contains identifiers that determine the processing finish status. +enum ProcessingFinishedStatus { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Processing is not finished. + NOT_READY(0), + + /// Processing is finished. + READY(1), + + /// Processing is finished by timeout. + TIMEOUT(2); + + const ProcessingFinishedStatus(this.value); + final int value; + + static ProcessingFinishedStatus? getByValue(int? i) { + if (i == null) return null; + try { + return ProcessingFinishedStatus.values.firstWhere((x) => x.value == i); + } catch (_) { + return ProcessingFinishedStatus.UNKNOWN; + } + } +} + +/// Enumeration contains a pool of constants that determine the type of resulting +/// data formed during the data scanning and processing cycle and passed +/// to the user application. +enum ResultType { + /// No result. + NONE(-1), + + /// Stores a graphic image. + EMPTY(0), + + /// Represented as binary array which contains image of the image graphic file. + RAW_IMAGE(1), + + /// Serves for storing text results of MRZ, document filling and bar-codes reading. + FILE_IMAGE(2), + + /// Serves for storing and passing to the user application of results of bar-codes + /// areas search on the scanned document page and their. + MRZ_OCR_EXTENDED(3), + + /// Serves for storing and passing to the user application of results of bar-codes + /// areas search on the scanned document page and their reading in binary non-formatted code. + BARCODES(5), + + /// Serves for storing graphic results of document filling area and bar-codes reading. + GRAPHICS(6), + + /// Serves for storing the information on document MRZ printing quality check results. + MRZ_TEST_QUALITY(7), + + /// Serves for storing information on candidate documents and passing it to the user + /// application when performing the recognition of the document type. + DOCUMENT_TYPES_CANDIDATES(8), + + /// Contains information on one candidate document when determining the document type. + CHOSEN_DOCUMENT_TYPE_CANDIDATE(9), + + /// Not used. Serves for storing the full list of documents stored in the current + /// document database and passing it to the user application. + DOCUMENTS_INFO_LIST(10), + + /// Serves for storing the results of comparing the MRZ text data, document filling + /// area data, bar-codes data and data retrieved from RFID-chip memory and passing + /// it to the user application. + OCR_LEXICAL_ANALYZE(15), + + /// Result stores a graphic image without compression. + RAW_UNCROPPED_IMAGE(16), + + /// Result serves for storing text results of MRZ, document filling and bar-codes reading. + VISUAL_OCR_EXTENDED(17), + + /// Result serves for storing text results of MRZ, document filling and bar-codes reading. + BAR_CODES_TEXT_DATA(18), + + /// Serves for storing graphic results of document filling area and bar-codes reading. + BAR_CODES_IMAGE_DATA(19), + + /// Serves for storing the result of document authenticity check using + /// the images for different lighting schemes and passing it to the user + /// application. + AUTHENTICITY(20), + + /// Not used + EXPERT_ANALYZE(21), + + /// Not used + OCR_LEXICAL_ANALYZE_EX(22), + + /// Stores a graphic image in without compression and passing it to the user application. + EOS_IMAGE(23), + + ///Stores a graphic image in without compression and passing it to the user application. + BAYER_IMAGE(24), + + ///Represented as binary array which contains array if data erade from magnetic stripe. + MAGNETIC_STRIPE(25), + + ///Serves for storing text results of MRZ, document filling and bar-codes reading. + MAGNETIC_STRIPE_TEXT_DATA(26), + + ///Represented as binary array which contains image of the graphic field image graphic file. + FIELD_FILE_IMAGE(27), + + ///Serves for storing the result of documents database check. + DATABASE_CHECK(28), + + ///Represented as binary array which contains ISO fingerprint template. + FINGERPRINT_TEMPLATE_ISO(29), + + ///Used for storing input image quality check results list. + INPUT_IMAGE_QUALITY(30), + + /// Serves for storing the result of document authenticity check using live + /// portrait image. + LIVE_PORTRAIT(32), + + /// Stores information about operations status. + STATUS(33), + + /// Serves for storing the result of document authenticity check using portrait images. + PORTRAIT_COMPARISON(34), + + /// Serves for storing the result of document authenticity check using external portait. + EXT_PORTRAIT(35), + + /// Used for storing text results list. + TEXT(36), + + /// Used for storing images results list. + IMAGES(37), + + /// Serves to store RFID session as binary data. + INTERNAL_RFID_SESSION(48), + + /// Serves to store the encrypted data object. + INTERNAL_ENCRYPTED_RCL(49), + + /// Serves to store the encrypted license key. + INTERNAL_LICENSE(50), + + /// Used for storing MRZ position. + MRZ_POSITION(61), + + /// Used for storing barcode position. + BARCODE_POSITION(62), + + /// Results in accordance with the BSI TR-03135 standard. + RESULT_TYPE_BSI_XML_V2(73), + + /// Used for storing document position. + DOCUMENT_POSITION(85), + + /// Not used + CUSTOM(100), + + /// Servers for storing the data reading results from the RFID-chip in a form + /// of a list of the logically separated data groups. + RFID_RAW_DATA(101), + + /// Servers for storing the results of data reading from the RFID-chip in a form + /// of a list of logically separated text data (text fields). + RFID_TEXT_DATA(102), + + /// Servers for storing the results of data reading from the RFID- chip in a form + /// of a list of logically separated graphic data (images, graphic fields). + RFID_IMAGE_DATA(103), + + /// Servers for storing the data reading results from the RFID-chip in a form + /// of a list of the logically separated data groups. + RFID_BINARY_DATA(104), + + /// Servers for storing the results of data reading in a form of a list of objects + /// of the original binary representation of the graphics in memory of the RFID-chip. + RFID_ORIGINAL_GRAPHICS(105), + + /// Digital Travel Credential data. + RFID_DTC_VC(109), + + MDL_PARSED_RESPONSE(121), + + /// VDS_NC. + VDSNC(124), + + /// VDS. + VDS(125); + + const ResultType(this.value); + final int value; + + static ResultType? getByValue(int? i) { + if (i == null) return null; + try { + return ResultType.values.firstWhere((x) => x.value == i); + } catch (_) { + return ResultType.NONE; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/authenticity/Authenticity.dart b/lib/src/results/authenticity/Authenticity.dart new file mode 100644 index 0000000000..8c8439a182 --- /dev/null +++ b/lib/src/results/authenticity/Authenticity.dart @@ -0,0 +1,98 @@ +// +// Authenticity.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains identifiers that determine the possibility +/// of performing different authenticity control procedures +/// using images for definite lighting schemes. +enum Authenticity { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// No authenticity control procedure provided for this document. + NONE(0), + + /// Document material UV fluorescence control (check for presence of UV + /// dull paper) is provided for this document. + UV_LUMINESCENCE(1), + + /// Control of MRZ contrast using the image for IR lighting scheme + /// is provided for this document. + IR_B900(2), + + /// Control of the presence of an image pattern with a specified color, + /// shape and brightness on a document page under white, UV and IR light. + IMAGE_PATTERN(4), + + /// UV fluorescence of protection fibers control is provided for this document. + AXIAL_PROTECTION(8), + + /// Blank elements visibility control using the images for IR lighting scheme + /// is provided for this document. + UV_FIBERS(16), + + /// Authenticity control using the images for white coaxial light scheme + /// is provided for this document. + IR_VISIBILITY(32), + + /// Make OCR for the text field in UV and compare it with other text sources. + OCR_SECURITY_TEXT(64), + + /// Find invisible personal information images. + IPI(128), + + /// Check photo is printed or sticked. + PHOTO_EMBED_TYPE(512), + + /// OVI check. + OVI(1024), + + /// Reserved for internal use. + HOLOGRAMS(4096), + + /// Reserved for internal use. + PHOTO_AREA(8192), + + /// Portrait comparison. + PORTRAIT_COMPARISON(32768), + + /// Barcode format check. + BARCODE_FORMAT_CHECK(65536), + + /// Kinegram. + KINEGRAM(131072), + + /// Reserved for internal use. + HOLOGRAMS_DETECTION(524288), + + /// Liveness. + LIVENESS(2097152), + + /// Extended OCR check. + OCR(4194304), + + /// Checks the correctness of the size of the MRZ lines, their relative position, + /// absence of signs that the image was edited. + MRZ(8388608), + + /// Status only. + STATUS_ONLY(2147483648); + + const Authenticity(this.value); + final int value; + + static Authenticity? getByValue(int? i) { + if (i == null) return null; + try { + return Authenticity.values.firstWhere((x) => x.value == i); + } catch (_) { + return Authenticity.UNKNOWN; + } + } +} diff --git a/lib/src/results/authenticity/authenticity_check.dart b/lib/src/results/authenticity/authenticity_check.dart new file mode 100644 index 0000000000..8165eec946 --- /dev/null +++ b/lib/src/results/authenticity/authenticity_check.dart @@ -0,0 +1,53 @@ +// +// AuthenticityCheck.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class AuthenticityCheck { + /// Indicates verification type result. + Authenticity get type => _type; + late Authenticity _type; + + /// Indicates verification result. + CheckResult get status => _status; + late CheckResult _status; + + int get pageIndex => _pageIndex; + late int _pageIndex; + + List get elements => _elements; + List _elements = []; + + String get typeName => _typeName; + late String _typeName; + + /// Allows you to deserialize object. + static AuthenticityCheck? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = AuthenticityCheck(); + + result._type = Authenticity.getByValue(jsonObject["type"])!; + result._status = CheckResult.getByValue(jsonObject["status"])!; + result._typeName = jsonObject["typeName"]; + result._pageIndex = jsonObject["pageIndex"]; + for (var item in jsonObject["elements"]) { + result.elements.addSafe(AuthenticityElement.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type.value, + "status": status.value, + "pageIndex": pageIndex, + "typeName": typeName, + "elements": elements.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/authenticity/authenticity_element.dart b/lib/src/results/authenticity/authenticity_element.dart new file mode 100644 index 0000000000..fccf400eed --- /dev/null +++ b/lib/src/results/authenticity/authenticity_element.dart @@ -0,0 +1,54 @@ +// +// AuthenticityElement.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class AuthenticityElement { + /// Indicates verification result of the field. + CheckResult get status => _status; + CheckResult _status = CheckResult.WAS_NOT_DONE; + + /// Indicates element type. + SecurityFeatureType get elementType => _elementType; + late SecurityFeatureType _elementType; + + /// Indicates element diagnose. + CheckDiagnose get elementDiagnose => _elementDiagnose; + late CheckDiagnose _elementDiagnose; + + String get elementTypeName => _elementTypeName; + late String _elementTypeName; + + String get elementDiagnoseName => _elementDiagnoseName; + late String _elementDiagnoseName; + + /// Allows you to deserialize object. + static AuthenticityElement? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = AuthenticityElement(); + + result._status = CheckResult.getByValue(jsonObject["status"])!; + result._elementType = + SecurityFeatureType.getByValue(jsonObject["elementType"])!; + result._elementDiagnose = + CheckDiagnose.getByValue(jsonObject["elementDiagnose"])!; + result._elementTypeName = jsonObject["elementTypeName"]; + result._elementDiagnoseName = jsonObject["elementDiagnoseName"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "status": status.value, + "elementType": elementType.value, + "elementDiagnose": elementDiagnose.value, + "elementTypeName": elementTypeName, + "elementDiagnoseName": elementDiagnoseName, + }.clearNulls(); +} diff --git a/lib/src/results/authenticity/authenticity_result.dart b/lib/src/results/authenticity/authenticity_result.dart new file mode 100644 index 0000000000..375326d96a --- /dev/null +++ b/lib/src/results/authenticity/authenticity_result.dart @@ -0,0 +1,37 @@ +// +// AuthenticityResult.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class AuthenticityResult { + @Deprecated("since 7.6, use `ResultsStatus.optical` instead") + CheckResult get status => _status; + late CheckResult _status; + + List get checks => _checks; + List _checks = []; + + /// Allows you to deserialize object. + static AuthenticityResult? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = AuthenticityResult(); + + result._status = CheckResult.getByValue(jsonObject["status"])!; + for (var item in jsonObject["checks"]) { + result._checks.addSafe(AuthenticityCheck.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "status": status.value, + "checks": checks.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/authenticity/check_diagnose.dart b/lib/src/results/authenticity/check_diagnose.dart new file mode 100644 index 0000000000..4d73f61697 --- /dev/null +++ b/lib/src/results/authenticity/check_diagnose.dart @@ -0,0 +1,383 @@ +// +// CheckDiagnose.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains identificators that determine the result of the +/// text field comparison from different sources. +enum CheckDiagnose { + /// Check was not performed. + UNKNOWN(0), + + /// Check was ok. + PASS(1), + + /// Invalid input data. + INVALID_INPUT_DATA(2), + + /// Internal error in module. + INTERNAL_ERROR(3), + + /// Exception caught + EXCEPTION_IN_MODULE(4), + + /// Can't make reliable decision. + UNCERTAIN_VERIFICATION(5), + + /// Image in necessary light is not found. + NECESSARY_IMAGE_NOT_FOUND(7), + + /// Necessary side of photo not found. + PHOTO_SIDES_NOT_FOUND(8), + + /// Invalid checksum. + INVALID_CHECKSUM(10), + + /// Syntactical error. + SYNTAX_ERROR(11), + + /// Logical error. + LOGIC_ERROR(12), + + /// Comparison was incorrect. + SOURCES_COMPARISON_ERROR(13), + + /// Logical error, e.g. the current date is less than issue date. + FIELDS_COMPARISON_LOGIC_ERROR(14), + + /// Wrong field format. + INVALID_FIELD_FORMAT(15), + + /// Element of the luminescense in the UV does not meet the standard. + TRUE_LUMINISCENCE_ERROR(20), + + /// The presence of excess luminescence in UV. + FALSE_LUMINISCENCE_ERROR(21), + + /// Pattern does not match the standard. + FIXED_PATTERN_ERROR(22), + + /// Low contrast of object in transmitted IR light. + LOW_CONTRAST_IN_IR_LIGHT(23), + + /// Background of page is too light or has invalid color. + INCORRECT_BACKGROUND_LIGHT(24), + + /// Background lightness of two pages is different. + BACKGROUND_COMPARISON_ERROR(25), + + /// Text has incorrect color of luminescence in UV light. + INCORRECT_TEXT_COLOR(26), + + /// Invalid luminescence in photo area. + PHOTO_FALSE_LUMINISCENCE(27), + + /// Object is too shifted from standard coordinates. + TOO_MUCH_SHIFT(28), + + /// Contact chip type mismatch. + CONTACT_CHIP_TYPE_MISMATCH(29), + + /// No protective fibers were found in UV. + FIBERS_NOT_FOUND(30), + + /// Error finding fibers, too many objects. + TOO_MANY_OBJECTS(31), + + /// Speck or exposure in UV image. + SPECKS_IN_UV(33), + + /// Resolution too low for fibers search. + TOO_LOW_RESOLUTION(34), + + /// Erroneous visibility of the element in IR. + INVISIBLE_ELEMENT_PRESENT(40), + + /// Element is absent in IR. + VISIBLE_ELEMENT_ABSENT(41), + + /// Element should be in color. + ELEMENT_SHOULD_BE_COLORED(42), + + /// Element should be in grayscale. + ELEMENT_SHOULD_BE_GRAYSCALE(43), + + PHOTO_WHITE_IR_DONT_MATCH(44), + + /// Glow paper in MRZ. + UV_DULL_PAPER_MRZ(50), + + /// Luminescence characters in MRZ. + FALSE_LUMINISCENCE_IN_MRZ(51), + + /// Glow in the field of photo paper. + UV_DULL_PAPER_PHOTO(52), + + /// Glow of the whole paper form. + UV_DULL_PAPER_BLANK(53), + + /// Glow of the document in UV. + UV_DULL_PAPER_ERROR(54), + + /// Element of blank has luminescence. + FALSE_LUMINISCENCE_IN_BLANK(55), + + /// Violation of the retro-reflective protection. + BAD_AREA_IN_AXIAL(60), + + /// Invalid params for IPI check. + FALSE_IPI_PARAMETERS(65), + + /// IR image too bright. + FIELD_POS_CORRECTOR_HIGHLIGHT_IR(80), + + /// Glares in photo area. + FIELD_POS_CORRECTOR_GLARES_IN_PHOTO_AREA(81), + + /// Photo replaced. + FIELD_POS_CORRECTOR_PHOTO_REPLACED(82), + + /// Facial landmarks (eyes) check error. + FIELD_POS_CORRECTOR_LANDMARKS_CHECK_ERROR(83), + + /// No facial image found. + FIELD_POS_CORRECTOR_FACE_PRESENCE_CHECK_ERROR(84), + + /// Facial image is found. + FIELD_POS_CORRECTOR_FACE_ABSENCE_CHECK_ERROR(85), + + CHD_FIELD_POS_CORRECTOR_INCORRECT_HEAD_POSITION(86), + + /// Age check error. + CHD_FIELD_POS_CORRECTOR_AGE_CHECK_ERROR(87), + + /// Sex check error. + CHD_FIELD_POS_CORRECTOR_SEX_CHECK_ERROR(88), + + /// OVI object is not visible in IR. + OVI_IR_INVISIBLE(90), + + /// Insufficient area of the object OVI. + OVI_INSUFFICIENT_AREA(91), + + /// OVI color of an object does not change. + OVI_COLOR_INVARIABLE(92), + + /// Impossible to determine the color of the AXIAL image. + OVI_BAD_COLOR_FRONT(93), + + /// Impossible to determine the color of the WHITE image. + OVI_BAD_COLOR_SIDE(94), + + /// Wide color spread. + OVI_WIDE_COLOR_SPREAD(95), + + /// Not enough color information. + OVI_BAD_COLOR_PERCENT(96), + + /// Hologram element absent. + HOLOGRAM_ELEMENT_ABSENT(100), + + /// There are no side or top images. Check cancelled. + HOLOGRAM_SIDE_TOP_IMAGES_ABSENT(101), + + /// Hologram element present. + HOLOGRAM_ELEMENT_PRESENT(102), + + HOLOGRAM_FRAMES_IS_ABSENT(103), + + HOLOGRAM_HOLO_FIELD_IS_ABSENT(104), + + /// Pattern is interrupted. + PHOTO_PATTERN_INTERRUPTED(110), + + /// Some of the patterns are shifted relative to each other. + PHOTO_PATTERN_SHIFTED(111), + + /// Some parts of the pattern have different color. + PHOTO_PATTERN_DIFFERENT_COLORS(112), + + /// Pattern visible in the infrared. + PHOTO_PATTERN_IR_VISIBLE(113), + + /// Edge of the photo does not intersect with the pattern. Check cancelled. + PHOTO_PATTERN_NOT_INTERSECT(114), + + /// Size of the photo does not correspond to requirements. + PHOTO_SIZE_IS_WRONG(115), + + /// Some parts of the pattern have invalid color. + PHOTO_PATTERN_INVALID_COLOR(116), + + /// Some patterns are relatively shifted. + PHOTO_PATTERN_SHIFTED_VERT(117), + + /// Not found Pattern. Check cancelled. + PHOTO_PATTERN_PATTERN_NOT_FOUND(118), + + /// Different lines thickness. + PHOTO_PATTERN_DIFFERENT_LINES_THICKNESS(119), + + /// Photo shape is not rectangular. + PHOTO_IS_NOT_RECTANGLE(120), + + /// Photo corners don't meet the requirements. + PHOTO_CORNERS_IS_WRONG(121), + + /// For internal use only. + DOCUMENT_IS_CANCELLING(122), + + ///Text color should be blue. + TEXT_COLOR_SHOULD_BE_BLUE(130), + + /// Text color should be green. + TEXT_COLOR_SHOULD_BE_GREEN(131), + + /// Text color should be red. + TEXT_COLOR_SHOULD_BE_RED(132), + + /// Text should be black. + TEXT_SHOULD_BE_BLACK(133), + + /// Security text is absent. + SECURITY_TEXT_IS_ABSENT(134), + + /// Barcode read with errors. + BARCODE_WAS_READ_WITH_ERRORS(140), + + /// Barcode data format error. + BARCODE_DATA_FORMAT_ERROR(141), + + /// Barcode size parameters error. + BARCODE_SIZE_PARAMS_ERROR(142), + + /// Not all barcodes read. + NOT_ALL_BARCODES_READ(143), + + /// Glares in barcode area. + GLARES_IN_BARCODE_AREA(144), + + CHD_NO_CERTIFICATE_FOR_DIGITAL_SIGNATURE_CHECK(145), + + /// Portraits differ. + PORTRAIT_COMPARISON_PORTRAITS_DIFFER(150), + + /// No reply from portrait comparison service. + PORTRAIT_COMPARISON_NO_SERVICE_REPLY(151), + + /// Portrait comparison service error. + PORTRAIT_COMPARISON_SERVICE_ERROR(152), + + /// Not enough images. + PORTRAIT_COMPARISON_NOT_ENOUGH_IMAGES(153), + + /// No image from camera. + PORTRAIT_COMPARISON_NO_LIVE_PHOTO(154), + + /// No license on portrait comparison service. + PORTRAIT_COMPARISON_NO_SERVICE_LICENSE(155), + + /// No portraits detected + PORTRAIT_COMPARISON_NO_PORTRAIT_DETECTED(156), + + /// Unsuitable light conditions. + MOBILE_IMAGES_UNSUITABLE_LIGHT_CONDITIONS(160), + + /// No difference in visible and UV mobile images. Possible UV torch malfunction. + MOBILE_IMAGES_WHITE_UV_NO_DIFFERENCE(161), + + /// Fingerprints comparison mismatch. + FINGERPRINTS_COMPARISON_MISMATCH(170), + + /// Face isn’t detected. + HOLO_PHOTO_FACE_NOT_DETECTED(180), + + /// Face comparison failed. + HOLO_PHOTO_FACE_COMPARISON_FAILED(181), + + /// Glare in center absent. + HOLO_PHOTO_FACE_GLARE_IN_CENTER_ABSENT(182), + + /// Hologram element shape error. + HOLO_ELEMENT_SHAPE_ERROR(183), + + /// Algorithm steps error. + ALGORITHM_STEPS_ERROR(184), + + /// Hologram areas not loaded. + HOLO_AREAS_NOT_LOADED(185), + + /// Hologram check finished by time out. + FINISHED_BY_TIMEOUT(186), + + HOLO_PHOTO_DOCUMENT_OUTSIDE_FRAME(187), + + LIVENESS_DEPTH_CHECK_FAILED(190), + + /// Hologram check finished by time out. + MRZ_QUALITY_WRONG_SYMBOL_POSITION(200), + + /// Wrong background. + MRZ_QUALITY_WRONG_BACKGROUND(201), + + MRZ_QUALITY_WRONG_MRZ_WIDTH(202), + + MRZ_QUALITY_WRONG_MRZ_HEIGHT(203), + + MRZ_QUALITY_WRONG_LINE_POSITION(204), + + MRZ_QUALITY_WRONG_FONT_TYPE(205), + + OCR_QUALITY_TEXT_POSITION(220), + + OCR_QUALITY_INVALID_FONT(221), + + OCR_QUALITY_INVALID_BACKGROUND(222), + + LAS_INK_INVALID_LINES_FREQUENCY(230), + + DOC_LIVENESS_DOCUMENT_NOT_LIVE(238), + + CHD_DOC_LIVENESS_BLACK_AND_WHITE_COPY_DETECTED(239), + + /// Traces of an electronic device were found in the image. + DOC_LIVENESS_ELECTRONIC_DEVICE_DETECTED(240), + + /// Invalid barcode background. + DOC_LIVENESS_INVALID_BARCODE_BACKGROUND(241), + + /// Virtual camera was detected. + DOC_LIVENESS_VIRTUAL_CAMERA_DETECTED(242), + + ICAO_IDB_BASE_32_ERROR(243), + + ICAO_IDB_ZIPPED_ERROR(244), + + ICAO_IDB_MESSAGE_ZONE_EMPTY(245), + + ICAO_IDB_SIGNATURE_MUST_BE_PRESENT(246), + + ICAO_IDB_SIGNATURE_MUST_NOT_BE_PRESENT(247), + + ICAO_IDB_CERTIFICATE_MUST_NOT_BE_PRESENT(248), + + /// Incorrect object color. + INCORRECT_OBJECT_COLOR(250); + + const CheckDiagnose(this.value); + final int value; + + static CheckDiagnose? getByValue(int? i) { + if (i == null) return null; + try { + return CheckDiagnose.values.firstWhere((x) => x.value == i); + } catch (_) { + return CheckDiagnose.UNKNOWN; + } + } +} diff --git a/lib/src/results/authenticity/security_feature_type.dart b/lib/src/results/authenticity/security_feature_type.dart new file mode 100644 index 0000000000..fc891be52d --- /dev/null +++ b/lib/src/results/authenticity/security_feature_type.dart @@ -0,0 +1,190 @@ +// +// SecurityFeatureType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains identifiers that determine the types of elements +/// for the document authenticity check. +enum SecurityFeatureType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-2), + + NONE(-1), + + /// Blank element. + BLANK(0), + + /// Personalization element. + FILL(1), + + /// Photo. + PHOTO(2), + + /// MRZ. + MRZ(3), + + /// Photo surrounding area. + FALSE_LUMINESCENCE(4), + + /// Reserved for internal use. + HOLO_SIMPLE(5), + + /// Reserved for internal use. + HOLO_VERIFY_STATIC(6), + + /// Reserved for internal use. + HOLO_VERIFY_MULTI_STATIC(7), + + /// Reserved for internal use. + HOLO_VERIFY_DINAMIC(8), + + /// Reserved for internal use. + PATTERN_NOT_INTERRUPTED(9), + + /// Reserved for internal use. + PATTERN_NOT_SHIFTED(10), + + /// Reserved for internal use. + PATTERN_SAME_COLORS(11), + + /// Reserved for internal use. + PATTERN_IR_INVISIBLE(12), + + /// Reserved for internal use. + PHOTO_SIZE_CHECK(13), + + /// Main portrait and ghost portrait comparison. + PORTRAIT_COMPARISON_VS_GHOST(14), + + /// Main portrait and RFID portrait comparison. + PORTRAIT_COMPARISON_VS_RFID(15), + + /// Main portrait and other page portrait comparison. + PORTRAIT_COMPARISON_VS_VISUAL(16), + + /// Barcode format check. + BARCODE(17), + + /// Different lines thickness. + PATTERN_DIFFERENT_LINES_THICKNESS(18), + + /// Portrait comparison with image from camera. + PORTRAIT_COMPARISON_VS_CAMERA(19), + + /// Portrait comparison with image from RFID. + PORTRAIT_COMPARISON_RFID_VS_CAMERA(20), + + /// Ghost photo. + GHOST_PHOTO(21), + + /// Clear ghost photo. + CLEAR_GHOST_PHOTO(22), + + /// Invisible object. + INVISIBLE_OBJECT(23), + + /// Low contrast object. + LOW_CONTRAST_OBJECT(24), + + /// Photo color type. + PHOTO_COLOR(25), + + /// Photo squareness check. + PHOTO_SHAPE(26), + + /// Photo corners shape. + PHOTO_CORNERS(27), + + DOCUMENT_CANCELLING_DETECTOR(28), + OCR(28), + + PORTRAIT_COMPARISON_EXTVS_VISUAL(29), + + PORTRAIT_COMPARISON_EXTVS_RFID(30), + + PORTRAIT_COMPARISON_EXTVS_LIVE(31), + + LIVENESS_DEPTH(32), + + MICROTEXT(33), + + FLUORESCENT_OBJECT(34), + + LANDMARKS_CHECK(35), + + FACE_PRESENCE(36), + + FACE_ABSENCE(38), + + LIVENESS_SCREEN_CAPTURE(39), + + /// Checking the presence of a device that could be used for document capturing. + LIVENESS_ELECTRONIC_DEVICE(40), + + LIVENESS_OVI(41), + + BARCODE_SIZE_CHECK(42), + + LAS_INK(43), + + LIVENESS_MLI(44), + + LIVENESS_BARCODE_BACKGROUND(45), + + /// Visual zone portrait image vs. image from barcode. + PORTRAIT_COMPARISON_VS_BARCODE(46), + + /// Image from barcode vs. image from RFID. + PORTRAIT_COMPARISON_RFID_VS_BARCODE(47), + + /// Image from barcode vs. external source image. + PORTRAIT_COMPARISON_EXT_VS_BARCODE(48), + + /// Image from barcode vs. photo from camera. + PORTRAIT_COMPARISON_BARCODE_VS_CAMERA(49), + + /// Digital signature сheck. + CHECK_DIGITAL_SIGNATURE(50), + + /// Contact сhip check. + CONTACT_CHIP_CLASSIFICATION(51), + + HEAD_POSITION_CHECK(52), + + LIVENESS_BLACK_AND_WHITE_COPY_CHECK(53), + + LIVENESS_DYNAPRINT(54), + + LIVENESS_GEOMETRY_CHECK(55), + + /// Age check. + AGE_CHECK(56), + + /// Sex check. + SEX_CHECK(57), + + PORTRAIT_COMPARISON_RFIDVSGHOST(58), + + PORTRAIT_COMPARISON_BARCODEVSGHOST(59), + + PORTRAIT_COMPARISON_GHOSTVSLIVE(60), + + PORTRAIT_COMPARISON_EXTVSGHOST(61); + + const SecurityFeatureType(this.value); + final int value; + + static SecurityFeatureType? getByValue(int? i) { + if (i == null) return null; + try { + return SecurityFeatureType.values.firstWhere((x) => x.value == i); + } catch (_) { + return SecurityFeatureType.UNKNOWN; + } + } +} diff --git a/lib/src/results/barcode/barcode_field.dart b/lib/src/results/barcode/barcode_field.dart new file mode 100644 index 0000000000..6f43eb5773 --- /dev/null +++ b/lib/src/results/barcode/barcode_field.dart @@ -0,0 +1,55 @@ +// +// BarcodeField.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class BarcodeField { + /// Decoded barcode type. + BarcodeType get barcodeType => _barcodeType; + late BarcodeType _barcodeType; + + /// Indicates barcode reading result. + BarcodeStatus get status => _status; + late BarcodeStatus _status; + + /// Contains the information about the PDF417 barcode. + PDF417Info? get pdf417Info => _pdf417Info; + PDF417Info? _pdf417Info; + + /// Results of reading data from barcode modules. + Uint8List? get data => _data; + Uint8List? _data; + + /// Indicates an index of the document page, whence the result is received. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Allows you to deserialize object. + static BarcodeField? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = BarcodeField(); + + result._barcodeType = BarcodeType.getByValue(jsonObject["barcodeType"])!; + result._status = BarcodeStatus.getByValue(jsonObject["status"])!; + result._pageIndex = jsonObject["pageIndex"]; + result._pdf417Info = PDF417Info.fromJson(jsonObject["pdf417Info"]); + result._data = _bytesFromBase64(jsonObject["data"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "barcodeType": barcodeType.value, + "status": status.value, + "pdf417Info": pdf417Info?.toJson(), + "data": _bytesToBase64(data), + "pageIndex": pageIndex, + }.clearNulls(); +} diff --git a/lib/src/results/barcode/barcode_result.dart b/lib/src/results/barcode/barcode_result.dart new file mode 100644 index 0000000000..53d75c97ec --- /dev/null +++ b/lib/src/results/barcode/barcode_result.dart @@ -0,0 +1,31 @@ +// +// BarcodeResult.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, describing single barcode extracted. +class BarcodeResult { + List get fields => _fields; + List _fields = []; + + /// Allows you to deserialize object. + static BarcodeResult? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = BarcodeResult(); + + for (var item in jsonObject["fields"]) { + result._fields.addSafe(BarcodeField.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"fields": fields.map((e) => e.toJson()).toList()}.clearNulls(); +} diff --git a/lib/src/results/barcode/barcode_status.dart b/lib/src/results/barcode/barcode_status.dart new file mode 100644 index 0000000000..d5cba70c0e --- /dev/null +++ b/lib/src/results/barcode/barcode_status.dart @@ -0,0 +1,119 @@ +// +// BarcodeStatus.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +enum BarcodeStatus { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// No error. + NO_ERR(0), + + /// Invalid result. + INVALID_RESULT(140), + + /// Null pointer of input arg/param error. + NULL_PTR_ERR(-6001), + + /// Function arg/param is bad. + BAD_ARG_ERR(-6002), + + /// Wrong value of data size. + SIZE_ERR(-6003), + + /// Bad values of any parameter range. + RANGE_ERR(-6004), + + /// Internal program error. + INTERNAL_ERR(-6005), + + /// try-except process. + TRY_EXCEPT_ERR(-6006), + + /// Barcode detection error. + BAR_CODE_NOT_FOUND(-6008), + + /// Barcode decoding error. + BAR_CODE_DECODE_ERR(-6010), + + /// "ImageProcess.dll" connection error. + NO_USER_DLL_FOUND(-6019), + + /// IPP Dll connection error. + NO_IPP_DLL_FOUND(-6020), + + /// Run-time error in IPP-function. + IPP_EXEC_ERR(-6024), + + /// try-except execution in IPP-function. + IPP_TRY_EXCEPT_ERR(-6025), + + /// Input data error. + BARCODE_ERROR_INPUT_PARAM(-11001), + + /// Initialization error. + BARCODE_ERROR_FINIT(-11006), + + /// "IpDecode.dll" connection error. + BARCODE_ERROR_NOT_LOAD_IP_DECODED_LL(-11012), + + /// Internal program error. + BARCODE_ERROR_INNER_PROBLEM(-11100), + + /// 1D-barcode decoding error. + BARCODE_ERROR_DECODE_1D_BAD_DECODE(-11200), + + /// Row or Column count computational error (PDF417). + BARCODE_ERROR_FIND_ROW_OR_COLUMN(-11201), + + /// MinX computational error (PDF417). + BARCODE_ERROR_FIND_3X8_2D_X(-11202), + + /// MinY computational error (PDF417). + BARCODE_ERROR_FIND_3X8_2D_Y(-11203), + + /// Invalid barcode angle (> 3 degree). + BARCODE_ERROR_2D_UGOL_MAX(-11204), + + /// The result may contain decoding errors. + BARCODE_ERROR_INDEFINITELY_DECODED(-11210), + + /// Dll initialization error. + BARCODE_ERROR_DLL_NOT_INIT(-11300), + + /// try-except in IPDECODE-function. + BARCODE_ERROR_IP_DECODE_DLL_Try_Except(-11400), + + /// Too many invalid code words. + IPDECODE_ERROR_LARGEERRORS(-4503), + + /// Invalid number of columns. + IPDECODE_ERROR_FAULTCOLUMNS(-4504), + + /// Invalid number of rows. + IPDECODE_ERROR_FAULTROWS(-4505), + + /// Correction Level error. + IPDECODE_ERROR_INCORRECT_ERROR_LEVEL(-4511), + + /// Loading "DevTable.bin" error. + IPDECODE_ERROR_LOADING_DEV_TABLE(-4512); + + const BarcodeStatus(this.value); + final int value; + + static BarcodeStatus? getByValue(int? i) { + if (i == null) return null; + try { + return BarcodeStatus.values.firstWhere((x) => x.value == i); + } catch (_) { + return BarcodeStatus.UNKNOWN; + } + } +} diff --git a/lib/src/results/barcode/barcode_type.dart b/lib/src/results/barcode/barcode_type.dart new file mode 100644 index 0000000000..9321f8f986 --- /dev/null +++ b/lib/src/results/barcode/barcode_type.dart @@ -0,0 +1,93 @@ +// +// BarcodeType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains the types of barcodes that can be processed. +enum BarcodeType { + /// Unknown. + UNKNOWN(0), + + /// One-dimensional barcode, ISO 15417 (ANSI/AIM BC4-1999 Code 128). + BCT_CODE128(1), + + /// One-dimensional barcode, ISO 16388 (ANSI/AIM BC1-1995 Code 39). + CODE39(2), + + /// One-dimensional barcode, EAN8, ISO 15418. + EAN8(3), + + /// One-dimensional barcode, Interleaved 2 of 5, ISO 16390 (ANSI/AIM BC2-1995 Interleaved 2 of 5). + ITF(4), + + /// Two-dimensional barcode, ISO 15438 (AIM USS PDF417). + PDF417(5), + + /// One-dimensional barcode, Standard 2 of 5 (Industrial). + STF(6), + + /// One-dimensional barcode, Matrix 2 of 5. + MTF(7), + + /// One-dimensional barcode, IATA 2 of 5 (Airline). + IATA(8), + + /// One-dimensional barcode, (ANSI/AIM BC3-1995, USS - Codabar). + CODABAR(9), + + /// One-dimensional barcode, UPC-A. + UPCA(10), + + /// One-dimensional barcode, (ANSI/AIM BC5-1995, USS - Code 93). + CODE93(11), + + /// One-dimensional barcode, UPC-E. + UPCE(12), + + /// One-dimensional barcode, EAN13, ISO 15418. + EAN13(13), + + /// Two-dimensional QR barcode. + QRCODE(14), + + /// Two-dimensional AZTEC barcode. + AZTEC(15), + + /// Two-dimensional DATAMATRIX barcode. + DATAMATRIX(16), + + /// One-dimensional barcodes. + ALL_1D(17), + + /// One-dimensional barcode, Code 11. + CODE11(18), + + /// Two-dimensional barcode, JAB Code + JABCODE(19); + + const BarcodeType(this.value); + final int value; + + static BarcodeType? getByValue(int? i) { + if (i == null) return null; + try { + return BarcodeType.values.firstWhere((x) => x.value == i); + } catch (_) { + return BarcodeType.UNKNOWN; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/barcode/pdf417_info.dart b/lib/src/results/barcode/pdf417_info.dart new file mode 100644 index 0000000000..af1b29395d --- /dev/null +++ b/lib/src/results/barcode/pdf417_info.dart @@ -0,0 +1,39 @@ +// +// PDF417Info.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class PDF417Info { + /// Barcode error correction level. + int get errorLevel => _errorLevel; + late int _errorLevel; + + /// Number of columns in a barcode. + int get columns => _columns; + late int _columns; + + /// Number of rows in a barcode. + int get rows => _rows; + late int _rows; + + /// Allows you to deserialize object. + static PDF417Info? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = PDF417Info(); + + result._errorLevel = jsonObject["errorLevel"]; + result._columns = jsonObject["columns"]; + result._rows = jsonObject["rows"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"errorLevel": errorLevel, "columns": columns, "rows": rows}.clearNulls(); +} diff --git a/lib/src/results/document_type.dart b/lib/src/results/document_type.dart new file mode 100644 index 0000000000..7832b64e27 --- /dev/null +++ b/lib/src/results/document_type.dart @@ -0,0 +1,869 @@ +// +// DocumentType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class DocumentType { + /// Document type name. + String? get name => _name; + String? _name; + + /// Document type numeric code. + int get id => _id; + late int _id; + + /// Document issuing country ICAO code. + String? get iCAOCode => _iCAOCode; + String? _iCAOCode; + + /// An array of IRS document identifiers. + List? get fDSID => _fDSID; + List? _fDSID; + + /// Document type. + DocType get type => _type; + late DocType _type; + + /// Document format. + DocFormat get format => _format; + late DocFormat _format; + + /// Flag for MRZ presence on a document. + bool get mrz => _mrz; + late bool _mrz; + + /// Document deprecation. + bool get isDeprecated => _isDeprecated; + late bool _isDeprecated; + + /// Document description text. + String? get description => _description; + String? _description; + + /// Document issue year. + String? get year => _year; + String? _year; + + /// Document issuing country name. + String? get countryName => _countryName; + String? _countryName; + + /// An index of the document page whence results are received. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Allows you to deserialize object. + static DocumentType? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocumentType(); + + result._pageIndex = jsonObject["pageIndex"]; + result._id = jsonObject["documentID"]; + result._type = DocType.getByValue(jsonObject["dType"])!; + result._format = DocFormat.getByValue(jsonObject["dFormat"])!; + result._mrz = jsonObject["dMRZ"]; + result._isDeprecated = jsonObject["isDeprecated"]; + result._name = jsonObject["name"]; + result._iCAOCode = jsonObject["ICAOCode"]; + result._description = jsonObject["dDescription"]; + result._year = jsonObject["dYear"]; + result._countryName = jsonObject["dCountryName"]; + result._fDSID = _intListFrom(jsonObject["FDSID"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "name": name, + "documentID": id, + "ICAOCode": iCAOCode, + "FDSID": fDSID, + "dType": type.value, + "dFormat": format.value, + "dMRZ": mrz, + "isDeprecated": isDeprecated, + "dDescription": description, + "dYear": year, + "dCountryName": countryName, + "pageIndex": pageIndex, + }.clearNulls(); +} + +/// Defining the geometric format of documents in accordance with ISO / IEC 7810. +enum DocFormat { + /// Unknown format. + UNKNOWN(-1), + + /// ID1 document format. + ID1(0), + + /// ID2 document format. + ID2(1), + + /// ID3 document format. + ID3(2), + + /// Undefined document format. + NON(3), + + /// A4 document format. + A4(4), + + /// ID3 double document format. + ID3_x2(5), + + /// ID2 Turkey document format. + ID2_TURKEY(6), + + /// ID1 format document rotated 90 degrees. + ID1_90(10), + + /// ID1 format document rotated 180 degrees. + ID1_180(11), + + /// ID1 format document rotated 270 degrees. + ID1_270(12), + + /// ID2 format document rotated 180 degrees. + ID2_180(13), + + /// ID3 format document rotated 180 degrees. + ID3_180(14), + + /// Arbitrary format. + CUSTOM(1000), + + /// Photo format. + PHOTO(1001), + + /// Flexible format. Standard formats can be resized during cropping, depending + /// on various factors: light, background etc. + FLEXIBLE(1002); + + const DocFormat(this.value); + final int value; + + static DocFormat? getByValue(int? i) { + if (i == null) return null; + try { + return DocFormat.values.firstWhere((x) => x.value == i); + } catch (_) { + return DocFormat.UNKNOWN; + } + } +} + +enum DocType { + /// An unknown document type. + NotDefined(0), + + /// Passport. + Passport(11), + + /// Identity Card. + IdentityCard(12), + + /// Diplomatic Passport. + DiplomaticPassport(13), + + /// Service Passport. + ServicePassport(14), + + /// Seaman's Identity Document. + SeamanIdentityDocument(15), + + /// Identity Card for Residence. + IdentityCardForResidence(16), + + /// Travel Document. + TravelDocument(17), + + /// Other. + Other(99), + + /// Visa ID-2. + VisaID2(29), + + /// Visa ID-3. + VisaID3(30), + + /// National Identity Card. + NationalIdentityCard(20), + + /// Social Identity Card. + SocialIdentityCard(21), + + /// Alien's Identity Card. + AliensIdentityCard(22), + + /// Privileged Identity Card. + PrivilegedIdentityCard(23), + + /// Residence Permit Identity Card. + ResidencePermitIdentityCard(24), + + /// Origin Card. + OriginCard(25), + + /// Emergency Passport. + EmergencyPassport(26), + + /// Alien's Passport. + AliensPassport(27), + + /// Alternative Identity Card. + AlternativeIdentityCard(28), + + /// Authorization Card. + AuthorizationCard(32), + + /// Beginner Permit. + BeginnerPermit(33), + + /// Border Crossing Card. + BorderCrossingCard(34), + + /// Chauffeur License. + ChauffeurLicense(35), + + /// Chauffeur License under 18. + ChauffeurLicenseUnder18(36), + + /// Chauffeur License under 21. + ChauffeurLicenseUnder21(37), + + /// Commercial Driving License. + CommercialDrivingLicense(38), + + /// Commercial Driving License Instructional Permit. + CommercialDrivingLicenseInstructionalPermit(39), + + /// Commercial Driving License under 18. + CommercialDrivingLicenseUnder18(40), + + /// Commercial Driving License under 21. + CommercialDrivingLicenseUnder21(41), + + /// Commercial Indtuction Permit. + CommercialInstructionPermit(42), + + /// Commercial New Permit. + CommercialNewPermit(43), + + /// Concealed Carry License. + ConcealedCarryLicense(44), + + /// Concealed Firearm Permit. + ConcealedFirearmPermit(45), + + /// Conditional Driving License. + ConditionalDrivingLicense(46), + + /// Department of Veterans Affairs Identity Card. + DepartmentOfVeteransAffairsIdentityCard(47), + + /// Diplomatic Driving License. + DiplomaticDrivingLicense(48), + + /// Driving License. + DrivingLicense(49), + + /// Driving License Instructional Permit. + DrivingLicenseInstructionalPermit(50), + + /// Driving License Instructional Permit under 18. + DrivingLicenseInstructionalPermitUnder18(51), + + /// Driving License Instructional Permit under 21. + DrivingLicenseInstructionalPermitUnder21(52), + + /// Driving License Learners Permit. + DrivingLicenseLearnersPermit(53), + + /// Driving License Learners Permit under 18. + DrivingLicenseLearnersPermitUnder18(54), + + /// Driving License Learners Permit under 21. + DrivingLicenseLearnersPermitUnder21(55), + + /// Driving License Novice. + DrivingLicenseNovice(56), + + /// Driving License Novice under 18. + DrivingLicenseNoviceUnder18(57), + + /// Driving License Novice under 21. + DrivingLicenseNoviceUnder21(58), + + /// Driving License Registered Offender. + DrivingLicenseRegisteredOffender(59), + + /// Driving License Redticted under 18. + DrivingLicenseRestrictedUnder18(60), + + /// Driving License Redticted under 21. + DrivingLicenseRestrictedUnder21(61), + + /// Driving License Temporary Visitor. + DrivingLicenseTemporaryVisitor(62), + + /// Driving License Temporary Visitor under 18. + DrivingLicenseTemporaryVisitorUnder18(63), + + /// Driving License Temporary Visitor under 21. + DrivingLicenseTemporaryVisitorUnder21(64), + + /// Driving License under 18. + DrivingLicenseUnder18(65), + + /// Driving License under 21. + DrivingLicenseUnder21(66), + + /// Employment Driving Permit. + EmploymentDrivingPermit(67), + + /// Enhanced Chauffeur License. + EnhancedChauffeurLicense(68), + + /// Enhanced Chauffeur License under 18. + EnhancedChauffeurLicenseUnder18(69), + + /// Enhanced Chauffeur License under 21. + EnhancedChauffeurLicenseUnder21(70), + + /// Enhanced Commercial Driving License. + EnhancedCommercialDrivingLicense(71), + + /// Enhanced Driving License. + EnhancedDrivingLicense(72), + + /// Enhanced Driving License under 18. + EnhancedDrivingLicenseUnder18(73), + + /// Enhanced Driving License under 21. + EnhancedDrivingLicenseUnder21(74), + + /// Enhanced Identity Card. + EnhancedIdentityCard(75), + + /// Enhanced Identity Card under 18. + EnhancedIdentityCardUnder18(76), + + /// Enhanced Identity Card under 21. + EnhancedIdentityCardUnder21(77), + + /// Enhanced Operators License. + EnhancedOperatorsLicense(78), + + /// Firearms Permit. + FirearmsPermit(79), + + /// Full Provisional License. + FullProvisionalLicense(80), + + /// Full Provisional License under 18. + FullProvisionalLicenseUnder18(81), + + /// Full Provisional License under 21. + FullProvisionalLicenseUnder21(82), + + /// Geneva Conventions Identity Card. + GenevaConventionsIdentityCard(83), + + /// Graduated Driving License under 18. + GraduatedDrivingLicenseUnder18(84), + + /// Graduated Driving License under 21. + GraduatedDrivingLicenseUnder21(85), + + /// Graduated Indtuction Permit under 18. + GraduatedInstructionPermitUnder18(86), + + /// Graduated Indtuction Permit under 21. + GraduatedInstructionPermitUnder21(87), + + /// Graduated License under 18. + GraduatedLicenseUnder18(88), + + /// Graduated License under 21. + GraduatedLicenseUnder21(89), + + /// Handgun Carry Permit. + HandgunCarryPermit(90), + + /// Identity and Privilege Card. + IdentityAndPrivilegeCard(91), + + /// Identity Card Mobility Impaired. + IdentityCardMobilityImpaired(92), + + /// Identity Card Registered Offender. + IdentityCardRegisteredOffender(93), + + /// Identity Card Temporary Visitor. + IdentityCaremporaryVisitor(94), + + /// Identity Card Temporary Visitor under 18. + IdentityCaremporaryVisitorUnder18(95), + + /// Identity Card Temporary Visitor under 21. + IdentityCaremporaryVisitorUnder21(96), + + /// Identity Card under 18. + IdentityCardUnder18(97), + + /// Identity Card under 21. + IdentityCardUnder21(98), + + /// Ignition Interlock Permit. + IgnitionInterlockPermit(100), + + /// Immigrant Visa. + ImmigrantVisa(101), + + /// Indtuction Permit. + InstructionPermit(102), + + /// Indtuction Permit under 18. + InstructionPermitUnder18(103), + + /// Indtuction Permit under 21. + InstructionPermitUnder21(104), + + /// Interim Driving License. + InterimDrivingLicense(105), + + /// Interim Identity Card. + InterimIdentityCard(106), + + /// Intermediate Driving License. + IntermediateDrivingLicense(107), + + /// Intermediate Driving License under 18. + IntermediateDrivingLicenseUnder18(108), + + /// Intermediate Driving License under 21. + IntermediateDrivingLicenseUnder21(109), + + /// Junior Driving License. + JuniorDrivingLicense(110), + + /// Learner Instructional Permit. + LearnerInstructionalPermit(111), + + /// Learner License. + LearnerLicense(112), + + /// Learner License under 18. + LearnerLicenseUnder18(113), + + /// Learner License under 21. + LearnerLicenseUnder21(114), + + /// Learner Permit. + LearnerPermit(115), + + /// Learner Permit under 18. + LearnerPermitUnder18(116), + + /// Learner Permit under 21. + LearnerPermitUnder21(117), + + /// Limited License. + LimitedLicense(118), + + /// Limited Permit. + LimitedPermit(119), + + /// Limited Term Driving License. + LimiteermDrivingLicense(120), + + /// Limited Term Identity Card. + LimiteermIdentityCard(121), + + /// Liquor Identity Card. + LiquorIdentityCard(122), + + /// New Permit. + NewPermit(123), + + /// New Permit under 18. + NewPermitUnder18(124), + + /// New Permit under 21. + NewPermitUnder21(125), + + /// Non-US Citizen Driving License. + NonUsCitizenDrivingLicense(126), + + /// Occupational Driving License. + OccupationalDrivingLicense(127), + + /// Oneida Tribe of Indians Identity Card. + OneidaTribeOfIndiansIdentityCard(128), + + /// Operator License. + OperatorLicense(129), + + /// Operator License under 18. + OperatorLicenseUnder18(130), + + /// Operator License under 21. + OperatorLicenseUnder21(131), + + /// Permanent Driving License. + PermanentDrivingLicense(132), + + /// Permit to Re-enter. + PermitToReEnter(133), + + /// Probationary Auto License. + ProbationaryAutoLicense(134), + + /// Probationary Auto License under 18. + ProbationaryDrivingLicenseUnder18(135), + + /// Probationary Auto License under 21. + ProbationaryDrivingLicenseUnder21(136), + + /// Probationary Vehicle Salesperson License. + ProbationaryVehicleSalespersonLicense(137), + + /// Provisional Driving License. + ProvisionalDrivingLicense(138), + + /// Provisional Driving License under 18. + ProvisionalDrivingLicenseUnder18(139), + + /// Provisional Driving License under 21. + ProvisionalDrivingLicenseUnder21(140), + + /// Provisional License. + ProvisionalLicense(141), + + /// Provisional License under 18. + ProvisionalLicenseUnder18(142), + + /// Provisional License under 21. + ProvisionalLicenseUnder21(143), + + /// Public Passenger Chauffeur License. + PublicPassengerChauffeurLicense(144), + + /// Racing and Gaming Comission Card. + RacingAndGamingComissionCard(145), + + /// Refugee Travel Document. + RefugeeTravelDocument(146), + + /// Renewal Permit. + RenewalPermit(147), + + /// Restricted Commercial Driving License. + RestrictedCommercialDrivingLicense(148), + + /// Restricted Driving License. + RestrictedDrivingLicense(149), + + /// Restricted Permit. + RestrictedPermit(150), + + /// Seasonal Permit. + SeasonalPermit(151), + + /// Seasonal Resident Identity Card. + SeasonalResidentIdentityCard(152), + + /// Senior Citizen Identity Card. + SeniorCitizenIdentityCard(153), + + /// Sex Offender. + SexOffender(154), + + /// Social Security Card. + SocialSecurityCard(155), + + /// Temporary Driving License. + TemporaryDrivingLicense(156), + + /// Temporary Driving License under 18. + TemporaryDrivingLicenseUnder18(157), + + /// Temporary Driving License under 21. + TemporaryDrivingLicenseUnder21(158), + + /// Temporary Identity Card. + TemporaryIdentityCard(159), + + /// Temporary Instruction Permit Identity Card. + TemporaryInstructionPermitIdentityCard(160), + + /// Temporary Instruction Permit Identity Card under 18. + TemporaryInstructionPermitIdentityCardUnder18(161), + + /// Temporary Instruction Permit Identity Card under 21. + TemporaryInstructionPermitIdentityCardUnder21(162), + + /// Temporary Visitor Driving License. + TemporaryVisitorDrivingLicense(163), + + /// Temporary Visitor Driving License under 18. + TemporaryVisitorDrivingLicenseUnder18(164), + + /// Temporary Visitor Driving License under 21. + TemporaryVisitorDrivingLicenseUnder21(165), + + /// Uniformed Services Identity Card. + UniformedServicesIdentityCard(166), + + /// Vehicle Salesperson License. + VehicleSalespersonLicense(167), + + /// Worker Identification Credential. + WorkerIdentificationCredential(168), + + /// Commercial Driving License Novice. + CommercialDrivingLicenseNovice(169), + + /// Commercial Driving License Novice under 18. + CommercialDrivingLicenseNoviceUnder18(170), + + /// Commercial Driving License Novice under 21. + CommercialDrivingLicenseNoviceUnder21(171), + + /// Passport Card. + PassportCard(172), + + /// Permanent Resident Card. + PermanentResidentCard(173), + + /// Personal Identification Verification. + PersonalIdentificationVerification(174), + + /// Temporary Operator License. + TemporaryOperatorLicense(175), + + /// Driving License under 19. + DrivingLicenseUnder19(176), + + /// Identity Card under 19. + IdentityCardUnder19(177), + + /// Visa. + Visa(178), + + /// Temporary Passport. + TemporaryPassport(179), + + /// Voting Card. + VotingCard(180), + + /// Health Card. + HealthCard(181), + + /// Certificate of Citizenship. + CertificateOfCitizenship(182), + + /// Address Card. + AddressCard(183), + + /// Airport Immigration Card. + AirportImmigrationCard(184), + + /// Alien Regidtation Card. + AlienRegistrationCard(185), + + /// APEH Card. + APEHCard(186), + + /// Coupon To Driving License. + CouponToDrivingLicense(187), + + /// Crew Member Certificate. + CrewMemberCertificate(188), + + /// Document for Return. + DocumentForReturn(189), + + /// E-Card. + ECard(190), + + /// Employment Card. + EmploymentCard(191), + + /// HKSAR Immigration Form. + HKSARImmigrationForm(192), + + /// Immigrant Card. + ImmigrantCard(193), + + /// Labour Card. + LabourCard(194), + + /// Laissez Passer. + LaissezPasser(195), + + /// Lawyer Identity Certificate. + LawyerIdentityCertificate(196), + + /// License Card. + LicenseCard(197), + + /// Passport Stateless. + PassportStateless(198), + + /// Passport Child. + PassportChild(199), + + /// Passport Consular. + PassportConsular(200), + + /// Passport Diplomatic Service. + PassportDiplomaticService(201), + + /// Passport Official. + PassportOfficial(202), + + /// Passport Provisional. + PassportProvisional(203), + + /// Passport Special. + PassportSpecial(204), + + /// Permission to the Local Border Traffic. + PermissionToTheLocalBorderTraffic(205), + + /// Registration Certificate. + RegistrationCertificate(206), + + /// SEDESOL Card. + SEDESOLCard(207), + + /// Social Card. + SocialCard(208), + + /// TB Card. + TBCard(209), + + /// Vehicle Passport. + VehiclePassport(210), + + /// W Document. + WDocument(211), + + /// Diplomatic Identity Card. + DiplomaticIdentityCard(212), + + /// Consular Identity Card. + ConsularIdentityCard(213), + + /// Income Tax Card. + IncomeTaxCard(214), + + /// Residence Permit. + ResidencePermit(215), + + /// Document of Identity. + DocumentOfIdentity(216), + + /// Border Crossing Permit. + BorderCrossingPermit(217), + + /// Passport Limited Validity. + PassportLimitedValidity(218), + + /// SIM Card. + SIMCard(219), + + /// Tax Card. + TaxCard(220), + + /// Company Card. + CompanyCard(221), + + /// Domestic Passport. + DomesticPassport(222), + + /// Identity Certificate. + IdentityCertificate(223), + + /// Resident Id Card. + ResidentIdCard(224), + + /// Armed Forces Identity Card. + ArmedForcesIdentityCard(225), + + /// Professional Card. + ProfessionalCard(226), + + /// Registration Stamp. + RegistrationStamp(227), + + /// Driver Card. + DriverCard(228), + + /// Driver Training Certificate. + DriverTrainingCertificate(229), + + /// Qualification Driving License. + QualificationDrivingLicense(230), + + /// Membership Card. + MembershipCard(231), + + /// Public Vehicle Driver Authority Card. + PublicVehicleDriverAuthorityCard(232), + + /// Marine License. + MarineLicense(233), + + /// Temporary Learner Driving License. + TemporaryLearnerDrivingLicense(234), + + /// Temporary Commercial Driving License. + TemporaryCommercialDrivingLicense(235), + + /// Interim Instructional Permit. + InterimInstructionalPermit(236), + + /// Certificate of Competency. + CertificateOfCompetency(237), + + /// Certificate of Proficiency. + CertificateOfProficiency(238), + + TradeLicense(239), + + PassportPage(240), + + Invoice(241), + + PassengerLocatorForm(242); + + const DocType(this.value); + final int value; + + static DocType? getByValue(int? i) { + if (i == null) return null; + try { + return DocType.values.firstWhere((x) => x.value == i); + } catch (_) { + return DocType.NotDefined; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/image_quality/image_quality.dart b/lib/src/results/image_quality/image_quality.dart new file mode 100644 index 0000000000..31b29c0311 --- /dev/null +++ b/lib/src/results/image_quality/image_quality.dart @@ -0,0 +1,51 @@ +// +// ImageQuality.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, containing information about single image quality check. +class ImageQuality { + /// Check result. + int get featureType => _featureType; + late int _featureType; + + /// Check result. + CheckResult get result => _result; + late CheckResult _result; + + /// Check result type. + ImageQualityCheckType get type => _type; + late ImageQualityCheckType _type; + + /// Coordinates of glares. + List get boundRects => _boundRects; + List _boundRects = []; + + /// Allows you to deserialize object. + static ImageQuality? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = ImageQuality(); + + result._featureType = jsonObject["featureType"]; + result._result = CheckResult.getByValue(jsonObject["result"])!; + result._type = ImageQualityCheckType.getByValue(jsonObject["type"])!; + for (var item in jsonObject["boundRects"]) { + result._boundRects.addSafe(Rect.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "featureType": featureType, + "result": result.value, + "type": type.value, + "boundRects": boundRects.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/image_quality/image_quality_check_type.dart b/lib/src/results/image_quality/image_quality_check_type.dart new file mode 100644 index 0000000000..a693a14260 --- /dev/null +++ b/lib/src/results/image_quality/image_quality_check_type.dart @@ -0,0 +1,76 @@ +// +// ImageQualityCheckType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +enum ImageQualityCheckType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Glares presence check. + IMAGE_GLARES(0), + + /// Focus quality check. + IMAGE_FOCUS(1), + + /// Image resolution check. + IMAGE_RESOLUTION(2), + + /// Image colorness check. + IMAGE_COLORNESS(3), + + /// Image perspective check, i.e. the deviation of the corners of the document + /// from the value of 90 degrees is checked. + PERSPECTIVE(4), + + /// Image quality check if the whole document page is completely within the image. + BOUNDS(5), + + /// Image moire check. + SCREEN_CAPTURE(6), + + /// Portrait image check. + PORTRAIT(7), + + /// Handwritten image check. + HANDWRITTEN(8), + + /// Signals whether the document image is bright enough. + BRIGHTNESS(9), + + /// Document occlusion check. + OCCLUSION(10); + + const ImageQualityCheckType(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static ImageQualityCheckType? getByValue(int? i) { + if (i == null) return null; + try { + return ImageQualityCheckType.values.firstWhere((x) => x.value == i); + } catch (_) { + return ImageQualityCheckType.UNKNOWN; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/image_quality/image_quality_group.dart b/lib/src/results/image_quality/image_quality_group.dart new file mode 100644 index 0000000000..72465d2363 --- /dev/null +++ b/lib/src/results/image_quality/image_quality_group.dart @@ -0,0 +1,51 @@ +// +// ImageQualityGroup.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, containing overall data about quality checks performed. +class ImageQualityGroup { + /// Number of results. + int get count => _count; + late int _count; + + /// Overall check result for document page. + CheckResult get result => _result; + late CheckResult _result; + + /// An array of single check result pointers. + List get imageQualityList => _imageQualityList; + List _imageQualityList = []; + + /// Index of the document page, whence the result is received. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Allows you to deserialize object. + static ImageQualityGroup? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = ImageQualityGroup(); + + result._count = jsonObject["count"]; + result._result = CheckResult.getByValue(jsonObject["result"])!; + result._pageIndex = jsonObject["pageIndex"]; + for (var item in jsonObject["imageQualityList"]) { + result._imageQualityList.addSafe(ImageQuality.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "count": count, + "result": result.value, + "pageIndex": pageIndex, + "imageQualityList": imageQualityList.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/rfid/Application.dart b/lib/src/results/rfid/Application.dart new file mode 100644 index 0000000000..23986974bd --- /dev/null +++ b/lib/src/results/rfid/Application.dart @@ -0,0 +1,103 @@ +// +// Application.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure is used to describe the contents of a single LDS applica-tion +/// and their analysis within the context of the communication session with +/// electronic document. +class Application { + /// Application identifier. + String? get applicationID => _applicationID; + String? _applicationID; + + /// Algorithm for calculating hash values for files for the proce-dure of PA. + String? get dataHashAlgorithm => _dataHashAlgorithm; + String? _dataHashAlgorithm; + + /// List of containers to store information about the read files of the application. + List get files => _files; + List _files = []; + + /// Status of the application selection procedure. + RFIDErrorCodes get status => _status; + late RFIDErrorCodes _status; + + /// Type of application of electronic document. + RFIDApplicationType get type => _type; + late RFIDApplicationType _type; + + /// Unicode version for application. + String? get unicodeVersion => _unicodeVersion; + String? _unicodeVersion; + + /// Application version. + String? get version => _version; + String? _version; + + /// Allows you to deserialize object. + static Application? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Application(); + + result._type = RFIDApplicationType.getByValue(jsonObject["type"])!; + result._status = RFIDErrorCodes.getByValue(jsonObject["status"])!; + result._applicationID = jsonObject["applicationID"]; + result._dataHashAlgorithm = jsonObject["dataHashAlgorithm"]; + result._unicodeVersion = jsonObject["unicodeVersion"]; + result._version = jsonObject["version"]; + for (var item in jsonObject["files"]) { + result._files.addSafe(File.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "applicationID": applicationID, + "dataHashAlgorithm": dataHashAlgorithm, + "files": files.map((e) => e.toJson()).toList(), + "status": status.value, + "type": type.value, + "unicodeVersion": unicodeVersion, + "version": version, + }.clearNulls(); +} + +/// Type of application of electronic document. +enum RFIDApplicationType { + /// ePassport. + E_PASSPORT(1), + + E_ID(2), + + E_SIGN(3), + + E_DL(4), + + /// Travel Records. + LDS2_TRAVEL_RECORDS(5), + + /// Visa Records. + LDS2_VISA_RECORDS(6), + + /// Add Biometrics. + LDS2_ADD_BIOMETRICS(7), + + /// eDTC PC. + E_DTC_PC(8); + + const RFIDApplicationType(this.value); + final int value; + + static RFIDApplicationType? getByValue(int? i) { + if (i == null) return null; + return RFIDApplicationType.values.firstWhere((x) => x.value == i); + } +} diff --git a/lib/src/results/rfid/Attribute.dart b/lib/src/results/rfid/Attribute.dart new file mode 100644 index 0000000000..304780d8dd --- /dev/null +++ b/lib/src/results/rfid/Attribute.dart @@ -0,0 +1,32 @@ +// +// Attribute.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class Attribute { + String? get type => _type; + String? _type; + + RFIDValue? get value => _value; + RFIDValue? _value; + + /// Allows you to deserialize object. + static Attribute? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Attribute(); + + result._type = jsonObject["type"]; + result._value = RFIDValue.fromJson(jsonObject["value"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"type": type, "value": value?.toJson()}.clearNulls(); +} diff --git a/lib/src/results/rfid/Authority.dart b/lib/src/results/rfid/Authority.dart new file mode 100644 index 0000000000..b66f39a640 --- /dev/null +++ b/lib/src/results/rfid/Authority.dart @@ -0,0 +1,41 @@ +// +// Authority.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class Authority { + List get attributes => _attributes; + List _attributes = []; + + String? get data => _data; + String? _data; + + RFIDValue? get friendlyName => _friendlyName; + RFIDValue? _friendlyName; + + /// Allows you to deserialize object. + static Authority? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Authority(); + + result._data = jsonObject["data"]; + result._friendlyName = RFIDValue.fromJson(jsonObject["friendlyName"]); + for (var item in jsonObject["attributes"]) { + result._attributes.addSafe(Attribute.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "attributes": attributes.map((e) => e.toJson()).toList(), + "data": data, + "friendlyName": friendlyName?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/rfid/Extension.dart b/lib/src/results/rfid/Extension.dart new file mode 100644 index 0000000000..9fee76a484 --- /dev/null +++ b/lib/src/results/rfid/Extension.dart @@ -0,0 +1,31 @@ +// +// Extension.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class Extension { + String? get data => _data; + String? _data; + + String? get type => _type; + String? _type; + + /// Allows you to deserialize object. + static Extension? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Extension(); + + result._data = jsonObject["data"]; + result._type = jsonObject["type"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => {"data": data, "type": type}.clearNulls(); +} diff --git a/lib/src/results/rfid/File.dart b/lib/src/results/rfid/File.dart new file mode 100644 index 0000000000..9b82183c40 --- /dev/null +++ b/lib/src/results/rfid/File.dart @@ -0,0 +1,88 @@ +// +// File.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class File { + FileData? get fileData => _fileData; + FileData? _fileData; + + String? get fileID => _fileID; + String? _fileID; + + List get notifications => _notifications; + List _notifications = []; + + RFIDErrorCodes get pAStatus => _pAStatus; + late RFIDErrorCodes _pAStatus; + + RFIDErrorCodes get readingStatus => _readingStatus; + late RFIDErrorCodes _readingStatus; + + int get readingTime => _readingTime; + late int _readingTime; + + RFIDDataFileType get type => _type; + late RFIDDataFileType _type; + + String get typeName => _typeName; + late String _typeName; + + List get docFieldsText => _docFieldsText; + List _docFieldsText = []; + + List get docFieldsGraphics => _docFieldsGraphics; + List _docFieldsGraphics = []; + + List get docFieldsOriginals => _docFieldsOriginals; + List _docFieldsOriginals = []; + + SecurityObjectCertificates? get certificates => _certificates; + SecurityObjectCertificates? _certificates; + + /// Allows you to deserialize object. + static File? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = File(); + + result._readingTime = jsonObject["readingTime"]; + result._type = RFIDDataFileType.getByValue(jsonObject["type"])!; + result._typeName = jsonObject["typeName"]; + result._pAStatus = RFIDErrorCodes.getByValue(jsonObject["pAStatus"])!; + result._readingStatus = + RFIDErrorCodes.getByValue(jsonObject["readingStatus"])!; + result._fileID = jsonObject["fileID"]; + result._fileData = FileData.fromJson(jsonObject["fileData"]); + result._certificates = SecurityObjectCertificates.fromJson( + jsonObject["certificates"], + ); + result._docFieldsText = _intListFrom(jsonObject["docFieldsText"])!; + result._docFieldsGraphics = _intListFrom(jsonObject["docFieldsGraphics"])!; + result._docFieldsOriginals = + _intListFrom(jsonObject["docFieldsOriginals"])!; + result._notifications = _intListFrom(jsonObject["notifications"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "fileData": fileData?.toJson(), + "fileID": fileID, + "notifications": notifications, + "pAStatus": pAStatus.value, + "readingStatus": readingStatus.value, + "readingTime": readingTime, + "type": type.value, + "typeName": typeName, + "docFieldsText": docFieldsText, + "docFieldsGraphics": docFieldsGraphics, + "docFieldsOriginals": docFieldsOriginals, + "certificates": certificates?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/rfid/access_control_procedure_type.dart b/lib/src/results/rfid/access_control_procedure_type.dart new file mode 100644 index 0000000000..a43ebe4e8a --- /dev/null +++ b/lib/src/results/rfid/access_control_procedure_type.dart @@ -0,0 +1,52 @@ +// +// AccessControlProcedureType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure is used to describe the results of a single authentication +/// procedure or a procedure of secure data access within the context +/// of the communication session with electronic document. +class AccessControlProcedureType { + /// Index of the active variant of the procedure. + int get activeOptionIdx => _activeOptionIdx; + late int _activeOptionIdx; + + /// List of remarks arisen during the procedure. + List get notifications => _notifications; + List _notifications = []; + + /// Procedure status. + RFIDErrorCodes get status => _status; + late RFIDErrorCodes _status; + + /// Procedure type. + RFIDAccessControlProcedureType get type => _type; + late RFIDAccessControlProcedureType _type; + + /// Allows you to deserialize object. + static AccessControlProcedureType? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = AccessControlProcedureType(); + + result._activeOptionIdx = jsonObject["activeOptionIdx"]; + result._type = + RFIDAccessControlProcedureType.getByValue(jsonObject["type"])!; + result._status = RFIDErrorCodes.getByValue(jsonObject["status"])!; + result._notifications = _intListFrom(jsonObject["notifications"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "activeOptionIdx": activeOptionIdx, + "notifications": notifications, + "status": status.value, + "type": type.value, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/card_properties.dart b/lib/src/results/rfid/card_properties.dart new file mode 100644 index 0000000000..0d7d5b9110 --- /dev/null +++ b/lib/src/results/rfid/card_properties.dart @@ -0,0 +1,115 @@ +// +// CardProperties.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure is used to store extended information about the characteristics +/// of the RFID-chip located in the scope of the reader. +class CardProperties { + /// Numeric ATQ_A value in hexadecimal format (e.g. "0x0000"). + int get aTQA => _aTQA; + late int _aTQA; + + /// ATQ_B contents in text format. Each byte is represented by its + /// hexadecimal value. The individual bytes are sepa-rated by spaces + /// (e.g. "50 F9 4F 41 60 00 00 00 00 77 81 81"). + String? get aTQB => _aTQB; + String? _aTQB; + + /// aTR contents in text format. Each byte is represented by its hexadecimal value. + /// The individual bytes are separated by spaces + /// (e.g. "3B 88 81 11 FC 00 00 00 00 77 81 81 00 93"). + String? get aTR => _aTR; + String? _aTR; + + /// Numeric Baudrate1 value in hexadecimal format (e.g. "0x0000000F"). + String? get baudrate1 => _baudrate1; + String? _baudrate1; + + /// Numeric Baudrate2 value in hexadecimal format. + String? get baudrate2 => _baudrate2; + String? _baudrate2; + + /// Numeric BitRateR value in hexadecimal format (e.g. "0x04"). + int get bitRateR => _bitRateR; + late int _bitRateR; + + /// Numeric BitRateS value in hexadecimal format (e.g. "0x04"). + int get bitRateS => _bitRateS; + late int _bitRateS; + + /// Text abbreviation of ChipType_A value. + int get chipTypeA => _chipTypeA; + late int _chipTypeA; + + /// Numeric MifareMemory value. + int get mifareMemory => _mifareMemory; + late int _mifareMemory; + + /// Text abbreviation of RFID_Type value. + int get rfidType => _rfidType; + late int _rfidType; + + /// Numeric SAK value in hexadecimal format (e.g. "0x00"). + int get sAK => _sAK; + late int _sAK; + + /// Boolean Support_4 value. + bool get support4 => _support4; + late bool _support4; + + /// Boolean Support_Mifare value. + bool get supportMifare => _supportMifare; + late bool _supportMifare; + + /// UID contents in text format. Each byte is represented by its hexadecimal value. + /// The individual bytes are separated by spaces (e.g. "F9 4F 41 60"). + String? get uID => _uID; + String? _uID; + + /// Allows you to deserialize object. + static CardProperties? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = CardProperties(); + + result._aTQA = jsonObject["aTQA"]; + result._bitRateR = jsonObject["bitRateR"]; + result._bitRateS = jsonObject["bitRateS"]; + result._chipTypeA = jsonObject["chipTypeA"]; + result._mifareMemory = jsonObject["mifareMemory"]; + result._rfidType = jsonObject["rfidType"]; + result._sAK = jsonObject["sAK"]; + result._support4 = jsonObject["support4"]; + result._supportMifare = jsonObject["supportMifare"]; + result._aTQB = jsonObject["aTQB"]; + result._aTR = jsonObject["aTR"]; + result._baudrate1 = jsonObject["baudrate1"]; + result._baudrate2 = jsonObject["baudrate2"]; + result._uID = jsonObject["uID"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "aTQA": aTQA, + "bitRateR": bitRateR, + "bitRateS": bitRateS, + "chipTypeA": chipTypeA, + "mifareMemory": mifareMemory, + "rfidType": rfidType, + "sAK": sAK, + "support4": support4, + "supportMifare": supportMifare, + "aTQB": aTQB, + "aTR": aTR, + "baudrate1": baudrate1, + "baudrate2": baudrate2, + "uID": uID, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/certificate_chain.dart b/lib/src/results/rfid/certificate_chain.dart new file mode 100644 index 0000000000..4d74a4c2bf --- /dev/null +++ b/lib/src/results/rfid/certificate_chain.dart @@ -0,0 +1,93 @@ +// +// CertificateChain.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class CertificateChain { + /// Define the type of certificate used in the procedure of document + /// security object digital signature verification. + RFIDCertificateType get type => _type; + late RFIDCertificateType _type; + + List get extensions => _extensions; + List _extensions = []; + + RFIDValue? get fileName => _fileName; + RFIDValue? _fileName; + + Authority? get issuer => _issuer; + Authority? _issuer; + + List get notifications => _notifications; + List _notifications = []; + + int get origin => _origin; + late int _origin; + + int get paStatus => _paStatus; + late int _paStatus; + + String? get serialNumber => _serialNumber; + String? _serialNumber; + + String? get signatureAlgorithm => _signatureAlgorithm; + String? _signatureAlgorithm; + + Authority? get subject => _subject; + Authority? _subject; + + String? get subjectPKAlgorithm => _subjectPKAlgorithm; + String? _subjectPKAlgorithm; + + RFIDValidity? get validity => _validity; + RFIDValidity? _validity; + + int get version => _version; + late int _version; + + /// Allows you to deserialize object. + static CertificateChain? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = CertificateChain(); + + result._origin = jsonObject["origin"]; + result._type = RFIDCertificateType.getByValue(jsonObject["type"])!; + result._version = jsonObject["version"]; + result._paStatus = jsonObject["paStatus"]; + result._serialNumber = jsonObject["serialNumber"]; + result._signatureAlgorithm = jsonObject["signatureAlgorithm"]; + result._subjectPKAlgorithm = jsonObject["subjectPKAlgorithm"]; + result._fileName = RFIDValue.fromJson(jsonObject["fileName"]); + result._validity = RFIDValidity.fromJson(jsonObject["validity"]); + result._issuer = Authority.fromJson(jsonObject["issuer"]); + result._subject = Authority.fromJson(jsonObject["subject"]); + result._notifications = _intListFrom(jsonObject["notifications"])!; + for (var item in jsonObject["extensions"]) { + result._extensions.addSafe(Extension.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type.value, + "extensions": extensions.map((e) => e.toJson()).toList(), + "fileName": fileName?.toJson(), + "issuer": issuer?.toJson(), + "notifications": notifications, + "origin": origin, + "paStatus": paStatus, + "serialNumber": serialNumber, + "signatureAlgorithm": signatureAlgorithm, + "subject": subject?.toJson(), + "subjectPKAlgorithm": subjectPKAlgorithm, + "validity": validity?.toJson(), + "version": version, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/certificate_data.dart b/lib/src/results/rfid/certificate_data.dart new file mode 100644 index 0000000000..347a02741f --- /dev/null +++ b/lib/src/results/rfid/certificate_data.dart @@ -0,0 +1,32 @@ +// +// CertificateData.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class CertificateData { + String? get data => _data; + String? _data; + + int get length => _length; + late int _length; + + /// Allows you to deserialize object. + static CertificateData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = CertificateData(); + + result._length = jsonObject["length"]; + result._data = jsonObject["data"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"data": data, "length": length}.clearNulls(); +} diff --git a/lib/src/results/rfid/data_field.dart b/lib/src/results/rfid/data_field.dart new file mode 100644 index 0000000000..9c3a2fc5e4 --- /dev/null +++ b/lib/src/results/rfid/data_field.dart @@ -0,0 +1,34 @@ +// +// DataField.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class DataField { + String get data => _data; + String _data = ""; + + RFIDDataFileType get fieldType => _fieldType; + RFIDDataFileType _fieldType = RFIDDataFileType.UNSPECIFIED; + + /// Allows you to deserialize object. + static DataField? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DataField(); + + result._data = jsonObject["data"]; + var fieldType = RFIDDataFileType.getByValue(jsonObject["fieldType"]); + if (fieldType == null) return null; + result._fieldType = fieldType; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"data": data, "fieldType": fieldType.value}.clearNulls(); +} diff --git a/lib/src/results/rfid/file_data.dart b/lib/src/results/rfid/file_data.dart new file mode 100644 index 0000000000..6e86f5678c --- /dev/null +++ b/lib/src/results/rfid/file_data.dart @@ -0,0 +1,44 @@ +// +// FileData.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class FileData { + String? get data => _data; + String? _data; + + int get length => _length; + late int _length; + + int get type => _type; + late int _type; + + int get status => _status; + late int _status; + + /// Allows you to serialize object. + static FileData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = FileData(); + + result._length = jsonObject["length"]; + result._type = jsonObject["type"]; + result._status = jsonObject["status"]; + result._data = jsonObject["data"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "data": data, + "length": length, + "type": type, + "status": status, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/rfid_access_control_procedure_type.dart b/lib/src/results/rfid/rfid_access_control_procedure_type.dart new file mode 100644 index 0000000000..b6f9936692 --- /dev/null +++ b/lib/src/results/rfid/rfid_access_control_procedure_type.dart @@ -0,0 +1,49 @@ +// +// RFIDAccessControlProcedureType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +enum RFIDAccessControlProcedureType { + /// Type is not defined. + UNDEFINED(0), + + /// Basic Access Control (BAC) / Protection (BAP). + BAC(1), + + /// Password Authenticated Connection Establishment. + PACE(2), + + /// Chip Authentication. + CA(3), + + /// Terminal Authentication. + TA(4), + + /// Active Authentication. + AA(5), + + /// Restricted Identification. + RI(6), + + /// Card info. + CARD_INFO(10); + + const RFIDAccessControlProcedureType(this.value); + final int value; + + static RFIDAccessControlProcedureType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDAccessControlProcedureType.values.firstWhere( + (x) => x.value == i, + ); + } catch (_) { + return RFIDAccessControlProcedureType.UNDEFINED; + } + } +} diff --git a/lib/src/results/rfid/rfid_certificate_type.dart b/lib/src/results/rfid/rfid_certificate_type.dart new file mode 100644 index 0000000000..857e3d25aa --- /dev/null +++ b/lib/src/results/rfid/rfid_certificate_type.dart @@ -0,0 +1,39 @@ +part of "../../../flutter_document_reader_api.dart"; + +enum RFIDCertificateType { + UNDEFINED(0), + + CSCA(1), + + CSCA_LINK(2), + + DS(3), + + MLS(4), + + DEV_LS(5), + + DEF_LS(6), + + BLS(7), + + LDS2(8), + + BCS(9), + + BCSNC(10), + + MDLS(13); + + const RFIDCertificateType(this.value); + final int value; + + static RFIDCertificateType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDCertificateType.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDCertificateType.UNDEFINED; + } + } +} diff --git a/lib/src/results/rfid/rfid_data_file_type.dart b/lib/src/results/rfid/rfid_data_file_type.dart new file mode 100644 index 0000000000..b2c0bdd024 --- /dev/null +++ b/lib/src/results/rfid/rfid_data_file_type.dart @@ -0,0 +1,133 @@ +// +// RFIDDataFileType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains a set of constants that define the file type +/// (or logical belonging of the data object) within the context of the +/// communication session with electronic document. +enum RFIDDataFileType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + UNSPECIFIED(0), + PASSPORT_DG1(1), + PASSPORT_DG2(2), + PASSPORT_DG3(3), + PASSPORT_DG4(4), + PASSPORT_DG5(5), + PASSPORT_DG6(6), + PASSPORT_DG7(7), + PASSPORT_DG8(8), + PASSPORT_DG9(9), + PASSPORT_DG10(10), + PASSPORT_DG11(11), + PASSPORT_DG12(12), + PASSPORT_DG13(13), + PASSPORT_DG14(14), + PASSPORT_DG15(15), + PASSPORT_DG16(16), + PASSPORT_DG17(17), + PASSPORT_DG18(18), + PASSPORT_DG19(19), + PASSPORT_DG20(20), + PASSPORT_SOD(21), + PASSPORT_CVCA(22), + PASSPORT_COM(23), + DTC_DG17(57), + DTC_DG18(58), + DTC_DG22(62), + DTC_DG23(63), + DTC_DG24(64), + ID_DG1(101), + ID_DG2(102), + ID_DG3(103), + ID_DG4(104), + ID_DG5(105), + ID_DG6(106), + ID_DG7(107), + ID_DG8(108), + ID_DG9(109), + ID_DG10(110), + ID_DG11(111), + ID_DG12(112), + ID_DG13(113), + ID_DG14(114), + ID_DG15(115), + ID_DG16(116), + ID_DG17(117), + ID_DG18(118), + ID_DG19(119), + ID_DG20(120), + ID_DG21(121), + ID_DG22(122), + DL_COM(150), + DL_DG1(151), + DL_DG2(152), + DL_DG3(153), + DL_DG4(154), + DL_DG5(155), + DL_DG6(156), + DL_DG7(157), + DL_DG8(158), + DL_DG9(159), + DL_DG10(160), + DL_DG11(161), + DL_DG12(162), + DL_DG13(163), + DL_DG14(164), + DL_SOD(165), + DL_CE(166), + DL_CVCA(167), + PACE_CARDACCESS(200), + PACE_CARDSECURITY(201), + PACE_CHIPSECURITY(202), + MIFARE_DATA(300), + MIFARE_VALIDITY(301), + AUTHENTICITYV2(302), + ATR(400), + ESIGN_PK(500), + ESIGN_SIGNEDDATA(501), + CERTIFICATE(600), + MASTERLIST(601), + DEFECTLIST(602), + DEVIATIONLIST(603), + APP_DIRECTORY(700), + SESSION(701), + LOGDATA(702), + CHIP_PROPERTIES(703), + POST_CA_RESPONSE(710), + POST_CA_PUBLIC_KEY(711), + POST_CA_INFO(712), + POST_CA_DPARAMS(713), + POST_CA_CHECK_PK(714), + POST_CA_CHECK_SK(715), + SAM_DATA(800), + SAM_DATA_MAX(800 + 32), + VDS(900), + VDSNC(901), + USERDEFINED(1000); + + const RFIDDataFileType(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static RFIDDataFileType? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDDataFileType.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDDataFileType.UNKNOWN; + } + } +} diff --git a/lib/src/results/rfid/rfid_session_data.dart b/lib/src/results/rfid/rfid_session_data.dart new file mode 100644 index 0000000000..197ff06234 --- /dev/null +++ b/lib/src/results/rfid/rfid_session_data.dart @@ -0,0 +1,111 @@ +// +// RFIDSessionData.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Used to describe the results of work with the SDK within the context +/// of the current communication session with electronic document. +class RFIDSessionData { + /// List of containers to store information about the supported procedures + /// of authentication and secure data access within the context of the session. + List get accessControls => _accessControls; + List _accessControls = []; + + /// List of containers to store information about the involved ap-plications + /// of electronic document. + List get applications => _applications; + List _applications = []; + + /// ist of containers to store information about the detected + /// document security objects. + List get securityObjects => _securityObjects; + List _securityObjects = []; + + /// Set of electronic document chip characteristics. + CardProperties? get cardProperties => _cardProperties; + CardProperties? _cardProperties; + + /// Total number of bytes received from the RFID-chip during the whole session. + int get totalBytesReceived => _totalBytesReceived; + late int _totalBytesReceived; + + /// Total number of bytes transmitted to the RFID-chip during the whole session. + int get totalBytesSent => _totalBytesSent; + late int _totalBytesSent; + + /// Status. + RFIDErrorCodes get status => _status; + late RFIDErrorCodes _status; + + /// Sign of support of RFID-chip for extended length commands of reading. + RFIDErrorCodes get extLeSupport => _extLeSupport; + late RFIDErrorCodes _extLeSupport; + + /// Total time of all operations performed during the session, ms. + int get processTime => _processTime; + late int _processTime; + + /// List of data fields + List get dataFields => _dataFields; + List _dataFields = []; + + /// List of data groups. + List? get dataGroups => _dataGroups; + List? _dataGroups; + + /// Allows you to deserialize object. + static RFIDSessionData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDSessionData(); + + result._totalBytesReceived = jsonObject["totalBytesReceived"]; + result._totalBytesSent = jsonObject["totalBytesSent"]; + result._status = RFIDErrorCodes.getByValue(jsonObject["status"])!; + result._extLeSupport = + RFIDErrorCodes.getByValue(jsonObject["extLeSupport"])!; + result._processTime = jsonObject["processTime"]; + result._cardProperties = CardProperties.fromJson( + jsonObject["cardProperties"], + ); + for (var item in jsonObject["accessControls"]) { + result._accessControls.addSafe(AccessControlProcedureType.fromJson(item)); + } + for (var item in jsonObject["applications"]) { + result._applications.addSafe(Application.fromJson(item)); + } + for (var item in jsonObject["securityObjects"]) { + result._securityObjects.addSafe(SecurityObject.fromJson(item)); + } + for (var item in jsonObject["dataFields"]) { + result._dataFields.addSafe(DataField.fromJson(item)); + } + if (jsonObject["dataGroups"] != null) { + result._dataGroups = []; + for (var item in jsonObject["dataGroups"]) { + result._dataGroups!.addSafe(RFIDDataFileType.getByValue(item)); + } + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "cardProperties": cardProperties?.toJson(), + "totalBytesReceived": totalBytesReceived, + "totalBytesSent": totalBytesSent, + "status": status.value, + "extLeSupport": extLeSupport.value, + "processTime": processTime, + "accessControls": accessControls.map((e) => e.toJson()).toList(), + "applications": applications.map((e) => e.toJson()).toList(), + "securityObjects": securityObjects.map((e) => e.toJson()).toList(), + "dataFields": dataFields.map((e) => e.toJson()).toList(), + "dataGroups": dataGroups?.map((e) => e.value).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/rfid/rfid_validity.dart b/lib/src/results/rfid/rfid_validity.dart new file mode 100644 index 0000000000..5805b78e31 --- /dev/null +++ b/lib/src/results/rfid/rfid_validity.dart @@ -0,0 +1,34 @@ +// +// RFIDValidity.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class RFIDValidity { + RFIDValue? get notAfter => _notAfter; + RFIDValue? _notAfter; + + RFIDValue? get notBefore => _notBefore; + RFIDValue? _notBefore; + + /// Allows you to deserialize object. + static RFIDValidity? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDValidity(); + + result._notAfter = RFIDValue.fromJson(jsonObject["notAfter"]); + result._notBefore = RFIDValue.fromJson(jsonObject["notBefore"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "notAfter": notAfter?.toJson(), + "notBefore": notBefore?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/rfid/rfid_value.dart b/lib/src/results/rfid/rfid_value.dart new file mode 100644 index 0000000000..3f7886fa3e --- /dev/null +++ b/lib/src/results/rfid/rfid_value.dart @@ -0,0 +1,49 @@ +// +// RFIDValue.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class RFIDValue { + String? get data => _data; + String? _data; + + int get length => _length; + late int _length; + + int get status => _status; + late int _status; + + int get type => _type; + late int _type; + + String? get format => _format; + String? _format; + + /// Allows you to deserialize object. + static RFIDValue? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDValue(); + + result._length = jsonObject["length"]; + result._type = jsonObject["type"]; + result._status = jsonObject["status"]; + result._data = jsonObject["data"]; + result._format = jsonObject["format"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "data": data, + "length": length, + "status": status, + "type": type, + "format": format, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/security_object.dart b/lib/src/results/rfid/security_object.dart new file mode 100644 index 0000000000..fb68f99e8f --- /dev/null +++ b/lib/src/results/rfid/security_object.dart @@ -0,0 +1,62 @@ +// +// SecurityObject.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure is used to describe the contents of a single document +/// security object (SO) and the results of its check within the context +/// of the communication session with electronic document. +class SecurityObject { + /// Reference to the source file of the security object data. + int get fileReference => _fileReference; + late int _fileReference; + + /// Security object identifier. + String? get objectType => _objectType; + String? _objectType; + + /// Security object version. + int get version => _version; + late int _version; + + /// List of containers to store information about digital + /// signature objects contained in the SO. + List get signerInfos => _signerInfos; + List _signerInfos = []; + + /// The list of remarks occured during the scanning procedure. + /// + /// Each element belongs to the [LDSParsingErrorCodes]. + List get notifications => _notifications; + List _notifications = []; + + /// Allows you to deserialize object. + static SecurityObject? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = SecurityObject(); + + result._fileReference = jsonObject["fileReference"]; + result._version = jsonObject["version"]; + result._objectType = jsonObject["objectType"]; + result._notifications = _intListFrom(jsonObject["notifications"])!; + for (var item in jsonObject["signerInfos"]) { + result.signerInfos.addSafe(SignerInfo.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "fileReference": fileReference, + "objectType": objectType, + "version": version, + "signerInfos": signerInfos.map((e) => e.toJson()).toList(), + "notifications": notifications, + }.clearNulls(); +} diff --git a/lib/src/results/rfid/security_object_certificates.dart b/lib/src/results/rfid/security_object_certificates.dart new file mode 100644 index 0000000000..87a4a3cadf --- /dev/null +++ b/lib/src/results/rfid/security_object_certificates.dart @@ -0,0 +1,30 @@ +// +// SecurityObjectCertificates.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class SecurityObjectCertificates { + CertificateData? get securityObject => _securityObject; + CertificateData? _securityObject; + + /// Allows you to deserialize object. + static SecurityObjectCertificates? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = SecurityObjectCertificates(); + + result._securityObject = CertificateData.fromJson( + jsonObject["securityObject"], + ); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"securityObject": securityObject?.toJson()}.clearNulls(); +} diff --git a/lib/src/results/rfid/signer_info.dart b/lib/src/results/rfid/signer_info.dart new file mode 100644 index 0000000000..316da19e64 --- /dev/null +++ b/lib/src/results/rfid/signer_info.dart @@ -0,0 +1,106 @@ +// +// SignerInfo.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure is used to store the result of the verification of a single digital +/// signature of the number present in EF.SOD. +class SignerInfo { + /// Data to hash. + String? get dataToHash => _dataToHash; + String? _dataToHash; + + /// Digital signature hash-function algorithm identifier. + String? get digestAlgorithm => _digestAlgorithm; + String? _digestAlgorithm; + + /// Result of the digital signature verification. + int get paStatus => _paStatus; + late int _paStatus; + + /// Digital signature algorithm identifier. + String? get signatureAlgorithm => _signatureAlgorithm; + String? _signatureAlgorithm; + + /// Version of the digital signature data structure. + int get version => _version; + late int _version; + + /// Identifier of the necessary certificate issuer. + Authority? get issuer => _issuer; + Authority? _issuer; + + /// Serial number of the necessary certificate. + RFIDValue? get serialNumber => _serialNumber; + RFIDValue? _serialNumber; + + /// Binary data of the verified digital signature. + RFIDValue? get signature => _signature; + RFIDValue? _signature; + + /// List of the signed attributes. + List get signedAttributes => _signedAttributes; + List _signedAttributes = []; + + /// Signature object identifier of the necessary certificate. + RFIDValue? get subjectKeyIdentifier => _subjectKeyIdentifier; + RFIDValue? _subjectKeyIdentifier; + + /// Certificate chain, used for the digital signature verification. + List get certificateChain => _certificateChain; + List _certificateChain = []; + + /// The list of remarks occured during the scanning procedure. + /// + /// Each element belongs to the [LDSParsingErrorCodes]. + List get notifications => _notifications; + List _notifications = []; + + /// Allows you to deserialize object. + static SignerInfo? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = SignerInfo(); + + result._version = jsonObject["version"]; + result._paStatus = jsonObject["paStatus"]; + result._dataToHash = jsonObject["dataToHash"]; + result._digestAlgorithm = jsonObject["digestAlgorithm"]; + result._signatureAlgorithm = jsonObject["signatureAlgorithm"]; + result._serialNumber = RFIDValue.fromJson(jsonObject["serialNumber"]); + result._signature = RFIDValue.fromJson(jsonObject["signature"]); + result._subjectKeyIdentifier = RFIDValue.fromJson( + jsonObject["subjectKeyIdentifier"], + ); + result._issuer = Authority.fromJson(jsonObject["issuer"]); + result._notifications = _intListFrom(jsonObject["notifications"])!; + for (var item in jsonObject["signedAttributes"]) { + result._signedAttributes.addSafe(Extension.fromJson(item)); + } + for (var item in jsonObject["certificateChain"]) { + result._certificateChain.addSafe(CertificateChain.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "dataToHash": dataToHash, + "digestAlgorithm": digestAlgorithm, + "version": version, + "paStatus": paStatus, + "signatureAlgorithm": signatureAlgorithm, + "issuer": issuer?.toJson(), + "serialNumber": serialNumber?.toJson(), + "signature": signature?.toJson(), + "subjectKeyIdentifier": subjectKeyIdentifier?.toJson(), + "signedAttributes": signedAttributes.map((e) => e.toJson()).toList(), + "certificateChain": certificateChain.map((e) => e.toJson()).toList(), + "notifications": notifications, + }.clearNulls(); +} diff --git a/lib/src/results/status/age_status.dart b/lib/src/results/status/age_status.dart new file mode 100644 index 0000000000..9df3b1b104 --- /dev/null +++ b/lib/src/results/status/age_status.dart @@ -0,0 +1,48 @@ +part of "../../../flutter_document_reader_api.dart"; + +/// Container for an age related scanning statuses. +class AgeStatus { + int? get threshold => _threshold; + late int? _threshold; + + CheckResult get overThreshold => _overThreshold; + late CheckResult _overThreshold; + + CheckResult get over18 => _over18; + late CheckResult _over18; + + CheckResult get over21 => _over21; + late CheckResult _over21; + + CheckResult get over25 => _over25; + late CheckResult _over25; + + CheckResult get over65 => _over65; + late CheckResult _over65; + + /// Allows you to deserialize object. + static AgeStatus? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = AgeStatus(); + + result._threshold = jsonObject["threshold"]; + result._overThreshold = + CheckResult.getByValue(jsonObject["overThreshold"])!; + result._over18 = CheckResult.getByValue(jsonObject["over18"])!; + result._over21 = CheckResult.getByValue(jsonObject["over21"])!; + result._over25 = CheckResult.getByValue(jsonObject["over25"])!; + result._over65 = CheckResult.getByValue(jsonObject["over65"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "threshold": threshold, + "overThreshold": overThreshold.value, + "over18": over18.value, + "over21": over21.value, + "over25": over25.value, + "over65": over65.value, + }.clearNulls(); +} diff --git a/lib/src/results/status/check_result.dart b/lib/src/results/status/check_result.dart new file mode 100644 index 0000000000..4fdb6dd44d --- /dev/null +++ b/lib/src/results/status/check_result.dart @@ -0,0 +1,35 @@ +// +// CheckResult.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +enum CheckResult { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Check was not passed, the controlled parameter is not permitted. + ERROR(0), + + /// Check was passed, the controlled parameter is permitted. + OK(1), + + /// Check was not carried out. + WAS_NOT_DONE(2); + + const CheckResult(this.value); + final int value; + + static CheckResult? getByValue(int? i) { + if (i == null) return null; + try { + return CheckResult.values.firstWhere((x) => x.value == i); + } catch (_) { + return CheckResult.UNKNOWN; + } + } +} diff --git a/lib/src/results/status/optical_status.dart b/lib/src/results/status/optical_status.dart new file mode 100644 index 0000000000..f0d224dcfd --- /dev/null +++ b/lib/src/results/status/optical_status.dart @@ -0,0 +1,81 @@ +// +// OpticalStatus.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Container for an optical related scanning statuses. +class OpticalStatus { + /// Summary of all optical results. + CheckResult get overallStatus => _overallStatus; + late CheckResult _overallStatus; + + /// MRZ verification: values validity, dates, checkdigits verification. + CheckResult get mrz => _mrz; + late CheckResult _mrz; + + /// Text fields valitity: values validity for specific fields, cross-comparison + /// of values from different sources, dates & checkdigits verification. + CheckResult get text => _text; + late CheckResult _text; + + /// Check status if document type was recognized or not. + CheckResult get docType => _docType; + late CheckResult _docType; + + /// Authenticity verification status. + CheckResult get security => _security; + late CheckResult _security; + + /// Input images quality verification status. + CheckResult get imageQA => _imageQA; + late CheckResult _imageQA; + + /// Document validity period verification status. + CheckResult get expiry => _expiry; + late CheckResult _expiry; + + /// Visible Digital Seal verification status. + CheckResult get vds => _vds; + late CheckResult _vds; + + /// Number of scanned document pages. + int get pagesCount => _pagesCount; + late int _pagesCount; + + /// Allows you to deserialize object. + static OpticalStatus? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = OpticalStatus(); + + result._overallStatus = + CheckResult.getByValue(jsonObject["overallStatus"])!; + result._mrz = CheckResult.getByValue(jsonObject["mrz"])!; + result._text = CheckResult.getByValue(jsonObject["text"])!; + result._docType = CheckResult.getByValue(jsonObject["docType"])!; + result._security = CheckResult.getByValue(jsonObject["security"])!; + result._imageQA = CheckResult.getByValue(jsonObject["imageQA"])!; + result._expiry = CheckResult.getByValue(jsonObject["expiry"])!; + result._vds = CheckResult.getByValue(jsonObject["vds"])!; + result._pagesCount = jsonObject["pagesCount"]!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "overallStatus": overallStatus.value, + "mrz": mrz.value, + "text": text.value, + "docType": docType.value, + "security": security.value, + "imageQA": imageQA.value, + "expiry": expiry.value, + "vds": vds.value, + "pagesCount": pagesCount, + }.clearNulls(); +} diff --git a/lib/src/results/status/results_status.dart b/lib/src/results/status/results_status.dart new file mode 100644 index 0000000000..54e5b71acf --- /dev/null +++ b/lib/src/results/status/results_status.dart @@ -0,0 +1,93 @@ +// +// ResultsStatus.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Provision of document verification status. +class ResultsStatus { + /// Summary of all results. + CheckResult get overallStatus => _overallStatus; + late CheckResult _overallStatus; + + /// Summary of all optical results. The same value as [OpticalStatus.overallStatus] + CheckResult get optical => _optical; + late CheckResult _optical; + + /// Container for an optical related scanning statuses. + OpticalStatus get detailsOptical => _detailsOptical; + late OpticalStatus _detailsOptical; + + /// Summary of all RFID results. Same as [RFIDStatus.overallStatus]. + CheckResult get rfid => _rfid; + late CheckResult _rfid; + + /// Container for a RFID related scanning statuses. + RFIDStatus get detailsRFID => _detailsRFID; + late RFIDStatus _detailsRFID; + + /// Comparison status for portrait in the document aganist live or external image. + CheckResult get portrait => _portrait; + late CheckResult _portrait; + + /// Verification status for document data against database. + CheckResult get stopList => _stopList; + late CheckResult _stopList; + + /// Summary of all mDL results. + CheckResult get mDL => _mDL; + late CheckResult _mDL; + + /// Summary of all age results. + CheckResult get age => _age; + late CheckResult _age; + + CheckResult? get captureProcessIntegrity => _captureProcessIntegrity; + late CheckResult? _captureProcessIntegrity; + + /// Container for an details age scanning statuses. + AgeStatus get ageStatus => _ageStatus; + late AgeStatus _ageStatus; + + /// Allows you to deserialize object. + static ResultsStatus? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = ResultsStatus(); + + result._overallStatus = + CheckResult.getByValue(jsonObject["overallStatus"])!; + result._optical = CheckResult.getByValue(jsonObject["optical"])!; + result._detailsOptical = + OpticalStatus.fromJson(jsonObject["detailsOptical"])!; + result._rfid = CheckResult.getByValue(jsonObject["rfid"])!; + result._detailsRFID = RFIDStatus.fromJson(jsonObject["detailsRFID"])!; + result._portrait = CheckResult.getByValue(jsonObject["portrait"])!; + result._stopList = CheckResult.getByValue(jsonObject["stopList"])!; + result._mDL = CheckResult.getByValue(jsonObject["mDL"])!; + result._age = CheckResult.getByValue(jsonObject["age"])!; + result._captureProcessIntegrity = + CheckResult.getByValue(jsonObject["captureProcessIntegrity"]); + result._ageStatus = AgeStatus.fromJson(jsonObject["detailsAge"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "overallStatus": overallStatus.value, + "optical": optical.value, + "rfid": rfid.value, + "portrait": portrait.value, + "stopList": stopList.value, + "mDL": mDL.value, + "age": age.value, + "captureProcessIntegrity": captureProcessIntegrity?.value, + "detailsOptical": detailsOptical.toJson(), + "detailsAge": ageStatus.toJson(), + "detailsRFID": detailsRFID.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/status/rfid_status.dart b/lib/src/results/status/rfid_status.dart new file mode 100644 index 0000000000..8d3becf681 --- /dev/null +++ b/lib/src/results/status/rfid_status.dart @@ -0,0 +1,68 @@ +// +// RFIDStatus.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Container for a RFID related scanning statuses. +class RFIDStatus { + /// Summary of all RFID results. + CheckResult get overallStatus => _overallStatus; + late CheckResult _overallStatus; + + /// Passive authentication status. + CheckResult get pa => _pa; + late CheckResult _pa; + + /// Chip authentication status. + CheckResult get ca => _ca; + late CheckResult _ca; + + /// Acitve authentication status. + CheckResult get aa => _aa; + late CheckResult _aa; + + /// Terminal authentication status. + CheckResult get ta => _ta; + late CheckResult _ta; + + /// Basics access control status. + CheckResult get bac => _bac; + late CheckResult _bac; + + /// Password authenticated connection establishment status. + CheckResult get pace => _pace; + late CheckResult _pace; + + /// Allows you to deserialize object. + static RFIDStatus? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDStatus(); + + result._pa = CheckResult.getByValue(jsonObject["pa"])!; + result._ca = CheckResult.getByValue(jsonObject["ca"])!; + result._aa = CheckResult.getByValue(jsonObject["aa"])!; + result._ta = CheckResult.getByValue(jsonObject["ta"])!; + result._bac = CheckResult.getByValue(jsonObject["bac"])!; + result._pace = CheckResult.getByValue(jsonObject["pace"])!; + result._overallStatus = + CheckResult.getByValue(jsonObject["overallStatus"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "overallStatus": overallStatus.value, + "pa": pa.value, + "ca": ca.value, + "aa": aa.value, + "ta": ta.value, + "bac": bac.value, + "pace": pace.value, + }.clearNulls(); +} diff --git a/lib/src/results/transaction_info.dart b/lib/src/results/transaction_info.dart new file mode 100644 index 0000000000..b4cf45545d --- /dev/null +++ b/lib/src/results/transaction_info.dart @@ -0,0 +1,40 @@ +// +// TransactionInfo.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class TransactionInfo { + String? get transactionId => _transactionId; + String? _transactionId; + + String? get tag => _tag; + String? _tag; + + /// The path to the logs folder of the session. + String? get sessionLogFolder => _sessionLogFolder; + String? _sessionLogFolder; + + /// Allows you to deserialize object. + static TransactionInfo? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TransactionInfo(); + + result._transactionId = jsonObject["transactionId"]; + result._tag = jsonObject["tag"]; + result._sessionLogFolder = jsonObject["sessionLogFolder"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "transactionId": transactionId, + "tag": tag, + "sessionLogFolder": sessionLogFolder, + }.clearNulls(); +} diff --git a/lib/src/results/visible_digital_seals/bytes_data.dart b/lib/src/results/visible_digital_seals/bytes_data.dart new file mode 100644 index 0000000000..07fa14dd34 --- /dev/null +++ b/lib/src/results/visible_digital_seals/bytes_data.dart @@ -0,0 +1,44 @@ +// +// BytesData.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class BytesData { + String get data => _data; + late String _data; + + int get length => _length; + late int _length; + + int get status => _status; + late int _status; + + int get type => _type; + late int _type; + + /// Allows you to deserialize object. + static BytesData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = BytesData(); + + result._data = jsonObject["data"]; + result._length = jsonObject["length"]; + result._status = jsonObject["status"]; + result._type = jsonObject["type"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "data": data, + "length": length, + "status": status, + "type": type, + }.clearNulls(); +} diff --git a/lib/src/results/visible_digital_seals/doc_feature.dart b/lib/src/results/visible_digital_seals/doc_feature.dart new file mode 100644 index 0000000000..c91c0c86a6 --- /dev/null +++ b/lib/src/results/visible_digital_seals/doc_feature.dart @@ -0,0 +1,26 @@ +part of "../../../flutter_document_reader_api.dart"; + +class DocFeature { + int? get type => _type; + int? _type; + + BytesData? get data => _data; + BytesData? _data; + + /// Allows you to deserialize object. + static DocFeature? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = DocFeature(); + + result._type = jsonObject["type"]; + result._data = BytesData.fromJson(jsonObject["data"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type, + "data": data?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/visible_digital_seals/lds_parsing_error_codes.dart b/lib/src/results/visible_digital_seals/lds_parsing_error_codes.dart new file mode 100644 index 0000000000..d925172298 --- /dev/null +++ b/lib/src/results/visible_digital_seals/lds_parsing_error_codes.dart @@ -0,0 +1,153 @@ +part of "../../../flutter_document_reader_api.dart"; + +enum LDSParsingErrorCodes { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + OK(0x00000001), + ASN_INCORRECT_DATA(0x80000001), + ASN_NOT_ENOUGH_DATA(0x80000002), + ASN_CONTENTS_UNEXPECTED_DATA(0x80000003), + ASN_SIGNED_DATA_INCORRECT_DATA(0x80000008), + ASN_SIGNED_DATA_ENCAP_CONTENTS_INCORRECT_DATA(0x80000009), + ASN_SIGNED_DATA_VERSION_INCORRECT_DATA(0x8000000A), + ASN_SIGNED_DATA_DIGEST_ALGORITHMS_INCORRECT_DATA(0x80000011), + ASN_LDS_OBJECT_INCORRECT_DATA(0x80000013), + ASN_LDS_OBJECT_VERSION_INCORRECT_DATA(0x80000014), + ASN_LDS_OBJECT_DIGEST_ALGORITHM_INCORRECT_DATA(0x80000015), + ASN_LDS_OBJECT_DG_HASHES_INCORRECT_DATA(0x80000016), + ASN_LDS_OBJECT_VERSION_INFO_INCORRECT_DATA(0x80000012), + ASN_CERTIFICATE_INCORRECT_DATA(0x80000017), + ASN_CERTIFICATE_VERSION_INCORRECT_DATA(0x80000018), + ASN_CERTIFICATE_SN_INCORRECT_DATA(0x80000019), + ASN_CERTIFICATE_SIGNATURE_INCORRECT_DATA(0x8000001A), + ASN_CERTIFICATE_ISSUER_INCORRECT_DATA(0x8000001B), + ASN_CERTIFICATE_VALIDITY_INCORRECT_DATA(0x8000001C), + ASN_CERTIFICATE_SUBJECT_INCORRECT_DATA(0x8000001D), + ASN_CERTIFICATE_SUBJECT_PK_INCORRECT_DATA(0x8000001E), + ASN_CERTIFICATE_EXTENSIONS_INCORRECT_DATA(0x8000001F), + ASN_SIGNER_INFO_INCORRECT_DATA(0x80000020), + ASN_SIGNER_INFO_VERSION_INCORRECT_DATA(0x80000021), + ASN_SIGNER_INFO_SID_INCORRECT_DATA(0x80000022), + ASN_SIGNER_INFO_DIGEST_ALG_INCORRECT_DATA(0x80000023), + ASN_SIGNER_INFO_SIGNED_ATTRS_INCORRECT_DATA(0x80000024), + ASN_SIGNER_INFO_SIGN_ALG_INCORRECT_DATA(0x80000025), + ASN_SIGNER_INFO_SIGNATURE_INCORRECT_DATA(0x80000026), + ASN_SIGNER_INFO_UNSIGNED_ATTRS_INCORRECT_DATA(0x80000027), + ICAO_LDS_OBJECT_UNSUPPORTED_DIGEST_ALGORITHM(0x80000030), + ICAO_SIGNED_DATA_SIGNER_INFOS_EMPTY(0x80000031), + ICAO_SIGNER_INFO_UNSUPPORTED_DIGEST_ALGORITHM(0x80000032), + ICAO_SIGNER_INFO_UNSUPPORTED_SIGNATURE_ALGORITHM(0x80000033), + ICAO_SIGNER_INFO_MESSAGE_DIGEST_ERROR(0x80000034), + ICAO_SIGNER_INFO_SIGNED_ATTRS_MISSED(0x80000036), + AUTH_SIGNER_INFO_CANT_FIND_CERTIFICATE(0x80000035), + AUTH_ERROR(0x80000050), + AUTH_UNSUPPORTED_SIGNATURE_ALGORITHM(0x80000051), + AUTH_UNSUPPORTED_PUBLIC_KEY_ALGORITHM(0x80000052), + AUTH_MESSED_ALGORITHMS(0x80000053), + AUTH_PUBLIC_KEY_DATA_INVALID(0x80000054), + AUTH_ALGORITHM_PARAMETERS_DATA_INVALID(0x80000055), + AUTH_SIGNATURE_DATA_INVALID(0x80000056), + AUTH_UNSUPPORTED_DIGEST_ALGORITHM(0x80000057), + AUTH_SIGNATURE_DATA_INCORRECT(0x80000058), + AUTH_ALGORITHM_PARAMETERS_NOT_DEFINED(0x80000059), + AUTH_SIGNATURE_CHECK_FAILED(0x8000005A), + DG_WRONG_TAH(0x80000070), + DG_CONTENTS_UNEXPECTED_DATA(0x80000071), + BAP_SYMMETRIC_CYPHER_CANT_INITIALIZE(0x81000011), + PACE_INFO_NOT_AVAILABLE(0x81000020), + PACE_SYMMETRIC_CYPHER_CANT_INITIALIZE(0x81000021), + PACE_KEY_AGREEMENT_CANT_INITIALIZE(0x81000022), + PACE_EPHEMERAL_KEYS_CANT_CREATE(0x81000023), + PACE_MAPPING_CANT_DECODE_NONCE(0x81000024), + PACE_SHARED_SECRET_CANT_CREATE(0x81000025), + PACE_DOMAIN_PARAMS_UNSUPPORTED_FORMAT(0x81000026), + PACE_EPHEMERAL_KEYS_INCORRECT(0x81000027), + PACE_MAPPING_EPHEMERAL_KEYS_INCORRECT(0x81000028), + PACE_MAPPING_CANT_PERFORM(0x81000029), + PACE_NON_MATCHING_AUTH_TOKENS(0x8100002A), + PACE_CAM_DATA_INCORRECT(0x8100002B), + PACE_CAM_DATA_CANT_VERIFY(0x8100002C), + PACE_CAM_DATA_NON_MATCHING(0x8100002D), + PACE_IM_SCHEME_INCORRECT(0x8100002E), + PACE_IM_RANDOM_MAPPING_FAILED(0x8100002F), + CA_CANT_FIND_PUBLIC_KEY(0x81000030), + CA_CANT_FIND_INFO(0x81000031), + CA_INCORRECT_VERSION(0x81000032), + CA_CANT_FIND_DOMAIN_PARAMETERS(0x81000033), + CA_KEY_AGREEMENT_CANT_INITIALIZE(0x81000034), + CA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM(0x81000035), + CA_EPHEMERAL_KEYS_CANT_CREATE(0x81000036), + CA_SHARED_SECRET_CANT_CREATE(0x81000037), + CA_NON_MATCHING_AUTH_TOKENS(0x81000038), + TA_INCORRECT_VERSION(0x81000040), + TA_CANT_BUILD_CERTIFICATE_CHAIN(0x81000041), + TA_CANT_FIND_IS_PRIVATE_KEY(0x81000042), + TA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM(0x81000043), + TA_SIGNATURE_BUILDING_ERROR(0x81000044), + TA_INVALID_KEY_ALGORITHM_PARAMETERS(0x81000045), + AA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM(0x81000050), + AA_PUBLIC_KEY_INCORRECT_DATA(0x81000051), + AA_PUBLIC_KEY_INCORRECT_PARAMETERS(0x81000052), + AA_PUBLIC_KEY_UNDEFINED_PARAMETERS(0x81000053), + AA_SIGNATURE_INCORRECT_DATA(0x81000054), + AA_UNSUPPORTED_RECOVERY_SCHEME(0x81000055), + AA_INCORRECT_TRAILER(0x81000056), + AA_UNSUPPORTED_DIGEST_ALGORITHM(0x81000057), + RI_SECTOR_KEY_CANT_FIND(0x81000070), + RI_SECTOR_KEY_INCORRECT_DATA(0x81000071), + RI_SECTOR_KEY_INCOMPLETE_DATA(0x81000072), + CV_CERTIFICATE_MISSING_MANDATORY_DATA_PK(0x81000060), + CV_CERTIFICATE_PUBLIC_KEY_UNSUPPORTED(0x81000062), + CV_CERTIFICATE_CHAT_UNSUPPORTED_TERMINAL_TYPE(0x81000063), + CV_CERTIFICATE_PRIVATE_KEY_UNSUPPORTED(0x8100006), + CV_CERTIFICATE_PRIVATE_KEY_INVALID_PARAMS(0x81000065), + CV_CERTIFICATE_INCORRECT_DATA(0x81000160), + CV_CERTIFICATE_CPI_INCORRECT_DATA(0x81000161), + CV_CERTIFICATE_CAR_INCORRECT_DATA(0x81000162), + CV_CERTIFICATE_PUBLIC_KEY_INCORRECT_DATA(0x81000163), + CV_CERTIFICATE_CHR_INCORRECT_DATA(0x81000164), + CV_CERTIFICATE_CHAT_INCORRECT_DATA(0x81000165), + CV_CERTIFICATE_VALID_FROM_INCORRECT_DATA(0x81000166), + CV_CERTIFICATE_VALID_TO_INCORRECT_DATA(0x81000167), + CV_CERTIFICATE_EXTENSIONS_INCORRECT_DATA(0x81000168), + CV_CERTIFICATE_PRIVATE_KEY_INCORRECT_DATA(0x81000169), + CV_CERTIFICATE_PRIVATE_KEY_MISSING(0x8100016A), + VDS_UNSUPPORTED_VERSION(0x81000200), + VDS_ISSUING_COUNTRY_SIZE(0x81000201), + VDS_ISSUING_COUNTRY_INCORRECT_DATA(0x81000202), + VDS_SIGNER_CERTIFICATE_SIZE(0x81000203), + VDS_SIGNER_CERTIFICATE_DATA(0x81000204), + VDS_SIGNATURE_INCORRECT_DATA(0x81000205), + VDS_NC_INCORRECT_DATA(0x81000300), + VDS_NC_MISSING_OR_INCORRECT_DATA(0x81000301), + VDS_NC_MISSING_OR_INCORRECT_HEADER(0x81000302), + VDS_NC_MISSING_OR_INCORRECT_TYPE(0x81000303), + VDS_NC_MISSING_OR_INCORRECT_VERSION(0x81000304), + VDS_NC_MISSING_OR_INCORRECT_ISSUING_COUNTRY(0x81000305), + VDS_NC_MISSING_OR_INCORRECT_MESSAGE(0x81000306), + VDS_NC_MISSING_OR_INCORRECT_SIGNATURE(0x81000307), + VDS_NC_MISSING_OR_INCORRECT_SIG_ALGORITHM(0x81000308), + VDS_NC_MISSING_OR_INCORRECT_CERTIFICATE(0x81000309), + VDS_NC_MISSING_OR_INCORRECT_SIG_VALUE(0x8100030A), + PACE_CAM_DATA_USAGE_INCORRECT(0x8100012B), + PACE_IM_MAPPING_DATA_INCORRECT(0x8100012F); + + const LDSParsingErrorCodes(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static LDSParsingErrorCodes? getByValue(int? i) { + if (i == null) return null; + try { + return LDSParsingErrorCodes.values.firstWhere((x) => x.value == i); + } catch (_) { + return LDSParsingErrorCodes.UNKNOWN; + } + } +} diff --git a/lib/src/results/visible_digital_seals/lds_parsing_notification_codes.dart b/lib/src/results/visible_digital_seals/lds_parsing_notification_codes.dart new file mode 100644 index 0000000000..e006b4ef92 --- /dev/null +++ b/lib/src/results/visible_digital_seals/lds_parsing_notification_codes.dart @@ -0,0 +1,264 @@ +// +// LDSParsingNotificationCodes.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +enum LDSParsingNotificationCodes { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + ASN_CERTIFICATE_INCORRECT_VERSION(0x90000001), + ASN_CERTIFICATE_NON_MATCHING_SIGNATURE_ALGORITHM(0x90000002), + ASN_CERTIFICATE_INCORRECT_TIME_CODING(0x90000003), + ASN_CERTIFICATE_INCORRECT_USE_OF_GENERALIZED_TIME(0x90000004), + ASN_CERTIFICATE_EMPTY_ISSUER(0x90000005), + ASN_CERTIFICATE_EMPTY_SUBJECT(0x90000006), + ASN_CERTIFICATE_UNSUPPORTED_CRITICAL_EXTENSION(0x90000008), + ASN_CERTIFICATE_FORCED_DEFAULT_CSCA_ROLE(0x9000000E), + ASN_CERTIFICATE_FORCED_DEFAULT_DS_ROLE(0x9000000F), + ASN_CERTIFICATE_INCORRECT_ISSUER_SUBJECT_DS(0x90000010), + ASN_CERTIFICATE_DUPLICATING_EXTENSIONS(0x90000017), + ICAO_CERTIFICATE_VERSION_MISSED(0x90000200), + ICAO_CERTIFICATE_VERSION_INCORRECT(0x90000201), + ICAO_CERTIFICATE_ISSUER_COUNTRY_MISSED(0x90000202), + ICAO_CERTIFICATE_ISSUER_COMMON_NAME_MISSED(0x90000203), + ICAO_CERTIFICATE_ISSUER_COUNTRY_NON_COMPLIANT(0x90000204), + ICAO_CERTIFICATE_SUBJECT_COUNTRY_MISSED(0x90000205), + ICAO_CERTIFICATE_SUBJECT_COMMON_NAME_MISSED(0x90000206), + ICAO_CERTIFICATE_SUBJECT_COUNTRY_NON_COMPLIANT(0x90000207), + ICAO_CERTIFICATE_USING_NON_COMPLIANT_DATA(0x90000208), + ICAO_CERTIFICATE_UNSUPPORTED_SIGNATURE_ALGORITHM(0x90000209), + ICAO_CERTIFICATE_UNSUPPORTED_PUBLIC_KEY_ALGORITHM(0x9000020A), + ICAO_CERTIFICATE_MISSED_EXTENSIONS(0x9000020B), + ICAO_CERTIFICATE_VALIDITY(0x9000020C), + ICAO_CERTIFICATE_EXT_USING_NON_COMPLIANT_DATA(0x9000020D), + ICAO_CERTIFICATE_EXT_KEY_USAGE_MISSED(0x9000020E), + ICAO_CERTIFICATE_EXT_KEY_USAGE_NOT_CRITICAL(0x9000020F), + ICAO_CERTIFICATE_EXT_KEY_USAGE_INCORRECT_DATA(0x90000210), + ICAO_CERTIFICATE_EXT_BASIC_C_MISSED(0x90000211), + ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_USAGE1(0x90000212), + ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_USAGE2(0x90000213), + ICAO_CERTIFICATE_EXT_BASIC_C_NOT_CRITICAL(0x90000214), + ICAO_CERTIFICATE_EXT_BASIC_C_INCORRECT_DATA(0x90000215), + ICAO_CERTIFICATE_EXT_BASIC_C_PATH_LEN_C_MISSED(0x90000216), + ICAO_CERTIFICATE_EXT_BASIC_C_PATH_LEN_C_INCORRECT(0x90000217), + ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_NOT_CRITICAL(0x90000218), + ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_INCORRECT_USAGE(0x90000219), + ICAO_CERTIFICATE_EXT_EXT_KEY_USAGE_INCORRECT_DATA(0x9000021A), + ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_MISSED(0x9000021B), + ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_INCORRECT_DATA(0x9000021C), + ICAO_CERTIFICATE_EXT_AUTH_KEY_ID_KEY_ID_MISSED(0x9000021D), + ICAO_CERTIFICATE_EXT_SUBJECT_KEY_ID_MISSED(0x9000021E), + ICAO_CERTIFICATE_EXT_SUBJECT_KEY_ID_INCORRECT_DATA(0x9000021F), + ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_MISSED(0x90000220), + ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_INCORRECT_DATA(0x90000221), + ICAO_CERTIFICATE_EXT_PRIVATE_KEY_UP_EMPTY(0x90000222), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_MISSED(0x90000223), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_INCORRECT_DATA(0x90000224), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_EMPTY(0x90000225), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_NON_COMPLIANT(0x90000226), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_CRITICAL(0x90000228), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_EMPTY(0x90000229), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_INCORRECT(0x9000022A), + ICAO_CERTIFICATE_EXT_SUBJECT_ALT_NAME_DN_NON_COMPLIANT(0x9000022B), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_MISSED(0x9000022C), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_INCORRECT_DATA(0x9000022D), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_EMPTY(0x9000022E), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_NON_COMPLIANT(0x9000022F), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_CRITICAL(0x90000231), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_EMPTY(0x90000232), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_INCORRECT(0x90000233), + ICAO_CERTIFICATE_EXT_ISSUER_ALT_NAME_DN_NON_COMPLIANT(0x90000234), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_MISSED(0x90000235), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_INCORRECT_DATA(0x90000236), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_VERSION(0x90000237), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_DOC_TYPES(0x90000238), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_DOC_TYPES_EMPTY(0x90000239), + ICAO_CERTIFICATE_EXT_CERT_POLICIES_INCORRECT_DATA(0x9000023A), + ICAO_CERTIFICATE_EXT_CERT_POLICIES_EMPTY(0x9000023B), + ICAO_CERTIFICATE_EXT_CERT_POLICIES_POLICY_ID_MISSED(0x9000023C), + ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_MISSED(0x9000023D), + ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_INCORRECT_DATA(0x9000023E), + ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_EMPTY(0x9000023F), + ICAO_CERTIFICATE_EXT_CRL_DIST_POINT_POINT_MISSED(0x90000240), + ICAO_CERTIFICATE_SN_NON_COMPLIANT(0x90000241), + ICAO_CERTIFICATE_ISSUER_SN_NON_COMPLIANT(0x90000242), + ICAO_CERTIFICATE_SUBJECT_SN_NON_COMPLIANT(0x90000243), + ICAO_CERTIFICATE_ISSUER_ATTRIBUTE_NON_COMPLIANT(0x90000244), + ICAO_CERTIFICATE_SUBJECT_ATTRIBUTE_NON_COMPLIANT(0x90000245), + ICAO_CERTIFICATE_ISSUER_SUBJECT_COUNTRY_NON_MATCHING(0x90000246), + ICAO_CERTIFICATE_EXT_CSCA_ALT_NAMES_NON_MATCHING(0x90000247), + ICAO_CERTIFICATE_EXT_NAME_CHANGE_INCORRECT_DATA(0x90000248), + ICAO_CERTIFICATE_EXT_NAME_CHANGE_NON_COMPLIANT(0x90000249), + ICAO_CERTIFICATE_EXT_NAME_CHANGE_CRITICAL(0x9000024A), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_NON_COMPLIANT(0x9000024B), + ICAO_CERTIFICATE_EXT_DOC_TYPE_LIST_CRITICAL(0x9000024C), + ICAO_CERTIFICATE_EXT_OPTIONAL_CRITICAL(0x9000024D), + ICAO_CERTIFICATE_SUBJECT_NON_COMPLIANT(0x9000024E), + ICAO_CERTIFICATE_SUBJECT_COMMON_NAME_NON_COMPLIANT(0x9000024F), + ICAO_COM_LDS_VERSION_INCORRECT(0x90000020), + ICAO_COM_LDS_VERSION_MISSING(0x90000021), + ICAO_COM_UNICODE_VERSION_INCORRECT(0x90000022), + ICAO_COM_UNICODE_VERSION_MISSING(0x90000023), + ICAO_COM_DGPM_INCORRECT(0x90000024), + ICAO_COM_DGPM_MISSING(0x90000025), + ICAO_COM_DGPM_UNEXPECTED(0x90000026), + ICAO_APPLICATION_LDS_VERSION_UNSUPPORTED(0x90000030), + ICAO_APPLICATION_UNICODE_VERSION_UNSUPPORTED(0x90000031), + ICAO_APPLICATION_LDS_VERSION_INCONSISTENT(0x90000032), + ICAO_APPLICATION_UNICODE_VERSION_INCONSISTENT(0x90000033), + ASN_SIGNED_DATA_OID_INCORRECT(0x90000100), + ASN_SIGNED_DATA_VERSION_INCORRECT(0x900001A0), + ASN_SIGNED_DATA_CONTENT_OID_INCORRECT(0x900001A1), + ICAO_SIGNED_DATA_VERSION_INCORRECT(0x90000101), + ICAO_SIGNED_DATA_DIGEST_ALGORITHMS_EMPTY(0x90000102), + ICAO_SIGNED_DATA_DIGEST_ALGORITHMS_UNSUPPORTED(0x90000103), + ICAO_SIGNED_DATA_SIGNER_INFOS_MULTIPLE_ENTRIES(0x90000109), + ICAO_SIGNED_DATA_CERTIFICATES_MISSED(0x900001B0), + ICAO_SIGNED_DATA_CERTIFICATES_EMPTY(0x900001B1), + ICAO_SIGNED_DATA_CRLS_INCORRECT_USAGE(0x900001B2), + ICAO_LDS_OBJECT_INCORRECT_CONTENT_OID(0x90000104), + ICAO_LDS_OBJECT_DG_NUMBER_INCORRECT(0x90000105), + ICAO_LDS_OBJECT_DG_HASH_MISSING(0x90000106), + ICAO_LDS_OBJECT_DG_HASH_EXTRA(0x90000107), + ICAO_LDS_OBJECT_VERSION_INCORRECT(0x90000108), + ICAO_MASTER_LIST_VERSION_INCORRECT(0x900001C0), + ICAO_DEVIATION_LIST_VERSION_INCORRECT(0x900001C8), + BSI_DEFECT_LIST_VERSION_INCORRECT(0x900001D0), + BSI_BLACK_LIST_VERSION_INCORRECT(0x900001D8), + ASN_SIGNER_INFO_VERSION_INCORRECT(0x9000010A), + ASN_SIGNER_INFO_SID_INCORRECT_CHOICE(0x9000010B), + ASN_SIGNER_INFO_SID_DIGEST_ALGORITHM_NOT_LISTED(0x9000010C), + ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_MISSING(0x9000010D), + ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_DATA(0x9000010E), + ASN_SIGNER_INFO_MESSAGE_DIGEST_ATTR_Value(0x9000010F), + ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_MISSING(0x90000110), + ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_DATA(0x90000111), + ASN_SIGNER_INFO_CONTENT_TYPE_ATTR_VALUE(0x90000112), + ASN_SIGNER_INFO_SIGNING_TIME_ATTR_MISSING(0x9000011B), + ASN_SIGNER_INFO_SIGNING_TIME_ATTR_DATA(0x9000011C), + ASN_SIGNER_INFO_SIGNING_TIME_ATTR_VALUE(0x9000011D), + ASN_SIGNER_INFO_LIST_CONTENT_DESCRIPTION_ATTR_MISSING(0x9000011E), + ASN_SIGNER_INFO_LIST_CONTENT_DESCRIPTION_ATTR_DATA(0x9000011F), + AUTH_SIGNER_INFO_CERTIFICATE_VALIDITY(0x90000115), + AUTH_SIGNER_INFO_CERTIFICATE_ROOT_IS_NOT_TRUSTED(0x90000116), + AUTH_SIGNER_INFO_CERTIFICATE_CANT_FIND_CSCA(0x90000117), + AUTH_SIGNER_INFO_CERTIFICATE_REVOKED(0x90000118), + AUTH_SIGNER_INFO_CERTIFICATE_SIGNATURE_INVALID(0x90000119), + UNSUPPORTED_IMAGE_FORMAT(0x9000011A), + MRZ_DOCUMENT_TYPE_UNKNOWN(0x00022008), + MRZ_ISSUING_STATE_SYNTAX_ERROR(0x00022009), + MRZ_NAME_IS_VOID(0x0002200A), + MRZ_NUMBER_INCORRECT_CHECKSUM(0x0002200D), + MRZ_NATIONALITY_SYNTAX_ERROR(0x0002200E), + MRZ_DOB_SYNTAX_ERROR(0x0002200F), + MRZ_DOB_ERROR(0x00022010), + MRZ_DOB_INCORRECT_CHECKSUM(0x00022011), + MRZ_SEX_INCORRECT(0x00022012), + MRZ_DOE_SYNTAX_ERROR(0x00022013), + MRZ_DOE_ERROR(0x00022014), + MRZ_DOE_INCORRECT_CHECKSUM(0x00022015), + MRZ_OPTIONAL_DATA_INCORRECT_CHECKSUM(0x00022016), + MRZ_INCORRECT_CHECKSUM(0x00022017), + MRZ_INCORRECT(0x00022018), + BIOMETRICS_FORMAT_OWNER_MISSING(0x90010000), + BIOMETRICS_FORMAT_OWNER_INCORRECT(0x90020000), + BIOMETRICS_FORMAT_TYPE_MISSING(0x90030000), + BIOMETRICS_FORMAT_TYPE_INCORRECT(0x90040000), + BIOMETRICS_TYPE_INCORRECT(0x90050000), + BIOMETRICS_SUB_TYPE_MISSING(0x90060000), + BIOMETRICS_SUB_TYPE_INCORRECT(0x90070000), + BIOMETRICS_BDB_IMAGE_MISSING(0x90080000), + BIOMETRICS_BDB_FORMAT_ID_INCORRECT(0x90090000), + BIOMETRICS_BDB_VERSION_INCORRECT(0x900A0000), + BIOMETRICS_BDB_DATA_LENGTH_INCORRECT(0x900B0000), + BIOMETRICS_BDB_DATA_GENDER(0x90100000), + BIOMETRICS_BDB_DATA_EYE_COLOR(0x90110000), + BIOMETRICS_BDB_DATA_HAIR_COLOR(0x90120000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_YAW(0x90130000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_PITCH(0x90140000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_ROLL(0x90150000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_U_YAW(0x90160000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_U_PITCH(0x90170000), + BIOMETRICS_BDB_DATA_POSE_ANGLE_U_ROLL(0x90180000), + BIOMETRICS_BDB_DATA_FACE_IMAGE_TYPE(0x90190000), + BIOMETRICS_BDB_DATA_IMAGE_DATA_TYPE(0x901A0000), + SI_PACE_INFO_UNSUPPORTED_STD_PARAMETERS(0x91000000), + SI_PACE_INFO_DEPRECATED_VERSION(0x91000001), + SI_PACE_DOMAIN_PARAMS_USING_STD_REF(0x91000002), + SI_PACE_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM(0x91000003), + SI_CA_INFO_INCORRECT_VERSION(0x91000004), + SI_CA_PUBLIC_KEY_UNSUPPORTED_ALGORITHM(0x91000005), + SI_CA_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM(0x91000006), + SI_TA_INFO_INCORRECT_VERSION(0x91000007), + SI_TA_INFO_FILE_ID_FOR_VERSION2(0x91000008), + SI_EID_SECURITY_UNSUPPORTED_DIGEST_ALGORITHM(0x91000009), + SI_RI_INFO_INCORRECT_VERSION(0x9100000A), + SI_RI_DOMAIN_PARAMS_UNSUPPORTED_ALGORITHM(0x9100000B), + SI_AA_INFO_INCORRECT_VERSION(0x9100000C), + SI_AA_INFO_UNSUPPORTED_ALGORITHM(0x9100000D), + SI_AA_INFO_INCONSISTENT_ALGORITHM_REFERENCE(0x9100000E), + SI_STORAGE_PACE_INFO_NOT_AVAILABLE(0x91000100), + SI_STORAGE_PACE_INFO_NO_STD_PARAMETERS(0x91000101), + SI_STORAGE_PACE_INFO_NO_MATCHING_DOMAIN_PARAMS(0x91000102), + SI_STORAGE_CA_INFO_NOT_AVAILABLE(0x91000103), + SI_STORAGE_CA_DOMAIN_PARAMS_NO_REQUIRED_OPTION(0x91000104), + SI_STORAGE_CA_DOMAIN_PARAMS_NOT_AVAILABLE(0x91000105), + SI_STORAGE_CA_ANONYMOUS_INFOS(0x91000106), + SI_STORAGE_CA_INFO_NO_MATCHING_DOMAIN_PARAMS(0x91000107), + SI_STORAGE_CA_INFO_NO_MATCHING_PUBLIC_KEY(0x91000108), + SI_STORAGE_CA_INCORRECT_INFOS_QUANTITY(0x91000109), + SI_STORAGE_TA_INFO_NOT_AVAILABLE(0x9100010A), + SI_STORAGE_CARD_INFO_LOCATOR_MULTIPLE_ENTRIES(0x9100010B), + SI_STORAGE_EID_SECURITY_INFO_MULTIPLE_ENTRIES(0x9100010C), + SI_STORAGE_PRIVILEGED_TI_MULTIPLE_ENTRIES(0x9100010D), + SI_STORAGE_PRIVILEGED_TI_INCORRECT_USAGE(0x9100010E), + SI_STORAGE_RI_DOMAIN_PARAMS_MULTIPLE_ENTRIES(0x9100010F), + SI_STORAGE_PACE_INFOS_NON_CONSISTANT(0x91000110), + SI_STORAGE_CS_NONCONSISTANT(0x91000111), + SI_STORAGE_CS_PACE_CAM_KEY_MISSING(0x91000112), + CV_CERTIFICATE_PROFILE_INCORRECT_VERSION(0x91000201), + CV_CERTIFICATE_VALIDITY(0x91000202), + CV_CERTIFICATE_NON_CV_CA_DOMAIN_PARAMETERS(0x91000203), + CV_CERTIFICATE_PRIVATE_KEY_INCORRECT_VERSION(0x91000204), + TA_PACE_STATIC_BINDING_USED(0x91000300), + AUTH_ML_SIGNER_INFO_CERTIFICATE_VALIDITY(0x92000115), + AUTH_ML_SIGNER_INFO_CERTIFICATE_ROOT_IS_NOT_TRUSTED(0x92000116), + AUTH_ML_SIGNER_INFO_CERTIFICATE_CANT_FIND_CSCA(0x92000117), + AUTH_ML_SIGNER_INFO_CERTIFICATE_REVOKED(0x92000118), + AUTH_ML_SIGNER_INFO_CERTIFICATE_SIGNATURE_INVALID(0x92000119), + NTF_LDS_ICAO_CERTIFICATE_CHAIN_COUNTRY_NON_MATCHING(0x90000250), + NTF_LDS_ICAO_CERTIFICATE_VISUAL_MRZ_COUNTRY_NON_MATCHING(0x90000251), + NTF_LDS_MRZ_COUNTRYCODE_VISUALMRZ_NON_MATCHING(0x00022019), + NTF_LDS_ICAO_CERTIFICATE_MRZ_COUNTRY_NON_MATCHING(0x90000252), + NTF_LDS_ICAO_CERTIFICATE_ISSUER_COUNTRY_NON_UPPER_CASE(0x90000253), + NTF_LDS_ICAO_CERTIFICATE_SUBJECT_COUNTRY_NON_UPPER_CASE(0x90000254), + ASN_CERTIFICATE_NONMATCHINGDSROLE(0x90000011), + MDL_CERTIFICATE_CHAIN_SOP_NONMATCHING(0x90000400), + MDL_CERTIFICATE_UNSUPPORTEDPUBLICKEYALGORITHM(0x90000401), + MDL_CERTIFICATE_UNSUPPORTEDSIGNATUREALGORITHM(0x90000402), + MDL_CERTIFICATE_UNSUPPORTEDPUBLICKEYPARAMS(0x90000403); + + const LDSParsingNotificationCodes(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static LDSParsingNotificationCodes? getByValue(int? i) { + if (i == null) return null; + try { + return LDSParsingNotificationCodes.values.firstWhere((x) => x.value == i); + } catch (_) { + return LDSParsingNotificationCodes.UNKNOWN; + } + } +} diff --git a/lib/src/results/visible_digital_seals/vds_data.dart b/lib/src/results/visible_digital_seals/vds_data.dart new file mode 100644 index 0000000000..357d264c4d --- /dev/null +++ b/lib/src/results/visible_digital_seals/vds_data.dart @@ -0,0 +1,94 @@ +part of "../../../flutter_document_reader_api.dart"; + +/// Visible Digital Seal. +class VDSData { + int? get type => _type; + late int? _type; + + int? get docType => _docType; + late int? _docType; + + int? get featureRef => _featureRef; + late int? _featureRef; + + /// Visible Digital Seal use case version. + int? get version => _version; + late int? _version; + + /// Three letter code identifying the issuing state or organization. + String? get issuingCountry => _issuingCountry; + String? _issuingCountry; + + String? get docIssueDate => _docIssueDate; + String? _docIssueDate; + + /// The binary data of the verified digital signature. + BytesData? get signature => _signature; + BytesData? _signature; + + String? get signatureDate => _signatureDate; + String? _signatureDate; + + String? get signer => _signer; + String? _signer; + + String? get certificate => _certificate; + String? _certificate; + + /// The certificate chain, used for the digital signature verification. + List get certificateChain => _certificateChain; + List _certificateChain = []; + + /// The doc features. + List get docFeatures => _docFeatures; + List _docFeatures = []; + + /// The list of remarks occured during the scanning procedure. + /// + /// Each element belongs to the [LDSParsingErrorCodes] or the [LDSParsingNotificationCodes]. + List get notifications => _notifications; + List _notifications = []; + + /// Allows you to deserialize object. + static VDSData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = VDSData(); + + result._type = jsonObject["type"]; + result._docType = jsonObject["docType"]; + result._featureRef = jsonObject["featureRef"]; + result._version = jsonObject["version"]; + result._issuingCountry = jsonObject["issuingCountry"]; + result._docIssueDate = jsonObject["docIssueDate"]; + result._signature = BytesData.fromJson(jsonObject["signature"]); + result._signatureDate = jsonObject["signatureDate"]; + result._signer = jsonObject["signer"]; + result._certificate = jsonObject["certificate"]; + for (var item in jsonObject["certificateChain"]) { + result._certificateChain.addSafe(CertificateChain.fromJson(item)); + } + for (var item in jsonObject["docFeatures"]) { + result._docFeatures.addSafe(DocFeature.fromJson(item)); + } + result._notifications = _intListFrom(jsonObject["notifications"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type, + "docType": docType, + "featureRef": featureRef, + "version": version, + "issuingCountry": issuingCountry, + "docIssueDate": docIssueDate, + "signature": signature?.toJson(), + "signatureDate": signatureDate, + "signer": signer, + "certificate": certificate, + "certificateChain": certificateChain.map((e) => e.toJson()).toList(), + "docFeatures": docFeatures.map((e) => e.toJson()).toList(), + "notifications": notifications, + }.clearNulls(); +} diff --git a/lib/src/results/visible_digital_seals/vdsnc_data.dart b/lib/src/results/visible_digital_seals/vdsnc_data.dart new file mode 100644 index 0000000000..c864461989 --- /dev/null +++ b/lib/src/results/visible_digital_seals/vdsnc_data.dart @@ -0,0 +1,86 @@ +// +// VDSNCData.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Visible Digital Seal for Non Constrained environments. +class VDSNCData { + /// Visible Digital Seal use case type. + /// Type is set to `icao.test` for Proof of Testing (data defined by CAPSCA), + /// `icao.vacc` for Proof of Vaccination (data defined by WHO). + /// Other Types may be added in the future. + String? get type => _type; + String? _type; + + /// Visible Digital Seal use case version. + int get version => _version; + late int _version; + + /// Three letter code identifying the issuing state or organization. + String? get issuingCountry => _issuingCountry; + String? _issuingCountry; + + /// The message field contains the actual data as a dictionary (JSON). + Map? get message => _message; + Map? _message = {}; + + /// The signature algorithm used to produce the signature. ECDSA scheme. + String? get signatureAlgorithm => _signatureAlgorithm; + String? _signatureAlgorithm; + + /// The binary data of the verified digital signature. + BytesData? get signature => _signature; + BytesData? _signature; + + /// The binary data of the signer certificate. + BytesData? get certificate => _certificate; + BytesData? _certificate; + + /// The certificate chain, used for the digital signature verification. + List get certificateChain => _certificateChain; + List _certificateChain = []; + + /// The list of remarks occured during the scanning procedure. + /// + /// Each element belongs to the [LDSParsingErrorCodes] or the [LDSParsingNotificationCodes]. + List get notifications => _notifications; + List _notifications = []; + + /// Allows you to deserialize object. + static VDSNCData? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = VDSNCData(); + + result._type = jsonObject["type"]; + result._version = jsonObject["version"]; + result._issuingCountry = jsonObject["issuingCountry"]; + result._message = jsonObject["message"]; + result._signatureAlgorithm = jsonObject["signatureAlgorithm"]; + result._signature = BytesData.fromJson(jsonObject["signature"]); + result._certificate = BytesData.fromJson(jsonObject["certificate"]); + for (var item in jsonObject["certificateChain"]) { + result._certificateChain.addSafe(CertificateChain.fromJson(item)); + } + result._notifications = _intListFrom(jsonObject["notifications"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "type": type, + "version": version, + "issuingCountry": issuingCountry, + "message": message, + "signatureAlgorithm": signatureAlgorithm, + "signature": signature?.toJson(), + "certificate": certificate?.toJson(), + "certificateChain": certificateChain.map((e) => e.toJson()).toList(), + "notifications": notifications, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/Comparison.dart b/lib/src/results/visual_results/Comparison.dart new file mode 100644 index 0000000000..4d93c473fc --- /dev/null +++ b/lib/src/results/visual_results/Comparison.dart @@ -0,0 +1,45 @@ +// +// Comparison.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class Comparison { + /// The value's origin source. + ResultType get sourceTypeLeft => _sourceTypeLeft; + late ResultType _sourceTypeLeft; + + /// The value's origin source. + ResultType get sourceTypeRight => _sourceTypeRight; + late ResultType _sourceTypeRight; + + /// The status of field comparisons. + CheckResult get status => _status; + late CheckResult _status; + + /// Allows you to deserialize object. + static Comparison? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Comparison(); + + result._sourceTypeLeft = + ResultType.getByValue(jsonObject["sourceTypeLeft"])!; + result._sourceTypeRight = + ResultType.getByValue(jsonObject["sourceTypeRight"])!; + result._status = CheckResult.getByValue(jsonObject["status"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "sourceTypeLeft": sourceTypeLeft.value, + "sourceTypeRight": sourceTypeRight.value, + "status": status.value, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/LCID.dart b/lib/src/results/visual_results/LCID.dart new file mode 100644 index 0000000000..753644d45a --- /dev/null +++ b/lib/src/results/visual_results/LCID.dart @@ -0,0 +1,209 @@ +// +// LCID.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains a language ID that identifies a particular language. +enum LCID { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + LATIN(0), + ABKHAZIAN_CYRILLIC(10011), + AFRIKAANS(1078), + ALBANIAN(1052), + AMHARIC(1118), + ARABIC_ALGERIA(5121), + ARABIC_BAHRAIN(15361), + ARABIC_EGYPT(3073), + ARABIC_IRAQ(2049), + ARABIC_JORDAN(11265), + ARABIC_KUWAIT(13313), + ARABIC_LEBANON(12289), + ARABIC_LIBYA(4097), + ARABIC_MOROCCO(6145), + ARABIC_OMAN(8193), + ARABIC_QATAR(16385), + ARABIC_SAUDI_ARABIA(1025), + ARABIC_SYRIA(10241), + ARABIC_TUNISIA(7169), + ARABIC_UAE(14337), + ARABIC_YEMEN(9217), + ARABIC_ARMENIAN(1067), + ARABIC_WORLD(4096), + AZERI_CYRILIC(2092), + AZERI_LATIN(1068), + ASSAMESE(1101), + BASQUE(1069), + BANK_CARD(10003), + BANK_CARD_CVV2(10004), + BANK_CARD_NAME(10002), + BANK_CARD_NUMBER(10000), + BANK_CARD_VALID_THRU(10001), + BELARUSIAN(1059), + BENGALI_BANGLADESH(2117), + BENGALI_INDIA(1093), + BULGARIAN(1026), + CATALAN(1027), + CHINESE_HONGKONG_SAR(3076), + CHINESE_MACAO_SAR(5124), + CHINESE(2052), + CHINESE_SINGAPORE(4100), + CHINESE_TAIWAN(1028), + CROATIAN(1050), + CZECH(1029), + DANISH(1030), + DIVEHI(1125), + DUTCH_BELGIUM(2067), + DUTCH_NETHERLANDS(1043), + ENGLISH_AUSTRALIA(3081), + ENGLISH_BELIZE(10249), + ENGLISH_CANADA(4105), + ENGLISH_CARRIBEAN(9225), + ENGLISH_IRELAND(6153), + ENGLISH_JAMAICA(8201), + ENGLISH_NEW_ZEALAND(5129), + ENGLISH_PHILIPPINES(13321), + ENGLISH_SOUTH_AFRICA(7177), + ENGLISH_TRINIDAD(11273), + ENGLISH_UK(2057), + ENGLISH_US(1033), + ENGLISH_ZIMBABWE(12297), + ESTONIAN(1061), + FAEROESE(1080), + FARSI(1065), + FINNISH(1035), + FRENCH_BELGIUM(2060), + FRENCH_CANADA(3084), + FRENCH_FRANCE(1036), + FRENCH_LUXEMBOURG(5132), + FRENCH_MONACO(6156), + FRENCH_SWITZERLAND(4108), + FYRO_MACEDONIAN(1071), + GALICIAN(1110), + GEORGIAN(1079), + GERMAN_AUSTRIA(3079), + GERMAN_GERMANY(1031), + GERMAN_LIECHTENSTEIN(5127), + GERMAN_LUXEMBOURG(4103), + GERMAN_SWITZERLAND(2055), + GREEK(1032), + GUJARATI(1095), + HEBREW(1037), + HINDI_INDIA(1081), + HUNGARIAN(1038), + ICELANDIC(1039), + INDONESIAN(1057), + ITALIAN_ITALY(1040), + ITALIAN_SWITZERLAND(2064), + JAPANESE(1041), + KANNADA(1099), + KASHMIRI(1120), + KAZAKH(1087), + KONKANI(1111), + KOREAN(1042), + KYRGYZ_CYRILICK(1088), + LAO(1108), + LATVIAN(1062), + LITHUANIAN(1063), + MALAY_MALAYSIA(1086), + MALAY_BRUNEI_DARUSSALAM(2110), + MARATHI(1102), + MONGOLIAN_CYRILIC(1104), + NORWEGIAN_BOKMAL(1044), + NORWEGIAN_NYORSK(2068), + PASHTO(1123), + POLISH(1045), + PORTUGUESE_BRAZIL(1046), + PORTUGUESE_PORTUGAL(2070), + PUNJABI(1094), + RHAETO_ROMANIC(1047), + ROMANIAN(1048), + RUSSIAN(1049), + SANSKRIT(1103), + SERBIAN_CYRILIC(3098), + SERBIAN_LATIN(2074), + SINDHI(2137), + SINDHI_INDIA(1113), + SINHALA(1115), + SLOVAK(1051), + SLOVENIAN(1060), + SPANISH_ARGENTINA(11274), + SPANISH_BOLIVIA(16394), + SPANISH_CHILE(13322), + SPANICH_COLOMBIA(9226), + SPANISH_COSTA_RICA(5130), + SPANISH_DOMINICAN_REPUBLIC(7178), + SPANISH_ECUADOR(12298), + SPANISH_EL_SALVADOR(17418), + SPANISH_GUATEMALA(4106), + SPANISH_HONDURAS(18442), + SPANISH_MEXICO(2058), + SPANISH_NICARAGUA(19466), + SPANISH_PANAMA(6154), + SPANISH_PARAGUAY(15370), + SPANISH_PERU(10250), + SPANISH_PUERTO_RICO(20490), + SPANISH_TRADITIONAL_SORT(1034), + SPANISH_INTERNATIONAL_SORT(3082), + SPANISH_URUGUAY(14346), + SPANISH_VENEZUELA(8202), + SWAHILI(1089), + SWEDISH(1053), + SWEDISH_FINLAND(2077), + SYRIAC(1114), + TAMIL(1097), + TATAR(1092), + TELUGU(1098), + THAI_THAILAND(1054), + TURKISH(1055), + TAJIK_CYRILLIC(1064), + TURKMEN(1090), + UKRAINIAN(1058), + URDU(1056), + UZBEK_CYRILIC(2115), + UZBEK_LATIN(1091), + VIETNAMESE(1066), + CTC_SIMPLIFIED(50001), + CTC_TRADITIONAL(50002), + MALTESE(1082), + BURMESE(1109), + KHMER(1107), + KARAKALPAK_LATIN(10012), + MALAYALAM(1100), + NEPALI(1121), + ORIYA(1096), + URDU_DETECTION(10560); + + const LCID(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static LCID? getByValue(int? i) { + if (i == null) return null; + try { + return LCID.values.firstWhere((x) => x.value == i); + } catch (_) { + return LCID.UNKNOWN; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/visual_results/Lights.dart b/lib/src/results/visual_results/Lights.dart new file mode 100644 index 0000000000..b333560d05 --- /dev/null +++ b/lib/src/results/visual_results/Lights.dart @@ -0,0 +1,54 @@ +// +// Lights.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains a set of identifiers used for identifying the +/// document reader possibilities, specifying lighting schemes for scanning, etc. +enum Lights { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Light off. + NONE(0), + + /// General UV light scheme. + UV(128), + + /// General white light scheme. + WHITE_FULL(6), + + IR(16777216), + + /// Upper/lower lighters of IR light scheme. + IR_TOP(8), + + /// Side lighters of IR light scheme. + IR_SIDE(16), + + /// Upper/lower and side lighters of IR light scheme. + IR_FULL((8 | 16)), + + /// OVD light for hologram visualization. + OVD(67108864), + + /// Combined light for [WHITE_FULL] and [OVD]. + WHITE_FULL_OVD(6 | 67108864); + + const Lights(this.value); + final int value; + + static Lights? getByValue(int? i) { + if (i == null) return null; + try { + return Lights.values.firstWhere((x) => x.value == i); + } catch (_) { + return Lights.UNKNOWN; + } + } +} diff --git a/lib/src/results/visual_results/Rect.dart b/lib/src/results/visual_results/Rect.dart new file mode 100644 index 0000000000..cd889ee9a0 --- /dev/null +++ b/lib/src/results/visual_results/Rect.dart @@ -0,0 +1,40 @@ +// +// Rect.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +class Rect { + int get bottom => _bottom; + late int _bottom; + + int get top => _top; + late int _top; + + int get left => _left; + late int _left; + + int get right => _right; + late int _right; + + /// Allows you to deserialize object. + static Rect? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Rect(); + + result._bottom = jsonObject["bottom"]; + result._top = jsonObject["top"]; + result._left = jsonObject["left"]; + result._right = jsonObject["right"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"bottom": bottom, "top": top, "left": left, "right": right}.clearNulls(); +} diff --git a/lib/src/results/visual_results/Symbol.dart b/lib/src/results/visual_results/Symbol.dart new file mode 100644 index 0000000000..ca686e0f3f --- /dev/null +++ b/lib/src/results/visual_results/Symbol.dart @@ -0,0 +1,43 @@ +// +// Symbol.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class Symbol { + /// ASCII code of symbol. + int get code => _code; + late int _code; + + /// Bounds result of the particular value. + Rect? get rect => _rect; + Rect? _rect; + + /// Symbol recognition probability (0–100, %). + int get probability => _probability; + late int _probability; + + /// Allows you to deserialize object. + static Symbol? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Symbol(); + + result._code = jsonObject["code"]; + result._rect = Rect.fromJson(jsonObject["rect"]); + result._probability = jsonObject["probability"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "rect": rect?.toJson(), + "code": code, + "probability": probability, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/Validity.dart b/lib/src/results/visual_results/Validity.dart new file mode 100644 index 0000000000..00d3a6dcfc --- /dev/null +++ b/lib/src/results/visual_results/Validity.dart @@ -0,0 +1,35 @@ +// +// Validity.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class Validity { + /// The value's origin source. + ResultType get sourceType => _sourceType; + late ResultType _sourceType; + + /// Overall validity status of all text fields of this particular field. + CheckResult get status => _status; + late CheckResult _status; + + /// Allows you to deserialize object. + static Validity? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Validity(); + + result._sourceType = ResultType.getByValue(jsonObject["sourceType"])!; + result._status = CheckResult.getByValue(jsonObject["status"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"sourceType": sourceType.value, "status": status.value}.clearNulls(); +} diff --git a/lib/src/results/visual_results/Value.dart b/lib/src/results/visual_results/Value.dart new file mode 100644 index 0000000000..389d7bb192 --- /dev/null +++ b/lib/src/results/visual_results/Value.dart @@ -0,0 +1,75 @@ +// +// Value.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class Value { + /// Identifies zone whence data is extracted. + ResultType get sourceType => _sourceType; + late ResultType _sourceType; + + /// A value. + String? get value => _value; + String? _value; + + /// An original value. + String? get originalValue => _originalValue; + String? _originalValue; + + /// An index of the document page whence the textual field is extracted. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Field rectangular area coordinates on the image. + Rect? get boundRect => _boundRect; + Rect? _boundRect; + + /// RFID origin data. Only for the 'RFID' source. + RFIDOrigin? get rfidOrigin => _rfidOrigin; + RFIDOrigin? _rfidOrigin; + + /// List of all symbols for this value. + List get originalSymbols => _originalSymbols; + List _originalSymbols = []; + + /// Textual field recognition probability (0 - 100, %). + int get probability => _probability; + late int _probability; + + /// Allows you to deserialize object. + static Value? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = Value(); + + result._pageIndex = jsonObject["pageIndex"]; + result._sourceType = ResultType.getByValue(jsonObject["sourceType"])!; + result._probability = jsonObject["probability"]; + result._value = jsonObject["value"]; + result._originalValue = jsonObject["originalValue"]; + result._boundRect = Rect.fromJson(jsonObject["boundRect"]); + for (var item in jsonObject["originalSymbols"]) { + result._originalSymbols.addSafe(Symbol.fromJson(item)); + } + result._rfidOrigin = RFIDOrigin.fromJson(jsonObject["rfidOrigin"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "sourceType": sourceType.value, + "value": value, + "originalValue": originalValue, + "pageIndex": pageIndex, + "boundRect": boundRect?.toJson(), + "rfidOrigin": rfidOrigin?.toJson(), + "originalSymbols": originalSymbols.map((e) => e.toJson()).toList(), + "probability": probability, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/field_type.dart b/lib/src/results/visual_results/field_type.dart new file mode 100644 index 0000000000..ce5b133ae0 --- /dev/null +++ b/lib/src/results/visual_results/field_type.dart @@ -0,0 +1,1980 @@ +// +// FieldType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enum contains identifiers that determine the logical type of text data +/// obtained while reading MRZ, document filling fields, and barcodes. +enum FieldType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Document class code. + DOCUMENT_CLASS_CODE(0), + + /// Issuing state code in compliance with 3166-1 standard (ICAO doc 9303). + ISSUING_STATE_CODE(1), + + /// Document number. + DOCUMENT_NUMBER(2), + + /// Expiry date of the document. + DATE_OF_EXPIRY(3), + + /// Issue date of the document. + DATE_OF_ISSUE(4), + + /// Date of birth. + DATE_OF_BIRTH(5), + + /// Place of birth. + PLACE_OF_BIRTH(6), + + /// Personal number. + PERSONAL_NUMBER(7), + + /// Surname. + SURNAME(8), + + /// Given name(s). + GIVEN_NAMES(9), + + /// Mother's name. + MOTHERS_NAME(10), + + /// Nationality. + NATIONALITY(11), + + /// Sex. + SEX(12), + + /// Height. + HEIGHT(13), + + /// Weight. + WEIGHT(14), + + /// Eye color. + EYES_COLOR(15), + + /// Hair color. + HAIR_COLOR(16), + + /// Address. + ADDRESS(17), + + /// Organ donor indicator. + DONOR(18), + + /// Social security number. + SOCIAL_SECURITY_NUMBER(19), + + /// Driving licence classification code. + DL_CLASS(20), + + /// Driving licenсe endorsement code. + DL_ENDORSED(21), + + /// Driving licence restriction code. + DL_RESTRICTION_CODE(22), + + /// Date of 21st birthday. + DL_UNDER_21_DATE(23), + + /// Issuing authority. + AUTHORITY(24), + + /// Surname and given name(s). + SURNAME_AND_GIVEN_NAMES(25), + + /// Nationality code in compliance with ISO3166-1 standard (ICAO doc 9303). + NATIONALITY_CODE(26), + + /// Passport number. + PASSPORT_NUMBER(27), + + /// Invitation number. + INVITATION_NUMBER(28), + + /// Visa identification number. + VISA_ID(29), + + /// Visa class. + VISA_CLASS(30), + + /// Visa subclass. + VISA_SUB_CLASS(31), + + /// Not used. + MRZ_STRING_1(32), + + /// Not used. + MRZ_STRING_2(33), + + /// Not used. + MRZ_STRING_3(34), + + /// MRZ type (ID-1 – 0, ID-2 – 1, ID-3 – 2). + MRZ_TYPE(35), + + /// Optional data. + OPTIONAL_DATA(36), + + /// Document class name. + DOCUMENT_CLASS_NAME(37), + + /// Issuing state name. + ISSUING_STATE_NAME(38), + + /// Place of issue. + PLACE_OF_ISSUE(39), + + /// Checksum for document number. + DOCUMENT_NUMBER_CHECKSUM(40), + + /// Checksum for date of birth. + DATE_OF_BIRTH_CHECKSUM(41), + + /// Checksum for date of expiry. + DATE_OF_EXPIRY_CHECKSUM(42), + + /// Checksum for personal number. + PERSONAL_NUMBER_CHECKSUM(43), + + /// Final checksum (for the whole MRZ). + FINAL_CHECKSUM(44), + + /// Checksum for passport number (for visas). + PASSPORT_NUMBER_CHECKSUM(45), + + /// Checksum for passport number (for visas). + INVITATION_NUMBER_CHECKSUM(46), + + /// Checksum for visa identification number. + VISA_ID_CHECKSUM(47), + + /// Checksum for surname + given name(s). + SURNAME_AND_GIVEN_NAMES_CHECKSUM(48), + + /// Checksum for visa expiry date. + VISA_VALID_UNTIL_CHECKSUM(49), + + /// Other information. + OTHER(50), + + /// MRZ lines. + MRZ_STRINGS(51), + + /// Name suffix. + NAME_SUFFIX(52), + + /// Name prefix. + NAME_PREFIX(53), + + /// Checksum for date of issue. + DATE_OF_ISSUE_CHECKSUM(54), + + /// Check digit for date of issue. + DATE_OF_ISSUE_CHECK_DIGIT(55), + + /// Document series. + DOCUMENT_SERIES(56), + + /// Serial number of registration certificate. + REG_CERT_REG_NUMBER(57), + + /// Vehicle model. + REG_CERT_CAR_MODEL(58), + + /// Vehicle color. + REG_CERT_CAR_COLOR(59), + + /// Vehicle identification number (VIN). + REG_CERT_BODY_NUMBER(60), + + /// Vehicle type. + REG_CERT_CAR_TYPE(61), + + /// Permissible maximum weight. + REG_CERT_MAX_WEIGHT(62), + + /// Vehicle weight. + REG_CERT_WEIGHT(63), + + /// Address (area). + ADDRESS_AREA(64), + + /// Address (state). + ADDRESS_STATE(65), + + /// Address (building number). + ADDRESS_BUILDING(66), + + /// Address (house number). + ADDRESS_HOUSE(67), + + /// Address (flat number). + ADDRESS_FLAT(68), + + /// Place of registration. + PLACE_OF_REGISTRATION(69), + + /// Date of registration. + DATE_OF_REGISTRATION(70), + + /// Resident from (date). + RESIDENT_FROM(71), + + /// Resident until (date). + RESIDENT_UNTIL(72), + + /// Issuing authority code (for the passport of the Russian Federation). + AUTHORITY_CODE(73), + + /// Place of birth (area). + PLACE_OF_BIRTH_AREA(74), + + /// Place of birth (state code). + PLACE_OF_BIRTH_STATE_CODE(75), + + /// Address (street). + ADDRESS_STREET(76), + + /// Address (city). + ADDRESS_CITY(77), + + /// Address (jurisdiction code). + ADDRESS_JURISDICTION_CODE(78), + + /// Address (postal code). + ADDRESS_POSTAL_CODE(79), + + /// Check digit for document number. + DOCUMENT_NUMBER_CHECK_DIGIT(80), + + /// Check digit for date of birth. + DATE_OF_BIRTH_CHECK_DIGIT(81), + + /// Check digit for document expiry date. + DATE_OF_EXPIRY_CHECK_DIGIT(82), + + /// Check digit for personal number. + PERSONAL_NUMBER_CHECK_DIGIT(83), + + /// Final check digit (for the whole MRZ). + FINAL_CHECK_DIGIT(84), + + /// Check digit for passport number (for visas). + PASSPORT_NUMBER_CHECK_DIGIT(85), + + /// Check digit for invitation number (for visas). + INVITATION_NUMBER_CHECK_DIGIT(86), + + /// Check digit for visa number. + VISA_ID_CHECK_DIGIT(87), + + /// Check digit for surname and given name(s). + SURNAME_AND_GIVEN_NAMES_CHECK_DIGIT(88), + + /// Check digit for visa expiry date. + VISA_VALID_UNTIL_CHECK_DIGIT(89), + + /// Permit type. + PERMIT_DL_CLASS(90), + + /// Permit expiry date. + PERMIT_DATE_OF_EXPIRY(91), + + /// Permit identifier. + PERMIT_IDENTIFIER(92), + + /// Permit issue date. + PERMIT_DATE_OF_ISSUE(93), + + /// Driving permit restriction code. + PERMIT_RESTRICTION_CODE(94), + + /// Driving permit endorsement code. + PERMIT_ENDORSED(95), + + /// A line used for document validation in accordance with the database. + ISSUE_TIMESTAMP(96), + + /// Number of duplicates. + NUMBER_OF_DUPLICATES(97), + + /// Medical indicator/code. + MEDICAL_INDICATOR_CODES(98), + + /// Indicator showing that the document holder is a non-resident. + NON_RESIDENT_INDICATOR(99), + + /// Visa type. + VISA_TYPE(100), + + /// The earliest date from which the visa is valid. + VISA_VALID_FROM(101), + + /// The date until which the visa is valid. + VISA_VALID_UNTIL(102), + + /// Duration of stay (in days) granted by the visa. + DURATION_OF_STAY(103), + + /// Number of entries granted by the visa. + NUMBER_OF_ENTRIES(104), + + /// Day in the date. + DAY(105), + + /// Month in the date. + MONTH(106), + + /// Year in the date. + YEAR(107), + + /// Identification number. + UNIQUE_CUSTOMER_IDENTIFIER(108), + + /// Commercial vehicle code. + COMMERCIAL_VEHICLE_CODES(109), + + /// Also known as (date of birth). + AKA_DATE_OF_BIRTH(110), + + /// Also known as (social security number). + AKA_SOCIAL_SECURITY_NUMBER(111), + + /// Also known as (surname). + AKA_SURNAME(112), + + /// Also known as (given names). + AKA_GIVEN_NAMES(113), + + /// Also known as (suffix name). + AKA_NAME_SUFFIX(114), + + /// Also known as (prefix name). + AKA_NAME_PREFIX(115), + + /// Mailing address (street). + MAILING_ADDRESS_STREET(116), + + /// Mailing address (city). + MAILING_ADDRESS_CITY(117), + + /// Mailing address (jurisdiction code). + MAILING_ADDRESS_JURISDICTION_CODE(118), + + /// Mailing address (postal code). + MAILING_ADDRESS_POSTAL_CODE(119), + + /// A number which is used for driving licence validation. + AUDIT_INFORMATION(120), + + /// Race/ethnicity. + INVENTORY_NUMBER(121), + + /// Race/ethnicity. + RACE_ETHNICITY(122), + + /// Jurisdiction vehicle class. + JURISDICTION_VEHICLE_CLASS(123), + + /// Jurisdiction endorsement code. + JURISDICTION_ENDORSEMENT_CODE(124), + + /// Jurisdiction restriction code. + JURISDICTION_RESTRICTION_CODE(125), + + /// Surname and (or) given name(s) at birth. + FAMILY_NAME(126), + + /// Given name(s) (Russian transcription). + GIVEN_NAMES_RUS(127), + + /// Visa ID (Russian transcription). + VISA_ID_RUS(128), + + /// Father’s name/patronymic. + FATHERS_NAME(129), + + /// Father’s name/patronymic (Russian transcription). + FATHERS_NAME_RUS(130), + + /// Surname and given name(s) (Russian transcription). + SURNAME_AND_GIVEN_NAMES_RUS(131), + + /// Place of birth (Russian transcription). + PLACE_OF_BIRTH_RUS(132), + + /// Document issuing authority (Russian transcription). + AUTHORITY_RUS(133), + + /// Numeric issuing state code in compliance with ISO 3166-1 standard. + ISSUING_STATE_CODE_NUMERIC(134), + + /// Numeric nationality code in compliance with ISO 3166-1 standard. + NATIONALITY_CODE_NUMERIC(135), + + /// Engine power. + ENGINE_POWER(136), + + /// Engine capacity. + ENGINE_VOLUME(137), + + /// Chassis number. + CHASSIS_NUMBER(138), + + /// Engine number. + ENGINE_NUMBER(139), + + /// Engine model. + ENGINE_MODEL(140), + + /// Vehicle category. + VEHICLE_CATEGORY(141), + + /// Identity card number. + IDENTITY_CARD_NUMBER(142), + + /// Control number. + CONTROL_NO(143), + + /// Parents' given names. + PARRENTS_GIVEN_NAMES(144), + + /// Second surname. + SECOND_SURNAME(145), + + /// Second name. + MIDDLE_NAME(146), + + /// Vehicle identification number. + REG_CERT_VIN(147), + + /// Check digit for vehicle identification number. + REG_CERT_VIN_CHECK_DIGIT(148), + + /// Checksum for vehicle identification number. + REG_CERT_VIN_CHECKSUM(149), + + /// Check digit for the first MRZ line. + LINE_1_CHECK_DIGIT(150), + + /// Check digit for the second MRZ line. + LINE_2_CHECK_DIGIT(151), + + /// Check digit for the third MRZ line. + LINE_3_CHECK_DIGIT(152), + + /// Checksum for the first MRZ line. + LINE_1_CHECKSUM(153), + + /// Checksum for the second MRZ line. + LINE_2_CHECKSUM(154), + + /// Checksum for the third MRZ line. + LINE_3_CHECKSUM(155), + + /// Check digit for vehicle registration number. + REG_CERT_REG_NUMBER_CHECK_DIGIT(156), + + /// Check sum for vehicle registration number. + REG_CERT_REG_NUMBER_CHECKSUM(157), + + /// Vehicle code according to ITS (IntelligentTransportation Systems). + REG_CERT_VEHICLE_ITS_CODE(158), + + /// Access number for RFID chip. + CARD_ACCESS_NUMBER(159), + + /// Marital status. + MARITAL_STATUS(160), + + /// Company name. + COMPANY_NAME(161), + + /// Special notes. + SPECIAL_NOTES(162), + + /// Surname of spouse. + SURNAME_OF_SPOSE(163), + + /// Number for checking document status. + TRACKING_NUMBER(164), + + /// Booklet number. + BOOKLET_NUMBER(165), + + /// Children. + CHILDREN(166), + + /// Copy number. + COPY(167), + + /// Serial number. + SERIAL_NUMBER(168), + + /// Dossier number. + DOSSIER_NUMBER(169), + + /// Also known as (surname and given names). + AKA_SURNAME_AND_GIVEN_NAMES(170), + + /// Territorial validity. + TERRITORIAL_VALIDITY(171), + + /// MRZ with correct checksums. + MRZ_STRINGS_WITH_CORRECT_CHECK_SUMS(172), + + /// Commercial driving license restriction code. + DL_CDL_RESTRICTION_CODE(173), + + /// Date of 18th birthday. + DL_UNDER_18_DATE(174), + + /// Date of record creation. + DL_RECORD_CREATED(175), + + /// Date of duplicate creation. + DL_DUPLICATE_DATE(176), + + /// Type of issued driving license. + DL_ISS_TYPE(177), + + /// Military card number. + MILITARY_BOOK_NUMBER(178), + + /// Destination. + DESTINATION(179), + + /// Blood group. + BLOOD_GROUP(180), + + /// Sequence number. + SEQUENCE_NUMBER(181), + + /// Car body type. + REG_CERT_BODY_TYPE(182), + + /// Car make. + REG_CERT_CAR_MARK(183), + + /// Transaction number. + TRANSACTION_NUMBER(184), + + /// Age. + AGE(185), + + /// Folio number. + FOLIO_NUMBER(186), + + /// Voter's identification number. + VOTER_KEY(187), + + /// Address (municipality). + ADDRESS_MUNICIPALITY(188), + + /// Address (location). + ADDRESS_LOCATION(189), + + /// Section/sector. + SECTION(190), + + /// OCR number. + OCR_NUMBER(191), + + /// Federal elections. + FEDERAL_ELECTIONS(192), + + /// Unique number. + REFERENCE_NUMBER(193), + + /// Checksum for optional data. + OPTIONAL_DATA_CHECKSUM(194), + + /// Check digit for optional data. + OPTIONAL_DATA_CHECK_DIGIT(195), + + /// Visa number. + VISA_NUMBER(196), + + /// Checksum for visa. + VISA_NUMBER_CHECKSUM(197), + + /// Checkdigit for visa. + VISA_NUMBER_CHECK_DIGIT(198), + + /// Voter. + VOTER(199), + + /// Type/number of the previous document. + PREVIOUS_TYPE(200), + + /// Reserved for internal use. + FIELD_FROM_MRZ(220), + + /// Reserved for internal use. + CURRENT_DATE(221), + + /// Status expiry date. + STATUS_DATE_OF_EXPIRY(251), + + /// Banknote number. + BANKNOTE_NUMBER(252), + + /// Customer Service Centre code. + CSC_CODE(253), + + /// Pseudonym. + ARTISTIC_NAME(254), + + /// Academic title. + ACADEMIC_TITLE(255), + + /// Address (country). + ADDRESS_COUNTRY(256), + + /// Address (zip code). + ADDRESS_ZIPCODE(257), + + /// Data on permanent residence permit 1(eID field). + E_ID_RESIDENCE_PERMIT_1(258), + + /// Data on permanent residence permit 2(eID field). + E_ID_RESIDENCE_PERMIT_2(259), + + /// Place of birth: street (eID field). + E_ID_PLACE_OF_BIRTH_STREET(260), + + /// Place of birth: city (eID field). + E_ID_PLACE_OF_BIRTH_CITY(261), + + /// Place of birth: state (eID field). + E_ID_PLACE_OF_BIRTH_STATE(262), + + /// Place of birth: country (eID field). + E_ID_PLACE_OF_BIRTH_COUNTRY(263), + + /// Place of birth: zip code (eID field). + E_ID_PLACE_OF_BIRTH_ZIPCODE(264), + + /// Commercial driving license class. + CDL_CLASS(265), + + /// Date of 19th birthday. + DL_UNDER_19_DATE(266), + + /// Weight (pounds). + WEIGHT_POUNDS(267), + + /// Indicator of document limited duration. + LIMITED_DURATION_DOCUMENT_INDICATOR(268), + + /// Endorsement expiry date. + ENDORSEMENT_EXPIRATION_DATE(269), + + /// Date of revision. + REVISION_DATE(270), + + /// Type of compliance. + COMPLIANCE_TYPE(271), + + /// Family name truncation. + FAMILY_NAME_TRUNCATION(272), + + /// First name truncation. + FIRST_NAME_TRUNCATION(273), + + /// Middle name truncation. + MIDDLE_NAME_TRUNCATION(274), + + /// Examination date. + EXAM_DATE(275), + + /// Organization. + ORGANIZATION(276), + + /// Department. + DEPARTMENT(277), + + /// Pay grade. + PAY_GRADE(278), + + /// Rank/status/title. + RANK(279), + + /// Number that relates to benefit eligibility. + BENEFITS_NUMBER(280), + + /// Sponsor's service. + SPONSOR_SERVICE(281), + + /// Sponsor's status. + SPONSOR_STATUS(282), + + /// Sponsor. + SPONSOR(283), + + /// Relationship. + RELATIONSHIP(284), + + /// Alien registration number issued by the U.S. + /// Citizenship and Immigration Service. + USCIS(285), + + /// Category. + CATEGORY(286), + + /// Conditions. + CONDITIONS(287), + + /// Identifier. + IDENTIFIER(288), + + /// Configuration. + CONFIGURATION(289), + + /// Discretionary data. + DISCRETIONARY_DATA(290), + + /// Optional data from MRZ Line 1. + LINE_1_OPTIONAL_DATA(291), + + /// Optional data from MRZ Line 2. + LINE_2_OPTIONAL_DATA(292), + + /// Optional data from MRZ Line 3. + LINE_3_OPTIONAL_DATA(293), + + /// Equivalence value (security code). + EQV_CODE(294), + + /// ALT сode. + ALT_CODE(295), + + /// Binary сode. + BINARY_CODE(296), + + /// Pseudo-code. + PSEUDO_CODE(297), + + /// Fee. + FEE(298), + + /// Stamp number. + STAMP_NUMBER(299), + + /// Parameters of biometric data protection. + SBH_SECURITYOPTIONS(300), + + /// Parameters of biometric data integrity. + SBH_INTEGRITYOPTIONS(301), + + /// Date of creation of biometric data record. + DATE_OF_CREATION(302), + + /// Term of validity of biometric data record. + VALIDITY_PERIOD(303), + + /// Version of header of biometric data format owner. + PATRON_HEADER_VERSION(304), + + /// Type of biometric data record. + BDB_TYPE(305), + + /// Type of biometric data. + BIOMETRIC_TYPE(306), + + /// Subtype of biometric data. + BIOMETRIC_SUBTYPE(307), + + /// Identifier of biometric data. + BIOMETRIC_PRODUCTID(308), + + /// Identifier of biometric data format owner. + BIOMETRIC_FORMAT_OWNER(309), + + /// Biometric data format. + BIOMETRIC_FORMAT_TYPE(310), + + /// DO's phone number. + PHONE(311), + + /// DO's profession. + PROFESSION(312), + + /// DO's title. + TITLE(313), + + /// DO's personal summary data. + PERSONAL_SUMMARY(314), + + /// Other valid identifier. + OTHER_VALID_ID(315), + + /// Custody information. + CUSTODY_INFO(316), + + /// Other name. + OTHER_NAME(317), + + /// Observations. + OBSERVATIONS(318), + + /// Tax information. + TAX(319), + + /// Date of document personalization. + DATE_OF_PERSONALIZATION(320), + + /// Serial number of personalization. + PERSONALIZATION_SN(321), + + /// Other person's name. + OTHERPERSON_NAME(322), + + /// Date of record entry on persons to notify in case of emergency. + PERSONTONOTIFY_DATE_OF_RECORD(323), + + /// Name of person to notify in case of emergency. + PERSONTONOTIFY_NAME(324), + + /// Phone number of person to notify in case of emergency. + PERSONTONOTIFY_PHONE(325), + + /// Address of person to notify in case of emergency. + PERSONTONOTIFY_ADDRESS(326), + + /// Textual information about the DS-certificate issuer. + DS_CERTIFICATE_ISSUER(327), + + /// Textual information about the document issuer. + DS_CERTIFICATE_SUBJECT(328), + + /// Start date of the DS-certificate validity. + DS_CERTIFICATE_VALIDFROM(329), + + /// Expiration date of the DS-certificate. + DS_CERTIFICATE_VALIDTO(330), + + /// Vehicle category/restrictions/conditions from + /// DG1 data group of eDL application. + VRC_DATAOBJECT_ENTRY(331), + + /// Type approval number. + TYPE_APPROVAL_NUMBER(332), + + /// Administrative number. + ADMINISTRATIVE_NUMBER(333), + + /// Document discriminator. + DOCUMENT_DISCRIMINATOR(334), + + /// Data discriminator. + DATA_DISCRIMINATOR(335), + + /// ISO issuer ID number. + ISO_ISSUER_ID_NUMBER(336), + + DTC_VERSION(337), + + DTC_ID(338), + + DTC_DATE_OF_EXPIRY(339), + + /// Registration number issued by GardaNational Immigration Bureau. + GNIB_NUMBER(340), + + /// Department number. + DEPT_NUMBER(341), + + /// Telegraph code. + TELEX_CODE(342), + + /// Allergies. + ALLERGIES(343), + + /// Sp. code. + SP_CODE(344), + + /// Code of restriction imposed by court. + COURT_CODE(345), + + /// County code. + CTY(346), + + /// Sponsor's social security number. + SPONSOR_SSN(347), + + /// Department of Defense identification number. + DO_D_NUMBER(348), + + /// Expiry date of Motorcycle status. + MC_NOVICE_DATE(349), + + /// DUF Number (a number that is assigned to everyone who applies + /// for residence inNorway). + DUF_NUMBER(350), + + /// Code of Philippine Land TransportationOffice Agency. + AGY(351), + + /// Passenger name record (reservation code). + PNR_CODE(352), + + /// Code of the airport of departure. + FROM_AIRPORT_CODE(353), + + /// Code of the airport of arrival. + TO_AIRPORT_CODE(354), + + /// Flight number. + FLIGHT_NUMBER(355), + + /// Date of flight. + DATE_OF_FLIGHT(356), + + /// Seat number. + SEAT_NUMBER(357), + + /// Date of boarding pass issue. + DATE_OF_ISSUE_BOARDING_PASS(358), + + /// Expiration date of Concealed CarryWeapon Permit. + CCW_UNTIL(359), + + /// Checksum for reference number. + REFERENCE_NUMBER_CHECKSUM(360), + + /// Check digit for reference number. + REFERENCE_NUMBER_CHECK_DIGIT(361), + + /// Room number. + ROOM_NUMBER(362), + + /// Religion. + RELIGION(363), + + /// Months to expire. + REMAINDER_TERM(364), + + /// Electronic ticket indicator. + ELECTRONIC_TICKET_INDICATOR(365), + + /// Compartment сode. + COMPARTMENT_CODE(366), + + /// Check-in sequence number on a boarding pass. + CHECK_IN_SEQUENCE_NUMBER(367), + + /// Code of the airline which issued the boarding pass. + AIRLINE_DESIGNATOR_OF_BOARDING_PASS_ISSUER(368), + + /// Numeric airline code. + AIRLINE_NUMERIC_CODE(369), + + /// Ticket number. + TICKET_NUMBER(370), + + /// Frequent flyer indicator. + FREQUENT_FLYER_AIRLINE_DESIGNATOR(371), + + /// Frequent flyer number. + FREQUENT_FLYER_NUMBER(372), + + /// Free baggage allowance. + FREE_BAGGAGE_ALLOWANCE(373), + + /// Codec for PDF417. + PDF_417_CODEC(374), + + /// Checksum for identity card number. + IDENTITY_CARD_NUMBER_CHECKSUM(375), + + /// Check digit for identity card number. + IDENTITY_CARD_NUMBER_CHECK_DIGIT(376), + + /// Veteran. + VETERAN(377), + + /// DL class code A1 valid from. + DL_CLASS_CODE_A_1_FROM(378), + + /// DL class code A1 valid to. + DL_CLASS_CODE_A_1_TO(379), + + /// DL class code A1 valid notes. + DL_CLASS_CODE_A_1_NOTES(380), + + /// DL class code A1 valid from. + DL_CLASS_CODE_A_FROM(381), + + /// DL class code A1 valid to. + DL_CLASS_CODE_A_TO(382), + + /// DL class code A1 valid notes. + DL_CLASS_CODE_A_NOTES(383), + + /// DL class code B valid from. + DL_CLASS_CODE_B_FROM(384), + + /// DL class code B valid to. + DL_CLASS_CODE_B_TO(385), + + /// DL class code B valid notes. + DL_CLASS_CODE_B_NOTES(386), + + /// DL class code C1 valid from. + DL_CLASS_CODE_C_1_FROM(387), + + /// DL class code C1 valid to. + DL_CLASS_CODE_C_1_TO(388), + + /// DL class code C1 valid notes. + DL_CLASS_CODE_C_1_NOTES(389), + + /// DL class code C valid from. + DL_CLASS_CODE_C_FROM(390), + + /// DL class code C valid to. + DL_CLASS_CODE_C_TO(391), + + /// DL class code C valid notes. + DL_CLASS_CODE_C_NOTES(392), + + /// DL class code D1 valid from. + DL_CLASS_CODE_D_1_FROM(393), + + /// DL class code D1 valid to. + DL_CLASS_CODE_D_1_TO(394), + + /// DL class code D1 valid notes. + DL_CLASS_CODE_D_1_NOTES(395), + + /// DL class code D valid from. + DL_CLASS_CODE_D_FROM(396), + + /// DL class code D valid to. + DL_CLASS_CODE_D_TO(397), + + /// DL class code D valid notes. + DL_CLASS_CODE_D_NOTES(398), + + /// DL class code BE valid from. + DL_CLASS_CODE_BE_FROM(399), + + /// DL class code BE valid to. + DL_CLASS_CODE_BE_TO(400), + + /// DL class code BE valid notes. + DL_CLASS_CODE_BE_NOTES(401), + + /// DL class code C1E valid from. + DL_CLASS_CODE_C_1_E_FROM(402), + + /// DL class code C1E valid to. + DL_CLASS_CODE_C_1_E_TO(403), + + /// DL class code C1E valid notes. + DL_CLASS_CODE_C_1_E_NOTES(404), + + /// DL class code CE valid from. + DL_CLASS_CODE_CE_FROM(405), + + /// DL class code CE valid to. + DL_CLASS_CODE_CE_TO(406), + + /// DL class code CE valid notes. + DL_CLASS_CODE_CE_NOTES(407), + + /// DL class code D1E valid from. + DL_CLASS_CODE_D_1_E_FROM(408), + + /// DL class code D1E valid to. + DL_CLASS_CODE_D_1_E_TO(409), + + /// DL class code D1E valid notes. + DL_CLASS_CODE_D_1_E_NOTES(410), + + /// DL class code DE valid from. + DL_CLASS_CODE_DE_FROM(411), + + /// DL class code DE valid to. + DL_CLASS_CODE_DE_TO(412), + + /// DL class code DE valid notes. + DL_CLASS_CODE_DE_NOTES(413), + + /// DL class code M valid from. + DL_CLASS_CODE_M_FROM(414), + + /// DL class code M valid to. + DL_CLASS_CODE_M_TO(415), + + /// DL class code M valid notes. + DL_CLASS_CODE_M_NOTES(416), + + /// DL class code L valid from. + DL_CLASS_CODE_L_FROM(417), + + /// DL class code L valid to. + DL_CLASS_CODE_L_TO(418), + + /// DL class code L valid notes. + DL_CLASS_CODE_L_NOTES(419), + + /// DL class code T valid from. + DL_CLASS_CODE_T_FROM(420), + + /// DL class code T valid to. + DL_CLASS_CODE_T_TO(421), + + /// DL class code T valid notes. + DL_CLASS_CODE_T_NOTES(422), + + /// DL class code AM valid from. + DL_CLASS_CODE_AM_FROM(423), + + /// DL class code AM valid to. + DL_CLASS_CODE_AM_TO(424), + + /// DL class code AM valid notes. + DL_CLASS_CODE_AM_NOTES(425), + + /// DL class code A2 valid from. + DL_CLASS_CODE_A_2_FROM(426), + + /// DL class code A2 valid to. + DL_CLASS_CODE_A_2_TO(427), + + /// DL class code A2 valid notes. + DL_CLASS_CODE_A_2_NOTES(428), + + /// DL class code B1 valid from. + DL_CLASS_CODE_B_1_FROM(429), + + /// DL class code B1 valid to. + DL_CLASS_CODE_B_1_TO(430), + + /// DL class code B1 valid notes. + DL_CLASS_CODE_B_1_NOTES(431), + + /// Surname at birth. + SURNAME_AT_BIRTH(432), + + /// Civil status. + CIVIL_STATUS(433), + + /// Number of seats. + NUMBER_OF_SEATS(434), + + /// Number of standing places. + NUMBER_OF_STANDING_PLACES(435), + + /// Maximum speed. + MAX_SPEED(436), + + /// Fuel type. + FUEL_TYPE(437), + + /// Vehicle environmental type. + EC_ENVIRONMENTAL_TYPE(438), + + /// Power–to–weight ratio. + POWER_WEIGHT_RATIO(439), + + /// Maximum weight of the trailer without brakes. + MAX_MASS_OF_TRAILER_BRAKED(440), + + /// Maximum weight of the trailer without brakes. + MAX_MASS_OF_TRAILER_UNBRAKED(441), + + /// Transmission type. + TRANSMISSION_TYPE(442), + + /// Trailer hitch. + TRAILER_HITCH(443), + + /// Accompanying person. + ACCOMPANIED_BY(444), + + /// Police district. + POLICE_DISTRICT(445), + + /// Date of first issue. + FIRST_ISSUE_DATE(446), + + /// Payload capacity. + PAYLOAD_CAPACITY(447), + + /// Number of axels. + NUMBER_OF_AXELS(448), + + /// Permissible axle load. + PERMISSIBLE_AXLE_LOAD(449), + + /// Precinct. + PRECINCT(450), + + /// Invited by. + INVITED_BY(451), + + /// Purpose of entry. + PURPOSE_OF_ENTRY(452), + + /// Skin color. + SKIN_COLOR(453), + + /// Complexion. + COMPLEXION(454), + + /// Airport of departure. + AIRPORT_FROM(455), + + /// Airport of arrival. + AIRPORT_TO(456), + + /// Airline name. + AIRLINE_NAME(457), + + /// A loyalty program offered by the airline to its customers who fly frequently. + AIRLINE_NAME_FREQUENT_FLYER(458), + + /// Licenсe number. + LICENSE_NUMBER(459), + + /// In tanks. + IN_TANKS(460), + + /// Except in tanks. + EXEPT_IN_TANKS(461), + + /// Passenger using the Fast Track service in the airport. + FAST_TRACK(462), + + /// Owner. + OWNER(463), + + /// MRZ strings from ICAO RFID. + MRZ_STRINGS_ICAO_RFID(464), + + /// The number of times a card with this number has been issued. + NUMBER_OF_CARD_ISSUANCE(465), + + /// Number of card issuance checksum. + NUMBER_OF_CARD_ISSUANCE_CHECKSUM(466), + + /// Number of card issuance check digit. + NUMBER_OF_CARD_ISSUANCE_CHECK_DIGIT(467), + + /// Century of birth. + CENTURY_DATE_OF_BIRTH(468), + + /// DL class code A3 valid from. + DL_CLASSCODE_A3_FROM(469), + + /// DL class code A3 valid to. + DL_CLASSCODE_A3_TO(470), + + /// DL class code A3 valid notes. + DL_CLASSCODE_A3_NOTES(471), + + /// DL class code C2 valid from. + DL_CLASSCODE_C2_FROM(472), + + /// DL class code C2 valid to. + DL_CLASSCODE_C2_TO(473), + + /// DL class code C2 valid notes. + DL_CLASSCODE_C2_NOTES(474), + + /// DL class code B2 valid from. + DL_CLASSCODE_B2_FROM(475), + + /// DL class code B2 valid to. + DL_CLASSCODE_B2_TO(476), + + /// DL class code B2 valid notes. + DL_CLASSCODE_B2_NOTES(477), + + /// DL class code D2 valid from. + DL_CLASSCODE_D2_FROM(478), + + /// DL class code B2 valid to. + DL_CLASSCODE_D2_TO(479), + + /// DL class code B2 valid notes. + DL_CLASSCODE_D2_NOTES(480), + + /// DL class code B2E valid from. + DL_CLASSCODE_B2E_FROM(481), + + /// DL class code B2E valid to. + DL_CLASSCODE_B2E_TO(482), + + /// DL class code B2E valid notes. + DL_CLASSCODE_B2E_NOTES(483), + + /// DL class code G valid from. + DL_CLASSCODE_G_FROM(484), + + /// DL class code G valid to. + DL_CLASSCODE_G_TO(485), + + /// DL class code G valid notes. + DL_CLASSCODE_G_NOTES(486), + + /// DL class code J valid from. + DL_CLASSCODE_J_FROM(487), + + /// DL class code J valid to. + DL_CLASSCODE_J_TO(488), + + /// DL class code J valid notes. + DL_CLASSCODE_J_NOTES(489), + + /// DL class code LC valid from. + DL_CLASSCODE_LC_FROM(490), + + /// DL class code LC valid to. + DL_CLASSCODE_LC_TO(491), + + /// DL class code LC valid notes. + DLC_LASSCODE_LC_NOTES(492), + + /// Bank card number. + BANKCARDNUMBER(493), + + /// Bank card validity. + BANKCARDVALIDTHRU(494), + + /// Tax number. + TAX_NUMBER(495), + + /// Health insurance number. + HEALTH_NUMBER(496), + + /// Grandfather's name. + GRANDFATHERNAME(497), + + /// Selectee indicator. + SELECTEE_INDICATOR(498), + + /// Mother's surname. + MOTHER_SURNAME(499), + + /// Mother's given name. + MOTHER_GIVENNAME(500), + + /// Father's surname. + FATHER_SURNAME(501), + + /// Father's given name. + FATHER_GIVENNAME(502), + + /// Mother's date of birth. + MOTHER_DATEOFBIRTH(503), + + /// Father's date of birth. + FATHER_DATEOFBIRTH(504), + + /// Mother's personal number. + MOTHER_PERSONALNUMBER(505), + + /// Father's personal number. + FATHER_PERSONALNUMBER(506), + + /// Mother's place of birth. + MOTHER_PLACEOFBIRTH(507), + + /// Father's place of birth. + FATHER_PLACEOFBIRTH(508), + + /// Mother's country of birth. + MOTHER_COUNTRYOFBIRTH(509), + + /// Father's country of birth. + FATHER_COUNTRYOFBIRTH(510), + + /// Date of first renewal. + DATE_FIRST_RENEWAL(511), + + /// Date of second renewal. + DATE_SECOND_RENEWAL(512), + + /// Place of examination. + PLACE_OF_EXAMINATION(513), + + /// Application number. + APPLICATION_NUMBER(514), + + /// Voucher number. + VOUCHER_NUMBER(515), + + /// Authorization number. + AUTHORIZATION_NUMBER(516), + + /// Faculty. + FACULTY(517), + + /// Form of education. + FORM_OF_EDUCATION(518), + + /// DNI number. + DNI_NUMBER(519), + + /// Retirement number. + RETIREMENT_NUMBER(520), + + /// Professional Id number. + PROFESSIONAL_ID_NUMBER(521), + + /// Age at issue. + AGE_AT_ISSUE(522), + + /// Years since issue. + YEARS_SINCE_ISSUE(523), + + /// DL class code BTP valid from. + DLCLASSCODE_BTP_FROM(524), + + /// DL class code BTP valid notes. + DLCLASSCODE_BTP_NOTES(525), + + /// DL class code BTP valid to. + DLCLASSCODE_BTP_TO(526), + + /// DL class code C3 valid from. + DLCLASSCODE_C3_FROM(527), + + /// DL class code C3 valid notes. + DLCLASSCODE_C3_NOTES(528), + + /// DL class code C3 valid to. + DLCLASSCODE_C3_TO(529), + + /// DL class code E valid from. + DLCLASSCODE_E_FROM(530), + + /// DL class code E valid notes. + DLCLASSCODE_E_NOTES(531), + + /// DL class code E valid to. + DLCLASSCODE_E_TO(532), + + /// DL class code F valid from. + DLCLASSCODE_F_FROM(533), + + /// DL class code F valid notes. + DLCLASSCODE_F_NOTES(534), + + /// DL class code F valid to. + DLCLASSCODE_F_TO(535), + + /// DL class code FA valid from. + DLCLASSCODE_FA_FROM(536), + + /// DL class code FA valid notes. + DLCLASSCODE_FA_NOTES(537), + + /// DL class code FA valid to. + DLCLASSCODE_FA_TO(538), + + /// DL class code FA1 valid from. + DLCLASSCODE_FA1_FROM(539), + + /// DL class code FA1 valid notes. + DLCLASSCODE_FA1_NOTES(540), + + /// DL class code FA1 valid to. + DLCLASSCODE_FA1_TO(541), + + /// DL class code FB valid from. + DLCLASSCODE_FB_FROM(542), + + /// DL class code FB valid notes. + DLCLASSCODE_FB_NOTES(543), + + /// DL class code FB valid to. + DLCLASSCODE_FB_TO(544), + + /// DL class code G1 valid from. + DLCLASSCODE_G1_FROM(545), + + /// DL class code G1 valid notes. + DLCLASSCODE_G1_NOTES(546), + + /// DL class code G1 valid to. + DLCLASSCODE_G1_TO(547), + + /// DL class code H valid from. + DLCLASSCODE_H_FROM(548), + + /// DL class code H valid notes. + DLCLASSCODE_H_NOTES(549), + + /// DL class code H valid to. + DLCLASSCODE_H_TO(550), + + /// DL class code I valid from. + DLCLASSCODE_I_FROM(551), + + /// DL class code I valid notes. + DLCLASSCODE_I_NOTES(552), + + /// DL class code I valid to. + DLCLASSCODE_I_TO(553), + + /// DL class code K valid from. + DLCLASSCODE_K_FROM(554), + + /// DL class code K valid notes. + DLCLASSCODE_K_NOTES(555), + + /// DL class code K valid to. + DLCLASSCODE_K_TO(556), + + /// DL class code LK valid from. + DLCLASSCODE_LK_FROM(557), + + /// DL class code LK valid notes. + DLCLASSCODE_LK_NOTES(558), + + /// DL class code LK valid to. + DLCLASSCODE_LK_TO(559), + + /// DL class code N valid from. + DLCLASSCODE_N_FROM(560), + + /// DL class code N valid notes. + DLCLASSCODE_N_NOTES(561), + + /// DL class code N valid to. + DLCLASSCODE_N_TO(562), + + /// DL class code S valid from. + DLCLASSCODE_S_FROM(563), + + /// DL class code S valid notes. + DLCLASSCODE_S_NOTES(564), + + /// DL class code S valid to. + DLCLASSCODE_S_TO(565), + + /// DL class code TB valid from. + DLCLASSCODE_TB_FROM(566), + + /// DL class code TB valid notes. + DLCLASSCODE_TB_NOTES(567), + + /// DL class code TB valid to. + DLCLASSCODE_TB_TO(568), + + /// DL class code TM valid from. + DLCLASSCODE_TM_FROM(569), + + /// DL class code TM valid notes. + DLCLASSCODE_TM_NOTES(570), + + /// DL class code TM valid to. + DLCLASSCODE_TM_TO(571), + + /// DL class code TR valid from. + DLCLASSCODE_TR_FROM(572), + + /// DL class code TR valid notes. + DLCLASSCODE_TR_NOTES(573), + + /// DL class code TR valid to. + DLCLASSCODE_TR_TO(574), + + /// DL class code TV valid from. + DLCLASSCODE_TV_FROM(575), + + /// DL class code TV valid notes. + DLCLASSCODE_TV_NOTES(576), + + /// DL class code TV valid to. + DLCLASSCODE_TV_TO(577), + + /// DL class code V valid from. + DLCLASSCODE_V_FROM(578), + + /// DL class code V valid notes. + DLCLASSCODE_V_NOTES(579), + + /// DL class code V valid to. + DLCLASSCODE_V_TO(580), + + /// DL class code W valid from. + DLCLASSCODE_W_FROM(581), + + /// DL class code W valid notes. + DLCLASSCODE_W_NOTES(582), + + /// DL class code W valid to. + DLCLASSCODE_W_TO(583), + + /// Uniform Resource Locator. + URL(584), + + /// Caliber. + CALIBER(585), + + /// Model. + MODEL(586), + + /// Make. + MAKE(587), + + /// Number of cylinders. + NUMBER_OF_CYLINDERS(588), + + /// Surname of husband after registration. + SURNAME_OF_HUSBAND_AFTER_REGISTRATION(589), + + /// Surname of wife after registration. + SURNAME_OF_WIFE_AFTER_REGISTRATION(590), + + /// Wife's date of birth. + DATE_OF_BIRTH_OF_WIFE(591), + + /// Husband's date of birth. + DATE_OF_BIRTH_OF_HUSBAND(592), + + /// Citizenship of the first person. + CITIZENSHIP_OF_FIRST_PERSON(593), + + /// Citizenship of the second person. + CITIZENSHIP_OF_SECOND_PERSON(594), + + /// Card Security Code. + CVV(595), + + /// Date of insurance expiry. + DATE_OF_INSURANCE_EXPIRY(596), + + /// Mortgage by. + MORTGAGE_BY(597), + + /// Old document number. + OLD_DOCUMENT_NUMBER(598), + + /// Old date of issue. + OLD_DATE_OF_ISSUE(599), + + /// Old place of issue. + OLD_PLACE_OF_ISSUE(600), + + /// DL category LR valid from. + DLCLASSCODE_LR_FROM(601), + + /// DL category LR valid to. + DLCLASSCODE_LR_TO(602), + + /// DL category LR valid notes. + DLCLASSCODE_LR_NOTES(603), + + /// DL category MR valid from. + DLCLASSCODE_MR_FROM(604), + + /// DL category MR valid to. + DLCLASSCODE_MR_TO(605), + + /// DL category MR valid notes. + DLCLASSCODE_MR_NOTES(606), + + /// DL category HR valid from. + DLCLASSCODE_HR_FROM(607), + + /// DL category HR valid to. + DLCLASSCODE_HR_TO(608), + + /// DL category HR valid notes. + DLCLASSCODE_HR_NOTES(609), + + /// DL category HC valid from. + DLCLASSCODE_HC_FROM(610), + + /// DL category HC valid to. + DLCLASSCODE_HC_TO(611), + + /// DL category HC valid notes. + DLCLASSCODE_HC_NOTES(612), + + /// DL category MC valid from. + DLCLASSCODE_MC_FROM(613), + + /// DL category MC valid to. + DLCLASSCODE_MC_TO(614), + + /// DL category MC valid notes. + DLCLASSCODE_MC_NOTES(615), + + /// DL category RE valid from. + DLCLASSCODE_RE_FROM(616), + + /// DL category RE valid to. + DLCLASSCODE_RE_TO(617), + + /// DL category RE valid notes. + DLCLASSCODE_RE_NOTES(618), + + /// DL category R valid from. + DLCLASSCODE_R_FROM(619), + + /// DL category R valid to. + DLCLASSCODE_R_TO(620), + + /// DL category R valid notes. + DLCLASSCODE_R_NOTES(621), + + /// DL category CA valid from. + DLCLASSCODE_CA_FROM(622), + + /// DL category CA valid to. + DLCLASSCODE_CA_TO(623), + + /// DL category CA valid notes. + DLCLASSCODE_CA_NOTES(624), + + /// Citizenship status. + CITIZENSHIP_STATUS(625), + + /// Start date of military service. + MILITARY_SERVICE_FROM(626), + + /// End date of military service. + MILITARY_SERVICE_TO(627), + + /// DL category NT valid notes. + DLCLASSCODE_NT_FROM(628), + + /// DL category NT valid to. + DLCLASSCODE_NT_TO(629), + + /// DL category NT valid notes. + DLCLASSCODE_NT_NOTES(630), + + /// DL category TN valid from. + DLCLASSCODE_TN_FROM(631), + + /// DL category TN valid to. + DLCLASSCODE_TN_TO(632), + + /// DL category TN valid notes. + DLCLASSCODE_TN_NOTES(633), + + /// DL category D3 valid from. + DLCLASSCODE_D3_FROM(634), + + /// DL category D3 valid to. + DLCLASSCODE_D3_TO(635), + + /// DL category D3 valid notes. + DLCLASSCODE_D3_NOTES(636), + + /// Alternative date of expiry. + ALT_DATE_OF_EXPIRY(637), + + /// DL category CD valid from. + DLCLASSCODE_CD_FROM(638), + + /// DL category CD valid to. + DLCLASSCODE_CD_TO(639), + + /// DL category CD valid notes. + DLCLASSCODE_CD_NOTES(640), + + /// End date of payment period. + PAYMENT_PERIOD_TO(643), + + /// Start date of payment period. + PAYMENT_PERIOD_FROM(642), + + /// Issuer identification number (IIN). + ISSUER_IDENTIFICATION_NUMBER(641), + + /// Vaccination certificate identifier. + VACCINATION_CERTIFICATE_IDENTIFIER(644), + + /// First name. + FIRST_NAME(645), + + /// Date of arrival. + DATE_OF_ARRIVAL(646), + + /// Second name. + SECOND_NAME(647), + + /// Third name. + THIRD_NAME(648), + + /// Fourth name. + FOURTH_NAME(649), + + /// Last name. + LAST_NAME(650), + + /// DL class code RM valid from. + DLCLASSCODE_RM_FROM(651), + + /// DL class code RM notes. + DLCLASSCODE_RM_NOTES(652), + + /// DL class code RM valid to. + DLCLASSCODE_RM_TO(653), + + /// DL class code PW valid from. + DLCLASSCODE_PW_FROM(654), + + /// DL class code PW notes. + DLCLASSCODE_PW_NOTES(655), + + /// DL class code PW valid to. + DLCLASSCODE_PW_TO(656), + + DLCLASSCODE_EB_FROM(657), + + DLCLASSCODE_EB_NOTES(658), + + DLCLASSCODE_EB_TO(659), + + DLCLASSCODE_EC_FROM(660), + + DLCLASSCODE_EC_NOTES(661), + + DLCLASSCODE_EC_TO(662), + + DLCLASSCODE_EC1_FROM(663), + + DLCLASSCODE_EC1_NOTES(664), + + DLCLASSCODE_EC1_TO(665), + + PLACE_OF_BIRTH_CITY(666), + + YEAR_OF_BIRTH(667), + + YEAR_OF_EXPIRY(668), + + GRANDFATHER_NAME_MATERNAL(669), + + FIRST_SURNAME(670), + + MONTH_OF_BIRTH(671), + + ADDRESS_FLOOR_NUMBER(672), + + ADDRESS_ENTRANCE(673), + + ADDRESS_BLOCK_NUMBER(674), + + ADDRESS_STREET_NUMBER(675), + + ADDRESS_STREET_TYPE(676), + + ADDRESS_CITY_SECTOR(677), + + ADDRESS_COUNTY_TYPE(678), + + ADDRESS_CITY_TYPE(679), + + ADDRESS_BUILDING_TYPE(680), + + /// Date of retirement. + DATE_OF_RETIREMENT(681), + + /// Document status. + DOCUMENT_STATUS(682), + + /// Signature. + SIGNATURE(683), + + /// Unique certificate identifier. + UNIQUE_CERTIFICATE_IDENTIFIER(684), + + /// Email. + EMAIL(685), + + /// Date of specimen collection. + DATE_OF_SPECIMEN_COLLECTION(686), + + /// Type of testing. + TYPE_OF_TESTING(687), + + /// Result of testing. + RESULT_OF_TESTING(688), + + /// Method of testing. + METHOD_OF_TESTING(689), + + // Digital travel authorization number. + DIGITAL_TRAVEL_AUTHORIZATION_NUMBER(690), + + /// Date of first positive test result. + DATE_OF_FIRST_POSITIVE_TEST_RESULT(691), + + EF_CARD_ACCESS(692), + + SHORT_FLIGHT_NUMBER(693), + + AIRLINE_CODE(694), + + MVC_AGENCY(695), + + ISSUING_STATE_CODE_ALPHA_2(696), + + NATIONALITY_CODE_ALPHA_2(697), + + FIRST_ISSUE_DATE_CHECKDIGIT(698), + + FIRST_ISSUE_DATE_CHECKSUM(699), + + EXPIRY_TIMESTAMP(700), + + COMMERCIAL_INDICATOR(701), + + NON_DOMICILED_INDICATOR(702), + + JURISDICTION_SPECIFIC_DATA(703), + + DATA_DATE_OF_EXPIRY(704), + + CONSUL(705); + + const FieldType(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static FieldType? getByValue(int? i) { + if (i == null) return null; + try { + return FieldType.values.firstWhere((x) => x.value == i); + } catch (_) { + return FieldType.UNKNOWN; + } + } + + static List? fromIntList(List? input) { + if (input == null) return null; + List list = []; + for (int item in input) { + list.addSafe(getByValue(item)); + } + return list; + } +} diff --git a/lib/src/results/visual_results/graphic_field.dart b/lib/src/results/visual_results/graphic_field.dart new file mode 100644 index 0000000000..c12edbb175 --- /dev/null +++ b/lib/src/results/visual_results/graphic_field.dart @@ -0,0 +1,79 @@ +// +// GraphicField.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, describing single graphic field extracted. +class GraphicField { + /// Identifies zone whence data is extracted. + ResultType get sourceType => _sourceType; + late ResultType _sourceType; + + /// Graphic field logical type. + GraphicFieldType get fieldType => _fieldType; + late GraphicFieldType _fieldType; + + /// Graphic field symbolic name. + String get fieldName => _fieldName; + late String _fieldName; + + /// Light type. + Lights get light => _light; + late Lights _light; + + /// Light symbolic name. + String get lightName => _lightName; + late String _lightName; + + /// An index of the document page whence the graphic field is extracted. + int get pageIndex => _pageIndex; + late int _pageIndex; + + /// Original page index. + int get originalPageIndex => _originalPageIndex; + late int _originalPageIndex; + + /// An image. + Uint8List? get value => _value; + Uint8List? _value; + + /// Field area coordinates on the general image. + Rect? get fieldRect => _fieldRect; + Rect? _fieldRect; + + /// Allows you to deserialize object. + static GraphicField? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = GraphicField(); + + result._sourceType = ResultType.getByValue(jsonObject["sourceType"])!; + result._fieldType = GraphicFieldType.getByValue(jsonObject["fieldType"])!; + result._light = Lights.getByValue(jsonObject["light"])!; + result._pageIndex = jsonObject["pageIndex"]; + result._originalPageIndex = jsonObject["originalPageIndex"]; + result._fieldName = jsonObject["fieldName"]; + result._lightName = jsonObject["lightName"]; + result._value = _bytesFromBase64(jsonObject["value"]); + result._fieldRect = Rect.fromJson(jsonObject["fieldRect"]); + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "sourceType": sourceType.value, + "fieldType": fieldType.value, + "fieldName": fieldName, + "light": light.value, + "lightName": lightName, + "pageIndex": pageIndex, + "originalPageIndex": originalPageIndex, + "value": _bytesToBase64(value), + "fieldRect": fieldRect?.toJson(), + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/graphic_field_type.dart b/lib/src/results/visual_results/graphic_field_type.dart new file mode 100644 index 0000000000..4b38dc0b00 --- /dev/null +++ b/lib/src/results/visual_results/graphic_field_type.dart @@ -0,0 +1,97 @@ +// +// GraphicFieldType.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Enumeration contains identifiers that determine the logical type +/// of the graphic data obtained while reading the document filling fields or barcodes. +enum GraphicFieldType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Photo of the document owner. + PORTRAIT(201), + + /// Fingerprint of the document owner. + FINGERPR(202), + + /// Iris of the document owner. + EYE(203), + + /// Signature of the document owner. + SIGNATURE(204), + + /// Barcode image. + BAR_CODE(205), + + /// Image of the citizenship proving document. + PROOF_OF_CITIZENSHIP(206), + + /// Document image. + DOCUMENT_IMAGE(207), + + /// Color dynamic area in the document. + COLOR_DYNAMIC(209), + + /// Ghost portrait. + GHOST_PORTRAIT(210), + + /// Stamp. + STAMP(211), + + /// Portrait of child. + PORTRAIT_OF_CHILD(212), + + /// Contact chip. + CONTACT_CHIP(213), + + /// Other image type. + OTHER(250), + + /// Fingerprint, left thumb. + FINGER_LEFT_THUMB(300), + + /// Fingerprint, left index. + FINGER_LEFT_INDEX(301), + + /// Fingerprint, left middle. + FINGER_LEFT_MIDDLE(302), + + /// Fingerprint, left ring. + FINGER_LEFT_RING(303), + + /// Fingerprint, left little. + FINGER_LEFT_LITTLE(304), + + /// Fingerprint, right thumb. + FINGER_RIGHT_THUMB(305), + + /// Fingerprint, right index. + FINGER_RIGHT_INDEX(306), + + /// Fingerprint, right middle. + FINGER_RIGHT_MIDDLE(307), + + /// Fingerprint, right ring. + FINGER_RIGHT_RING(308), + + /// Fingerprint, right little. + FINGER_RIGHT_LITTLE(309); + + const GraphicFieldType(this.value); + final int value; + + static GraphicFieldType? getByValue(int? i) { + if (i == null) return null; + try { + return GraphicFieldType.values.firstWhere((x) => x.value == i); + } catch (_) { + return GraphicFieldType.UNKNOWN; + } + } +} diff --git a/lib/src/results/visual_results/graphic_result.dart b/lib/src/results/visual_results/graphic_result.dart new file mode 100644 index 0000000000..6443389ebd --- /dev/null +++ b/lib/src/results/visual_results/graphic_result.dart @@ -0,0 +1,32 @@ +// +// GraphicResult.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, containing all graphic fields extracted. +class GraphicResult { + /// An array of graphic results. + List get fields => _fields; + List _fields = []; + + /// Allows you to deserialize object. + static GraphicResult? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = GraphicResult(); + + for (var item in jsonObject["fields"]) { + result._fields.addSafe(GraphicField.fromJson(item)); + } + + return result; + } + + /// Allows you to serialize object. + Map toJson() => + {"fields": fields.map((e) => e.toJson()).toList()}.clearNulls(); +} diff --git a/lib/src/results/visual_results/rfid_origin.dart b/lib/src/results/visual_results/rfid_origin.dart new file mode 100644 index 0000000000..d39b4716c8 --- /dev/null +++ b/lib/src/results/visual_results/rfid_origin.dart @@ -0,0 +1,45 @@ +// +// RFIDOrigin.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure containing rfid origin values. +class RFIDOrigin { + int get dg => _dg; + late int _dg; + + int get dgTag => _dgTag; + late int _dgTag; + + int get entryView => _entryView; + late int _entryView; + + int get tagEntry => _tagEntry; + late int _tagEntry; + + /// Allows you to deserialize object. + static RFIDOrigin? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDOrigin(); + + result._dg = jsonObject["dg"]; + result._dgTag = jsonObject["dgTag"]; + result._entryView = jsonObject["entryView"]; + result._tagEntry = jsonObject["tagEntry"]; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "dg": dg, + "dgTag": dgTag, + "entryView": entryView, + "tagEntry": tagEntry, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/text_field.dart b/lib/src/results/visual_results/text_field.dart new file mode 100644 index 0000000000..1e9079384e --- /dev/null +++ b/lib/src/results/visual_results/text_field.dart @@ -0,0 +1,105 @@ +// +// TextField.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Serves for storing information from one text data field. +class TextField { + /// Textual field logical type. + FieldType get fieldType => _fieldType; + late FieldType _fieldType; + + /// Textual field symbolic name. + String get fieldName => _fieldName; + late String _fieldName; + + /// ID of language-culture to differentiate one field of the same type from + /// another (for example Belarus Passport Page # 31 – Belarusian and Russian + /// fields of the same type). + LCID get lcid => _lcid; + late LCID _lcid; + + /// LCID symbolic name. + String get lcidName => _lcidName; + late String _lcidName; + + /// Value from the field. + String? get value => _value; + String? _value; + + Value? getValue() => _getValue; + Value? _getValue; + + /// An array of values. + List get values => _values; + List _values = []; + + /// Textual field check result. + CheckResult get status => _status; + late CheckResult _status; + + /// List of all comparison statuses for this field type. + List get comparisonList => _comparisonList; + List _comparisonList = []; + + /// List of all validity statuses for this field type. + List get validityList => _validityList; + List _validityList = []; + + /// Comparison result of the field. + CheckResult get comparisonStatus => _comparisonStatus; + late CheckResult _comparisonStatus; + + /// Validity result of the field + CheckResult get validityStatus => _validityStatus; + late CheckResult _validityStatus; + + /// Allows you to deserialize object. + static TextField? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TextField(); + + result._fieldType = FieldType.getByValue(jsonObject["fieldType"])!; + result._lcid = LCID.getByValue(jsonObject["lcid"])!; + result._status = CheckResult.getByValue(jsonObject["status"])!; + result._comparisonStatus = + CheckResult.getByValue(jsonObject["comparisonStatus"])!; + result._validityStatus = + CheckResult.getByValue(jsonObject["validityStatus"])!; + result._lcidName = jsonObject["lcidName"]; + result._fieldName = jsonObject["fieldName"]; + result._value = jsonObject["value"]; + result._getValue = Value.fromJson(jsonObject["getValue"]); + for (var item in jsonObject["values"]) { + result._values.addSafe(Value.fromJson(item)); + } + for (var item in jsonObject["comparisonList"]) { + result._comparisonList.addSafe(Comparison.fromJson(item)); + } + for (var item in jsonObject["validityList"]) { + result._validityList.addSafe(Validity.fromJson(item)); + } + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "fieldType": fieldType.value, + "fieldName": fieldName, + "lcid": lcid.value, + "lcidName": lcidName, + "value": value, + "getValue": getValue()?.toJson(), + "values": values.map((e) => e.toJson()).toList(), + "status": status.value, + "comparisonList": comparisonList.map((e) => e.toJson()).toList(), + "validityList": validityList.map((e) => e.toJson()).toList(), + "comparisonStatus": comparisonStatus.value, + "validityStatus": validityStatus.value, + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/text_result.dart b/lib/src/results/visual_results/text_result.dart new file mode 100644 index 0000000000..9214c4da26 --- /dev/null +++ b/lib/src/results/visual_results/text_result.dart @@ -0,0 +1,62 @@ +// +// TextResult.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure, containing all text data extracted and recognized from the document. +class TextResult { + /// Textual fields check result. + CheckResult get status => _status; + late CheckResult _status; + + /// Comparison status of all text fields. + CheckResult get comparisonStatus => _comparisonStatus; + late CheckResult _comparisonStatus; + + /// Validity status of all text fields. + CheckResult get validityStatus => _validityStatus; + late CheckResult _validityStatus; + + /// List of all available origin source with overall validity + /// status of all text fields of a particular source type. + List get availableSourceList => _availableSourceList; + List _availableSourceList = []; + + /// An array of textual results. + List get fields => _fields; + List _fields = []; + + /// Allows you to deserialize object. + static TextResult? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TextResult(); + + result._status = CheckResult.getByValue(jsonObject["status"])!; + result._comparisonStatus = + CheckResult.getByValue(jsonObject["comparisonStatus"])!; + result._validityStatus = + CheckResult.getByValue(jsonObject["validityStatus"])!; + for (var item in jsonObject["availableSourceList"]) { + result._availableSourceList.addSafe(TextSource.fromJson(item)); + } + for (var item in jsonObject["fields"]) { + result._fields.addSafe(TextField.fromJson(item)); + } + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "status": status.value, + "comparisonStatus": comparisonStatus.value, + "validityStatus": validityStatus.value, + "availableSourceList": + availableSourceList.map((e) => e.toJson()).toList(), + "fields": fields.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/results/visual_results/text_source.dart b/lib/src/results/visual_results/text_source.dart new file mode 100644 index 0000000000..3006e8c8f6 --- /dev/null +++ b/lib/src/results/visual_results/text_source.dart @@ -0,0 +1,44 @@ +// +// TextSource.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../../flutter_document_reader_api.dart"; + +/// Structure describing single value of the field. +class TextSource { + /// The value's origin source. + ResultType get sourceType => _sourceType; + late ResultType _sourceType; + + /// The value's origin source string description. + String? get source => _source; + String? _source; + + /// Overall validity status of all text fields of this source type. + CheckResult get validityStatus => _validityStatus; + late CheckResult _validityStatus; + + /// Allows you to deserialize object. + static TextSource? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TextSource(); + + result._sourceType = ResultType.getByValue(jsonObject["sourceType"])!; + result._source = jsonObject["source"]; + result._validityStatus = + CheckResult.getByValue(jsonObject["validityStatus"])!; + + return result; + } + + /// Allows you to serialize object. + Map toJson() => { + "sourceType": sourceType.value, + "source": source, + "validityStatus": validityStatus.value, + }.clearNulls(); +} diff --git a/lib/src/rfid/ca_protocol.dart b/lib/src/rfid/ca_protocol.dart new file mode 100644 index 0000000000..6dc9472bca --- /dev/null +++ b/lib/src/rfid/ca_protocol.dart @@ -0,0 +1,36 @@ +part of "../../flutter_document_reader_api.dart"; + +class CAProtocol { + String get version => _version; + late String _version; + + String get scheme => _scheme; + late String _scheme; + + String get keyAlgorithm => _keyAlgorithm; + late String _keyAlgorithm; + + bool get chipIndividual => _chipIndividual; + late bool _chipIndividual; + + @visibleForTesting + static CAProtocol? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = CAProtocol(); + + result._version = jsonObject["version"]; + result._scheme = jsonObject["scheme"]; + result._keyAlgorithm = jsonObject["keyAlgorithm"]; + result._chipIndividual = jsonObject["chipIndividual"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "version": version, + "scheme": scheme, + "keyAlgorithm": keyAlgorithm, + "chipIndividual": chipIndividual, + }.clearNulls(); +} diff --git a/lib/src/rfid/pa_attribute.dart b/lib/src/rfid/pa_attribute.dart new file mode 100644 index 0000000000..b26121a9f8 --- /dev/null +++ b/lib/src/rfid/pa_attribute.dart @@ -0,0 +1,31 @@ +// +// PAAttribute.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class PAAttribute { + String get type => _type; + late String _type; + + String get value => _value; + late String _value; + + @visibleForTesting + static PAAttribute? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = PAAttribute(); + + result._type = jsonObject["type"] ?? ""; + result._value = jsonObject["value"] ?? ""; + + return result; + } + + @visibleForTesting + Map toJson() => {"type": type, "value": value}.clearNulls(); +} diff --git a/lib/src/rfid/pa_resources_issuer.dart b/lib/src/rfid/pa_resources_issuer.dart new file mode 100644 index 0000000000..4afb213e65 --- /dev/null +++ b/lib/src/rfid/pa_resources_issuer.dart @@ -0,0 +1,40 @@ +// +// PAResourcesIssuer.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class PAResourcesIssuer { + Uint8List get data => _data; + late Uint8List _data; + + String? get friendlyName => _friendlyName; + String? _friendlyName; + + List get attributes => _attributes; + List _attributes = []; + + @visibleForTesting + static PAResourcesIssuer? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = PAResourcesIssuer(); + + result._data = _bytesFromBase64(jsonObject["data"])!; + result._friendlyName = jsonObject["friendlyName"]; + for (var item in jsonObject["attributes"]) { + result._attributes.addSafe(PAAttribute.fromJson(item)); + } + return result; + } + + @visibleForTesting + Map toJson() => { + "data": _bytesToBase64(data), + "friendlyName": friendlyName, + "attributes": attributes.map((e) => e.toJson()).toList(), + }.clearNulls(); +} diff --git a/lib/src/rfid/pace_protocol.dart b/lib/src/rfid/pace_protocol.dart new file mode 100644 index 0000000000..f82fbfc138 --- /dev/null +++ b/lib/src/rfid/pace_protocol.dart @@ -0,0 +1,31 @@ +part of "../../flutter_document_reader_api.dart"; + +class PACEProtocol { + String get version => _version; + late String _version; + + String get stdDomainParams => _stdDomainParams; + late String _stdDomainParams; + + String get keyAlgorithm => _keyAlgorithm; + late String _keyAlgorithm; + + @visibleForTesting + static PACEProtocol? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = PACEProtocol(); + + result._version = jsonObject["version"]; + result._stdDomainParams = jsonObject["stdDomainParams"]; + result._keyAlgorithm = jsonObject["keyAlgorithm"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "version": version, + "stdDomainParams": stdDomainParams, + "keyAlgorithm": keyAlgorithm, + }.clearNulls(); +} diff --git a/lib/src/rfid/pkd_certificate.dart b/lib/src/rfid/pkd_certificate.dart new file mode 100644 index 0000000000..e55b81b3bd --- /dev/null +++ b/lib/src/rfid/pkd_certificate.dart @@ -0,0 +1,122 @@ +// +// PKDCertificate.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Class contains information about PKD certificate. +class PKDCertificate { + /// Certificate in binary type. + ByteData get binaryData => _binaryData; + ByteData _binaryData; + + /// Indicates type of certificate. + PKDResourceType get resourceType => _resourceType; + PKDResourceType _resourceType; + + /// Private key in binary type. + ByteData? get privateKey => _privateKey; + ByteData? _privateKey; + + PKDCertificate( + ByteData binaryData, + PKDResourceType resourceType, { + ByteData? privateKey, + }) : _binaryData = binaryData, + _resourceType = resourceType, + _privateKey = privateKey; + + @visibleForTesting + static PKDCertificate? fromJson(jsonObject) { + if (jsonObject == null) return null; + return PKDCertificate( + _dataFromBase64(jsonObject["binaryData"])!, + PKDResourceType.getByValue(jsonObject["resourceType"])!, + privateKey: _dataFromBase64(jsonObject["privateKey"]), + ); + } + + @visibleForTesting + Map toJson() => { + "binaryData": _dataToBase64(binaryData), + "resourceType": resourceType.value, + "privateKey": _dataToBase64(privateKey), + }.clearNulls(); +} + +enum PKDResourceType { + /// Will be returned if [getByValue] if a non-existent was passed. + UNKNOWN(-1), + + /// Certificate file contents (.pem, .cer, .crt, .der). + CERTIFICATE_PA(0), + + /// Certificate file contents (.cvcert) and private key file contents (.pkcs8). + CERTIFICATE_TA(1), + + /// LDIF file contents (.ldif). + LDIF(2), + + /// CRL file contents (.crl). + CRL(3), + + /// Master List (.ml, .mls). + ML(4), + + /// Defect List (.dl, .dls, .dfl). + DEFL(5), + + /// Deviance List (.dl, .dls, .dvl). + DEVL(6), + + /// Black List (.bl, .bls). + BL(7), + + /// LDIF file contents for TA. + LDIF_TA(8), + + /// Master List with CV certificates for TA. + ML_TA(9), + + /// CBOR List. + CBOR(10); + + const PKDResourceType(this.value); + final int value; + + static PKDResourceType? getByValue(int? i) { + if (i == null) return null; + try { + return PKDResourceType.values.firstWhere((x) => x.value == i); + } catch (_) { + return PKDResourceType.UNKNOWN; + } + } + + static PKDResourceType getType(String value) { + switch (value) { + case "pa": + return CERTIFICATE_PA; + case "ta": + return CERTIFICATE_TA; + case "ldif": + return LDIF; + case "crl": + return CRL; + case "ml": + return ML; + case "defl": + return DEFL; + case "devl": + return DEVL; + case "bl": + return BL; + default: + return CERTIFICATE_PA; + } + } +} diff --git a/lib/src/rfid/rfid_error_codes.dart b/lib/src/rfid/rfid_error_codes.dart new file mode 100644 index 0000000000..801a0e7a66 --- /dev/null +++ b/lib/src/rfid/rfid_error_codes.dart @@ -0,0 +1,146 @@ +// +// RFIDErrorCodes.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +enum RFIDErrorCodes { + UNDEFINED(0), + NO_ERROR(0x00000001), + ALREADY_DONE(0x00000002), + FAILED(0xffffffff), + NO_CHIP_DETECTED(0x80010001), + NOT_AVAILABLE(0x80010002), + INVALID_PARAMETER(0x80010004), + NOT_INITIALIZED(0x80010005), + NOT_ENOUGH_MEMORY(0x80010006), + INVALID_DIRECTORY(0x80010008), + UNKNOWN_COMMAND(0x80010009), + FILE_IO_ERROR(0x8001000A), + BUSY(0x8001000B), + OLD_FIRMWARE(0x8001000C), + PCSC_FAILED(0x80020000), + PCSC_READER_NOT_AVAILABLE(0x80020001), + PCSC_CANT_CONNECT_CARD(0x80020002), + PCSC_CARD_IS_NOT_CONNECTED(0x80020003), + PCSC_OPERATION_CANCELLED(0x80020004), + PCSC_CARD_IS_BUSY(0x80020005), + PCSC_FAILED_SCARD(0x80020006), + PCSC_EXT_LE_FAILED(0x80020010), + LAYER6_SECURITY_MANAGER(0x86000000), + LAYER6_APP_SELECTION_FAILURE(0x86000001), + LAYER6_MUTUAL_AUTH_MAC_FAIL(0x86000100), + LAYER6_MUTUAL_AUTH_ENC_FAIL(0x86000101), + LAYER6_MUTUAL_AUTH_FAILURE(0x86000102), + LAYER6_MUTUAL_AUTH_FAILURE_DATA(0x86000103), + LAYER6_SM_DO_8E_MISSING(0x86000200), + LAYER6_SM_DO_87_MISSING(0x86000201), + LAYER6_SM_DO_99_MISSING(0x86000202), + LAYER6_SM_MAC_INCORRECT(0x86000203), + LAYER6_SM_DO_87_INCORRECT(0x86000204), + LAYER6_NON_TLV_RESPONSE_DATA(0x86000300), + LAYER6_WRONG_RND_ICC_LENGTH(0x86000301), + LAYER6_INT_AUTH_FAILURE(0x86000302), + LAYER6_MSE_SET_KAT_FAILURE(0x86000303), + LAYER6_MSE_SET_DST_FAILURE(0x86000304), + LAYER6_PSO_CERTIFICATE_FAILURE(0x86000305), + LAYER6_MSE_SET_AT_FAILURE(0x86000306), + LAYER6_GET_CHALLENGE_FAILURE(0x86000307), + LAYER6_EXT_AUTH_FAILURE(0x86000308), + LAYER6_GENERAL_AUTH_FAILURE(0x86000309), + LAYER6_FILE_NOT_FOUND(0x80006A82), + LAYER6_FILE_EOF1(0x80006282), + LAYER6_FILE_EOF2(0x80006B00), + LAYER6_INCORRECT_PARAMS(0x80006A80), + LAYER6_NO_REFERENCE_DATA(0x80006A88), + LAYER6_PWD_SUSPEND(0x800063C1), + LAYER6_PWD_BLOCKED(0x800063C0), + LAYER6_PWD_DEACTIVATED(0x80006283), + LAYER6_PWD_BLOCKED2(0x80006983), + LAYER6_PWD_DEACTIVATED2(0x80006984), + LAYER6_PWD_SUSPEND2(0x80006985), + LAYER6_PWD_FAILED(0x801063C0), + NOT_PERFORMED(0x83000000), + SESSION_IS_CLOSED(0x83000001), + SESSION_TERMINAL_UNSUPPORTED_OPERATION(0x83000002), + SESSION_TERMINAL_TYPE_UNKNOWN(0x83000010), + SESSION_TERMINAL_TYPE_BAD_CERTIFICATE(0x83000011), + SESSION_TERMINAL_TYPE_NOT_SET(0x83000012), + SESSION_PROCEDURE_TYPE_UNKNOWN(0x83000013), + Session_Procedure_Type_Unsupported(0x83000014), + SESSION_PROCEDURE_TYPE_NOT_SET(0x83000015), + SESSION_ACCESS_KEY_UNKNOWN_TYPE(0x83000016), + SESSION_ACCESS_KEY_UNSUPPORTED_SM_TYPE(0x83000017), + SESSION_ACCESS_KEY_INCORRECT_SM_TYPE(0x83000018), + SESSION_ACCESS_KEY_RESTRICTED(0x83000019), + SESSION_ACCESS_KEY_INCORRECT_DATA(0x8300001A), + SESSION_ACCESS_KEY_NOT_SET(0x8300001B), + SESSION_PWD_MANAGEMENT_NOT_AUTHORIZED(0x8300001C), + SESSION_ACCESS_CONTROL_UNKNOWN_TYPE(0x83000020), + SESSION_ACCESS_CONTROL_REQUIRES_SM(0x83000021), + SESSION_ACCESS_CONTROL_REQUIRES_PACE(0x83000022), + SESSION_ACCESS_CONTROL_REQUIRES_CA_KEYS(0x83000023), + SESSION_ACCESS_CONTROL_REQUIRES_TA(0x83000024), + SESSION_ACCESS_CONTROL_REQUIRES_CA(0x83000025), + SESSION_ACCESS_CONTROL_INCORRECT_OPTION_CA(0x83000026), + SESSION_ACCESS_CONTROL_CA_FAILED(0x83000027), + SESSION_ACCESS_CONTROL_TA_FAILED(0x83000028), + SESSION_ACCESS_CONTROL_AA_FAILED(0x83000029), + SESSION_ACCESS_CONTROL_RI_FAILED(0x8300002A), + SESSION_PA_SIGNATURE_CHECK_FAILED(0x83000030), + SESSION_PA_HASH_CHECK_FAILED(0x83000031), + SESSION_INVALID_AUX_DATA_DATE_OF_EXPIRY(0x83000040), + SESSION_INVALID_AUX_DATA_DATE_OF_BIRTH(0x83000041), + SESSION_INVALID_AUX_DATA_COMMUNITY_ID(0x83000042), + SESSION_E_SIGN_REQUIRES_APP_SELECTION(0x83000050), + SESSION_E_SIGN_PIN_NOT_SET(0x83000051), + SESSION_E_SIGN_PIN_NOT_VERIFIED(0x83000052), + SESSION_INCORRECT_DATA(0x83000060), + SESSION_FILE_NOT_ENOUGH_DATA(0x83010000), + SESSION_FILE_INCORRECT_DATA(0x83020000), + SESSION_FILE_UNEXPECTED_DATA(0x83030000), + SESSION_FILE_CONTENTS_UNEXPECTED_DATA(0x83040000), + SESSION_FILE_WRONG_TAG(0x83050000), + SESSION_FILE_CANT_USE_DATA(0x83060000), + SESSION_FILE_CANT_READ_DATA(0x83070000), + SESSION_FILE_ACCESS_DENIED(0x83080000), + LAYER34_NO_ERROR(0x84000000), + LAYER34_TIME_OUT(0x84010000), + LAYER34_COLLISION(0x84020000), + LAYER34_CRC(0x84030000), + LAYER34_DATA_INTEGRITY(0x84040000), + LAYER34_DATA_LENGTH(0x84050000), + Layer34_RFU(0x84060000), + LAYER34_COLLISION_TOO_MANY(0x84070000), + LAYER34_PROTOCOL_B(0x84080000), + LAYER34_DATA_CONTENTS(0x84090000), + LAYER34_PROTOCOL(0x840A0000), + LAYER34_GLOBAL_TIME_OUT(0x840B0000), + LAYER34_MIFARE_AUTH(0x840C0000), + LAYER34_SAM_ERROR(0x840D0000), + LAYER34_SAM_COLLISION(0x840E0000), + LAYER34_SAM_ACKNOWLEDGE(0x840F0000); + + const RFIDErrorCodes(this.value); + final int value; + + Future getTranslation() async { + return await _bridge.invokeMethod("getTranslation", [ + runtimeType.toString(), + value, + ]); + } + + static RFIDErrorCodes? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDErrorCodes.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDErrorCodes.UNDEFINED; + } + } +} diff --git a/lib/src/rfid/rfid_notification.dart b/lib/src/rfid/rfid_notification.dart new file mode 100644 index 0000000000..dbc5980fb1 --- /dev/null +++ b/lib/src/rfid/rfid_notification.dart @@ -0,0 +1,203 @@ +// +// RFIDNotification.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// Structure containing data of notification about RFID reading process. +class RFIDNotification { + /// RFID notification code. + RFIDNotificationCodes get notificationCode => _notificationCode; + late RFIDNotificationCodes _notificationCode; + + /// Defines the file type (or logical belonging of the data object) within + /// the context of the communication session with electronic document. + RFIDDataFileType get dataFileType => _dataFileType; + late RFIDDataFileType _dataFileType; + + /// RFID progress. + int get progress => _progress; + late int _progress; + + @visibleForTesting + static RFIDNotification? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = RFIDNotification(); + + result._notificationCode = + RFIDNotificationCodes.getByValue(jsonObject["notificationCode"])!; + result._dataFileType = + RFIDDataFileType.getByValue(jsonObject["dataFileType"])!; + result._progress = jsonObject["progress"]; + + return result; + } + + @visibleForTesting + Map toJson() => { + "notificationCode": notificationCode.value, + "dataFileType": dataFileType.value, + "progress": progress, + }.clearNulls(); +} + +/// Enumeration contains a set of notification returned +/// to the user application by calling the callback-function. +enum RFIDNotificationCodes { + /// Will be returned by [getByValue] if a non-existent value was passed. + UNKNOWN(-1), + + /// The notification indicates an error. + ERROR(65536), + + /// Event of appearance of RFID-chip in the scope of the reader antenna + /// or its moving away from the scope of the reader. + DOCUMENT_READY(65537), + + /// Event of the beginning/end of data reading from the RFID-chip via ISO/IEC + /// 14443-4 proto-col When working in the batch mode. + READ_PROTOCOL4(65539), + + /// Event of the beginning/end of data reading from the RFID-chip via ISO/IEC + /// 14443-3 proto-col. + READ_PROTOCOL3(65546), + + /// Indication of the progress of execution of data reading operation. + PROGRESS(65547), + + /// Indication of the next step of terminal authentication in + /// Online-authentication mode. + TA_STEP(65550), + + /// Event of detection of the need to organize a secure communication channel. + SM_REQUIRED(65551), + + /// Event informing the user application on detection of data incompliance + /// processed with the regulations of normative documents, errors when + /// executing the current operation. + ISO_ERROR(69632), + + /// Request of the user-defined DS-certificate priot to the procedure of digital + /// signature verifi-cation of EF.SOD document security object in the batch mode. + PA_REQUEST(77824), + + /// Event of the result of the opening of a secure communication channel. + SM_ESTABLISHED(81935), + + /// Event of unplugging of the RFID-chip reader from the PC. + PCSC_READER_DISCONNECTED(131072), + + /// Event of the beginning of reorganization of the list of RFID-readers + /// connected to the PC, working under PC/SC-driver control. + PCSC_READER_LIST_CHANGED(131073), + + /// Transfer of the total amount of information received from the RFID-chip + /// to the user appli-cation during execution of data reading operation. + PCSC_BYTES_RECEIVED(131074), + + /// Transfer of the total time of execution of data reading operation + /// to the user application. + PCSC_TOTAL_READING_TIME(131075), + + /// Transfer of the total amount of information and service groups data + /// received from the RF-ID-chip to the user application during execution + /// of data reading operation. + PCSC_DATA_RECEIVED(131076), + + /// Transfer of the total amount of information transmitted to the RFID-chip + /// to the user appli-cation during execution of data reading operation. + PCSC_BYTES_SENT(131077), + + /// Transfer of the average data reading rate to the user application. + PCSC_TOTAL_READING_SPEED(131078), + + /// Transfer of the total time of execution of data reading procedure + /// to the user application. + PCSC_TOTAL_PROCESS_TIME(131079), + + /// Event of the beginning of reorganization of the list of RFID-readers + /// connected to the PC, working under PC/SC-driver control. + PCSC_READER_LIST_CHANGING(131080), + + /// Event of detection of extended length reading commands support + /// by the RFID-chip. + PCSC_EXT_LENGTH_SUPPORT(131088), + + /// Event of the start/end of the certificate chain formation for the + /// document security object digital signature verification + /// as a part of passive authentication procedure. + PA_CERTIFICATE_CHAIN(131089), + + /// Event that indicates a type of the current analyzed element of the + /// certificate chain being composed. + /// + /// All subsequent notifications prior to the next [PA_CERTIFICATE_CHAIN_ITEM] + /// or [PA_CERTIFICATE_CHAIN] will correspond to this element. + PA_CERTIFICATE_CHAIN_ITEM(131090), + + /// A request from the user application of some data or actions in a certain + /// step of the scenario. + SCENARIO(131104), + + /// Event of the beginning/end of file reading. + PCSC_READING_DATAGROUP(196608), + + /// Event of detection of file absence. + PCSC_FILE_NOT_FOUND(262144), + + /// Event of reaching the file end when performing its reading. + PCSC_END_OF_FILE(327680), + + /// Event of detection of absence of the file access rights. + PCSC_FILE_ACCESS_DENIED(393216), + + /// Event of the application selection operation. + PCSC_APPLICATION_SELECTED(458752), + + /// Event of the beginning of the authentication or secure data access procedure. + AC_PROCEDURE_START(524288), + + /// Event of the end of the authentication or secure data access procedure. + AC_PROCEDURE_FINISH(589824), + + /// Event of the data security object verification as part of PA. + PA_SECURITY_OBJECT_CHECK(655360), + + /// Event of the file data integrity checking as part of PA. + PA_FILE_CHECK(720896), + + /// Event of the procedure of file contents updating. + PCSC_UPDATING_DATAGROUP(786432), + + /// Event of the auxiliary data verification. + AUXILIARY_DATA_VALIDATION(851968), + + /// Event of the receiving of the sector identifier data during RI. + RI_SECTOR_ID(917504), + + /// Event of the detection of real biometric data absence in DG3 or DG4 + /// and random filling data usage. + BIOMETRICS_EMPTY_PLACEHOLDER(983040), + + SESSION_FILE_DATA_UPDATED(1048576), + + TCC_TA_RESOURCES(1114112), + + TCC_TA_SIGNATURE(1114113); + + const RFIDNotificationCodes(this.value); + final int value; + + static RFIDNotificationCodes? getByValue(int? i) { + if (i == null) return null; + try { + return RFIDNotificationCodes.values.firstWhere((x) => x.value == i); + } catch (_) { + return RFIDNotificationCodes.UNKNOWN; + } + } +} diff --git a/lib/src/rfid/ta_challenge.dart b/lib/src/rfid/ta_challenge.dart new file mode 100644 index 0000000000..cbd339f3c6 --- /dev/null +++ b/lib/src/rfid/ta_challenge.dart @@ -0,0 +1,49 @@ +// +// TAChallenge.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +class TAChallenge { + Uint8List get data => _data; + late Uint8List _data; + + String get auxPCD => _auxPCD; + late String _auxPCD; + + String get challengePICC => _challengePICC; + late String _challengePICC; + + String get hashPK => _hashPK; + late String _hashPK; + + String get idPICC => _idPICC; + late String _idPICC; + + @visibleForTesting + static TAChallenge? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TAChallenge(); + + result._data = _bytesFromBase64(jsonObject["data"])!; + result._auxPCD = jsonObject["auxPCD"] ?? ""; + result._challengePICC = jsonObject["challengePICC"] ?? ""; + result._hashPK = jsonObject["hashPK"] ?? ""; + result._idPICC = jsonObject["idPICC"] ?? ""; + + return result; + } + + @visibleForTesting + Map toJson() => { + "data": _bytesToBase64(data), + "auxPCD": auxPCD, + "challengePICC": challengePICC, + "hashPK": hashPK, + "idPICC": idPICC, + }.clearNulls(); +} diff --git a/lib/src/rfid/tcc_params.dart b/lib/src/rfid/tcc_params.dart new file mode 100644 index 0000000000..c3b2507774 --- /dev/null +++ b/lib/src/rfid/tcc_params.dart @@ -0,0 +1,54 @@ +// +// TccParams.dart +// DocumentReader +// +// Created by Pavel Masiuk on 21.09.2023. +// Copyright © 2023 Regula. All rights reserved. +// + +part of "../../flutter_document_reader_api.dart"; + +/// TCC service related parameters for RFID session configuration. +class TccParams { + /// The TA URL for the TCC service. The value of the property + /// must be a valid URL string. + String? serviceUrlTA; + + /// The PA URL for the TCC service. The value of the property + /// must be a valid URL string. + String? serviceUrlPA; + + /// The URL for the certificate for a TCC service. + /// The value of the property must be a valid URL string. + String? pfxCertUrl; + + /// The passphrase for the cerficiate provided by the [pfxCertUrl] property. + String? pfxPassPhrase; + + /// The bytes of the certificate for a TCC service. + /// This data will be used instead of loading the certificate via [pfxCertUrl]. + ByteData? pfxCert; + + @visibleForTesting + static TccParams? fromJson(jsonObject) { + if (jsonObject == null) return null; + var result = TccParams(); + + result.serviceUrlTA = jsonObject["serviceUrlTA"]; + result.serviceUrlPA = jsonObject["serviceUrlPA"]; + result.pfxCertUrl = jsonObject["pfxCertUrl"]; + result.pfxPassPhrase = jsonObject["pfxPassPhrase"]; + result.pfxCert = _dataFromBase64(jsonObject["pfxCert"]); + + return result; + } + + @visibleForTesting + Map toJson() => { + "serviceUrlTA": serviceUrlTA, + "serviceUrlPA": serviceUrlPA, + "pfxCertUrl": pfxCertUrl, + "pfxPassPhrase": pfxPassPhrase, + "pfxCert": _dataToBase64(pfxCert), + }.clearNulls(); +} diff --git a/pubspec.lock b/pubspec.lock index 20c75f4e87..fe19b5045b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -5,50 +5,50 @@ packages: dependency: transitive description: name: async - sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 url: "https://pub.dev" source: hosted - version: "2.11.0" + version: "2.13.1" boolean_selector: dependency: transitive description: name: boolean_selector - sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" characters: dependency: transitive description: name: characters - sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.4.0" clock: dependency: transitive description: name: clock - sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" collection: dependency: transitive description: name: collection - sha256: f092b211a4319e98e5ff58223576de6c2803db36221657b46c82574721240687 + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" url: "https://pub.dev" source: hosted - version: "1.17.2" + version: "1.19.1" fake_async: dependency: transitive description: name: fake_async - sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "1.3.3" flutter: dependency: "direct main" description: flutter @@ -59,107 +59,139 @@ packages: description: flutter source: sdk version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: "direct dev" + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" matcher: dependency: transitive description: name: matcher - sha256: "1803e76e6653768d64ed8ff2e1e67bea3ad4b923eb5c56a295c3e634bad5960e" + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 url: "https://pub.dev" source: hosted - version: "0.12.16" + version: "0.12.17" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.5.0" + version: "0.11.1" meta: - dependency: transitive + dependency: "direct dev" description: name: meta - sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" url: "https://pub.dev" source: hosted - version: "1.9.1" + version: "1.17.0" path: dependency: transitive description: name: path - sha256: "8829d8a55c13fc0e37127c29fedf290c102f4e40ae94ada574091fe0ff96c917" + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" url: "https://pub.dev" source: hosted - version: "1.8.3" + version: "1.9.1" sky_engine: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_span: dependency: transitive description: name: source_span - sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.10.2" stack_trace: dependency: transitive description: name: stack_trace - sha256: c3c7d8edb15bee7f0f74debd4b9c5f3c2ea86766fe4178eb2a18eb30a0bdaed5 + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.12.1" stream_channel: dependency: transitive description: name: stream_channel - sha256: "83615bee9045c1d322bbbd1ba209b7a749c2cbcdcb3fdd1df8eb488b3279c1c8" + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.4" string_scanner: dependency: transitive description: name: string_scanner - sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" url: "https://pub.dev" source: hosted - version: "1.2.0" + version: "1.4.1" term_glyph: dependency: transitive description: name: term_glyph - sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.2.2" test_api: dependency: transitive description: name: test_api - sha256: "75760ffd7786fffdfb9597c35c5b27eaeec82be8edfb6d71d32651128ed7aab8" + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 url: "https://pub.dev" source: hosted - version: "0.6.0" + version: "0.7.7" vector_math: dependency: transitive description: name: vector_math - sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b url: "https://pub.dev" source: hosted - version: "2.1.4" - web: + version: "2.2.0" + vm_service: dependency: transitive description: - name: web - sha256: dc8ccd225a2005c1be616fe02951e2e342092edf968cf0844220383757ef8f10 + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" url: "https://pub.dev" source: hosted - version: "0.1.4-beta" + version: "15.2.0" sdks: - dart: ">=3.1.0-185.0.dev <4.0.0" - flutter: ">=1.10.0" + dart: ">=3.8.0-0 <4.0.0" + flutter: ">=3.18.0-18.0.pre.54" diff --git a/pubspec.yaml b/pubspec.yaml index 14b4b95b3e..fdee031aad 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,13 +1,14 @@ name: flutter_document_reader_api -description: - This is a flutter module for Regula document reader. - It allows you to easily scan documents, for example passport, using your phone's camera. Supports Android and iOS -version: 6.9.2 -homepage: "https://github.com/regulaforensics/DocumentReader-Flutter" +description: + This is a flutter module for Regula document reader. + It allows you to easily scan documents, for example passport, using your phone's camera. Supports Android and iOS. +repository: https://github.com/regulaforensics/DocumentReader-Flutter +issue_tracker: https://github.com/regulaforensics/DocumentReader-Flutter/issues +version: 9.5.1277-rc environment: - sdk: '>=2.12.0 <3.0.0' - flutter: ">=1.10.0" + sdk: '>=3.1.5 <4.0.0' + flutter: '>=3.10.0' dependencies: flutter: @@ -16,12 +17,14 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + lints: ^4.0.0 + meta: ^1.10.0 flutter: plugin: platforms: android: - package: io.flutter.plugins.regula.documentreader.flutter_document_reader_api + package: com.regula.plugin.documentreader pluginClass: FlutterDocumentReaderApiPlugin ios: - pluginClass: FlutterDocumentReaderApiPlugin \ No newline at end of file + pluginClass: FlutterDocumentReaderApiPlugin diff --git a/test/document_reader_test.dart b/test/document_reader_test.dart index ab73b3a234..35cab25b85 100644 --- a/test/document_reader_test.dart +++ b/test/document_reader_test.dart @@ -1 +1,188 @@ -void main() {} +import 'package:flutter_document_reader_api/flutter_document_reader_api.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'json.dart'; +import 'utils.dart'; + +void main() { + group('DocumentReader', () { + compare('initConfig', initConfig, InitConfig.fromJson); + compare( + 'onlineProcessingConfig', + onlineProcessingConfig, + OnlineProcessingConfig.fromJson, + ); + compare('imageInputData', imageInputData, ImageInputData.fromJson); + compare('recognizeConfig', recognizeConfig, RecognizeConfig.fromJson); + compare('recognizeConfig2', recognizeConfig2, RecognizeConfig.fromJson); + compare('scannerConfig', scannerConfig, ScannerConfig.fromJson); + compare('finalizeConfig', finalizeConfig, FinalizeConfig.fromJson); + + compare( + 'faceApiSearchParams', + faceApiSearchParams, + FaceApiSearchParams.fromJson, + ); + compare('faceApiParams', faceApiParams, FaceApiParams.fromJson); + + compareParams('livenessParams', livenessParams, LivenessParams.fromJson); + compareParams( + 'authenticityParams', + authenticityParams, + AuthenticityParams.fromJson, + ); + compare('glaresCheckParams', glaresCheckParams, GlaresCheckParams.fromJson); + compare('rfidParams', rfidParams, RFIDParams.fromJson); + compareParams('imageQA', imageQA, ImageQA.fromJson); + compare( + 'backendProcessingConfig', + backendProcessingConfig, + BackendProcessingConfig.fromJson, + ); + compare('bsi', bsi, Bsi.fromJson); + compareParams( + 'processParams', + processParams, + ProcessParams.fromJson, + skip: ["logs"], + ); + compareParams('eDLDataGroups', eDLDataGroups, EDLDataGroups.fromJson); + compareParams( + 'ePassportDataGroups', + ePassportDataGroups, + EPassportDataGroups.fromJson, + ); + compareParams('eIDDataGroups', eIDDataGroups, EIDDataGroups.fromJson); + compareParams('dtcDataGroup', dtcDataGroup, DTCDataGroup.fromJson); + compareParams('rfidScenario', rfidScenario, RFIDScenario.fromJson); + compareParams( + 'customizationColors', + customizationColors, + CustomizationColors.fromJson, + ); + compareParams( + 'customizationFonts', + customizationFonts, + CustomizationFonts.fromJson, + ); + compareParams( + 'customizationImages', + customizationImages, + CustomizationImages.fromJson, + ); + compareParams( + 'customizationTimings', + customizationTimings, + CustomizationTimings.fromJson, + ); + compareParams( + 'customizationContentModes', + customizationContentModes, + CustomizationContentModes.fromJson, + ); + compareParams( + 'customizationMatrices', + customizationMatrices, + CustomizationMatrices.fromJson, + ); + compareParams('customization', customization, Customization.fromJson); + compareParams('functionality', functionality, Functionality.fromJson); + + compare('documentsDatabase', documentsDatabase, DocumentsDatabase.fromJson); + compare('docReaderVersion', docReaderVersion, DocReaderVersion.fromJson); + compare('docReaderScenario', docReaderScenario, DocReaderScenario.fromJson); + compare('license', license, License.fromJson); + compare( + 'docReaderException', + docReaderException, + DocReaderException.fromJson, + ); + compare('rfidException', rfidException, RFIDException.fromJson); + compare('prepareProgress', prepareProgress, PrepareProgress.fromJson); + + compare( + 'authenticityElement', + authenticityElement, + AuthenticityElement.fromJson, + ); + compare('authenticityCheck', authenticityCheck, AuthenticityCheck.fromJson); + compare( + 'authenticityResult', + authenticityResult, + AuthenticityResult.fromJson, + ); + compare('pdf417Info', pdf417Info, PDF417Info.fromJson); + compare('barcodeField', barcodeField, BarcodeField.fromJson); + compare('barcodeResult', barcodeResult, BarcodeResult.fromJson); + compare('imageQuality', imageQuality, ImageQuality.fromJson); + compare('imageQualityGroup', imageQualityGroup, ImageQualityGroup.fromJson); + compare( + 'accessControlProcedureType', + accessControlProcedureType, + AccessControlProcedureType.fromJson, + ); + compare('fileData', fileData, FileData.fromJson); + compare('certificateData', certificateData, CertificateData.fromJson); + compare( + 'securityObjectCertificates', + securityObjectCertificates, + SecurityObjectCertificates.fromJson, + ); + compare('file', file, File.fromJson); + compare('application', application, Application.fromJson); + compare('rfidValue', rfidValue, RFIDValue.fromJson); + compare('attribute', attribute, Attribute.fromJson); + compare('authority', authority, Authority.fromJson); + compare('cardProperties', cardProperties, CardProperties.fromJson); + compare('extension', extension, Extension.fromJson); + compare('rfidValidity', rfidValidity, RFIDValidity.fromJson); + compare('certificateChain', certificateChain, CertificateChain.fromJson); + compare('dataField', dataField, DataField.fromJson); + compare('signerInfo', signerInfo, SignerInfo.fromJson); + compare('securityObject', securityObject, SecurityObject.fromJson); + compare('rfidSessionData', rfidSessionData, RFIDSessionData.fromJson); + compare('bytesData', bytesData, BytesData.fromJson); + compare('vdsncData', vdsncData, VDSNCData.fromJson); + compare('docFeature', docFeature, DocFeature.fromJson); + compare('vdsData', vdsData, VDSData.fromJson); + compare('opticalStatus', opticalStatus, OpticalStatus.fromJson); + compare('ageStatus', ageStatus, AgeStatus.fromJson); + compare('rfidStatus', rfidStatus, RFIDStatus.fromJson); + compare('resultsStatus', resultsStatus, ResultsStatus.fromJson); + compare('comparison', comparison, Comparison.fromJson); + compare('rect', rect, Rect.fromJson); + compare('graphicField', graphicField, GraphicField.fromJson); + compare('graphicResult', graphicResult, GraphicResult.fromJson); + compare('rfidOrigin', rfidOrigin, RFIDOrigin.fromJson); + compare('symbol', symbol, Symbol.fromJson); + compare('validity', validity, Validity.fromJson); + compare('value', value, Value.fromJson); + compare('textField', textField, TextField.fromJson); + compare('textSource', textSource, TextSource.fromJson); + compare('textResult', textResult, TextResult.fromJson); + compare('documentType', documentType, DocumentType.fromJson); + compare('coordinate', coordinate, Coordinate.fromJson); + compare('position', position, Position.fromJson); + compare('transactionInfo', transactionInfo, TransactionInfo.fromJson); + compare('results', results, Results.fromJson); + + compare('rfidNotification', rfidNotification, RFIDNotification.fromJson); + compare('paAttribute', paAttribute, PAAttribute.fromJson); + compare('paResourcesIssuer', paResourcesIssuer, PAResourcesIssuer.fromJson); + compare('pkdCertificate', pkdCertificate, PKDCertificate.fromJson); + compare('taChallenge', taChallenge, TAChallenge.fromJson); + compare('paceProtocol', paceProtocol, PACEProtocol.fromJson); + compare('caProtocol', caProtocol, CAProtocol.fromJson); + compare('tccParams', tccParams, TccParams.fromJson); + + compare('deviceRetrievalMethod', deviceRetrievalMethod, + DeviceRetrievalMethod.fromJson); + compare('deviceEngagement', deviceEngagement, DeviceEngagement.fromJson); + compare('nameSpaceMDL', nameSpaceMDL, NameSpaceMDL.fromJson); + compare( + 'documentRequestMDL', documentRequestMDL, DocumentRequestMDL.fromJson); + compare('documentRequest18013MDL', documentRequest18013MDL, + DocumentRequest18013MDL.fromJson); + compare('dataRetrieval', dataRetrieval, DataRetrieval.fromJson); + }); +} diff --git a/test/json.dart b/test/json.dart new file mode 100644 index 0000000000..9bd37b1927 --- /dev/null +++ b/test/json.dart @@ -0,0 +1,1082 @@ +var useOldXcode = true; + +var img1 = useOldXcode + ? "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAAaADAAQAAAABAAAAAQAAAAD5Ip3+AAAADElEQVQIHWP4//8/AAX+Av6fyi0TAAAAAElFTkSuQmCC" + : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAAAGgAwAEAAAAAQAAAAEAAAAAChjw/QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAxJREFUCB1j+P//PwAF/gL+n8otEwAAAABJRU5ErkJggg=="; +var img2 = useOldXcode + ? "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAAaADAAQAAAABAAAAAQAAAAD5Ip3+AAAAC0lEQVQIHWNgAAIAAAUAAY27m/MAAAAASUVORK5CYII=" + : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAAAGgAwAEAAAAAQAAAAEAAAAAChjw/QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAtJREFUCB1jYAACAAAFAAGNu5vzAAAAAElFTkSuQmCC"; +var img3 = useOldXcode + ? "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAAaADAAQAAAABAAAAAQAAAAD5Ip3+AAAADUlEQVQIHWP4z8BQDwAEgAF/OENMJgAAAABJRU5ErkJggg==" + : "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAIRlWElmTU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAAAEgAAAABAAOgAQADAAAAAQABAACgAgAEAAAAAQAAAAGgAwAEAAAAAQAAAAEAAAAAChjw/QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAA1JREFUCB1j+M/AUA8ABIABfzhDTCYAAAAASUVORK5CYII="; + +var faceApiSearchParams = { + "limit": 1, + "threshold": 2, + "groupIds": ["test1", "test2", "test3"], +}; +var faceApiParams = { + "url": "test1", + "mode": "test2", + "threshold": 1, + "serviceTimeout": 2, + "proxy": "test3", + "proxyPassword": "test4", + "proxyType": 3, + "searchParams": faceApiSearchParams, +}; +var livenessParams = { + "checkOVI": true, + "checkMLI": false, + "checkHolo": true, + "checkED": false, + "checkBlackAndWhiteCopy": true, + "checkDynaprint": false, + "checkGeometry": true, + "checkBarcodeBackground": false, +}; +var authenticityParams = { + "useLivenessCheck": true, + "checkUVLuminiscence": false, + "checkIRB900": true, + "checkImagePatterns": false, + "checkFibers": true, + "checkExtMRZ": false, + "checkExtOCR": true, + "checkAxial": false, + "checkBarcodeFormat": true, + "checkIRVisibility": false, + "checkIPI": true, + "checkPhotoEmbedding": false, + "checkPhotoComparison": true, + "checkLetterScreen": false, + "checkSecurityText": true, + "livenessParams": livenessParams, +}; +var glaresCheckParams = {"imgMarginPart": 0.5, "maxGlaringPart": 1.5}; +var imageQA = { + "dpiThreshold": 1, + "angleThreshold": 2, + "documentPositionIndent": 3, + "focusCheck": true, + "glaresCheck": false, + "colornessCheck": true, + "screenCapture": false, + "expectedPass": [1, 2, 3], + "glaresCheckParams": glaresCheckParams, + "brightnessThreshold": 0.5, + "occlusionCheck": true, +}; +var rfidParams = { + "paIgnoreNotificationCodes": [1, 2, 3], +}; +var backendProcessingConfig = { + "url": "test", + "rfidServerSideChipVerification": true, + "mdlVerification": false, + "httpHeaders": {"key1": "val1", "key2": "val2", "key3": "val3"}, + "timeoutConnection": 0.5, +}; +var bsi = { + "generateResult": true, +}; +var processParams = { + "multipageProcessing": true, + "debugSaveImages": false, + "debugSaveLogs": true, + "returnUncroppedImage": false, + "uvTorchEnabled": true, + "debugSaveCroppedImages": false, + "disableFocusingCheck": true, + "debugSaveRFIDSession": false, + "doublePageSpread": true, + "manualCrop": false, + "integralImage": true, + "returnCroppedBarcode": false, + "checkRequiredTextFields": false, + "depersonalizeLog": true, + "generateDoublePageSpreadImage": false, + "alreadyCropped": true, + "matchTextFieldMask": false, + "updateOCRValidityByGlare": false, + "noGraphics": true, + "multiDocOnImage": false, + "parseBarcodes": false, + "shouldReturnPackageForReprocess": true, + "disablePerforationOCR": false, + "respectImageQuality": true, + "strictImageQuality": true, + "splitNames": false, + "useFaceApi": false, + "useAuthenticityCheck": true, + "checkHologram": false, + "generateNumericCodes": true, + "strictBarcodeDigitalSignatureCheck": false, + "selectLongestNames": true, + "generateDTCVC": false, + "strictDLCategoryExpiry": true, + "generateAlpha2Codes": false, + "disableAuthResolutionFilter": true, + "strictSecurityChecks": false, + "returnTransliteratedFields": true, + "checkCaptureProcessIntegrity": false, + "strictExpiryDate": true, + "debugSaveBinarySession": false, + "checkVDS": true, + "strictAgeCheck": false, + "bsiTr03135": bsi, + "measureSystem": 1, + "barcodeParserType": 3, + "perspectiveAngle": 4, + "minDPI": 5, + "imageDpiOutMax": 6, + "forceDocID": 6, + "pdfPagesLimit": 7, + "forceDocFormat": 3, + "shiftExpiryDate": 9, + "minimalHolderAge": 10, + "imageOutputMaxHeight": 11, + "imageOutputMaxWidth": 12, + "processAuth": 13, + "convertCase": 3, + "logLevel": "FatalError", + "mrzDetectMode": 1, + "dateFormat": "test1", + "scenario": "Mrz", + "captureButtonScenario": "Locate", + "timeout": 15, + "timeoutFromFirstDetect": 16, + "timeoutFromFirstDocType": 17, + "documentAreaMin": 18, + "timeoutLiveness": 19, + "documentIDList": [1, 2, 3], + "barcodeTypes": [4, 5, 6], + "fieldTypesFilter": [7, 8, 9], + "resultTypeOutput": [10, 9, 8], + "mrzFormatsFilter": ["1x30", "3x30", "2x30"], + "documentGroupFilter": [135, 136, 137], + "lcidIgnoreFilter": [10011, 1078, 1052], + "lcidFilter": [1118, 5121, 15361], + "fieldTypesIgnoreFilter": [22, 23, 24], + "imageQA": imageQA, + "rfidParams": rfidParams, + "faceApiParams": faceApiParams, + "backendProcessingConfig": backendProcessingConfig, + "authenticityParams": authenticityParams, + "customParams": {"test1": true, "test2": 1, "test3": "test"}, +}; +var font1 = {"name": "AppleSDGothicNeo-Thin", "size": 10, "style": 2}; +var font2 = {"name": "Copperplate-Light", "size": 20, "style": 1}; +var customizationColors = { + "rfidProcessingScreenBackground": 0xff000000, + "rfidProcessingScreenHintLabelText": 0xff000001, + "rfidProcessingScreenHintLabelBackground": 0xff000002, + "rfidProcessingScreenProgressLabelText": 0xff000003, + "rfidProcessingScreenProgressBar": 0xff000004, + "rfidProcessingScreenProgressBarBackground": 0xff000005, + "rfidProcessingScreenResultLabelText": 0xff000006, + "rfidProcessingScreenLoadingBar": 0xff000007, + "rfidEnableNfcTitleText": 0xff000008, + "rfidEnableNfcDescriptionText": 0xff000009, + "rfidEnableNfcButtonText": 0xff000010, + "rfidEnableNfcButtonBackground": 0xff000011, + "mdlProcessingScreenBackground": 0xff000012, + "mdlProcessingScreenHintLabelText": 0xff000013, + "mdlProcessingScreenHintLabelBackground": 0xff000014, + "mdlProcessingScreenProgressLabelText": 0xff000015, + "mdlProcessingScreenResultLabelText": 0xff000016, + "mdlProcessingScreenLoadingBar": 0xff000017, + "mdlEnableNfcTitleText": 0xff000018, + "mdlEnableNfcDescriptionText": 0xff000019, + "mdlEnableNfcButtonText": 0xff000020, + "mdlEnableNfcButtonBackground": 0xff000021, + "nextPageIdCardFront": 0xff000022, + "nextPageIdCardBack": 0xff000023, + "nextPagePassportShift": 0xff000024, + "nextPagePassportFlip": 0xff000025, +}; +var customizationFonts = { + "rfidProcessingScreenHintLabel": font1, + "rfidProcessingScreenProgressLabel": font2, + "rfidProcessingScreenResultLabel": font1, + "rfidEnableNfcTitleText": font2, + "rfidEnableNfcDescriptionText": font1, + "rfidEnableNfcButtonText": font2, + "mdlProcessingScreenHintLabel": font1, + "mdlProcessingScreenProgressLabel": font2, + "mdlProcessingScreenResultLabel": font1, + "mdlEnableNfcTitleText": font2, + "mdlEnableNfcDescriptionText": font1, + "mdlEnableNfcButtonText": font2, +}; +var customizationImages = { + "helpAnimation": img1, + "livenessAnimation": img2, + "borderBackground": img1, + "torchButtonOn": img2, + "torchButtonOff": img1, + "captureButton": img2, + "switchButton": img1, + "closeButton": img2, + "multipageButton": img1, + "rfidProcessingScreenFailureImage": img1, + "rfidEnableNfcImage": img2, + "rfidDisableNfcImage": img1, + "mdlProcessingScreenFailureImage": img2, + "mdlEnableNfcImage": img1, + "mdlDisableNfcImage": img2, + "nextPageIdCardFront": img1, + "nextPageIdCardBack": img2, + "nextPagePassportShift": img1, + "nextPagePassportFlipStart": img2, + "nextPagePassportFlipClean": img1, + "nextPagePassportFlipTop": img2, + "nextPagePassportFlipBottom": img1, +}; +var customizationTimings = { + "nextPageIdCardStartDelay": 0, + "nextPageIdCardEndDelay": 1, + "nextPagePassportShiftStartDelay": 2, + "nextPagePassportShiftEndDelay": 3, + "nextPagePassportFlipStartDelay": 4, + "nextPagePassportFlipEndDelay": 5, +}; +var customizationContentModes = { + "nextPageIdCardFront": 0, + "nextPageIdCardBack": 1, +}; +var customizationMatrices = { + "nextPageIdCardFront": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9], + "nextPageIdCardBack": [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9], +}; +var customization = { + "showStatusMessages": true, + "showResultStatusMessages": false, + "showHelpAnimation": true, + "showNextPageAnimation": false, + "showBackgroundMask": true, + "cameraFrameBorderWidth": 1, + "cameraFrameLineLength": 2, + "cameraFrameShapeType": 1, + "cameraFrameOffsetWidth": 3, + "status": "test1", + "resultStatus": "test2", + "multipageButtonText": "test3", + "cameraFrameDefaultColor": 0xff000000, + "cameraFrameActiveColor": 0xff000001, + "statusTextColor": 0xff000002, + "resultStatusTextColor": 0xff000003, + "resultStatusBackgroundColor": 0xff000004, + "multipageButtonBackgroundColor": 0xff000005, + "tintColor": 0xff000006, + "activityIndicatorColor": 0xff000007, + "statusBackgroundColor": 0xff000008, + "cameraPreviewBackgroundColor": 0xff000009, + "backgroundMaskColor": 0xff000010, + "multipageButtonTextColor": 0xff000011, + "statusPositionMultiplier": 0.5, + "resultStatusPositionMultiplier": 1.5, + "toolbarSize": 2.5, + "backgroundMaskAlpha": 3.5, + "customStatusPositionMultiplier": 4.5, + "cameraFrameVerticalPositionMultiplier": 5.5, + "cameraFrameLandscapeAspectRatio": 6.5, + "cameraFramePortraitAspectRatio": 7.5, + "cameraFrameCornerRadius": 8.5, + "livenessAnimationPositionMultiplier": 9.5, + "nextPageAnimationStartDelay": 10.5, + "nextPageAnimationEndDelay": 11.5, + "activityIndicatorPortraitPositionMultiplier": 12.5, + "activityIndicatorLandscapePositionMultiplier": 13.5, + "cameraPreviewVerticalPositionMultiplier": 14.5, + "multipageButtonPositionMultiplier": 15.5, + "multipageAnimationFrontImage": img1, + "multipageAnimationBackImage": img2, + "borderBackgroundImage": img3, + "helpAnimationImage": img1, + "closeButtonImage": img2, + "captureButtonImage": img3, + "cameraSwitchButtonImage": img1, + "torchButtonOnImage": img2, + "torchButtonOffImage": img3, + "changeFrameButtonExpandImage": img1, + "changeFrameButtonCollapseImage": img2, + "livenessAnimationImage": img3, + "multipageButtonImage": img1, + "customLabelStatus": "test3", + "cameraFrameLineCap": 2, + "uiCustomizationLayer": {"test": "test"}, + "statusTextFont": font1, + "resultStatusTextFont": font2, + "multipageButtonTextFont": font1, + "helpAnimationImageContentMode": 0, + "multipageAnimationFrontImageContentMode": 1, + "multipageAnimationBackImageContentMode": 2, + "livenessAnimationImageContentMode": 3, + "borderBackgroundImageContentMode": 4, + "helpAnimationImageMatrix": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9], + "multipageAnimationFrontImageMatrix": [ + 2.1, + 2.2, + 2.3, + 2.4, + 2.5, + 2.6, + 2.7, + 2.8, + 2.9, + ], + "multipageAnimationBackImageMatrix": [ + 3.1, + 3.2, + 3.3, + 3.4, + 3.5, + 3.6, + 3.7, + 3.8, + 3.9, + ], + "livenessAnimationImageMatrix": [4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9], + "borderBackgroundImageMatrix": [5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9], + "colors": customizationColors, + "fonts": customizationFonts, + "images": customizationImages, + "timings": customizationTimings, + "contentModes": customizationContentModes, + "matrices": customizationMatrices, +}; +var cameraSize = {"width": 0, "height": 1}; +var functionality = { + "pictureOnBoundsReady": true, + "showTorchButton": false, + "showCloseButton": true, + "videoCaptureMotionControl": false, + "showCaptureButton": true, + "showChangeFrameButton": false, + "showSkipNextPageButton": true, + "useAuthenticator": true, + "skipFocusingFrames": true, + "showCameraSwitchButton": false, + "displayMetadata": true, + "isZoomEnabled": false, + "isCameraTorchCheckDisabled": true, + "recordScanningProcess": false, + "manualMultipageMode": true, + "singleResult": false, + "torchTurnedOn": false, + "preventScreenRecording": true, + "homeIndicatorAutoHide": false, + "hideStatusBar": true, + "showCaptureButtonDelayFromDetect": 0, + "showCaptureButtonDelayFromStart": 1, + "rfidTimeout": 2, + "forcePagesCount": 3, + "orientation": 1, + "captureMode": 2, + "cameraMode": 0, + "cameraPositionIOS": 1, + "cameraFrame": "id1", + "btDeviceName": "test", + "zoomFactor": 0.5, + "exposure": 1.5, + "videoRecordingSizeDownscaleFactor": 2.5, + "mdlTimeout": 3.5, + "excludedCamera2Models": ["test1", "test2", "test3"], + "cameraSize": cameraSize, + "videoSessionPreset": 6, +}; +var eDLDataGroups = { + "DG1": true, + "DG2": false, + "DG3": true, + "DG4": false, + "DG5": true, + "DG6": false, + "DG7": true, + "DG8": false, + "DG9": true, + "DG10": false, + "DG11": true, + "DG12": false, + "DG13": true, + "DG14": false, +}; +var ePassportDataGroups = { + "DG1": true, + "DG2": false, + "DG3": true, + "DG4": false, + "DG5": true, + "DG6": false, + "DG7": true, + "DG8": false, + "DG9": true, + "DG10": false, + "DG11": true, + "DG12": false, + "DG13": true, + "DG14": false, + "DG15": true, + "DG16": false, +}; +var eIDDataGroups = { + "DG1": true, + "DG2": false, + "DG3": true, + "DG4": false, + "DG5": true, + "DG6": false, + "DG7": true, + "DG8": false, + "DG9": true, + "DG10": false, + "DG11": true, + "DG12": false, + "DG13": true, + "DG14": false, + "DG15": true, + "DG16": false, + "DG17": true, + "DG18": false, + "DG19": true, + "DG20": false, + "DG21": true, +}; +var dtcDataGroup = { + "DG17": true, + "DG18": false, + "DG22": false, + "DG23": true, + "DG24": false, +}; +var rfidScenario = { + "paceStaticBinding": true, + "onlineTA": false, + "writeEid": true, + "universalAccessRights": false, + "authorizedRestrictedIdentification": true, + "auxVerificationCommunityID": false, + "auxVerificationDateOfBirth": true, + "skipAA": false, + "strictProcessing": true, + "pkdDSCertPriority": false, + "pkdUseExternalCSCA": true, + "trustedPKD": false, + "passiveAuth": true, + "useSFI": false, + "readEPassport": true, + "readEID": false, + "readEDL": true, + "authorizedSTSignature": false, + "authorizedSTQSignature": true, + "authorizedWriteDG17": false, + "authorizedWriteDG18": true, + "authorizedWriteDG19": false, + "authorizedWriteDG20": true, + "authorizedWriteDG21": false, + "authorizedVerifyAge": true, + "authorizedVerifyCommunityID": false, + "authorizedPrivilegedTerminal": true, + "authorizedCANAllowed": false, + "authorizedPINManagement": true, + "authorizedInstallCert": false, + "authorizedInstallQCert": true, + "applyAmendments": false, + "autoSettings": true, + "proceedReadingAlways": false, + "readDTC": true, + "mrzStrictCheck": false, + "loadCRLFromRemote": true, + "independentSODStatus": false, + "readingBuffer": -1, + "onlineTAToSignDataType": 3, + "defaultReadingBufferSize": 2, + "signManagementAction": 3, + "profilerType": 2, + "authProcType": 3, + "baseSMProcedure": 4, + "pacePasswordType": 5, + "terminalType": 1, + "password": "test1", + "pkdPA": "test2", + "pkdEAC": "test3", + "mrz": "test4", + "eSignPINDefault": "test5", + "eSignPINNewValue": "test6", + "cardAccess": "test7", + "mrzHash": "test8", + "documentNumber": "test9", + "dateOfBirth": "test10", + "dateOfExpiry": "test11", + "eDLDataGroups": eDLDataGroups, + "ePassportDataGroups": ePassportDataGroups, + "eIDDataGroups": eIDDataGroups, + "dtcDataGroups": dtcDataGroup, +}; + +var initConfig = { + "delayedNNLoad": false, + "licenseUpdate": true, + "licenseUpdateTimeout": 1.5, + "customDb": img1, + "blackList": {"key1": "val1", "key2": "val2", "key3": "val3"}, + "databasePath": "test", + "license": img2, + "useBleDevice": true, +}; +var onlineProcessingConfig = { + "mode": 1, + "url": "test", + "imageFormat": 1, + "imageCompressionQuality": 1.5, + "processParams": processParams, + "requestHeaders": {"key1": "val1", "key2": "val2", "key3": "val3"}, +}; +var imageInputData = {"image": img1, "light": 128, "pageIndex": 2}; +var recognizeConfig = { + "scenario": "Mrz", + "livePortrait": img1, + "extPortrait": img2, + "oneShotIdentification": true, + "dtc": img1, + "image": img3, + "data": img1, + "images": [img1, img2, img3], + "dataList": [img3, img2, img1], + "imageInputData": [imageInputData, imageInputData, imageInputData], +}; +var recognizeConfig2 = { + "onlineProcessingConfig": onlineProcessingConfig, + "livePortrait": img1, + "extPortrait": img2, + "oneShotIdentification": true, + "image": img3, + "data": img1, + "images": [img1, img2, img3], + "imageInputData": [imageInputData, imageInputData, imageInputData], +}; +var scannerConfig = { + "scenario": "Mrz", + "onlineProcessingConfig": onlineProcessingConfig, + "livePortrait": img1, + "extPortrait": img2, + "cameraId": 1, +}; +var finalizeConfig = { + "rawImages": true, + "video": false, + "rfidSession": true, + "mdlSession": false, +}; + +var documentsDatabase = { + "databaseID": "test1", + "version": "test2", + "date": "test3", + "databaseDescription": "test4", + "countriesNumber": 1, + "documentsNumber": 2, + "size": 3, +}; +var docReaderVersion = { + "api": "test1", + "core": "test2", + "coreMode": "test3", + "database": documentsDatabase, +}; +var docReaderScenario = { + "uvTorch": true, + "frameOrientation": 2, + "faceExt": false, + "multiPageOff": false, + "seriesProcessMode": true, + "frameKWHLandscape": 0.5, + "frameKWHPortrait": 1.5, + "frameKWHDoublePageSpreadPortrait": 2.5, + "frameKWHDoublePageSpreadLandscape": 3.5, + "name": "test1", + "caption": "test2", + "description": "test3", + "manualCrop": false, +}; +var license = { + "expiryDate": "test1", + "countryFilter": ["test2", "test3", "test4"], + "isRfidAvailable": true, +}; +var docReaderException = {"code": 1, "message": "test1"}; +var rfidException = {"code": 2, "message": "test2"}; +var prepareProgress = {"downloadedBytes": 1, "totalBytes": 2, "progress": 50}; + +var authenticityElement = { + "status": 1, + "elementType": 2, + "elementDiagnose": 3, + "elementTypeName": "Photo element", + "elementDiagnoseName": "Error of internal data processing", +}; +var authenticityCheck = { + "type": 1, + "status": 2, + "typeName": "UV dull paper check", + "pageIndex": 3, + "elements": [authenticityElement, authenticityElement, authenticityElement], +}; +var authenticityResult = { + "status": 2, + "checks": [authenticityCheck, authenticityCheck, authenticityCheck], +}; +var pdf417Info = {"errorLevel": 2, "columns": 3, "rows": 4}; +var barcodeField = { + "barcodeType": 5, + "status": -6001, + "pageIndex": 2, + "pdf417Info": pdf417Info, + "data": img1, +}; +var barcodeResult = { + "fields": [barcodeField, barcodeField, barcodeField], +}; +var rect = {"bottom": 0, "top": 1, "left": 2, "right": 3}; +var imageQuality = { + "featureType": 1, + "result": 2, + "type": 3, + "boundRects": [rect, rect, rect], +}; +var imageQualityGroup = { + "count": 1, + "result": 2, + "pageIndex": 3, + "imageQualityList": [imageQuality, imageQuality, imageQuality], +}; +var accessControlProcedureType = { + "activeOptionIdx": 1, + "type": 2, + "status": 1, + "notifications": [1, 2, 3], +}; +var fileData = {"data": "test", "length": 2, "type": 3, "status": 4}; +var certificateData = {"data": "test", "length": 1}; +var securityObjectCertificates = {"securityObject": certificateData}; +var file = { + "fileData": fileData, + "fileID": "test1", + "notifications": [1, 2, 3], + "pAStatus": 1, + "readingStatus": 2, + "readingTime": 3, + "type": 4, + "typeName": "Biometry - Iris Data (DG4)", + "docFieldsText": [4, 5, 6], + "docFieldsGraphics": [7, 8, 9], + "docFieldsOriginals": [10, 11, 12], + "certificates": securityObjectCertificates, +}; +var application = { + "applicationID": "test1", + "dataHashAlgorithm": "test2", + "files": [file, file, file], + "status": 1, + "type": 2, + "unicodeVersion": "test3", + "version": "test4", +}; +var rfidValue = { + "data": "test1", + "length": 1, + "status": 2, + "type": 3, + "format": "test2", +}; +var attribute = {"type": "test", "value": rfidValue}; +var authority = { + "attributes": [attribute, attribute, attribute], + "data": "test", + "friendlyName": rfidValue, +}; +var cardProperties = { + "aTQA": 1, + "bitRateR": 2, + "bitRateS": 3, + "chipTypeA": 4, + "mifareMemory": 5, + "rfidType": 6, + "sAK": 7, + "support4": true, + "supportMifare": false, + "aTQB": "test1", + "aTR": "test2", + "baudrate1": "test3", + "baudrate2": "test4", + "uID": "test5", +}; +var extension = {"data": "test1", "type": "test2"}; +var rfidValidity = {"notAfter": rfidValue, "notBefore": rfidValue}; +var certificateChain = { + "type": 1, + "extensions": [extension, extension, extension], + "fileName": rfidValue, + "issuer": authority, + "notifications": [1, 2, 3], + "origin": 2, + "paStatus": 3, + "serialNumber": "test1", + "signatureAlgorithm": "test2", + "subject": authority, + "subjectPKAlgorithm": "test3", + "validity": rfidValidity, + "version": 4, +}; +var dataField = {"data": "test", "fieldType": 1}; +var signerInfo = { + "dataToHash": "test1", + "digestAlgorithm": "test2", + "version": 1, + "paStatus": 2, + "signatureAlgorithm": "test3", + "issuer": authority, + "serialNumber": rfidValue, + "signature": rfidValue, + "subjectKeyIdentifier": rfidValue, + "signedAttributes": [extension, extension, extension], + "certificateChain": [certificateChain, certificateChain, certificateChain], + "notifications": [1, 2, 3], +}; +var securityObject = { + "fileReference": 1, + "objectType": "test", + "version": 2, + "signerInfos": [signerInfo, signerInfo, signerInfo], + "notifications": [1, 2, 3], +}; +var rfidSessionData = { + "accessControls": [ + accessControlProcedureType, + accessControlProcedureType, + accessControlProcedureType, + ], + "applications": [application, application, application], + "securityObjects": [securityObject, securityObject, securityObject], + "dataFields": [dataField, dataField, dataField], + "dataGroups": [1, 2, 3], + "cardProperties": cardProperties, + "totalBytesReceived": 1, + "totalBytesSent": 2, + "status": 1, + "extLeSupport": 1, + "processTime": 4, +}; +var bytesData = {"data": "test", "length": 1, "status": 2, "type": 3}; +var vdsncData = { + "type": "test1", + "version": 1, + "issuingCountry": "test2", + "message": {"key1": "val1", "key2": "val2", "key3": "val3"}, + "signatureAlgorithm": "test3", + "signature": bytesData, + "certificate": bytesData, + "certificateChain": [certificateChain, certificateChain, certificateChain], + "notifications": [3000000001, 3000000002, 3000000003], +}; +var docFeature = {"type": 0, "data": bytesData}; +var vdsData = { + "type": 1, + "docType": 2, + "featureRef": 3, + "version": 4, + "issuingCountry": "test1", + "docIssueDate": "test2", + "signature": bytesData, + "signatureDate": "test3", + "signer": "test4", + "certificate": "test5", + "certificateChain": [certificateChain, certificateChain, certificateChain], + "docFeatures": [docFeature, docFeature, docFeature], + "notifications": [3000000001, 3000000002, 3000000003], +}; +var opticalStatus = { + "overallStatus": 0, + "mrz": 1, + "text": 2, + "docType": 0, + "security": 1, + "imageQA": 2, + "expiry": 0, + "vds": 1, + "pagesCount": 3, +}; +var ageStatus = { + "threshold": 0, + "overThreshold": 1, + "over18": 2, + "over21": 0, + "over25": 1, + "over65": 2, +}; +var rfidStatus = { + "overallStatus": 0, + "pa": 1, + "ca": 2, + "aa": 0, + "ta": 1, + "bac": 2, + "pace": 0, +}; +var resultsStatus = { + "overallStatus": 0, + "optical": 1, + "rfid": 2, + "portrait": 0, + "stopList": 1, + "mDL": 2, + "age": 0, + "captureProcessIntegrity": 1, + "detailsOptical": opticalStatus, + "detailsAge": ageStatus, + "detailsRFID": rfidStatus, +}; +var comparison = {"sourceTypeLeft": 0, "sourceTypeRight": 1, "status": 2}; +var graphicField = { + "sourceType": 0, + "fieldType": 201, + "fieldName": "Portrait", + "light": 128, + "lightName": "UV", + "pageIndex": 3, + "originalPageIndex": 4, + "value": img1, + "fieldRect": rect, +}; +var graphicResult = { + "fields": [graphicField, graphicField, graphicField], +}; +var rfidOrigin = {"dg": 1, "dgTag": 2, "entryView": 3, "tagEntry": 4}; +var symbol = {"rect": rect, "code": 1, "probability": 2}; +var validity = {"sourceType": 1, "status": 2}; +var value = { + "sourceType": 3, + "value": "test1", + "originalValue": "test2", + "pageIndex": 2, + "boundRect": rect, + "rfidOrigin": rfidOrigin, + "originalSymbols": [symbol, symbol, symbol], + "probability": 1, +}; +var textField = { + "fieldType": 1, + "fieldName": "Issuing state code", + "lcid": 10011, + "lcidName": "Abkhazian (Cyrillic)", + "value": "test3", + "getValue": value, + "values": [value, value, value], + "status": 2, + "comparisonList": [comparison, comparison, comparison], + "validityList": [validity, validity, validity], + "comparisonStatus": 0, + "validityStatus": 1, +}; +var textSource = { + "sourceType": validity["sourceType"], + "source": "sourceType", + "validityStatus": 1, +}; +var documentReaderTextSource2 = { + "sourceType": comparison["sourceTypeLeft"], + "source": "sourceTypeLeft", + "validityStatus": 1, +}; +var documentReaderTextSource3 = { + "sourceType": comparison["sourceTypeRight"], + "source": "sourceTypeRight", + "validityStatus": 1, +}; +var textResult = { + "status": 0, + "comparisonStatus": 1, + "validityStatus": 2, + "availableSourceList": [ + textSource, + documentReaderTextSource2, + documentReaderTextSource3, + ], + "fields": [textField, textField, textField], +}; +var documentType = { + "name": "test1", + "documentID": 1, + "ICAOCode": "test2", + "FDSID": [1, 2, 3], + "dType": 11, + "dFormat": 2, + "dMRZ": true, + "isDeprecated": false, + "dDescription": "test3", + "dYear": "test4", + "dCountryName": "test5", + "pageIndex": 3, +}; +var coordinate = {"x": 1, "y": 2}; +var position = { + "docFormat": 0, + "resultStatus": 1, + "width": 2, + "height": 3, + "angle": 0.5, + "dpi": 4, + "inverse": 5, + "perspectiveTr": 6, + "objArea": 7, + "objIntAngleDev": 8, + "pageIndex": 9, + "center": coordinate, + "leftTop": coordinate, + "leftBottom": coordinate, + "rightTop": coordinate, + "rightBottom": coordinate, +}; +var transactionInfo = { + "transactionId": "test1", + "tag": "test2", + "sessionLogFolder": "test3", +}; +var results = { + "chipPage": 0, + "processingFinishedStatus": 2, + "elapsedTime": 3, + "elapsedTimeRFID": 4, + "morePagesAvailable": 5, + "graphicResult": graphicResult, + "textResult": textResult, + "documentPosition": [position], + "barcodePosition": [position, position], + "mrzPosition": [position, position, position], + "imageQuality": [imageQualityGroup, imageQualityGroup, imageQualityGroup], + "documentType": [documentType, documentType, documentType], + "rawResult": "test2", + "bsiTr03135Results": "test3", + "rfidSessionData": rfidSessionData, + "authenticityResult": authenticityResult, + "barcodeResult": barcodeResult, + "status": resultsStatus, + "vdsncData": vdsncData, + "vdsData": vdsData, + "dtcData": img1, + "transactionInfo": transactionInfo, +}; + +var rfidNotification = { + "notificationCode": 65536, + "dataFileType": 1, + "progress": 2, +}; +var paAttribute = {"type": "test1", "value": "test2"}; +var paResourcesIssuer = { + "data": img1, + "friendlyName": "test", + "attributes": [paAttribute, paAttribute, paAttribute], +}; +var pkdCertificate = { + "binaryData": img1, + "resourceType": 0, + "privateKey": img2, +}; +var taChallenge = { + "data": img1, + "auxPCD": "test1", + "challengePICC": "test2", + "hashPK": "test3", + "idPICC": "test4", +}; +var paceProtocol = { + "version": "123", + "stdDomainParams": "test2", + "keyAlgorithm": "test3", +}; +var caProtocol = { + "version": "123", + "scheme": "test2", + "keyAlgorithm": "test3", + "chipIndividual": true, +}; +var tccParams = { + "serviceUrlTA": "test1", + "serviceUrlPA": "test2", + "pfxCertUrl": "test3", + "pfxPassPhrase": "test4", + "pfxCert": img1, +}; +var deviceRetrievalMethod = { + "type": 1, + "version": 2, + "cmdMaxLength": 3, + "respMaxLength": 4, + "clientModeSupport": true, + "clientModeUUID": "test1", + "serverModeSupport": true, + "serverModeUUID": "test2", +}; +var deviceEngagement = { + "deviceRetrievalMethods": [ + deviceRetrievalMethod, + deviceRetrievalMethod, + deviceRetrievalMethod, + ], +}; +var nameSpaceMDL = { + "name": "test1", + "map": {"test2": 0, "test3": 1, "test4": 0}, +}; +var documentRequestMDL = { + "docType": "test1", + "namespaces": [nameSpaceMDL, nameSpaceMDL, nameSpaceMDL], +}; +var documentRequest18013MDL = { + "docType": "org.iso.18013.5.1.mDL", + "namespaces": [nameSpaceMDL, nameSpaceMDL, nameSpaceMDL], + "familyName": 0, + "givenName": 1, + "birthDate": 1, + "issueDate": 0, + "expiryDate": 1, + "issuingCountry": 0, + "issuingAuthority": 0, + "documentNumber": 0, + "portrait": 1, + "drivingPrivileges": 0, + "unDistinguishingSign": 0, + "administrativeNumber": 1, + "sex": 0, + "height": 0, + "weight": 0, + "eyeColour": 1, + "hairColour": 0, + "birthPlace": 1, + "residentAddress": 0, + "portraitCaptureDate": 0, + "ageInYears": 1, + "ageBirthYear": 1, + "ageOver18": 1, + "issuingJurisdiction": 0, + "nationality": 0, + "residentCity": 1, + "residentState": 0, + "residentPostalCode": 0, + "residentCountry": 1, + "biometricTemplateFace": 0, + "biometricTemplateIris": 0, + "biometricTemplateFinger": 1, + "biometricTemplateSignatureSign": 1, + "familyNameNationalCharacter": 0, + "givenNameNationalCharacter": 1, + "signatureUsualMark": 0, +}; +var dataRetrieval = { + "docRequestPreset": 0, + "intentToRetain": 1, + "deviceRetrieval": 2, + "requests": [documentRequestMDL, documentRequest18013MDL], +}; diff --git a/test/nullable.dart b/test/nullable.dart new file mode 100644 index 0000000000..4c232f0b7d --- /dev/null +++ b/test/nullable.dart @@ -0,0 +1,58 @@ +Map?> nullableMap = { + "initConfig": ["databasePath", "customDb", "licenseUpdateTimeout"], + "recognizeConfig": [ + "onlineProcessingConfig", + "livePortrait", + "extPortrait", + "data", + "images", + "dataList", + "imageInputData", + ], + "recognizeConfig2": ["scenario", "image"], + "scannerConfig": ["scenario", "livePortrait", "extPortrait"], + "scannerConfig2": ["onlineProcessingConfig"], + "onlineProcessingConfig": ["requestHeaders"], + "faceApiSearchParams": ["groupIds"], + "faceApiParams": ["searchParams", "proxy", "proxyPassword", "proxyType"], + "livenessParams!": [], + "authenticityParams!": ["livenessParams"], + "glaresCheckParams!": [], + "rfidParams!": [], + "imageQA!": [], + "backendProcessingConfig!": ["url", "mdlVerification"], + "bsi!": [], + "processParams!": ["imageQA", "authenticityParams"], + "rfidScenario!": [ + "defaultReadingBufferSize", + "eDLDataGroups", + "ePassportDataGroups", + "eIDDataGroups", + "dtcDataGroups", + ], + "customization!": ["colors", "fonts", "images"], + "functionality!": [], + "documentsDatabase!": ["countriesNumber", "documentsNumber"], + "docReaderVersion!": [], + "license": ["expiryDate", "countryFilter"], + "vdsncData": ["type", "issuingCountry", "signatureAlgorithm"], + "graphicField": ["fieldRect"], + "symbol": ["rect"], + "value": ["boundRect", "rfidOrigin"], + "textSource": ["source"], + "documentType": [ + "name", + "iCAOCode", + "fDSID", + "dDescription", + "dYear", + "dCountryName", + ], + "transactionInfo!": [], + "results": ["authenticityResult", "bsiTr03135Results"], + "paResourcesIssuer": ["friendlyName"], + "pkdCertificate": ["privateKey"], + "tccParams!": [], + "deviceRetrievalMethod!": ["type", "version"], + "documentRequest18013MDL!": ["docType", "namespaces"], +}; diff --git a/test/utils.dart b/test/utils.dart new file mode 100644 index 0000000000..3488277ce3 --- /dev/null +++ b/test/utils.dart @@ -0,0 +1,72 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meta/meta.dart'; + +import 'nullable.dart'; + +Future writeJson(String name, Map contents) async { + var file = File("test/json/" + name + ".json"); + var jsonDir = Directory.fromUri(Uri(path: "test/json")); + if (!await jsonDir.exists()) jsonDir.create(); + await file.writeAsString(jsonEncode(contents)); +} + +@isTest +void compare( + String name, + Map json, + T Function(dynamic) fromJson, +) { + test(name, () async { + var toJson = (input) => input.toJson(); + var actual = toJson(fromJson(json)); + expect(json, actual); + await writeJson(name, json); + + var nullable = nullableMap[name]; + bool invert = nullableMap[name + "!"] != null; + if (invert) nullable = nullableMap[name + "!"]; + if (nullable != null) { + Map copy = {}; + if (!invert) { + copy = toJson(fromJson(json)); + for (String item in nullable) { + copy.remove(item); + } + } else { + for (String item in nullable) { + copy[item] = json[item]; + } + } + var actual = toJson(fromJson(copy)); + expect(copy, actual); + writeJson(name + "Nullable", copy); + } + }); +} + +@isTest +void compareParams( + String name, + Map json, + T Function(dynamic) fromJson, { + List? skip, +}) { + test(name, () { + var toJson = (input) => input.toJson(); + var getTestSetters = (input) => input.testSetters; + var object = fromJson(json); + var actual = toJson(object); + var testSetters = getTestSetters(object); + if (skip != null) { + for (String item in skip) { + (actual as Map).remove(item); + (testSetters as Map).remove(item); + } + } + expect(json, actual); + expect(json, testSetters); + writeJson(name, json); + }); +}