diff --git a/app/build.gradle b/app/build.gradle index d6b6a697..dda1d5b5 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -12,8 +12,8 @@ android { targetSdkVersion 33 - versionCode 323 - versionName '2.5.1' + versionCode 324 + versionName '2.5.2' multiDexEnabled true diff --git a/app/src/main/java/com/prey/FileConfigReader.java b/app/src/main/java/com/prey/FileConfigReader.java index ed68f1e0..f19fd7af 100644 --- a/app/src/main/java/com/prey/FileConfigReader.java +++ b/app/src/main/java/com/prey/FileConfigReader.java @@ -183,4 +183,13 @@ public String getPreyForgot() { public boolean getOpenPin() { return Boolean.parseBoolean(properties.getProperty("open-pin")); } + + /** + * Method returns logger maximum + * @return logger_max + */ + public int getLoggerMax() { + return Integer.parseInt(properties.getProperty("logger-max")); + } + } \ No newline at end of file diff --git a/app/src/main/java/com/prey/PreyApp.java b/app/src/main/java/com/prey/PreyApp.java index 520595e3..732e9560 100644 --- a/app/src/main/java/com/prey/PreyApp.java +++ b/app/src/main/java/com/prey/PreyApp.java @@ -19,6 +19,7 @@ import com.prey.actions.aware.AwareController; import com.prey.actions.fileretrieval.FileretrievalController; import com.prey.actions.geofences.GeofenceController; +import com.prey.actions.logger.LoggerController; import com.prey.actions.report.ReportScheduled; import com.prey.actions.triggers.TriggerController; import com.prey.activities.LoginActivity; diff --git a/app/src/main/java/com/prey/PreyConfig.java b/app/src/main/java/com/prey/PreyConfig.java index 3e1e45bf..915ec0ab 100644 --- a/app/src/main/java/com/prey/PreyConfig.java +++ b/app/src/main/java/com/prey/PreyConfig.java @@ -41,7 +41,7 @@ public class PreyConfig { private static PreyConfig cachedInstance = null; public static final String TAG = "PREY"; private static final String HTTP = "https://"; - public static final String VERSION_PREY_DEFAULT = "2.4.9"; + public static final String VERSION_PREY_DEFAULT = "2.5.2"; // Milliseconds per second private static final int MILLISECONDS_PER_SECOND = 1000; // Set to 1000 * 60 in production. @@ -1610,4 +1610,15 @@ public void setDenyNotification(boolean denyNotification) { public boolean getDenyNotification() { return getBoolean(PreyConfig.DENY_NOTIFICATION, false); } -} + + public static final String LOGGER_ID = "LOGGER_ID"; + + public void setLoggerId(int loggerId){ + saveInt(PreyConfig.LOGGER_ID, loggerId); + } + + public int getLoggerId(){ + return getInt(PreyConfig.LOGGER_ID, 1); + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/HttpDataService.java b/app/src/main/java/com/prey/actions/HttpDataService.java index bf7cf8a7..16119c42 100644 --- a/app/src/main/java/com/prey/actions/HttpDataService.java +++ b/app/src/main/java/com/prey/actions/HttpDataService.java @@ -11,8 +11,12 @@ import java.util.List; import java.util.Map; +import com.prey.PreyLogger; import com.prey.net.http.EntityFile; +import org.json.JSONException; +import org.json.JSONObject; + public class HttpDataService { private String key; @@ -72,6 +76,30 @@ public HashMap getDataAsParameters() { return parameters; } + /** + * Method to transform parameter list into json + * + * @return json + */ + public JSONObject getDataJson() { + JSONObject json = new JSONObject(); + try { + if (isList()) { + JSONObject jsonList = new JSONObject(); + for (String valueKey : dataList.keySet()) { + String valueData = dataList.get(valueKey); + jsonList.put(valueKey, valueData); + } + json.put(key, jsonList); + } else { + json.put(key, singleData); + } + } catch (JSONException e) { + PreyLogger.e(String.format("error getDataJson:%s", e.getMessage()), e); + } + return json; + } + public String getDataAsString() { StringBuffer sb = new StringBuffer(); if (isList()) { diff --git a/app/src/main/java/com/prey/actions/fileretrieval/FileretrievalOpenHelper.java b/app/src/main/java/com/prey/actions/fileretrieval/FileretrievalOpenHelper.java index 0f2f9f1a..75fcd6f3 100644 --- a/app/src/main/java/com/prey/actions/fileretrieval/FileretrievalOpenHelper.java +++ b/app/src/main/java/com/prey/actions/fileretrieval/FileretrievalOpenHelper.java @@ -116,8 +116,9 @@ public List getAllFileretrieval() { list.add(dto); } while (cursor.moveToNext()); } + database.close(); }catch (Exception e){ - PreyLogger.e("Error:"+e.getMessage(),e); + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); }finally { if(cursor!=null){ try{cursor.close();}catch (Exception e1){} @@ -142,8 +143,9 @@ public FileretrievalDto getFileretrieval(String id) { dto.setStatus(cursor.getInt(3)); } while (cursor.moveToNext()); } + database.close(); }catch (Exception e){ - PreyLogger.e("Error:"+e.getMessage(),e); + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); }finally { if(cursor!=null){ try{cursor.close();}catch (Exception e1){} 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 67ff982a..4236fdf2 100644 --- a/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java +++ b/app/src/main/java/com/prey/actions/geofences/GeofenceOpenHelper.java @@ -140,8 +140,9 @@ public List getAllGeofences() { list.add(geofence); } while (cursor.moveToNext()); } + database.close(); }catch (Exception e){ - PreyLogger.e("error:"+e.getMessage(),e); + PreyLogger.e(String.format("error:%s", e.getMessage()), e); }finally { if(cursor!=null){ try{cursor.close();}catch (Exception e1){} @@ -169,8 +170,9 @@ public GeofenceDto getGeofence(String id) { geofence.setExpires(cursor.getInt(6)); } while (cursor.moveToNext()); } + database.close(); }catch (Exception e){ - PreyLogger.e("error:"+e.getMessage(),e); + PreyLogger.e(String.format("error:%s", e.getMessage()), e); }finally { if(cursor!=null){ try{cursor.close();}catch (Exception e1){} 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 c1e13162..30c887ce 100644 --- a/app/src/main/java/com/prey/actions/location/LocationUtil.java +++ b/app/src/main/java/com/prey/actions/location/LocationUtil.java @@ -26,6 +26,7 @@ import com.google.android.gms.tasks.OnSuccessListener; import com.prey.PreyConfig; import com.prey.PreyLogger; +import com.prey.PreyPermission; import com.prey.actions.HttpDataService; import com.prey.actions.geofences.GeofenceController; import com.prey.json.UtilJson; @@ -33,6 +34,8 @@ import com.prey.net.PreyWebServices; import com.prey.services.LocationService; +import org.json.JSONObject; + public class LocationUtil { public static final String LAT = "lat"; @@ -71,10 +74,18 @@ public static PreyLocation getLocation(Context ctx, String messageId, boolean as boolean isGpsEnabled = PreyLocationManager.getInstance(ctx).isGpsLocationServiceActive(); boolean isNetworkEnabled = PreyLocationManager.getInstance(ctx).isNetworkLocationServiceActive(); boolean isWifiEnabled = PreyWifiManager.getInstance(ctx).isWifiEnabled(); - boolean isGooglePlayServicesAvailable=isGooglePlayServicesAvailable(ctx); - String locationInfo="{\"gps\":" + isGpsEnabled + ",\"net\":" + isNetworkEnabled + ",\"wifi\":" + isWifiEnabled+",\"play\":"+isGooglePlayServicesAvailable+"}"; - PreyConfig.getPreyConfig(ctx).setLocationInfo(locationInfo); - PreyLogger.d(locationInfo); + boolean isGooglePlayServicesAvailable = isGooglePlayServicesAvailable(ctx); + boolean canAccessBackgroundLocation = PreyPermission.canAccessBackgroundLocationView(ctx); + boolean canAccessFineLocation = PreyPermission.canAccessFineLocation(ctx); + boolean canAccessCoarseLocation = PreyPermission.canAccessCoarseLocation(ctx); + JSONObject json = new JSONObject(); + json.put("location", (canAccessFineLocation || canAccessCoarseLocation)); + json.put("location_background", canAccessBackgroundLocation); + json.put("gps", isGpsEnabled); + json.put("net", isNetworkEnabled); + json.put("wifi", isWifiEnabled); + json.put("play", isGooglePlayServicesAvailable); + PreyConfig.getPreyConfig(ctx).setLocationInfo(json.toString()); String method = getMethod(isGpsEnabled, isNetworkEnabled); try { preyLocation = getPreyLocationAppService(ctx, method, asynchronous, preyLocation, maximum); diff --git a/app/src/main/java/com/prey/actions/logger/LoggerController.java b/app/src/main/java/com/prey/actions/logger/LoggerController.java new file mode 100644 index 00000000..d9795d09 --- /dev/null +++ b/app/src/main/java/com/prey/actions/logger/LoggerController.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2023 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.logger; + +import android.content.Context; + +import com.prey.FileConfigReader; +import com.prey.PreyConfig; +import com.prey.PreyLogger; +import com.prey.events.Event; + +import org.json.JSONObject; + +import java.io.File; +import java.util.Date; +import java.util.Map; + +public class LoggerController { + + private Context ctx; + private static LoggerController INSTANCE; + + public static LoggerController getInstance(Context ctx) { + if (INSTANCE == null) { + INSTANCE = new LoggerController(ctx); + } + return INSTANCE; + } + + private final String CMD = "CMD"; + private final String ACTION = "ACTION"; + private final String DATA = "DATA"; + private final String REPORT = "REPORT"; + private final String UPLOAD = "UPLOAD"; + private final String GEOFENCING = "GEOFENCING"; + private final String EVENTS = "EVENTS"; + private final String TREE = "TREE"; + + private int maxLogger; + + private LoggerController(Context context) { + ctx = context; + try { + maxLogger = FileConfigReader.getInstance(context).getLoggerMax(); + } catch (Exception e) { + maxLogger = 500; + } + sequence = PreyConfig.getPreyConfig(context).getLoggerId(); + } + + private int sequence = 1; + + public synchronized int getSequence(Context context) { + sequence++; + PreyConfig.getPreyConfig(context).setLoggerId(sequence); + return sequence; + } + + /** + * Method to register logger + * + * @param type + * @param txt + */ + public void addLogger(String type, String txt) { + int loggerID = getSequence(ctx); + LoggerDto dto = new LoggerDto(); + dto.setType(type); + dto.setTxt(txt); + dto.setLoggerId(loggerID); + dto.setTime(new Date().toGMTString()); + LoggerDatasource datasource = new LoggerDatasource(ctx); + try { + datasource.createLogger(dto); + } catch (Exception e) { + PreyLogger.e(String.format("logger error:%s", e.getMessage()), e); + } + if (loggerID > maxLogger) { + datasource.deleteMinorsLogger(loggerID - maxLogger); + } + PreyLogger.d(String.format("logger dto:%s", dto.toString())); + } + + public void addComands(String commands) { + addLogger(CMD, commands); + } + + public void addData(JSONObject json) { + addLogger(DATA, json.toString()); + } + + public void addTree(JSONObject json) { + addLogger(TREE, json.toString()); + } + + public void addEvents(Event event, JSONObject json) { + JSONObject newJson = new JSONObject(); + try { + newJson.put("name", event.getName()); + newJson.put("info", event.getInfo()); + newJson.put("status", json); + } catch (Exception e) { + PreyLogger.e(String.format("error addEvents:%s", e.getMessage()), e); + } + addLogger(EVENTS, newJson.toString()); + } + + public void addReport(JSONObject json) { + addLogger(REPORT, json.toString()); + + } + + public void addGeofencing(String json) { + try { + addLogger(GEOFENCING, json.toString()); + } catch (Exception e) { + addLogger(GEOFENCING, json); + } + } + + public void addUpload(File file, int responseCode) { + JSONObject newJson = new JSONObject(); + try { + newJson.put("name", file.getName()); + newJson.put("length", file.length()); + newJson.put("responseCode", responseCode); + } catch (Exception e) { + PreyLogger.e(String.format("error addUpload:%s", e.getMessage()), e); + } + addLogger(UPLOAD, newJson.toString()); + } + + public void addActionResult(String status, Map params) { + JSONObject json = new JSONObject(); + try { + json.put("command", params.get("command")); + json.put("target", params.get("target")); + json.put("status", params.get("status")); + if (params.containsKey("reason")) { + String reason = params.get("reason"); + try { + JSONObject jsonReason = new JSONObject(reason); + json.put("reason", jsonReason); + } catch (Exception e) { + json.put("reason", reason); + } + } + addLogger(ACTION, json.toString()); + } catch (Exception e) { + PreyLogger.e(String.format("error addActionResult:%s", e.getMessage()), e); + } + } + + public void deleteAllLogger() { + LoggerDatasource datasource = new LoggerDatasource(ctx); + datasource.deleteAllLogger(); + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/logger/LoggerDatasource.java b/app/src/main/java/com/prey/actions/logger/LoggerDatasource.java new file mode 100644 index 00000000..d5eca821 --- /dev/null +++ b/app/src/main/java/com/prey/actions/logger/LoggerDatasource.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2023 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.logger; + +import android.content.Context; + +import com.prey.PreyLogger; + +import java.util.List; + +public class LoggerDatasource { + + private LoggerOpenHelper dbHelper; + + public LoggerDatasource(Context context) { + dbHelper = new LoggerOpenHelper(context); + } + + public void createLogger(LoggerDto dto) { + try { + dbHelper.insertLogger(dto); + } catch (Exception e) { + try { + dbHelper.updateLogger(dto); + } catch (Exception e1) { + PreyLogger.e(String.format("error db update:%s", e1.getMessage()), e1); + } + } + } + + public void deleteLogger(int id) { + dbHelper.deleteLogger(id); + } + + public List getAllLogger() { + return dbHelper.getAllLogger(); + } + + public LoggerDto getLogger(int id) { + return dbHelper.getLogger(id); + } + + public void deleteAllLogger() { + dbHelper.deleteAllLogger(); + } + + public void deleteMinorsLogger(int id) { + dbHelper.deleteMinorsLogger(id); + } +} diff --git a/app/src/main/java/com/prey/actions/logger/LoggerDto.java b/app/src/main/java/com/prey/actions/logger/LoggerDto.java new file mode 100644 index 00000000..1aa2d1de --- /dev/null +++ b/app/src/main/java/com/prey/actions/logger/LoggerDto.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2023 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.logger; + +public class LoggerDto { + + private int loggerId; + private String txt; + private String type; + private String time; + + public int getLoggerId() { + return loggerId; + } + + public void setLoggerId(int loggerId) { + this.loggerId = loggerId; + } + + public String getTxt() { + return txt; + } + + public void setTxt(String txt) { + this.txt = txt; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("loggerId:").append(loggerId).append(","); + sb.append("txt:").append(txt).append(","); + sb.append("type:").append(type); + return sb.toString(); + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/logger/LoggerOpenHelper.java b/app/src/main/java/com/prey/actions/logger/LoggerOpenHelper.java new file mode 100644 index 00000000..cafa1737 --- /dev/null +++ b/app/src/main/java/com/prey/actions/logger/LoggerOpenHelper.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2023 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.actions.logger; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; + +import com.prey.PreyLogger; + +import java.util.ArrayList; +import java.util.List; + +public class LoggerOpenHelper extends SQLiteOpenHelper { + + private static final int DATABASE_VERSION = 1; + private static final String DATABASE_NAME = "PreyLogger.db"; + public static final String LOGGER_TABLE_NAME = "prey_logger"; + public static final String COLUMN_LOGGERID = "_logger_id"; + public static final String COLUMN_TYPE = "_type"; + public static final String COLUMN_TIME = "_time"; + public static final String COLUMN_TXT = "_txt"; + + private static final String LOGGER_TABLE_CREATE = + "CREATE TABLE ".concat(LOGGER_TABLE_NAME).concat(" (").concat( + COLUMN_LOGGERID).concat(" INTEGER PRIMARY KEY, ").concat( + COLUMN_TXT).concat(" TEXT,").concat( + COLUMN_TIME).concat(" TEXT,").concat( + COLUMN_TYPE).concat(" TEXT").concat( + ");"); + + public LoggerOpenHelper(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + try { + db.execSQL(LOGGER_TABLE_CREATE); + } catch (Exception e) { + PreyLogger.e(String.format("Error creating table:%s", e.getMessage()), e); + } + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + try { + db.execSQL("DROP TABLE IF EXISTS ".concat(LOGGER_TABLE_NAME)); + } catch (Exception e) { + PreyLogger.e(String.format("error drop table:%s", e.getMessage()), e); + } + onCreate(db); + } + + public void insertLogger(LoggerDto dto) { + PreyLogger.d("___db insertLogger"); + SQLiteDatabase database = this.getWritableDatabase(); + ContentValues values = new ContentValues(); + values.put(COLUMN_LOGGERID, dto.getLoggerId()); + values.put(COLUMN_TXT, dto.getTxt()); + values.put(COLUMN_TYPE, dto.getType()); + values.put(COLUMN_TIME, dto.getTime()); + PreyLogger.d(String.format("___db insert:%s", dto.toString())); + database.insert(LOGGER_TABLE_NAME, null, values); + database.close(); + } + + public void updateLogger(LoggerDto dto) { + SQLiteDatabase database = this.getWritableDatabase(); + ContentValues values = new ContentValues(); + values.put(COLUMN_TXT, dto.getTxt()); + values.put(COLUMN_TYPE, dto.getType()); + values.put(COLUMN_TIME, dto.getTime()); + String selection = COLUMN_LOGGERID + " = ?"; + String[] selectionArgs = {String.valueOf(dto.getLoggerId())}; + PreyLogger.d(String.format("___db update:%s", dto.toString())); + database.update(LOGGER_TABLE_NAME, values, selection, selectionArgs); + database.close(); + } + + public void deleteLogger(int id) { + SQLiteDatabase database = this.getWritableDatabase(); + String deleteQuery = "DELETE FROM ".concat(LOGGER_TABLE_NAME).concat(" where ").concat(COLUMN_LOGGERID).concat("=").concat(String.valueOf(id)); + PreyLogger.d(String.format("___db query:%s", deleteQuery)); + database.execSQL(deleteQuery); + database.close(); + } + + public void deleteMinorsLogger(int id) { + SQLiteDatabase database = this.getWritableDatabase(); + String deleteQuery = "DELETE FROM ".concat(LOGGER_TABLE_NAME).concat(" where ").concat(COLUMN_LOGGERID).concat("<").concat(String.valueOf(id)); + PreyLogger.d(String.format("___db query:%s", deleteQuery)); + database.execSQL(deleteQuery); + database.close(); + } + + public void deleteAllLogger() { + SQLiteDatabase database = this.getWritableDatabase(); + String deleteQuery = "DELETE FROM ".concat(LOGGER_TABLE_NAME); + PreyLogger.d(String.format("___db query:%s", deleteQuery)); + database.execSQL(deleteQuery); + database.close(); + } + + public List getAllLogger() { + Cursor cursor = null; + List list = new ArrayList(); + try { + String selectQuery = "SELECT * FROM ".concat(LOGGER_TABLE_NAME); + SQLiteDatabase database = this.getReadableDatabase(); + cursor = database.rawQuery(selectQuery, null); + if (cursor.moveToFirst()) { + do { + LoggerDto dto = new LoggerDto(); + dto.setLoggerId(cursor.getInt(0)); + dto.setTxt(cursor.getString(1)); + dto.setTime(cursor.getString(2)); + dto.setType(cursor.getString(3)); + list.add(dto); + } while (cursor.moveToNext()); + } + database.close(); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } finally { + if (cursor != null) { + try { + cursor.close(); + } catch (Exception e1) { + } + } + } + return list; + } + + public LoggerDto getLogger(int id) { + Cursor cursor = null; + LoggerDto dto = null; + try { + SQLiteDatabase database = this.getReadableDatabase(); + String selectQuery = "SELECT * FROM ".concat(LOGGER_TABLE_NAME).concat(" where ").concat(COLUMN_LOGGERID).concat("='").concat(String.valueOf(id)).concat("'"); + cursor = database.rawQuery(selectQuery, null); + if (cursor.moveToFirst()) { + do { + dto = new LoggerDto(); + dto.setLoggerId(cursor.getInt(0)); + dto.setTxt(cursor.getString(1)); + dto.setTime(cursor.getString(2)); + dto.setType(cursor.getString(3)); + } while (cursor.moveToNext()); + } + database.close(); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } finally { + if (cursor != null) { + try { + cursor.close(); + } catch (Exception e1) { + PreyLogger.e(String.format("Error:%s", e1.getMessage()), e1); + } + } + } + return dto; + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/actions/picture/PictureUtil.java b/app/src/main/java/com/prey/actions/picture/PictureUtil.java index e702909d..208dba83 100644 --- a/app/src/main/java/com/prey/actions/picture/PictureUtil.java +++ b/app/src/main/java/com/prey/actions/picture/PictureUtil.java @@ -127,6 +127,7 @@ public static HttpDataService getPicture(Context ctx) { currentVolume = PreyConfig.getPreyConfig(ctx).getVolume(); if (currentVolume > 0) { //set old volume + mgr = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE); mgr.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND); } } catch (Exception e) { diff --git a/app/src/main/java/com/prey/actions/triggers/TriggerOpenHelper.java b/app/src/main/java/com/prey/actions/triggers/TriggerOpenHelper.java index fd8adf82..a6d262b4 100644 --- a/app/src/main/java/com/prey/actions/triggers/TriggerOpenHelper.java +++ b/app/src/main/java/com/prey/actions/triggers/TriggerOpenHelper.java @@ -115,8 +115,9 @@ public List getAllTriggers() { list.add(trigger); } while (cursor.moveToNext()); } + database.close(); } catch (Exception e) { - PreyLogger.e("error:" + e.getMessage(), e); + PreyLogger.e(String.format("error:%s", e.getMessage()), e); } finally { if (cursor != null) { try { @@ -144,8 +145,9 @@ public TriggerDto getTrigger(String id) { trigger.setActions(cursor.getString(3)); } while (cursor.moveToNext()); } + database.close(); } catch (Exception e) { - PreyLogger.e("error:" + e.getMessage(), e); + PreyLogger.e(String.format("error:%s", e.getMessage()), e); } finally { if (cursor != null) { try { diff --git a/app/src/main/java/com/prey/json/UtilJson.java b/app/src/main/java/com/prey/json/UtilJson.java index 3cb04fa0..f015b11c 100644 --- a/app/src/main/java/com/prey/json/UtilJson.java +++ b/app/src/main/java/com/prey/json/UtilJson.java @@ -9,8 +9,10 @@ import com.prey.PreyLogger; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -117,4 +119,41 @@ public static int getInt(JSONObject jsonObject, String key) throws JSONException return out; } + /** + * Method merge the json + * + * @param json1 + * @param json2 + * @return json merge + */ + public static JSONObject merge(JSONObject json1, JSONObject json2) { + try { + Iterator it = json2.keys(); + while (it.hasNext()) { + String key = it.next(); + json1.put(key, json2.get(key)); + } + } catch (Exception e) { + PreyLogger.e(String.format("error merge:%s", e.getMessage()), e); + } + return json1; + } + + /** + * Method add json2 in json1 with key name + * + * @param json1 + * @param name + * @param json2 + * @return json merge + */ + public static JSONObject merge(JSONObject json1, String name, JSONArray json2) { + try { + json1.put(name, json2); + } catch (Exception e) { + PreyLogger.e(String.format("error merge:%s", e.getMessage()), e); + } + return json1; + } + } \ No newline at end of file diff --git a/app/src/main/java/com/prey/json/actions/ListPermissions.java b/app/src/main/java/com/prey/json/actions/ListPermissions.java new file mode 100644 index 00000000..30af1d0d --- /dev/null +++ b/app/src/main/java/com/prey/json/actions/ListPermissions.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2024 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.json.actions; + +import android.content.Context; + +import com.prey.PreyLogger; +import com.prey.PreyPermission; +import com.prey.actions.observer.ActionResult; +import com.prey.backwardcompatibility.FroyoSupport; +import com.prey.events.Event; +import com.prey.events.manager.EventThread; +import com.prey.json.UtilJson; +import com.prey.net.PreyWebServices; + +import org.json.JSONObject; + +import java.util.List; + +public class ListPermissions { + + public void start(Context ctx, List list, JSONObject parameters) { + get(ctx, list, parameters); + } + + /** + * Method collects all permissions + * + * @param ctx + * @param list + * @param parameters + */ + public void get(Context ctx, List list, JSONObject parameters) { + String messageId = null; + String reason = null; + try { + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "processed", messageId, UtilJson.makeMapParam("start", "list_permissions", "started", reason)); + boolean canAccessFineLocation = PreyPermission.canAccessFineLocation(ctx); + boolean canAccessCoarseLocation = PreyPermission.canAccessCoarseLocation(ctx); + boolean canAccessCamera = PreyPermission.canAccessCamera(ctx); + boolean canAccessStorage = PreyPermission.canAccessStorage(ctx); + boolean canAccessBackgroundLocation = PreyPermission.canAccessBackgroundLocationView(ctx); + boolean canDrawOverlays = PreyPermission.canDrawOverlays(ctx); + boolean canAccessibility = PreyPermission.isAccessibilityServiceView(ctx); + boolean isAdminActive = FroyoSupport.getInstance(ctx).isAdminActive(); + boolean notification = !PreyPermission.areNotificationsEnabled(ctx); + JSONObject info = new JSONObject(); + info.put("location", (canAccessFineLocation || canAccessCoarseLocation)); + info.put("location_background", canAccessBackgroundLocation); + info.put("camera", canAccessCamera); + info.put("storage", canAccessStorage); + info.put("admin", isAdminActive); + info.put("draw_overlays", canDrawOverlays); + info.put("accessibility", canAccessibility); + info.put("notification", notification); + PreyLogger.d(String.format("list_permission:%s", info.toString())); + Event event = new Event(); + event.setName("list_permission"); + event.setInfo(info.toString()); + JSONObject jsonObjectStatus = new JSONObject(); + PreyLogger.d(info.toString()); + new EventThread(ctx, event, jsonObjectStatus).start(); + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "processed", messageId, UtilJson.makeMapParam("start", "list_permissions", "stopped", reason)); + } catch (Exception e) { + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "failed", messageId, UtilJson.makeMapParam("start", "list_permissions", "failed", e.toString())); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/json/actions/Logretrieval.java b/app/src/main/java/com/prey/json/actions/Logretrieval.java new file mode 100644 index 00000000..30c9e082 --- /dev/null +++ b/app/src/main/java/com/prey/json/actions/Logretrieval.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Created by Orlando Aliaga + * Copyright 2024 Prey Inc. All rights reserved. + * License: GPLv3 + * Full license at "/LICENSE" + ******************************************************************************/ +package com.prey.json.actions; + +import android.content.Context; + +import com.prey.PreyConfig; +import com.prey.PreyLogger; +import com.prey.actions.logger.LoggerDatasource; +import com.prey.actions.logger.LoggerDto; +import com.prey.actions.observer.ActionResult; +import com.prey.json.UtilJson; +import com.prey.net.PreyWebServices; + +import org.json.JSONObject; + +import java.util.List; + +public class Logretrieval { + + public void start(Context ctx, List list, JSONObject parameters) { + get(ctx, list, parameters); + } + + /** + * Method retrieves the last logger + * + * @param ctx + * @param list + * @param parameters + */ + public void get(Context ctx, List list, JSONObject parameters) { + String messageId = null; + try { + messageId = UtilJson.getString(parameters, PreyConfig.MESSAGE_ID); + PreyLogger.d(String.format("messageId:%s", messageId)); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + String reason = null; + LoggerDatasource datasource = new LoggerDatasource(ctx); + List loggers = datasource.getAllLogger(); + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "processed", messageId, UtilJson.makeMapParam("get", "logretrieval", "started", reason)); + StringBuffer sb = new StringBuffer(); + for (int i = 0; loggers != null && i < loggers.size(); i++) { + LoggerDto dto = loggers.get(i); + if (!dto.getTxt().contains("[]")) { + sb.append("info").append(dto.getTime()).append("[").append(dto.getType()).append("]:").append(dto.getTxt()).append("\n"); + } + } + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "processed", messageId, UtilJson.makeMapParam("get", "logretrieval", "stopped", reason)); + try { + PreyWebServices.getInstance().uploadLogger(ctx, sb.toString()); + } catch (Exception e) { + PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, "failed", messageId, UtilJson.makeMapParam("start", "logretrieval", "failed", e.toString())); + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/prey/json/actions/Tree.java b/app/src/main/java/com/prey/json/actions/Tree.java index f4c08d7d..c731264b 100644 --- a/app/src/main/java/com/prey/json/actions/Tree.java +++ b/app/src/main/java/com/prey/json/actions/Tree.java @@ -12,6 +12,8 @@ import com.prey.PreyConfig; import com.prey.PreyLogger; +import com.prey.PreyPermission; +import com.prey.actions.logger.LoggerController; import com.prey.actions.observer.ActionResult; import com.prey.json.UtilJson; import com.prey.net.PreyHttpResponse; @@ -58,14 +60,23 @@ public void get(Context ctx, List list, JSONObject parameters) { File dir = new File(pathBase+path); JSONArray array = getFilesRecursiveJSON(pathBase, dir, depth-1); JSONObject jsonTree = new JSONObject(); - jsonTree.put("tree", array.toString()); + jsonTree.put("tree", array); + boolean canAccessStorage = PreyPermission.canAccessStorage(ctx); + try { + JSONObject info = new JSONObject(); + info.put("storage", canAccessStorage); + jsonTree.put("permissions", info); + } catch (Exception e) { + PreyLogger.e(String.format("error:%s", e.getMessage()), e); + } + LoggerController.getInstance(ctx).addTree(jsonTree); PreyHttpResponse response=PreyWebServices.getInstance().sendTree(ctx, jsonTree); PreyLogger.d(String.format("Tree stopped response:%d", response.getStatusCode())); PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, UtilJson.makeMapParam("get", "tree", "stopped",reason)); PreyLogger.d("Tree stopped"); } catch (Exception e) { PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx, messageId, UtilJson.makeMapParam("get", "tree", "failed", e.getMessage())); - PreyLogger.d("Tree failed:"+e.getMessage()); + PreyLogger.e(String.format("Tree failed:%s", e.getMessage()), e); } } diff --git a/app/src/main/java/com/prey/json/parser/JSONParser.java b/app/src/main/java/com/prey/json/parser/JSONParser.java index 864113bf..724cd75c 100644 --- a/app/src/main/java/com/prey/json/parser/JSONParser.java +++ b/app/src/main/java/com/prey/json/parser/JSONParser.java @@ -16,6 +16,7 @@ import android.content.Context; import com.prey.PreyLogger; +import com.prey.actions.logger.LoggerController; import com.prey.net.PreyHttpResponse; import com.prey.net.PreyRestHttpClient; @@ -48,6 +49,8 @@ public List getJSONFromUrl(Context ctx, String uri) { PreyLogger.d("_______cmd________"); PreyLogger.d(sb); } + //json = "[{\"command\":\"get\",\"target\":\"logretrieval\",\"options\":{}}]"; + //json = "[{\"command\":\"start\",\"target\":\"list_permissions\",\"options\":{}}]"; //json = "[{\"command\":\"history\",\"target\":\"call\",\"options\":{}}]"; //json = "[{\"command\":\"history\",\"target\":\"sms\",\"options\":{}}]"; //json = "[{\"command\":\"history\",\"target\":\"contact\",\"options\":{}}]"; @@ -89,6 +92,7 @@ public List getJSONFromUrl(Context ctx, String uri) { if ("Invalid.".equals(json)) { return null; } + LoggerController.getInstance(ctx).addComands(json); return getJSONFromTxt(ctx, json); } diff --git a/app/src/main/java/com/prey/net/PreyRestHttpClient.java b/app/src/main/java/com/prey/net/PreyRestHttpClient.java index 7e613445..36dd2569 100644 --- a/app/src/main/java/com/prey/net/PreyRestHttpClient.java +++ b/app/src/main/java/com/prey/net/PreyRestHttpClient.java @@ -170,6 +170,18 @@ public int uploadFile(Context ctx,String url, File file,long total) { return UtilConnection.uploadFile(PreyConfig.getPreyConfig(ctx), url, file,total); } + /** + * Method to upload logger + * + * @param ctx + * @param url + * @param text + * @return PreyHttpResponse + */ + public PreyHttpResponse uploadLogger(Context ctx, String url, String text) { + return UtilConnection.uploadLogger(ctx, url, text); + } + public PreyHttpResponse connectionPostAuthorizationCorrelationId(String url, String status, Map params,String correlationId) throws Exception { PreyLogger.d("Sending using 'POST' - URI: " + url + " - parameters: " + params.toString()+" status:"+status+" correlationId:"+correlationId); PreyHttpResponse response=UtilConnection.connectionPostAuthorizationCorrelationId(PreyConfig.getPreyConfig(ctx),url,params,CONTENT_TYPE_URL_ENCODED,status,correlationId); diff --git a/app/src/main/java/com/prey/net/PreyWebServices.java b/app/src/main/java/com/prey/net/PreyWebServices.java index b8df7b4f..91d49e28 100644 --- a/app/src/main/java/com/prey/net/PreyWebServices.java +++ b/app/src/main/java/com/prey/net/PreyWebServices.java @@ -32,6 +32,7 @@ import com.prey.PreyConfig; import com.prey.PreyLogger; import com.prey.PreyName; +import com.prey.PreyPermission; import com.prey.PreyPhone; import com.prey.PreyPhone.Hardware; import com.prey.PreyPhone.Wifi; @@ -39,10 +40,12 @@ import com.prey.PreyVerify; import com.prey.actions.HttpDataService; import com.prey.actions.fileretrieval.FileretrievalDto; +import com.prey.actions.logger.LoggerController; import com.prey.actions.observer.ActionsController; import com.prey.backwardcompatibility.AboveCupcakeSupport; import com.prey.events.Event; import com.prey.exceptions.PreyException; +import com.prey.json.UtilJson; import com.prey.json.parser.JSONParser; import com.prey.net.http.EntityFile; import com.prey.R; @@ -590,14 +593,18 @@ public PreyHttpResponse sendPreyHttpData(Context ctx, ArrayList PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx); Map parameters = new HashMap(); List entityFiles = new ArrayList(); + JSONObject json = new JSONObject(); for (HttpDataService httpDataService : dataToSend) { if (httpDataService != null) { + JSONObject jsonData = httpDataService.getDataJson(); + json = UtilJson.merge(json, jsonData); parameters.putAll(httpDataService.getDataAsParameters()); if (httpDataService.getEntityFiles() != null && httpDataService.getEntityFiles().size() > 0) { entityFiles.addAll(httpDataService.getEntityFiles()); } } } + LoggerController.getInstance(ctx).addData(json); PreyHttpResponse preyHttpResponse = null; if(parameters.size()>0||entityFiles.size()>0) { Hardware hardware = new PreyPhone(ctx).getHardware(); @@ -674,9 +681,10 @@ public PreyHttpResponse sendPreyHttpEvent(Context ctx, Event event, JSONObject j parameters.put("name", event.getName()); parameters.put("info", event.getInfo()); parameters.put("status", jsonObject.toString()); - PreyLogger.d("EVENT sendPreyHttpEvent url:" + url); - PreyLogger.d("EVENT name:" + event.getName() + " info:" + event.getInfo()); - PreyLogger.d("EVENT status:" + jsonObject.toString()); + PreyLogger.d(String.format("EVENT sendPreyHttpEvent url:%s", url)); + PreyLogger.d(String.format("EVENT name:%s info:%s", event.getName(), event.getInfo())); + PreyLogger.d(String.format("EVENT status:%s", jsonObject.toString())); + LoggerController.getInstance(ctx).addEvents(event, jsonObject); String status = jsonObject.toString(); preyHttpResponse = PreyRestHttpClient.getInstance(ctx).postStatusAutentication(url, status, parameters); if(preyHttpResponse!=null) { @@ -715,6 +723,7 @@ public void sendNotifyActionResultPreyHttp(final Context ctx,final String status new Thread() { public void run() { PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx); + LoggerController.getInstance(ctx).addActionResult(status, params); String response = null; try { String url = getResponseUrlJson(ctx); @@ -732,14 +741,46 @@ public PreyHttpResponse sendPreyHttpReport(Context ctx, List da PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx); HashMap parameters = new HashMap(); List entityFiles = new ArrayList(); + JSONObject json = new JSONObject(); for (HttpDataService httpDataService : dataToSend) { if (httpDataService != null) { + JSONObject jsonData = httpDataService.getDataJson(); + json = UtilJson.merge(json, jsonData); parameters.putAll(httpDataService.getReportAsParameters()); if (httpDataService.getEntityFiles() != null && httpDataService.getEntityFiles().size() > 0) { - entityFiles.addAll(httpDataService.getEntityFiles()); + List listFiles = httpDataService.getEntityFiles(); + entityFiles.addAll(listFiles); + JSONArray array = new JSONArray(); + try { + for (int i = 0; listFiles != null && i < listFiles.size(); i++) { + EntityFile file = listFiles.get(i); + JSONObject jsonFile = new JSONObject(); + jsonFile.put("name", file.getName()); + jsonFile.put("fileName", file.getFilename()); + jsonFile.put("mimeType", file.getMimeType()); + array.put(jsonFile); + } + json = UtilJson.merge(json, "files", array); + } catch (Exception e) { + PreyLogger.e(String.format("error:%s", e.getMessage()), e); + } } } } + boolean canAccessFineLocation = PreyPermission.canAccessFineLocation(ctx); + boolean canAccessCoarseLocation = PreyPermission.canAccessCoarseLocation(ctx); + boolean canAccessCamera = PreyPermission.canAccessCamera(ctx); + boolean canAccessBackgroundLocation = PreyPermission.canAccessBackgroundLocationView(ctx); + try { + JSONObject info = new JSONObject(); + info.put("location", (canAccessFineLocation || canAccessCoarseLocation)); + info.put("location_background", canAccessBackgroundLocation); + info.put("camera", canAccessCamera); + json.put("permissions", info); + } catch (Exception e) { + PreyLogger.e(String.format("error:%s", e.getMessage()), e); + } + LoggerController.getInstance(ctx).addReport(json); PreyHttpResponse preyHttpResponse = null; try { String url = getReportUrlJson(ctx); @@ -842,6 +883,7 @@ public String geofencing(Context ctx) throws PreyException { sb = sb.trim(); } } + LoggerController.getInstance(ctx).addGeofencing(sb); }catch(Exception e){ PreyLogger.e("Error, causa:" + e.getMessage(), e); return null; @@ -873,8 +915,9 @@ public JSONObject getStatus(Context ctx) throws PreyException { return jsnobject; } - public PreyHttpResponse sendTree(final Context ctx,JSONObject json ) throws PreyException{ + public PreyHttpResponse sendTree(final Context ctx, JSONObject json) throws PreyException{ String uri = getDeviceUrlApiv2(ctx).concat("/data.json"); + LoggerController.getInstance(ctx).addData(json); return PreyRestHttpClient.getInstance(ctx).jsonMethodAutentication(uri,UtilConnection.REQUEST_METHOD_POST,json); } @@ -1271,4 +1314,27 @@ public boolean validToken(Context ctx, String token) throws Exception { return statusCode == 200; } + /** + * Method to upload logger + * + * @param ctx + * @param text + * @return PreyHttpResponse + * @throws Exception + */ + public PreyHttpResponse uploadLogger(final Context ctx, String text) throws Exception { + String url = PreyConfig.getPreyConfig(ctx).getPreyUrl().concat("upload/log?deviceKey=").concat(PreyConfig.getPreyConfig(ctx).getDeviceId()); + PreyLogger.d(String.format("url%s:", url)); + PreyHttpResponse response = PreyRestHttpClient.getInstance(ctx).uploadLogger(ctx, url, text); + int statusCode = -1; + try { + statusCode = response.getStatusCode(); + PreyLogger.d(String.format("statusCode%s:", statusCode)); + PreyLogger.d(String.format("uploadString%s:", response.getResponseAsString())); + } catch (Exception e) { + PreyLogger.e(String.format("Error uploadString:%s", e.getMessage()), e); + } + return response; + } + } \ 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 26c3ea56..770e15b9 100644 --- a/app/src/main/java/com/prey/net/UtilConnection.java +++ b/app/src/main/java/com/prey/net/UtilConnection.java @@ -13,6 +13,7 @@ import com.prey.PreyConfig; import com.prey.PreyLogger; import com.prey.PreyUtils; +import com.prey.actions.logger.LoggerController; import com.prey.net.http.EntityFile; import com.prey.net.http.SimpleMultipartEntity; @@ -41,6 +42,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import javax.net.ssl.HttpsURLConnection; @@ -548,6 +551,7 @@ public static int uploadFile(PreyConfig preyConfig,String page, File file,long t connection.disconnect(); } } + LoggerController.getInstance(preyConfig.getContext()).addUpload(file, responseCode); return responseCode; } @@ -636,4 +640,95 @@ public static PreyHttpResponse postJson(String uri,String userAgent,JSONObject j return response; } -} + /** + * Method to upload logger + * + * @param ctx + * @param uri + * @param text + * @return PreyHttpResponse + */ + public static PreyHttpResponse uploadLogger(Context ctx, String uri, String text) { + BufferedWriter writer = null; + OutputStream os = null; + PreyHttpResponse response = null; + HttpURLConnection conn = null; + InputStream input = null; + FileInputStream fileInput = null; + ByteArrayOutputStream out = null; + try { + PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx); + try { + ZipEntry e1 = new ZipEntry("prey.log"); + out = new ByteArrayOutputStream(); + ZipOutputStream zs = new ZipOutputStream(out); + zs.putNextEntry(e1); + zs.write(text.getBytes()); + zs.close(); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + PreyLogger.d(String.format("uri:%s", uri)); + URL url = new URL(uri); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + conn.addRequestProperty("Origin", "android:com.prey"); + conn.addRequestProperty("User-Agent", getUserAgent(preyConfig)); + conn.addRequestProperty("Authorization", getAuthorization(preyConfig)); + conn.addRequestProperty("Content-Type", "multipart/form-data;boundary=logs.zip"); + os = conn.getOutputStream(); + ByteArrayInputStream inStream = new ByteArrayInputStream(out.toByteArray()); + int maxByte = 4096; + byte[] buffer = new byte[maxByte]; + int length; + while ((length = inStream.read(buffer)) > 0) { + os.write(buffer, 0, length); + } + os.flush(); + conn.connect(); + response = new PreyHttpResponse(conn); + PreyLogger.d(String.format("statusCode:%s", response.getStatusCode())); + PreyLogger.d(String.format("response:%s", response.getResponseAsString())); + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } finally { + try { + if (input != null) { + input.close(); + } + } catch (IOException e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + try { + if (fileInput != null) { + fileInput.close(); + } + } catch (IOException e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + try { + if (writer != null) { + writer.close(); + } + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + try { + if (os != null) { + os.close(); + } + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + try { + if (conn != null) { + conn.disconnect(); + } + } catch (Exception e) { + PreyLogger.e(String.format("Error:%s", e.getMessage()), e); + } + } + return response; + } + +} \ No newline at end of file