create(Face face) {
-// return new GooglyFaceTracker(null,null);
-// }
-// };
-// processor = new MultiProcessor.Builder<>(factory).build();
-// }
-
- detector.setProcessor(processor);
-
- if (!detector.isOperational()) {
- // Note: The first time that an app using face API is installed on randA device, GMS will
- // download randA native library to the device in order to do detection. Usually this
- // completes before the app is run for the first time. But if that download has not yet
- // completed, then the above call will not detect any faces.
- //
- // isOperational() can be used to check if the required native library is currently
- // available. The detector will automatically become operational once the library
- // download completes on device.
- Toast.makeText(this, "Face detector dependencies are not yet available.", Toast.LENGTH_LONG).show();
- // Check for low storage. If there is low storage, the native library will not be
- // downloaded, so detection will not become operational.
- IntentFilter lowStorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
- boolean hasLowStorage = registerReceiver(null, lowStorageFilter) != null;
-
- if (hasLowStorage) {
- Toast.makeText(this, "Low storage", Toast.LENGTH_LONG).show();
- }
- }
- return detector;
- }
-
- private void createCameraSource() {
- reset();
- GooglyFaceTracker.gestures[0] = false;
- GooglyFaceTracker.gestures[1] = false;
- GooglyFaceTracker.gestures[2] = false;
- GooglyFaceTracker.gestures[3] = false;
- /*do {
- Random rand = new Random();
- randA = rand.nextInt(2);
- randB = rand.nextInt(4);
- }while (randA == randB || 5 == (randA + randB));*/
- randA = 0;
- randB = 1;
-
- /*if(randB < randA){
- int temp = randA;
- randA = randB;
- randB = temp;
- }*/
- //msg = "";
- //msg = strMsgs[randA] /*+ " , " + strMsgs[randB]*/;
- GooglyFaceTracker.gestures[randA] = true;
- //GooglyFaceTracker.gestures[randB] = true;
-
- Context context = getApplicationContext();
- FaceDetector detector = createFaceDetector(context);
-
- // The camera source is initialized to use either the front or rear facing camera. We use randA
- // relatively low resolution for the camera preview, since this is sufficient for this app
- // and the face detector will run faster at lower camera resolutions.
- //
- // However, note that there is randA speed/accuracy trade-off with respect to choosing the
- // camera resolution. The face detector will run faster with lower camera resolutions,
- // but may miss smaller faces, landmarks, or may not correctly detect eyes open/closed in
- // comparison to using higher camera resolutions. If you have any of these issues, you may
- // want to increase the resolution.
- mCameraSource = new CameraSource.Builder(context, detector)
- .setFacing(cameraFaceID)
- .setRequestedPreviewSize(640, 480)
- .setRequestedFps(60.0f)
- .setAutoFocusEnabled(true)
- .build();
- startCameraTimer();
- }
- public void startCameraTimer() {
- try {
- if(null != timer){
- timer.purge();
- timer.cancel();
- timer = null;
- }
- timer = new Timer();
- timerTask = new TimerTask() {
- @Override
- public void run() {
- try {
- if (mCameraSource != null) {
- mCameraSource.stop();
- //mCameraSource.release();
- }
- if (timer != null) {
- timer.cancel();
- timer = null;
- }
- }catch (Exception ex){
- ex.printStackTrace();
- }
- ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM,1000);
- toneGenerator.startTone(ToneGenerator.TONE_DTMF_S,300);
- captureFailed(FaceCaptureResult.CAPTURE_TIMEOUT, "Capture Timeout");
- //finish();
- }
- };
- timer.schedule(timerTask, faceCaptureTimeout);
- }catch (Exception ex){
- ex.getMessage();
- }
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if(null != toneGenerator){
- toneGenerator.release();
- }
- if(null != timer){
- timer.purge();
- timer.cancel();
- }
- if (mCameraSource != null) {
- try {
- mCameraSource.stop();
- } catch (Exception ex) { ex.printStackTrace();
- }
- try {
- mCameraSource.release();
- } catch (Exception ex) { ex.printStackTrace();
- }
- }
- }
- });
- }
- private void reset(){
- GooglyFaceTracker.gestureCount = 0;
- GooglyFaceTracker.verticalNod_min = 0;
- GooglyFaceTracker.verticalNod_max = 0;
- GooglyFaceTracker.horizontalNod_max = 0;
- GooglyFaceTracker.horizontalNod_min = 0;
- GooglyFaceTracker.smile_min = 0;
- GooglyFaceTracker.smile_max = 0;
- GooglyFaceTracker.SMILE_COMPLETED = false;
- GooglyFaceTracker.VERTICAL_NOD = false;
- GooglyFaceTracker.HORIZONTAL_NOD = false;
- GooglyFaceTracker.BLINK_COMPLETED = false;
-
- gestureBcompleted = false;
- gestureAcompleted = false;
- gestureCcompleted = false;
- }
- private void updateGif(int number){
- try {
- switch (number) {
- case 0: {
- /*if (!RDMainActivity.sharedPreferences.getBoolean("GESTURES_MUTED",false)) {
- player = new MediaPlayer();
- AssetFileDescriptor afd = getAssets().openFd("Blink.mp3");
- player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- player.prepare();
- player.start();
- }*/
- Glide.with(this)
- //.asGif()
- .load(R.raw.blink)
- .into(gesturesImg);
- break;
- }
- case 1: {
- /*if (!RDMainActivity.sharedPreferences.getBoolean("GESTURES_MUTED",false)) {
- player = new MediaPlayer();
- AssetFileDescriptor afd = getAssets().openFd("Smile.mp3");
- player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- player.prepare();
- player.start();
- }*/
- Glide.with(this)
- //.asGif()
- .load(R.raw.smile)
- .into(gesturesImg);
- break;
- }
- /*case 2: {
- AssetFileDescriptor afd = null;
- Random r= new Random();
- int a = r.nextInt(2);
- if(0 == a) {
- statusMsg.setText("Turn Head Right");
- afd = getAssets().openFd("TurnHeadRight.mp3");
- }else {
- statusMsg.setText("Turn Head Left");
- afd = getAssets().openFd("TurnHeadLeft.mp3");
- }
- if(null!= afd && (!RDMainActivity.sharedPreferences.getBoolean("GESTURES_MUTED",false))) {
- player = new MediaPlayer();
- player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- player.prepare();
- player.start();
- }
- Glide.with(this)
- //.asGif()
- .load(R.raw.horizontal)
- .into(gesturesImg);
- break;
- }
- case 3: {
- if (!RDMainActivity.sharedPreferences.getBoolean("GESTURES_MUTED", false)) {
- player = new MediaPlayer();
- AssetFileDescriptor afd = getAssets().openFd("MoveHeadUp.mp3");
- player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- player.prepare();
- player.start();
- }
- Glide.with(this)
- //.asGif()
- .load(R.raw.vertical)
- .into(gesturesImg);
- break;
- }*/
- case 4: {
- /*if (!RDMainActivity.sharedPreferences.getBoolean("GESTURES_MUTED",false)) {
- player = new MediaPlayer();
- AssetFileDescriptor afd = getAssets().openFd("LookStraight.mp3");
- player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
- player.prepare();
- player.start();
- }*/
- Glide.with(this)
- //.asGif()
- .load(R.raw.look_straight)
- .into(gesturesImg);
- break;
- }
- default: {
- Glide.with(this)
- //.asGif()
- .load(R.raw.gestures)
- .into(gesturesImg);
- break;
- }
- }
- }
- catch(Exception ex){
-
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/CameraSourcePreview.java b/app/src/main/java/nprime/reg/sbi/googlevision/CameraSourcePreview.java
deleted file mode 100644
index 4e07ecd..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/CameraSourcePreview.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package nprime.reg.sbi.googlevision;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.content.res.Configuration;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import android.view.ViewGroup;
-
-import androidx.core.app.ActivityCompat;
-
-import com.google.android.gms.common.images.Size;
-import com.google.android.gms.vision.CameraSource;
-
-import java.io.IOException;
-
-public class CameraSourcePreview extends ViewGroup {
- private static final String TAG = "CameraSourcePreview";
-
- private Context mContext;
- private SurfaceView mSurfaceView;
- private boolean mStartRequested;
- private boolean mSurfaceAvailable;
- private CameraSource mCameraSource;
- private GraphicOverlay mOverlay;
-
- public CameraSourcePreview(Context context, AttributeSet attrs) {
- super(context, attrs);
- mContext = context;
- mStartRequested = false;
- mSurfaceAvailable = false;
-
- mSurfaceView = new SurfaceView(context);
- mSurfaceView.getHolder().addCallback(new SurfaceCallback());
- addView(mSurfaceView);
- }
-
- public void start(CameraSource cameraSource) throws IOException {
- if (cameraSource == null) {
- stop();
- }
-
- mCameraSource = cameraSource;
-
- if (mCameraSource != null) {
- mStartRequested = true;
- startIfReady();
- }
- }
-
- public void start(CameraSource cameraSource, GraphicOverlay overlay) throws IOException {
- mOverlay = overlay;
- start(cameraSource);
- }
-
- public void stop() {
- if (mCameraSource != null) {
- try {
- mCameraSource.stop();
- } catch (Exception ex){
- ex.printStackTrace();
- }
- }
- }
-
- public void release() {
- if (mCameraSource != null) {
- mCameraSource.release();
- mCameraSource = null;
- }
- }
-
- private void startIfReady() throws IOException {
- if (mStartRequested && mSurfaceAvailable ) {
- if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
- mCameraSource.start(mSurfaceView.getHolder());
- if (mOverlay != null) {
- Size size = mCameraSource.getPreviewSize();
- int min = Math.min(size.getWidth(), size.getHeight());
- int max = Math.max(size.getWidth(), size.getHeight());
- if (isPortraitMode()) {
- // Swap width and height sizes when in portrait, since it will be rotated by
- // 90 degrees
- mOverlay.setCameraInfo(min, max, mCameraSource.getCameraFacing());
- } else {
- mOverlay.setCameraInfo(max, min, mCameraSource.getCameraFacing());
- }
- mOverlay.clear();
- }
- }
- mStartRequested = false;
- }
- }
-
- private class SurfaceCallback implements SurfaceHolder.Callback {
- @Override
- public void surfaceCreated(SurfaceHolder surface) {
- mSurfaceAvailable = true;
- try {
- startIfReady();
- } catch (IOException e) {
- Log.e(TAG, "Could not start camera source.", e);
- }
- }
-
- @Override
- public void surfaceDestroyed(SurfaceHolder surface) {
- mSurfaceAvailable = false;
- }
-
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
- }
- }
-
- @Override
- protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
- int previewWidth = 640;
- int previewHeight = 480;
- if (mCameraSource != null) {
- Size size = mCameraSource.getPreviewSize();
- if (size != null) {
- previewWidth = size.getWidth();
- previewHeight = size.getHeight();
- }
- }
-
- // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
- if (isPortraitMode()) {
- int tmp = previewWidth;
- previewWidth = previewHeight;
- previewHeight = tmp;
- }
-
- final int viewWidth = right - left;
- final int viewHeight = bottom - top;
-
- int childWidth;
- int childHeight;
- int childXOffset = 0;
- int childYOffset = 0;
- float widthRatio = (float) viewWidth / (float) previewWidth;
- float heightRatio = (float) viewHeight / (float) previewHeight;
-
- // To fill the view with the camera preview, while also preserving the correct aspect ratio,
- // it is usually necessary to slightly oversize the child and to crop off portions along one
- // of the dimensions. We scale up based on the dimension requiring the most correction, and
- // compute a crop offset for the other dimension.
- if (widthRatio > heightRatio) {
- childWidth = viewWidth;
- childHeight = (int) ((float) previewHeight * widthRatio);
- childYOffset = (childHeight - viewHeight) / 2;
- } else {
- childWidth = (int) ((float) previewWidth * heightRatio);
- childHeight = viewHeight;
- childXOffset = (childWidth - viewWidth) / 2;
- }
-
- for (int i = 0; i < getChildCount(); ++i) {
- // One dimension will be cropped. We shift child over or up by this offset and adjust
- // the size to maintain the proper aspect ratio.
- getChildAt(i).layout(
- -1 * childXOffset, -1 * childYOffset,
- childWidth - childXOffset, childHeight - childYOffset);
- }
-
- try {
- startIfReady();
- } catch (IOException e) {
- Log.e(TAG, "Could not start camera source.", e);
- }
- }
-
- private boolean isPortraitMode() {
- int orientation = mContext.getResources().getConfiguration().orientation;
- if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
- return false;
- }
- if (orientation == Configuration.ORIENTATION_PORTRAIT) {
- return true;
- }
-
- Log.d(TAG, "isPortraitMode returning false by default");
- return false;
- }
-}
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/FaceGraphic.java b/app/src/main/java/nprime/reg/sbi/googlevision/FaceGraphic.java
deleted file mode 100644
index 1dc956b..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/FaceGraphic.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package nprime.reg.sbi.googlevision;
-
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Rect;
-
-import com.google.android.gms.vision.face.Face;
-
-/**
- * Graphic instance for rendering face position, orientation, and landmarks within an associated
- * graphic overlay view.
- */
-class FaceGraphic extends GraphicOverlay.Graphic {
- private static final float BOX_STROKE_WIDTH = 5.0f;
- private Rect rect = null;
-
- private static final int COLOR_CHOICES[] = {
- Color.BLUE,
- Color.CYAN,
- Color.GREEN,
- Color.MAGENTA,
- Color.RED,
- Color.WHITE,
- Color.YELLOW
- };
- private static int mCurrentColorIndex = 0;
- private Paint mBoxPaint;
- private volatile Face mFace;
-
- FaceGraphic(GraphicOverlay overlay) {
- super(overlay);
-
- mCurrentColorIndex = (mCurrentColorIndex + 1) % COLOR_CHOICES.length;
- final int selectedColor = COLOR_CHOICES[2];//COLOR_CHOICES[mCurrentColorIndex];
-
- mBoxPaint = new Paint();
- mBoxPaint.setColor(selectedColor);
- mBoxPaint.setStyle(Paint.Style.STROKE);
- mBoxPaint.setStrokeWidth(BOX_STROKE_WIDTH);
- }
-
- /**
- * Updates the face instance from the detection of the most recent frame. Invalidates the
- * relevant portions of the overlay to trigger a redraw.
- */
- void updateFace(Face face) {
- mFace = face;
- //postInvalidate();
- }
-
- Rect getFaceRect() {
- return rect;
- }
-
- /**
- * Draws the face annotations for position on the supplied canvas.
- */
- @Override
- public void draw(Canvas canvas) {
- try {
- Face face = mFace;
- if (face == null) {
- return;
- }
- float x = translateX(face.getPosition().x + face.getWidth() / 2);
- float y = translateY(face.getPosition().y + face.getHeight() / 2);
- // Draws a bounding box around the face.
- float xOffset = scaleX(face.getWidth() / 2.0f);
- float yOffset = scaleY(face.getHeight() / 2.0f);
- float left = x - xOffset;
- float top = y - yOffset;
- float right = x + xOffset;
- float bottom = y + yOffset;
- //canvas.drawRect(left, top, right, bottom, mBoxPaint);
- int radius = (int)((3/2) * xOffset);
- canvas.drawCircle(x, y, radius, mBoxPaint);
- rect = new Rect((int) left, (int) top, (int) right, (int) bottom);
- } catch (Exception ex) {ex.printStackTrace();}
- }
-}
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/GooglyFaceTracker.java b/app/src/main/java/nprime/reg/sbi/googlevision/GooglyFaceTracker.java
deleted file mode 100644
index e0c6c5d..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/GooglyFaceTracker.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright (C) The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package nprime.reg.sbi.googlevision;
-
-import android.graphics.Rect;
-
-import com.google.android.gms.vision.Tracker;
-import com.google.android.gms.vision.face.Face;
-import com.google.android.gms.vision.face.FaceDetector;
-
-/**
- * Tracks the eye positions and state over time, managing an underlying graphic which renders googly
- * eyes over the source video.
- *
- * To improve eye tracking performance, it also helps to keep track of the previous landmark
- * proportions relative to the detected face and to interpolate landmark positions for future
- * updates if the landmarks are missing. This helps to compensate for intermediate frames where the
- * face was detected but one or both of the eyes were not detected. Missing landmarks can happen
- * during quick movements due to camera image blurring.
- */
-class GooglyFaceTracker extends Tracker {
-
- public static boolean[] gestures = new boolean[4];
- public static int gestureCount = 0;
- private float lastMid_x = 0;
- private float lastMid_y = 0;
- public static float verticalNod_min = 0;
- public static float verticalNod_max = 0;
- public static float horizontalNod_min = 0;
- public static float horizontalNod_max = 0;
- public static float smile_min = 0;
- public static float smile_max = 0;
- public static boolean BLINK_COMPLETED = false;
- public static boolean SMILE_COMPLETED = false;
- public static boolean VERTICAL_NOD = false;
- public static boolean HORIZONTAL_NOD = false;
- private static final int NOD_THRESHOLD = 60;
- private static final int RECT_WIDTH_THRESHOLD = 350;
- private static final float EYE_CLOSED_THRESHOLD = 0.4f;
- private static final float SMILE_THRESHOLD = 0.4f;
- private blinkEvent blinkListner;
- private faceDetectedEvent faceListner;
- private boolean isFace = false;
- private FaceGraphic mFaceGraphic;
- private GraphicOverlay mOverlay;
- private Rect rect = null;
- private int facecnt = 0;
- // Record the previously seen proportions of the landmark locations relative to the bounding box
- // of the face. These proportions can be used to approximate where the landmarks are within the
- // face bounding box if the eye landmark is missing in randA future update.
-// private Map mPreviousProportions = new HashMap<>();
-
- // Similarly, keep track of the previous eye open state so that it can be reused for
- // intermediate frames which lack eye landmarks and corresponding eye state.
- private boolean mPreviousIsLeftOpen = true;
- private boolean mPreviousIsRightOpen = true;
- private int eyeCnt = 0;
-
-
- //==============================================================================================
- // Methods
- //==============================================================================================
-
- GooglyFaceTracker(blinkEvent blinklstr,faceDetectedEvent facelstr,GraphicOverlay overlay) {
- this.blinkListner = blinklstr;
- this.faceListner = facelstr;
- mOverlay = overlay;
- mFaceGraphic = new FaceGraphic(overlay);
- }
-
- /**
- * Resets the underlying googly eyes graphic and associated physics state.
- */
- @Override
- public void onNewItem(int id, Face face) {
- }
-
- /**
- * Updates the positions and state of eyes to the underlying graphic, according to the most
- * recent face detection results. The graphic will render the eyes and simulate the motion of
- * the iris based upon these changes over time.
- */
- @Override
- public void onUpdate(FaceDetector.Detections detectionResults, Face face) {
-
- mOverlay.add(mFaceGraphic);
- mFaceGraphic.updateFace(face);
- rect = mFaceGraphic.getFaceRect();
- if (facecnt<3) {
- facecnt++;
- return;
- }
- isFace = true;
- int frameWidth = detectionResults.getFrameMetadata().getWidth();
- int frameHeight = detectionResults.getFrameMetadata().getHeight();
- float faceWidth = face.getWidth();
- int rectWidth = rect.width();
-
- /*if(faceWidth < 0.5f * frameWidth){
- return;
- }*/
-
- faceListner.onfaceDetectedEvent(true, rect, face,
- mOverlay.getCameraInfo(), frameWidth, frameHeight);
- /*if(gestures[0] && !BLINK_COMPLETED){
- float leftOpenScore = face.getIsLeftEyeOpenProbability();
- boolean isLeftOpen;
- if (leftOpenScore == Face.UNCOMPUTED_PROBABILITY) {
- isLeftOpen = mPreviousIsLeftOpen;
- } else {
- isLeftOpen = (leftOpenScore > EYE_CLOSED_THRESHOLD);
- }
-
- float rightOpenScore = face.getIsRightEyeOpenProbability();
- boolean isRightOpen;
-
- if (rightOpenScore == Face.UNCOMPUTED_PROBABILITY) {
- isRightOpen = mPreviousIsRightOpen;
- } else {
- isRightOpen = (rightOpenScore > EYE_CLOSED_THRESHOLD);
- }
-
- if (eyeCnt > 0) { // || to && condition SSS
-// if ((mPreviousIsLeftOpen != isLeftOpen && !isLeftOpen) || (mPreviousIsRightOpen != isRightOpen && !isRightOpen)) {
- if ((mPreviousIsLeftOpen != isLeftOpen && !isLeftOpen) && (mPreviousIsRightOpen != isRightOpen && !isRightOpen)) {
- BLINK_COMPLETED = true;
- gestureCount += 1;
- //if (blinkListner != null) blinkListner.onblinkEvent();
- }
- }
- else if (eyeCnt == 0 && (isLeftOpen || isRightOpen)) {
- eyeCnt = 1;
- }
- mPreviousIsLeftOpen = isLeftOpen;
- mPreviousIsRightOpen = isRightOpen;
- }
- if(gestures[1] && !SMILE_COMPLETED) {
- float smileScore = face.getIsSmilingProbability();
- //System.out.println("TMF20-face : "+ smileScore);
- smile_min = ((smileScore < smile_min) || smile_min == 0.0) ? smileScore : smile_min;
- smile_max = smileScore > smile_max ? smileScore : smile_max;
- if(smileScore == Face.UNCOMPUTED_PROBABILITY){
- smile_min = 0;
- smile_max = 0;
- }
- //System.out.println("TMF20-face : " + (smile_max - smile_min) + "---smile max : " + smile_max + " smile min : " + smile_min);
- if(((smile_max - smile_min) > SMILE_THRESHOLD) && (smile_min != 0.0f) && (smile_max != 0.0f)){
- SMILE_COMPLETED = true;
- gestureCount += 1;
- //System.out.println("TMF20-face : gesture count : " + gestureCount);
- }
- }
- if(gestures[2] && !HORIZONTAL_NOD && (rect.width() > RECT_WIDTH_THRESHOLD)){
- float x = rect.exactCenterX();
- if(0 == horizontalNod_min || 0 == horizontalNod_max){
- horizontalNod_min = x;
- horizontalNod_max = x;
- }else{
- if (x < horizontalNod_min) { horizontalNod_min = x; }
- if (x > horizontalNod_max) { horizontalNod_max = x; }
- }
- //System.out.println("TMF20-face : horizontal nod : " + (horizontalNod_max - horizontalNod_min) + "---horizontalNod max : " + horizontalNod_max + " horizontalNod min : " + horizontalNod_min);
- if((horizontalNod_max - horizontalNod_min) > NOD_THRESHOLD ){
- HORIZONTAL_NOD = true;
- gestureCount += 1;
- }
- }
- if(gestures[3] && !VERTICAL_NOD && (rect.width() > RECT_WIDTH_THRESHOLD)) {
- float y = rect.exactCenterY();
- //System.out.println("TMF20-face : y :"+ rect.exactCenterY());
- if(0 == verticalNod_min || 0 == verticalNod_max){
- verticalNod_min = y;
- verticalNod_max = y;
- }else{
- if(y < verticalNod_min){ verticalNod_min = y; }
- if(y > verticalNod_max){ verticalNod_max = y; }
- }
- //System.out.println("TMF20-face : vertical nod : " + (verticalNod_max - verticalNod_min) + "---verticalNod max : " + verticalNod_max + " verticalNod min : " + verticalNod_min);
- if((verticalNod_max - verticalNod_min) > NOD_THRESHOLD){
- VERTICAL_NOD = true;
- gestureCount += 1;
- }
- }
- if(gestureCount >= CameraActivity.faceMaxGestures *//*&& (SMILE_COMPLETED || BLINK_COMPLETED)*//*){
- //System.out.println("TMF20-face : gesture count [" + gestureCount + "] ---smile : " + SMILE_COMPLETED + " | Blink : " + BLINK_COMPLETED + " | Horizontal nod :" + HORIZONTAL_NOD + " | Vertical nod :" + VERTICAL_NOD);
- float leftOpenScore = face.getIsLeftEyeOpenProbability();
- float rightOpenScore = face.getIsRightEyeOpenProbability();
- //float smileScore = face.getIsSmilingProbability();
- //System.out.println("TMF20-face : left eye score" + leftOpenScore + " | right eye score" + rightOpenScore);
- if(leftOpenScore > 0.7 && rightOpenScore > 0.7) {
- //gestureCount = 0;
- smile_max = 0;
- smile_min = 0;
- verticalNod_min = 0;
- verticalNod_max = 0;
- horizontalNod_min = 0;
- horizontalNod_max = 0;
- BLINK_COMPLETED = false;
- SMILE_COMPLETED = false;
- VERTICAL_NOD = false;
- HORIZONTAL_NOD = false;
- if (blinkListner != null) blinkListner.onblinkEvent();
- }
- }*/
- }
-
- /**
- * Hide the graphic when the corresponding face was not detected. This can happen for
- * intermediate frames temporarily (e.g., if the face was momentarily blocked from
- * view).
- */
- @Override
- public void onMissing(FaceDetector.Detections detectionResults) {
- if (isFace) {
- int frameWidth = detectionResults.getFrameMetadata().getWidth();
- int frameHeight = detectionResults.getFrameMetadata().getHeight();
- mPreviousIsLeftOpen = true;
- mPreviousIsRightOpen = true;
- eyeCnt = 0;
- facecnt=0;
- isFace= false;
- faceListner.onfaceDetectedEvent(false,null,null,
- null, frameWidth, frameHeight);
- }
- mOverlay.remove(mFaceGraphic);
- rect = null;
- }
-
- /**
- * Called when the face is assumed to be gone for good. Remove the googly eyes graphic from
- * the overlay.
- */
- @Override
- public void onDone() {
- mOverlay.remove(mFaceGraphic);
- rect=null;
- }
-
-
-}
\ No newline at end of file
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/GraphicOverlay.java b/app/src/main/java/nprime/reg/sbi/googlevision/GraphicOverlay.java
deleted file mode 100644
index 5cbd5ae..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/GraphicOverlay.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (C) The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package nprime.reg.sbi.googlevision;
-
-import android.content.Context;
-import android.graphics.Canvas;
-import android.util.AttributeSet;
-import android.view.View;
-
-import com.google.android.gms.common.images.Size;
-import com.google.android.gms.vision.CameraSource;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * A view which renders a series of custom graphics to be overlayed on top of an associated preview
- * (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove
- * them, triggering the appropriate drawing and invalidation within the view.
- *
- * Supports scaling and mirroring of the graphics relative the camera's preview properties. The
- * idea is that detection items are expressed in terms of a preview size, but need to be scaled up
- * to the full view size, and also mirrored in the case of the front-facing camera.
- *
- * Associated {@link Graphic} items should use the following methods to convert to view coordinates
- * for the graphics that are drawn:
- *
- * - {@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the
- * supplied value from the preview scale to the view scale.
- * - {@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate
- * from the preview's coordinate system to the view coordinate system.
- *
- */
-public class GraphicOverlay extends View {
- private final Object mLock = new Object();
- private int mPreviewWidth;
- private float mWidthScaleFactor = 1.0f;
- private int mPreviewHeight;
- private float mHeightScaleFactor = 1.0f;
- private int mFacing = CameraSource.CAMERA_FACING_BACK;
- private Set mGraphics = new HashSet<>();
-
- /**
- * Base class for a custom graphics object to be rendered within the graphic overlay. Subclass
- * this and implement the {@link Graphic#draw(Canvas)} method to define the
- * graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}.
- */
- public static abstract class Graphic {
- private GraphicOverlay mOverlay;
-
- public Graphic(GraphicOverlay overlay) {
- mOverlay = overlay;
- }
-
- /**
- * Draw the graphic on the supplied canvas. Drawing should use the following methods to
- * convert to view coordinates for the graphics that are drawn:
- *
- * - {@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of
- * the supplied value from the preview scale to the view scale.
- * - {@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the
- * coordinate from the preview's coordinate system to the view coordinate system.
- *
- *
- * @param canvas drawing canvas
- */
- public abstract void draw(Canvas canvas);
-
- /**
- * Adjusts a horizontal value of the supplied value from the preview scale to the view
- * scale.
- */
- public float scaleX(float horizontal) {
- return horizontal * mOverlay.mWidthScaleFactor;
- }
-
- /**
- * Adjusts a vertical value of the supplied value from the preview scale to the view scale.
- */
- public float scaleY(float vertical) {
- return vertical * mOverlay.mHeightScaleFactor;
- }
-
- /**
- * Adjusts the x coordinate from the preview's coordinate system to the view coordinate
- * system.
- */
- public float translateX(float x) {
- if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) {
- return mOverlay.getWidth() - scaleX(x);
- } else {
- return scaleX(x);
- }
- }
-
- /**
- * Adjusts the y coordinate from the preview's coordinate system to the view coordinate
- * system.
- */
- public float translateY(float y) {
- return scaleY(y);
- }
-
- public void postInvalidate() {
- mOverlay.postInvalidate();
- }
- }
-
- public GraphicOverlay(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- /**
- * Removes all graphics from the overlay.
- */
- public void clear() {
- synchronized (mLock) {
- mGraphics.clear();
- }
- postInvalidate();
- }
-
- /**
- * Adds a graphic to the overlay.
- */
- public void add(Graphic graphic) {
- synchronized (mLock) {
- mGraphics.add(graphic);
- }
- postInvalidate();
- }
-
- /**
- * Removes a graphic from the overlay.
- */
- public void remove(Graphic graphic) {
- synchronized (mLock) {
- mGraphics.remove(graphic);
- }
- postInvalidate();
- }
-
- /**
- * Sets the camera attributes for size and facing direction, which informs how to transform
- * image coordinates later.
- */
- public void setCameraInfo(int previewWidth, int previewHeight, int facing) {
- synchronized (mLock) {
- mPreviewWidth = previewWidth;
- mPreviewHeight = previewHeight;
- mFacing = facing;
- }
- postInvalidate();
- }
-
- public Size getCameraInfo(){
- return new Size(mPreviewWidth,mPreviewHeight);
- }
- /**
- * Draws the overlay with its associated graphic objects.
- */
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
-
- synchronized (mLock) {
- if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) {
- mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth;
- mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight;
- }
-
- for (Graphic graphic : mGraphics) {
- graphic.draw(canvas);
- }
- }
- }
-}
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/blinkEvent.java b/app/src/main/java/nprime/reg/sbi/googlevision/blinkEvent.java
deleted file mode 100644
index 7cbd39d..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/blinkEvent.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package nprime.reg.sbi.googlevision;
-
-
-public interface blinkEvent {
- void onblinkEvent();
-}
diff --git a/app/src/main/java/nprime/reg/sbi/googlevision/faceDetectedEvent.java b/app/src/main/java/nprime/reg/sbi/googlevision/faceDetectedEvent.java
deleted file mode 100644
index e3a46af..0000000
--- a/app/src/main/java/nprime/reg/sbi/googlevision/faceDetectedEvent.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package nprime.reg.sbi.googlevision;
-
-
-import android.graphics.Rect;
-
-import com.google.android.gms.common.images.Size;
-import com.google.android.gms.vision.face.Face;
-
-/**
- * Created by Rajeev debnath on 30-03-2017.
- */
-
-public interface faceDetectedEvent {
- void onfaceDetectedEvent(boolean isface, Rect rect, Face face,
- Size size, int frameWidth, int frameHeight);
-}
diff --git a/app/src/main/java/nprime/reg/sbi/mds/DeviceMain.java b/app/src/main/java/nprime/reg/sbi/mds/DeviceMain.java
deleted file mode 100644
index a188dd8..0000000
--- a/app/src/main/java/nprime/reg/sbi/mds/DeviceMain.java
+++ /dev/null
@@ -1,453 +0,0 @@
-package nprime.reg.sbi.mds;
-
-import androidx.annotation.NonNull;
-import androidx.appcompat.app.AppCompatActivity;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.mmc.DataObjects.DeviceSnapshotResponse;
-import com.mmc.DataObjects.MSBDeviceRegistrationResponse;
-import com.mmc.DataObjects.MSBEncryptionCertResponse;
-import com.mmc.DataObjects.MSBKeyRotationResponse;
-
-import java.io.ByteArrayInputStream;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Date;
-
-import nprime.reg.sbi.face.MainActivity;
-import nprime.reg.sbi.face.R;
-import nprime.reg.sbi.mmc.MDServiceUtility;
-import nprime.reg.sbi.mmc.MMCHelper;
-import nprime.reg.sbi.mmc.ManagementClient;
-import nprime.reg.sbi.scanner.ResponseGenerator.ResponseGenHelper;
-import nprime.reg.sbi.secureLib.DeviceKeystore;
-import nprime.reg.sbi.utility.CommonDeviceAPI;
-import nprime.reg.sbi.utility.DeviceConstants;
-import nprime.reg.sbi.utility.ErrorList;
-import nprime.reg.sbi.utility.Logger;
-
-public class DeviceMain extends AppCompatActivity {
-
- public static final int HANDLER_STATUS = 1;
- public static final int HANDLER_TOAST = 2;
-
- public static MMCHelper mmcHelper;
- public static MDServiceUtility mdServiceUtility;
- public static DeviceMain deviceMain;
- public static DeviceKeystore deviceKeystore;
- public static ManagementClient managementClient = null;
- public static Context context;
- public static ErrorList errTable;
-
- public boolean mgmtServerConnectivity = true;
- public boolean serverStatus = false;
- public DeviceSnapshotResponse gSnapshotResponse;
- public String mainSerialNumber;
- public String mainDeviceCode;
- public MSBKeyRotationResponse gmsbKeyRotationResp;
- public CommonDeviceAPI deviceCommonDeviceAPI;
- public static long serverTimeStampinMillis = 0;
- public static boolean isSchedulerStarted = false;
- public boolean isRegistered = false;
-
- public static boolean isDeviceWhitelist = true;
- public static boolean isDeviceValidMDLicense = true;
- public static boolean isKeyRotationRequired = false;
- public static boolean isMDserviceStarted = false;
- public int advanceKeyRotationDays = 5;
- public MSBDeviceRegistrationResponse gmsbDeviceRegistrationResp;
- public MSBEncryptionCertResponse gmsbEncryptionCertResponse;
-
- TextView tvInitStatus;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_device_main);
-
- tvInitStatus = findViewById(R.id.tv_init_status);
-
- context = this;
- //deviceHelper = new DeviceHelper();
- mmcHelper = new MMCHelper();
- mdServiceUtility = new MDServiceUtility();
- //deviceMain = new DeviceMain();
- deviceKeystore = new DeviceKeystore();
- deviceMain.deviceCommonDeviceAPI = new CommonDeviceAPI();
- errTable = new ErrorList();
- new Thread(){
- @Override
- public void run() {
- MainActivity.initSuccessful = init();
- if(MainActivity.initSuccessful) {
- MainActivity.sharedPreferences.edit().putLong("LastInitTimeMills", new Date().getTime()).apply();
- setResult(Activity.RESULT_OK);
- }else {
- setResult(Activity.RESULT_CANCELED);
- }
- ((Activity)context).finish();
- }
- }.start();
- }
-
- public void sendInitMessage(int what, Object obj) {
- Message message = new Message();
- message.what = what;
- message.obj = obj;
- handler.sendMessage(message);
- }
-
- Handler handler = new Handler(Looper.getMainLooper()){
- @Override
- public void handleMessage(@NonNull Message msg) {
- super.handleMessage(msg);
- switch (msg.what){
- case HANDLER_STATUS :
- String text = (String)msg.obj;
- tvInitStatus.setText(text);
- break;
- case HANDLER_TOAST :
- String toastText = (String)msg.obj;
- Toast.makeText(DeviceMain.this, toastText, Toast.LENGTH_SHORT).show();
- break;
- default:
- }
-
- }
- };
- public boolean init(){
- deviceMain.mainSerialNumber = deviceMain.deviceCommonDeviceAPI.getSerialNumber();
-
- deviceKeystore.initStore();
- if (null == managementClient){
- managementClient = new ManagementClient(mdServiceUtility, mainSerialNumber);
- }
-
- deviceMain.serverStatus = managementClient.pingtoMgmtServer();
- if(true == deviceMain.serverStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.DEBUG, DeviceConstants.MSPMDSERVICE, "Ping to Management Client is Successful");
- sendInitMessage(HANDLER_STATUS, "Ping to Management Client is Successful");
- }
- }
- else
- {
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Unable to reach Management Client");
- sendInitMessage(HANDLER_STATUS, "Unable to reach Management Client");
- Logger.w(DeviceConstants.LOG_TAG, "Unable to reach Management Client");
- }
- }
-
- boolean readStatus = managementClient.readSnapshotDetails();
- if(true == readStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.DEBUG, DeviceConstants.MSPMDSERVICE, "Snapshot details read successfully");
- sendInitMessage(HANDLER_STATUS, "Snapshot details read successfully");
- }
-
- if(null == deviceMain.gSnapshotResponse || !deviceMain.mainSerialNumber.equals(deviceMain.gSnapshotResponse.serialNumber)) {
- Logger.w(DeviceConstants.LOG_TAG, "New Device connected.");
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //FileUtils.cleanDirectory(new File(deviceMain.appFolderPath));
- deviceKeystore.removeKeys();
- }
- gmsbKeyRotationResp = null;
- }
- else if (null != deviceMain.gSnapshotResponse){
- deviceMain.mainDeviceCode = deviceMain.gSnapshotResponse.serialNumber; //gSnapshotResponse.deviceCodeUUID;
- }
- }
-
- //GetSnapshotDetails
- deviceMain.serverStatus = managementClient.fetchSnapshotDetails();
- if(true == deviceMain.serverStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Snapshot details received successfully from server");
- sendInitMessage(HANDLER_STATUS, "Snapshot details received successfully from server");
- }
-
- int retCode = Integer.valueOf(DeviceMain.deviceMain.gSnapshotResponse.responseCode);
- if (retCode != 0){
- //deviceCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", retCode + " : " + DeviceMain.deviceMain.gSnapshotResponse.description);
- sendInitMessage(HANDLER_TOAST, retCode + " : " + DeviceMain.deviceMain.gSnapshotResponse.description);
- return false;
- }
-
- //System.out.println("From Snapshot : " + gSnapshotResponse.serverTimeStamp);
- //Checking Timestamp
- serverTimeStampinMillis = deviceMain.deviceCommonDeviceAPI.getMillisfromISO(DeviceMain.deviceMain.gSnapshotResponse.serverTimeStamp);
-
- //prompt MDS Download
- if (true == Boolean.valueOf(DeviceMain.deviceMain.gSnapshotResponse.deviceServiceUpdateRequired)){
- //deviceCommonDeviceAPI.showMessagewithLink("Face Auth SBI", "Please install latest MDS, link : ", gSnapshotResponse.deviceServiceDownloadURL);
- sendInitMessage(HANDLER_TOAST, "Face Auth SBI - Please install latest MDS,\n link : " + deviceMain.gSnapshotResponse.deviceServiceDownloadURL);
- }
-
- String currentTime = deviceMain.deviceCommonDeviceAPI.getISOTimeStamp();
- //System.out.println("Current Timestamp : " + currentTime);
- Logger.i(DeviceConstants.LOG_TAG, "Current Timestamp : " + currentTime);
-
- long currentTimeinmillis = deviceMain.deviceCommonDeviceAPI.getMillisfromISO(currentTime);
-
- long timediff = Math.abs(serverTimeStampinMillis - currentTimeinmillis);
-
- if (timediff > DeviceConstants.MDS_TIMESYNC_TOLERANCE){
- Logger.e(DeviceConstants.LOG_TAG, "System time(" + currentTime +
- ") is not in sync with server time(" + DeviceMain.deviceMain.gSnapshotResponse.serverTimeStamp + ")");
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Time Sync Failed");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Time Sync Failed");
- }
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //FileUtils.cleanDirectory(new File(deviceMain.appFolderPath));
- deviceKeystore.removeKeys();
- }
- DeviceMain.deviceMain.gmsbKeyRotationResp = null;
- //deviceCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Time Sync Failed, Please correct system time and restart Face Auth SBI");
- sendInitMessage(HANDLER_TOAST, "Time Sync Failed, Please correct system time and restart Face Auth SBI");
- return false;
- }
- }
- else
- {
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- Logger.i(DeviceConstants.LOG_TAG, "Failed to fetch Snapshot details");
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Failed to fetch Snapshot details");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Failed to fetch Snapshot details");
- }
-
- //readSnapshotDetails
- readStatus = managementClient.readSnapshotDetails();
- if(true == readStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.DEBUG, DeviceConstants.MSPMDSERVICE, "Snapshot details read successfully");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Snapshot details read successfully");
- }
- }
- else
- {
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.DEBUG, DeviceConstants.MSPMDSERVICE, "Failed to read snapshot from filesystem");
- //deviceCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Snapshot not available, Please connect to internet and restart Face Auth SBI");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Failed to read snapshot from filesystem");
- sendInitMessage(HANDLER_TOAST, "Face Auth SBI" + "Snapshot not available, Please connect to internet and restart Face Auth SBI");
- }
- return false;
- }
- }
- if (false == mdServiceUtility.checkSnapshotValidity())
- {
- return false;
- }
-
- //Time Sync Scheduler
- if (false == isSchedulerStarted){
- boolean schedulerStatus = mdServiceUtility.snapshotValidityScheduler();
- if (schedulerStatus){
- isSchedulerStarted = true;
- //Logger.WriteLog(LOGTYPE.INFO, "Snapshot validity scheduler started");
- }
- else{
- isSchedulerStarted = false;
- //Logger.WriteLog(LOGTYPE.ERROR, "Snapshot validity scheduler failed to start");
- return false;
- }
- }
-
- //updating current uuid
- if (null != deviceMain.gSnapshotResponse){
- deviceMain.mainDeviceCode = deviceMain.gSnapshotResponse.serialNumber; //gSnapshotResponse.deviceCodeUUID;
- isRegistered = Boolean.valueOf(deviceMain.gSnapshotResponse.isDeviceRegistered);
- isDeviceWhitelist = Boolean.valueOf(deviceMain.gSnapshotResponse.isWhiteListed);
- isDeviceValidMDLicense = Boolean.valueOf(deviceMain.gSnapshotResponse.isDeviceValid);
- }
-
- if ((!isDeviceValidMDLicense)){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, errTable.getMessage("MDSRVMSG_0020"));
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + errTable.getMessage("MDSRVMSG_0020"));
- return false;
- }
-
- if ((!isDeviceWhitelist)){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, errTable.getMessage("MDSRVMSG_0013"));
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + errTable.getMessage("MDSRVMSG_0013"));
- //TBD : Dialog BOX with Serial number
- return false;
- }
-
- //TBD : Compute Key Validity in days and update deviceKeyValidityDays
- if (!isRegistered){
- isRegistered = managementClient.registerDevice();
- if (isRegistered){
- deviceMain.serverStatus = managementClient.fetchSnapshotDetails();
- if(deviceMain.serverStatus){
- Logger.i(DeviceConstants.LOG_TAG, "Device Snapshot updated");
- }
-
- mainDeviceCode = deviceMain.gmsbDeviceRegistrationResp.serialNumber;//deviceMain.gmsbDeviceRegistrationResp.deviceCodeUUID;
-
- deviceMain.gSnapshotResponse.isDeviceRegistered = String.valueOf(isRegistered);
- deviceMain.gSnapshotResponse.deviceCodeUUID = deviceMain.gmsbDeviceRegistrationResp.serialNumber;//deviceMain.gmsbDeviceRegistrationResp.deviceCodeUUID;
- }
- }
-
-
- //get encryption certificate only if thumbprint is not matching
- //Fetch encryption cert
- /*if (DeviceMain.deviceMain.mgmtServerConnectivity){
- readStatus = managementClient.readEncryptionCert();
- if(true == readStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- Logger.i(DeviceConstants.LOG_TAG, "Encryption cert read successfully");
- //mdServiceUtility.showNotification(LOGTYPE.DEBUG, DeviceConstants.MSPMDSERVICE, "Encryption cert read successfully");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Encryption cert read successfully");
- }
- }
-
- if (null == DeviceMain.deviceMain.gmsbEncryptionCertResponse ||
- null == DeviceMain.deviceMain.gmsbEncryptionCertResponse.encryptionCertData ||
- DeviceMain.deviceMain.gmsbEncryptionCertResponse.encryptionCertData.isEmpty()){
- deviceMain.serverStatus = managementClient.fetchEncrytionCert();
- if(true == deviceMain.serverStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- Logger.i(DeviceConstants.LOG_TAG, "Encryption cert received successfully from server");
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Encryption cert received successfully from server");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Encryption cert received successfully from server");
- }
- }
- }
- else{
- try {
- byte []encryptionCert = org.apache.commons.codec.binary.Base64.decodeBase64(DeviceMain.deviceMain.gmsbEncryptionCertResponse.encryptionCertData.getBytes());
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- X509Certificate x509Cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(encryptionCert));
- String encryptThumbprint = deviceMain.deviceCommonDeviceAPI.getThumbprint(x509Cert);
-
- if (false == DeviceMain.deviceMain.gSnapshotResponse.encryptionCertThumbprint.equalsIgnoreCase(encryptThumbprint)){
- deviceMain.serverStatus = managementClient.fetchEncrytionCert();
- if(true == deviceMain.serverStatus){
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- Logger.i(DeviceConstants.LOG_TAG, "Encryption cert received successfully from server");
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Encryption cert received successfully from server");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Encryption cert received successfully from server");
- }
- }
- }
- }catch (CertificateException e){
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- }
- }*/
- //Fetch encryption cert
-
- boolean bValidCert = false;
-
- bValidCert = mdServiceUtility.CheckValidCertificate();
- if (false == bValidCert) {
- //Remove existing Keys
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- deviceKeystore.removeKeys();
- }
- gmsbKeyRotationResp = null;
- //Generate keypair at local keystore and retrieve Device Public Key
- deviceMain.serverStatus = managementClient.initiateKeyRotation();
- if(true == deviceMain.serverStatus){
-
- Logger.i(DeviceConstants.LOG_TAG, "Key is installed");
- managementClient.fetchSnapshotDetails();
-
- bValidCert = mdServiceUtility.CheckValidCertificate();
-
- if (false == bValidCert){
- Logger.i(DeviceConstants.LOG_TAG, "Key Expired or does not exist");
- return false;
- }
- //String serialNumber = DeviceMain.deviceMain.deviceCommonDeviceAPI.getSerialNumber();
- //deviceCommonDeviceAPI.WriteFiletoHost((byte)DeviceIDDetails.RESERVED_MOSIP_CERT_1, serialNumber.getBytes());
-
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, errTable.getMessage("MDSRVMSG_0014"));
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + errTable.getMessage("MDSRVMSG_0014"));
- Logger.i(DeviceConstants.LOG_TAG, "Key Rotation completed");
- }
- }
- else {
- Logger.i(DeviceConstants.LOG_TAG, "Key installation failed");
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Key Expired and Rotation Failed");
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + "Key Expired and Rotation Failed");
- Logger.e(DeviceConstants.LOG_TAG, "Key expired and Rotation Failed");
- }
- return false;
- }
- }
- else {
- if (!mdServiceUtility.checkAdvanceKeyRotation()){
- deviceMain.serverStatus = managementClient.initiateKeyRotation();
- if(true == deviceMain.serverStatus){
- Logger.i(DeviceConstants.LOG_TAG, "Key is installed");
- deviceMain.serverStatus = managementClient.fetchSnapshotDetails();
-
- bValidCert = mdServiceUtility.CheckValidCertificate();
-
- if (!bValidCert){
- Logger.i(DeviceConstants.LOG_TAG, "Key Expired");
- return false;
- }
- //String serialNumber = DeviceMain.deviceMain.deviceCommonDeviceAPI.getSerialNumber();
- //deviceCommonDeviceAPI.WriteFiletoHost((byte)DeviceIDDetails.RESERVED_MOSIP_CERT_1, serialNumber.getBytes());
-
- if (DeviceMain.deviceMain.mgmtServerConnectivity){
- //mdServiceUtility.showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, errTable.getMessage("MDSRVMSG_0014"));
- sendInitMessage(HANDLER_STATUS, DeviceConstants.MSPMDSERVICE + errTable.getMessage("MDSRVMSG_0014"));
- Logger.i(DeviceConstants.LOG_TAG, "Key Rotation completed...");
- }
- }
- }
- }
-
-
-
- //TBD : Compute Key Validity in days and update deviceKeyValidityDays
- /* if (!isRegistered){
- isRegistered = managementClient.registerDevice();
- if (isRegistered){
- deviceMain.serverStatus = managementClient.fetchSnapshotDetails();
- if(true == deviceMain.serverStatus){
- Logger.i(DeviceConstants.LOG_TAG, "Device Snapshot updated");
- }
-
- deviceMain.mainDeviceCode = gSnapshotResponse.serialNumber; //deviceMain.gmsbDeviceRegistrationResp.deviceCodeUUID;
-
- deviceMain.gSnapshotResponse.isDeviceRegistered = String.valueOf(isRegistered);
- deviceMain.gSnapshotResponse.deviceCodeUUID = deviceMain.gmsbDeviceRegistrationResp.deviceCodeUUID;
-
- //deviceCommonDeviceAPI.WriteFiletoHost((byte)DeviceIDDetails.RESERVED_MOSIP_CERT_2, mainDeviceCode.getBytes());
-
- //String serialNumber = DeviceMain.deviceMain.deviceCommonDeviceAPI.getSerialNumber();
- //deviceCommonDeviceAPI.WriteFiletoHost((byte)DeviceIDDetails.RESERVED_MOSIP_CERT_1, serialNumber.getBytes());
- }
- }*/
- return true;
- }
-
- public String getDeviceDriverInfo(DeviceConstants.ServiceStatus currentStatus, String szTimeStamp, String requestType) {
- return ResponseGenHelper.getDeviceDriverInfo(currentStatus, szTimeStamp, requestType);
- }
-
- public String discoverDevice(DeviceConstants.ServiceStatus currentStatus, String szTimeStamp, String requestType) {
- return ResponseGenHelper.getDeviceDiscovery(currentStatus, szTimeStamp, requestType);
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/nprime/reg/sbi/mmc/MDServiceUtility.java b/app/src/main/java/nprime/reg/sbi/mmc/MDServiceUtility.java
deleted file mode 100644
index e69bf9e..0000000
--- a/app/src/main/java/nprime/reg/sbi/mmc/MDServiceUtility.java
+++ /dev/null
@@ -1,343 +0,0 @@
-package nprime.reg.sbi.mmc;
-
-import java.io.InputStream;
-import java.security.KeyStore;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.X509Certificate;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManagerFactory;
-
-import nprime.reg.sbi.face.MainActivity;
-import nprime.reg.sbi.face.R;
-import nprime.reg.sbi.faceCaptureApi.KeysNotFoundException;
-import nprime.reg.sbi.mds.DeviceMain;
-import nprime.reg.sbi.utility.CommonDeviceAPI;
-import nprime.reg.sbi.utility.DeviceConstants;
-import nprime.reg.sbi.utility.Logger;
-import okhttp3.OkHttpClient;
-
-public class MDServiceUtility {
-
- CommonDeviceAPI devCommonDeviceAPI;
- public long lastSnapshotValidityCheck = 0L;
-
- public MDServiceUtility() {
- devCommonDeviceAPI = new CommonDeviceAPI();
- }
-
- public OkHttpClient getHttpClient() {
- OkHttpClient testClient = null;
- try {
- /*javax.security.cert.X509Certificate cert = javax.security.cert.X509Certificate.getInstance(DeviceConstants.sslCert.getBytes());
- String shaValue = Base64.encodeToString(sha256Digest(cert.getPublicKey().getEncoded()), 0);
-
- CertificatePinner certificatePinner = new CertificatePinner.Builder()
- .add("mmc.nprime.in", "sha256/" + shaValue)
- .build();*/
- //javax.security.cert.X509Certificate x509Certificate = javax.security.cert.X509Certificate.getInstance(DeviceConstants.sslCert.getBytes());
- CertificateFactory factory = CertificateFactory.getInstance("X.509");
- InputStream is = DeviceMain.context.getResources().openRawResource(R.raw.sslcert);//new ByteArrayInputStream(x509Certificate.getEncoded());
- Certificate cert = factory.generateCertificate(is);
-
- String keyStoreType = KeyStore.getDefaultType();
- KeyStore keyStore = KeyStore.getInstance(keyStoreType);
- keyStore.load(null, null);
- keyStore.setCertificateEntry("ca", cert);
-
- // creating a TrustManager that trusts the CAs in our KeyStore
- String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
- tmf.init(keyStore);
-
- // creating an SSLSocketFactory that uses our TrustManager
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, tmf.getTrustManagers(), null);
-
- /*KeyStore keyStore = SslUtils.getKeyStore(context, fileName);
- SSLContext sslContext = SSLContext.getInstance("SSL");
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- trustManagerFactory.init(keyStore);*/
- //sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
- testClient = new OkHttpClient.Builder()
- .sslSocketFactory(sslContext.getSocketFactory())
- //.certificatePinner(certificatePinner)
- .build();
- }catch (Exception e){
- e.printStackTrace();
- }
- return testClient;
- }
- private byte[] sha256Digest(byte[] data) {
- MessageDigest mdSha256 = null;
- try {
- mdSha256 = MessageDigest.getInstance("SHA-256");
- } catch (NoSuchAlgorithmException e1) {
- e1.printStackTrace();
- //System.out.println("Error initializing SHA1 message digest");
- }
- mdSha256.update(data);
- byte[] sha256hash = mdSha256.digest();
- return sha256hash;
- }
-
- public boolean checkSnapshotValidity() {
- boolean validityStatus = true;
- long snapshotValidity = devCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity);
-
- long currentTimeinmillis = devCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.deviceCommonDeviceAPI.getISOTimeStamp());
-
- if (snapshotValidity > 0 && currentTimeinmillis > 0){
- long timediff = snapshotValidity - currentTimeinmillis;
-
- if (timediff <= 0){//Already expired case
- Logger.w(DeviceConstants.LOG_TAG, "Timesync validity is expired (" + DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity
- + "), Connect to Internet and Restart Face Auth SBI" );
- //devCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Timesync validity is expired, Connect to Internet and Restart Face Auth SBI");
- //new File(DeviceMain.deviceMain.appFolderPath + "\\snapShot.info").delete();
- DeviceMain.deviceMain.gSnapshotResponse = null;
- validityStatus = false;
- }
- }
- return validityStatus;
- }
-
- public boolean snapshotValidityScheduler() {
- boolean status = false;
- try{
- Timer time = new Timer();
- status = true;
- TimeSyncScheduler tSyncScheduler = new TimeSyncScheduler();
- time.scheduleAtFixedRate(tSyncScheduler, 0, DeviceConstants.MDS_SCHEDULER_INTERVAL);
- }
- catch(Exception ex){
- status = false;
- }
- return status;
- }
-
- public boolean CheckValidCertificate() {
-
- boolean bStatus = false;
- try {
- if (true == Boolean.valueOf(DeviceMain.deviceMain.gSnapshotResponse.mandatoryKeyRotation)){
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Mandatory key rotation enabled, please initiate key rotation");
- return false;
- }
-
- if (false == isValidDeviceforCertificate()){
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Device serial does not match with device certificate");
- return false;
- }
-
-
- X509Certificate certificate = DeviceMain.deviceKeystore.getX509Certificate();
-
- if (null != certificate)
- {
- Date date = new Date();
- certificate.checkValidity(date);
- bStatus = true;
- Logger.i(DeviceConstants.LOG_TAG, "Face Auth SBI :: Device has valid certificate!!!");
- }
- }
- catch(CertificateExpiredException | CertificateNotYetValidException e){
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Certificate is expired or will be expired shortly");
- bStatus = false;
- }
- catch(Exception e){
- bStatus = false;
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Error occurred while checking certficate");
- }
- return bStatus;
- }
-
- private boolean isValidDeviceforCertificate() {
- boolean status = false;
- String serialNo = DeviceMain.deviceMain.mainSerialNumber;
- String commonName = "";
-
- if (!DeviceMain.deviceMain.mgmtServerConnectivity){
- return true;
- }
-
- try{
- X509Certificate certificate = DeviceMain.deviceKeystore.getX509Certificate();
-
- if (null == certificate){
- status = false;
- }
- else{
- commonName = getCommonName(certificate);
-
- if (commonName.startsWith(serialNo)){
- status = true;
- }
- else{
- status = false;
- }
- }
- }
- catch(KeysNotFoundException ex){
- status = false;
- Logger.w(DeviceConstants.LOG_TAG, "Face Auth SBI :: Device key not found");
- }
- catch(Exception ex){
- status = false;
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: While validating Certificate of connected device");
- }
-
- return status;
- }
-
- private String getCommonName(X509Certificate c) {
- for (String each : c.getSubjectDN().getName().split(",\\s*")) {
- if (each.startsWith("CN=")) {
- String result = each.substring(3);
- return result;
- }
- }
- throw new IllegalStateException("Missed CN in Subject DN: "
- + c.getSubjectDN());
- }
-
- public boolean checkAdvanceKeyRotation() {
- boolean bStatus = false;
-
- try {
- X509Certificate certificate = DeviceMain.deviceKeystore.getX509Certificate();
-
- if (null != certificate)
- {
- Date date = new Date();
- Calendar calender = Calendar.getInstance();
- calender.setTime(date);
- calender.add(Calendar.DATE, DeviceMain.deviceMain.advanceKeyRotationDays);
-
- certificate.checkValidity(calender.getTime());
- bStatus = true;
- }
- }
- catch(CertificateExpiredException | CertificateNotYetValidException e){
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Certificate is expired or will be expired shortly");
- bStatus = false;
- }
- catch(Exception e){
- Logger.e(DeviceConstants.LOG_TAG, "Face Auth SBI :: Error while checking Advance Key Rotation");
- bStatus = false;
- }
-
- return bStatus;
- }
-
- public boolean checkSnapshotValidityAndInit() {
- boolean validityStatus = true;
-
- if (!DeviceMain.deviceMain.mgmtServerConnectivity){
- return true;
- }
-
- if(null == DeviceMain.deviceMain.gSnapshotResponse){
- MDServiceUtility mdServiceUtility = new MDServiceUtility();
- CommonDeviceAPI commonDeviceAPI = new CommonDeviceAPI();
- ManagementClient managementClient = new ManagementClient(mdServiceUtility, commonDeviceAPI.getSerialNumber());
- managementClient.readSnapshotDetails();
- }
- long snapshotValidity = devCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity);
-
- long currentTimeinmillis = devCommonDeviceAPI.getMillisfromISO(
- devCommonDeviceAPI.getISOTimeStamp());
-
- if (snapshotValidity > 0 && currentTimeinmillis > 0){
- long timediff = snapshotValidity - currentTimeinmillis;
-
- if (timediff <= 0){//Already expired case
- Logger.w(DeviceConstants.LOG_TAG, "Timesync validity is expired (" + DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity
- + "), Trying to reach Management Server" );
- //devCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Timesync validity is expired, Trying to reach Management Server");
- //new File(DeviceMain.deviceMain.appFolderPath + "\\snapShot.info").delete();
- DeviceMain.deviceMain.gSnapshotResponse = null;
- validityStatus = false;
- MainActivity.initSuccessful = false;
- MainActivity.sharedPreferences.edit().putLong("LastInitTimeMills", 0).apply();
- //doInitDataInThread();
- }
- }
- return validityStatus;
- }
-
- public class TimeSyncScheduler extends TimerTask
- {
- public TimeSyncScheduler(){
- }
-
- public void run()
- {
- long currentTime = (new Date()).getTime();
- if ((currentTime - lastSnapshotValidityCheck) < DeviceConstants.MDS_SCHEDULER_INTERVAL/2){
- return;
- }
- performSnapshotValidityCheck();
- lastSnapshotValidityCheck = (new Date()).getTime();
- }
- }
-
- private void performSnapshotValidityCheck() {
- if (!DeviceMain.deviceMain.mgmtServerConnectivity){
- return;
- }
-
- Logger.i(DeviceConstants.LOG_TAG, "Starting Snapshot Validity check" );
-
- long snapshotValidity = DeviceMain.deviceMain.deviceCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity);
-
- long currentTimeinmillis = DeviceMain.deviceMain.deviceCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.deviceCommonDeviceAPI.getISOTimeStamp());
-
- if (snapshotValidity > 0 && currentTimeinmillis > 0){
- long timediff = snapshotValidity - currentTimeinmillis;
-
- if (timediff < DeviceConstants.MDS_SNAPSHOTVALIDITY_WARNING){
- DeviceMain.deviceMain.init();
- }
-
- snapshotValidity = devCommonDeviceAPI.getMillisfromISO(
- DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity);
-
- timediff = snapshotValidity - currentTimeinmillis;
-
- if (timediff <= 0){//Already expired case
- Logger.i(DeviceConstants.LOG_TAG, "Timesync validity is expired (" + DeviceMain.deviceMain.gSnapshotResponse.snapshotValidity
- + "), Please connect to internet and restart Face Auth SBI" );
- //devCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Timesync validity is expired, Please connect to internet and restart Face Auth SBI...");
- //new File(DeviceMain.deviceMain.appFolderPath + "\\snapShot.info").delete();
- DeviceMain.deviceMain.gSnapshotResponse = null;
- }
- else if (timediff < DeviceConstants.MDS_SNAPSHOTVALIDITY_WARNING){
- int hrs = (int)(timediff/3600000); // 1 hr (millisecond) - 3600000
- if (hrs > 0){
- //showNotification(LOGTYPE.INFO, DeviceConstants.MSPMDSERVICE, "Connect to Internet in " + hrs + " hour(s) and restart Face Auth SBI");
- Logger.i(DeviceConstants.LOG_TAG, "Connect to Internet in " + hrs + " hour(s) and restart Face Auth SBI" );
- }
- else{
- //devCommonDeviceAPI.showAlwaysOnTopMessage("Face Auth SBI", "Connect to Internet now and restart Face Auth SBI");
- Logger.i(DeviceConstants.LOG_TAG, "Connect to Internet now and restart Face Auth SBI" );
- }
- }
- }
- }
-
-}
diff --git a/app/src/main/java/nprime/reg/sbi/mmc/MMCHelper.java b/app/src/main/java/nprime/reg/sbi/mmc/MMCHelper.java
deleted file mode 100644
index 9463ac0..0000000
--- a/app/src/main/java/nprime/reg/sbi/mmc/MMCHelper.java
+++ /dev/null
@@ -1,622 +0,0 @@
-package nprime.reg.sbi.mmc;
-
-import android.util.Base64;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.mmc.DataObjects.DeviceData;
-import com.mmc.DataObjects.DeviceDataRequest;
-import com.mmc.DataObjects.DeviceRegistration;
-import com.mmc.DataObjects.DeviceSnapshot;
-import com.mmc.DataObjects.MSBDeviceRegistration;
-import com.mmc.DataObjects.MSBEncryptionCert;
-import com.mmc.DataObjects.MSBKeyRotation;
-
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.StringReader;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PublicKey;
-import java.security.SignatureException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Random;
-
-import nprime.reg.sbi.faceCaptureApi.DeviceIDDetails;
-import nprime.reg.sbi.mds.DeviceMain;
-import nprime.reg.sbi.scanner.ResponseGenerator.ResponseGenHelper;
-import nprime.reg.sbi.utility.CommonDeviceAPI;
-import nprime.reg.sbi.utility.DeviceConstants;
-import nprime.reg.sbi.utility.Logger;
-
-public class MMCHelper {
- CommonDeviceAPI libCommonDeviceAPI;
- MMCServiceUtility mmcServiceUtility;
-
- ObjectMapper oB = null;
-
- public MMCHelper() {
- libCommonDeviceAPI = new CommonDeviceAPI();
- mmcServiceUtility = new MMCServiceUtility();
-
- oB = new ObjectMapper();
- }
-
- public String getMsbDeviceSnapShot() {
- String responseBody = "";
- CertificateFactory cf;
- byte[] headerBytes = null;
- byte[] payloadBytes = null;
- JSONObject data = new JSONObject();
- String msbDeviceSnapshotRequest = "";
-
- try {
-
- if (oB == null){
- oB = new ObjectMapper();
- }
-
- cf = CertificateFactory.getInstance("X.509");
-
- byte[] x509MOSIPCertByte = libCommonDeviceAPI.readFilefromHost((byte) DeviceIDDetails.HOST_CERT);
- X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(x509MOSIPCertByte));
-
- //HeaderData
- headerBytes = libCommonDeviceAPI.getHeader(certificate);
-
- //Payload
- payloadBytes = getDeviceSnapshotData();
-
- String encodedData = getJwtEncodedData(headerBytes, payloadBytes, certificate);
-
- data.put("msbDeviceSnapshot", encodedData);
-
- msbDeviceSnapshotRequest = data.toString();
-
- responseBody = mmcServiceUtility.getDataFromMMC(msbDeviceSnapshotRequest);
- } catch (CertificateException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return responseBody;
- }
-
- private String getJwtEncodedData(byte[] headerBytes, byte[] payloadBytes, X509Certificate certificate) {
- //HeaderData
- String headerBuffer = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(headerBytes);//Base64.encodeToString(headerBytes, Base64.NO_PADDING);
-
- //Payload
- String payloadBuffer = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(payloadBytes);//Base64.encodeToString(payloadBytes, Base64.NO_PADDING);
-
- String signString = headerBuffer + "." + payloadBuffer;
-
- //Signature
- String signatureBuffer = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
- libCommonDeviceAPI.getSignatureMMCKey(signString.getBytes() , certificate));
- //Base64.encodeToString(libCommonDeviceAPI
- //.getSignatureMMCKey(signString.getBytes() , certificate), Base64.NO_PADDING);
-
- String encodedData = signString + "." + signatureBuffer;
-
- return encodedData;
- }
-
- private byte[] getDeviceSnapshotData() {
- byte[] deviceSnapshotData = null;
- try
- {
-
- DeviceSnapshot deviceSnapshotPayload = new DeviceSnapshot();
- deviceSnapshotPayload.uniqueTransactionId = getUniqueID();
- deviceSnapshotPayload.timeStamp = libCommonDeviceAPI.getISOTimeStamp();
- deviceSnapshotPayload.serialNumber = libCommonDeviceAPI.getSerialNumber();
- deviceSnapshotPayload.deviceCodeUUID = libCommonDeviceAPI.getSerialNumber();//DeviceMain.deviceMain.mainDeviceCode;
- deviceSnapshotPayload.modelID = DeviceConstants.DEVICEMODEL;
- deviceSnapshotPayload.deviceProviderId = DeviceConstants.PROVIDERID;
- deviceSnapshotPayload.bioType = "Face";
- deviceSnapshotPayload.certificationLevel = "L0";
- deviceSnapshotPayload.devicePurpose = DeviceConstants.PURPOSE;
- deviceSnapshotPayload.env = DeviceConstants.ENVIRONMENT;
- deviceSnapshotPayload.deviceServiceVersion = DeviceConstants.MDSVERSION;
- deviceSnapshotPayload.specVersion = DeviceConstants.REGSERVER_VERSION;
- deviceSnapshotPayload.hostos = DeviceConstants.OSTYPE;
-
- deviceSnapshotData = oB.writeValueAsString(deviceSnapshotPayload).getBytes();
-
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
-
-
- return deviceSnapshotData;
- }
-
- private String getUniqueID() {
- int trid = 10000000 + new Random().nextInt(90000000);
- return String.valueOf(trid);
- }
-
- public boolean evaluateMMCResponse(String responseData) {
- byte[] headerBuffer = null;
- byte[] signatureBuffer = null;
- String responseToken;
- boolean certVerifyStatus = false;
- try {
-
- if (0 == responseData.length()){
- return false;
- }
-
- JSONObject requestfromMDS = libCommonDeviceAPI.parseJsonRequest(new BufferedReader(new StringReader(responseData)));
- if(null == requestfromMDS){
- return false;
- }
-
- if (requestfromMDS.length() != 1) {
-
- Logger.d(DeviceConstants.LOG_TAG, "Face SBI :: " + requestfromMDS.get("description"));
- //libCommonDeviceAPI.showAlwaysOnTopMessage("Face SBI", requestfromMDS.get("description").toString());
- return false;
- }
-
- String requestType = requestfromMDS.names().getString(0);
-
- responseToken = requestfromMDS.get(requestType).toString();
- String []mdsResponseArray = responseToken.split("\\.");
-
- headerBuffer = java.util.Base64.getUrlDecoder().decode(mdsResponseArray[0]); //Base64.decode(mdsResponseArray[0], Base64.DEFAULT);
-
- String hostCert = new JSONObject(new String(headerBuffer)).getJSONArray("x5c").getString(0);
-
- CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
- //InputStream stream = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(hostCert));
- InputStream stream = new ByteArrayInputStream(Base64.decode(hostCert, Base64.DEFAULT));
- X509Certificate hostX509Cert = (X509Certificate) certFactory.generateCertificate(stream);
-
- //Check Trust of Certificate if successful then verify Signature
-
- if (evaluateTrust(hostX509Cert)) {
-
- //Signature
- signatureBuffer = java.util.Base64.getUrlDecoder().decode(mdsResponseArray[2]); //Base64.decode(mdsResponseArray[2], Base64.DEFAULT);
-
- certVerifyStatus = libCommonDeviceAPI.verifySignature( (mdsResponseArray[0] + "." + mdsResponseArray[1]).getBytes(), signatureBuffer, hostX509Cert);
- }
-
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- Logger.e(DeviceConstants.LOG_TAG, "Error while validating MMC response");
- } catch (CertificateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return certVerifyStatus;
- }
-
- private boolean evaluateTrust(X509Certificate x509CertfromMMC) {
- boolean isValidCert = false;
-
- try {
-
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- byte[] x509CertByte = libCommonDeviceAPI.readFilefromHost((byte) DeviceIDDetails.TRUST_CERT);
-
- X509Certificate trustCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(x509CertByte));
-
- if (null != trustCert){
- PublicKey trustPublicKeyMDS = trustCert.getPublicKey();
-
- x509CertfromMMC.verify(trustPublicKeyMDS);
-
- Logger.d(DeviceConstants.LOG_TAG,"Face SBI :: TRUST CERT verification Success");
- isValidCert = true;
- }
- else {
- isValidCert = false;
- }
-
- } catch (CertificateException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- } catch (InvalidKeyException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- } catch (NoSuchProviderException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- } catch (SignatureException e) {
- // TODO Auto-generated catch block
- //e.printStackTrace();
- Logger.e(DeviceConstants.LOG_TAG,"Face SBI :: TRUST CERT verification Failed");
- }
-
-
- return isValidCert;
- }
-
- public String getmsbKeyRotation() {
- CertificateFactory cf;
- byte[] headerBuffer = null;
- byte[] payloadBuffer = null;
- JSONObject data = new JSONObject();
- String responseBody = "";
- String msbKeyRotationRequest = "";
-
- try {
-
- if (oB == null){
- oB = new ObjectMapper();
- }
-
- cf = CertificateFactory.getInstance("X.509");
-
- byte[] x509MOSIPCertByte = libCommonDeviceAPI.readFilefromHost((byte)DeviceIDDetails.HOST_CERT);
- X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(x509MOSIPCertByte));
-
- //HeaderData
- headerBuffer = libCommonDeviceAPI.getHeader(certificate);
-
- //Payload
- payloadBuffer = getmsbKeyRotationData();
-
- String encodedData = getJwtEncodedData(headerBuffer, payloadBuffer, certificate);
-
- data.put("msbKeyRotation", encodedData);
-
- msbKeyRotationRequest = data.toString();
-
- responseBody = mmcServiceUtility.getDataFromMMC(msbKeyRotationRequest);
- } catch (CertificateException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return responseBody;
- }
-
- private byte[] getmsbKeyRotationData() {
- byte[] msbKeyRotationData = null;
- try
- {
- MSBKeyRotation msbKeyRotationPayload = new MSBKeyRotation();
- msbKeyRotationPayload.uniqueTransactionId = String.valueOf(getUniqueID());
- msbKeyRotationPayload.timeStamp = libCommonDeviceAPI.getISOTimeStamp();
- msbKeyRotationPayload.serialNumber = libCommonDeviceAPI.getSerialNumber();//DeviceMain.deviceMain.mainSerialNumber;
- msbKeyRotationPayload.deviceCodeUUID = libCommonDeviceAPI.getSerialNumber();//DeviceMain.deviceMain.mainDeviceCode;
- msbKeyRotationPayload.modelID = DeviceConstants.DEVICEMODEL;
- msbKeyRotationPayload.deviceProviderId = DeviceConstants.PROVIDERID;
- msbKeyRotationPayload.bioType = "Face";
- msbKeyRotationPayload.certificationLevel = "L0";
- msbKeyRotationPayload.devicePurpose = DeviceConstants.PURPOSE;
- msbKeyRotationPayload.env = DeviceConstants.ENVIRONMENT;
- msbKeyRotationPayload.deviceServiceVersion = DeviceConstants.MDSVERSION;
- msbKeyRotationPayload.specVersion = DeviceConstants.REGSERVER_VERSION;
- msbKeyRotationPayload.hostos = DeviceConstants.OSTYPE;
-
-
- byte[] deviceCSR = libCommonDeviceAPI.generateCSR(DeviceMain.deviceKeystore);
-
- //msbKeyRotationPayload.csrData = DatatypeConverter.printBase64Binary(deviceCSR);
- msbKeyRotationPayload.csrData = java.util.Base64.getEncoder().encodeToString(deviceCSR);//Base64.encodeToString(deviceCSR, Base64.DEFAULT);
-
- msbKeyRotationData = oB.writeValueAsString(msbKeyRotationPayload).getBytes();
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
-
- return msbKeyRotationData;
- }
-
- public String getmsbDeviceRegistration() {
- CertificateFactory cf;
- byte[] headerBuffer = null;
- byte[] payloadBuffer = null;
- JSONObject data = new JSONObject();
- String responseBody = "";
- String msbDeviceRegistationRequest = "";
-
- try {
-
- if (oB == null){
- oB = new ObjectMapper();
- }
-
- cf = CertificateFactory.getInstance("X.509");
-
- byte[] x509MOSIPCertByte = libCommonDeviceAPI.readFilefromHost((byte)DeviceIDDetails.HOST_CERT);
- X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(x509MOSIPCertByte));
-
- //HeaderData
- headerBuffer = libCommonDeviceAPI.getHeader(certificate);
-
- //Payload
- payloadBuffer = getmsbDeviceRegistrationData();
-
- String encodedData = getJwtEncodedData(headerBuffer, payloadBuffer, certificate);
-
- data.put("msbDeviceRegistration", encodedData);
-
- msbDeviceRegistationRequest = data.toString();
- responseBody = mmcServiceUtility.getDataFromMMC(msbDeviceRegistationRequest);
-
- } catch (CertificateException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return responseBody;
- }
-
- private byte[] getmsbDeviceRegistrationData() {
- byte[] msbRegistrationData = null;
- try
- {
- MSBDeviceRegistration msbDeviceRegistrationPayload = new MSBDeviceRegistration();
- msbDeviceRegistrationPayload.uniqueTransactionId = String.valueOf(getUniqueID());
- msbDeviceRegistrationPayload.timeStamp = libCommonDeviceAPI.getISOTimeStamp();
- msbDeviceRegistrationPayload.serialNumber = libCommonDeviceAPI.getSerialNumber();
- msbDeviceRegistrationPayload.deviceCodeUUID = DeviceMain.deviceMain.mainDeviceCode;
- msbDeviceRegistrationPayload.modelID = DeviceConstants.DEVICEMODEL;
- msbDeviceRegistrationPayload.deviceProviderId = DeviceConstants.PROVIDERID;
- msbDeviceRegistrationPayload.bioType = "Face";
- msbDeviceRegistrationPayload.certificationLevel = "L0";
- msbDeviceRegistrationPayload.devicePurpose = DeviceConstants.PURPOSE;
- msbDeviceRegistrationPayload.env = DeviceConstants.ENVIRONMENT;
- msbDeviceRegistrationPayload.deviceServiceVersion = DeviceConstants.MDSVERSION;
- msbDeviceRegistrationPayload.specVersion = DeviceConstants.REGSERVER_VERSION;
- msbDeviceRegistrationPayload.hostos = DeviceConstants.OSTYPE;
-
- //Registration Request JSON
- String serialNumber = libCommonDeviceAPI.getSerialNumber();
- String regRequestData = getRegRequest(serialNumber);
-
- msbDeviceRegistrationPayload.deviceRegistrationRequest = regRequestData;
-
- msbRegistrationData = oB.writeValueAsString(msbDeviceRegistrationPayload).getBytes();
-
- //System.out.println("Registration Data : " + new String(msbRegistrationData));
-
- }
- catch(Exception ex)
- {
- ex.printStackTrace();
- }
- return msbRegistrationData;
- }
-
- private String getRegRequest(String serialNumber) {
-
- String finalResponse = "";
- String registrationRequest = "";
- JSONArray jsonDSubid = new JSONArray();
- DeviceData deviceData = new DeviceData();
- DeviceDataRequest deviceDataRequest = new DeviceDataRequest();
- com.mmc.DataObjects.DeviceInfo devInfo = new com.mmc.DataObjects.DeviceInfo();
-
- DeviceRegistration deviceRegistration = new DeviceRegistration();
- try{
- if (oB == null){
- oB = new ObjectMapper();
- }
-
- //digital ID
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
-
- //String certStr = new String(libCommonDeviceAPI.readFilefromHost((byte)DeviceIDDetails.DEVICE_CERT));
-
- X509Certificate certificate = DeviceMain.deviceKeystore.getX509Certificate();
- String certStr = java.util.Base64.getEncoder().encodeToString(certificate.getEncoded());
- //Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP);
-
-
- byte[] headerData = libCommonDeviceAPI.getHeaderfromCert(certStr);
- String enCodedHeader = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(headerData);
- //Base64.encodeToString(headerData, Base64.NO_PADDING);
-
- String payLoad = ResponseGenHelper.getDigitalID(serialNumber, libCommonDeviceAPI.getISOTimeStamp());
- String enCodedPayLoad = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(payLoad.getBytes());
- //Base64.encodeToString(payLoad.getBytes(), Base64.NO_PADDING);
-
- byte [] inputString = (enCodedHeader + "." + enCodedPayLoad).getBytes();
-
- byte[] signature = "".getBytes();
- if (libCommonDeviceAPI.isValidDeviceforCertificate(DeviceMain.deviceMain.mainSerialNumber, DeviceMain.deviceKeystore)){
- signature = libCommonDeviceAPI.getSignature(DeviceMain.deviceKeystore, inputString);
- }
- String enCodedSignature = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(signature);
- //Base64.encodeToString(signature, Base64.NO_PADDING);
-
-
- jsonDSubid.put(0);
- devInfo.deviceSubId = "1";//jsonDSubid.toString();
- devInfo.certification = DeviceConstants.CERTIFICATIONLEVEL;
- devInfo.digitalId = enCodedHeader + "." + enCodedPayLoad + "." + enCodedSignature;
- devInfo.firmware = "1.0.9999";
- //devInfo.deviceExpiry = DeviceMain.deviceMain.gSnapshotResponse.keyExpiryTimeStamp;
-
- //yyyy-MM-dd'T'HH:mm:ss.SSSX
- /*DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.getDefault());
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.YEAR, DeviceConstants.MDS_REGISTRATION_DEVICE_EXPIRY);
- String expiryForDevice = format.format(calendar.getTime());*/
- DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
- String expiryForDevice = formatter.format(ZonedDateTime.now().plusYears(DeviceConstants.MDS_REGISTRATION_DEVICE_EXPIRY).withZoneSameInstant(ZoneOffset.UTC));
- devInfo.deviceExpiry = expiryForDevice;
- devInfo.timeStamp = libCommonDeviceAPI.getISOTimeStamp();
-
- byte[] deviceInfoPayload = oB.writeValueAsBytes(devInfo);
- String enCodedPayloadDeviceinfo = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(deviceInfoPayload); //Base64.encodeToString(deviceInfoPayload, Base64.NO_PADDING);
- byte[] inputStringDeviceinfo = (enCodedHeader + "." + enCodedPayloadDeviceinfo).getBytes();
- byte[] signatureDeviceInfo = "".getBytes();
-
- if (libCommonDeviceAPI.isValidDeviceforCertificate(DeviceMain.deviceMain.mainSerialNumber, DeviceMain.deviceKeystore)){
- signatureDeviceInfo = libCommonDeviceAPI.getSignature(DeviceMain.deviceKeystore, inputStringDeviceinfo);
- }
-
- String enCodedSignatureDeviceInfo = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(signatureDeviceInfo); //Base64.encodeToString(signatureDeviceInfo, Base64.NO_PADDING);
-
- String deviceInfoData = enCodedHeader + "." + enCodedPayloadDeviceinfo + "." + enCodedSignatureDeviceInfo;
-
-
- deviceData.deviceId = DeviceMain.deviceMain.mainSerialNumber;
- deviceData.purpose = DeviceConstants.DeviceUsage.Registration.toString().toUpperCase();
- deviceData.deviceInfo = deviceInfoData;
- deviceData.foundationalTrustProviderId = "";
-
-
- byte[] deviceDataPayload = oB.writeValueAsBytes(deviceData);
- String enCodedPayloadDevicedata = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(deviceDataPayload); //Base64.encodeToString(deviceDataPayload, Base64.NO_PADDING);
- byte[] inputStringDevicedata = (enCodedHeader + "." + enCodedPayloadDevicedata).getBytes();
-
- byte[] signatureDevicedata = "".getBytes();
- if (libCommonDeviceAPI.isValidDeviceforCertificate(DeviceMain.deviceMain.mainSerialNumber, DeviceMain.deviceKeystore)){
- signatureDevicedata = libCommonDeviceAPI.getSignature(DeviceMain.deviceKeystore, inputStringDevicedata);
- }
-
- String enCodedSignatureDevicedata = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(signatureDevicedata); //Base64.encodeToString(signatureDevicedata, Base64.NO_PADDING);
-
- String deviceDataString = enCodedHeader + "." + enCodedPayloadDevicedata + "." + enCodedSignatureDevicedata;
-
- deviceDataRequest.deviceData = deviceDataString;
-
- deviceRegistration.id = "io.mosip.deviceregister";
-
- //List