Skip to content

Commit

Permalink
Can now send hash via SMS and Accident location is included while cal…
Browse files Browse the repository at this point in the history
…culating hash
  • Loading branch information
Jagrut Kosti committed Jan 25, 2017
1 parent 16f3724 commit d504c5d
Show file tree
Hide file tree
Showing 11 changed files with 372 additions and 259 deletions.
3 changes: 3 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@
<service
android:name=".service.LocationChangeService"
android:exported="false" />
<service
android:name=".service.PostCollisionTasksService"
android:exported="false" />

<receiver android:name=".service.BackgroundService$CollisionBroadcastReceiver">
<intent-filter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ public class HistoryFiles {
private String publicKey;
private String seed;
private String savedHash;
private String accidentLocation;

public String getAccidentLocation() {
return accidentLocation;
}

public void setAccidentLocation(String accidentLocation) {
this.accidentLocation = accidentLocation;
}

public String getSavedHash() {
return savedHash;
Expand Down
110 changes: 110 additions & 0 deletions app/src/main/java/dashit/uni/com/dashit/model/SHAHashTasks.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package dashit.uni.com.dashit.model;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import dashit.uni.com.dashit.DashItApplication;
import dashit.uni.com.dashit.R;

/**
* Created by Jagrut on 25-Jan-17.
*/

public class SHAHashTasks {
/**
* Create a byte array of video files in given directory and location and then generate hash.
*/
public static String generateHashFromFilesAndLocation(String directory, String location){
String generateHashFromFileAndLocation = null;
File directoryOfFiles = new File(directory);
if(directoryOfFiles.isDirectory()){
File[] filesInDir = directoryOfFiles.listFiles();
Arrays.sort(filesInDir);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for(File file : filesInDir){
if(file.exists() && !file.isDirectory() && file.getAbsolutePath().endsWith(".mp4")){
//byte[] byteArray = new byte[(int) file.length()];
try {
InputStream fileIS = new FileInputStream(file);
BufferedInputStream bufferedIS = new BufferedInputStream(fileIS);
byte buffer[] = new byte[1024];
int read;
while((read = bufferedIS.read(buffer)) != -1){
outputStream.write(buffer, 0, read);
}
/*fileIS.read(byteArray);
outputStream.write(byteArray);*/
fileIS.close();
bufferedIS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

try {
outputStream.write(location.getBytes());
byte[] finalByte = outputStream.toByteArray();
Log.i("Final Byte Array Length", "" + finalByte.length);

MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(finalByte);
byte[] mdBytes = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < mdBytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & mdBytes[i]));
}
Log.i("Hex format : ", "" + hexString.toString());
outputStream.close();
generateHashFromFileAndLocation = hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return generateHashFromFileAndLocation;
}

/**
* Fetches data from origin stamp server for the given Hash value
* @param hash the hash for which data should be fetched
* @return {String} the data from server in String
*/
public static String getDataForHash(String hash){
String url = DashItApplication.getAppContext().getString(R.string.timestampUrl);
StringBuffer buffer = new StringBuffer();
try {
URL obj = new URL(url + hash);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "Token token=\"" + DashItApplication.getAppContext().getString(R.string.timestampToken) + "\"");
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept", "*/*");
String line;

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();

}
return buffer.toString();
}
}
112 changes: 17 additions & 95 deletions app/src/main/java/dashit/uni/com/dashit/service/BackgroundService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.location.Location;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
Expand Down Expand Up @@ -61,6 +62,7 @@ public class BackgroundService extends Service implements SurfaceHolder.Callback
int accidentOnVideoIndex = 0;
Handler handler;
Handler screenSizeHandler;
static String accidentLocation;

private WindowManager windowManager;
private SurfaceView surfaceView;
Expand Down Expand Up @@ -142,7 +144,7 @@ public void onCreate() {
* Depending on that it updates the surface to tiny tile on right side of screen or big tile
* in center.
*/
Runnable mStatusChecker = new Runnable() {
/* Runnable mStatusChecker = new Runnable() {
@Override
public void run() {
try {
Expand Down Expand Up @@ -171,7 +173,7 @@ public void run() {
screenSizeHandler.postDelayed(mStatusChecker, 500);
}
}
};
};*/

/**
* When the surface is created, it will start recording the video in infinite loop.
Expand Down Expand Up @@ -212,8 +214,8 @@ public void run() {
try {
Thread.sleep(20000);
stopRecording();
screenSizeHandler.removeCallbacks(mStatusChecker);
generateHash();
//screenSizeHandler.removeCallbacks(mStatusChecker);
orderAndSaveVideos();
windowManager.removeView(surfaceView);
} catch (InterruptedException e) {
e.printStackTrace();
Expand All @@ -238,8 +240,8 @@ public void onDestroy() {
} catch (InterruptedException e) {
e.printStackTrace();
}
windowManager.removeView(surfaceView);
screenSizeHandler.removeCallbacks(mStatusChecker);
//windowManager.removeView(surfaceView);
//screenSizeHandler.removeCallbacks(mStatusChecker);
}

@Nullable
Expand Down Expand Up @@ -297,15 +299,9 @@ public void stopRecording() {
camera.release();
}

/**
* Executed only when a collision is detected.
* Order the videos in correct order.
* Get the video files in that order and move them to another location under a new directory.
* Create a byte array of video files and generate hash.
*/
public void generateHash() {
public void orderAndSaveVideos() {
int[] orderOfVideo = new int[3];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

if (accidentOnVideoIndex == 2) {
orderOfVideo[0] = 1;
orderOfVideo[1] = 2;
Expand All @@ -327,104 +323,29 @@ public void generateHash() {
FileOutputStream target = new FileOutputStream(dir.getPath() + "/" + (i + 1) + "accVideo" + orderOfVideo[i] + ".mp4");
InputStream fileIS = new FileInputStream(file);
fileIS.read(byteArray);

target.write(byteArray);
outputStream.write(byteArray);

fileIS.close();
target.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
byte[] finalByte = outputStream.toByteArray();
Log.i("Final Byte Array Length", "" + finalByte.length);
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(finalByte);
byte[] mdBytes = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < mdBytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & mdBytes[i]));
}
Log.i("Hex format : ", "" + hexString.toString());

//Create a hash.txt file
File hash = new File(dir.getPath() + "/hash.txt");
FileWriter writer = new FileWriter(hash);
writer.append(hexString.toString());
writer.flush();
writer.close();
outputStream.close();
sendHashToServer(hexString.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Send the generated hash to Originstamp server
*
* @param hashString the hash to be submitted
*/
public void sendHashToServer(String hashString) {
String url = getString(R.string.timestampUrl);
String postData = "{\"hash_sha256\" : \"" + hashString + "\"}";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Token token=\""+getString(R.string.timestampToken)+"\"");
con.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept", "*/*");
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
dos.writeBytes(postData);
dos.flush();
dos.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();

handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(DashItApplication.getAppContext(), "Hash sent successfully!", Toast.LENGTH_LONG).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(BackgroundService.this, "Problems while sending hash. Please check you internet connection.", Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(BackgroundService.this, "Problems while sending hash. Please check you internet connection.", Toast.LENGTH_LONG).show();
}
});
}
Intent postCollisionTasks = new Intent(getApplicationContext(), PostCollisionTasksService.class);
postCollisionTasks.putExtra("directoryPath", dir.getAbsolutePath());
postCollisionTasks.putExtra("accidentLocation", accidentLocation);
startService(postCollisionTasks);
stopSelf();
}


@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}

/**
Expand All @@ -433,6 +354,7 @@ public void surfaceDestroyed(SurfaceHolder holder) {
public static class CollisionBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
accidentLocation = (String) intent.getExtras().get("accidentLocation");
accidentStatus = true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,14 @@ protected Void doInBackground(Void... voids) {
float distanceInMeters = lastLocation.distanceTo(currentLocation);

if(distanceInMeters < 50.00){
Intent intent = new Intent();
intent.setAction("com.collisionDetected.Broadcast");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);
String accidentLocation = String.valueOf(lastLocation.getLatitude());
accidentLocation = accidentLocation + "," + String.valueOf(lastLocation.getLongitude());

Intent collisionDetectedIntent = new Intent();
collisionDetectedIntent.setAction("com.collisionDetected.Broadcast");
collisionDetectedIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
collisionDetectedIntent.putExtra("accidentLocation", accidentLocation);
sendBroadcast(collisionDetectedIntent);
}
} catch (InterruptedException e) {
e.printStackTrace();
Expand Down
Loading

0 comments on commit d504c5d

Please sign in to comment.