Merge branch 'develop' into master for v0.5.0

master
Keith Irwin 2017-03-15 06:40:43 -04:00
commit 203e3a4fc2
No known key found for this signature in database
GPG Key ID: 378933C743E2BBC0
9 changed files with 266 additions and 94 deletions

View File

@ -16,13 +16,13 @@ android {
}
}
compileSdkVersion 23
buildToolsVersion "23.0.3"
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "us.keithirwin.tracman"
minSdkVersion 14
targetSdkVersion 23
versionCode 10
versionName "0.2.0"
versionName "0.5.0"
}
buildTypes {
release {
@ -42,11 +42,10 @@ dependencies {
compile 'com.android.support:design:23.2.0'
compile 'com.google.android.gms:play-services-location:9.8.0'
compile 'com.google.android.gms:play-services-auth:9.8.0'
compile ('com.github.nkzawa:socket.io-client:0.4.1'){
exclude group: 'org.json', module: 'json'
compile ('io.socket:socket.io-client:0.8.3'){
exclude group:'org.json', module:'json'
}
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
}
apply plugin: 'com.google.gms.google-services'

View File

@ -13,7 +13,7 @@ public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// Starts location service on boot
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean("pref_start_boot", true)) {
if (prefs.getBoolean("pref_start_boot", false)) {
context.startService(new Intent(context, LocationService.class));
}
}

View File

@ -12,15 +12,12 @@ import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
@ -29,9 +26,11 @@ import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import io.socket.client.IO;
import io.socket.client.Manager;
import io.socket.emitter.Emitter;
import io.socket.client.Socket;
import io.socket.engineio.client.Transport;
import org.json.JSONException;
import org.json.JSONObject;
@ -42,9 +41,10 @@ import java.net.URISyntaxException;
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
public LocationService() {}
private String TAG = "LocationService";
//private String TAG = "LocationService";
final String SERVER_ADDRESS = "https://tracman.org";
private Socket mSocket;
private Socket socket;
private String mUserID;
private String mUserSK;
private SharedPreferences sharedPref;
@ -100,48 +100,92 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
@Override
public void onReceive(Context context, Intent intent) {
connectLocationUpdates(300, LocationRequest.PRIORITY_NO_POWER);
// Log.d(TAG, "Priority and interval lowered due to low power");
//Log.d(TAG, "Priority and interval lowered due to low power");
}
};
// private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// return new java.security.cert.X509Certificate[] {};
// }
//
// public void checkClientTrusted(X509Certificate[] chain,
// String authType) throws CertificateException {
// }
//
// public void checkServerTrusted(X509Certificate[] chain,
// String authType) throws CertificateException {
// }
// } };
@Override
public void onCreate() {
super.onCreate();
// Log.d(TAG, "onCreate called");
//Log.d(TAG, "onCreate called");
// Get preferences
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
setupNotifications(true);
showNotification(getText(R.string.connecting), false);
// Log.d(TAG, "Notification set up");
//Log.d(TAG, "Notification set up");
buildGoogleApiClient();
// Log.d(TAG, "Google API Client built");
//Log.d(TAG, "Google API Client built");
mGoogleApiClient.connect();
// Log.d(TAG, "Connected to Google API Client");
//Log.d(TAG, "Connected to Google API Client");
IntentFilter lowPowerFilter = new IntentFilter();
lowPowerFilter.addAction("android.intent.action.BATTERY_LOW");
registerReceiver(LowPowerReceiver, lowPowerFilter);
// Log.d(TAG, "LowPowerReceiver activated");
//Log.d(TAG, "LowPowerReceiver activated");
mUserID = sharedPref.getString("loggedInUserId", null);
mUserSK = sharedPref.getString("loggedInUserSk", null);
final String SERVER_ADDRESS = "https://tracman.org/";
// Connect to socket
try {
mSocket = IO.socket(SERVER_ADDRESS);
mSocket.on("activate", onActivate);
mSocket.connect();
mSocket.emit("room", "app-"+mUserID);
// Log.d(TAG, "Connected to socket.io server "+SERVER_ADDRESS);
// Connect to socket.io
IO.Options opts = new IO.Options();
opts.secure = true;
socket = IO.socket(SERVER_ADDRESS, opts);
showNotification(getText(R.string.connected), false);
// Log errors
// socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
// @Override
// public void call(Object... args) {
// Transport transport = (Transport) args[0];
// transport.on(Transport.EVENT_ERROR, new Emitter.Listener() {
// @Override
// public void call(Object... args) {
// Exception e = (Exception) args[0];
// Log.e(TAG, "Transport error " + e);
// e.printStackTrace();
// e.getCause().printStackTrace();
// }
// });
// }
// });
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
socket.emit("can-set", mUserID);
}
});
// Listen for activation signals
socket.on("activate", onActivate);
socket.connect();
} catch (URISyntaxException e) {
showNotification(getText(R.string.server_connection_error), false);
// Log.e(TAG, "Failed to connect to sockets server " + SERVER_ADDRESS, e);
//Log.e(TAG, "Failed to connect to sockets server " + SERVER_ADDRESS, e);
}
showNotification(getText(R.string.connected), false);
}
private int getPrioritySetting() {
@ -170,11 +214,11 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
// Get permission
if (!checkLocationPermission(this)) {
// Log.d(TAG, "Location permission denied");
//Log.d(TAG, "Location permission denied");
//TODO: Turn off location updates
} else {
// Log.d(TAG, "Location permission granted");
//Log.d(TAG, "Location permission granted");
// Request location updates
if (mGoogleApiClient.isConnected()) {
@ -200,7 +244,7 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
@Override
public void onConnected(Bundle bundle) {
// Log.d(TAG, "onConnected called");
//Log.d(TAG, "onConnected called");
mLocationRequest = LocationRequest.create();
connectLocationUpdates(getIntervalSetting(), getPrioritySetting());
@ -214,7 +258,7 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Log.e(TAG, "onConnectionFailed: " + connectionResult);
//Log.e(TAG, "onConnectionFailed: " + connectionResult);
showNotification(getText(R.string.google_connection_error), false);
buildGoogleApiClient();
}
@ -223,11 +267,11 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
@Override
public void call(final Object... args) {
if (args[0].toString().equals("true")) {
// Log.d(TAG, "Activating realtime updates");
//Log.d(TAG, "Activating realtime updates");
connectLocationUpdates(getIntervalSetting(), getPrioritySetting());
showNotification(getString(R.string.realtime_updates), true);
} else {
// Log.d(TAG, "Deactivating realtime updates");
//Log.d(TAG, "Deactivating realtime updates");
connectLocationUpdates(300, LocationRequest.PRIORITY_NO_POWER);
showNotification(getString(R.string.occasional_updates), false);
}
@ -237,56 +281,45 @@ public class LocationService extends Service implements GoogleApiClient.Connecti
@Override
public void onLocationChanged(Location location) {
// Check for internet connectivity
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
JSONObject mLocationView = new JSONObject();
try {
mLocationView.put("usr", mUserID);
mLocationView.put("tok", mUserSK);
mLocationView.put("lat", String.valueOf(location.getLatitude()));
mLocationView.put("lon", String.valueOf(location.getLongitude()));
mLocationView.put("dir", String.valueOf(location.getBearing()));
mLocationView.put("spd", String.valueOf(location.getSpeed()));
} catch (JSONException e) {
// Log.e(TAG, "Failed to put JSON data");
}
mSocket.emit("app", mLocationView);
// Log.v(TAG, "Location updated: " + mLocationView.toString());
} else {
showNotification(getString(R.string.not_connected), false);
JSONObject mLocationView = new JSONObject();
try {
mLocationView.put("usr", mUserID);
mLocationView.put("tok", mUserSK);
mLocationView.put("lat", String.valueOf(location.getLatitude()));
mLocationView.put("lon", String.valueOf(location.getLongitude()));
mLocationView.put("dir", String.valueOf(location.getBearing()));
mLocationView.put("spd", String.valueOf(location.getSpeed()));
} catch (JSONException e) {
//Log.e(TAG, "Failed to put JSON data");
}
socket.emit("set", mLocationView);
//Log.v(TAG, "Location updated: " + mLocationView.toString());
}
@Override
public void onConnectionSuspended(int i) {
// Log.d(TAG, "onConnectionSuspended called");
//Log.d(TAG, "onConnectionSuspended called");
showNotification(getText(R.string.google_connection_error), false);
}
@Override
public void onDestroy() {
super.onDestroy();
// Log.d(TAG, "onDestroy executed");
//Log.d(TAG, "onDestroy executed");
mSocket.disconnect();
// Log.d(TAG, "Disconnected from sockets");
socket.disconnect();
socket.off("activate", onActivate);
//Log.d(TAG, "Disconnected from sockets");
mGoogleApiClient.disconnect();
// Log.d(TAG, "Google API disconnected");
//Log.d(TAG, "Google API disconnected");
unregisterReceiver(LowPowerReceiver);
// Log.d(TAG, "LowPowerReceiver deactivated");
//Log.d(TAG, "LowPowerReceiver deactivated");
setupNotifications(false);
showNotification(getText(R.string.disconnected), false);
// Log.d(TAG, "Notification changed");
//Log.d(TAG, "Notification changed");
}
}

View File

@ -25,17 +25,35 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Collections;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Call;
import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.TlsVersion;
public class LoginActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private static final String TAG = "LoginActivity";
// private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;
// Development
//private final String SERVER_ADDRESS = "https://dev.tracman.org/";
//private static final String GOOGLE_WEB_CLIENT_ID = "483494341936-hps4p2pcu3ctshjvqm3pqdbg0t0q281o.apps.googleusercontent.com";
// Production
private final String SERVER_ADDRESS = "https://tracman.org/";
private static final String GOOGLE_WEB_CLIENT_ID = "483494341936-hrn0ms1tebgdtfs5f4i6ebmkt3qmo16o.apps.googleusercontent.com";
@ -122,23 +140,36 @@ public class LoginActivity extends AppCompatActivity implements
}
private void AuthenticateGoogle(final String token) throws Exception {
final OkHttpClient client = new OkHttpClient();
// Needed to support TLS 1.1 and 1.2
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory(), trustManager)
.build();
Request request = new Request.Builder()
.url(SERVER_ADDRESS+"auth/google/idtoken?id_token="+token)
.build();
// Log.d(TAG, "Attempting Tracman signin with token: " + token);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException throwable) {
public void onFailure(Call call, IOException e) {
// Log.e(TAG, "Failed to connect to server: " + SERVER_ADDRESS + "auth/google/idtoken?id_token=" + token);
showError(R.string.server_connection_error);
throwable.printStackTrace();
e.printStackTrace();
}
@Override
public void onResponse(Response res) throws IOException {
public void onResponse(Call call, Response res) throws IOException {
if (!res.isSuccessful()) {
showError(R.string.login_no_user_error);
res.body().close();
@ -173,9 +204,11 @@ public class LoginActivity extends AppCompatActivity implements
editor.commit();
startActivity(new Intent(getBaseContext(), SettingsActivity.class));
}
}
}
});
}
private void handleSignInResult(GoogleSignInResult result) {

View File

@ -6,7 +6,6 @@ import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
@ -14,7 +13,6 @@ import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
@ -36,8 +34,8 @@ import java.util.List;
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
// private static final String TAG = "SettingsActivity";
private static int MY_FINE_LOCATION_PERMISSION = 425;
//private static final String TAG = "SettingsActivity";
private static final int MY_FINE_LOCATION_PERMISSION = 425;
/**
* A preference value change listener that updates the preference's summary
@ -68,6 +66,37 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
};
/**
* A preference value change listener that restarts the location service
* after something relevant is changed.
*/
private Preference.OnPreferenceChangeListener sRestartLocationServiceOnChangeListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object obj) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
stopService(new Intent(SettingsActivity.this, LocationService.class));
if (sharedPref.getBoolean("gps_switch", false)) {
// Ask for location permissions (can't be done in service, only activity)
if (!LocationService.checkLocationPermission(SettingsActivity.this)) {
ActivityCompat.requestPermissions(
SettingsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_FINE_LOCATION_PERMISSION);
}
// Log.d(TAG, "Starting LocationService");
startService(new Intent(SettingsActivity.this, LocationService.class));
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
@ -103,6 +132,9 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
setupActionBar();
// Log.d(TAG, "activity onCreate called");
// Restart LocationService when any related preference is changed
// findPreference("gps_switch").setOnPreferenceChangeListener(sRestartLocationServiceOnChangeListener);
// Get User ID
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String mUserID = sharedPref.getString("loggedInUserId", null);
@ -111,19 +143,9 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
}
private void showLocationPermissionDialog() {
if (!LocationService.checkLocationPermission(this)) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_FINE_LOCATION_PERMISSION);
}
}
@Override
protected void onStop() {
// Log.d(TAG, "onStop called");
//Log.d(TAG, "onStop called");
super.onStop();
// Restart service so settings can take effect
@ -132,13 +154,19 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
if (sharedPref.getBoolean("gps_switch", false)) {
// Ask for location permissions (can't be done in service, only activity)
showLocationPermissionDialog();
if (!LocationService.checkLocationPermission(this)) {
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_FINE_LOCATION_PERMISSION);
}
// Start location tracking service
// Log.d(TAG, "Starting LocationService");
startService(new Intent(this, LocationService.class));
}
}
/**
@ -201,12 +229,16 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
// // Restart LocationService when any related preference is changed
// findPreference("gps_switch").setOnPreferenceChangeListener(sRestartLocationServiceOnChangeListener);
// Bind the summary of preferences to their value
bindPreferenceSummaryToValue(findPreference("broadcast_frequency"));
bindPreferenceSummaryToValue(findPreference("broadcast_priority"));

View File

@ -0,0 +1,75 @@
package us.keithirwin.tracman;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
/**
* @author fkrauthan
* From: https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/
*/
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory internalSSLSocketFactory;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
internalSSLSocketFactory = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}

View File

@ -2,7 +2,7 @@
<string name="app_name" translatable="false">Tracman</string>
<string name="app_address" translatable="false">us.keithirwin.tracman</string>
<string name="version_code" translatable="false">10</string>
<string name="version" translatable="false">0.2.0</string>
<string name="version" translatable="false">0.5.0</string>
<string name="loading">Loading…</string>
<string name="logo_description" translatable="false">[T]</string>

View File

@ -5,7 +5,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.android.tools.build:gradle:2.3.0'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong

View File

@ -1,2 +1,2 @@
#Tue Sep 27 15:34:22 EDT 2016
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
#Fri Mar 03 16:00:54 EST 2017
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip