From 70813a9b4503bf08d094a457289b2a8c75586bf8 Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Wed, 2 Oct 2024 23:18:45 -0300 Subject: [PATCH 01/10] New API to get token New API to get token --- app/src/main/java/com/prey/PreyConfig.java | 71 ++++++++++++++++++---- 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/prey/PreyConfig.java b/app/src/main/java/com/prey/PreyConfig.java index 535dae50..60b0532f 100644 --- a/app/src/main/java/com/prey/PreyConfig.java +++ b/app/src/main/java/com/prey/PreyConfig.java @@ -17,12 +17,17 @@ import android.preference.PreferenceManager; import android.view.View; +import androidx.annotation.NonNull; + import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationRequest; +import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; +import com.google.firebase.messaging.FirebaseMessaging; import com.prey.actions.location.PreyLocation; import com.prey.activities.FeedbackActivity; import com.prey.managers.PreyConnectivityManager; @@ -616,7 +621,22 @@ public void onSuccess(InstanceIdResult instanceIdResult) { } }); } catch (Exception ex) { - PreyLogger.e("registerC2dm error2:" + ex.getMessage(), ex); + try { + FirebaseMessaging.getInstance().getToken() + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (!task.isSuccessful()) { + PreyLogger.e(String.format("registerC2dm error:%s", task.getException().getMessage()), task.getException()); + } + String token = task.getResult(); + PreyLogger.d(String.format("registerC2dm token:%s", token)); + sendToken(ctx, token); + } + }); + } catch (Exception exception) { + PreyLogger.e(String.format("registerC2dm error:%s", exception.getMessage()), exception); + } } } } @@ -1125,15 +1145,15 @@ public PreyLocation getLocation(){ public void setLocationAware(PreyLocation location){ if(location!=null) { - saveFloat(PreyConfig.AWARE_LAT, location.getLat().floatValue()); - saveFloat(PreyConfig.AWARE_LNG, location.getLng().floatValue()); + saveString(PreyConfig.AWARE_LAT, location.getLat().toString()); + saveString(PreyConfig.AWARE_LNG, location.getLng().toString()); saveFloat(PreyConfig.AWARE_ACC, location.getAccuracy()); } } public void removeLocationAware(){ - saveFloat(PreyConfig.AWARE_LAT, 0); - saveFloat(PreyConfig.AWARE_LNG, 0); + saveString(PreyConfig.AWARE_LAT, ""); + saveString(PreyConfig.AWARE_LNG, ""); saveFloat(PreyConfig.AWARE_ACC, 0); saveString(PreyConfig.AWARE_DATE, ""); } @@ -1149,15 +1169,21 @@ public void setAwareDate(String awareDate){ public PreyLocation getLocationAware(){ try{ - float lat=getFloat(PreyConfig.AWARE_LAT,0); - float lng=getFloat(PreyConfig.AWARE_LNG,0); - float acc=getFloat(PreyConfig.AWARE_ACC,0); - if(lat==0||lng==0){ + String lat=""; + String lng=""; + try { + lat = getString(PreyConfig.AWARE_LAT, ""); + lng = getString(PreyConfig.AWARE_LNG, ""); + }catch (Exception e){ + + } + float acc=getFloat(PreyConfig.AWARE_ACC,0f); + if(lat==null||"".equals(lat)||lng==null||"".equals(lng)){ return null; } PreyLocation location= new PreyLocation(); - location.setLat(lat); - location.setLng(lng); + location.setLat(Double.parseDouble(lat)); + location.setLng(Double.parseDouble(lng)); location.setAccuracy(acc); return location; }catch(Exception e){ @@ -1632,4 +1658,27 @@ public void setMinutesToQueryServer(int minutesToQueryServer) { PreyLogger.d(String.format("setMinutesToQueryServer [%s]", minutesToQueryServer)); saveInt(PreyConfig.MINUTES_TO_QUERY_SERVER, minutesToQueryServer); } + + public static final String AWARE_TIME = "AWARE_TIME"; + + public void setAwareTime() { + //the date is saved 10 minutes in the future + Calendar cal=Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.MINUTE ,10); + long dateTimeLong=cal.getTimeInMillis(); + PreyLogger.d(String.format("AWARE WORK AwareTime [%s]", dateTimeLong)); + saveLong(PreyConfig.AWARE_TIME, dateTimeLong); + } + + public boolean isTimeNextAware() { + //validates if the saved date is old + long awareTime = getLong(AWARE_TIME, 0); + if (awareTime == 0) + return true; + long timeNow = new Date().getTime(); + PreyLogger.d(String.format("AWARE WORK AwareTime difference [%s] current[%s] > save[%s] ", (timeNow - awareTime), timeNow, awareTime)); + return timeNow > awareTime; + } + } From d9a7eb010a54f61a2c7254a0fad40702a443a210 Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Wed, 2 Oct 2024 23:20:25 -0300 Subject: [PATCH 02/10] New worker for send location. New worker for send location. --- app/src/main/java/com/prey/PreyApp.java | 2 + .../prey/actions/aware/AwareController.java | 22 +++-- .../java/com/prey/net/PreyRestHttpClient.java | 33 ++++---- .../java/com/prey/net/UtilConnection.java | 83 ++++++++++++------- .../com/prey/workers/IncrementWorker.java | 50 +++++++++++ .../java/com/prey/workers/PreyWorker.java | 49 +++++++++++ 6 files changed, 181 insertions(+), 58 deletions(-) create mode 100644 app/src/main/java/com/prey/workers/IncrementWorker.java create mode 100644 app/src/main/java/com/prey/workers/PreyWorker.java diff --git a/app/src/main/java/com/prey/PreyApp.java b/app/src/main/java/com/prey/PreyApp.java index 537d4b01..14df39e2 100644 --- a/app/src/main/java/com/prey/PreyApp.java +++ b/app/src/main/java/com/prey/PreyApp.java @@ -33,6 +33,7 @@ import com.prey.services.AwareJobService; import com.prey.services.PreyDisablePowerOptionsService; import com.prey.services.PreyJobService; +import com.prey.workers.PreyWorker; import java.util.Date; import java.util.Map; @@ -117,6 +118,7 @@ public void run() { AwareController.getInstance().init(ctx); AwareScheduled.getInstance(ctx).run(); LocationScheduled.getInstance().run(ctx); + PreyWorker.getInstance().startPeriodicWork(ctx); } FileretrievalController.getInstance().run(ctx); TriggerController.getInstance().run(ctx); diff --git a/app/src/main/java/com/prey/actions/aware/AwareController.java b/app/src/main/java/com/prey/actions/aware/AwareController.java index f0eb5718..634be555 100644 --- a/app/src/main/java/com/prey/actions/aware/AwareController.java +++ b/app/src/main/java/com/prey/actions/aware/AwareController.java @@ -7,8 +7,6 @@ package com.prey.actions.aware; import android.Manifest; -import android.app.NotificationChannel; -import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; @@ -18,8 +16,6 @@ import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationManagerCompat; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; @@ -30,7 +26,6 @@ import com.prey.FileConfigReader; import com.prey.PreyConfig; import com.prey.PreyLogger; -import com.prey.R; import com.prey.actions.location.LocationUpdatesService; import com.prey.actions.location.LocationUtil; import com.prey.actions.location.PreyLocation; @@ -185,7 +180,6 @@ public static boolean mustSendAware(Context ctx, PreyLocation oldLocation, PreyL if (oldLocation == null) { if (newLocation != null) { sendAware = true; - PreyConfig.getPreyConfig(ctx).setLocationAware(newLocation); } } else { if (newLocation != null) { @@ -193,7 +187,6 @@ public static boolean mustSendAware(Context ctx, PreyLocation oldLocation, PreyL PreyLogger.d("AWARE distance:" + distance + " > " + distanceAware); if (distance > distanceAware) { sendAware = true; - PreyConfig.getPreyConfig(ctx).setLocationAware(newLocation); } } } @@ -240,12 +233,17 @@ public static PreyHttpResponse sendNowAware(Context ctx, PreyLocation locationNo } preyResponse = PreyWebServices.getInstance().sendLocation(ctx, location); if (preyResponse != null) { - PreyLogger.d("AWARE getStatusCode :"+preyResponse.getStatusCode()); - if (preyResponse.getStatusCode() == HttpURLConnection.HTTP_CREATED) { - PreyConfig.getPreyConfig(ctx).setAware(false); + int statusCode = preyResponse.getStatusCode(); + String response = preyResponse.getResponseAsString(); + PreyLogger.d(String.format("AWARE statusCode:%s response:%s", statusCode, response)); + if (statusCode == HttpURLConnection.HTTP_CREATED || statusCode == HttpURLConnection.HTTP_OK) { + PreyConfig.getPreyConfig(ctx).setLocationAware(locationNow); + PreyConfig.getPreyConfig(ctx).setAwareTime(); + if ("OK".equals(response)) { + PreyConfig.getPreyConfig(ctx).setAwareDate(PreyConfig.FORMAT_SDF_AWARE.format(new Date())); + PreyLogger.d(String.format("AWARE sendNowAware:%s", locationNow.toString())); + } } - PreyConfig.getPreyConfig(ctx).setAwareDate(PreyConfig.FORMAT_SDF_AWARE.format(new Date())); - PreyLogger.d("AWARE sendNowAware:" + locationNow.toString()); } } return preyResponse; diff --git a/app/src/main/java/com/prey/net/PreyRestHttpClient.java b/app/src/main/java/com/prey/net/PreyRestHttpClient.java index 7e613445..f9d9c890 100644 --- a/app/src/main/java/com/prey/net/PreyRestHttpClient.java +++ b/app/src/main/java/com/prey/net/PreyRestHttpClient.java @@ -130,17 +130,16 @@ public int postJson(String url, JSONObject jsonParam) { } public PreyHttpResponse jsonMethod(String url, String method, JSONObject jsonParam) { - PreyHttpResponse response=null; - HttpURLConnection connection=null; + PreyHttpResponse response = null; + HttpURLConnection connection = null; try { - PreyLogger.d("Sending using 'POST' - URI: " + url + " - parameters: " + jsonParam.toString()); - connection=UtilConnection.connectionJson(PreyConfig.getPreyConfig(ctx),url,method,jsonParam,null); - response = new PreyHttpResponse(connection); - if(response!=null) { - PreyLogger.d("Response from server: " + response.toString()); + PreyLogger.d(String.format("Sending using 'POST' - URI:%s - parameters:%s", url, jsonParam.toString())); + response = UtilConnection.connectionJson(PreyConfig.getPreyConfig(ctx), url, method, jsonParam, null); + if (response != null) { + PreyLogger.d(String.format("Response from server:%s", response.toString())); } } catch (Exception e) { - PreyLogger.e("jsonMethod "+method+" error:" + e.getMessage(), e); + PreyLogger.e(String.format("jsonMethod:%s error:%s", method, e.getMessage()), e); } finally { if (connection != null) connection.disconnect(); @@ -149,15 +148,16 @@ public PreyHttpResponse jsonMethod(String url, String method, JSONObject jsonPar } public PreyHttpResponse jsonMethodAutentication(String url,String method, JSONObject jsonParam) { - PreyHttpResponse response =null; - HttpURLConnection connection=null; + PreyHttpResponse response = null; + HttpURLConnection connection = null; try { - PreyLogger.d("Sending using '"+method+"' - URI: " + url + " - parameters: " + (jsonParam==null?"":jsonParam.toString())); - connection=UtilConnection.connectionJsonAuthorization(PreyConfig.getPreyConfig(ctx),url,method,jsonParam); - response = new PreyHttpResponse(connection); - PreyLogger.d("Response from server: " + response.toString()); + PreyLogger.d(String.format("Sending using %s - URI:%s - parameters:%s", method, url, (jsonParam == null ? "" : jsonParam.toString()))); + response = UtilConnection.connectionJsonAuthorization(PreyConfig.getPreyConfig(ctx), url, method, jsonParam); + if (response != null) { + PreyLogger.d(String.format("Response from server:%s", response.toString())); + } } catch (Exception e) { - PreyLogger.e("jsonMethodAutentication "+method+" error:" + e.getMessage(), e); + PreyLogger.e(String.format("jsonMethodAutentication:%s error:%s", method, e.getMessage()), e); } finally { if (connection != null) { connection.disconnect(); @@ -206,7 +206,6 @@ public PreyHttpResponse sendHelp(Context ctx, String uri, Map pa * @throws Exception */ public PreyHttpResponse validToken(Context ctx, String uri, JSONObject json) throws Exception { - HttpURLConnection connection = UtilConnection.connectionJson(PreyConfig.getPreyConfig(ctx), uri, UtilConnection.REQUEST_METHOD_POST, json); - return new PreyHttpResponse(connection); + return UtilConnection.connectionJson(PreyConfig.getPreyConfig(ctx), uri, UtilConnection.REQUEST_METHOD_POST, json); } } \ No newline at end of file diff --git a/app/src/main/java/com/prey/net/UtilConnection.java b/app/src/main/java/com/prey/net/UtilConnection.java index 65fe77cb..2ef4d67f 100644 --- a/app/src/main/java/com/prey/net/UtilConnection.java +++ b/app/src/main/java/com/prey/net/UtilConnection.java @@ -7,8 +7,6 @@ package com.prey.net; import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; import com.prey.PreyConfig; import com.prey.PreyLogger; @@ -387,46 +385,73 @@ public static PreyHttpResponse convertPreyHttpResponse(int responseCode,HttpURLC return new PreyHttpResponse(responseCode,sb.toString(),mapHeaderFields); } - public static HttpURLConnection connectionJson(PreyConfig preyConfig, String uri, String method, JSONObject jsonParam) { + public static PreyHttpResponse connectionJson(PreyConfig preyConfig, String uri, String method, JSONObject jsonParam) { return connectionJson(preyConfig,uri,REQUEST_METHOD_POST,jsonParam,null); } - public static HttpURLConnection connectionJsonAuthorization(PreyConfig preyConfig,String uri,String method, JSONObject jsonParam) { + public static PreyHttpResponse connectionJsonAuthorization(PreyConfig preyConfig,String uri,String method, JSONObject jsonParam) { return connectionJson(preyConfig,uri,method,jsonParam,"Basic " + getCredentials(preyConfig.getApiKey(), "X")); } - public static HttpURLConnection connectionJson(PreyConfig preyConfig, String uri, String method, JSONObject jsonParam, String authorization) { + public static PreyHttpResponse connectionJson(PreyConfig preyConfig, String uri, String method, JSONObject jsonParam, String authorization) { + PreyHttpResponse response = null; HttpURLConnection connection = null; - int httpResult = -1; try { if (isInternetAvailable(preyConfig.getContext())) { - URL url = new URL(uri); - PreyLogger.d(String.format("postJson page: %s", uri)); - connection = (HttpURLConnection) url.openConnection(); - connection.setDoOutput(true); - connection.setRequestMethod(method); - connection.setUseCaches(USE_CACHES); - connection.setConnectTimeout(CONNECT_TIMEOUT); - connection.setReadTimeout(READ_TIMEOUT); - connection.setRequestProperty("Content-Type", "application/json"); - if (authorization != null) - connection.addRequestProperty("Authorization", authorization); - connection.addRequestProperty("User-Agent", getUserAgent(preyConfig)); - connection.addRequestProperty("Origin", "android:com.prey"); - connection.connect(); - if (jsonParam != null) { - PreyLogger.d(String.format("jsonParam.toString():%s", jsonParam.toString())); - OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); - out.write(jsonParam.toString()); - out.close(); - } - httpResult = connection.getResponseCode(); - PreyLogger.d(String.format("postJson responseCode:%s", httpResult)); + boolean delay = false; + int retry = 0; + do { + if (delay) { + Thread.sleep(ARRAY_RETRY_DELAY_MS[retry] * 1000); + } + URL url = new URL(uri); + if (uri.indexOf("https:") >= 0) { + connection = (HttpsURLConnection) url.openConnection(); + } else { + connection = (HttpURLConnection) url.openConnection(); + } + connection.setDoOutput(true); + connection.setRequestMethod(method); + connection.setUseCaches(USE_CACHES); + connection.setConnectTimeout(CONNECT_TIMEOUT); + connection.setReadTimeout(READ_TIMEOUT); + connection.setRequestProperty("Content-Type", "application/json"); + if (authorization != null) + connection.addRequestProperty("Authorization", authorization); + connection.addRequestProperty("User-Agent", getUserAgent(preyConfig)); + connection.addRequestProperty("Origin", "android:com.prey"); + connection.connect(); + if (jsonParam != null) { + PreyLogger.d(String.format("jsonParam.toString():%s", jsonParam.toString())); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(jsonParam.toString()); + out.close(); + } + int responseCode = connection.getResponseCode(); + switch (responseCode) { + case HttpURLConnection.HTTP_CREATED: + response = convertPreyHttpResponse(responseCode, connection); + retry = RETRIES; + break; + case HttpURLConnection.HTTP_OK: + response = convertPreyHttpResponse(responseCode, connection); + retry = RETRIES; + break; + default: + break; + } + connection.disconnect(); + retry++; + if (retry <= RETRIES) { + PreyLogger.d("AWARE WORK Failed retry " + retry + "/" + RETRIES); + } + delay = true; + } while (retry < RETRIES); } } catch (Exception e) { PreyLogger.e(String.format("postJson error:%s", e.getMessage()), e); } - return connection; + return response; } private static String getPostDataString(Map params) throws UnsupportedEncodingException{ diff --git a/app/src/main/java/com/prey/workers/IncrementWorker.java b/app/src/main/java/com/prey/workers/IncrementWorker.java new file mode 100644 index 00000000..40c0561b --- /dev/null +++ b/app/src/main/java/com/prey/workers/IncrementWorker.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2024 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ + +package com.prey.workers; + +import android.content.Context; + +import androidx.annotation.NonNull; +import androidx.work.Worker; +import androidx.work.WorkerParameters; + +import com.prey.PreyConfig; +import com.prey.PreyLogger; +import com.prey.actions.aware.AwareController; + +public class IncrementWorker extends Worker { + + public IncrementWorker( + @NonNull Context context, + @NonNull WorkerParameters params) { + super(context, params); + } + + @Override + public Result doWork() { + PreyLogger.d("AWARE WORK doWork"); + Context context = getApplicationContext(); + try { + if (PreyConfig.getPreyConfig(context).isTimeNextAware()) { + new Thread() { + public void run() { + new AwareController().init(context); + } + }.start(); + } + return Result.success(); + } catch (NumberFormatException e) { + PreyLogger.e(String.format("----------Error IncrementWorker:%s", e.getMessage()), e); + return Result.failure(); + } catch (Throwable throwable) { + PreyLogger.e(String.format("----------Error IncrementWorker:%s", throwable.getMessage()), throwable); + return Result.failure(); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/workers/PreyWorker.java b/app/src/main/java/com/prey/workers/PreyWorker.java new file mode 100644 index 00000000..0f3ddc7c --- /dev/null +++ b/app/src/main/java/com/prey/workers/PreyWorker.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2024 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ + +package com.prey.workers; + +import android.content.Context; + +import androidx.work.PeriodicWorkRequest; +import androidx.work.WorkManager; + +import java.util.concurrent.TimeUnit; + +public class PreyWorker { + + private static PreyWorker _instance = null; + public static final String INCREMENT_WORK_NAME = "prey_increment_work"; + + private PreyWorker() { + } + + public static PreyWorker getInstance() { + if (_instance == null) + _instance = new PreyWorker(); + return _instance; + } + + /** + * Starts a periodic worker to run every 15 minutes, with a 5 minute flex period. + * @param context the application context + */ + public void startPeriodicWork(Context context) { + WorkManager workManager = WorkManager.getInstance(context); + workManager.cancelAllWorkByTag(INCREMENT_WORK_NAME); + PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder( + IncrementWorker.class, + 15, + TimeUnit.MINUTES, + 5, + TimeUnit.MINUTES) + .addTag(INCREMENT_WORK_NAME) + .build(); + workManager.enqueue(workRequest); + } + +} \ No newline at end of file From c19dc8f666cc7cb478229a5ae228f97ac062af1e Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Wed, 2 Oct 2024 23:22:20 -0300 Subject: [PATCH 03/10] Force location sending. Force location sending. --- .../main/java/com/prey/actions/location/daily/DailyLocation.java | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/com/prey/actions/location/daily/DailyLocation.java b/app/src/main/java/com/prey/actions/location/daily/DailyLocation.java index 4600f5ee..5af14325 100644 --- a/app/src/main/java/com/prey/actions/location/daily/DailyLocation.java +++ b/app/src/main/java/com/prey/actions/location/daily/DailyLocation.java @@ -85,6 +85,7 @@ public static void sendLocation(Context context, PreyLocation preyLocation) thro json.put("lng", preyLocation.getLng()); json.put("accuracy", accD); json.put("method", method); + json.put("force", true); JSONObject location = new JSONObject(); location.put("location", json); if (android.os.Build.VERSION.SDK_INT > 9) { From 3384f61835c126f401c1922b64586347a6349ede Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Wed, 2 Oct 2024 23:23:54 -0300 Subject: [PATCH 04/10] Update API Update API --- app/build.gradle | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 8d229080..df2dec8d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -52,15 +52,16 @@ dependencies { implementation 'com.google.android.gms:play-services-maps:19.0.0' implementation 'com.google.firebase:firebase-core:21.1.1' implementation 'com.google.firebase:firebase-iid:21.1.0' - implementation 'com.google.firebase:firebase-messaging:24.0.0' - implementation 'com.google.firebase:firebase-analytics:22.0.2' - implementation 'com.google.firebase:firebase-crashlytics:19.0.3' + implementation 'com.google.firebase:firebase-messaging:24.0.2' + implementation 'com.google.firebase:firebase-analytics:22.1.2' + implementation 'com.google.firebase:firebase-crashlytics:19.2.0' implementation 'com.google.firebase:firebase-database:21.0.0' implementation 'com.android.installreferrer:installreferrer:2.2' implementation 'com.android.support:multidex:1.0.3' implementation 'com.google.code.gson:gson:2.10.1' implementation 'androidx.biometric:biometric:1.2.0-alpha05' + implementation "androidx.work:work-runtime:2.9.1" testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.2.1' From 41da0ac3179ebf968ee30357fe42fb9edde20c72 Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Wed, 2 Oct 2024 23:24:22 -0300 Subject: [PATCH 05/10] New version 2.6.2 New version 2.6.2 --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index df2dec8d..af028269 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { targetSdkVersion 34 - versionCode 342 - versionName '2.6.1' + versionCode 348 + versionName '2.6.2' multiDexEnabled true From 5ed1c57f68d280bfe4cd4ca40c7b43083200ef5e Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Thu, 10 Oct 2024 18:28:19 -0300 Subject: [PATCH 06/10] Restriction is added to configure with policies Restriction is added to configure with policies --- app/src/main/AndroidManifest.xml | 4 + app/src/main/java/com/prey/PreyPhone.java | 32 +++++++ .../activities/CheckPasswordHtmlActivity.java | 85 +++++++++++++++++++ .../java/com/prey/net/PreyWebServices.java | 15 ++-- app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/app_restrictions.xml | 11 +++ 7 files changed, 146 insertions(+), 5 deletions(-) create mode 100644 app/src/main/res/xml/app_restrictions.xml diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index bb202205..e4940b4a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -37,6 +37,7 @@ + @@ -91,6 +92,9 @@ + + c = Class.forName("android.os.SystemProperties"); + Method getMethod = c.getMethod("get", String.class); + serialNumber = getSerialNumberFromProperty(getMethod, "gsm.sn1"); + if (serialNumber == null) { + serialNumber = getSerialNumberFromProperty(getMethod, "ril.serialnumber"); + } + if (serialNumber == null) { + serialNumber = getSerialNumberFromProperty(getMethod, "ro.serialno"); + } + if (serialNumber == null) { + serialNumber = getSerialNumberFromProperty(getMethod, "sys.serialnumber"); + } + if (serialNumber == null) { + serialNumber = Build.SERIAL; + } + } catch (Exception e) { + PreyLogger.e(String.format("Error getSerialNumber:%s", e.getMessage()), e); + serialNumber = null; + } + return serialNumber; + } + + private static String getSerialNumberFromProperty(Method getMethod, String propertyName) throws Exception { + return (String) getMethod.invoke(null, propertyName); + } + } \ No newline at end of file diff --git a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java index eca7acac..df1a8fa2 100644 --- a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java +++ b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java @@ -15,8 +15,10 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; +import android.content.RestrictionsManager; import android.database.Cursor; import android.net.Uri; +import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; @@ -42,15 +44,22 @@ import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; +import com.prey.PreyAccountData; +import com.prey.PreyApp; import com.prey.PreyConfig; import com.prey.PreyLogger; import com.prey.PreyPermission; +import com.prey.PreyStatus; import com.prey.PreyUtils; import com.prey.R; +import com.prey.actions.aware.AwareController; import com.prey.activities.js.CustomWebView; import com.prey.activities.js.WebAppInterface; import com.prey.backwardcompatibility.FroyoSupport; +import com.prey.json.actions.Location; +import com.prey.net.PreyWebServices; +import com.prey.preferences.RunBackgroundCheckBoxPreference; import com.prey.services.PreyAccessibilityService; import com.prey.services.PreyOverlayService; @@ -82,6 +91,22 @@ public void onReceive(Context context, Intent intent) { } }; + private final BroadcastReceiver restriction_receiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (!PreyConfig.getPreyConfig(context).isThisDeviceAlreadyRegisteredWithPrey()) { + RestrictionsManager restrictionsManager = (RestrictionsManager) context.getSystemService(Context.RESTRICTIONS_SERVICE); + Bundle restrictions = restrictionsManager.getApplicationRestrictions(); + if (restrictions != null && restrictions.containsKey("setup_key")) { + String setupKey = restrictions.getString("setup_key"); + if (setupKey != null && !"".equals(setupKey)) { + new AddDeviceWithRestriction().execute(setupKey); + } + } + } + } + }; + private WebView myWebView = null; public static int OVERLAY_PERMISSION_REQ_CODE = 5469; @@ -103,6 +128,11 @@ protected void onCreate(Bundle savedInstanceState) { } else { registerReceiver(close_prey_receiver, new IntentFilter(CLOSE_PREY)); } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(restriction_receiver, new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED), RECEIVER_EXPORTED); + } else { + registerReceiver(restriction_receiver, new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED)); + } if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); @@ -133,8 +163,11 @@ protected void onResume() { protected void onDestroy() { super.onDestroy(); unregisterReceiver(close_prey_receiver); + unregisterReceiver(restriction_receiver); } + + public void settings() { PreyLogger.d("CheckPasswordHtmlActivity: settings"); myWebView = (WebView) findViewById(R.id.install_browser); @@ -745,4 +778,56 @@ public void openBiometric(){ showBiometricPrompt(signature,2); } } + String error = null; + + private class AddDeviceWithRestriction extends AsyncTask { + + @Override + protected Void doInBackground(String... data) { + error = null; + try { + final Context ctx = getApplicationContext(); + String apiKey = data[0]; + String deviceType = PreyUtils.getDeviceType(ctx); + String nameDevice = PreyUtils.getNameDevice(ctx); + PreyLogger.d(String.format("apikey:%s mail:%s type:%s nameDevice:%s", apiKey, deviceType, nameDevice)); + if (!PreyConfig.getPreyConfig(ctx).isThisDeviceAlreadyRegisteredWithPrey()) { + PreyAccountData accountData = PreyWebServices.getInstance().registerNewDeviceWithApiKeyEmail(ctx, apiKey, deviceType, nameDevice); + if (accountData != null) { + PreyConfig.getPreyConfig(ctx).saveAccount(accountData); + PreyConfig.getPreyConfig(ctx).registerC2dm(); + String email = PreyWebServices.getInstance().getEmail(ctx); + PreyConfig.getPreyConfig(ctx).setEmail(email); + PreyConfig.getPreyConfig(ctx).setRunBackground(true); + RunBackgroundCheckBoxPreference.notifyReady(ctx); + PreyConfig.getPreyConfig(ctx).setInstallationStatus(""); + new PreyApp().run(ctx); + new Thread() { + public void run() { + try { + PreyStatus.getInstance().initConfig(getApplicationContext()); + AwareController.getInstance().init(ctx); + new Location().get(ctx, null, null); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + } + }.start(); + } + } + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + error = e.getMessage(); + } + return null; + } + + @Override + protected void onPostExecute(Void unused) { + if (error == null) { + reload(); + } + } + } + } \ No newline at end of file diff --git a/app/src/main/java/com/prey/net/PreyWebServices.java b/app/src/main/java/com/prey/net/PreyWebServices.java index ca50546a..564c6028 100644 --- a/app/src/main/java/com/prey/net/PreyWebServices.java +++ b/app/src/main/java/com/prey/net/PreyWebServices.java @@ -267,23 +267,27 @@ public PreyAccountData registerNewDeviceToAccount(Context ctx, String email, Str } + public PreyAccountData registerNewDeviceWithApiKeyEmail(Context ctx, String apiKey, String deviceType, String name) throws Exception { + return registerNewDeviceWithApiKeyEmail(ctx, apiKey, null, deviceType, name); + } + public PreyAccountData registerNewDeviceWithApiKeyEmail(Context ctx, String apiKey, String email, String deviceType, String name) throws Exception { String deviceId = null; - PreyHttpResponse responseDevice = registerNewDevice(ctx, apiKey, deviceType,name); + PreyHttpResponse responseDevice = registerNewDevice(ctx, apiKey, deviceType, name); String xmlDeviceId = null; - if(responseDevice!=null) { + if (responseDevice != null) { xmlDeviceId = responseDevice.getResponseAsString(); } //if json - if (xmlDeviceId!=null&&xmlDeviceId.contains("{\"key\"")) { + if (xmlDeviceId != null && xmlDeviceId.contains("{\"key\"")) { try { JSONObject jsnobject = new JSONObject(xmlDeviceId); deviceId = jsnobject.getString("key"); } catch (Exception e) { } } - PreyAccountData newAccount =null; - if (deviceId!=null&&!"".equals(deviceId)) { + PreyAccountData newAccount = null; + if (deviceId != null && !"".equals(deviceId)) { newAccount = new PreyAccountData(); newAccount.setApiKey(apiKey); newAccount.setDeviceId(deviceId); @@ -574,6 +578,7 @@ public HashMap increaseData(Context ctx, HashMap parameters.put(prefix + "[cpu_cores]", hardware.getCpuCores()); parameters.put(prefix + "[ram_size]", "" + hardware.getTotalMemory()); parameters.put(prefix + "[serial_number]", hardware.getSerialNumber()); + parameters.put(prefix + "[uuid]", hardware.getUuid()); parameters.put(prefix + "[google_services]", String.valueOf(PreyUtils.isGooglePlayServicesAvailable(ctx))); int nic = 0; Wifi wifi = phone.getWifi(); diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7c26be7f..538ed8fa 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -375,4 +375,6 @@ Ingresar con huella Permite a Prey usar tu huella digital para acceder a la configuración de aplicación. + Clave de configuración + Clave de cuenta diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 75c1d5f2..1322a61d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -381,4 +381,6 @@ Login with fingerprint Allows Prey to enter the app configuration using only your fingerprint. + Setup key + Account key diff --git a/app/src/main/res/xml/app_restrictions.xml b/app/src/main/res/xml/app_restrictions.xml new file mode 100644 index 00000000..635a261b --- /dev/null +++ b/app/src/main/res/xml/app_restrictions.xml @@ -0,0 +1,11 @@ + + + + + + \ No newline at end of file From 53d343beff664980cee5c1c9215de6f5bb27cca7 Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Thu, 10 Oct 2024 18:30:02 -0300 Subject: [PATCH 07/10] New version 2.6.3 New version 2.6.3 --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index af028269..fd08d3af 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { targetSdkVersion 34 - versionCode 348 - versionName '2.6.2' + versionCode 349 + versionName '2.6.3' multiDexEnabled true From 1b29e35e0f743532fc1ca52f445a15e8f6bf5d45 Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Thu, 10 Oct 2024 18:35:42 -0300 Subject: [PATCH 08/10] Revert "New version 2.6.3" This reverts commit 53d343beff664980cee5c1c9215de6f5bb27cca7. --- app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index fd08d3af..af028269 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { targetSdkVersion 34 - versionCode 349 - versionName '2.6.3' + versionCode 348 + versionName '2.6.2' multiDexEnabled true From 03736af3ef8853dbb605d101c488b9f5a8c99ded Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Fri, 11 Oct 2024 10:29:10 -0300 Subject: [PATCH 09/10] Documentation is added Documentation is added --- app/src/main/java/com/prey/PreyConfig.java | 50 +++++-- app/src/main/java/com/prey/PreyPhone.java | 31 +++- .../prey/actions/aware/AwareController.java | 29 +++- .../activities/CheckPasswordHtmlActivity.java | 41 +++++- .../java/com/prey/net/UtilConnection.java | 137 +++++++++++------- .../com/prey/workers/IncrementWorker.java | 21 ++- .../java/com/prey/workers/PreyWorker.java | 20 ++- 7 files changed, 250 insertions(+), 79 deletions(-) diff --git a/app/src/main/java/com/prey/PreyConfig.java b/app/src/main/java/com/prey/PreyConfig.java index 60b0532f..91356f2e 100644 --- a/app/src/main/java/com/prey/PreyConfig.java +++ b/app/src/main/java/com/prey/PreyConfig.java @@ -1167,26 +1167,40 @@ public void setAwareDate(String awareDate){ saveString(PreyConfig.AWARE_DATE, awareDate); } - public PreyLocation getLocationAware(){ - try{ - String lat=""; - String lng=""; + /** + * Retrieves the location aware settings. + * + * @return A PreyLocation object containing the location aware settings, or null if the settings are not available. + */ + public PreyLocation getLocationAware() { + try { + // Initialize latitude and longitude variables + String lat = ""; + String lng = ""; + // Attempt to retrieve the latitude and longitude values from storage + //The data saving is changed to string because decimals are lost try { lat = getString(PreyConfig.AWARE_LAT, ""); lng = getString(PreyConfig.AWARE_LNG, ""); - }catch (Exception e){ - + } catch (Exception e) { + PreyLogger.e(String.format("Error getLocationAware:%s", e.getMessage()), e); } - float acc=getFloat(PreyConfig.AWARE_ACC,0f); - if(lat==null||"".equals(lat)||lng==null||"".equals(lng)){ + // Retrieve the accuracy value from storage + float acc = getFloat(PreyConfig.AWARE_ACC, 0f); + // Check if the latitude or longitude values are empty or null + if (lat == null || "".equals(lat) || lng == null || "".equals(lng)) { + // If either value is empty or null, return null return null; } - PreyLocation location= new PreyLocation(); + // Create a new PreyLocation object + PreyLocation location = new PreyLocation(); location.setLat(Double.parseDouble(lat)); location.setLng(Double.parseDouble(lng)); location.setAccuracy(acc); + // Return the PreyLocation object return location; - }catch(Exception e){ + } catch (Exception e) { + PreyLogger.e(String.format("Error getLocationAware:%s", e.getMessage()), e); return null; } } @@ -1659,8 +1673,16 @@ public void setMinutesToQueryServer(int minutesToQueryServer) { saveInt(PreyConfig.MINUTES_TO_QUERY_SERVER, minutesToQueryServer); } + /** + * Key for storing the aware time in the configuration. + */ public static final String AWARE_TIME = "AWARE_TIME"; + /** + * Sets the aware time to 10 minutes in the future. + * + * This method updates the aware time stored in the configuration. + */ public void setAwareTime() { //the date is saved 10 minutes in the future Calendar cal=Calendar.getInstance(); @@ -1671,6 +1693,14 @@ public void setAwareTime() { saveLong(PreyConfig.AWARE_TIME, dateTimeLong); } + /** + * Checks if it's time for the next aware event. + * + * This method compares the current time with the saved aware time. + * It is used to not request the location for at least 10 minutes + * + * @return true if it's time for the next aware event, false otherwise + */ public boolean isTimeNextAware() { //validates if the saved date is old long awareTime = getLong(AWARE_TIME, 0); diff --git a/app/src/main/java/com/prey/PreyPhone.java b/app/src/main/java/com/prey/PreyPhone.java index 6c275e92..7d15e7c5 100644 --- a/app/src/main/java/com/prey/PreyPhone.java +++ b/app/src/main/java/com/prey/PreyPhone.java @@ -658,32 +658,55 @@ public static String getNetworkClass(Context ctx) { } } + /** + * Retrieves the device's serial number. + * + * This method attempts to retrieve the serial number from various system properties. + * If all attempts fail, it falls back to using the Build.SERIAL property. + * + * @return the device's serial number, or null if it could not be retrieved + */ public static String getSerialNumber() { + // Initialize the serial number to null String serialNumber = null; try { + // Get the SystemProperties class Class c = Class.forName("android.os.SystemProperties"); + // Get the get() method of the SystemProperties class Method getMethod = c.getMethod("get", String.class); - serialNumber = getSerialNumberFromProperty(getMethod, "gsm.sn1"); + // Attempt to retrieve the serial number from various system properties + serialNumber = getSerialNumberFromProperty(getMethod, "gsm.sn1"); // GSM serial number if (serialNumber == null) { - serialNumber = getSerialNumberFromProperty(getMethod, "ril.serialnumber"); + serialNumber = getSerialNumberFromProperty(getMethod, "ril.serialnumber"); // RIL serial number } if (serialNumber == null) { - serialNumber = getSerialNumberFromProperty(getMethod, "ro.serialno"); + serialNumber = getSerialNumberFromProperty(getMethod, "ro.serialno");// Serial number from ro.serialno property } if (serialNumber == null) { - serialNumber = getSerialNumberFromProperty(getMethod, "sys.serialnumber"); + serialNumber = getSerialNumberFromProperty(getMethod, "sys.serialnumber");// Serial number from sys.serialnumber property } if (serialNumber == null) { + // If all else fails, use the Build.SERIAL property serialNumber = Build.SERIAL; } } catch (Exception e) { PreyLogger.e(String.format("Error getSerialNumber:%s", e.getMessage()), e); serialNumber = null; } + // Return the retrieved serial number, or null if it could not be retrieved return serialNumber; } + /** + * Retrieves the value of the specified system property. + * + * @param getMethod the method used to retrieve the system property value + * @param propertyName the name of the system property to retrieve + * @return the value of the system property, or null if it could not be retrieved + * @throws Exception if an error occurs while retrieving the system property value + */ private static String getSerialNumberFromProperty(Method getMethod, String propertyName) throws Exception { + // Invoke the getMethod with the propertyName as an argument to retrieve the system property value return (String) getMethod.invoke(null, propertyName); } diff --git a/app/src/main/java/com/prey/actions/aware/AwareController.java b/app/src/main/java/com/prey/actions/aware/AwareController.java index 634be555..8495c4a6 100644 --- a/app/src/main/java/com/prey/actions/aware/AwareController.java +++ b/app/src/main/java/com/prey/actions/aware/AwareController.java @@ -206,41 +206,60 @@ public static void getSendNowAware(Context ctx) throws Exception{ * @return returns PreyHttpResponse */ public static PreyHttpResponse sendNowAware(Context ctx, PreyLocation locationNow) throws Exception { + // Initialize response variable PreyHttpResponse preyResponse = null; if (locationNow == null || locationNow.getLat() == 0 || locationNow.getLng() == 0) { + // Log message if location is invalid PreyLogger.d("AWARE sendNowAware is zero"); return preyResponse; } + // Get location aware status from config boolean isLocationAware = PreyConfig.getPreyConfig(ctx).getAware(); - PreyLogger.d("AWARE sendNowAware isLocationAware:"+isLocationAware); - if (isLocationAware){ + PreyLogger.d(String.format("AWARE sendNowAware isLocationAware:%s", isLocationAware)); + // Check if location aware is enabled + if (isLocationAware) { String messageId = null; String reason = null; double accD = Math.round(locationNow.getAccuracy() * 100.0) / 100.0; + // Create JSON object for location data JSONObject json = new JSONObject(); - String method=locationNow.getMethod(); - if(method==null) - method="native"; + String method = locationNow.getMethod(); + // Get method from location object, default to "native" if null + if (method == null) + method = "native"; + // Put location data into JSON object json.put("lat", locationNow.getLat()); json.put("lng", locationNow.getLng()); json.put("accuracy", accD); json.put("method", method); + // Create JSON object for location wrapper JSONObject location = new JSONObject(); + // Put location data into location wrapper location.put("location", json); + // Set thread policy for Android versions > 9 if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } + // Send location data using web services preyResponse = PreyWebServices.getInstance().sendLocation(ctx, location); + // Check if response is not null if (preyResponse != null) { + // Get status code and response from response object int statusCode = preyResponse.getStatusCode(); String response = preyResponse.getResponseAsString(); + // Log status code and response PreyLogger.d(String.format("AWARE statusCode:%s response:%s", statusCode, response)); + // Check if status code is HTTP_CREATED or HTTP_OK if (statusCode == HttpURLConnection.HTTP_CREATED || statusCode == HttpURLConnection.HTTP_OK) { + // Set location aware data in config PreyConfig.getPreyConfig(ctx).setLocationAware(locationNow); PreyConfig.getPreyConfig(ctx).setAwareTime(); + // Check if response is "OK" if ("OK".equals(response)) { + // The date of the last location sent correctly is saved (yyyy-MM-dd ) PreyConfig.getPreyConfig(ctx).setAwareDate(PreyConfig.FORMAT_SDF_AWARE.format(new Date())); + // Log location aware data PreyLogger.d(String.format("AWARE sendNowAware:%s", locationNow.toString())); } } diff --git a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java index df1a8fa2..3318d738 100644 --- a/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java +++ b/app/src/main/java/com/prey/activities/CheckPasswordHtmlActivity.java @@ -91,15 +91,26 @@ public void onReceive(Context context, Intent intent) { } }; + /** + * BroadcastReceiver to handle restriction events. + * Checks if the device is already registered with Prey and if not, retrieves the setup key from application restrictions. + */ private final BroadcastReceiver restriction_receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { + // Check if the device is already registered with Prey if (!PreyConfig.getPreyConfig(context).isThisDeviceAlreadyRegisteredWithPrey()) { + // Get the RestrictionsManager instance RestrictionsManager restrictionsManager = (RestrictionsManager) context.getSystemService(Context.RESTRICTIONS_SERVICE); + // Retrieve the application restrictions Bundle restrictions = restrictionsManager.getApplicationRestrictions(); + // Check if the restrictions bundle is not null and contains the "setup_key" if (restrictions != null && restrictions.containsKey("setup_key")) { + // Get the setup key from the restrictions bundle String setupKey = restrictions.getString("setup_key"); + // Check if the setup key is not null and not empty if (setupKey != null && !"".equals(setupKey)) { + // Execute the AddDeviceWithRestriction task with the setup key new AddDeviceWithRestriction().execute(setupKey); } } @@ -780,33 +791,54 @@ public void openBiometric(){ } String error = null; + /** + * AsyncTask to add a device with recovered the key from the restrictions. + * This task registers a new device with the provided API key, device type, and device name. + */ private class AddDeviceWithRestriction extends AsyncTask { + /** + * Performs the device registration in the background. + * + * @param data API key, device type, and device name. + * @return null + */ @Override protected Void doInBackground(String... data) { + // Reset error message error = null; try { + // Get application context final Context ctx = getApplicationContext(); + // Extract API key, device type, and device name from input data String apiKey = data[0]; String deviceType = PreyUtils.getDeviceType(ctx); String nameDevice = PreyUtils.getNameDevice(ctx); - PreyLogger.d(String.format("apikey:%s mail:%s type:%s nameDevice:%s", apiKey, deviceType, nameDevice)); + PreyLogger.d(String.format("apikey:%s type:%s nameDevice:%s", apiKey, deviceType, nameDevice)); + // Check if device is already registered if (!PreyConfig.getPreyConfig(ctx).isThisDeviceAlreadyRegisteredWithPrey()) { + // Register new device with API key and email PreyAccountData accountData = PreyWebServices.getInstance().registerNewDeviceWithApiKeyEmail(ctx, apiKey, deviceType, nameDevice); if (accountData != null) { + // Save account data PreyConfig.getPreyConfig(ctx).saveAccount(accountData); + // Register C2DM PreyConfig.getPreyConfig(ctx).registerC2dm(); + // Get email from web services String email = PreyWebServices.getInstance().getEmail(ctx); + // Set email in config PreyConfig.getPreyConfig(ctx).setEmail(email); PreyConfig.getPreyConfig(ctx).setRunBackground(true); RunBackgroundCheckBoxPreference.notifyReady(ctx); PreyConfig.getPreyConfig(ctx).setInstallationStatus(""); + // Run PreyApp new PreyApp().run(ctx); new Thread() { public void run() { try { PreyStatus.getInstance().initConfig(getApplicationContext()); AwareController.getInstance().init(ctx); + // Get location new Location().get(ctx, null, null); } catch (Exception e) { PreyLogger.e(String.format("Error:%s", e.getMessage()), e); @@ -822,9 +854,16 @@ public void run() { return null; } + /** + * Called after device registration is complete. + * Reloads the activity if no error occurred. + * + * @param unused unused + */ @Override protected void onPostExecute(Void unused) { if (error == null) { + // Reload activity reload(); } } diff --git a/app/src/main/java/com/prey/net/UtilConnection.java b/app/src/main/java/com/prey/net/UtilConnection.java index 2ef4d67f..886e99f8 100644 --- a/app/src/main/java/com/prey/net/UtilConnection.java +++ b/app/src/main/java/com/prey/net/UtilConnection.java @@ -393,64 +393,91 @@ public static PreyHttpResponse connectionJsonAuthorization(PreyConfig preyConfig return connectionJson(preyConfig,uri,method,jsonParam,"Basic " + getCredentials(preyConfig.getApiKey(), "X")); } - public static PreyHttpResponse connectionJson(PreyConfig preyConfig, String uri, String method, JSONObject jsonParam, String authorization) { + /** + * Sends a JSON request to the specified URI and returns the response. + * + * @param config The PreyConfig object containing configuration settings. + * @param uri The URI to send the request to. + * @param method The HTTP method to use (e.g. "POST", "GET", etc.). + * @param jsonParam The JSON data to send with the request. + * @param authorization The authorization token to include with the request. + * @return The PreyHttpResponse object containing the response from the server. + */ + public static PreyHttpResponse connectionJson(PreyConfig config, String uri, String method, JSONObject jsonParam, String authorization) { + // Initialize variables to track the response and retry count PreyHttpResponse response = null; - HttpURLConnection connection = null; - try { - if (isInternetAvailable(preyConfig.getContext())) { - boolean delay = false; - int retry = 0; - do { - if (delay) { - Thread.sleep(ARRAY_RETRY_DELAY_MS[retry] * 1000); - } - URL url = new URL(uri); - if (uri.indexOf("https:") >= 0) { - connection = (HttpsURLConnection) url.openConnection(); - } else { - connection = (HttpURLConnection) url.openConnection(); - } - connection.setDoOutput(true); - connection.setRequestMethod(method); - connection.setUseCaches(USE_CACHES); - connection.setConnectTimeout(CONNECT_TIMEOUT); - connection.setReadTimeout(READ_TIMEOUT); - connection.setRequestProperty("Content-Type", "application/json"); - if (authorization != null) - connection.addRequestProperty("Authorization", authorization); - connection.addRequestProperty("User-Agent", getUserAgent(preyConfig)); - connection.addRequestProperty("Origin", "android:com.prey"); - connection.connect(); - if (jsonParam != null) { - PreyLogger.d(String.format("jsonParam.toString():%s", jsonParam.toString())); - OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); - out.write(jsonParam.toString()); - out.close(); - } - int responseCode = connection.getResponseCode(); - switch (responseCode) { - case HttpURLConnection.HTTP_CREATED: - response = convertPreyHttpResponse(responseCode, connection); - retry = RETRIES; - break; - case HttpURLConnection.HTTP_OK: - response = convertPreyHttpResponse(responseCode, connection); - retry = RETRIES; - break; - default: - break; - } - connection.disconnect(); - retry++; - if (retry <= RETRIES) { - PreyLogger.d("AWARE WORK Failed retry " + retry + "/" + RETRIES); - } - delay = true; - } while (retry < RETRIES); + int retryCount = 0; + boolean shouldDelay = false; + + // Loop until we've reached the maximum number of retries + while (retryCount < RETRIES) { + try { + // If we've previously failed, wait for a short period of time before retrying + if (shouldDelay) { + Thread.sleep(ARRAY_RETRY_DELAY_MS[retryCount] * 1000); + } + + // Create a URL object from the URI + URL url = new URL(uri); + + // Open a connection to the URL, using HTTPS if the URI starts with "https" + HttpURLConnection connection = uri.startsWith("https") ? (HttpsURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection(); + + // Set up the connection properties + connection.setDoOutput(true); // We're sending data with the request + connection.setRequestMethod(method); // Set the HTTP method + connection.setUseCaches(USE_CACHES); // Use caching if enabled + connection.setConnectTimeout(CONNECT_TIMEOUT); // Set the connection timeout + connection.setReadTimeout(READ_TIMEOUT); // Set the read timeout + + // Set the Content-Type header to application/json + connection.setRequestProperty("Content-Type", "application/json"); + + // If an authorization token is provided, add it to the request headers + if (authorization != null) { + connection.setRequestProperty("Authorization", authorization); + } + + // Add the User-Agent and Origin headers + connection.setRequestProperty("User-Agent", getUserAgent(config)); + connection.setRequestProperty("Origin", "android:com.prey"); + + // Connect to the server + connection.connect(); + + // If we have JSON data to send, write it to the output stream + if (jsonParam != null) { + OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); + writer.write(jsonParam.toString()); + writer.close(); + } + + // Get the response code from the server + int responseCode = connection.getResponseCode(); + + // Handle the response code + switch (responseCode) { + case HttpURLConnection.HTTP_CREATED: + case HttpURLConnection.HTTP_OK: + // If the response was successful, convert it to a PreyHttpResponse object and exit the loop + response = convertPreyHttpResponse(responseCode, connection); + retryCount = RETRIES; // exit loop + break; + default: + // If the response was not successful, increment the retry count and delay before retrying + retryCount++; + shouldDelay = true; + } + + // Disconnect from the server + connection.disconnect(); + } catch (Exception e) { + // Log any errors that occur during the request + PreyLogger.e(String.format("Error connecting to url:%s error:" , uri, e.getMessage()), e); } - } catch (Exception e) { - PreyLogger.e(String.format("postJson error:%s", e.getMessage()), e); } + + // Return the response from the server return response; } diff --git a/app/src/main/java/com/prey/workers/IncrementWorker.java b/app/src/main/java/com/prey/workers/IncrementWorker.java index 40c0561b..7af4e476 100644 --- a/app/src/main/java/com/prey/workers/IncrementWorker.java +++ b/app/src/main/java/com/prey/workers/IncrementWorker.java @@ -17,25 +17,44 @@ import com.prey.PreyLogger; import com.prey.actions.aware.AwareController; +/** + * A Worker class responsible for incrementing a value and handling AwareController initialization. + */ public class IncrementWorker extends Worker { + /** + * Constructor for IncrementWorker. + * + * @param context the application context + * @param params the worker parameters + */ public IncrementWorker( @NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } + /** + * Performs the work for this Worker. + * + * @return Result.success() if the work is successful, Result.failure() otherwise + */ @Override public Result doWork() { + // Log a debug message to indicate the start of the work PreyLogger.d("AWARE WORK doWork"); + // Get the application context Context context = getApplicationContext(); try { + // Check if it's time to run the AwareController if (PreyConfig.getPreyConfig(context).isTimeNextAware()) { + // Create a new thread to run the AwareController initialization new Thread() { public void run() { + // Initialize the AwareController new AwareController().init(context); } - }.start(); + }.start(); // Start the thread } return Result.success(); } catch (NumberFormatException e) { diff --git a/app/src/main/java/com/prey/workers/PreyWorker.java b/app/src/main/java/com/prey/workers/PreyWorker.java index 0f3ddc7c..1bcbbe09 100644 --- a/app/src/main/java/com/prey/workers/PreyWorker.java +++ b/app/src/main/java/com/prey/workers/PreyWorker.java @@ -14,14 +14,25 @@ import java.util.concurrent.TimeUnit; +/** + * This class represents a worker that starts a periodic worker to run every 15 minutes, with a 5 minute flex period. + */ public class PreyWorker { private static PreyWorker _instance = null; public static final String INCREMENT_WORK_NAME = "prey_increment_work"; + /** + * Private constructor to prevent instantiation of this class. + */ private PreyWorker() { } + /** + * Returns the singleton instance of the PreyWorker. + * + * @return the singleton instance of PreyWorker + */ public static PreyWorker getInstance() { if (_instance == null) _instance = new PreyWorker(); @@ -35,14 +46,17 @@ public static PreyWorker getInstance() { public void startPeriodicWork(Context context) { WorkManager workManager = WorkManager.getInstance(context); workManager.cancelAllWorkByTag(INCREMENT_WORK_NAME); - PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder( + // Create a PeriodicWorkRequest builder + PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder( IncrementWorker.class, 15, TimeUnit.MINUTES, 5, TimeUnit.MINUTES) - .addTag(INCREMENT_WORK_NAME) - .build(); + .addTag(INCREMENT_WORK_NAME); + // Build the PeriodicWorkRequest + PeriodicWorkRequest workRequest = builder.build(); + // Enqueue the work request workManager.enqueue(workRequest); } From aec7098871b025197af9a809775c17542b6e871c Mon Sep 17 00:00:00 2001 From: Orlando Aliaga Date: Fri, 11 Oct 2024 10:34:54 -0300 Subject: [PATCH 10/10] HTTP_CREATED added HTTP_CREATED added --- app/src/main/java/com/prey/net/UtilConnection.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/src/main/java/com/prey/net/UtilConnection.java b/app/src/main/java/com/prey/net/UtilConnection.java index 886e99f8..e32ab158 100644 --- a/app/src/main/java/com/prey/net/UtilConnection.java +++ b/app/src/main/java/com/prey/net/UtilConnection.java @@ -458,6 +458,10 @@ public static PreyHttpResponse connectionJson(PreyConfig config, String uri, Str // Handle the response code switch (responseCode) { case HttpURLConnection.HTTP_CREATED: + // If the response was successful, convert it to a PreyHttpResponse object and exit the loop + response = convertPreyHttpResponse(responseCode, connection); + retryCount = RETRIES; // exit loop + break; case HttpURLConnection.HTTP_OK: // If the response was successful, convert it to a PreyHttpResponse object and exit the loop response = convertPreyHttpResponse(responseCode, connection);