diff --git a/app/build.gradle b/app/build.gradle index 22ae6fcd..2141682e 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,8 +10,8 @@ android { applicationId "com.prey" minSdkVersion 14 targetSdkVersion 24 - versionCode 155 - versionName '1.9.5' + versionCode 156 + versionName '1.9.6' multiDexEnabled true } buildTypes { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d53c1d6a..eb51ef2a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,8 +2,8 @@ + android:versionCode="156" + android:versionName="1.9.6" > @@ -67,7 +67,6 @@ - @@ -295,6 +294,9 @@ + + + @@ -303,9 +305,6 @@ - - - @@ -342,7 +341,7 @@ - + @@ -353,6 +352,7 @@ + @@ -360,7 +360,7 @@ - + conversionData){ InstallConversionData += install_type + media_source + install_time + click_time + is_first_launch; sessionCount++; } - } } diff --git a/app/src/main/java/com/prey/PreyConfig.java b/app/src/main/java/com/prey/PreyConfig.java index 96bfaa70..f12485a2 100644 --- a/app/src/main/java/com/prey/PreyConfig.java +++ b/app/src/main/java/com/prey/PreyConfig.java @@ -32,6 +32,7 @@ import com.prey.services.PreyDisablePowerOptionsService; import com.prey.services.PreyRegistrationIntentService; +import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; @@ -47,7 +48,7 @@ public class PreyConfig { private static final String HTTP="https://"; - public static final String VERSION_PREY_DEFAULT="1.9.5"; + public static final String VERSION_PREY_DEFAULT="1.9.6"; // Milliseconds per second private static final int MILLISECONDS_PER_SECOND = 1000; @@ -129,13 +130,11 @@ public class PreyConfig { public static final int ANDROID_TOUR_COMPLETED = 2003; public static final int ANDROID_PRIVILEGES_GIVEN = 2004; public static final int ANDROID_SIGN_IN = 2005; - public static final int ANDROID_LOGIN_SETTINGS = 2007; - public static final int ANDROID_FAILED_LOGIN_SETTINGS = 2008; public static final int ANDROID_VERSION_UPDATED = 2009; public static final int ANDROID_ONBOARDING_INIT = 2010; public static final int ANDROID_ONBOARDING_COMPLETED = 2011; - public static final String PREFERENCE_PREY_VERSION="PREFERENCE_PREY_VERSION"; + public static final String PREY_VERSION="PREY_VERSION"; public static final String API_KEY="API_KEY"; public static final String DEVICE_ID = "DEVICE_ID"; @@ -168,11 +167,12 @@ public class PreyConfig { public static final String COUNTER_OFF="counter_off"; - - public static final String AWARE="aware"; public static final String AWARE_LAT="AWARE_LAT"; public static final String AWARE_LNG="AWARE_LNG"; public static final String AWARE_ACC="AWARE_ACC"; + public static final String AWARE_DATE="AWARE_DATE"; + + public static final String AUTO_CONNECT="auto_connect"; @@ -194,7 +194,7 @@ public class PreyConfig { private boolean runOnce; private boolean disablePowerOptions; - + private String version; private PreyConfig(Context ctx) { this.ctx = ctx; @@ -215,7 +215,10 @@ private PreyConfig(Context ctx) { this.disablePowerOptions = settings.getBoolean(PreyConfig.PREFS_DISABLE_POWER_OPTIONS, false); } catch ( Exception e){ } catch ( NoClassDefFoundError e) {} - + try { + version =getString(PreyConfig.PREY_VERSION, getInfoPreyVersion(ctx)); + }catch ( Exception e){ + } } public static synchronized PreyConfig getPreyConfig(Context ctx) { @@ -228,8 +231,10 @@ public static synchronized PreyConfig getPreyConfig(Context ctx) { return cachedInstance; } - private static void deleteCacheInstance() { + public static void deleteCacheInstance(Context ctx) { cachedInstance = null; + PreferenceManager.getDefaultSharedPreferences(ctx). + edit().clear().apply(); } public Context getContext(){ @@ -302,7 +307,9 @@ private void removeKey(String key){ SharedPreferences.Editor editor = settings.edit(); editor.remove(key); editor.commit(); - }catch(Exception e){} + }catch(Exception e){ + PreyLogger.e("removeKey:"+e.getMessage(),e); + } } private long getLong(String key, long defaultValue){ @@ -433,7 +440,7 @@ public void setSecurityPrivilegesAlreadyPrompted(boolean securityPrivilegesAlrea editor.commit(); } - public String getPreyVersion() { + public String getInfoPreyVersion(Context ctx) { String versionName=VERSION_PREY_DEFAULT; try{ PackageInfo pinfo =ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); @@ -952,14 +959,6 @@ public boolean isSmsCommand(){ return getBoolean(PreyConfig.SMS_COMMAND, false); } - public String getPreferencePreyVersion(){ - return getString(PreyConfig.PREFERENCE_PREY_VERSION, ""); - } - - public void setPreferencePreyVersion(String preferencePreyVersion) { - saveString(PreyConfig.PREFERENCE_PREY_VERSION, preferencePreyVersion); - } - public void setLocationLowBattery(boolean locationLowBattery) { saveBoolean(PreyConfig.PREFERENCE_LOCATION_LOW_BATTERY, locationLowBattery); } @@ -1034,14 +1033,6 @@ public void setJobIdLock(String jobIdLock) { saveString(PreyConfig.JOB_ID_LOCK, jobIdLock); } - public boolean getAware() { - return getBoolean(PreyConfig.AWARE, false); - } - - public void setAware(boolean aware) { - this.saveBoolean(PreyConfig.AWARE, aware); - } - public int getCounterOff(){ return getInt(PreyConfig.COUNTER_OFF,0); } @@ -1067,12 +1058,26 @@ public long getLastTimeSecureLock(){ return getLong(PreyConfig.LAST_TIME_SECURE_LOCK, 0); } + public static SimpleDateFormat FORMAT_SDF_AWARE=new SimpleDateFormat("yyyy-MM-dd"); + public void setLocationAware(PreyLocation location){ - saveFloat(PreyConfig.AWARE_LAT,(float)location.getLat()); - saveFloat(PreyConfig.AWARE_LNG,(float)location.getLng()); - saveFloat(PreyConfig.AWARE_ACC,location.getAccuracy()); + if(location!=null) { + saveFloat(PreyConfig.AWARE_LAT, (float) location.getLat()); + saveFloat(PreyConfig.AWARE_LNG, (float) location.getLng()); + saveFloat(PreyConfig.AWARE_ACC, location.getAccuracy()); + } + } + + public String getAwareDate(){ + return getString(PreyConfig.AWARE_DATE, ""); + } + + public void setAwareDate(String awareDate){ + PreyLogger.i("AWARE setAwareDate ["+awareDate+"]"); + saveString(PreyConfig.AWARE_DATE, awareDate); } + public PreyLocation getLocationAware(){ try{ float lat=getFloat(PreyConfig.AWARE_LAT,0); @@ -1091,4 +1096,20 @@ public PreyLocation getLocationAware(){ } } + public boolean getAutoConnect() { + return getBoolean(PreyConfig.AUTO_CONNECT, false); + } + + public void setAutoConnect(boolean auto_connect) { + this.saveBoolean(PreyConfig.AUTO_CONNECT, auto_connect); + } + + public String getPreyVersion(){ + return version; + } + + public void setPreyVersion(String version) { + this.version=version; + this.saveString(PreyConfig.PREY_VERSION, version); + } } \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/autoconnect/AutoConnectAlarmReceiver.java b/app/src/main/java/com/prey/actions/autoconnect/AutoConnectAlarmReceiver.java new file mode 100644 index 00000000..8dc52b7d --- /dev/null +++ b/app/src/main/java/com/prey/actions/autoconnect/AutoConnectAlarmReceiver.java @@ -0,0 +1,31 @@ +package com.prey.actions.autoconnect; + + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + + +import com.prey.PreyLogger; + +public class AutoConnectAlarmReceiver extends BroadcastReceiver { + + @Override + public void onReceive(Context context, Intent intent) { + try { + String minuteSt = "2";//PreyConfig.getPreyConfig(context).getIntervalAware(); + PreyLogger.d("______________________________"); + PreyLogger.d("______________________________"); + PreyLogger.d("----------AutoConnect AlarmReceiver onReceive[" + minuteSt + "]"); + final Context ctx = context; + new Thread() { + public void run() { + new AutoConnectService().run(ctx); + } + }.start(); + } catch (Exception e) { + PreyLogger.e("AutoConnect AlarmReceiver error:" + e.getMessage(), e); + } + } + +} diff --git a/app/src/main/java/com/prey/actions/autoconnect/AutoConnectBlacklist.java b/app/src/main/java/com/prey/actions/autoconnect/AutoConnectBlacklist.java new file mode 100644 index 00000000..5583ac70 --- /dev/null +++ b/app/src/main/java/com/prey/actions/autoconnect/AutoConnectBlacklist.java @@ -0,0 +1,39 @@ +package com.prey.actions.autoconnect; + +import com.prey.PreyLogger; + +import java.util.ArrayList; +import java.util.List; + +public class AutoConnectBlacklist { + + + private static AutoConnectBlacklist instance=null; + private AutoConnectBlacklist(){ + blackList=new ArrayList<>(); + } + private List blackList; + + public static AutoConnectBlacklist getInstance(){ + if(instance==null){ + instance=new AutoConnectBlacklist(); + } + return instance; + } + + public boolean contains(String ssid){ + return blackList.contains(ssid); + } + public void add(String ssid){ + blackList.add(ssid); + } + + public void print( ){ + + for (int i=0;blackList!=null&&i results = null; + int j = 0; + + do { + mWifiManager.reconnect(); + mWifiManager.startScan(); + results = mWifiManager.getScanResults(); + PreyLogger.i("AutoConnect Service results intento[" + j + "] tamanio" + results.size()); + j++; + if (results.size() == 0) { + try { + Thread.sleep(3000); + } catch (Exception e) { + } + } + } while (results.size() == 0 && j < 20); + + + + List openList=new ArrayList<>(); + for (int i = 0; results != null && i < results.size(); i++) { + ScanResult scan = results.get(i); + final String ssid = scan.SSID; + // PreyLogger.i("AutoConnect Service ["+i+"] SSID:" + scan.SSID + " capabilities:" + scan.capabilities + " "); + AutoConnectBlacklist.getInstance().print(); + if ("[ESS]".equals(scan.capabilities) && !AutoConnectBlacklist.getInstance().contains(ssid)&& !ssid.equals("Prey-Guest")) { + PreyLogger.i("AutoConnect Service SSID:" + ssid + " capabilities:" + scan.capabilities + " "); + if(!openList.contains(ssid)) + openList.add(ssid); + } + } + + + Comparator comp = new Comparator() { + @Override + public int compare(String a, String b) { + return a.compareTo(b); + } + }; + + + Collections.sort(openList, comp); + PreyLogger.i("AutoConnect Service openList size:" + (openList==null?0:openList.size())); + for (int i = 0; openList != null && i < openList.size(); i++) { + String ssid = openList.get(i); + int networkId = connect(ctx, ssid); + try { + Thread.sleep(4000); + } catch (Exception e) { + } + haveNetwork = haveNetworkConnection(ctx); + PreyLogger.i("AutoConnect Service haveNetwork["+i+"][" + ssid + "]:" + haveNetwork); + if (haveNetwork) { + JSONObject jsnobject = null; + try { + String device=PreyConfig.getPreyConfig(ctx).getDeviceId(); + String uri = "https://solid.preyproject.com/api/v2/devices/"+device+"/status.json"; + URL url = new URL(uri); + PreyLogger.i("AutoConnect Service url["+i+"][" + ssid + "]:" + url); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(3000); + connection.addRequestProperty("Authorization", UtilConnection.getAuthorization(PreyConfig.getPreyConfig(ctx))); + int responseCode = connection.getResponseCode(); + + PreyLogger.i("AutoConnect Service responseCode["+i+"][" + ssid + "]:" + responseCode); + PreyHttpResponse response = UtilConnection.convertPreyHttpResponse(responseCode, connection); + String responseAsString = null; + if (response != null) { + responseAsString = response.getResponseAsString(); + PreyLogger.i("AutoConnect Service responseAsString["+i+"][" + ssid + "]:" + responseAsString); + } + if (responseAsString != null) { + jsnobject = new JSONObject(responseAsString); + } + + PreyLogger.i("AutoConnect Service jsnobject["+i+"][" + ssid + "]:" + jsnobject); + + } catch (Exception e) { + PreyLogger.i("AutoConnect Service error["+i+"][" + ssid + "]:" + e.getMessage()); + } + + if (jsnobject != null) { + + break; + } else { + WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); + wifiManager.removeNetwork(networkId); + + PreyLogger.i("AutoConnect Service removeNetwork ["+i+"][" + ssid + "]:" + networkId); + AutoConnectBlacklist.getInstance().add(ssid); + } + } + // + + } + if (cerrar) { + PreyLogger.i("AutoConnect Service mWifiManager.isWifiEnabled():" + mWifiManager.isWifiEnabled()); + //mWifiManager.setWifiEnabled(false); + PreyLogger.i("AutoConnect Service mWifiManager.isWifiEnabled():" + mWifiManager.isWifiEnabled()); + } + } + + } + + + public int connect(Context ctx,String networkSSID) { + PreyLogger.i("AutoConnect Service connect:" + networkSSID); + + WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); + + WifiConfiguration config = new WifiConfiguration(); + config.SSID = "\"".concat(networkSSID).concat("\""); + config.status = WifiConfiguration.Status.DISABLED; + config.priority = 40; + config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + config.allowedAuthAlgorithms.clear(); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + + config.preSharedKey = "\"p8hHxCw8jxrq\""; + + int networkId = wifiManager.addNetwork(config); + PreyLogger.i("AutoConnect Service networkSSID["+networkSSID+"] networkId:" + networkId); + if (networkId != -1) { + + + boolean isDisconnected = wifiManager.disconnect(); + PreyLogger.i("isDisconnected : " + isDisconnected); + + boolean isEnabled = wifiManager.enableNetwork(networkId, true); + PreyLogger.i("isEnabled : " + isEnabled); + + boolean isReconnected = wifiManager.reconnect(); + + } + return networkId; + + } + + private boolean haveNetworkConnection(Context ctx) { + + boolean haveConnectedMobile = false; + boolean haveConnectedWifi = false; + ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo[] netInfo = cm.getAllNetworkInfo(); + for (NetworkInfo ni : netInfo) { + if (ni.getTypeName().equalsIgnoreCase("WIFI")) + if (ni.isConnected()) + haveConnectedWifi = true; + if (ni.getTypeName().equalsIgnoreCase("MOBILE")) + if (ni.isConnected()) + haveConnectedMobile = true; + } + return haveConnectedWifi || haveConnectedMobile; + } + + + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + } + + boolean wifiConnected=false; + boolean mobileConnected=false; + + public void updateConnectedFlags(Context ctx) { + ConnectivityManager connMgr = (ConnectivityManager) + ctx.getSystemService(Context.CONNECTIVITY_SERVICE); + + NetworkInfo activeInfo = connMgr.getActiveNetworkInfo(); + if (activeInfo != null && activeInfo.isConnected()) { + wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI; + mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE; + } else { + wifiConnected = false; + mobileConnected = false; + } + } + + + + +} diff --git a/app/src/main/java/com/prey/actions/autoconnect/BriefWiFiInfo.java b/app/src/main/java/com/prey/actions/autoconnect/BriefWiFiInfo.java new file mode 100644 index 00000000..c3f98be4 --- /dev/null +++ b/app/src/main/java/com/prey/actions/autoconnect/BriefWiFiInfo.java @@ -0,0 +1,24 @@ +package com.prey.actions.autoconnect; + +public class BriefWiFiInfo { + + private String ssid; + private int rssi; + + + public String getSsid() { + return ssid; + } + + public void setSsid(String ssid) { + this.ssid = ssid; + } + + public int getRssi() { + return rssi; + } + + public void setRssi(int rssi) { + this.rssi = rssi; + } +} diff --git a/app/src/main/java/com/prey/actions/autoconnect/WifiConnect.java b/app/src/main/java/com/prey/actions/autoconnect/WifiConnect.java new file mode 100644 index 00000000..7f4e897b --- /dev/null +++ b/app/src/main/java/com/prey/actions/autoconnect/WifiConnect.java @@ -0,0 +1,167 @@ +package com.prey.actions.autoconnect; + + +import android.content.Context; +import android.net.wifi.ScanResult; +import android.net.wifi.WifiConfiguration; +import android.net.wifi.WifiManager; + +import com.prey.PreyLogger; + +import java.util.ArrayList; +import java.util.List; + +public class WifiConnect { + + private Context ctx; + private WifiManager mWifiManager; + + + public WifiConnect(Context ctx) { + this.ctx = ctx; + + mWifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); + + } + + + public void scan(){ + + if (mWifiManager.isWifiEnabled() == false) { + + mWifiManager.setWifiEnabled(true); + try { Thread.sleep(4000);} catch (Exception e) { } + } + List results = mWifiManager.getScanResults(); + PreyLogger.i("results size:" + results.size()); + for (int i = 0; results != null && i < results.size(); i++) { + ScanResult scan = results.get(i); + + if ("[ESS]".equals(scan.capabilities)&&scan.SSID.indexOf("Prey")<0) { + PreyLogger.i("ssid:" + scan.SSID + " " + scan.capabilities + " "); + + //WifiConfiguration conf = new WifiConfiguration(); + String ssid = scan.SSID ; + //wifiManager.addNetwork(conf); + connect(ctx,ssid); + // break; + } + } + } + + public void onScanResultsAvailable() { + List scanResults = mWifiManager.getScanResults(); + ArrayList wiFiList = new ArrayList<>(); + for (ScanResult scanResult : scanResults) { + BriefWiFiInfo briefWiFiInfo = new BriefWiFiInfo(); + briefWiFiInfo.setSsid(scanResult.SSID); + int rssiPercentage = WifiManager.calculateSignalLevel(scanResult.level, 100); + briefWiFiInfo.setRssi(rssiPercentage); + wiFiList.add(briefWiFiInfo); + } + // mWifiConnectorListener.onWiFiScanResults(wiFiList); + } + + + public void connect(Context ctx,String networkSSID) { + WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); + + WifiConfiguration config = new WifiConfiguration(); + config.SSID = "\"".concat(networkSSID).concat("\""); + config.status = WifiConfiguration.Status.DISABLED; + config.priority = 40; + config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + config.allowedAuthAlgorithms.clear(); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + int networkId = wifiManager.addNetwork(config); + + if (networkId != -1) { + + + boolean isDisconnected = wifiManager.disconnect(); + PreyLogger.i("isDisconnected : " + isDisconnected); + + boolean isEnabled = wifiManager.enableNetwork(networkId, true); + PreyLogger.i("isEnabled : " + isEnabled); + + boolean isReconnected = wifiManager.reconnect(); + + } + + } + + +/* + + public NetworkInfo.DetailedState connectToWiFi(int securityType, String ssid, String key) { + Log.d(TAG, "connectToWiFi() called with: securityType = [" + securityType + "], ssid = [" + ssid + "], key = [" + key + "]"); + // Check if already connected to that wifi + String currentSsid = getActiveConnection().getSSID(); + Log.d(TAG, "Current Ssid " + currentSsid); + NetworkInfo.DetailedState currentState = WifiInfo.getDetailedStateOf(getActiveConnection().getSupplicantState()); //todo check this + if (currentState == NetworkInfo.DetailedState.CONNECTED && currentSsid.equals(quoted(ssid))) { + Log.d(TAG, "Already connected"); + mWifiConnectorListener.onWiFiStateUpdate(getActiveConnection(), NetworkInfo.DetailedState.CONNECTED); + return NetworkInfo.DetailedState.CONNECTED; + } + + int highestPriorityNumber = 0; + WifiConfiguration selectedConfig = null; + // Check if not connected but has connected to that wifi in the past + for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) { + if (config.priority > highestPriorityNumber) highestPriorityNumber = config.priority; + if (config.SSID.equals(quoted(ssid)) && config.allowedKeyManagement.get(securityType)) { + Log.d(TAG, "Saved preshared key is " + config.preSharedKey); + if (securityType == WifiConfiguration.KeyMgmt.WPA_PSK + && config.preSharedKey != null && config.preSharedKey.equals(key)) + selectedConfig = config; + else if (securityType == WifiConfiguration.KeyMgmt.NONE) + selectedConfig = config; + } + } + + if (selectedConfig != null) { + selectedConfig.priority = highestPriorityNumber + 1; + mWifiManager.updateNetwork(selectedConfig); + // mWifiManager.disconnect(); /* disconnect from whichever wifi you're connected to + mWifiManager.enableNetwork(selectedConfig.networkId, true); + mWifiManager.reconnect(); + Log.d(TAG, "Connection exists in past, enabling and connecting priority = " + highestPriorityNumber); + return NetworkInfo.DetailedState.CONNECTING; + } + + // Make new connection + WifiConfiguration config = new WifiConfiguration(); + config.SSID = quoted(ssid); + config.priority = highestPriorityNumber + 1; + config.status = WifiConfiguration.Status.ENABLED; + if (securityType == WifiConfiguration.KeyMgmt.WPA_PSK) { + config.preSharedKey = quoted(key); + config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); + config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); + config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); + config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); + config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); + } else { + config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); + } + Log.d(TAG, "Attempting new wifi connection, setting priority number to, connecting " + config.priority); + + int netId = mWifiManager.addNetwork(config); + // mWifiManager.disconnect(); disconnect from whichever wifi you're connected to + mWifiManager.enableNetwork(netId, true); + mWifiManager.reconnect(); // todo? + return NetworkInfo.DetailedState.CONNECTING; + } + +*/ +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/aware/AwareAlarmReceiver.java b/app/src/main/java/com/prey/actions/aware/AwareAlarmReceiver.java deleted file mode 100644 index 2f557370..00000000 --- a/app/src/main/java/com/prey/actions/aware/AwareAlarmReceiver.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Created by Orlando Aliaga - * Copyright 2018 Prey Inc. All rights reserved. - * License: GPLv3 - * Full license at "/LICENSE" - ******************************************************************************/ -package com.prey.actions.aware; - - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -import com.prey.PreyConfig; -import com.prey.PreyLogger; - -public class AwareAlarmReceiver extends BroadcastReceiver { - - @Override - public void onReceive(Context context, Intent intent) { - try { - String minuteSt = PreyConfig.getPreyConfig(context).getIntervalAware(); - PreyLogger.d("______________________________"); - PreyLogger.d("______________________________"); - PreyLogger.d("----------AlarmAwareReceiver onReceive[" + minuteSt + "]"); - final Context ctx = context; - new Thread() { - public void run() { - new AwareService().run(ctx); - } - }.start(); - } catch (Exception e) { - - } - } - -} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/aware/AwareConfig.java b/app/src/main/java/com/prey/actions/aware/AwareConfig.java index 969e9188..6f63e70c 100644 --- a/app/src/main/java/com/prey/actions/aware/AwareConfig.java +++ b/app/src/main/java/com/prey/actions/aware/AwareConfig.java @@ -8,7 +8,6 @@ import android.content.Context; -import com.prey.PreyConfig; import com.prey.PreyLogger; import com.prey.net.PreyWebServices; @@ -21,8 +20,11 @@ public class AwareConfig { private AwareConfig(Context ctx) { this.ctx = ctx; + locationAware=getLocationAwareJson(); } + public boolean locationAware = false; + public static synchronized AwareConfig getAwareConfig(Context ctx) { if (cachedInstance == null) { synchronized (AwareConfig.class) { @@ -33,35 +35,32 @@ public static synchronized AwareConfig getAwareConfig(Context ctx) { return cachedInstance; } - public boolean getLocationAware() { - boolean locationAware = false; + public boolean isLocationAware(){ + return locationAware; + } + + public void setLocationAware(boolean locationAware){ + this.locationAware=locationAware; + } + + private boolean getLocationAwareJson() { try { JSONObject jsnobject = PreyWebServices.getInstance().getStatus(ctx); if (jsnobject != null) { + PreyLogger.d("AWARE jsnobject :" + jsnobject); JSONObject jsnobjectSettings = jsnobject.getJSONObject("settings"); JSONObject jsnobjectLocal = jsnobjectSettings.getJSONObject("local"); locationAware = jsnobjectLocal.getBoolean("location_aware"); - PreyLogger.d("locationAware :" + locationAware); + PreyLogger.d("AWARE getLocationAware :" + locationAware); } else { - PreyLogger.d("getLocationAware null"); + PreyLogger.d("AWARE getLocationAware null"); + locationAware = false; } } catch (Exception e) { - PreyLogger.e("Error:" + e.getMessage(), e); + PreyLogger.e("AWARE Error:" + e.getMessage(), e); + locationAware = false; } return locationAware; } - public void init() { - boolean locationAware = getLocationAware(); - if (locationAware) { - startAware(); - } - } - - public void startAware() { - PreyLogger.d("startAware"); - PreyConfig.getPreyConfig(ctx).setAware(true); - PreyConfig.getPreyConfig(ctx).setIntervalAware("15"); - AwareScheduled.getInstance(ctx).run(); - } } \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/aware/AwareController.java b/app/src/main/java/com/prey/actions/aware/AwareController.java new file mode 100644 index 00000000..b474ecca --- /dev/null +++ b/app/src/main/java/com/prey/actions/aware/AwareController.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2018 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.aware; + +import android.Manifest; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.support.annotation.NonNull; +import android.support.v4.app.ActivityCompat; + +import com.google.android.gms.location.Geofence; +import com.google.android.gms.location.GeofencingRequest; +import com.google.android.gms.location.LocationServices; +import com.google.android.gms.tasks.OnFailureListener; +import com.google.android.gms.tasks.OnSuccessListener; + +import com.prey.FileConfigReader; +import com.prey.PreyConfig; +import com.prey.PreyLogger; +import com.prey.actions.location.LocationUtil; +import com.prey.actions.location.PreyLocation; +import com.prey.net.PreyHttpResponse; +import com.prey.net.PreyWebServices; + +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class AwareController { + + public static String GEO_AWARE_NAME = "AWARE"; + private static AwareController INSTANCE; + + public static AwareController getInstance() { + if (INSTANCE == null) { + INSTANCE = new AwareController(); + } + return INSTANCE; + } + + public void init(Context ctx) { + try{ + boolean isLocationAware=AwareConfig.getAwareConfig(ctx).isLocationAware(); + PreyLogger.d("AWARE AwareController init:"+isLocationAware); + if (isLocationAware) { + PreyLocation locationAware = LocationUtil.getLocation(ctx, null, false); + PreyLocation locationNow = sendAware(ctx, locationAware); + if (locationNow != null) { + run(ctx); + } + } + } catch (Exception e) { + PreyLogger.e("AWARE error:" + e.getMessage(), e); + } + } + + public void run(final Context ctx) { + PreyLogger.d("AWARE AwareController run"); + try { + int loiteringDelay= FileConfigReader.getInstance(ctx).getGeofenceLoiteringDelay(); + int radiusAware= FileConfigReader.getInstance(ctx).getRadiusAware(); + //remove + List listRemove = new ArrayList(); + listRemove.add(GEO_AWARE_NAME); + LocationServices.getGeofencingClient(ctx).removeGeofences(listRemove); + //new + PreyLocation locationOld=PreyConfig.getPreyConfig(ctx).getLocationAware(); + double lat=locationOld.getLat(); + double lng=locationOld.getLng(); + PreyLogger.d("AWARE lat:" + lat + " lng:" + lng); + List mGeofenceList = new ArrayList(); + mGeofenceList.add(new com.google.android.gms.location.Geofence.Builder() + .setRequestId(GEO_AWARE_NAME) + .setCircularRegion(lat, lng, radiusAware) + .setExpirationDuration(Geofence.NEVER_EXPIRE) + .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER|Geofence.GEOFENCE_TRANSITION_EXIT) + .setLoiteringDelay(loiteringDelay) + .setNotificationResponsiveness(0) + .build()); + GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); + builder.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_EXIT|GeofencingRequest.INITIAL_TRIGGER_ENTER); + builder.addGeofences(mGeofenceList); + GeofencingRequest geofencingRequest = builder.build(); + if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + Intent intent = new Intent(ctx, AwareIntentService.class); + PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + LocationServices.getGeofencingClient(ctx).addGeofences(geofencingRequest,pendingIntent) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + PreyLogger.d("AWARE saveGeofence"); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + PreyLogger.e("AWARE saveGeofence error: " + e.getMessage(),e); + } + }); + }//if + } catch (Exception e) { + PreyLogger.e("AWARE error:" + e.getMessage(), e); + } + } + + + public static synchronized PreyLocation sendAware(Context ctx, PreyLocation locationAware) throws Exception{ + //get location + PreyLocation locationNow = locationAware; + if (locationNow != null) { + PreyLocation locationOld = PreyConfig.getPreyConfig(ctx).getLocationAware(); + if (locationOld != null) { + //compare + int maxDistance=PreyConfig.getPreyConfig(ctx).getDistanceAware(); + double distance = LocationUtil.distance(locationNow, locationOld); + PreyLogger.d("AWARE distance:"+distance +" <= " + maxDistance); + if (distance <= maxDistance){ + locationNow=null; + } + } + PreyConfig.getPreyConfig(ctx).setLocationAware(locationAware); + } + //send aware + if (locationNow != null) { + sendNowAware(ctx,locationNow); + } + return locationAware; + } + + public static void getSendNowAware(Context ctx) throws Exception{ + PreyLocation locationNow= LocationUtil.getLocation(ctx, null, false); + PreyLogger.d("AWARE locationNow:"+locationNow.toString()); + sendNowAware(ctx,locationNow); + } + + private static void sendNowAware(Context ctx, PreyLocation locationNow) throws Exception { + boolean isLocationAware = AwareConfig.getAwareConfig(ctx).isLocationAware(); + PreyLogger.d("AWARE sendNowAware isLocationAware:"+isLocationAware); + if (isLocationAware){ + String messageId = null; + String reason = null; + double accD = Math.round(locationNow.getAccuracy() * 100.0) / 100.0; + JSONObject json = new JSONObject(); + json.put("lat", Double.toString(locationNow.getLat())); + json.put("lng", Double.toString(locationNow.getLng())); + json.put("accuracy", Double.toString(accD)); + json.put("method", locationNow.getMethod()); + JSONObject location = new JSONObject(); + location.put("location", json); + PreyHttpResponse preyResponse = PreyWebServices.getInstance().sendLocation(ctx, location); + if (preyResponse != null) { + if (preyResponse.getStatusCode() == 201) { + PreyLogger.d("AWARE getStatusCode 201"); + AwareConfig.getAwareConfig(ctx).setLocationAware(false); + } + PreyConfig.getPreyConfig(ctx).setAwareDate(PreyConfig.FORMAT_SDF_AWARE.format(new Date())); + PreyLogger.d("AWARE sendNowAware:" + locationNow.toString()); + } + } + } + + + +} diff --git a/app/src/main/java/com/prey/actions/aware/AwareIntentService.java b/app/src/main/java/com/prey/actions/aware/AwareIntentService.java new file mode 100644 index 00000000..c0827965 --- /dev/null +++ b/app/src/main/java/com/prey/actions/aware/AwareIntentService.java @@ -0,0 +1,71 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2018 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.aware; + +import android.app.IntentService; +import android.content.Context; +import android.content.Intent; +import android.location.Location; + +import com.google.android.gms.location.Geofence; +import com.google.android.gms.location.GeofencingEvent; + +import com.prey.PreyConfig; +import com.prey.PreyLogger; +import com.prey.actions.geofences.GeofenceController; +import com.prey.actions.geofences.GeofenceDataSource; +import com.prey.actions.location.PreyLocation; + +import java.util.List; + +public class AwareIntentService extends IntentService { + + public AwareIntentService() { + super(PreyConfig.TAG); + } + + @Override + protected void onHandleIntent(Intent intent) { + PreyLogger.d("AWARE AwareIntentService"); + GeofencingEvent event = GeofencingEvent.fromIntent(intent); + if (event != null) { + PreyLogger.d("AWARE AwareIntentService event:"+(event.getGeofenceTransition()== Geofence.GEOFENCE_TRANSITION_ENTER?"GEOFENCING_IN":"GEOFENCING_OUT")); + if (event.hasError()) { + onError(event.getErrorCode()); + } else { + notifyGeofenceTransition(getApplicationContext(), event.getGeofenceTransition(), event.getTriggeringGeofences(), event.getTriggeringLocation()); + } + } + stopSelf(); + } + + private void notifyGeofenceTransition(Context context, int geofenceTransition, List triggeringGeofences, Location location) { + GeofenceDataSource dataSource = new GeofenceDataSource(context); + String transition = ""; + for (Geofence geofence : triggeringGeofences) { + if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { + transition = GeofenceController.GEOFENCING_IN; + } else { + transition = GeofenceController.GEOFENCING_OUT; + } + } + if(GeofenceController.GEOFENCING_OUT.equals(transition)) { + PreyLogger.d("AWARE notifyGeofenceTransition transition:"+transition); + try { + AwareController.sendAware(context,new PreyLocation(location)); + AwareController.getInstance().run(context); + } catch (Exception e) { + PreyLogger.e("AWARE notifyGeofenceTransition error:" + e.getMessage(), e); + } + } + } + + private void onError(int i) { + PreyLogger.d("AWARE onError in " + (i==Geofence.GEOFENCE_TRANSITION_ENTER?"GEOFENCING_IN":"GEOFENCING_OUT")); + } + +} diff --git a/app/src/main/java/com/prey/actions/aware/AwareService.java b/app/src/main/java/com/prey/actions/aware/AwareService.java deleted file mode 100644 index 15f50f44..00000000 --- a/app/src/main/java/com/prey/actions/aware/AwareService.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Created by Orlando Aliaga - * Copyright 2018 Prey Inc. All rights reserved. - * License: GPLv3 - * Full license at "/LICENSE" - ******************************************************************************/ -package com.prey.actions.aware; - - -import android.app.IntentService; -import android.content.Context; -import android.content.Intent; -import android.location.Address; -import android.location.Geocoder; -import android.location.Location; - -import com.prey.PreyConfig; -import com.prey.PreyLogger; -import com.prey.actions.geofences.GeofenceController; -import com.prey.actions.geofences.GeofenceDto; -import com.prey.actions.location.LocationUtil; -import com.prey.actions.location.PreyLocation; -import com.prey.json.UtilJson; -import com.prey.net.PreyHttpResponse; -import com.prey.net.PreyWebServices; - -import org.json.JSONObject; - -import java.util.List; -import java.util.Locale; - -public class AwareService extends IntentService { - - public AwareService() { - super("awareService"); - } - - public AwareService(String name) { - super(name); - } - - @Override - protected void onHandleIntent(Intent intent) { - run(getApplicationContext()); - stopSelf(); - } - - public void run(Context ctx) { - PreyLogger.d("AwareService run"); - int i = 0; - try { - String minuteSt = PreyConfig.getPreyConfig(ctx).getIntervalAware(); - PreyLogger.d("AwareService [" + minuteSt + "]"); - if (PreyConfig.getPreyConfig(ctx).getAware() && minuteSt != null && !"".equals(minuteSt)) { - int geofenceMaximumAccuracy=PreyConfig.getPreyConfig(ctx).getGeofenceMaximumAccuracy(); - PreyLocation locationNow = null; - float accuracy=0; - do { - locationNow = LocationUtil.getLocation(ctx, null, false); - if(locationNow!=null){ - accuracy=locationNow.getAccuracy(); - } - Thread.sleep(1000); - i = i + 1; - } while (i < 3); - - - if(locationNow != null && geofenceMaximumAccuracy getJSONFromUrl(Context ctx) { - String commands = null; + String json = null; try { - commands = PreyWebServices.getInstance().geofencing(ctx); + json = PreyWebServices.getInstance().geofencing(ctx); } catch (Exception e) { } - return getJSONFromTxt(ctx, commands); + return getJSONFromTxt(ctx, json); } public static List getJSONFromTxt(Context ctx, String json) { @@ -47,7 +47,7 @@ public static List getJSONFromTxt(Context ctx, String json) { listGeofence.add(geofence); } } catch (Exception e) { - PreyLogger.e("error in parser:" + e.getMessage(), e); + return null; } return listGeofence; } diff --git a/app/src/main/java/com/prey/actions/geofences/GeofenceController.java b/app/src/main/java/com/prey/actions/geofences/GeofenceController.java index 600573c7..a2a75786 100644 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceController.java +++ b/app/src/main/java/com/prey/actions/geofences/GeofenceController.java @@ -15,11 +15,6 @@ import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.common.api.PendingResult; -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.api.Status; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationServices; @@ -28,7 +23,7 @@ import com.prey.FileConfigReader; import com.prey.PreyConfig; import com.prey.PreyLogger; -import com.prey.actions.aware.AwareService; +import com.prey.actions.location.LocationUtil; import com.prey.actions.location.PreyLocation; import com.prey.events.Event; import com.prey.events.manager.EventThread; @@ -49,7 +44,10 @@ public class GeofenceController { private List listWeb = null; private Map mapBD = null; private Map mapWeb = null; - private GeofenceDataSource dataSource = null; + + public static final String GEOFENCING_OUT="geofencing_out"; + public static final String GEOFENCING_IN="geofencing_in"; + public static GeofenceController getInstance() { if (INSTANCE == null) { @@ -58,77 +56,83 @@ public static GeofenceController getInstance() { return INSTANCE; } - public void run(final Context ctx) { + + public void run(Context ctx) { try { - dataSource = new GeofenceDataSource(ctx); + GeofenceDataSource dataSource = new GeofenceDataSource(ctx); listBD = dataSource.getAllGeofences(); - listWeb = GeofecenceParse.getJSONFromUrl(ctx); - updateZones(ctx,listWeb,listBD); + listWeb =null; + try {listWeb = GeofecenceParse.getJSONFromUrl(ctx); } catch (Exception e) {} + updateZones(ctx,listWeb,listBD,dataSource); } catch (Exception e) { PreyLogger.e("error run"+e.getMessage(),e); } } - private void updateZones( Context ctx,List listWeb ,List listBD){ - List listDelete=new ArrayList<>(); - List listUpdate=new ArrayList<>(); - Map mapBD = convertMap(listBD); - Map mapWeb = convertMap(listWeb); - List removeList = new ArrayList(); - List listRemove = new ArrayList(); - List listAdd = new ArrayList(); - for(int i=0;listBD!=null&&i listWeb ,List listBD,GeofenceDataSource dataSource){ + try { + List listDelete=new ArrayList<>(); + List listUpdate=new ArrayList<>(); + Map mapBD = convertMap(listBD); + Map mapWeb = convertMap(listWeb); + List removeList = new ArrayList(); + List listRemove = new ArrayList(); + List listAdd = new ArrayList(); + for(int i=0;listBD!=null&&i0) { - LocationServices.getGeofencingClient(ctx).removeGeofences(listRemove); - } - if (removeList != null && removeList.size() > 0) { - String infoDelete = "["; - for (int i = 0; removeList != null && i < removeList.size(); i++) { - infoDelete += removeList.get(i); - if (i + 1 < removeList.size()) { - infoDelete += ","; + if(listRemove!=null&&listRemove.size()>0) { + LocationServices.getGeofencingClient(ctx).removeGeofences(listRemove); + } + if (removeList != null && removeList.size() > 0) { + String infoDelete = "["; + for (int i = 0; removeList != null && i < removeList.size(); i++) { + infoDelete += removeList.get(i); + if (i + 1 < removeList.size()) { + infoDelete += ","; + } } + infoDelete += "]"; + PreyLogger.d("GEO infoDelete:" + infoDelete); + sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "stopped", infoDelete)); } - infoDelete += "]"; - PreyLogger.d("infoDelete:" + infoDelete); - sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "stopped", infoDelete)); - } - - for(int i=0;listWeb!=null&&i0) { - sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "started", infoAdd)); - } - if(listWeb!=null&&listWeb.size()>0) { - initList(ctx, listWeb); + infoAdd += "]"; + if(listAdd!=null&&listAdd.size()>0) { + sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "started", infoAdd)); + } + List list=dataSource.getAllGeofences(); + if(list!=null&&list.size()>0) { + initList(ctx, list); + } + } catch (Exception e) { + PreyLogger.e("error run"+e.getMessage(),e); } } public void deleteAllZones(Context ctx){ + GeofenceDataSource dataSource = new GeofenceDataSource(ctx); listBD = dataSource.getAllGeofences(); for(int i=0;listBD!=null&&i convertMap(List list) { + if(list==null){ + return null; + } Map map = new HashMap(); for (int i = 0; list != null && i < list.size(); i++) { GeofenceDto geo = list.get(i); @@ -148,120 +155,116 @@ private Map convertMap(List list) { public void sendNotify(final Context ctx, final Map params) { new Thread() { public void run() { - PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, params); + try{ + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, params); + } catch (Exception e) { + } } }.start(); } - public void init(final Context ctx) { - PreyLogger.d("_GeofenceController__init"); - try { - GeofenceDataSource dataSource = new GeofenceDataSource(ctx); - List listBD = dataSource.getAllGeofences(); - initList(ctx,listBD); - } catch (Exception e) { + public void initList(Context ctx,List listBD) { + int loiteringDelay= FileConfigReader.getInstance(ctx).getGeofenceLoiteringDelay(); + List mGeofenceList = new ArrayList(); + final List listToBdAdd = new ArrayList(); + String info = "["; + for (int i = 0; listBD != null && i < listBD.size(); i++) { + GeofenceDto geo = listBD.get(i); + listToBdAdd.add(geo); + PreyLogger.d("GEO START id:" + geo.name + " lat:" + geo.latitude + " long:" + geo.longitude + " ra:" + geo.radius +" type:"+ geo.type+ " expires:" + geo.expires); + mGeofenceList.add(new com.google.android.gms.location.Geofence.Builder() + .setRequestId(geo.id) + .setCircularRegion(geo.latitude, geo.longitude, geo.radius) + .setExpirationDuration(Geofence.NEVER_EXPIRE) + .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER|Geofence.GEOFENCE_TRANSITION_EXIT) + .setLoiteringDelay(loiteringDelay) //30 seconds + .setNotificationResponsiveness(0) //0 seconds + .build()); + info += geo.id; + if (i + 1 < listBD.size()) { + info += ","; + } } - } + info += "]"; - public void initList(final Context ctx,List listBD) { - List mGeofenceList = new ArrayList(); - final List listToBdAdd = new ArrayList(); - String info = "["; - for (int i = 0; listBD != null && i < listBD.size(); i++) { - GeofenceDto geo = listBD.get(i); - listToBdAdd.add(geo); - PreyLogger.d("__[START]___________id:" + geo.name + " lat:" + geo.latitude + " long:" + geo.longitude + " ra:" + geo.radius + " expires:" + geo.expires); - int transitionTypes = com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_ENTER | - com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_DWELL | - com.google.android.gms.location.Geofence.GEOFENCE_TRANSITION_EXIT; - mGeofenceList.add(new com.google.android.gms.location.Geofence.Builder() - .setRequestId(geo.id) - .setCircularRegion(geo.latitude, geo.longitude, geo.radius) - .setExpirationDuration(Geofence.NEVER_EXPIRE) - .setTransitionTypes(transitionTypes) - .setLoiteringDelay(FileConfigReader.getInstance(ctx).getGeofenceLoiteringDelay()) - .build()); - info += geo.id; - if (i + 1 < listBD.size()) { - info += ","; - } - } - info += "]"; - final String extraInfo = info; - PreyLogger.d("info:" + extraInfo); - GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); - builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); - builder.addGeofences(mGeofenceList); - GeofencingRequest geofencingRequest = builder.build(); - try { - if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { - Intent intent = new Intent(ctx, GeofenceIntentService.class); - PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); - LocationServices.getGeofencingClient(ctx).addGeofences( - geofencingRequest, - pendingIntent - ) - .addOnSuccessListener(new OnSuccessListener() { + final String extraInfo = info; + PreyLogger.d("GEO info:" + extraInfo); + GeofencingRequest.Builder builderEnter = new GeofencingRequest.Builder(); + builderEnter.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER|GeofencingRequest.INITIAL_TRIGGER_EXIT); + builderEnter.addGeofences(mGeofenceList ); + GeofencingRequest geofencingRequest = builderEnter.build(); + final Context ctx2=ctx; + try { + if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + Intent intent = new Intent(ctx, GeofenceIntentService.class); + PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + LocationServices.getGeofencingClient(ctx).addGeofences(geofencingRequest,pendingIntent) + .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { - PreyLogger.d("********saveGeofence"); + PreyLogger.d("GEO saveGeofence"); } - }) - .addOnFailureListener(new OnFailureListener() { + }) + .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { - PreyLogger.d("*********************Registering geofence failed: " + e.getMessage()); - sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "failed", "status:" + e.getMessage())); + PreyLogger.d("GEO saveGeofence failed: " + e.getMessage()); + sendNotify(ctx2, UtilJson.makeMapParam("start", "geofencing", "failed", "status:" + e.getMessage())); } - }); - } - } catch (Exception e) { - PreyLogger.e("error ---->isConnected:" + e.getMessage(), e); - sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "failed", "error:" + e.getMessage())); - } + }); + }//if + } catch (Exception e) { + PreyLogger.e("GEO error:" + e.getMessage(), e); + sendNotify(ctx, UtilJson.makeMapParam("start", "geofencing", "failed", "error:" + e.getMessage())); + } } - public static void verifyGeozone(Context ctx,PreyLocation locationNow){ - PreyLogger.d("________________Connection verifyGeozone"); - GeofenceDataSource dataSource = new GeofenceDataSource(ctx); - List listBD = dataSource.getAllGeofences(); - for (int i = 0; listBD != null && i < listBD.size(); i++) { - GeofenceDto geo = listBD.get(i); - PreyLogger.d("________________geo id:"+geo.id+" type_:"+geo.getType()+" radi:"+geo.getRadius()); - int geofenceMaximumAccuracy=PreyConfig.getPreyConfig(ctx).getGeofenceMaximumAccuracy(); - PreyLogger.d("locationNow.getAccuracy:"+locationNow.getAccuracy() +" geofenceMaximumAccuracy:"+geofenceMaximumAccuracy); - if(locationNow.getAccuracy() < geofenceMaximumAccuracy) { - PreyLocation locationGeo=geo.getPreyLocation(); - double distance=AwareService.distance(locationNow,locationGeo); - String transition=""; - PreyLogger.d("________________geo id:"+geo.id+" distance:"+distance); - if (distance > geo.getRadius()) { - transition = GeofenceIntentService.GEOFENCING_OUT; - } else { - transition = GeofenceIntentService.GEOFENCING_IN; + public synchronized static void verifyGeozone(Context ctx,PreyLocation locationNow){ + PreyLogger.d("GEO connection verifyGeozone"); + try{ + if(locationNow!=null) { + GeofenceDataSource dataSource = new GeofenceDataSource(ctx); + List listBD = dataSource.getAllGeofences(); + PreyLogger.d("GEO listBD size:" + (listBD == null ? 0 : listBD.size())); + int maximumAccuracy = PreyConfig.getPreyConfig(ctx).getGeofenceMaximumAccuracy(); + for (int i = 0; listBD != null && i < listBD.size(); i++) { + GeofenceDto geo = listBD.get(i); + validateGeozone(ctx, geo, maximumAccuracy, locationNow, dataSource); } - PreyLogger.d("________________geo id:"+geo.id+" newEventGeo:" + transition+" type:"+geo.getType()); - if (!transition.equals(geo.getType())) { - if(GeofenceIntentService.GEOFENCING_IN.equals(transition)||(GeofenceIntentService.GEOFENCING_OUT.equals(transition) && geo.getType()!=null)) { - try { - JSONObject info = new JSONObject(); - info.put("id", "" + geo.id); - info.put("lat", locationNow.getLat()); - info.put("lng", locationNow.getLng()); - info.put("accuracy", locationNow.getAccuracy()); - info.put("method", locationNow.getMethod()); - Event event = new Event(); - event.setName(transition); - event.setInfo(info.toString()); - JSONObject jsonObjectStatus = new JSONObject(); - dataSource.updateGeofenceType(geo.id, transition); - PreyLogger.d("________________geo id:"+geo.id+" event:" + transition.toString()); - new EventThread(ctx, event, jsonObjectStatus, transition).start(); - } catch (Exception e) { - PreyLogger.e("error:" + e.getMessage(), e); - } - }else{ - dataSource.updateGeofenceType(geo.id, transition); + } + } catch (Exception e) { + } + } + + public static void validateGeozone(Context ctx,GeofenceDto geo,int maximumAccuracy,PreyLocation locationNow,GeofenceDataSource dataSource){ + if(locationNow!=null&&locationNow.getAccuracy() < maximumAccuracy) { + PreyLocation locationGeo = geo.getPreyLocation(); + double distance = LocationUtil.distance(locationNow,locationGeo); + String transition=""; + if (distance > geo.getRadius()) { + transition = GEOFENCING_OUT; + } else { + transition = GEOFENCING_IN; + } + dataSource.updateGeofenceType(geo.id, transition); + PreyLogger.d("GEO validateGeozone name:"+geo.name+" type:"+geo.getType()+" transition:" + transition); + if (!transition.equals(geo.getType())) { + if(GEOFENCING_IN.equals(transition)||(GEOFENCING_OUT.equals(transition) && geo.getType()!=null)) { + try { + JSONObject info = new JSONObject(); + info.put("id", "" + geo.id); + info.put("lat", locationNow.getLat()); + info.put("lng", locationNow.getLng()); + info.put("accuracy", locationNow.getAccuracy()); + info.put("method", locationNow.getMethod()); + Event event = new Event(); + event.setName(transition); + event.setInfo(info.toString()); + JSONObject jsonObjectStatus = new JSONObject(); + PreyLogger.d("GEO name:"+geo.name+" event:" + transition.toString()); + new EventThread(ctx, event, jsonObjectStatus, transition).start(); + } catch (Exception e) { + PreyLogger.e("GEO error:" + e.getMessage(), e); } } } diff --git a/app/src/main/java/com/prey/actions/geofences/GeofenceDataSource.java b/app/src/main/java/com/prey/actions/geofences/GeofenceDataSource.java index 4534a31d..b1ca2cba 100644 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceDataSource.java +++ b/app/src/main/java/com/prey/actions/geofences/GeofenceDataSource.java @@ -27,7 +27,7 @@ public void createGeofence(GeofenceDto geofence) { try { dbHelper.updateGeofence(geofence); } catch (Exception e1) { - PreyLogger.e("error db update:" + e1.getMessage(), e1); + PreyLogger.e("GEO error db update:" + e1.getMessage(), e1); } } } diff --git a/app/src/main/java/com/prey/actions/geofences/GeofenceErrorMessages.java b/app/src/main/java/com/prey/actions/geofences/GeofenceErrorMessages.java deleted file mode 100644 index a9edaef7..00000000 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceErrorMessages.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Created by Orlando Aliaga - * Copyright 2015 Prey Inc. All rights reserved. - * License: GPLv3 - * Full license at "/LICENSE" - ******************************************************************************/ -package com.prey.actions.geofences; - -import android.content.Context; -import android.content.res.Resources; - -import com.google.android.gms.location.GeofenceStatusCodes; -import com.prey.R; - -public class GeofenceErrorMessages { - - private GeofenceErrorMessages() { - } - - public static String getErrorString(Context context, int errorCode) { - Resources mResources = context.getResources(); - switch (errorCode) { - case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE: - return mResources.getString(R.string.geofence_not_available); - case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES: - return mResources.getString(R.string.geofence_too_many_geofences); - case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS: - return mResources.getString(R.string.geofence_too_many_pending_intents); - default: - return mResources.getString(R.string.unknown_geofence_error); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/geofences/GeofenceIntentService.java b/app/src/main/java/com/prey/actions/geofences/GeofenceIntentService.java index 19842c39..d8242ed5 100644 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceIntentService.java +++ b/app/src/main/java/com/prey/actions/geofences/GeofenceIntentService.java @@ -7,27 +7,17 @@ package com.prey.actions.geofences; import android.app.IntentService; -import android.app.Notification; -import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.location.Location; -import android.support.v4.app.NotificationCompat; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingEvent; + import com.prey.PreyConfig; import com.prey.PreyLogger; -import com.prey.R; -import com.prey.actions.HttpDataService; -import com.prey.actions.location.LocationUtil; import com.prey.actions.location.PreyLocation; -import com.prey.events.Event; -import com.prey.events.manager.EventThread; - -import org.json.JSONObject; -import java.util.ArrayList; import java.util.List; public class GeofenceIntentService extends IntentService { @@ -38,121 +28,29 @@ public GeofenceIntentService() { @Override protected void onHandleIntent(Intent intent) { - - GeofencingEvent event = GeofencingEvent.fromIntent(intent); - if (event != null) { - if (event.hasError()) { - onError(event.getErrorCode()); - } else { - int transition = event.getGeofenceTransition(); - event.getTriggeringLocation().getLongitude(); - event.getTriggeringLocation().getLatitude(); - event.getTriggeringLocation().getAccuracy(); - - - - if (transition == Geofence.GEOFENCE_TRANSITION_ENTER || transition == Geofence.GEOFENCE_TRANSITION_DWELL || transition == Geofence.GEOFENCE_TRANSITION_EXIT) { - List geofenceIds = new ArrayList<>(); - List triggeringGeofences = event.getTriggeringGeofences(); - notifyGeofenceTransition(getApplicationContext(), transition, triggeringGeofences, event.getTriggeringLocation()); - } - } - } - } - - public static final String GEOFENCING_OUT="geofencing_out"; - public static final String GEOFENCING_IN="geofencing_in"; - - private void notifyGeofenceTransition( - Context context, - int geofenceTransition, - List triggeringGeofences, Location location) { - PreyLogger.d("notifyGeofenceTransition lat:"+location.getLatitude()+" lng:"+location.getLongitude()+" acc:"+location.getAccuracy()); try { - for (Geofence geofence : triggeringGeofences) { - String requestId = geofence.getRequestId(); - PreyLogger.d("geofence.getRequestId():" + requestId); - Event event = new Event(); - String transition = ""; - if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { - transition = GEOFENCING_IN; + PreyLogger.d("GEO GeofenceIntentService"); + GeofencingEvent event = GeofencingEvent.fromIntent(intent); + if (event != null) { + if (event.hasError()) { + PreyLogger.d("GEO GeofenceIntentService hasError:" +event.toString()); } else { - transition = GEOFENCING_OUT; - } - event.setName(transition); - String newEventGeo=transition+"_"+requestId; - PreyLogger.d("event:"+transition); - GeofenceDataSource dataSource = new GeofenceDataSource(context); - GeofenceDto geo = dataSource.getGeofences(requestId); - int geofenceMaximumAccuracy=PreyConfig.getPreyConfig(context).getGeofenceMaximumAccuracy(); - PreyLogger.d("geofenceMaximumAccuracy:"+geofenceMaximumAccuracy); - if (!transition.equals(geo.getType())){ - int i=0; - PreyLocation locationNow =null; - do { - locationNow = LocationUtil.getLocation(context,null,false); - if(locationNow!=null) { - PreyLogger.d("locationNow lat:" + locationNow.getLat() + " lng:" + locationNow.getLng() + " acc:" + locationNow.getAccuracy()); - } - Thread.sleep(1000); - i=i+1; - }while (i<10 &&locationNow.getAccuracy() > geofenceMaximumAccuracy); - if(locationNow.getAccuracy() > geofenceMaximumAccuracy){ - locationNow=null; - } - JSONObject jsonObjectStatus = new JSONObject(); - if(locationNow!=null) { - double distance = distance(geo, locationNow); - PreyLogger.d("geofenceMaximumAccuracy distance:" + distance + " geo.getRadius()" + geo.getRadius()+" type:" + geo.getType()); - if (GEOFENCING_IN.equals(transition)) { - if (distance >= geo.getRadius()) { - PreyLogger.d("geofenceMaximumAccuracy distance is greater "); - } else { - JSONObject info = new JSONObject(); - info.put("id", Integer.parseInt(requestId)); - info.put("lat", locationNow.getLat()); - info.put("lng", locationNow.getLng()); - info.put("accuracy", locationNow.getAccuracy()); - info.put("method", locationNow.getMethod()); - event.setInfo(info.toString()); - dataSource.updateGeofenceType(geo.id,transition); - new EventThread(this, event, jsonObjectStatus, newEventGeo).start(); - } - } else { - if (distance <= geo.getRadius()) { - PreyLogger.d("geofenceMaximumAccuracy distance is less "); - } else { - JSONObject info = new JSONObject(); - info.put("id", Integer.parseInt(requestId)); - info.put("lat", locationNow.getLat()); - info.put("lng", locationNow.getLng()); - info.put("accuracy", locationNow.getAccuracy()); - info.put("method", locationNow.getMethod()); - event.setInfo(info.toString()); - dataSource.updateGeofenceType(geo.id,transition); - new EventThread(this, event, jsonObjectStatus, newEventGeo).start(); - } - } - } + notifyGeofenceTransition(getApplicationContext(), event.getGeofenceTransition(), event.getTriggeringGeofences(), event.getTriggeringLocation()); } } } catch (Exception e) { - PreyLogger.e("notifyGeofenceTransition error:" + e.getMessage(), e); + PreyLogger.e("GEO GeofenceIntentService error:" + e.getMessage(), e); } + stopSelf(); } - private void onError(int i) { - PreyLogger.d("***************Geofencing Error: " + i); - } - - private double distance( GeofenceDto start,PreyLocation end){ - Location locStart = new Location(""); - locStart.setLatitude(start.getLatitude()); - locStart.setLongitude(start.getLongitude()); - Location locEnd = new Location(""); - locEnd.setLatitude(end.getLat()); - locEnd.setLongitude(end.getLng()); - return Math.round(locStart.distanceTo(locEnd)); + private void notifyGeofenceTransition(Context context, int geofenceTransition, List triggeringGeofences, Location location) { + PreyLocation locationNow=null; + try{ + locationNow=new PreyLocation(location); + }catch (Exception e){ + } + GeofenceController.verifyGeozone(context,locationNow); } } \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java b/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java index 2b89b265..9e0103d6 100644 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java +++ b/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java @@ -91,7 +91,7 @@ public void updateGeofence(GeofenceDto geofence) { values.put(COLUMN_EXPIRES, geofence.getExpires()); String selection = COLUMN_ID + " = ?"; String[] selectionArgs = {geofence.getId()}; - PreyLogger.d("___db update:" + geofence.toString()); + //PreyLogger.d("___db update:" + geofence.toString()); database.update(GEOFENCE_TABLE_NAME, values, selection, selectionArgs); database.close(); } @@ -102,7 +102,7 @@ public void updateGeofenceType(String id,String type) { values.put(COLUMN_TYPE,type); String selection = COLUMN_ID + " = ?"; String[] selectionArgs = {id}; - PreyLogger.d("___db update type:"+type+" id:" + id); + //PreyLogger.d("___db update type:"+type+" id:" + id); database.update(GEOFENCE_TABLE_NAME, values, selection, selectionArgs); database.close(); } @@ -111,7 +111,7 @@ public void updateGeofenceType(String id,String type) { public void deleteGeofence(String id) { SQLiteDatabase database = this.getWritableDatabase(); String deleteQuery = "DELETE FROM " + GEOFENCE_TABLE_NAME + " where " + COLUMN_ID + "='" + id + "'"; - PreyLogger.d("query" + deleteQuery); + //PreyLogger.d("query" + deleteQuery); database.execSQL(deleteQuery); database.close(); } @@ -119,7 +119,7 @@ public void deleteGeofence(String id) { public void deleteAllGeofence() { SQLiteDatabase database = this.getWritableDatabase(); String deleteQuery = "DELETE FROM " + GEOFENCE_TABLE_NAME ; - PreyLogger.d("query" + deleteQuery); + //PreyLogger.d("query" + deleteQuery); database.execSQL(deleteQuery); database.close(); } @@ -161,7 +161,6 @@ public GeofenceDto getGeofence(String id) { SQLiteDatabase database = this.getReadableDatabase(); String selectQuery = "SELECT * FROM " + GEOFENCE_TABLE_NAME + " where " + COLUMN_ID + "='" + id + "'"; cursor = database.rawQuery(selectQuery, null); - if (cursor.moveToFirst()) { do { geofence = new GeofenceDto(); diff --git a/app/src/main/java/com/prey/actions/location/LocationUtil.java b/app/src/main/java/com/prey/actions/location/LocationUtil.java index ca824840..6a557657 100644 --- a/app/src/main/java/com/prey/actions/location/LocationUtil.java +++ b/app/src/main/java/com/prey/actions/location/LocationUtil.java @@ -8,7 +8,6 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import android.Manifest; @@ -23,8 +22,6 @@ import com.google.android.gms.common.GooglePlayServicesUtil; import com.prey.PreyConfig; import com.prey.PreyLogger; -import com.prey.PreyPhone; -import com.prey.PreyPhone.Wifi; import com.prey.actions.HttpDataService; import com.prey.actions.geofences.GeofenceController; import com.prey.json.UtilJson; @@ -39,14 +36,18 @@ public class LocationUtil { public static final String ACC = "accuracy"; public static final String METHOD = "method"; - public static HttpDataService dataLocation(Context ctx, String messageId, boolean asynchronous) { + public static HttpDataService dataLocation(final Context ctx, String messageId, boolean asynchronous) { HttpDataService data = null; try { - PreyLocation preyLocation = getLocation(ctx,messageId,asynchronous); + final PreyLocation preyLocation = getLocation(ctx,messageId,asynchronous); if (preyLocation != null) { PreyLogger.d("locationData:" + preyLocation.getLat() + " " + preyLocation.getLng() + " " + preyLocation.getAccuracy()); data = convertData(preyLocation); - GeofenceController.verifyGeozone(ctx, preyLocation); + new Thread() { + public void run() { + GeofenceController.verifyGeozone(ctx, preyLocation); + } + }.start(); }else{ return null; } @@ -139,7 +140,7 @@ public void run() { if (currentLocation != null) { //PreyLogger.d("getPreyLocationPlayService["+i+"]:"+currentLocation.toString()); preyLocation = new PreyLocation(currentLocation, method); - preyLocationOld = sendLocation(ctx, asynchronous, preyLocationOld, preyLocation); + //preyLocationOld = sendLocation(ctx, asynchronous, preyLocationOld, preyLocation); if(!asynchronous) i=MAXIMUM_OF_ATTEMPTS; } @@ -149,7 +150,8 @@ public void run() { PreyLogger.d("Error getPreyLocationPlayService:"+e.getMessage()); throw e; } finally { - play.stopLocationUpdates(); + if(play!=null) + play.stopLocationUpdates(); } return preyLocation; } @@ -170,7 +172,7 @@ private static PreyLocation getPreyLocationAppService(final Context ctx, String preyLocation=location; preyLocation.setMethod(method); PreyLogger.d("getPreyLocationAppService["+i+"]:"+preyLocation.toString()); - preyLocationOld = sendLocation(ctx, asynchronous, preyLocationOld, preyLocation); + //preyLocationOld = sendLocation(ctx, asynchronous, preyLocationOld, preyLocation); if(!asynchronous) i=MAXIMUM_OF_ATTEMPTS; } @@ -203,7 +205,7 @@ private static PreyLocation sendLocation(Context ctx,boolean asynchronous, PreyL } } - private static double distance(PreyLocation locationOld, PreyLocation locationNew){ + public static double distance(PreyLocation locationOld, PreyLocation locationNew){ if(locationOld!=null&&locationNew!=null) { Location locStart = new Location(""); locStart.setLatitude(locationNew.getLat()); diff --git a/app/src/main/java/com/prey/actions/location/PreyGooglePlayServiceLocation.java b/app/src/main/java/com/prey/actions/location/PreyGooglePlayServiceLocation.java index 733b86a5..5c73bf71 100644 --- a/app/src/main/java/com/prey/actions/location/PreyGooglePlayServiceLocation.java +++ b/app/src/main/java/com/prey/actions/location/PreyGooglePlayServiceLocation.java @@ -106,7 +106,7 @@ public void onLocationChanged(Location location) { mCurrentLocation = location; if (location != null) { mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); - PreyLogger.d("latitude:" + location.getLatitude() + " longitude:" + location.getLongitude() + " accuracy:" + location.getAccuracy()); + //PreyLogger.d("latitude:" + location.getLatitude() + " longitude:" + location.getLongitude() + " accuracy:" + location.getAccuracy()); stopLocationUpdates(); } diff --git a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java index 42c48fb5..2f779b6e 100644 --- a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java +++ b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java @@ -46,19 +46,6 @@ protected void onCreate(Bundle savedInstanceState) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.webview); PreyLogger.d("CheckPasswordHtmlActivity: onCreate"); - new Thread() { - public void run() { - String email= PreyWebServices.getInstance().getEmail(getApplicationContext()); - PreyConfig.getPreyConfig(getApplicationContext()).setEmail(email); - try { - boolean twoStep = PreyWebServices.getInstance().getTwoStepEnabled(getApplicationContext()); - PreyConfig.getPreyConfig(getApplicationContext()).setTwoStep(twoStep); - }catch(Exception e){ - PreyConfig.getPreyConfig(getApplicationContext()).setTwoStep(false); - } - - } - }.start(); loadUrl(); } diff --git a/app/src/main/java/com/prey/activities/SignInActivity.java b/app/src/main/java/com/prey/activities/SignInActivity.java index b2b2c8fd..c69c6ecb 100644 --- a/app/src/main/java/com/prey/activities/SignInActivity.java +++ b/app/src/main/java/com/prey/activities/SignInActivity.java @@ -33,6 +33,7 @@ import com.appsflyer.AFInAppEventType; import com.appsflyer.AppsFlyerLib; import com.prey.actions.aware.AwareConfig; +import com.prey.actions.aware.AwareController; import com.prey.barcodereader.BarcodeActivity; import com.prey.PreyAccountData; import com.prey.PreyConfig; @@ -297,7 +298,7 @@ protected Void doInBackground(String... data) { PreyConfig.getPreyConfig(getApplicationContext()).setEmail(email); new Thread() { public void run() { - AwareConfig.getAwareConfig(getApplicationContext()).init(); + AwareController.getInstance().init(getApplicationContext()); } }.start(); try { diff --git a/app/src/main/java/com/prey/activities/SignUpActivity.java b/app/src/main/java/com/prey/activities/SignUpActivity.java index 9a1b1817..7be5a2a7 100644 --- a/app/src/main/java/com/prey/activities/SignUpActivity.java +++ b/app/src/main/java/com/prey/activities/SignUpActivity.java @@ -19,6 +19,7 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; +import android.support.constraint.ConstraintLayout; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; @@ -42,6 +43,7 @@ import com.prey.PreyUtils; import com.prey.R; import com.prey.actions.aware.AwareConfig; +import com.prey.actions.aware.AwareController; import com.prey.exceptions.PreyException; import com.prey.net.PreyWebServices; import com.prey.util.KeyboardStatusDetector; @@ -170,7 +172,7 @@ public void onVisibilityChanged(boolean keyboardVisible) { try { - RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linkSignup.getLayoutParams(); + ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) linkSignup.getLayoutParams(); if (keyboardVisible) { PreyLogger.d("key on"); @@ -269,7 +271,7 @@ protected Void doInBackground(String... data) { PreyConfig.getPreyConfig(getApplicationContext()).setEmail(email); new Thread() { public void run() { - AwareConfig.getAwareConfig(getApplicationContext()).init(); + AwareController.getInstance().init(getApplicationContext()); } }.start(); try { diff --git a/app/src/main/java/com/prey/activities/WelcomeActivity.java b/app/src/main/java/com/prey/activities/WelcomeActivity.java index 0673af9b..0849ebfa 100644 --- a/app/src/main/java/com/prey/activities/WelcomeActivity.java +++ b/app/src/main/java/com/prey/activities/WelcomeActivity.java @@ -72,20 +72,13 @@ public void menu() { public void ready() { PreyLogger.d("ready WelcomeActivity"); PreyVerify.getInstance(this); - - Intent intent = null; - - intent = new Intent(getApplicationContext(), CheckPasswordHtmlActivity.class); - + Intent intent = new Intent(getApplicationContext(), CheckPasswordHtmlActivity.class); startActivity(intent); finish(); } - - private static final int SECURITY_PRIVILEGES = 10; - @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { PreyLogger.d("requestCode:" + requestCode + " resultCode:" + resultCode); diff --git a/app/src/main/java/com/prey/barcodereader/BarcodeActivity.java b/app/src/main/java/com/prey/barcodereader/BarcodeActivity.java index 1d7677bf..bafdb5c5 100755 --- a/app/src/main/java/com/prey/barcodereader/BarcodeActivity.java +++ b/app/src/main/java/com/prey/barcodereader/BarcodeActivity.java @@ -28,6 +28,7 @@ import com.prey.PreyLogger; import com.prey.PreyUtils; import com.prey.R; +import com.prey.actions.aware.AwareController; import com.prey.activities.PermissionInformationActivity; import com.prey.activities.SignInActivity; import com.prey.net.PreyWebServices; @@ -98,20 +99,26 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { statusMessage.setText(R.string.barcode_success); PreyLogger.d("Barcode read: " + barcode.displayValue); String barcodeValue = barcode.displayValue; - + String apikey = ""; + String mail = "batch@preyproject.com"; if (barcodeValue.indexOf("prey") >= 0) { barcodeValue = barcodeValue.substring(5); - String[] pairs = barcodeValue.split("&"); - String apikey = ""; - String mail = "batch@preyproject.com"; - for (String pair : pairs) { - String[] llave = pair.split("="); + if(barcodeValue.indexOf("&")>=0){ + String[] pairs = barcodeValue.split("&"); + for (String pair : pairs) { + String[] llave = pair.split("="); + PreyLogger.d("key[" + llave[0] + "]" + llave[1]); + if (llave[0].equals("api_key")) { + apikey = llave[1]; + } + } + }else{ + String[] llave = barcodeValue.split("="); PreyLogger.d("key[" + llave[0] + "]" + llave[1]); if (llave[0].equals("api_key")) { apikey = llave[1]; } - } if (!"".equals(apikey)) { new AddDeviceToApiKeyBatch().execute(apikey, mail, PreyUtils.getDeviceType(this)); @@ -157,12 +164,10 @@ protected void onPreExecute() { @Override protected Void doInBackground(String... data) { + error = null; try { - error = null; Context ctx = getApplicationContext(); - PreyLogger.d("apikey:" + data[0] + " mail:" + data[1] + " device:" + data[2]); - if(!PreyConfig.getPreyConfig(ctx).isThisDeviceAlreadyRegisteredWithPrey()) { PreyAccountData accountData = PreyWebServices.getInstance().registerNewDeviceWithApiKeyEmail(ctx, data[0], data[1], data[2]); if (accountData != null) { @@ -172,10 +177,15 @@ protected Void doInBackground(String... data) { PreyWebServices.getInstance().sendEvent(getApplication(), PreyConfig.ANDROID_SIGN_IN); String email=PreyWebServices.getInstance().getEmail(getApplicationContext()); PreyConfig.getPreyConfig(getApplicationContext()).setEmail(email); + new Thread() { + public void run() { + AwareController.getInstance().init(getApplicationContext()); + } + }.start(); } } - } catch (Exception e) { + PreyLogger.e("error:"+e.getMessage(),e); error = e.getMessage(); } return null; diff --git a/app/src/main/java/com/prey/beta/actions/PreyBetaActionsRunner.java b/app/src/main/java/com/prey/beta/actions/PreyBetaActionsRunner.java index 80e854f5..7e32a13f 100644 --- a/app/src/main/java/com/prey/beta/actions/PreyBetaActionsRunner.java +++ b/app/src/main/java/com/prey/beta/actions/PreyBetaActionsRunner.java @@ -85,6 +85,7 @@ public void run() { PreyLogger.d("_________New Thread"); PreyBetaActionsRunner.getInstructions(context); } catch (PreyException e) { + PreyLogger.e("_________getInstructionsNewThread:"+e.getMessage(),e); } } }).start(); diff --git a/app/src/main/java/com/prey/events/factories/EventFactory.java b/app/src/main/java/com/prey/events/factories/EventFactory.java index 704e8abf..fabe68f4 100644 --- a/app/src/main/java/com/prey/events/factories/EventFactory.java +++ b/app/src/main/java/com/prey/events/factories/EventFactory.java @@ -28,6 +28,7 @@ import com.prey.PreyLogger; import com.prey.PreyPermission; import com.prey.R; +import com.prey.actions.aware.AwareController; import com.prey.actions.fileretrieval.FileretrievalController; import com.prey.activities.CheckPasswordHtmlActivity; import com.prey.beta.actions.PreyBetaController; @@ -45,6 +46,7 @@ public class EventFactory { private static final String AIRPLANE_MODE = "android.intent.action.AIRPLANE_MODE"; private static final String BATTERY_LOW = "android.intent.action.BATTERY_LOW"; private static final String SIM_STATE_CHANGED = "android.intent.action.SIM_STATE_CHANGED"; + private static final String USER_PRESENT = "android.intent.action.USER_PRESENT"; public static Event getEvent(final Context ctx, Intent intent) { String message = "getEvent[" + intent.getAction() + "]"; @@ -125,6 +127,7 @@ public void run() { } } catch (Exception e) { } + return new Event(Event.WIFI_CHANGED, info.toString()); } if (WIFI_STATE_CHANGED.equals(intent.getAction())) { @@ -186,9 +189,26 @@ public void run() { } } } + if(USER_PRESENT.equals(intent.getAction())){ + String awareDate=PreyConfig.getPreyConfig(ctx).getAwareDate(); + String now=PreyConfig.FORMAT_SDF_AWARE.format(new Date()); + PreyLogger.d("AWARE USER_PRESENT awareDate:"+awareDate+" now:"+now); + if(!now.equals(awareDate)) { + PreyLogger.d("AWARE getSendNowAware: "+now); + new Thread() { + public void run() { + try{ + AwareController.getSendNowAware(ctx); + } catch (Exception e) {} + } + }.start(); + } + } return null; } + + public static boolean isAirplaneModeOn(Context context) { return Settings.System.getInt(context.getContentResolver (), Settings.System.AIRPLANE_MODE_ON, 0) != 0; diff --git a/app/src/main/java/com/prey/json/actions/Detach.java b/app/src/main/java/com/prey/json/actions/Detach.java index b711b872..c44f1f93 100644 --- a/app/src/main/java/com/prey/json/actions/Detach.java +++ b/app/src/main/java/com/prey/json/actions/Detach.java @@ -7,14 +7,17 @@ package com.prey.json.actions; import android.content.Context; +import android.content.Intent; import com.prey.PreyConfig; import com.prey.PreyLogger; -import com.prey.actions.aware.AwareScheduled; +import com.prey.actions.aware.AwareConfig; import com.prey.actions.fileretrieval.FileretrievalController; import com.prey.actions.geofences.GeofenceController; import com.prey.actions.observer.ActionResult; import com.prey.actions.report.ReportScheduled; +import com.prey.activities.LoginActivity; +import com.prey.activities.WelcomeBatchActivity; import com.prey.backwardcompatibility.FroyoSupport; import com.prey.net.PreyWebServices; @@ -49,6 +52,9 @@ public static String detachDevice(Context ctx){ } } catch (Exception e) {} PreyLogger.d("3:"+error); + try { + AwareConfig.getAwareConfig(ctx).setLocationAware(false); + } catch (Exception e) {} try { GeofenceController.getInstance().deleteAllZones(ctx); } catch (Exception e) {} @@ -58,7 +64,6 @@ public static String detachDevice(Context ctx){ } catch (Exception e) {} PreyLogger.d("5:"+error); try { ReportScheduled.getInstance(ctx).reset();} catch (Exception e) {error += e.getMessage();} - try { AwareScheduled.getInstance(ctx).reset();} catch (Exception e) {error += e.getMessage();} try { PreyWebServices.getInstance().deleteDevice(ctx);} catch (Exception e) { } PreyLogger.d("6:"+error); try { PreyConfig.getPreyConfig(ctx).wipeData();} catch (Exception e) {error += e.getMessage();} @@ -70,6 +75,17 @@ public static String detachDevice(Context ctx){ try { PreyConfig.getPreyConfig(ctx).setDeviceId("");} catch (Exception e) {error = e.getMessage();} try { PreyConfig.getPreyConfig(ctx).setApiKey("");} catch (Exception e) {error = e.getMessage();} PreyLogger.d("8:"+error); + + PreyLogger.d("Email:"+PreyConfig.getPreyConfig(ctx).getEmail()); + PreyLogger.d("DeviceId:"+PreyConfig.getPreyConfig(ctx).getDeviceId()); + PreyLogger.d("ApiKey:"+PreyConfig.getPreyConfig(ctx).getApiKey()); + try {PreyConfig.deleteCacheInstance(ctx);} catch (Exception e) {} + try { + Intent intent = new Intent(ctx, LoginActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | + Intent.FLAG_ACTIVITY_CLEAR_TASK); + ctx.startActivity(intent); + } catch (Exception e) {} return error; } } diff --git a/app/src/main/java/com/prey/json/actions/Location.java b/app/src/main/java/com/prey/json/actions/Location.java index 47f9f169..80eb0b3c 100644 --- a/app/src/main/java/com/prey/json/actions/Location.java +++ b/app/src/main/java/com/prey/json/actions/Location.java @@ -17,6 +17,7 @@ import com.prey.PreyLogger; import com.prey.actions.HttpDataService; import com.prey.actions.aware.AwareConfig; +import com.prey.actions.aware.AwareController; import com.prey.actions.location.LocationThread; import com.prey.actions.location.LocationUtil; import com.prey.actions.observer.ActionResult; @@ -90,8 +91,8 @@ public void sms(Context ctx, List list, JSONObject parameters) { } public List start_location_aware(Context ctx, List list, JSONObject parameters) { - PreyLogger.d("_________start_location_aware:"); - AwareConfig.getAwareConfig(ctx).startAware(); + PreyLogger.d("AWARE start_location_aware:"); + AwareController.getInstance().init(ctx); return null; } diff --git a/app/src/main/java/com/prey/json/actions/Report.java b/app/src/main/java/com/prey/json/actions/Report.java index 535e6e53..050a7bfe 100644 --- a/app/src/main/java/com/prey/json/actions/Report.java +++ b/app/src/main/java/com/prey/json/actions/Report.java @@ -13,14 +13,11 @@ import org.json.JSONObject; import android.content.Context; -import android.content.Intent; -import android.widget.Toast; import com.prey.PreyConfig; import com.prey.PreyLogger; import com.prey.actions.observer.ActionResult; import com.prey.actions.report.ReportScheduled; -import com.prey.actions.report.ReportService; public class Report { diff --git a/app/src/main/java/com/prey/net/PreyWebServices.java b/app/src/main/java/com/prey/net/PreyWebServices.java index 112b7156..0c0e848c 100644 --- a/app/src/main/java/com/prey/net/PreyWebServices.java +++ b/app/src/main/java/com/prey/net/PreyWebServices.java @@ -822,15 +822,10 @@ public JSONObject getStatus(Context ctx) throws PreyException { public void sendEvent(final Context ctx,final int id ) { new Thread() { public void run() { - - PreyPhone phone=new PreyPhone(ctx); String serialNumber=phone.getHardware().getSerialNumber(); - String version=PreyConfig.getPreyConfig(ctx).getPreyVersion(); String sid=PreyConfig.getPreyConfig(ctx).getSessionId(); - - String time = "" + new Date().getTime(); try { String page = FileConfigReader.getInstance(ctx).getPreyEventsLogs();; PreyLogger.d("URL:"+page); diff --git a/app/src/main/java/com/prey/net/UtilConnection.java b/app/src/main/java/com/prey/net/UtilConnection.java index aa471146..63bbf5c1 100644 --- a/app/src/main/java/com/prey/net/UtilConnection.java +++ b/app/src/main/java/com/prey/net/UtilConnection.java @@ -69,7 +69,7 @@ private static String getUserAgent(PreyConfig preyConfig) { return "Prey/".concat(preyConfig.getPreyVersion()).concat(" (Android " + PreyUtils.getBuildVersionRelease() + ")"); } - private static String getAuthorization(PreyConfig preyConfig) { + public static String getAuthorization(PreyConfig preyConfig) { //PreyLogger.d("getAuthorization:("+preyConfig.getApiKey()+",X)"); return "Basic " + getCredentials(preyConfig.getApiKey(), "X"); } @@ -119,7 +119,6 @@ public static final PreyHttpResponse connection(PreyConfig preyConfig,String uri HttpURLConnection connection=null; int retry = 0; boolean delay=false; - PreyLogger.d("uri:"+uri); if(params!=null){ Iterator ite=params.keySet().iterator(); while (ite.hasNext()){ @@ -163,11 +162,10 @@ public static final PreyHttpResponse connection(PreyConfig preyConfig,String uri PreyLogger.d("X-Prey-Device-ID:"+deviceId); connection.addRequestProperty("X-Prey-State", status); PreyLogger.d("X-Prey-State:"+status); - } - connection.addRequestProperty("User-Agent", getUserAgent(preyConfig)); + PreyLogger.d("User-Agent:"+getUserAgent(preyConfig)); if (entityFiles==null&&(params!=null&¶ms.size()>0)){ OutputStream os = connection.getOutputStream(); DataOutputStream dos = new DataOutputStream( os ); @@ -341,7 +339,7 @@ private static void saveFile(String idFile,ByteArrayOutputStream outputStream){ } } - private static PreyHttpResponse convertPreyHttpResponse(int responseCode,HttpURLConnection connection)throws Exception { + public static PreyHttpResponse convertPreyHttpResponse(int responseCode,HttpURLConnection connection)throws Exception { StringBuffer sb = new StringBuffer(); if(responseCode==200||responseCode==201||responseCode==422) { InputStream input = null; diff --git a/app/src/main/java/com/prey/receivers/PreyBootController.java b/app/src/main/java/com/prey/receivers/PreyBootController.java index 453103f1..92212406 100644 --- a/app/src/main/java/com/prey/receivers/PreyBootController.java +++ b/app/src/main/java/com/prey/receivers/PreyBootController.java @@ -30,11 +30,6 @@ public void onReceive(Context context, Intent intent) { Report.run(context, Integer.parseInt(interval)); } final Context ctx = context; - new Thread() { - public void run() { - AwareConfig.getAwareConfig(ctx).init(); - } - }.start(); new Thread() { public void run() { try { diff --git a/app/src/main/java/com/prey/services/MyFirebaseMessagingService.java b/app/src/main/java/com/prey/services/MyFirebaseMessagingService.java index c2c48550..17818078 100644 --- a/app/src/main/java/com/prey/services/MyFirebaseMessagingService.java +++ b/app/src/main/java/com/prey/services/MyFirebaseMessagingService.java @@ -6,24 +6,37 @@ ******************************************************************************/ package com.prey.services; -import com.firebase.jobdispatcher.FirebaseJobDispatcher; -import com.firebase.jobdispatcher.GooglePlayDriver; -import com.firebase.jobdispatcher.Job; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; + import com.prey.PreyLogger; import com.prey.beta.actions.PreyBetaController; -import org.json.JSONArray; -import org.json.JSONObject; - public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { - PreyLogger.d("MyFirebaseMessagingService onMessageReceived" ); + PreyLogger.d("FIREBASE onMessageReceived" ); if (remoteMessage.getData().size() > 0) { - PreyBetaController.startPrey(this,null); + final String text= remoteMessage.getData().toString(); + PreyLogger.d("FIREBASE data:"+text); + String cmd=null; + try { + cmd = remoteMessage.getData().get("cmd"); + } catch (Exception e) { + cmd = null; + } + /* + cmd="{\"command\":\"start\",\"target\":\"alert\",\"options\":{\"alert_message\":\"oso\"}}"; + android.os.Handler handler = new android.os.Handler(Looper.getMainLooper()); + handler.post(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(),cmd,Toast.LENGTH_LONG).show(); + } + });*/ + PreyLogger.d("FIREBASE cmd:"+cmd); + PreyBetaController.startPrey(this,cmd); } } diff --git a/app/src/main/java/com/prey/services/PreyLockService.java b/app/src/main/java/com/prey/services/PreyLockService.java index 7c73272c..1183157e 100644 --- a/app/src/main/java/com/prey/services/PreyLockService.java +++ b/app/src/main/java/com/prey/services/PreyLockService.java @@ -20,7 +20,6 @@ import android.widget.Button; import android.widget.EditText; import android.widget.TextView; -import android.widget.Toast; import com.prey.PreyConfig; import com.prey.PreyLogger; diff --git a/app/src/main/java/com/prey/services/PreyNotificationForeGroundService.java b/app/src/main/java/com/prey/services/PreyNotificationForeGroundService.java index 738653ee..be28c938 100644 --- a/app/src/main/java/com/prey/services/PreyNotificationForeGroundService.java +++ b/app/src/main/java/com/prey/services/PreyNotificationForeGroundService.java @@ -60,7 +60,7 @@ private void startForegroundService() { builder = new Notification.Builder(this); } builder.setWhen(System.currentTimeMillis()); - builder.setSmallIcon(R.drawable.icon_cog); + builder.setSmallIcon(R.drawable.prey_protected); builder.setContentTitle(getString(R.string.disable_power_ready)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { builder.setPriority(Notification.PRIORITY_MIN); diff --git a/app/src/main/res/drawable/prey_protected.png b/app/src/main/res/drawable/prey_protected.png new file mode 100644 index 00000000..1686f865 Binary files /dev/null and b/app/src/main/res/drawable/prey_protected.png differ diff --git a/app/src/main/res/raw/config b/app/src/main/res/raw/config index 60c3b2b4..9836244b 100644 --- a/app/src/main/res/raw/config +++ b/app/src/main/res/raw/config @@ -13,8 +13,9 @@ prey-events-logs=https://clients1.preyproject.com/events/log #production prey-subdomain=solid prey-domain=preyproject.com + #staging -#prey-subdomain=panel1 +#prey-subdomain=panel #prey-domain=preyhq.com @@ -44,11 +45,11 @@ analytics-ua=UA-8743344-9 prey-uninstall=http://help.preyproject.com/article/190-how-to-uninstall-prey prey-uninstall-es=http://ayuda.preyproject.com/article/226-como-desinstalar-prey -#300 meters -geofence-maximum-accuracy=300 +#900 meters +geofence-maximum-accuracy=900 #four minutes -geofence-loitering-delay=240000 +geofence-loitering-delay=30000 #notification Responsiveness geofence-notification-responsiveness=5000 @@ -56,6 +57,7 @@ geofence-notification-responsiveness=5000 #100 meters distance-location=100 -distance-aware=200 +distance-aware=120 +radius-aware=300 flyer-key=pzZcjLhYQ5emA8XLvSKNub diff --git a/build.gradle b/build.gradle index 136bfd6b..144ad7dc 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ buildscript { google() } dependencies { - classpath 'com.android.tools.build:gradle:3.1.2' + classpath 'com.android.tools.build:gradle:3.1.4' classpath 'com.google.gms:google-services:4.0.0' // NOTE: Do not place your application dependencies here; they belong