Haven is for people who need a way to protect their personal spaces and possessions without compromising their own privacy, through an Android app and on-device sensors
Added async tasks to upload images, positions and stuff, fixed some errors
Marco Ziccardi407a7b639df6
diff --git a/AndroidManifest.xml b/AndroidManifest.xmlindex f9b1dd0..7aebf07 100644--- a/AndroidManifest.xml+++ b/AndroidManifest.xml@@ -10,6 +10,9 @@<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />+ <uses-permission android:name="android.permission.SEND_SMS" /><uses-feature android:name="android.hardware.camera" /><uses-feature android:name="android.hardware.camera.autofocus" /><uses-feature android:glEsVersion="0x00020000" android:required="true" />diff --git a/libs/httpclient-4.2.2.jar b/libs/httpclient-4.2.2.jarnew file mode 100644index 0000000..5f768c4Binary files /dev/null and b/libs/httpclient-4.2.2.jar differdiff --git a/libs/httpcore-4.2.3.jar b/libs/httpcore-4.2.3.jarnew file mode 100644index 0000000..2b1a140Binary files /dev/null and b/libs/httpcore-4.2.3.jar differdiff --git a/libs/httpmime-4.2.2.jar b/libs/httpmime-4.2.2.jarnew file mode 100644index 0000000..515ed31Binary files /dev/null and b/libs/httpmime-4.2.2.jar differdiff --git a/res/layout/activity_start.xml b/res/layout/activity_start.xmlindex 6bf1a7d..3fc324f 100644--- a/res/layout/activity_start.xml+++ b/res/layout/activity_start.xml@@ -218,7 +218,31 @@android:id="@+id/password"android:layout_below="@id/email"android:hint="@string/password_hint"- android:inputType="text"+ android:inputType="textPassword"+ android:layout_centerHorizontal="true"+ android:layout_width="fill_parent"+ android:layout_height="wrap_content"+ android:paddingTop="10dp"+ />++ </RelativeLayout>++ <RelativeLayout+ android:background="@drawable/back"+ android:layout_below="@id/remote_options"+ android:id="@+id/unlock_options"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:paddingLeft="30dp"+ android:paddingRight="30dp"+ android:layout_marginTop="10dp"+ android:layout_marginLeft="20dp"+ android:layout_marginRight="20dp">++ <EditText+ android:id="@+id/unlock_code"+ android:hint="@string/unlock_code_hint"+ android:inputType="textPassword"android:layout_centerHorizontal="true"android:layout_width="fill_parent"android:layout_height="wrap_content"@@ -229,8 +253,8 @@<Buttonandroid:id="@+id/start_button"- android:text="Start"- android:layout_below="@id/remote_options"+ android:text="@string/start_button"+ android:layout_below="@id/unlock_options"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"/>diff --git a/res/values/strings.xml b/res/values/strings.xmlindex ac632ab..433d69c 100644--- a/res/values/strings.xml+++ b/res/values/strings.xml@@ -1,9 +1,10 @@<resources><string name="app_name">SecureIt</string>- <string name="hello_world">Hello world!</string>+<string name="menu_stop">Stop</string>- <string name="title_activity_start">StartActivity</string>++ <string name="title_activity_start">SecureIt</string><string name="accelerometer_label">Use accelerometer to detect motion@@ -44,6 +45,15 @@Password</string>+ <string name="unlock_code_hint">+ Code to stop the app+ </string>+++ <string name="start_button">+ Start+ </string>+<string name="camera_prompt">Select the camera</string>diff --git a/src/me/ziccard/secureit/MonitorActivity.java b/src/me/ziccard/secureit/MonitorActivity.javaindex be08f25..01fd1db 100644--- a/src/me/ziccard/secureit/MonitorActivity.java+++ b/src/me/ziccard/secureit/MonitorActivity.java@@ -5,7 +5,8 @@ import me.ziccard.secureit.fragment.CameraFragment;import me.ziccard.secureit.fragment.EmptyFragment;import me.ziccard.secureit.fragment.MicrophoneFragment;import me.ziccard.secureit.service.BluetoothService;-import android.content.Context;+import android.app.AlertDialog;+import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.support.v4.app.Fragment;@@ -13,8 +14,11 @@ import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import android.support.v4.view.ViewPager;+import android.text.InputType;import android.view.Menu;import android.view.MenuItem;+import android.widget.EditText;+import android.widget.Toast;import com.viewpagerindicator.TitlePageIndicator;import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;@@ -109,13 +113,61 @@ public class MonitorActivity extends FragmentActivity {public boolean onOptionsItemSelected (MenuItem item) {switch (item.getItemId()){case R.id.menu_settings:- Intent intent = new Intent(- getApplicationContext(), StartActivity.class);- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);- startActivity(intent);- stopService(new Intent(this, BluetoothService.class));+ createUnlockDialog();break;}return true;}++ /**+ * Closes the monitor activity and unset session properties+ */+ private void close() {+ Intent intent = new Intent(+ getApplicationContext(), StartActivity.class);+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);+ startActivity(intent);+ stopService(new Intent(this, BluetoothService.class));+ preferences.unsetAccessToken();+ preferences.unsetDelegatedAccessToken();+ preferences.unsetPhoneId();++ }++ /**+ * When user closes the activity+ */+ @Override+ public void onBackPressed() {+ createUnlockDialog();+ }++ /**+ * Shows a dialog prompting the unlock code+ */+ private void createUnlockDialog() {+ final AlertDialog.Builder builder = new AlertDialog.Builder(this);+ builder.setTitle("Stop monitoring?");+ final EditText input = new EditText(this);+ input.setHint("Unlock code");+ input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);+ builder.setView(input);++ builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {+ public void onClick(DialogInterface dialog, int whichButton) {+ if (input.getText().toString().equals(preferences.getUnlockCode())) {+ dialog.dismiss();+ close();+ } else {+ dialog.dismiss();+ Toast.makeText(+ getApplicationContext(),+ "Wrong unlock code",+ Toast.LENGTH_SHORT).show();+ }+ }+ });++ builder.show();+ }}diff --git a/src/me/ziccard/secureit/Preview.java b/src/me/ziccard/secureit/Preview.javaindex 0fe50c1..9df81db 100644--- a/src/me/ziccard/secureit/Preview.java+++ b/src/me/ziccard/secureit/Preview.java@@ -29,6 +29,11 @@ import android.widget.Toast;public class Preview extends SurfaceView implements SurfaceHolder.Callback {+ /**+ * Object to retrieve and set shared preferences+ */+ private SecureItPreferences prefs;+private List<MotionListener> listeners = new ArrayList<MotionListener>();/**@@ -54,16 +59,6 @@ public class Preview extends SurfaceView implements SurfaceHolder.Callback {*/private int imageCount = 0;- /**- * Max number of pictures stored- */- private static final int MAX_IMAGES = 10;-- /**- * PATH to the directory where to save images- */- private static final String FILE = "/secureit";-SurfaceHolder mHolder;public Camera camera;@@ -76,6 +71,7 @@ public class Preview extends SurfaceView implements SurfaceHolder.Callback {// underlying surface is created and destroyed.mHolder = getHolder();mHolder.addCallback(this);+ prefs = new SecureItPreferences(context);}public void addListener(MotionListener listener) {@@ -129,15 +125,20 @@ public class Preview extends SurfaceView implements SurfaceHolder.Callback {YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),size.width, size.height, null);- imageCount = (imageCount + 1)%11;+ imageCount = (imageCount + 1)%(prefs.getMaxImages()+1);- File file = new File(Environment.getExternalStorageDirectory()- .getPath() + FILE + imageCount + ".jpg");+ File file = new File(+ Environment.getExternalStorageDirectory().getPath() ++ prefs.getImagePath() ++ imageCount ++ ".jpg");FileOutputStream filecon = new FileOutputStream(file);+image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 90,filecon);+} catch (FileNotFoundException e) {Toast toast = Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG);toast.show();@@ -181,10 +182,9 @@ public class Preview extends SurfaceView implements SurfaceHolder.Callback {// Surface will be destroyed when we return, so stop the preview.// Because the CameraDevice object is not a shared resource, it's very// important to release it when the activity is paused.-+ camera.setPreviewCallback(null);camera.stopPreview();camera.release();- camera = null;}public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {@@ -216,7 +216,7 @@ public class Preview extends SurfaceView implements SurfaceHolder.Callback {parameters.setPreviewSize(w, h);camera.setDisplayOrientation(180);}- camera.setParameters(parameters);+ //camera.setParameters(parameters);camera.startPreview();}}\ No newline at end of filediff --git a/src/me/ziccard/secureit/SecureItPreferences.java b/src/me/ziccard/secureit/SecureItPreferences.javaindex 80c6707..297b87a 100644--- a/src/me/ziccard/secureit/SecureItPreferences.java+++ b/src/me/ziccard/secureit/SecureItPreferences.java@@ -30,6 +30,20 @@ public class SecureItPreferences {private static final String SMS_NUMBER="sms_number";private static final String REMOTE_ACTIVE="remote_active";private static final String REMOTE_EMAIL="remote_email";+ private static final String UNLOCK_CODE="unlock_code";++ private static final String ACCESS_TOKEN="access_token";+ private static final String DELEGATED_ACCESS_TOKEN="deferred_access_token";++ private static final String PHONE_ID="phone_id";++ private static final String DIR_PATH = "/secureit";++ private static final String IMAGE_PATH = DIR_PATH+"/secureit";+ private static final int MAX_IMAGES = 10;++ private static final String AUDIO_PATH = DIR_PATH+"/SecureIt_Audio";+ private static final long AUDIO_LENGTH = 10000;public SecureItPreferences(Context context) {@@ -141,8 +155,80 @@ public class SecureItPreferences {prefsEditor.commit();}+ public void setUnlockCode(String unlockCode) {+ prefsEditor.putString(UNLOCK_CODE, unlockCode);+ prefsEditor.commit();+ }++ public String getUnlockCode() {+ return appSharedPrefs.getString(UNLOCK_CODE, "");+ }+public String getRemoteEmail() {return appSharedPrefs.getString(REMOTE_EMAIL, "");}-++ public void setAccessToken(String accessToken) {+ prefsEditor.putString(ACCESS_TOKEN, accessToken);+ prefsEditor.commit();+ }++ public String getAccessToken() {+ return appSharedPrefs.getString(ACCESS_TOKEN, "");+ }++ public void unsetAccessToken() {+ prefsEditor.remove(ACCESS_TOKEN);+ }++ public void setDelegatedAccessToken(String deferredAccessToken) {+ prefsEditor.putString(DELEGATED_ACCESS_TOKEN, deferredAccessToken);+ prefsEditor.commit();+ }++ public String getDelegatedAccessToken() {+ return appSharedPrefs.getString(DELEGATED_ACCESS_TOKEN, "");+ }++ public void unsetDelegatedAccessToken() {+ prefsEditor.remove(DELEGATED_ACCESS_TOKEN);+ }++ public String getImagePath() {+ return IMAGE_PATH;+ }++ public int getMaxImages() {+ return MAX_IMAGES;+ }++ public void setPhoneId(String phoneId) {+ prefsEditor.putString(PHONE_ID, phoneId);+ prefsEditor.commit();+ }++ public void unsetPhoneId() {+ prefsEditor.remove(PHONE_ID);+ }++ public String getPhoneId() {+ return appSharedPrefs.getString(PHONE_ID, "");+ }++ public String getDirPath() {+ return DIR_PATH;+ }++ public String getAudioPath() {+ return AUDIO_PATH;+ }++ public long getAudioLenght() {+ return AUDIO_LENGTH;+ }++ public String getSMSText() {+ return "WARNING: SecureIt has detected an intrusion.\n"++ "PhoneId: "+getPhoneId();+ }}diff --git a/src/me/ziccard/secureit/StartActivity.java b/src/me/ziccard/secureit/StartActivity.javaindex 9c36ebf..84d962d 100644--- a/src/me/ziccard/secureit/StartActivity.java+++ b/src/me/ziccard/secureit/StartActivity.java@@ -1,12 +1,15 @@package me.ziccard.secureit;-import me.ziccard.secureit.async.AuthenticatorTask;+import java.io.File;+import me.ziccard.secureit.async.BluetoothServerTask;import me.ziccard.secureit.async.BluetoothServerTask.NoBluetoothException;-import me.ziccard.secureit.async.MicRecorderTask;-import me.ziccard.secureit.async.MicRecorderTaskFactory;-import me.ziccard.secureit.async.MicRecorderTaskFactory.RecordLimitExceeded;+import me.ziccard.secureit.async.upload.AudioRecorderTask;+import me.ziccard.secureit.async.upload.AudioRecorderTaskFactory;+import me.ziccard.secureit.async.upload.AuthenticatorTask;+import me.ziccard.secureit.async.upload.AudioRecorderTaskFactory.RecordLimitExceeded;import android.os.Bundle;+import android.os.Environment;import android.app.Activity;import android.content.ComponentName;import android.content.Context;@@ -21,9 +24,9 @@ import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.EditText;import android.widget.RelativeLayout;-import android.widget.Toast;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.Spinner;+import android.widget.Toast;public class StartActivity extends Activity {@@ -32,17 +35,16 @@ public class StartActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);- //TODO ELIMINARE SOLO PROVA- try {- MicRecorderTaskFactory.makeRecorder().start();- } catch (RecordLimitExceeded e) {- // WE HAVE AN UpDATED RECORD- e.printStackTrace();- }setContentView(R.layout.activity_start);preferences = new SecureItPreferences(this.getApplicationContext());+ /*+ * We create an application directory to store images and audio+ */+ File directory = new File(Environment.getExternalStorageDirectory()+preferences.getDirPath());+ directory.mkdirs();+/*** Checkboxes for enabled app options*/@@ -95,6 +97,9 @@ public class StartActivity extends Activity {final EditText password = (EditText)this.findViewById(R.id.password);+ final EditText unlockCode = (EditText)+ this.findViewById(R.id.unlock_code);+final Button startButton = (Button) this.findViewById(R.id.start_button);@@ -178,7 +183,8 @@ public class StartActivity extends Activity {} else {preferences.activateMicrophone(false);}- if (smsCheck.isChecked()) {+ if (smsCheck.isChecked() && !phoneNumber.getText().toString().equals("")) {+ Log.i("StartActivity", "Send message alert is active");preferences.activateSms(true);preferences.setSmsNumber(phoneNumber.getText().toString());@@ -193,7 +199,23 @@ public class StartActivity extends Activity {preferences.activateRemote(false);}- if (preferences.getRemoteActivation()) {+ if (!unlockCode.getText().toString().equals("")) {+ preferences.setUnlockCode(unlockCode.getText().toString());+ } else {+ /*+ * We cannot start without an unlock code+ */+ Toast.makeText(StartActivity.this, "Empty unlock code", Toast.LENGTH_LONG).show();+ return;+ }++ if (preferences.getRemoteActivation() &&+ preferences.getRemoteEmail() != null &&+ !password.getText().toString().equals("")) {++ /*+ * Authentication is set so we need to authenticate+ */AuthenticatorTask task = new AuthenticatorTask(StartActivity.this,preferences.getRemoteEmail(),password.getText().toString());@@ -204,9 +226,7 @@ public class StartActivity extends Activity {MonitorActivity.class);StartActivity.this.startActivity(intent);- }--+ }}});diff --git a/src/me/ziccard/secureit/async/BluetoothServerTask.java b/src/me/ziccard/secureit/async/BluetoothServerTask.javaindex 6f26f34..fdf6adf 100644--- a/src/me/ziccard/secureit/async/BluetoothServerTask.java+++ b/src/me/ziccard/secureit/async/BluetoothServerTask.java@@ -4,13 +4,23 @@ import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.Date;++import me.ziccard.secureit.async.upload.DelegatedPositionUploaderTask;import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;import me.ziccard.secureit.config.Remote;import me.ziccard.secureit.messages.BluetoothMessage;+import me.ziccard.secureit.messages.HelloMessage;import me.ziccard.secureit.messages.KeyRequest;+import me.ziccard.secureit.messages.KeyResponse;+import me.ziccard.secureit.messages.MessageBuilder;+import me.ziccard.secureit.messages.MessageType;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothServerSocket;import android.bluetooth.BluetoothSocket;+import android.content.Context;+import android.location.Location;+import android.location.LocationManager;+import android.location.LocationProvider;import android.util.Log;public class BluetoothServerTask extends Thread {@@ -24,8 +34,10 @@ public class BluetoothServerTask extends Thread {private final BluetoothServerSocket mmServerSocket;private BluetoothAdapter mBluetoothAdapter;++ private Context context;- public BluetoothServerTask() throws NoBluetoothException {+ public BluetoothServerTask(Context context) throws NoBluetoothException {Log.i("BluetoothServerTask", "Created");mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();@@ -34,6 +46,7 @@ public class BluetoothServerTask extends Thread {throw new NoBluetoothException();}+ this.context = context;Log.i("BluetoothServerTask", "Got adapter");// Use a temporary object that is later assigned to mmServerSocket,// because mmServerSocket is final@@ -93,19 +106,37 @@ public class BluetoothServerTask extends Thread {try {//Receiving first hello messageObjectInputStream instream = socket.getInputStream();- BluetoothMessage message = (BluetoothMessage) instream.readObject();+ HelloMessage message = (HelloMessage) instream.readObject();Log.i("BluetoothServerTask", "Received message "+message.getType().toString());+ /*+ * Get last known location+ */+ LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);+ String locationProvider = LocationManager.NETWORK_PROVIDER;+ Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);+//Sending key requestObjectOutputStream ostream = socket.getOutputStream();Date timestamp = new Date();- message = new KeyRequest(10.0, 10.0, timestamp);+ MessageBuilder builder = new MessageBuilder();+ builder.setLat(lastKnownLocation.getLatitude());+ builder.setLng(lastKnownLocation.getLongitude());+ builder.setTimestamp(new Date());++ KeyRequest keyRequest = (KeyRequest) builder.buildMessage(MessageType.KEY_REQUEST);ostream.writeObject(message);- Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());+ Log.i("BluetoothServerTask", "Sent message " + keyRequest.getType().toString());//Receiving key response- message = (BluetoothMessage) instream.readObject();- Log.i("BluetoothServerTask", "Received message "+message.getType().toString());+ KeyResponse keyResponse = (KeyResponse) instream.readObject();+ Log.i("BluetoothServerTask", "Received message "+keyResponse.getType().toString());++ new DelegatedPositionUploaderTask(+ message.getPhoneId(),+ keyRequest.getLat(),+ keyRequest.getLng(),+ keyResponse.getAccessKey()).execute();socket.close();} catch (Exception e) {diff --git a/src/me/ziccard/secureit/async/DataUploaderTask.java b/src/me/ziccard/secureit/async/DataUploaderTask.javadeleted file mode 100644index 252cc0e..0000000--- a/src/me/ziccard/secureit/async/DataUploaderTask.java+++ /dev/null@@ -1,184 +0,0 @@-package me.ziccard.secureit.async;--import java.io.File;-import java.util.ArrayList;-import java.util.List;-import me.ziccard.secureit.config.Remote;-import org.apache.http.HttpException;-import org.apache.http.HttpResponse;-import org.apache.http.NameValuePair;-import org.apache.http.client.HttpClient;-import org.apache.http.client.entity.UrlEncodedFormEntity;-import org.apache.http.client.methods.HttpPost;-import org.apache.http.entity.FileEntity;-import org.apache.http.impl.client.DefaultHttpClient;-import org.apache.http.message.BasicNameValuePair;-import android.os.AsyncTask;-import android.util.Log;--public class DataUploaderTask extends AsyncTask<Void, Void, Void> {-- private static final int WIFI_CONNECTIVITY = 0;-- private static final int MOBILE_CONNECTIVITY = 1;-- private static final int NO_CONNECTIVITY = 2;-- /**- * Paths to images to be uploaded- */- private List<String> imagePaths = null;-- /**- * Path to audio to be uploaded- */- private String audioPath = null;-- /**- * Latitude of the last position to be uploaded- */- private Double lat = null;-- /**- * Longitude of the last position to be uploaded- */- private Double lon = null;-- /**- * ID of the phone sending data- */- private String phoneId = null;-- /**- * Access token of the phone sending data- */- private String accessToken = null;-- /**- * Private connectivity type- */- private int connectivityType;-- /**- * Constructor- * @param phoneId- * @param accessToken- */- public DataUploaderTask(String phoneId, String accessToken, int connectivityType) {- this.phoneId = phoneId;- this.accessToken = accessToken;- this.connectivityType = connectivityType;- }-- public void setImagesPath(List<String> paths) {- this.imagePaths = paths;- }-- public void setAudioPath(String path) {- this.audioPath = path;- }-- @Override- protected Void doInBackground(Void... params) {- HttpClient client = new DefaultHttpClient();- /*- * If imagePaths != null send all the images- * to /phone/phoneId/images [POST]- */- if (imagePaths != null) {- for (String path : imagePaths) {- HttpPost request = new HttpPost(- Remote.HOST+- Remote.PHONES+"/"+phoneId+- Remote.UPLOAD_IMAGES);- /*- * Getting the image from the file system- */- File image = new File(path);- FileEntity entity = new FileEntity(image, "image/jpeg");- request.setEntity(entity);-- /*- * Authentication token- */- request.setHeader("access_token", accessToken);-- try {- HttpResponse response = client.execute(request);- if (response.getStatusLine().getStatusCode() != 200) {- throw new HttpException();- }- } catch (Exception e) {- Log.e("DataUploaderTask", "Error uploading image: "+path);- }- }- }- /*- * If audioPath != null send the track- * to /phone/phoneId/audio [POST]- */- if (audioPath != null) {- HttpPost request = new HttpPost(- Remote.HOST+- Remote.PHONES+"/"+phoneId+- Remote.UPLOAD_AUDIO);- /*- * Getting the audio from the file system- */- File audio = new File(audioPath);- FileEntity entity = new FileEntity(audio, "audio/mp3");- request.setEntity(entity);-- /*- * Authentication token- */- request.setHeader("access_token", accessToken);-- try {- HttpResponse response = client.execute(request);- if (response.getStatusLine().getStatusCode() != 200) {- throw new HttpException();- }- } catch (Exception e) {- Log.e("DataUploaderTask", "Error uploading audio: "+audioPath);- }- }- /*- * If lat != null and lon != null send the last- * detected position to /phone/phoneId/position [POST]- */- if (lat != null && lon != null) {- HttpPost request = new HttpPost(- Remote.HOST+- Remote.PHONES+"/"+phoneId+- Remote.UPLOAD_POSITION);-- /*- * Adding latitude and longitude- */- List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);- nameValuePairs.add(new BasicNameValuePair("lat",- lat.toString()));- nameValuePairs.add(new BasicNameValuePair("long",- lon.toString()));- try {- request.setEntity(new UrlEncodedFormEntity(nameValuePairs));-- /*- * Authentication token- */- request.setHeader("access_token", accessToken);-- HttpResponse response = client.execute(request);- if (response.getStatusLine().getStatusCode() != 200) {- throw new HttpException();- }- } catch (Exception e) {- Log.e("DataUploaderTask", "Error uploading location");- }- }- return null;- }---}diff --git a/src/me/ziccard/secureit/async/MicRecorderTask.java b/src/me/ziccard/secureit/async/MicRecorderTask.javadeleted file mode 100644index dc9df30..0000000--- a/src/me/ziccard/secureit/async/MicRecorderTask.java+++ /dev/null@@ -1,70 +0,0 @@-package me.ziccard.secureit.async;--import android.content.ContentValues;-import android.media.MediaRecorder;-import android.os.Environment;-import android.provider.MediaStore;--public class MicRecorderTask extends Thread {-- /**- * Name of the file to wich we are going to record audio- */- private static final String FILENAME = "SecureIt_Audio";-- /**- * True iff the thread is recording- */- private boolean recording = false;-- /**- * Duration in milliseconds of the audio track- */- private static final long DURATION = 10000;-- /**- * Getter for recording data field- */- public boolean isRecording() {- return recording;- }-- /**- * We make recorder protected in order to forse- * Factory usage- */- protected MicRecorderTask() {- super();- }- @Override- public void run() {- recording = true;- final MediaRecorder recorder = new MediaRecorder();- ContentValues values = new ContentValues(3);- values.put(MediaStore.MediaColumns.TITLE, FILENAME);- recorder.setAudioSource(MediaRecorder.AudioSource.MIC);- recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);- recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);-- recorder.setOutputFile(Environment.getExternalStorageDirectory().getPath()+- "/"+FILENAME+".mp3");- try {- recorder.prepare();- } catch (Exception e){- e.printStackTrace();- }-- recorder.start();- try {- Thread.sleep(DURATION);- } catch (InterruptedException e) {- // TODO Auto-generated catch block- e.printStackTrace();- }- recorder.stop();- recorder.release();- recording = false;-- }--}diff --git a/src/me/ziccard/secureit/async/MicRecorderTaskFactory.java b/src/me/ziccard/secureit/async/MicRecorderTaskFactory.javadeleted file mode 100644index cf1e7f5..0000000--- a/src/me/ziccard/secureit/async/MicRecorderTaskFactory.java+++ /dev/null@@ -1,23 +0,0 @@-package me.ziccard.secureit.async;--public class MicRecorderTaskFactory {-- public static class RecordLimitExceeded extends Exception {-- /**- *- */- private static final long serialVersionUID = 7030672869928993643L;-- }-- private static MicRecorderTask task;-- public static MicRecorderTask makeRecorder() throws RecordLimitExceeded {- if (task != null && task.isRecording())- throw new RecordLimitExceeded();- task = new MicRecorderTask();- return task;- }--}diff --git a/src/me/ziccard/secureit/async/MicSamplerTask.java b/src/me/ziccard/secureit/async/MicSamplerTask.javaindex 6ccf802..90befc4 100644--- a/src/me/ziccard/secureit/async/MicSamplerTask.java+++ b/src/me/ziccard/secureit/async/MicSamplerTask.java@@ -8,7 +8,6 @@ public class MicSamplerTask extends AsyncTask<Void,Object,Void> {private MicListener listener = null;private AudioCodec volumeMeter = new AudioCodec();- private boolean terminated = false;public static interface MicListener {public void onSignalReceived(short[] signal);@@ -19,10 +18,6 @@ public class MicSamplerTask extends AsyncTask<Void,Object,Void> {this.listener = listener;}- synchronized public void terminate() {- terminated = true;- }-protected Void onPreExecute(Void...params) {return null;}@@ -51,8 +46,9 @@ public class MicSamplerTask extends AsyncTask<Void,Object,Void> {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();+ return null;}- if (terminated) { volumeMeter.stop(); return null; }+ if (isCancelled()) { volumeMeter.stop(); return null; }}}diff --git a/src/me/ziccard/secureit/async/upload/AudioRecorderTask.java b/src/me/ziccard/secureit/async/upload/AudioRecorderTask.javanew file mode 100644index 0000000..04b4f1c--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/AudioRecorderTask.java@@ -0,0 +1,161 @@+package me.ziccard.secureit.async.upload;++import java.io.BufferedReader;+import java.io.File;+import java.io.InputStreamReader;+import org.apache.http.HttpException;+import org.apache.http.HttpResponse;+import org.apache.http.client.HttpClient;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.entity.mime.HttpMultipartMode;+import org.apache.http.entity.mime.MultipartEntity;+import org.apache.http.entity.mime.content.FileBody;+import org.apache.http.impl.client.DefaultHttpClient;+import me.ziccard.secureit.SecureItPreferences;+import me.ziccard.secureit.config.Remote;+import android.content.ContentValues;+import android.content.Context;+import android.media.MediaRecorder;+import android.os.Environment;+import android.provider.MediaStore;+import android.util.Log;++public class AudioRecorderTask extends Thread {++ /**+ * Context used to retrieve shared preferences+ */+ @SuppressWarnings("unused")+ private Context context;++ /**+ * Shared preferences of the application+ */+ private SecureItPreferences prefs;++ /**+ * Name of the audio file to store+ */+ private String filename;++ /**+ * Id of the phone+ */+ private String phoneId;++ /**+ * Access token to upload the audio+ */+ private String accessToken;++ /**+ * True iff the thread is recording+ */+ private boolean recording = false;++ /**+ * Getter for recording data field+ */+ public boolean isRecording() {+ return recording;+ }++ /**+ * We make recorder protected in order to forse+ * Factory usage+ */+ protected AudioRecorderTask(Context context) {+ super();+ this.context = context;+ this.prefs = new SecureItPreferences(context);+ this.filename = prefs.getAudioPath();+ this.phoneId = prefs.getPhoneId();+ this.accessToken = prefs.getAccessToken();+ Log.i("AudioRecorderTask", "Created recorder");+ }++ @Override+ public void run() {+ recording = true;+ final MediaRecorder recorder = new MediaRecorder();++ ContentValues values = new ContentValues(3);+ values.put(MediaStore.MediaColumns.TITLE, filename);++ recorder.setAudioSource(MediaRecorder.AudioSource.MIC);+ recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);+ recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);++ String audioPath = Environment.getExternalStorageDirectory().getPath() ++ filename ++ ".m4a";++ recorder.setOutputFile(audioPath);+ try {+ recorder.prepare();+ } catch (Exception e){+ e.printStackTrace();+ return;+ }++ Log.i("AudioRecorderTask", "Start recording");+ recorder.start();+ try {+ Thread.sleep(prefs.getAudioLenght());+ } catch (InterruptedException e) {+ e.printStackTrace();+ }++ recorder.stop();+ Log.i("AudioRecorderTask", "Stopped recording");+ recorder.release();+ recording = false;++ /*+ * Uploading the audio+ */+ Log.i("AudioRecorderTask", "Trying to upload");+ HttpClient httpclient = new DefaultHttpClient();+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_AUDIO);++ Log.i("AudioRecorderTask",+ "URI: "+Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_AUDIO);+ /*+ * Getting the audio from the file system+ */+ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);+ File audio = new File(audioPath);+ reqEntity.addPart("audio", new FileBody(audio, "audio/mp3"));+ request.setEntity(reqEntity);++ /*+ * Authentication token+ */+ request.setHeader("access_token", accessToken);++ try {+ HttpResponse response = httpclient.execute(request);++ BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));+ StringBuilder builder = new StringBuilder();+ for (String line = null; (line = reader.readLine()) != null;) {+ builder.append(line).append("\n");+ }++ Log.i("AudioRecorderTask", "Response:\n"+builder.toString());++ if (response.getStatusLine().getStatusCode() != 200) {+ Log.i("AudioRecorderTask", "Error uploading audio: "+audioPath);+ throw new HttpException();+ }+ } catch (Exception e) {+ Log.e("DataUploaderTask", "Error uploading audio: "+audioPath);+ }+ }++}diff --git a/src/me/ziccard/secureit/async/upload/AudioRecorderTaskFactory.java b/src/me/ziccard/secureit/async/upload/AudioRecorderTaskFactory.javanew file mode 100644index 0000000..a02c13c--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/AudioRecorderTaskFactory.java@@ -0,0 +1,25 @@+package me.ziccard.secureit.async.upload;++import android.content.Context;++public class AudioRecorderTaskFactory {++ public static class RecordLimitExceeded extends Exception {++ /**+ *+ */+ private static final long serialVersionUID = 7030672869928993643L;++ }++ private static AudioRecorderTask task;++ public static AudioRecorderTask makeRecorder(Context context) throws RecordLimitExceeded {+ if (task != null && task.isRecording())+ throw new RecordLimitExceeded();+ task = new AudioRecorderTask(context);+ return task;+ }++}diff --git a/src/me/ziccard/secureit/async/AuthenticatorTask.java b/src/me/ziccard/secureit/async/upload/AuthenticatorTask.javasimilarity index 53%rename from src/me/ziccard/secureit/async/AuthenticatorTask.javarename to src/me/ziccard/secureit/async/upload/AuthenticatorTask.javaindex 7202a3f..add3ab0 100644--- a/src/me/ziccard/secureit/async/AuthenticatorTask.java+++ b/src/me/ziccard/secureit/async/upload/AuthenticatorTask.java@@ -1,9 +1,12 @@-package me.ziccard.secureit.async;+package me.ziccard.secureit.async.upload;+import java.io.BufferedReader;import java.io.IOException;+import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import me.ziccard.secureit.MonitorActivity;+import me.ziccard.secureit.SecureItPreferences;import me.ziccard.secureit.config.Remote;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;@@ -11,10 +14,12 @@ import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;-import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;+import org.json.JSONException;+import org.json.JSONObject;+import org.json.JSONTokener;import android.app.Activity;import android.app.AlertDialog;import android.app.ProgressDialog;@@ -53,6 +58,11 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{*/private String accessToken;+ /**+ * Delegated authentication token+ */+ private String delegatedAccessToken;+/*** True iff authentication has failed*/@@ -61,13 +71,14 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{/*** Manager to get device infos*/- private TelephonyManager manager = (TelephonyManager) activity.- getSystemService(Context.TELEPHONY_SERVICE);+ private TelephonyManager manager;public AuthenticatorTask(Activity activity, String username, String password) {this.activity = activity;this.username = username;this.password = password;+ this.manager = (TelephonyManager) activity.+ getSystemService(Context.TELEPHONY_SERVICE);}/**@@ -93,6 +104,7 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{dialog = new ProgressDialog(activity);dialog.setCancelable(false);dialog.setTitle("Authenticating");+ dialog.setMessage("Trying to authenticate");dialog.show();}@@ -102,7 +114,8 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{* PHASE1: Authenticate*/HttpClient httpclient = new DefaultHttpClient();- HttpPost httppost = new HttpPost(Remote.HOST+"signup");+ HttpPost httppost = new HttpPost(Remote.HOST+Remote.ACCESS_TOKEN);+ HttpResponse response = null;try {// Add your dataList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);@@ -111,54 +124,15 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));// Execute HTTP Post Request- HttpResponse response;- response = httpclient.execute(httppost);--- if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {- authenticationFailure = true;- return null;- }- accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());- Log.i("AuthenticatorTask", accessToken);- } catch (ClientProtocolException e) {- authenticationFailure = true;- e.printStackTrace();- } catch (IOException e) {- authenticationFailure = true;- e.printStackTrace();- }- /*- * TODO retrieve access token- */- /*- * PHASE2: Register phone- */- httppost = new HttpPost(Remote.HOST+"phones");- try {-- List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);- nameValuePairs.add(new BasicNameValuePair("id",- manager.getDeviceId()));- nameValuePairs.add(new BasicNameValuePair("model",- Build.MANUFACTURER+" "+Build.PRODUCT));- nameValuePairs.add(new BasicNameValuePair("version", "VERSION"));- httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));-- httppost.addHeader("access_token", accessToken);-- // Execute HTTP Post Request- HttpResponse response;response = httpclient.execute(httppost);--- if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {++ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {authenticationFailure = true;- return null;+ return null;}- accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());- Log.i("AuthenticatorTask", accessToken);+ //accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());+ //Log.i("AuthenticatorTask", accessToken);} catch (ClientProtocolException e) {authenticationFailure = true;@@ -166,7 +140,73 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{} catch (IOException e) {authenticationFailure = true;e.printStackTrace();- }+ }++ try {+ if (response != null) {++ /*+ * Retrieving access token from response+ */+ BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));+ StringBuilder builder = new StringBuilder();+ for (String line = null; (line = reader.readLine()) != null;) {+ builder.append(line).append("\n");+ }++ Log.i("AuthenticatorToken", "FIRST RESPONSE:\n"+builder.toString());++ JSONTokener tokener = new JSONTokener(builder.toString());+ JSONObject finalResult = new JSONObject(tokener);+ accessToken = finalResult.getString("access_token");+ delegatedAccessToken = finalResult.getString("delegated_access_token");++ /*+ * PHASE2: Register phone+ */+ httppost = new HttpPost(Remote.HOST+Remote.PHONES);+++ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("id",+ manager.getDeviceId()));+ nameValuePairs.add(new BasicNameValuePair("model",+ Build.MANUFACTURER+" "+Build.PRODUCT));+ nameValuePairs.add(new BasicNameValuePair("version", "VERSION"));+ httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));++ httppost.addHeader("access_token", accessToken);++ // Execute HTTP Post Request+ response = httpclient.execute(httppost);+++ if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {+ authenticationFailure = true;+ return null;+ }+ //accessToken = org.apache.http.util.EntityUtils.toString(response.getEntity());+ Log.i("AuthenticatorTask", accessToken);++ /*+ * Storing access token+ */+ SecureItPreferences prefs = new SecureItPreferences(activity);+ prefs.setAccessToken(accessToken);+ prefs.setDelegatedAccessToken(delegatedAccessToken);+ prefs.setPhoneId(manager.getDeviceId());+ }++ } catch (ClientProtocolException e) {+ authenticationFailure = true;+ e.printStackTrace();+ } catch (IOException e) {+ authenticationFailure = true;+ e.printStackTrace();+ } catch (JSONException e) {+ authenticationFailure = true;+ e.printStackTrace();+ }return null;}@@ -184,5 +224,4 @@ public class AuthenticatorTask extends AsyncTask<Void, Void, Void>{showFailureDialog();}}-}diff --git a/src/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java b/src/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.javanew file mode 100644index 0000000..91eae45--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/BluetoothPeriodicPositionUploaderTask.java@@ -0,0 +1,198 @@+package me.ziccard.secureit.async.upload;++import java.io.ObjectInputStream;+import java.io.ObjectOutputStream;+import java.security.NoSuchAlgorithmException;+import java.security.spec.AlgorithmParameterSpec;+import java.util.ArrayList;+import java.util.Date;++import javax.crypto.Cipher;+import javax.crypto.NoSuchPaddingException;+import javax.crypto.spec.IvParameterSpec;+import javax.crypto.spec.SecretKeySpec;++import me.ziccard.secureit.SecureItPreferences;+import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;+import me.ziccard.secureit.config.Remote;+import me.ziccard.secureit.messages.BluetoothMessage;+import me.ziccard.secureit.messages.HelloMessage;+import me.ziccard.secureit.messages.KeyRequest;+import me.ziccard.secureit.messages.KeyResponse;+import me.ziccard.secureit.messages.MessageBuilder;+import me.ziccard.secureit.messages.MessageType;+import android.bluetooth.BluetoothAdapter;+import android.bluetooth.BluetoothDevice;+import android.bluetooth.BluetoothSocket;+import android.content.BroadcastReceiver;+import android.content.Context;+import android.content.Intent;+import android.content.IntentFilter;+import android.os.AsyncTask;+import android.util.Base64;+import android.util.Log;+import android.widget.Toast;++public class BluetoothPeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> {++ @SuppressWarnings("unused")+ private Context context;++ /**+ * Boolean true iff last thread iterations position has been sent+ */+ private boolean dataSent = false;++ private SecureItPreferences prefs;++ /**+ * Adapter for bluetooth services+ */+ private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();++ /**+ * Creates a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED+ */+ private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {++ private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();++ @Override+ public void onReceive(Context context, Intent intent) {+ String action = intent.getAction();+ // When discovery finds a device+ if (BluetoothDevice.ACTION_FOUND.equals(action)) {+ // Get the BluetoothDevice object from the Intent+ BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);+ devices.add(device);++ Log.i("BluetoothPeriodicPositionUploaderTask", "Discovered "+device.getName());+ CharSequence text = "Discovered "+device.getName();+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(context, text, duration);+ toast.show();++ return;+ }+ // When ending the discovery+ if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {+ for (BluetoothDevice device : devices){+ Log.i("DISCOVERY", "FINISHED");+ try {+ BluetoothSocket tmp = null;+ tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);++ if (tmp != null) {++ Log.i("BluetoothPeriodicPositionUploaderTask", "Trying to connect to " + device.getName());++ adapter.cancelDiscovery();+ tmp.connect();++ Log.i("BluetoothPeriodicPositionUploaderTask", "Connected to " + device.getName());++ ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);++ MessageBuilder builder = new MessageBuilder();+ builder.setPhoneId(phoneId);+ builder.setTimestamp(new Date());+ //Sending hello message+ BluetoothMessage message = builder.buildMessage(MessageType.HELLO);+ ObjectOutputStream ostream = socket.getOutputStream();+ ostream.writeObject(message);+ Log.i("BluetoothPeriodicPositionUploaderTask", "Sent message " + message.getType().toString());++ //Receiving key request+ ObjectInputStream instream = socket.getInputStream();+ KeyRequest keyRequestMessage = (KeyRequest) instream.readObject();+ Log.i("BluetoothPeriodicPositionUploaderTask", "Received message "+message.getType().toString());++ builder.setLat(keyRequestMessage.getLat());+ builder.setLng(keyRequestMessage.getLng());+ builder.setTimestamp(keyRequestMessage.getTimestamp());+ builder.setPassword(delegatedAccessToken);++ message = builder.buildMessage(MessageType.KEY_RESPONSE);+ ostream.writeObject(message);+ Log.i("BluetoothPeriodicPositionUploaderTask", "Sent message " + message.getType().toString());++ socket.close();++ CharSequence text = "Bluetooth message sent";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(context, text, duration);+ toast.show();++ dataSent = true;+ }+ } catch (Exception e) {+ e.printStackTrace();+ }+ }+ context.unregisterReceiver(broadcastReceiver);+ }+ }+ };++ /**+ * ID of the phone sending data+ */+ private String phoneId = null;++ /**+ * Access token of the phone sending data+ */+ private String delegatedAccessToken = null;++ /**+ * Constructor+ * @param context+ * @param lat+ * @param lng+ */+ public BluetoothPeriodicPositionUploaderTask(Context context) {+ this.context = context;+ prefs = new SecureItPreferences(context);+ this.phoneId = prefs.getPhoneId();+ this.delegatedAccessToken = prefs.getDelegatedAccessToken();++ Log.i("BluetoothPeriodicPositionUploaderTask", "Created");+ }++ @Override+ protected void onCancelled () {+ Log.i("BluetoothPeriodicPositionUploaderTask", "Task stopped");+ }++ @Override+ protected Void doInBackground(Void... params) {++ while(true) {++ this.context.registerReceiver(broadcastReceiver,+ new IntentFilter(BluetoothDevice.ACTION_FOUND));++ this.context.registerReceiver(broadcastReceiver,+ new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));++ Boolean runningBluetooth = adapter.startDiscovery();++ if (!runningBluetooth) {+ Log.i("BluetoothPeriodicPositionUploaderTask", "Bluetooth is off");+ } else {+ Log.i("BluetoothPeriodicPositionUploaderTask", "Started discovery");+ }++ if (isCancelled()) {+ return null;+ }++ try {+ if (dataSent) Thread.sleep(3600*1000);+ else Thread.sleep(60*1000);+ } catch (InterruptedException e) {+ return null;+ }+ }+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/async/upload/DelegatedPositionUploaderTask.java b/src/me/ziccard/secureit/async/upload/DelegatedPositionUploaderTask.javanew file mode 100644index 0000000..c075be3--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/DelegatedPositionUploaderTask.java@@ -0,0 +1,104 @@+package me.ziccard.secureit.async.upload;++import java.io.BufferedReader;+import java.io.InputStreamReader;+import java.util.ArrayList;+import java.util.List;+import me.ziccard.secureit.config.Remote;+import org.apache.http.HttpException;+import org.apache.http.HttpResponse;+import org.apache.http.NameValuePair;+import org.apache.http.client.HttpClient;+import org.apache.http.client.entity.UrlEncodedFormEntity;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.message.BasicNameValuePair;+import android.os.AsyncTask;+import android.util.Log;++public class DelegatedPositionUploaderTask extends AsyncTask<Void, Void, Void> {++ /**+ * Latitude of the last position to be uploaded+ */+ protected double lat;++ /**+ * Longitude of the last position to be uploaded+ */+ protected double lng;++ /**+ * ID of the phone sending data+ */+ private String phoneId = null;++ /**+ * Access token of the phone sending data+ */+ private String accessKey = null;++ /**+ * Constructor+ * @param context+ * @param lat+ * @param lng+ */+ public DelegatedPositionUploaderTask(String phoneId, double lat, double lng, String accessKey) {++ this.lat = lat;+ this.lng = lng;+ this.phoneId = phoneId;+ this.accessKey = accessKey;++ }++ @Override+ protected Void doInBackground(Void... params) {++ while(true) {++ Log.i("DelegatedPositionUploaderTask", "Started");++ HttpClient client = new DefaultHttpClient();++ /*+ * Send the last+ * detected position to /phone/phoneId/position [POST]+ */+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.DELEGATED_UPLOAD_POSITION);++ /*+ * Adding latitude and longitude+ */+ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("lat", ""+lat));+ nameValuePairs.add(new BasicNameValuePair("long", ""+lng));+ nameValuePairs.add(new BasicNameValuePair("access_key", accessKey));+ try {+ request.setEntity(new UrlEncodedFormEntity(nameValuePairs));+++ HttpResponse response = client.execute(request);++ BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));+ StringBuilder builder = new StringBuilder();+ for (String line = null; (line = reader.readLine()) != null;) {+ builder.append(line).append("\n");+ }++ Log.i("PeriodicPositionUploaderTask", "Response:\n"+builder.toString());++ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }++ } catch (Exception e) {+ Log.e("DelegatedPositionUploaderTask", "Error uploading delegated location");+ }+ }+ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/async/upload/ImagesUploaderTask.java b/src/me/ziccard/secureit/async/upload/ImagesUploaderTask.javanew file mode 100644index 0000000..327661d--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/ImagesUploaderTask.java@@ -0,0 +1,147 @@+package me.ziccard.secureit.async.upload;++import java.io.BufferedReader;+import java.io.File;+import java.io.InputStreamReader;++import me.ziccard.secureit.SecureItPreferences;+import me.ziccard.secureit.config.Remote;+import org.apache.http.HttpException;+import org.apache.http.HttpResponse;+import org.apache.http.client.HttpClient;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.entity.mime.HttpMultipartMode;+import org.apache.http.entity.mime.MultipartEntity;+import org.apache.http.entity.mime.content.FileBody;+import org.apache.http.impl.client.DefaultHttpClient;+import android.content.Context;+import android.os.AsyncTask;+import android.os.Environment;+import android.util.Log;++public class ImagesUploaderTask extends AsyncTask<Void, Void, Void> {++ @SuppressWarnings("unused")+ private Context context;++ private SecureItPreferences prefs;++ public static final int WIFI_CONNECTIVITY = 0;++ public static final int MOBILE_CONNECTIVITY = 1;++ public static final int NO_CONNECTIVITY = 2;++ /**+ * ID of the phone sending data+ */+ private String phoneId = null;++ /**+ * Access token of the phone sending data+ */+ private String accessToken = null;++ /**+ * Private connectivity type+ */+ private int connectivityType;++ /**+ * Constructor+ * @param phoneId+ * @param accessToken+ */+ public ImagesUploaderTask(Context context, int connectivityType) {+ this.context = context;+ prefs = new SecureItPreferences(context);++ this.phoneId = prefs.getPhoneId();+ this.accessToken = prefs.getAccessToken();+ this.connectivityType = connectivityType;+ }+++ @Override+ protected Void doInBackground(Void... params) {+ HttpClient client = new DefaultHttpClient();++ Log.i("ImagesUploaderTask","Started");++ int imagesToUpload = 0;++ /*+ * If we are using mobile connectivity we upload half of the images+ * stored+ */+ if (connectivityType == WIFI_CONNECTIVITY) {+ imagesToUpload = prefs.getMaxImages();+ }+ if (connectivityType == MOBILE_CONNECTIVITY) {+ imagesToUpload = prefs.getMaxImages() / 2;+ }+ if (connectivityType == NO_CONNECTIVITY) {+ imagesToUpload = 0;+ }++ for (int imageCount = 0; imageCount < imagesToUpload; imageCount++) {++ String path = Environment.getExternalStorageDirectory().getPath() ++ prefs.getImagePath() ++ imageCount ++ ".jpg";++ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_IMAGES);++ Log.i("ImagesUploaderTask", "Uploading image "+path);++ /*+ * Get image from filesystem+ */+ File image = new File(path);++ //Only if the image exists we upload it+ if (image.exists()) {++ Log.i("ImagesUploaderTask", "Image exists");++ /*+ * Getting the image from the file system+ */+ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);+ reqEntity.addPart("image", new FileBody(image, "image/jpeg"));+ request.setEntity(reqEntity);++ /*+ * Setting the access token+ */+ request.setHeader("access_token", accessToken);++ try {+ HttpResponse response = client.execute(request);++ BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));+ StringBuilder builder = new StringBuilder();+ for (String line = null; (line = reader.readLine()) != null;) {+ builder.append(line).append("\n");+ }++ Log.i("ImagesRecorderTask", "Response:\n"+builder.toString());++ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }+ } catch (Exception e) {+ Log.e("ImageUploaderTask", "Error uploading image: "+path);+ }+ //otherwise no other image exists+ } else {+ return null;+ }+ }+ return null;+ }+}diff --git a/src/me/ziccard/secureit/async/upload/PeriodicPositionUploaderTask.java b/src/me/ziccard/secureit/async/upload/PeriodicPositionUploaderTask.javanew file mode 100644index 0000000..615f4a3--- /dev/null+++ b/src/me/ziccard/secureit/async/upload/PeriodicPositionUploaderTask.java@@ -0,0 +1,204 @@+package me.ziccard.secureit.async.upload;++import java.io.BufferedReader;+import java.io.InputStreamReader;+import java.util.ArrayList;+import java.util.List;+import me.ziccard.secureit.SecureItPreferences;+import me.ziccard.secureit.config.Remote;+import org.apache.http.HttpException;+import org.apache.http.HttpResponse;+import org.apache.http.NameValuePair;+import org.apache.http.client.HttpClient;+import org.apache.http.client.entity.UrlEncodedFormEntity;+import org.apache.http.client.methods.HttpPost;+import org.apache.http.impl.client.DefaultHttpClient;+import org.apache.http.message.BasicNameValuePair;++import android.content.Context;+import android.location.Location;+import android.location.LocationListener;+import android.location.LocationManager;+import android.net.ConnectivityManager;+import android.net.NetworkInfo;+import android.os.AsyncTask;+import android.os.Bundle;+import android.util.Log;++public class PeriodicPositionUploaderTask extends AsyncTask<Void, Void, Void> implements LocationListener {++ private static final double INVALID_VALUE = Double.MAX_VALUE;++ /**+ * In case 3G and WIFI are turned off we start the upload+ * using bluetooth+ */+ private BluetoothPeriodicPositionUploaderTask bluetoothTask;++ /**+ * Context to retrieve shared preferences+ */+ private Context context;++ /**+ * Boolean true iff last thread iterations position has been sent+ */+ private boolean dataSent = false;++ private SecureItPreferences prefs;++ /**+ * Latitude of the last position to be uploaded+ */+ protected double lat = INVALID_VALUE;++ /**+ * Longitude of the last position to be uploaded+ */+ protected double lng = INVALID_VALUE;++ /**+ * Manager to retrieve location+ */+ private LocationManager locationManager = null;++ /**+ * ID of the phone sending data+ */+ private String phoneId = null;++ /**+ * Access token of the phone sending data+ */+ private String accessToken = null;++ /**+ * Constructor+ * @param context+ * @param lat+ * @param lng+ */+ public PeriodicPositionUploaderTask(Context context) {+ this.context = context;+ locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);++ locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);+ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);++ prefs = new SecureItPreferences(context);++ this.phoneId = prefs.getPhoneId();+ this.accessToken = prefs.getAccessToken();+ }++ @Override+ protected void onCancelled () {+ if (bluetoothTask != null) bluetoothTask.cancel(true);+ else locationManager.removeUpdates(this);+ }++ @Override+ protected Void doInBackground(Void... params) {++ while(true) {++ Log.i("PeriodicPositionUploaderTask", "Started");++ if (isCancelled()) {+ return null;+ }++ HttpClient client = new DefaultHttpClient();++ /*+ * Send the last+ * detected position to /phone/phoneId/position [POST]+ */+ HttpPost request = new HttpPost(+ Remote.HOST++ Remote.PHONES+"/"+phoneId++ Remote.UPLOAD_POSITION);++ /*+ * Adding latitude and longitude+ */+ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);+ nameValuePairs.add(new BasicNameValuePair("lat", ""+lat));+ nameValuePairs.add(new BasicNameValuePair("long", ""+lng));+ try {+ request.setEntity(new UrlEncodedFormEntity(nameValuePairs));++ /*+ * Access token+ */+ request.setHeader("access_token", accessToken);++ /*+ * We send position only if Gps/Network fixed+ */++ if (lat != Double.MAX_VALUE && lng != Double.MAX_VALUE) {+ dataSent = true;+ HttpResponse response = client.execute(request);++ BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));+ StringBuilder builder = new StringBuilder();+ for (String line = null; (line = reader.readLine()) != null;) {+ builder.append(line).append("\n");+ }++ Log.i("PeriodicPositionUploaderTask", "Response:\n"+builder.toString());++ if (response.getStatusLine().getStatusCode() != 200) {+ throw new HttpException();+ }+ } else {+ Log.i("PeriodicPositionUploaderTask", "We have no position data yet");+ dataSent = false;+ }+ } catch (Exception e) {+ Log.e("DataUploaderTask", "Error uploading location");+ /*+ * We check if we still have connectivity, if this is not true+ * we start BluetoothPeriodicPositionUploader+ */+ ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);+ NetworkInfo activeNetwork = cm.getActiveNetworkInfo();+ boolean isConnected = activeNetwork.isConnectedOrConnecting();+ if (!isConnected) {+ bluetoothTask = new BluetoothPeriodicPositionUploaderTask(context);+ bluetoothTask.execute();+ locationManager.removeUpdates(this);+ return null;+ }+ }++ try {+ if (dataSent) Thread.sleep(3600*1000);+ else Thread.sleep(60*1000);+ } catch (InterruptedException e) {+ return null;+ }+ }+ }++ public void onLocationChanged(Location location) {+ lat = location.getLatitude();+ lng = location.getLongitude();+ }++ public void onProviderDisabled(String provider) {+ // Nothing interesting to do++ }++ public void onProviderEnabled(String provider) {+ // Nothing interesting to do++ }++ public void onStatusChanged(String provider, int status, Bundle extras) {+ // Nothing interesting to do++ }+}\ No newline at end of filediff --git a/src/me/ziccard/secureit/config/Remote.java b/src/me/ziccard/secureit/config/Remote.javaindex cc191ca..40396b8 100644--- a/src/me/ziccard/secureit/config/Remote.java+++ b/src/me/ziccard/secureit/config/Remote.java@@ -4,11 +4,11 @@ import java.util.UUID;public class Remote {- public static final String HOST = "http://secureit.mziccard.cloudbees.net/";+ public static final String HOST = "http://192.168.1.49:9000/";public static final String ACCESS_TOKEN = "users/accesstoken";- public static final String PHONES = "phones";+ public static final String PHONES = "api/phones";public static final String UPLOAD_IMAGES = "/image";@@ -16,6 +16,8 @@ public class Remote {public static final String UPLOAD_POSITION = "/position";+ public static final String DELEGATED_UPLOAD_POSITION = "/position/delegated";+public static final String BLUETOOTH_NAME = "me.ziccard.secureit";public static final UUID BLUETOOTH_UUID =diff --git a/src/me/ziccard/secureit/fragment/AccelerometerFragment.java b/src/me/ziccard/secureit/fragment/AccelerometerFragment.javaindex ddab057..a3710f4 100644--- a/src/me/ziccard/secureit/fragment/AccelerometerFragment.java+++ b/src/me/ziccard/secureit/fragment/AccelerometerFragment.java@@ -123,6 +123,13 @@ public class AccelerometerFragment extends Fragment implements SensorEventListen//sensorMgr.unregisterListener(this);}+ @Override+ public void onDestroy() {+ super.onDestroy();+ sensorMgr.unregisterListener(this);+ getActivity().unbindService(mConnection);+ }+@Overridepublic void onResume() {super.onResume();diff --git a/src/me/ziccard/secureit/fragment/MicrophoneFragment.java b/src/me/ziccard/secureit/fragment/MicrophoneFragment.javaindex d87d5e5..b1facf5 100644--- a/src/me/ziccard/secureit/fragment/MicrophoneFragment.java+++ b/src/me/ziccard/secureit/fragment/MicrophoneFragment.java@@ -1,11 +1,8 @@package me.ziccard.secureit.fragment;import android.os.Bundle;-import android.graphics.Color;import android.support.v4.app.Fragment;import android.util.Log;-import java.text.DecimalFormat;-import me.ziccard.secureit.MicrophoneVolumePicker;import me.ziccard.secureit.R;import me.ziccard.secureit.VolumeDynamicSeries;@@ -18,7 +15,7 @@ import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;-public final class MicrophoneFragment extends Fragment implements MicSamplerTask.MicListener{+public final class MicrophoneFragment extends Fragment implements MicSamplerTask.MicListener {private MicSamplerTask microphone;@@ -49,7 +46,6 @@ public final class MicrophoneFragment extends Fragment implements MicSamplerTask@Overridepublic void onPause() {super.onPause();- microphone.terminate();}@Override@@ -99,15 +95,18 @@ public final class MicrophoneFragment extends Fragment implements MicSamplerTaskLinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.linear_layout);MicrophoneVolumePicker picker = new MicrophoneVolumePicker(this.getActivity());layout.addView(picker, params);----+microphone = new MicSamplerTask();microphone.setMicListener(this);microphone.execute();}+ @Override+ public void onDestroy() {+ Log.i("MircorphoneFramgnet", "Fragment destroyed");+ super.onDestroy();+ microphone.cancel(true);+ }public void onSignalReceived(short[] signal) {@@ -118,7 +117,7 @@ public final class MicrophoneFragment extends Fragment implements MicSamplerTaskint total = 0;int count = 0;for (short peak : signal) {- Log.i("MicrophoneFragment", "Sampled values are: "+peak);+ //Log.i("MicrophoneFragment", "Sampled values are: "+peak);if (peak != 0) {total+=Math.abs(peak);count++;@@ -139,9 +138,6 @@ public final class MicrophoneFragment extends Fragment implements MicSamplerTask}public void onMicError() {- Log.e("MicrophoneActivity", "Microphone is not ready");- CharSequence text = "Microphone is not ready";- Toast toast = Toast.makeText(this.getActivity(), text, Toast.LENGTH_LONG);- toast.show();+ Log.e("MicrophoneActivity", "Microphone is not ready");}}\ No newline at end of filediff --git a/src/me/ziccard/secureit/messages/BluetoothMessageData.java b/src/me/ziccard/secureit/messages/BluetoothMessageData.javaindex c1345aa..bf189f5 100644--- a/src/me/ziccard/secureit/messages/BluetoothMessageData.java+++ b/src/me/ziccard/secureit/messages/BluetoothMessageData.java@@ -5,5 +5,9 @@ import java.util.Date;public class BluetoothMessageData {protected Date timestamp;++ public Date getTimestamp() {+ return timestamp;+ }}diff --git a/src/me/ziccard/secureit/messages/HelloMessage.java b/src/me/ziccard/secureit/messages/HelloMessage.javaindex 79a71c2..d5ede5c 100644--- a/src/me/ziccard/secureit/messages/HelloMessage.java+++ b/src/me/ziccard/secureit/messages/HelloMessage.java@@ -1,11 +1,33 @@package me.ziccard.secureit.messages;+import java.util.Date;+public class HelloMessage extends BluetoothMessageData implements BluetoothMessage {/****/private static final long serialVersionUID = 4363335604763136855L;++ /**+ * Id of the phone delegating an alert+ */+ private String phoneId;++ /**+ * Constructor+ */+ public HelloMessage(String phoneId, Date timestamp) {+ this.phoneId = phoneId;+ this.timestamp = timestamp;+ }++ /**+ * phoneId getter+ */+ public String getPhoneId() {+ return phoneId;+ }public MessageType getType() {return MessageType.HELLO;diff --git a/src/me/ziccard/secureit/messages/KeyRequest.java b/src/me/ziccard/secureit/messages/KeyRequest.javaindex 17dcf2f..afb9f5b 100644--- a/src/me/ziccard/secureit/messages/KeyRequest.java+++ b/src/me/ziccard/secureit/messages/KeyRequest.java@@ -20,6 +20,7 @@ public class KeyRequest extends BluetoothMessageData implements BluetoothMessagepublic double getLng() {return lng;}+/****/diff --git a/src/me/ziccard/secureit/messages/KeyResponse.java b/src/me/ziccard/secureit/messages/KeyResponse.javaindex 9f8a608..621684d 100644--- a/src/me/ziccard/secureit/messages/KeyResponse.java+++ b/src/me/ziccard/secureit/messages/KeyResponse.java@@ -1,5 +1,7 @@package me.ziccard.secureit.messages;+import java.util.Date;+public class KeyResponse extends BluetoothMessageData implements BluetoothMessage {/**@@ -7,6 +9,11 @@ public class KeyResponse extends BluetoothMessageData implements BluetoothMessag*/private static final long serialVersionUID = -4625933882220755290L;+ public KeyResponse(String accessKey, Date timestamp) {+ this.accessKey = accessKey;+ this.timestamp = timestamp;+ }+private String accessKey;public String getAccessKey() {diff --git a/src/me/ziccard/secureit/messages/MessageBuilder.java b/src/me/ziccard/secureit/messages/MessageBuilder.javanew file mode 100644index 0000000..f4d34ad--- /dev/null+++ b/src/me/ziccard/secureit/messages/MessageBuilder.java@@ -0,0 +1,92 @@+package me.ziccard.secureit.messages;++import java.security.spec.AlgorithmParameterSpec;+import java.util.Date;++import javax.crypto.Cipher;+import javax.crypto.spec.IvParameterSpec;+import javax.crypto.spec.SecretKeySpec;++import android.util.Base64;++public class MessageBuilder {++ /**+ * Phone Id+ */+ private String phoneId;++ /**+ * Latitude value+ */+ private double lat;++ /**+ * Longitude value+ */+ private double lng;++ /**+ * Timestamp+ */+ private Date timestamp;++ /**+ * Password used to encrypt KeyResponse+ */+ private String password;++ public void setPhoneId(String phoneId) {+ this.phoneId = phoneId;+ }++ public void setLat(double lat) {+ this.lat = lat;+ }++ public void setLng(double lng) {+ this.lng = lng;+ }++ public void setTimestamp(Date timestamp) {+ this.timestamp = timestamp;+ }++ public void setPassword(String password) {+ this.password = password;+ }++ /**+ * Constructor+ * @param type+ * @return+ */+ public BluetoothMessage buildMessage(MessageType type) {+ switch (type) {+ case HELLO:+ return new HelloMessage(phoneId, new Date());+ case KEY_REQUEST:+ return new KeyRequest(lat, lng, new Date());+ case KEY_RESPONSE:+ String accessKey = "{\"lat\": \"" + lat + "\"," ++ "\"long\": \"" + lng + "\"," ++ "\"timestamp\": \"" + timestamp + "\"}";++ SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");+ AlgorithmParameterSpec paramSpec = new IvParameterSpec(password.substring(0, 16).getBytes());+ Cipher cipher;+ try {+ cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");+ cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);+ byte[] ecrypted = cipher.doFinal(accessKey.getBytes());+ accessKey = Base64.encodeToString(ecrypted, Base64.DEFAULT);+ } catch (Exception e) {++ e.printStackTrace();+ }+ return new KeyResponse(accessKey, new Date());+ default:+ return new HelloMessage(phoneId, new Date());+ }+ }+}diff --git a/src/me/ziccard/secureit/service/BluetoothService.java b/src/me/ziccard/secureit/service/BluetoothService.javaindex 7652816..ebebff9 100644--- a/src/me/ziccard/secureit/service/BluetoothService.java+++ b/src/me/ziccard/secureit/service/BluetoothService.java@@ -8,8 +8,14 @@ import java.util.Date;import me.ziccard.secureit.MonitorActivity;import me.ziccard.secureit.R;+import me.ziccard.secureit.SecureItPreferences;import me.ziccard.secureit.async.BluetoothServerTask;import me.ziccard.secureit.async.BluetoothServerTask.NoBluetoothException;+import me.ziccard.secureit.async.upload.AudioRecorderTaskFactory;+import me.ziccard.secureit.async.upload.AudioRecorderTaskFactory.RecordLimitExceeded;+import me.ziccard.secureit.async.upload.BluetoothPeriodicPositionUploaderTask;+import me.ziccard.secureit.async.upload.ImagesUploaderTask;+import me.ziccard.secureit.async.upload.PeriodicPositionUploaderTask;import me.ziccard.secureit.bluetooth.ObjectBluetoothSocket;import me.ziccard.secureit.config.Remote;import me.ziccard.secureit.messages.BluetoothMessage;@@ -30,10 +36,12 @@ import android.content.Intent;import android.content.IntentFilter;import android.net.ConnectivityManager;import android.net.NetworkInfo;+import android.os.AsyncTask;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.os.Messenger;+import android.telephony.SmsManager;import android.util.Log;import android.widget.Toast;@@ -41,15 +49,16 @@ import android.widget.Toast;public class BluetoothService extends Service {/**- * To show a notification on service start+ * Task used to upload position, is periodic, when we close the app+ * we need to stop the service and that task*/- private NotificationManager manager;+ private AsyncTask<Void, Void, Void> positionTask = null;/**- * Registered clients to the service+ * To show a notification on service start*/- //private ArrayList<Messenger> clients = new ArrayList<Messenger>();-+ private NotificationManager manager;+/*** Acceleration detected message*/@@ -68,24 +77,12 @@ public class BluetoothService extends Service {/*** True only if service has been alerted by the accelerometer*/- private boolean accelerometer_alerted;-- /**- * True only if service has been alerted by the camera- **/- private boolean camera_alerted;-- /**- * True only if service has been alerted by the camera- **/- private boolean microphone_alerted;--+ private boolean already_alerted;/**- * Adapter for bluetooth services+ * Object used to retrieve shared preferences*/- private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();+ private SecureItPreferences prefs = null;/*** Handler for incoming messages@@ -96,81 +93,7 @@ public class BluetoothService extends Service {alert(msg.what);}}-- // Create a BroadcastReceiver for ACTION_FOUND and ACTION_DISCOVERY_FINISHED- private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {-- private ArrayList<BluetoothDevice> devices = new ArrayList<BluetoothDevice>();-- @Override- public void onReceive(Context context, Intent intent) {- String action = intent.getAction();- // When discovery finds a device- if (BluetoothDevice.ACTION_FOUND.equals(action)) {- // Get the BluetoothDevice object from the Intent- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);- devices.add(device);--- Log.i("BluetoothService", "DISCOVERED "+device.getName());- CharSequence text = "Discovered "+device.getName();- int duration = Toast.LENGTH_SHORT;- Toast toast = Toast.makeText(BluetoothService.this, text, duration);- toast.show();-- return;- }- // When ending the discovery- if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {- for (BluetoothDevice device : devices){- Log.i("DISCOVERY", "FINISHED");- try {- BluetoothSocket tmp = null;- tmp = device.createInsecureRfcommSocketToServiceRecord(Remote.BLUETOOTH_UUID);- if (tmp != null) {-- Log.i("BluetoothService", "Trying to connect to " + device.getName());-- adapter.cancelDiscovery();- tmp.connect();-- Log.i("BluetoothService", "Connected to " + device.getName());-- ObjectBluetoothSocket socket = new ObjectBluetoothSocket(tmp);-- //Sending hello message- BluetoothMessage message = new HelloMessage();- ObjectOutputStream ostream = socket.getOutputStream();- message = new HelloMessage();- ostream.writeObject(message);- Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());-- //Receiving key request- ObjectInputStream instream = socket.getInputStream();- message = (BluetoothMessage) instream.readObject();- Log.i("BluetoothServerTask", "Received message "+message.getType().toString());-- message = new KeyResponse();- ostream.writeObject(message);- Log.i("BluetoothServerTask", "Sent message " + message.getType().toString());-- socket.close();-- CharSequence text = "Written message";- int duration = Toast.LENGTH_SHORT;- Toast toast = Toast.makeText(BluetoothService.this, text, duration);- toast.show();- }- } catch (Exception e) {- e.printStackTrace();- }- }- unregisterReceiver(broadcastReceiver);- }- }- };-/*** Messenger interface used by clients to interact*/@@ -182,11 +105,13 @@ public class BluetoothService extends Service {@Overridepublic void onCreate() {manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);+ prefs = new SecureItPreferences(this);try {- new BluetoothServerTask().start();+ new BluetoothServerTask(this).start();} catch (NoBluetoothException e) {- CharSequence text = "Sorry, bluetooth is off!";+ Log.i("BluetoothService", "Background bluetooth server not started");+ CharSequence text = "Background bluetooth server not started";int duration = Toast.LENGTH_SHORT;Toast toast = Toast.makeText(this, text, duration);toast.show();@@ -203,6 +128,9 @@ public class BluetoothService extends Service {public void onDestroy() {// Cancel the persistent notification.manager.cancel(R.string.secure_service_started);+ if (positionTask!=null && !positionTask.isCancelled()) {+ positionTask.cancel(true);+ }// Tell the user we stopped.Toast.makeText(this, R.string.secure_service_stopped, Toast.LENGTH_SHORT).show();@@ -245,70 +173,85 @@ public class BluetoothService extends Service {*/private void alert(int alertType) {- if (accelerometer_alerted && camera_alerted && microphone_alerted) return;-- accelerometer_alerted = true;- camera_alerted = true;- microphone_alerted = true;+ /*+ * If we have already received an alert+ */+ if (already_alerted) return;/*- * Need to check the type o connectivity+ * Alse we set an alert has bee received+ */+ already_alerted = true;++ /*+ * If remote communication with SecureIt back-end is required we+ * need to check the type of connectivity*/- ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();- boolean isConnected = activeNetwork.isConnectedOrConnecting();- boolean isWifi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;- // Phone is connected- if (isConnected) {- // through wireless- if (isWifi) {- CharSequence text = "WIFI: we are sending a lot of data";- int duration = Toast.LENGTH_SHORT;- Toast toast = Toast.makeText(this, text, duration);- toast.show();- //(new DataUploaderTask(null, null, DataUploaderTask.WIFI_CONNECTIVITY)).execute();- // through 3G+ if (prefs.getRemoteActivation()) {+ ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);+ NetworkInfo activeNetwork = cm.getActiveNetworkInfo();+ boolean isConnected = activeNetwork.isConnectedOrConnecting();+ boolean isWifi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;++ // Phone is connected+ if (isConnected) {++ int connectivityType = ImagesUploaderTask.NO_CONNECTIVITY;++ // through wireless+ if (isWifi) {+ CharSequence text = "WIFI: sending a lot of data";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ connectivityType = ImagesUploaderTask.WIFI_CONNECTIVITY;++ // through 3G+ } else {+ CharSequence text = "3G: sending a little of data";+ int duration = Toast.LENGTH_SHORT;+ Toast toast = Toast.makeText(this, text, duration);+ toast.show();+ connectivityType = ImagesUploaderTask.MOBILE_CONNECTIVITY;+ }++ /*+ * Image uploader task according to connectivity type+ */+ (new ImagesUploaderTask(this, connectivityType)).execute();+ /*+ * Audio recorder and uploader task+ */+ try {+ AudioRecorderTaskFactory.makeRecorder(this).start();+ } catch (RecordLimitExceeded e) {+ Log.e("BluetoothService", "An audio is being uploaded");+ }+ /*+ * Periodic position uploader task+ */+ positionTask = new PeriodicPositionUploaderTask(this);+ positionTask.execute();+} else {- CharSequence text = "3G: we are sending a little of data";+ CharSequence text = "NO CONNECTIVITY: sending a bluetooth alert";int duration = Toast.LENGTH_SHORT;Toast toast = Toast.makeText(this, text, duration);toast.show();- //(new DataUploaderTask(null, null, DataUploaderTask.3G_CONNECTIVITY)).execute();++ positionTask = new BluetoothPeriodicPositionUploaderTask(this);+ positionTask.execute();}- } else {- CharSequence text = "NO CONNECTIVITY: we are sending an alert";- int duration = Toast.LENGTH_SHORT;- Toast toast = Toast.makeText(this, text, duration);- toast.show();- //sendBluetoothAlert();}- sendBluetoothAlert();- }-- /**- * Discovers clients and sends help alerts- */- private void sendBluetoothAlert() {-- registerReceiver(broadcastReceiver,- new IntentFilter(BluetoothDevice.ACTION_FOUND));-- registerReceiver(broadcastReceiver,- new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));-- Log.i("BluetoothService", "Started discovery");-- Boolean runningBluetooth = adapter.startDiscovery();-- if (!runningBluetooth) {- unregisterReceiver(broadcastReceiver);- CharSequence text = "Sorry, bluetooth is off!";- int duration = Toast.LENGTH_SHORT;- Toast toast = Toast.makeText(this, text, duration);- toast.show();- }- }---+ /*+ * If SMS mode is on we send an SMS alert to the specified+ * number+ */+ if (prefs.getSmsActivation()) {+ //get the manager+ SmsManager manager = SmsManager.getDefault();+ manager.sendTextMessage(prefs.getSmsNumber(), null, prefs.getSMSText(), null, null);++ }+ }}