diff --git a/README.md b/README.md index 215d15d..08fadfc 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ You can use native camera to scan the documents or image from gallery for extrac 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. -# Content +# Contents * [How to build demo application](#how-to-build-demo-application) * [Troubleshooting license issues](#troubleshooting-license-issues) * [Documentation](#documentation) @@ -34,8 +34,8 @@ $ pod install ### 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 application (Bundle) ID, which you use, is specified in the license. +1. The OS, which you use, is specified in the license (e.g., Android and/or iOS). +2. The application (Bundle) ID, which you use, is specified in the license. 3. The license is valid (not expired). 4. The date and time on the device, where you run the application, are valid. 5. You use the latest release version of the Document Reader SDK. diff --git a/RNDocumentReaderApi.podspec b/RNDocumentReaderApi.podspec index 37d6fd4..d8b37e8 100644 --- a/RNDocumentReaderApi.podspec +++ b/RNDocumentReaderApi.podspec @@ -14,6 +14,6 @@ Pod::Spec.new do |s| s.source = { :http => 'file:' + __dir__ } s.ios.deployment_target = '9.0.0' s.source_files = "ios/*.{h,m}" - s.dependency 'DocumentReader', '5.2.1331' + s.dependency 'DocumentReader', '5.3.1509' s.dependency 'React' end diff --git a/android/build.gradle b/android/build.gradle index a3df07c..11d0bdd 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -39,7 +39,7 @@ dependencies { //noinspection GradleDynamicVersion implementation 'com.facebook.react:react-native:+' //noinspection GradleDependency - implementation('com.regula.documentreader:api:5.2.2995') { + implementation('com.regula.documentreader:api:5.3.3597') { transitive = true } } diff --git a/android/src/main/java/com/regula/documentreader/JSONConstructor.java b/android/src/main/java/com/regula/documentreader/JSONConstructor.java index 49622a1..1e29c3b 100644 --- a/android/src/main/java/com/regula/documentreader/JSONConstructor.java +++ b/android/src/main/java/com/regula/documentreader/JSONConstructor.java @@ -19,8 +19,6 @@ 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.DocumentReaderJsonResult; -import com.regula.documentreader.api.results.DocumentReaderJsonResultGroup; import com.regula.documentreader.api.results.DocumentReaderNotification; import com.regula.documentreader.api.results.DocumentReaderResults; import com.regula.documentreader.api.results.DocumentReaderScenarioFull; @@ -63,6 +61,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -133,8 +132,8 @@ static JSONObject resultsToJsonObject(DocumentReaderResults results, Context con jsonObject.put("graphicResult", generateDocumentReaderGraphicResult(results.graphicResult, context)); if (results.imageQuality != null) jsonObject.put("imageQuality", generateImageQualityGroup(results.imageQuality, context)); - if (results.jsonResult != null) - jsonObject.put("jsonResult", generateDocumentReaderJsonResult(results.jsonResult, context)); + if (results.rawResult != null) + jsonObject.put("rawResult", results.rawResult); if (results.mrzPosition != null) jsonObject.put("mrzPosition", generateElementPosition(results.mrzPosition)); if (results.rfidSessionData != null) @@ -257,8 +256,8 @@ static private JSONObject generateDocumentReaderGraphicField(DocumentReaderGraph result.put("lightName", eRPRM_Lights.getTranslation(context, documentReaderGraphicField.light)); result.put("pageIndex", documentReaderGraphicField.pageIndex); result.put("value", documentReaderGraphicField.imageBase64()); - if (documentReaderGraphicField.getRect() != null) - result.put("fieldRect", generateDocReaderFieldRect(documentReaderGraphicField.getRect())); + if (documentReaderGraphicField.boundRect != null) + result.put("fieldRect", generateDocReaderFieldRect(documentReaderGraphicField.boundRect)); return result; } @@ -299,20 +298,6 @@ static private JSONObject generateImageQuality(ImageQuality imageQuality, Contex return result; } - static private JSONObject generateDocumentReaderJsonResult(DocumentReaderJsonResult documentReaderJsonResult, Context context) throws JSONException { - return new JSONObject().put("results", generateList(documentReaderJsonResult.results, JSONConstructor::generateDocumentReaderJsonResultGroup, context)); - } - - static private JSONObject generateDocumentReaderJsonResultGroup(DocumentReaderJsonResultGroup documentReaderJsonResultGroup, Context context) throws JSONException { - JSONObject result = new JSONObject(); - result.put("lightType", documentReaderJsonResultGroup.lightType); - result.put("pageIdx", documentReaderJsonResultGroup.pageIdx); - result.put("resultType", documentReaderJsonResultGroup.resultType); - result.put("jsonResult", documentReaderJsonResultGroup.jsonResult); - - return result; - } - static private JSONObject generateRfidSessionData(RFIDSessionData rfidSessionData, Context context) throws JSONException { JSONObject result = new JSONObject(); result.put("totalBytesSent", rfidSessionData.totalBytesSent); @@ -681,25 +666,28 @@ static JSONArray generateByteArray(byte[] array) throws JSONException { return result; } - static JSONObject generateCompletion(int action, DocumentReaderResults results, Throwable error, Context context) throws JSONException { + static JSONObject generateCompletion(int action, DocumentReaderResults results, Throwable error, Context context) { JSONObject result = new JSONObject(); - result.put("action", action); - switch (action) { - case DocReaderAction.PROCESS: - case DocReaderAction.PROCESS_WHITE_UV_IMAGES: - result.put("results", ""); - break; - case DocReaderAction.NOTIFICATION: - result.put("results", resultsToJsonObjectNotification(results)); - break; - case DocReaderAction.COMPLETE: - case DocReaderAction.MORE_PAGES_AVAILABLE: - case DocReaderAction.CANCEL: - case DocReaderAction.ERROR: - result.put("results", resultsToJsonObject(results, context)); - break; + try { + result.put("action", action); + switch (action) { + case DocReaderAction.PROCESS: + case DocReaderAction.PROCESS_WHITE_UV_IMAGES: + result.put("results", ""); + break; + case DocReaderAction.NOTIFICATION: + result.put("results", resultsToJsonObjectNotification(results)); + break; + case DocReaderAction.COMPLETE: + case DocReaderAction.MORE_PAGES_AVAILABLE: + case DocReaderAction.CANCEL: + case DocReaderAction.ERROR: + result.put("results", resultsToJsonObject(results, context)); + break; + } + result.put("error", generateThrowable(error, context)); + } catch (JSONException ignored) { } - result.put("error", generateThrowable(error, context)); return result; } @@ -710,7 +698,7 @@ static JSONObject generateThrowable(Throwable throwable, Context context) throws return result; result.put("localizedMessage", throwable.getLocalizedMessage()); result.put("message", throwable.getMessage()); - result.put("toString", throwable.toString()); + result.put("string", throwable.toString()); result.put("stackTrace", generateArray(throwable.getStackTrace(), JSONConstructor::generateStackTraceElement, context)); return result; @@ -725,7 +713,7 @@ static JSONObject generateStackTraceElement(StackTraceElement e, Context context result.put("lineNumber", e.getLineNumber()); result.put("methodName", e.getMethodName()); result.put("isNativeMethod", e.isNativeMethod()); - result.put("toString", e.toString()); + result.put("string", e.toString()); return result; } @@ -734,14 +722,13 @@ static JSONObject generateStackTraceElement(StackTraceElement e, Context context static Bitmap bitmapFromBase64(String base64) { byte[] decodedString = Base64.decode(base64, Base64.DEFAULT); - return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); - } - - static byte[] byteArrayFromJson(JSONArray array) throws JSONException { - byte[] bytes = new byte[array.length()]; - for (int i = 0; i < array.length(); i++) - bytes[i] = (byte) array.getInt(i); - return bytes; + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inPreferredConfig = Bitmap.Config.RGB_565; + Bitmap result = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length, options); + 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 Drawable drawableFromBase64(String base64, Context context) { @@ -827,4 +814,11 @@ static Bounds boundsFromJson(JSONObject object) throws JSONException { 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; + } } \ No newline at end of file diff --git a/android/src/main/java/com/regula/documentreader/RNRegulaDocumentReaderModule.java b/android/src/main/java/com/regula/documentreader/RNRegulaDocumentReaderModule.java index 3300b4e..89b29e0 100644 --- a/android/src/main/java/com/regula/documentreader/RNRegulaDocumentReaderModule.java +++ b/android/src/main/java/com/regula/documentreader/RNRegulaDocumentReaderModule.java @@ -9,7 +9,6 @@ import android.nfc.NfcAdapter; import android.nfc.tech.IsoDep; import android.util.Base64; -import android.util.Log; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; @@ -44,8 +43,7 @@ public class RNRegulaDocumentReaderModule extends ReactContextBaseJavaModule imp private final static String completionEvent = "completionEvent"; private static int databaseDownloadProgress = 0; JSONArray data; - private NfcAdapter nfcAdapter; - private ReactContext reactContext; + private final ReactContext reactContext; private boolean backgroundRFIDEnabled = false; public RNRegulaDocumentReaderModule(ReactApplicationContext reactContext) { @@ -65,54 +63,30 @@ private Context getContext() { return reactContext.getCurrentActivity(); } + private Activity getActivity() { + return getCurrentActivity(); + } + @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { } @Override public void onNewIntent(Intent intent) { - if (intent.getAction() != null && intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) && backgroundRFIDEnabled) { - Log.d("RFID", "starting rfid reader"); + if (intent.getAction() != null && intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED) && backgroundRFIDEnabled) Instance().readRFID(IsoDep.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)), getCompletion()); - } } @Override public void onHostResume() { - if (backgroundRFIDEnabled) { - if (nfcAdapter == null) - nfcAdapter = NfcAdapter.getDefaultAdapter(getCurrentActivity()); - startForegroundDispatch(getCurrentActivity(), nfcAdapter); - } + if (backgroundRFIDEnabled) + startForegroundDispatch(getActivity()); } @Override public void onHostPause() { if (backgroundRFIDEnabled) - stopForegroundDispatch(getCurrentActivity(), nfcAdapter); - } - - private void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) { - adapter.disableForegroundDispatch(activity); - } - - private void startForegroundDispatch(final Activity activity, NfcAdapter adapter) { - 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"} - }; - adapter.enableForegroundDispatch(activity, PendingIntent.getActivity(activity.getApplicationContext(), 0, new Intent(activity.getApplicationContext(), activity.getClass()), 0), filters, techList); - Log.d("RFID", "NFC adapter dispatch enabled for android.nfc.tech.IsoDep"); - } - - private void stopBackgroundRFID() { - if (!backgroundRFIDEnabled) - return; - stopForegroundDispatch(getCurrentActivity(), nfcAdapter); - backgroundRFIDEnabled = false; + NfcAdapter.getDefaultAdapter(getActivity()).disableForegroundDispatch(getActivity()); } @Override @@ -126,19 +100,26 @@ private T args(int index) throws JSONException { private void sendProgress(int progress) { WritableMap map = Arguments.createMap(); - map.putString("msg", "Downloading database: " + progress + "%"); + map.putString("msg", progress + ""); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(prepareDatabaseProgressChangeEvent, map); } - private void sendCompletion(int action, DocumentReaderResults results, Throwable error, Context context) { + private void sendCompletion(int action, DocumentReaderResults results, Throwable error) { WritableMap map = Arguments.createMap(); - try { - map.putString("msg", JSONConstructor.generateCompletion(action, results, error, context).toString()); - } catch (JSONException ignored) { - } + map.putString("msg", JSONConstructor.generateCompletion(action, results, error, getContext()).toString()); reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(completionEvent, map); } + private interface Callback { + void success(Object o); + + void error(String s); + + default void success() { + success(""); + } + } + @ReactMethod public void exec(String moduleName, String action, ReadableArray args, com.facebook.react.bridge.Callback successCallback, com.facebook.react.bridge.Callback errorCallback) { data = new JSONArray(args.toArrayList()); @@ -262,6 +243,9 @@ public void error(String s) { case "readRFID": readRFID(callback); break; + case "getRfidSessionStatus": + getRfidSessionStatus(callback); + break; case "setEnableCoreLogs": setEnableCoreLogs(callback, args(0)); break; @@ -301,6 +285,9 @@ public void error(String s) { case "recognizeImage": recognizeImage(callback, args(0)); break; + case "setRfidSessionStatus": + setRfidSessionStatus(callback, args(0)); + break; case "recognizeImageFrame": recognizeImageFrame(callback, args(0), args(1)); break; @@ -319,17 +306,32 @@ public void error(String s) { case "recognizeImageWithCameraMode": recognizeImageWithCameraMode(callback, args(0), args(1)); break; - case "getRfidSessionStatus": - getRfidSessionStatus(callback); - break; - case "setRfidSessionStatus": - setRfidSessionStatus(callback, args(0)); - break; } } catch (Exception ignored) { } } + 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()); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0); + NfcAdapter.getDefaultAdapter(getActivity()).enableForegroundDispatch(activity, pendingIntent, filters, techList); + } + + private void stopBackgroundRFID() { + if (!backgroundRFIDEnabled) + return; + NfcAdapter.getDefaultAdapter(getActivity()).disableForegroundDispatch(getActivity()); + backgroundRFIDEnabled = false; + } + private void getAvailableScenarios(Callback callback) throws JSONException { callback.success(JSONConstructor.generateList(Instance().availableScenarios, JSONConstructor::generateDocumentReaderScenario, getContext()).toString()); } @@ -442,9 +444,8 @@ private void startNewPage(Callback callback) { callback.success(); } - private void recognizeImageWithImageInputParams(Callback callback, String base64Image, final JSONObject params) throws JSONException { + private void recognizeImageWithImageInputParams(@SuppressWarnings("unused") Callback callback, String base64Image, final JSONObject params) throws JSONException { Instance().recognizeImage(JSONConstructor.bitmapFromBase64(base64Image), new ImageInputParam(params.getInt("width"), params.getInt("height"), params.getInt("type")), getCompletion()); - callback.success(); } private void recognizeImageWithOpts(Callback callback, final JSONObject opts, String base64Image) throws JSONException { @@ -452,19 +453,17 @@ private void recognizeImageWithOpts(Callback callback, final JSONObject opts, St recognizeImage(callback, base64Image); } - private void recognizeImage(Callback callback, String base64Image) { + private void recognizeImage(@SuppressWarnings("unused") Callback callback, String base64Image) { stopBackgroundRFID(); Instance().recognizeImage(JSONConstructor.bitmapFromBase64(base64Image), getCompletion()); - callback.success(); } - private void recognizeImages(Callback callback, JSONArray base64Images) throws JSONException { + 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] = JSONConstructor.bitmapFromBase64(base64Images.getString(i)); Instance().recognizeImages(images, getCompletion()); - callback.success(); } private void removeDatabase(Callback callback) { @@ -489,7 +488,7 @@ private void addPKDCertificates(Callback callback, JSONArray certificatesJSON) t List certificates = new ArrayList<>(); for (int i = 0; i < certificatesJSON.length(); i++) { JSONObject certificate = certificatesJSON.getJSONObject(i); - certificates.add(new PKDCertificate(JSONConstructor.byteArrayFromJson(certificate.getJSONArray("binaryData")), certificate.getInt("resourceType"), certificate.has("certificate") ? JSONConstructor.byteArrayFromJson(certificate.getJSONArray("privateKey")) : null)); + 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(); @@ -500,32 +499,28 @@ private void clearPKDCertificates(Callback callback) { callback.success(); } - private void recognizeImageFrame(Callback callback, String base64Image, final JSONObject opts) throws JSONException { + private void recognizeImageFrame(@SuppressWarnings("unused") Callback callback, String base64Image, final JSONObject opts) throws JSONException { Instance().recognizeImageFrame(JSONConstructor.bitmapFromBase64(base64Image), new ImageInputParam(opts.getInt("width"), opts.getInt("height"), opts.getInt("type")), getCompletion()); - callback.success(); } - private void recognizeVideoFrame(Callback callback, String byteString, final JSONObject opts) throws JSONException { + 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()); - callback.success(); } - private void showScannerWithCameraID(Callback callback, int cameraID) { + private void showScannerWithCameraID(@SuppressWarnings("unused") Callback callback, int cameraID) { stopBackgroundRFID(); Instance().showScanner(getContext(), cameraID, getCompletion()); - callback.success(); } private void showScanner(Callback callback) { showScannerWithCameraID(callback, -1); } - private void showScannerWithCameraIDAndOpts(Callback callback, int cameraID, final JSONObject opts) throws JSONException { + 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()); - callback.success(); } private void stopScanner(Callback callback) { @@ -533,14 +528,14 @@ private void stopScanner(Callback callback) { callback.success(); } - private void startRFIDReader(Callback callback) { + private void startRFIDReader(@SuppressWarnings("unused") Callback callback) { stopBackgroundRFID(); Instance().startRFIDReader(getContext(), getCompletion()); - callback.success(); } private void stopRFIDReader(Callback callback) { Instance().stopRFIDReader(getContext()); + stopBackgroundRFID(); callback.success(); } @@ -566,30 +561,30 @@ private void setConfig(Callback callback, final JSONObject opts) throws JSONExce callback.success(); } - private void setCameraSessionIsPaused(Callback callback, @SuppressWarnings("unused") boolean ignored) { - callback.error("setCameraSessionIsPaused() is an ios-only method"); + private void readRFID(@SuppressWarnings("unused") Callback callback) { + backgroundRFIDEnabled = true; + startForegroundDispatch(getActivity()); } - private void readRFID(Callback callback) { - if (nfcAdapter == null) - nfcAdapter = NfcAdapter.getDefaultAdapter(getCurrentActivity()); - backgroundRFIDEnabled = true; - startForegroundDispatch(getCurrentActivity(), nfcAdapter); - callback.success(); + 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"); } + @SuppressWarnings("unused") private void recognizeImageWithCameraMode(Callback callback, String base64, boolean mode) { callback.error("recognizeImageWithCameraMode() is an ios-only method"); } + @SuppressWarnings("unused") private void initializeReaderWithDatabasePath(Callback callback, Object license, String path) { callback.error("initializeReaderWithDatabasePath() is an ios-only method"); } + @SuppressWarnings("unused") private void setRfidSessionStatus(Callback callback, String s) { callback.error("setRfidSessionStatus() is an ios-only method"); } @@ -600,7 +595,7 @@ private void getRfidSessionStatus(Callback callback) { private IDocumentReaderCompletion getCompletion() { return (action, results, error) -> { - sendCompletion(action, results, error, getContext()); + sendCompletion(action, results, error); if (action == DocReaderAction.ERROR || action == DocReaderAction.CANCEL || (action == DocReaderAction.COMPLETE && results.rfidResult == 1)) stopBackgroundRFID(); }; @@ -634,14 +629,4 @@ private IDocumentReaderInitCompletion getInitCompletion(Callback callback) { callback.error("Init failed:" + error); }; } - - private interface Callback { - void success(Object o); - - void error(String s); - - default void success() { - success(""); - } - } } \ No newline at end of file diff --git a/android/src/main/java/com/regula/documentreader/RegulaConfig.java b/android/src/main/java/com/regula/documentreader/RegulaConfig.java index ca783de..3d0335c 100644 --- a/android/src/main/java/com/regula/documentreader/RegulaConfig.java +++ b/android/src/main/java/com/regula/documentreader/RegulaConfig.java @@ -18,14 +18,7 @@ import java.math.BigDecimal; -import static com.regula.documentreader.JSONConstructor.drawableFromBase64; -import static com.regula.documentreader.JSONConstructor.bitmapFromDrawable; -import static com.regula.documentreader.JSONConstructor.barcodeTypeArrayFromJson; -import static com.regula.documentreader.JSONConstructor.faceMetaDataArrayFromJson; -import static com.regula.documentreader.JSONConstructor.floatArrayFromJson; -import static com.regula.documentreader.JSONConstructor.intArrayFromJson; -import static com.regula.documentreader.JSONConstructor.generateIntArray; -import static com.regula.documentreader.JSONConstructor.matrixFromFloatArray; +import static com.regula.documentreader.JSONConstructor.*; class RegulaConfig { static void setConfig(DocumentReader reader, JSONObject opts, Context context) throws JSONException { @@ -90,8 +83,17 @@ private static void setFunctionality(Functionality functionality, JSONObject opt editor.setCaptureMode(opts.getInt("captureMode")); if (opts.has("displayMetadata")) editor.setDisplayMetadata(opts.getBoolean("displayMetadata")); -// if (opts.has("cameraSize")) -// editor.setCameraSize(); + 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()); + editor.apply(); } @@ -150,6 +152,10 @@ private static void setProcessParams(ProcessParam processParams, JSONObject opts 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"); } private static void setCustomization(ParamsCustomization customization, JSONObject opts, Context context) throws JSONException { @@ -262,6 +268,9 @@ private static void setCustomization(ParamsCustomization customization, JSONObje 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()); + editor.apply(); } @@ -289,7 +298,14 @@ private static JSONObject getFunctionality(Functionality functionality) throws J object.put("startDocReaderForResult", functionality.getStartDocReaderForResult()); object.put("captureMode", functionality.getCaptureMode()); object.put("displayMetadata", functionality.isDisplayMetaData()); -// object.put("cameraSize", functionality.getCameraSize()); + 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()); return object; } @@ -316,9 +332,9 @@ private static JSONObject getCustomization(ParamsCustomization customization) th object.put("cameraFrameLineLength", customization.getCameraFrameLineLength()); object.put("cameraFrameShapeType", customization.getCameraFrameShapeType()); object.put("resultStatusTextSize", customization.getResultStatusTextSize()); - object.put("multipageAnimationFrontImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getMultipageAnimationFrontImage()))); - object.put("multipageAnimationBackImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getMultipageAnimationBackImage()))); - object.put("borderBackgroundImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getBorderBackgroundImage()))); + 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()); @@ -330,7 +346,7 @@ private static JSONObject getCustomization(ParamsCustomization customization) th object.put("statusPositionMultiplier", customization.getStatusPositionMultiplier()); object.put("resultStatusPositionMultiplier", customization.getResultStatusPositionMultiplier()); object.put("backgroundMaskAlpha", customization.getBackgroundMaskAlpha()); - object.put("helpAnimationImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getHelpAnimationImageDrawable()))); + object.put("helpAnimationImage", bitmapToBase64String(bitmapFromDrawable(customization.getHelpAnimationImageDrawable()))); object.put("cameraFrameOffsetWidth", customization.getCameraFrameOffsetWidth()); object.put("customLabelStatus", customization.getCustomLabelStatus().toString()); object.put("customStatusPositionMultiplier", customization.getCustomStatusPositionMultiplier()); @@ -339,17 +355,18 @@ private static JSONObject getCustomization(ParamsCustomization customization) th object.put("cameraFramePortraitAspectRatio", customization.getCameraFramePortraitAspectRatio()); object.put("cameraFrameCornerRadius", customization.getCameraFrameCornerRadius()); object.put("cameraFrameLineCap", customization.getCameraFrameLineCap().toString()); - object.put("torchImageOnImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOnDrawable()))); - object.put("torchImageOffImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOffDrawable()))); - object.put("closeButtonImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getCloseButtonDrawable()))); - object.put("captureButtonImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getCaptureButtonDrawable()))); - object.put("changeFrameCollapseButtonImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameCollapseButtonDrawable()))); - object.put("changeFrameExpandButtonImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameExpandButtonDrawable()))); - object.put("cameraSwitchButtonImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getCameraSwitchButtonDrawable()))); - object.put("torchButtonOnImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOnDrawable()))); - object.put("torchButtonOffImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOffDrawable()))); - object.put("changeFrameButtonExpandImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameExpandButtonDrawable()))); - object.put("changeFrameButtonCollapseImage", JSONConstructor.bitmapToBase64String(bitmapFromDrawable(customization.getChangeFrameCollapseButtonDrawable()))); + object.put("torchImageOnImage", bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOnDrawable()))); + object.put("torchImageOffImage", bitmapToBase64String(bitmapFromDrawable(customization.getTorchImageOffDrawable()))); + 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()); return object; } @@ -380,14 +397,16 @@ private static JSONObject getProcessParams(ProcessParam processParams, Context c 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); if (processParams.documentIDList != null) object.put("documentIDList", generateIntArray(processParams.documentIDList)); if (processParams.doBarcodes != null) - object.put("barcodeTypes", JSONConstructor.generateArray(processParams.doBarcodes)); + object.put("barcodeTypes", generateArray(processParams.doBarcodes)); if (processParams.fieldTypesFilter != null) object.put("fieldTypesFilter", generateIntArray(processParams.fieldTypesFilter)); if (processParams.faceMetaData != null) - object.put("faceMetaData", JSONConstructor.generateArray(processParams.faceMetaData, JSONConstructor::generateFaceMetaData, context)); + object.put("faceMetaData", generateArray(processParams.faceMetaData, JSONConstructor::generateFaceMetaData, context)); return object; } @@ -485,6 +504,8 @@ static void setRfidScenario(JSONObject opts) throws JSONException { 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")) diff --git a/example/App.js b/example/App.js index 4e451c1..9c75a0f 100644 --- a/example/App.js +++ b/example/App.js @@ -11,13 +11,40 @@ const eventManager = new NativeEventEmitter(Regula.RNRegulaDocumentReader) const DocumentReader = Regula.DocumentReader const Enum = DocumentReader.Enum +var licPath = Platform.OS === 'ios' ? (RNFS.MainBundlePath + "/regula.license") : "regula.license" +var certDir = Platform.OS === 'ios' ? (RNFS.MainBundlePath + "/certificates") : "certificates" +var readDir = Platform.OS === 'ios' ? RNFS.readDir : RNFS.readDirAssets +var readFile = Platform.OS === 'ios' ? RNFS.readFile : RNFS.readFileAssets + +async function addCertificates() { + var certificates = [] + var items = await readDir(certDir, 'base64') + + for (var i in items) { + var item = items[i] + if (item.isFile()) { + var findExt = item.name.split('.') + var pkdResourceType = 0 + if (findExt.length > 0) + pkdResourceType = Enum.PKDResourceType.getType(findExt[findExt.length - 1].toLowerCase()) + + var file = await readFile(item.path, 'base64') + certificates.push({ + 'binaryData': file, + 'resourceType': pkdResourceType + }) + } + } + DocumentReader.addPKDCertificates(certificates, s => { + console.log("certificates added") + }, e => console.log(e)) +} + export default class App extends Component { constructor(props) { super(props) - eventManager.addListener('prepareDatabaseProgressChangeEvent', e => this.setState({ fullName: e["msg"] })) + eventManager.addListener('prepareDatabaseProgressChangeEvent', e => this.setState({ fullName: "Downloading database: " + e["msg"] + "%" })) eventManager.addListener('completionEvent', e => this.handleCompletion(DocumentReader.DocumentReaderCompletion.fromJson(JSON.parse(e["msg"])))) - var licPath = Platform.OS === 'ios' ? (RNFS.MainBundlePath + "/regula.license") : "regula.license" - var readFile = Platform.OS === 'ios' ? RNFS.readFile : RNFS.readFileAssets DocumentReader.prepareDatabase("Full", (respond) => { console.log(respond) readFile(licPath, 'base64').then((res) => { @@ -52,9 +79,10 @@ export default class App extends Component { }} /> }) DocumentReader.getDocumentReaderIsReady((isReady) => { - if (isReady) + if (isReady) { this.setState({ fullName: "Ready" }) - else + // addCertificates() + } else this.setState({ fullName: "Failed" }) }, error => console.log(error)) }, error => console.log(error)) @@ -115,26 +143,26 @@ export default class App extends Component { DocumentReader.setRfidSessionStatus(this.state.rfidDescription + "\n" + results.value + "%", e => { }, e => { }) } - clearResults(){ + clearResults() { this.setState({ fullName: "Ready", docFront: require('./images/id.png'), portrait: require('./images/portrait.png') }) } displayResults(results) { this.setState({ fullName: results.getTextFieldValueByType({ fieldType: Enum.eVisualFieldType.FT_SURNAME_AND_GIVEN_NAMES }) }) - if (results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE) != null) - this.setState({ docFront: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE) } }) - if (results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_PORTRAIT) != null) - this.setState({ portrait: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_PORTRAIT) } }) + if (results.getGraphicFieldImageByType({ fieldType: Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE }) != null) + this.setState({ docFront: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType({ fieldType: Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE }) } }) + if (results.getGraphicFieldImageByType({ fieldType: Enum.eGraphicFieldType.GF_PORTRAIT }) != null) + this.setState({ portrait: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType({ fieldType: Enum.eGraphicFieldType.GF_PORTRAIT }) } }) } - customRFID(){ + customRFID() { this.showRfidUI() - DocumentReader.readRFID(e => { }, e => {}) + DocumentReader.readRFID(e => { }, e => { }) } - usualRFID(){ + usualRFID() { this.setState({ doRfid: false }) - DocumentReader.startRFIDReader(e => { }, e => {}) + DocumentReader.startRFIDReader(e => { }, e => { }) } handleResults(results) { @@ -293,7 +321,7 @@ export default class App extends Component { images.push(response[i].data) } this.setState({ fullName: "PROCESSING..." }) - DocumentReader.recognizeImages(images, s => {}, e => console.log(e)) + DocumentReader.recognizeImages(images, s => { }, e => console.log(e)) }).catch(e => { console.log("ImagePicker: " + e) }) diff --git a/example/App.js-e b/example/App.js-e deleted file mode 100644 index 08b36b4..0000000 --- a/example/App.js-e +++ /dev/null @@ -1,336 +0,0 @@ -import React, { Component } from 'react' -import { StyleSheet, View, Button, Text, Image, ScrollView, NativeEventEmitter, Platform, TouchableOpacity } from 'react-native' -import Regula from '@regulaforensics/api_module_place_holder' -import * as RNFS from 'react-native-fs' -import RadioGroup from 'react-native-radio-buttons-group' -import ImagePicker from 'react-native-customized-image-picker' -import * as Progress from 'react-native-progress' -import CheckBox from 'react-native-check-box' - -const eventManager = new NativeEventEmitter(Regula.RNRegulaDocumentReader) -const DocumentReader = Regula.DocumentReader -const Enum = DocumentReader.Enum - -export default class App extends Component { - constructor(props) { - super(props) - eventManager.addListener('prepareDatabaseProgressChangeEvent', e => this.setState({ fullName: e["msg"] })) - eventManager.addListener('completionEvent', e => this.handleCompletion(DocumentReader.DocumentReaderCompletion.fromJson(JSON.parse(e["msg"])))) - var licPath = Platform.OS === 'ios' ? (RNFS.MainBundlePath + "/regula.license") : "regula.license" - var readFile = Platform.OS === 'ios' ? RNFS.readFile : RNFS.readFileAssets - DocumentReader.prepareDatabase("Full", (respond) => { - console.log(respond) - readFile(licPath, 'base64').then((res) => { - this.setState({ fullName: "Initializing..." }) - DocumentReader.initializeReader(res, (respond) => { - console.log(respond) - DocumentReader.isRFIDAvailableForUse((canRfid) => { - if (canRfid) { - this.setState({ canRfid: true, rfidUIHeader: "Reading RFID", rfidDescription: "Place your phone on top of the NFC tag", rfidUIHeaderColor: "black" }) - this.setState({ canRfidTitle: '' }) - } - }, error => console.log(error)) - DocumentReader.getAvailableScenarios((jstring) => { - var scenariosTemp = JSON.parse(jstring) - var scenariosL = [] - for (var i in scenariosTemp) { - scenariosL.push({ - label: DocumentReader.Scenario.fromJson(typeof scenariosTemp[i] === "string" ? JSON.parse(scenariosTemp[i]) : scenariosTemp[i]).name, - value: i - }) - } - this.setState({ scenarios: scenariosL }) - this.setState({ selectedScenario: this.state.scenarios[0]['label'] }) - this.setState({ radio: null }) - this.setState({ - radio: { - var selectedItem - for (var index in data) - if (data[index]['selected']) - selectedItem = data[index]['label'] - this.setState({ selectedScenario: selectedItem }) - }} /> - }) - DocumentReader.getDocumentReaderIsReady((isReady) => { - if (isReady) - this.setState({ fullName: "Ready" }) - else - this.setState({ fullName: "Failed" }) - }, error => console.log(error)) - }, error => console.log(error)) - }, error => console.log(error)) - }) - }, error => console.log(error)) - - this.state = { - fullName: "Please wait...", - doRfid: false, - canRfid: false, - canRfidTitle: '(unavailable)', - scenarios: [], - selectedScenario: "", - portrait: require('./images/portrait.png'), - docFront: require('./images/id.png'), - radio: - } - } - - handleCompletion(completion) { - if (this.state.isReadingRfid && (completion.action === Enum.DocReaderAction.CANCEL || completion.action === Enum.DocReaderAction.ERROR)) - this.hideRfidUI() - if (this.state.isReadingRfid && completion.action === Enum.DocReaderAction.NOTIFICATION) - this.updateRfidUI(completion.results.documentReaderNotification) - if (completion.action === Enum.DocReaderAction.COMPLETE) - if (this.state.isReadingRfid) - if (completion.results.rfidResult !== 1) - this.restartRfidUI() - else { - this.hideRfidUI() - this.displayResults(completion.results) - } - else - this.handleResults(completion.results) - } - - showRfidUI() { - // show animation - this.setState({ isReadingRfid: true }) - } - - hideRfidUI() { - // show animation - this.restartRfidUI() - this.setState({ isReadingRfid: false, rfidUIHeader: "Reading RFID", rfidUIHeaderColor: "black" }) - } - - restartRfidUI() { - this.setState({ rfidUIHeaderColor: "red", rfidUIHeader: "Failed!", rfidDescription: "Place your phone on top of the NFC tag", rfidProgress: -1 }) - } - - updateRfidUI(results) { - if (results.code === Enum.eRFID_NotificationAndErrorCodes.RFID_NOTIFICATION_PCSC_READING_DATAGROUP) - this.setState({ rfidDescription: Enum.eRFID_DataFile_Type.getTranslation(results.number) }) - this.setState({ rfidUIHeader: "Reading RFID", rfidUIHeaderColor: "black", rfidProgress: results.value / 100 }) - if (Platform.OS === 'ios') - DocumentReader.setRfidSessionStatus(this.state.rfidDescription + "\n" + results.value + "%", e => { }, e => { }) - } - - clearResults(){ - this.setState({ fullName: "Ready", docFront: require('./images/id.png'), portrait: require('./images/portrait.png') }) - } - - displayResults(results) { - this.setState({ fullName: results.getTextFieldValueByType({ fieldType: Enum.eVisualFieldType.FT_SURNAME_AND_GIVEN_NAMES }) }) - if (results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE) != null) - this.setState({ docFront: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_DOCUMENT_IMAGE) } }) - if (results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_PORTRAIT) != null) - this.setState({ portrait: { uri: "data:image/png;base64," + results.getGraphicFieldImageByType(Enum.eGraphicFieldType.GF_PORTRAIT) } }) - } - - customRFID(){ - this.showRfidUI() - DocumentReader.readRFID(e => { }, e => {}) - } - - usualRFID(){ - this.setState({ doRfid: false }) - DocumentReader.startRFIDReader(e => { }, e => {}) - } - - handleResults(results) { - if (this.state.doRfid && results != null && results.chipPage != 0) { - accessKey = null - accessKey = results.getTextFieldValueByType(Enum.eVisualFieldType.FT_MRZ_STRINGS) - if (accessKey != null && accessKey != "") { - accessKey = accessKey.replace(/^/g, '').replace(/\n/g, '') - DocumentReader.setRfidScenario({ - mrz: accessKey, - pacePasswordType: Enum.eRFID_Password_Type.PPT_MRZ, - }, e => { }, error => console.log(error)) - } else { - accessKey = null - accessKey = results.getTextFieldValueByType(159) - if (accessKey != null && accessKey != "") { - DocumentReader.setRfidScenario({ - password: accessKey, - pacePasswordType: Enum.eRFID_Password_Type.PPT_CAN, - }, e => { }, error => console.log(error)) - } - } - // this.customRFID() - this.usualRFID() - } else - this.displayResults(results) - } - - render() { - return ( - - {(this.state.isReadingRfid && Platform.OS === 'android') && - {this.state.rfidUIHeader} - {this.state.rfidDescription} - - { this.hideRfidUI() }}> - X - - - } - {!this.state.isReadingRfid && - - {this.state.fullName} - - - - - Portrait - - - - - - Document image - - - - - - - {this.state.radio} - - - - { - if (this.state.canRfid) { - this.setState({ doRfid: !this.state.doRfid }) - } - }} - disabled={!this.state.canRfid} - /> - - {'Process rfid reading' + this.state.canRfidTitle} - - - - -