Skip to content

Commit

Permalink
Modified from tradle/react-native-regula-document-reader
Browse files Browse the repository at this point in the history
  • Loading branch information
Oussama Ghalbzouri - ERF3D committed Sep 18, 2019
0 parents commit 9a9a02d
Show file tree
Hide file tree
Showing 15 changed files with 1,178 additions and 0 deletions.
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@

# react-native-regula-document-reader

## Getting started

`npm install react-native-regula-document-reader --save`

### Mostly automatic installation

`react-native link react-native-regula-document-reader`

#### iOS

1. Add to Podfile:
```
pod 'DocumentReader', '~> 4.0'
pod 'DocumentReaderFull', '~> 4.0'
```
1. Generate license for your application bundle ID: https://licensing.regulaforensics.com/. Convert it to a base64 string, e.g.: `fs.readFileSync('./path/to/regula.license').toString('base64')`
1. Download database from: https://licensing.regulaforensics.com/Customer/Account/Databases. Add it to the iOS project (db.dat).
1. Go to your project Targets -> Builds Settings -> Always Embed Swift Standard Libraries - set to Yes
1. Go to your project Targets -> Info -> Add new key Privacy - Camera Usage Description = “Your message that will be appeared during ask to run camera”.

#### Android

1. Open your top level build.gradle (android/build.gradle)
1. add the block below:
```
allprojects {
 repositories {
    maven {
      url "http://maven.regulaforensics.com/RegulaDocumentReader"
   }
  }
}
```
1. In your app level build.gradle:
1. increate 'minSdkVersion' to 19 (if it's below)
1. Open AndroidManifest.xml file and set: `android:allowBackup="true"`
1. `mkdir -p android/app/src/main/res/raw/`
1. Copy `regula.license` to that folder
1. This project comes bundled with a db.dat, but if you want to use the latest, download it from Regula and copy it to `node_modules/react-native-regula-document-reader/android/src/main/assets/Regula/`

## Usage
```js
import RegulaDocumentReader, { Scenario } from 'react-native-regula-document-reader';

// do this early on to save some time
await RegulaDocumentReader.initialize({
licenseKey: base64LicenseKeyYouCreatedAbove
})

// initialize on the fly, and scan
// set options as you like
// see Regula docs for what they mean
await RegulaDocumentReader.scan({
functionality: {
showTorchButton: true,
showCloseButton: true,
showCaptureButton: true,
showCaptureButtonAfterDelay: true,
showSkipNextPageButton: true,
videoCaptureMotionControl: true,
showChangeFrameButton: true,
},
customization: {
showHintMessages: true,
showHelpAnimation: true,
},
processParams: {
scenario: Scenario.mrz,
multipageProcessing: false,
dateFormat: 'dd-mm-yyyy',
},
})
```
52 changes: 52 additions & 0 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import groovy.json.JsonSlurper

def computeVersionName() {
// dynamically retrieve version from package.json
def slurper = new JsonSlurper()
def json = slurper.parse(file('../package.json'), "utf-8")
return json.version
}

buildscript {
repositories {
jcenter()
}

dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}

apply plugin: 'com.android.library'

def DEFAULT_COMPILE_SDK_VERSION = 25
def DEFAULT_BUILD_TOOLS_VERSION = "25.0.2"
def DEFAULT_TARGET_SDK_VERSION = 25

android {
compileSdkVersion rootProject.hasProperty('compileSdkVersion') ? rootProject.compileSdkVersion : DEFAULT_COMPILE_SDK_VERSION
buildToolsVersion rootProject.hasProperty('buildToolsVersion') ? rootProject.buildToolsVersion : DEFAULT_BUILD_TOOLS_VERSION

defaultConfig {
minSdkVersion 19
targetSdkVersion rootProject.hasProperty('targetSdkVersion') ? rootProject.targetSdkVersion : DEFAULT_TARGET_SDK_VERSION
versionCode 1
versionName computeVersionName()
}
lintOptions {
abortOnError false
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'com.facebook.react:react-native:+'
implementation 'com.regula.documentreader.fullrfid:core:+@aar'
implementation('com.regula.documentreader:api:+@aar') {
transitive = true
}
implementation project(':react-native-image-store') // From node_modules
}
6 changes: 6 additions & 0 deletions android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.regula.documentreader">

</manifest>

Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
package com.regula.documentreader;

import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Base64;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.regula.documentreader.api.DocumentReader;
import com.regula.documentreader.api.enums.DocReaderAction;
import com.regula.documentreader.api.enums.eGraphicFieldType;
import com.regula.documentreader.api.results.DocumentReaderJsonResultGroup;
import com.regula.documentreader.api.results.DocumentReaderResults;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import io.tradle.reactimagestore.ImageStoreModule;

public class RNRegulaDocumentReaderModule extends ReactContextBaseJavaModule {

private final ReactApplicationContext reactContext;

//constructor
public RNRegulaDocumentReaderModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}

//Mandatory function getName that specifies the module name
@Override
public String getName() {
return "RNRegulaDocumentReader";
}
@ReactMethod
public void prepareDatabase(ReadableMap opts, final Callback cb) {
String dbID = opts.getString("dbID");
if (dbID == null)
dbID = "Full";
try {
DocumentReader.Instance().prepareDatabase(reactContext.getApplicationContext(), dbID, new
DocumentReader.DocumentReaderPrepareCompletion() {
@Override
public void onPrepareProgressChanged(int progress) {
// System.out.println("prepareDatabase: ");
//get progress update
}

@Override
public void onPrepareCompleted(boolean status, String error) {
System.out.println("prepareDatabase: completed status = " + status + "; error = " + error);
if (status) {
// initialize(opts, cb);
cb.invoke(null, null);
} else {
cb.invoke(error == null ? "preparation failed" : error);
}
//database downloaded
}
});
} catch (Exception e) {
e.printStackTrace();
cb.invoke(e.toString(), null);
}
}

@ReactMethod
public void initialize(ReadableMap opts, final Callback cb) {
try {
byte[] license = Base64.decode(opts.getString("licenseKey"), Base64.NO_WRAP);
DocumentReader.Instance().initializeReader(reactContext.getApplicationContext(), license, new DocumentReader.DocumentReaderInitCompletion() {
@Override
public void onInitCompleted(boolean b, String s) {
if (b) {
cb.invoke(null, null);
} else {
cb.invoke(s == null ? "initilization failed" : s);
}
}
});
} catch (Exception e) {
e.printStackTrace();
cb.invoke(e.toString(), null);
}
}

@ReactMethod
public void scan(ReadableMap opts, final Callback cb) {
final DocumentReader reader = DocumentReader.Instance();
RegulaConfig.setCustomization(reader.customization, opts.getMap("customization"));
RegulaConfig.setFunctionality(reader.functionality, opts.getMap("functionality"));
RegulaConfig.setProcessParams(reader.processParams, opts.getMap("processParams"));
DocumentReader.Instance().showScanner(new DocumentReader.DocumentReaderCompletion() {
@Override
public void onCompleted(int action, DocumentReaderResults documentReaderResults, String s) {
switch (action) {
case DocReaderAction.COMPLETE:
JSONObject resultObj = new JSONObject();
if (documentReaderResults != null) {
try {
// TODO: do these in parallel, async
Uri front = maybeGetImage(documentReaderResults.getGraphicFieldImageByType(eGraphicFieldType.GT_DOCUMENT_FRONT));
Uri back = maybeGetImage(documentReaderResults.getGraphicFieldImageByType(eGraphicFieldType.GT_DOCUMENT_REAR));

if (front != null) {
resultObj.put("imageFront", front.toString());
}

if (back != null) {
resultObj.put("imageBack", back.toString());
}
} catch (Exception ex) {
cb.invoke(resultObj.toString(), null);
return;
}

if (documentReaderResults.jsonResult != null) {
JSONArray jsonArray = new JSONArray();
int index = 0;
try {
for (DocumentReaderJsonResultGroup group : documentReaderResults.jsonResult.results) {
jsonArray.put(index, new JSONObject(group.jsonResult));
index++;
}

resultObj.put("jsonResult", jsonArray);
} catch (Exception ex) {
cb.invoke(resultObj.toString(), null);
return;
}
}
}

String resultString = resultObj.toString();
cb.invoke(null, resultString);

break;
case DocReaderAction.CANCEL:
cb.invoke("Cancelled by user", null);
break;
case DocReaderAction.ERROR:
cb.invoke(s, null);
break;
default:
break;
}
}

});
}

// @ReactMethod
// public void setScenario(String identifier) {
// DocumentReader.Instance().processParams.scenario = identifier;
// }

private Uri maybeGetImage(Bitmap bitmap) throws IOException {
if (bitmap == null) return null;

return ImageStoreModule.storeImageBitmap(reactContext, bitmap, "image/png", 100);
}

private byte[] readLicense() throws IOException {
InputStream licInput = null;
int resId = reactContext
.getResources()
.getIdentifier("regula", "raw", reactContext.getPackageName());

if (resId != 0) {
licInput = reactContext.getResources().openRawResource(resId);
}

if (licInput == null) {
throw new RuntimeException("missing license!");
}

int available = licInput.available();
byte[] license = new byte[available];
licInput.read(license);

return license;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.regula.documentreader;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class RNRegulaDocumentReaderPackage implements ReactPackage {

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}

@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
//We import the module file here
modules.add(new RNRegulaDocumentReaderModule(reactContext));

return modules;
}

// Backward compatibility
public List<Class<? extends JavaScriptModule>> createJSModules() {
return new ArrayList<>();
}
}
Loading

0 comments on commit 9a9a02d

Please sign in to comment.