Colota - Android GPS Location tracker
refactor: move geofence logic from LocationUtils to GeofenceHelper
Max Dietriche6f6e01d73da
diff --git a/android/app/src/main/java/com/locata/BootReceiver.kt b/android/app/src/main/java/com/colota/BootReceiver.ktsimilarity index 96%rename from android/app/src/main/java/com/locata/BootReceiver.ktrename to android/app/src/main/java/com/colota/BootReceiver.ktindex 66cd8415..fa097af2 100644--- a/android/app/src/main/java/com/locata/BootReceiver.kt+++ b/android/app/src/main/java/com/colota/BootReceiver.kt@@ -57,7 +57,7 @@ class LocationBootReceiver : BroadcastReceiver() {* Waits for database to be ready with retry logic.* Database might not be immediately available after boot.*/- private suspend fun waitForDatabaseReady(dbHelper: LocationDatabaseHelper): Boolean {+ private suspend fun waitForDatabaseReady(dbHelper: DatabaseHelper): Boolean {repeat(MAX_DB_RETRIES) { attempt ->try {// Test database access@@ -77,7 +77,7 @@ class LocationBootReceiver : BroadcastReceiver() {private suspend fun handleBootCompleted(context: Context, action: String) {try {- val dbHelper = LocationDatabaseHelper.getInstance(context)+ val dbHelper = DatabaseHelper.getInstance(context)// Wait for database to be readyif (!waitForDatabaseReady(dbHelper)) {diff --git a/android/app/src/main/java/com/locata/BuildConfigModule.kt b/android/app/src/main/java/com/colota/BuildConfigModule.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/BuildConfigModule.ktrename to android/app/src/main/java/com/colota/BuildConfigModule.ktdiff --git a/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt b/android/app/src/main/java/com/colota/DatabaseHelper.ktsimilarity index 98%rename from android/app/src/main/java/com/locata/LocationDatabaseHelper.ktrename to android/app/src/main/java/com/colota/DatabaseHelper.ktindex 17fc18c8..c26d442b 100644--- a/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt+++ b/android/app/src/main/java/com/colota/DatabaseHelper.kt@@ -28,7 +28,7 @@ import org.json.JSONObject** @param context The Android [Context] used to open or create the database.*/-class LocationDatabaseHelper private constructor(context: Context) :+class DatabaseHelper private constructor(context: Context) :SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {companion object {@@ -49,16 +49,16 @@ class LocationDatabaseHelper private constructor(context: Context) :private const val TAG = "LocationDB"@Volatile- private var INSTANCE: LocationDatabaseHelper? = null+ private var INSTANCE: DatabaseHelper? = null/**- * Returns the singleton instance of the [LocationDatabaseHelper].+ * Returns the singleton instance of the [DatabaseHelper].* Using the Application Context prevents memory leaks.*/@JvmStatic- fun getInstance(context: Context): LocationDatabaseHelper {+ fun getInstance(context: Context): DatabaseHelper {return INSTANCE ?: synchronized(this) {- INSTANCE ?: LocationDatabaseHelper(context.applicationContext).also {+ INSTANCE ?: DatabaseHelper(context.applicationContext).also {INSTANCE = it}}diff --git a/android/app/src/main/java/com/locata/DeviceInfoHelper.kt b/android/app/src/main/java/com/colota/DeviceInfoHelper.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/DeviceInfoHelper.ktrename to android/app/src/main/java/com/colota/DeviceInfoHelper.ktdiff --git a/android/app/src/main/java/com/locata/FileOperations.kt b/android/app/src/main/java/com/colota/FileOperations.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/FileOperations.ktrename to android/app/src/main/java/com/colota/FileOperations.ktdiff --git a/android/app/src/main/java/com/colota/GeofenceHelper.kt b/android/app/src/main/java/com/colota/GeofenceHelper.ktnew file mode 100644index 00000000..445bc9a1--- /dev/null+++ b/android/app/src/main/java/com/colota/GeofenceHelper.kt@@ -0,0 +1,225 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota++import android.content.ContentValues+import android.content.Context+import android.location.Location+import android.util.Log+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.WritableArray+import kotlin.math.*++class GeofenceHelper(private val context: Context) {++ private val dbHelper by lazy { DatabaseHelper.getInstance(context) }++ @Volatile+ private var cachedGeofences: List<CachedGeofence>? = null+ private var lastGeofenceCacheTime: Long = 0+ private val GEOFENCE_CACHE_MS = 30000L++ data class CachedGeofence(+ val name: String,+ val lat: Double,+ val lon: Double,+ val radius: Double+ )++ companion object {+ private const val TAG = "GeofenceHelper"+ private const val EARTH_RADIUS_METERS = 6371000.0+ }++ // --- Math Engine ---++ private fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+ val dLat = Math.toRadians(lat2 - lat1)+ val dLon = Math.toRadians(lon2 - lon1)+ val a = sin(dLat / 2).pow(2) ++ cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2).pow(2)+ return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))+ }++ private fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radius: Double): Boolean {+ // Fast bounding-box rejection+ val maxDeg = radius / 111000.0+ if (Math.abs(lat1 - lat2) > maxDeg || Math.abs(lon1 - lon2) > maxDeg) return false+ return calculateDistance(lat1, lon1, lat2, lon2) <= radius+ }++ // --- Core Logic ---++ /**+ * Checks if location is within any active silent zone.+ * Returns immediately on first match for better performance.+ */+ fun getSilentZone(location: Location): String? {+ val fences = getGeofences()+ return fences.find {+ isWithinRadius(location.latitude, location.longitude, it.lat, it.lon, it.radius)+ }?.name+ }++ /**+ * Invalidates cache when geofences change+ */+ fun invalidateCache() {+ cachedGeofences = null+ lastGeofenceCacheTime = 0++ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Geofence cache invalidated")+ }+ }++ /**+ * Gets geofences from cache or refreshes if stale+ */+ private fun getGeofences(): List<CachedGeofence> {+ val now = System.currentTimeMillis()+ if (cachedGeofences == null || (now - lastGeofenceCacheTime) > GEOFENCE_CACHE_MS) {+ refreshCache()+ }+ return cachedGeofences ?: emptyList()+ }++ /**+ * Refreshes geofence cache from database+ */+ private fun refreshCache() {+ val fences = mutableListOf<CachedGeofence>()+ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_GEOFENCES,+ arrayOf("name", "latitude", "longitude", "radius"),+ "enabled = 1 AND pause_tracking = 1",+ null, null, null, null+ ).use { cursor ->+ val nameIdx = cursor.getColumnIndexOrThrow("name")+ val latIdx = cursor.getColumnIndexOrThrow("latitude")+ val lonIdx = cursor.getColumnIndexOrThrow("longitude")+ val radIdx = cursor.getColumnIndexOrThrow("radius")++ while (cursor.moveToNext()) {+ fences.add(CachedGeofence(+ cursor.getString(nameIdx),+ cursor.getDouble(latIdx),+ cursor.getDouble(lonIdx),+ cursor.getDouble(radIdx)+ ))+ }+ }+ cachedGeofences = fences+ lastGeofenceCacheTime = System.currentTimeMillis()+ }++ // --- Database CRUD (For React Native Module) ---++ /**+ * Fetches all geofences with optimized column index caching.+ */+ fun getGeofencesAsArray(): WritableArray {+ val array = Arguments.createArray()++ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_GEOFENCES,+ null, null, null, null, null,+ "created_at DESC"+ ).use { cursor ->+ // Cache column indices (faster than repeated getColumnIndexOrThrow calls)+ val idIdx = cursor.getColumnIndexOrThrow("id")+ val nameIdx = cursor.getColumnIndexOrThrow("name")+ val latIdx = cursor.getColumnIndexOrThrow("latitude")+ val lonIdx = cursor.getColumnIndexOrThrow("longitude")+ val radiusIdx = cursor.getColumnIndexOrThrow("radius")+ val enabledIdx = cursor.getColumnIndexOrThrow("enabled")+ val pauseIdx = cursor.getColumnIndexOrThrow("pause_tracking")+ val createdIdx = cursor.getColumnIndexOrThrow("created_at")++ while (cursor.moveToNext()) {+ array.pushMap(Arguments.createMap().apply {+ putInt("id", cursor.getInt(idIdx))+ putString("name", cursor.getString(nameIdx))+ putDouble("lat", cursor.getDouble(latIdx))+ putDouble("lon", cursor.getDouble(lonIdx))+ putDouble("radius", cursor.getDouble(radiusIdx))+ putBoolean("enabled", cursor.getInt(enabledIdx) == 1)+ putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)+ putDouble("createdAt", cursor.getLong(createdIdx).toDouble())+ })+ }+ }++ return array+ }++ /**+ * Inserts a new geofence into the database.+ */+ fun insertGeofence(+ name: String,+ lat: Double,+ lon: Double,+ rad: Double,+ pause: Boolean+ ): Int {+ val values = ContentValues().apply {+ put("name", name)+ put("latitude", lat)+ put("longitude", lon)+ put("radius", rad)+ put("enabled", 1)+ put("pause_tracking", if (pause) 1 else 0)+ put("created_at", System.currentTimeMillis())+ }++ return dbHelper.writableDatabase+ .insert(DatabaseHelper.TABLE_GEOFENCES, null, values)+ .toInt()+ }++ /**+ * Updates geofence with only provided fields.+ */+ fun updateGeofence(+ id: Int,+ name: String?,+ lat: Double?,+ lon: Double?,+ rad: Double?,+ en: Boolean?,+ pause: Boolean?+ ): Boolean {+ val values = ContentValues().apply {+ name?.let { put("name", it) }+ lat?.let { put("latitude", it) }+ lon?.let { put("longitude", it) }+ rad?.let { put("radius", it) }+ en?.let { put("enabled", if (it) 1 else 0) }+ pause?.let { put("pause_tracking", if (it) 1 else 0) }+ }++ if (values.size() == 0) return false++ return dbHelper.writableDatabase.update(+ DatabaseHelper.TABLE_GEOFENCES,+ values,+ "id = ?",+ arrayOf(id.toString())+ ) > 0+ }++ /**+ * Deletes a geofence by ID.+ */+ fun deleteGeofence(id: Int): Boolean {+ return dbHelper.writableDatabase.delete(+ DatabaseHelper.TABLE_GEOFENCES,+ "id = ?",+ arrayOf(id.toString())+ ) > 0+ }+}\ No newline at end of filediff --git a/android/app/src/main/java/com/locata/LocationForegroundService.kt b/android/app/src/main/java/com/colota/LocationForegroundService.ktsimilarity index 97%rename from android/app/src/main/java/com/locata/LocationForegroundService.ktrename to android/app/src/main/java/com/colota/LocationForegroundService.ktindex 5a6c7adb..f73902c8 100644--- a/android/app/src/main/java/com/locata/LocationForegroundService.kt+++ b/android/app/src/main/java/com/colota/LocationForegroundService.kt@@ -22,9 +22,11 @@ class LocationForegroundService : Service() {// --- Core Components ---private lateinit var fusedLocationClient: FusedLocationProviderClientprivate lateinit var notificationManager: NotificationManager- private lateinit var dbHelper: LocationDatabaseHelper+ private lateinit var dbHelper: DatabaseHelperprivate lateinit var locationUtils: LocationUtilsprivate lateinit var deviceInfoHelper: DeviceInfoHelper+ private lateinit var networkManager: NetworkManager+ private lateinit var geofenceHelper: GeofenceHelper// Properly manage scope lifecycle to prevent memory leakprivate var serviceScope: CoroutineScope? = null@@ -84,16 +86,18 @@ class LocationForegroundService : Service() {fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager- dbHelper = LocationDatabaseHelper.getInstance(this)+ dbHelper = DatabaseHelper.getInstance(this)locationUtils = LocationUtils(this)deviceInfoHelper = DeviceInfoHelper(this)+ networkManager = NetworkManager(this)+ geofenceHelper = GeofenceHelper(this)createNotificationChannel()}override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {if (!::dbHelper.isInitialized) {- dbHelper = LocationDatabaseHelper.getInstance(this)+ dbHelper = DatabaseHelper.getInstance(this)}val savedSettings = dbHelper.getAllSettings()@@ -221,7 +225,7 @@ class LocationForegroundService : Service() {lastKnownLocation = it// Check if starting in a pause zone- locationUtils.getSilentZone(it)?.let { zoneName ->+ geofenceHelper.getSilentZone(it)?.let { zoneName ->enterSilentZone(GeofenceInfo(-1, zoneName))} ?: run {// Not in zone - show coordinates immediately@@ -241,7 +245,7 @@ class LocationForegroundService : Service() {}private fun handleZoneRecheckAction() {- locationUtils.invalidateGeofenceCache()+ geofenceHelper.invalidateCache()val cachedLoc = lastKnownLocationval now = System.currentTimeMillis()@@ -276,7 +280,7 @@ class LocationForegroundService : Service() {private fun recheckZoneWithLocation(location: android.location.Location) {- val zoneName = locationUtils.getSilentZone(location)+ val zoneName = geofenceHelper.getSilentZone(location)when {// Just entered a pause zone or changed zones@@ -325,7 +329,7 @@ class LocationForegroundService : Service() {lastKnownLocation = location// Silent Zone Logic - CHECK IF IT'S A PAUSE ZONE- val zoneName = locationUtils.getSilentZone(location)+ val zoneName = geofenceHelper.getSilentZone(location)when {zoneName != null && !insideSilentZone -> {@@ -463,7 +467,7 @@ class LocationForegroundService : Service() {val baseDelay = calculateNextSyncDelay()delay(baseDelay * 1000L)- if (config.isOfflineMode || !locationUtils.isNetworkAvailable()) {+ if (config.isOfflineMode || !networkManager.isNetworkAvailable()) {continue}@@ -565,7 +569,7 @@ class LocationForegroundService : Service() {// Attempt only retriable itemsval results = retriable.map { item ->async {- val success = locationUtils.sendToEndpoint(+ val success = networkManager.sendToEndpoint(JSONObject(item.payload),endpoint)@@ -639,14 +643,13 @@ class LocationForegroundService : Service() {// Immediate send mode (syncInterval = 0)if (config.syncIntervalSeconds == 0) {Log.d(TAG, "Instant send")- val success = locationUtils.sendToEndpoint(payload, endpoint)+ val success = networkManager.sendToEndpoint(payload, endpoint)if (success) {dbHelper.removeFromQueueByLocationId(locationId)lastQueueCountCheck = 0lastSuccessfulSyncTime = System.currentTimeMillis()} else {- // Increment retry count using the queue ID we got from insertdbHelper.incrementRetryCount(queueId, "Send failed")}}diff --git a/android/app/src/main/java/com/locata/LocationServiceModule.kt b/android/app/src/main/java/com/colota/LocationServiceModule.ktsimilarity index 96%rename from android/app/src/main/java/com/locata/LocationServiceModule.ktrename to android/app/src/main/java/com/colota/LocationServiceModule.ktindex 0fd1aded..fbaa4d29 100644--- a/android/app/src/main/java/com/locata/LocationServiceModule.kt+++ b/android/app/src/main/java/com/colota/LocationServiceModule.kt@@ -27,9 +27,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :LifecycleEventListener {private val locationUtils = LocationUtils(reactContext)- private val dbHelper = LocationDatabaseHelper.getInstance(reactContext)+ private val dbHelper = DatabaseHelper.getInstance(reactContext)private val fileOps = FileOperations(reactContext)private val deviceInfo = DeviceInfoHelper(reactContext)+ private val geofenceHelper = GeofenceHelper(reactContext)// Coroutine scope for async operationsprivate val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())@@ -335,9 +336,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :pause: Boolean,promise: Promise) = executeAsync(promise) {- val result = locationUtils.insertGeofence(name, lat, lon, radius, pause)+ val result = geofenceHelper.insertGeofence(name, lat, lon, radius, pause)if (result > 0) {- locationUtils.invalidateGeofenceCache()+ geofenceHelper.invalidateCache()triggerZoneRecheck()}result@@ -349,7 +350,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :*/@ReactMethodfun getGeofences(promise: Promise) = executeAsync(promise) {- locationUtils.getGeofencesAsArray()+ geofenceHelper.getGeofencesAsArray()}@ReactMethod@@ -363,9 +364,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :pause: Boolean?,promise: Promise) = executeAsync(promise) {- val result = locationUtils.updateGeofence(id, name, lat, lon, radius, enabled, pause)+ val result = geofenceHelper.updateGeofence(id, name, lat, lon, radius, enabled, pause)if (result) {- locationUtils.invalidateGeofenceCache()+ geofenceHelper.invalidateCache()triggerZoneRecheck()}result@@ -377,9 +378,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :*/@ReactMethodfun deleteGeofence(id: Int, promise: Promise) = executeAsync(promise) {- val result = locationUtils.deleteGeofence(id)+ val result = geofenceHelper.deleteGeofence(id)if (result) {- locationUtils.invalidateGeofenceCache()+ geofenceHelper.invalidateCache()triggerZoneRecheck()}result@@ -399,7 +400,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(null)} else {executeAsync(promise) {- locationUtils.getSilentZone(loc)+ geofenceHelper.getSilentZone(loc)}}}.addOnFailureListener { e ->diff --git a/android/app/src/main/java/com/locata/LocationServicePackage.kt b/android/app/src/main/java/com/colota/LocationServicePackage.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/LocationServicePackage.ktrename to android/app/src/main/java/com/colota/LocationServicePackage.ktdiff --git a/android/app/src/main/java/com/colota/LocationsUtils.kt b/android/app/src/main/java/com/colota/LocationsUtils.ktnew file mode 100644index 00000000..afcd1985--- /dev/null+++ b/android/app/src/main/java/com/colota/LocationsUtils.kt@@ -0,0 +1,172 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota++import android.content.ContentValues+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.location.Location+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.os.BatteryManager+import android.util.Log+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.ReadableMap+import com.facebook.react.bridge.WritableArray+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import org.json.JSONObject+import java.net.URL+import javax.net.ssl.HttpsURLConnection+import kotlin.math.*++/**+ * Utility class providing specialized logic for the Colota tracking engine.+ * Maintains a reference to [Context] to handle system-level queries like battery and network.+ */+class LocationUtils(private val context: Context) {++ companion object {+ private const val TAG = "LocationUtils"+ private const val EARTH_RADIUS_METERS = 6371000.0+ private const val CONNECTION_TIMEOUT = 10000+ private const val READ_TIMEOUT = 10000+ }++ // Lazy initialization - only created when first accessed+ private val dbHelper by lazy { DatabaseHelper.getInstance(context) }++ // Cache connectivity manager to avoid repeated getSystemService calls+ private val connectivityManager: ConnectivityManager by lazy {+ context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager+ }++ @Volatile+ private var cachedGeofences: List<CachedGeofence>? = null+ private var lastGeofenceCacheTime: Long = 0+ private val GEOFENCE_CACHE_MS = 30000L // 30 seconds++ data class CachedGeofence(+ val name: String,+ val lat: Double,+ val lon: Double,+ val radius: Double+ )++ @Volatile+ private var lastNetworkCheck: Boolean = true+ private var lastNetworkCheckTime: Long = 0+ private val NETWORK_CHECK_CACHE_MS = 5000L // 5 seconds++ // ========================================+ // GEOMETRY+ // ========================================++ /**+ * Calculates the great-circle distance using Haversine formula.+ * Optimized with cached radians conversion.+ */+ fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+ val dLat = Math.toRadians(lat2 - lat1)+ val dLon = Math.toRadians(lon2 - lon1)+ val lat1Rad = Math.toRadians(lat1)+ val lat2Rad = Math.toRadians(lat2)++ val a = sin(dLat / 2).pow(2) ++ cos(lat1Rad) * cos(lat2Rad) * sin(dLon / 2).pow(2)++ return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))+ }++ /**+ * Fast distance check without square root for geofence detection.+ * Returns true if within radius (cheaper than full Haversine).+ */+ fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radiusMeters: Double): Boolean {+ // Quick rejection test using simple lat/lon differences+ val latDiff = Math.abs(lat1 - lat2)+ val lonDiff = Math.abs(lon1 - lon2)++ // Rough approximation: 1 degree ≈ 111km at equator+ val maxDegreeDiff = radiusMeters / 111000.0++ // Quick rejection: if way outside bounding box, skip expensive calculation+ if (latDiff > maxDegreeDiff || lonDiff > maxDegreeDiff) {+ return false+ }++ // Only do full Haversine if within rough bounding box+ return calculateDistance(lat1, lon1, lat2, lon2) <= radiusMeters+ }++ // ========================================+ // DATA CONVERSION+ // ========================================++ /**+ * Maps native location data into JSONObject with dynamic field mapping.+ */+ fun buildPayload(+ location: Location,+ batteryLevel: Int,+ batteryStatus: Int,+ fieldMap: Map<String, String>,+ timestamp: Long+ ): JSONObject {+ return JSONObject().apply {+ put(fieldMap["lat"] ?: "lat", location.latitude)+ put(fieldMap["lon"] ?: "lon", location.longitude)+ put(fieldMap["acc"] ?: "acc", location.accuracy.roundToInt())++ if (location.hasAltitude()) {+ put(fieldMap["alt"] ?: "alt", location.altitude.roundToInt())+ }++ put(fieldMap["vel"] ?: "vel", location.speed.roundToInt())+ put(fieldMap["batt"] ?: "batt", batteryLevel)+ put(fieldMap["bs"] ?: "bs", batteryStatus)+ put(fieldMap["tst"] ?: "tst", timestamp)++ if (location.hasBearing()) {+ put(fieldMap["bear"] ?: "bear", location.bearing.toDouble())+ }+ }+ }++ /**+ * Parses JSON string to Map with error handling.+ */+ fun parseFieldMap(jsonString: String?): Map<String, String>? {+ if (jsonString.isNullOrBlank()) return null++ return try {+ val json = JSONObject(jsonString)+ json.keys().asSequence().associateWith { json.getString(it) }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to parse field map", e)+ null+ }+ }++ /**+ * Converts ReadableMap to JSON string with null safety.+ */+ fun convertFieldMapToJson(fieldMap: ReadableMap): String {+ val json = JSONObject()+ val iterator = fieldMap.keySetIterator()++ while (iterator.hasNextKey()) {+ val key = iterator.nextKey()+ fieldMap.getString(key)?.let { value ->+ json.put(key, value)+ }+ }++ return json.toString()+ }++}\ No newline at end of filediff --git a/android/app/src/main/java/com/locata/MainActivity.kt b/android/app/src/main/java/com/colota/MainActivity.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/MainActivity.ktrename to android/app/src/main/java/com/colota/MainActivity.ktdiff --git a/android/app/src/main/java/com/locata/MainApplication.kt b/android/app/src/main/java/com/colota/MainApplication.ktsimilarity index 100%rename from android/app/src/main/java/com/locata/MainApplication.ktrename to android/app/src/main/java/com/colota/MainApplication.ktdiff --git a/android/app/src/main/java/com/colota/NetworkManager.kt b/android/app/src/main/java/com/colota/NetworkManager.ktnew file mode 100644index 00000000..45d5f1d5--- /dev/null+++ b/android/app/src/main/java/com/colota/NetworkManager.kt@@ -0,0 +1,148 @@+package com.Colota++import android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.util.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import org.json.JSONObject+import java.net.HttpURLConnection+import java.net.URL+import java.nio.charset.StandardCharsets++/**+ * Handles all outgoing network communication for the tracking engine.+ */+class NetworkManager(private val context: Context) {++ companion object {+ private const val TAG = "NetworkManager"+ private const val CONNECTION_TIMEOUT = 10000+ private const val READ_TIMEOUT = 10000+ private const val NETWORK_CHECK_CACHE_MS = 5000L+ }++ private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager++ // Cache variables for network availability+ @Volatile private var lastNetworkCheck: Boolean = true+ private var lastNetworkCheckTime: Long = 0++ /**+ * Executes an asynchronous POST request to the server.+ */+ suspend fun sendToEndpoint(payload: JSONObject, endpoint: String): Boolean = withContext(Dispatchers.IO) {+ if (endpoint.isBlank()) {+ if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")+ return@withContext false+ }++ val url = try {+ URL(endpoint)+ } catch (e: Exception) {+ Log.e(TAG, "Invalid URL: $endpoint")+ return@withContext false+ }++ if (!isValidProtocol(url)) {+ Log.e(TAG, "Protocol blocked or invalid: $endpoint")+ return@withContext false+ }++ if (!isNetworkAvailable()) {+ if (BuildConfig.DEBUG) Log.d(TAG, "Sync skipped: No internet")+ return@withContext false+ }++ var connection: HttpURLConnection? = null+ try {+ connection = url.openConnection() as HttpURLConnection+ connection.apply {+ requestMethod = "POST"+ setRequestProperty("Content-Type", "application/json; charset=UTF-8")+ setRequestProperty("Accept", "application/json")+ doOutput = true+ connectTimeout = CONNECTION_TIMEOUT+ readTimeout = READ_TIMEOUT+ useCaches = false+ }++ // Write payload+ val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)+ connection.setFixedLengthStreamingMode(bodyBytes.size)+ connection.outputStream.use { it.write(bodyBytes) }++ val responseCode = connection.responseCode+ return@withContext if (responseCode in 200..299) {+ if (BuildConfig.DEBUG) Log.d(TAG, "Location successfully sent")+ true+ } else {+ val errorBody = try {+ connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"+ } catch (_: Exception) { "Could not read error body" }+ Log.e(TAG, "POST failed: $responseCode - $errorBody")+ false+ }+ } catch (e: Exception) {+ Log.e(TAG, "Network error: ${e.message}", e)+ false+ } finally {+ connection?.disconnect()+ }+ }++ /**+ * Validates protocol and enforces HTTPS for public hosts.+ */+ private fun isValidProtocol(url: URL): Boolean {+ val protocol = url.protocol.lowercase()+ val host = url.host ?: return false++ if (protocol != "http" && protocol != "https") return false++ // Enforce HTTPS for anything that isn't a local/private IP+ if (protocol == "http" && !isPrivateHost(host)) {+ return false+ }+ return true+ }++ /**+ * Checks if the given host is private or local.+ */+ private fun isPrivateHost(host: String): Boolean {+ if (host == "localhost") return true+ return try {+ val address = java.net.InetAddress.getByName(host)+ address.isAnyLocalAddress || address.isLoopbackAddress || address.isSiteLocalAddress+ } catch (e: Exception) {+ false+ }+ }++ /**+ * Checks for an active, validated internet connection with caching.+ */+ fun isNetworkAvailable(): Boolean {+ val now = System.currentTimeMillis()+ if ((now - lastNetworkCheckTime) < NETWORK_CHECK_CACHE_MS) {+ return lastNetworkCheck+ }++ lastNetworkCheck = try {+ val network = connectivityManager.activeNetwork+ val capabilities = connectivityManager.getNetworkCapabilities(network)++ capabilities != null &&+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)+ } catch (e: Exception) {+ Log.e(TAG, "Network check failed", e)+ false+ }++ lastNetworkCheckTime = now+ return lastNetworkCheck+ }+}\ No newline at end of filediff --git a/android/app/src/main/java/com/locata/ServiceConfig.kt b/android/app/src/main/java/com/colota/ServiceConfig.ktsimilarity index 95%rename from android/app/src/main/java/com/locata/ServiceConfig.ktrename to android/app/src/main/java/com/colota/ServiceConfig.ktindex 3079b46a..adde6204 100644--- a/android/app/src/main/java/com/locata/ServiceConfig.kt+++ b/android/app/src/main/java/com/colota/ServiceConfig.kt@@ -30,7 +30,7 @@ data class ServiceConfig(/*** Loads configuration from database settings.*/- fun fromDatabase(dbHelper: LocationDatabaseHelper): ServiceConfig {+ fun fromDatabase(dbHelper: DatabaseHelper): ServiceConfig {val saved = dbHelper.getAllSettings()return ServiceConfig(@@ -50,7 +50,7 @@ data class ServiceConfig(/*** Loads configuration from Intent extras (for service start).*/- fun fromIntent(intent: Intent, dbHelper: LocationDatabaseHelper): ServiceConfig {+ fun fromIntent(intent: Intent, dbHelper: DatabaseHelper): ServiceConfig {val extras = intent.extras ?: return fromDatabase(dbHelper)// Load from database first, then override with intent extrasdiff --git a/android/app/src/main/java/com/locata/LocationsUtils.kt b/android/app/src/main/java/com/locata/LocationsUtils.ktdeleted file mode 100644index 1b9fae5b..00000000--- a/android/app/src/main/java/com/locata/LocationsUtils.kt+++ /dev/null@@ -1,524 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--package com.Colota--import android.content.ContentValues-import android.content.Context-import android.content.Intent-import android.content.IntentFilter-import android.location.Location-import android.net.ConnectivityManager-import android.net.NetworkCapabilities-import android.os.BatteryManager-import android.util.Log-import com.facebook.react.bridge.Arguments-import com.facebook.react.bridge.ReadableMap-import com.facebook.react.bridge.WritableArray-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import org.json.JSONObject-import java.net.URL-import javax.net.ssl.HttpsURLConnection-import kotlin.math.*--/**- * Utility class providing specialized logic for the Colota tracking engine.- * Maintains a reference to [Context] to handle system-level queries like battery and network.- */-class LocationUtils(private val context: Context) {-- companion object {- private const val TAG = "LocationUtils"- private const val EARTH_RADIUS_METERS = 6371000.0- private const val CONNECTION_TIMEOUT = 10000- private const val READ_TIMEOUT = 10000- }-- // Lazy initialization - only created when first accessed- private val dbHelper by lazy { LocationDatabaseHelper.getInstance(context) }-- // Cache connectivity manager to avoid repeated getSystemService calls- private val connectivityManager: ConnectivityManager by lazy {- context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager- }-- @Volatile- private var cachedGeofences: List<CachedGeofence>? = null- private var lastGeofenceCacheTime: Long = 0- private val GEOFENCE_CACHE_MS = 30000L // 30 seconds-- data class CachedGeofence(- val name: String,- val lat: Double,- val lon: Double,- val radius: Double- )-- @Volatile- private var lastNetworkCheck: Boolean = true- private var lastNetworkCheckTime: Long = 0- private val NETWORK_CHECK_CACHE_MS = 5000L // 5 seconds-- // ========================================- // NETWORK & SYNC- // ========================================-- /**- * Executes an asynchronous POST request to the server.- * Handles HTTP only for private IPs/localhost, HTTPS otherwise.- */- suspend fun sendToEndpoint(- payload: JSONObject,- endpoint: String- ): Boolean = withContext(Dispatchers.IO) {-- if (endpoint.isBlank()) {- // Endpoint empty, nothing to do- if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")- return@withContext false- }-- // Parse URL safely- val url = try {- URL(endpoint)- } catch (e: Exception) {- Log.e(TAG, "Invalid URL: $endpoint")- return@withContext false- }-- val protocol = url.protocol.lowercase()- val host = url.host ?: return@withContext false-- // Only allow http or https- if (protocol != "http" && protocol != "https") {- Log.e(TAG, "Invalid protocol: $endpoint")- return@withContext false- }-- // HTTP only allowed for private IPs / localhost- if (protocol == "http" && !isPrivateHost(host)) {- Log.e(TAG, "HTTP blocked for non-private host: $endpoint")- return@withContext false- }-- // Check network availability- if (!isNetworkAvailable()) {- if (BuildConfig.DEBUG) Log.d(TAG, "Sync skipped: No internet")- return@withContext false- }-- var connection: java.net.HttpURLConnection? = null-- try {- connection = url.openConnection() as java.net.HttpURLConnection-- connection.apply {- requestMethod = "POST"- setRequestProperty("Content-Type", "application/json; charset=UTF-8")- setRequestProperty("Accept", "application/json")- doOutput = true- connectTimeout = CONNECTION_TIMEOUT- readTimeout = READ_TIMEOUT- useCaches = false- }-- // Write payload to output stream- val bodyBytes = payload.toString().toByteArray(Charsets.UTF_8)- connection.setFixedLengthStreamingMode(bodyBytes.size)-- connection.outputStream.use { it.write(bodyBytes) }-- val responseCode = connection.responseCode-- return@withContext if (responseCode in 200..299) {- if (BuildConfig.DEBUG) Log.d(TAG, "Location successfully sent")- true- } else {- val errorBody = try {- connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"- } catch (_: Exception) {- "Could not read error body"- }- Log.e(TAG, "POST failed: $responseCode - $errorBody")- false- }-- } catch (e: Exception) {- Log.e(TAG, "Network error: ${e.message}", e)- false- } finally {- connection?.disconnect()- }- }--- /**- * Checks if the given host is private or local.- * Returns true for:- * - "localhost"- * - Loopback addresses (127.x.x.x, ::1)- * - Site-local addresses (RFC1918)- * - Any local/unspecified addresses (0.0.0.0, ::)- */- private fun isPrivateHost(host: String): Boolean {- if (host == "localhost") return true // explicit localhost check-- return try {- val address = java.net.InetAddress.getByName(host)-- // isAnyLocalAddress: 0.0.0.0 / ::0- // isLoopbackAddress: 127.x.x.x / ::1- // isSiteLocalAddress: 10.x.x.x, 172.16-31.x.x, 192.168.x.x- address.isAnyLocalAddress ||- address.isLoopbackAddress ||- address.isSiteLocalAddress- } catch (e: Exception) {- // Could not resolve host; treat as non-private- if (BuildConfig.DEBUG) Log.d(TAG, "Host resolution failed for $host: ${e.message}")- false- }- }-- /**- * Checks for an active, validated internet connection.- * Cached to avoid excessive system calls.- */- fun isNetworkAvailable(): Boolean {- val now = System.currentTimeMillis()-- // Return cached result if fresh- if ((now - lastNetworkCheckTime) < NETWORK_CHECK_CACHE_MS) {- return lastNetworkCheck- }-- lastNetworkCheck = try {- val network = connectivityManager.activeNetwork- if (network == null) {- lastNetworkCheckTime = now- return false- }-- val capabilities = connectivityManager.getNetworkCapabilities(network)- if (capabilities == null) {- lastNetworkCheckTime = now- return false- }-- // Check for both internet capability and that the OS has validated the connection- capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&- capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)- } catch (e: SecurityException) {- Log.e(TAG, "Missing network permission", e)- false- } catch (e: Exception) {- Log.e(TAG, "Network check failed", e)- false- }-- lastNetworkCheckTime = now- return lastNetworkCheck- }-- // ========================================- // GEOMETRY- // ========================================-- /**- * Calculates the great-circle distance using Haversine formula.- * Optimized with cached radians conversion.- */- fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {- val dLat = Math.toRadians(lat2 - lat1)- val dLon = Math.toRadians(lon2 - lon1)- val lat1Rad = Math.toRadians(lat1)- val lat2Rad = Math.toRadians(lat2)-- val a = sin(dLat / 2).pow(2) +- cos(lat1Rad) * cos(lat2Rad) * sin(dLon / 2).pow(2)-- return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))- }-- /**- * Fast distance check without square root for geofence detection.- * Returns true if within radius (cheaper than full Haversine).- */- fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radiusMeters: Double): Boolean {- // Quick rejection test using simple lat/lon differences- val latDiff = Math.abs(lat1 - lat2)- val lonDiff = Math.abs(lon1 - lon2)-- // Rough approximation: 1 degree ≈ 111km at equator- val maxDegreeDiff = radiusMeters / 111000.0-- // Quick rejection: if way outside bounding box, skip expensive calculation- if (latDiff > maxDegreeDiff || lonDiff > maxDegreeDiff) {- return false- }-- // Only do full Haversine if within rough bounding box- return calculateDistance(lat1, lon1, lat2, lon2) <= radiusMeters- }-- // ========================================- // DATA CONVERSION- // ========================================-- /**- * Maps native location data into JSONObject with dynamic field mapping.- */- fun buildPayload(- location: Location,- batteryLevel: Int,- batteryStatus: Int,- fieldMap: Map<String, String>,- timestamp: Long- ): JSONObject {- return JSONObject().apply {- put(fieldMap["lat"] ?: "lat", location.latitude)- put(fieldMap["lon"] ?: "lon", location.longitude)- put(fieldMap["acc"] ?: "acc", location.accuracy.roundToInt())-- if (location.hasAltitude()) {- put(fieldMap["alt"] ?: "alt", location.altitude.roundToInt())- }-- put(fieldMap["vel"] ?: "vel", location.speed.roundToInt())- put(fieldMap["batt"] ?: "batt", batteryLevel)- put(fieldMap["bs"] ?: "bs", batteryStatus)- put(fieldMap["tst"] ?: "tst", timestamp)-- if (location.hasBearing()) {- put(fieldMap["bear"] ?: "bear", location.bearing.toDouble())- }- }- }-- /**- * Parses JSON string to Map with error handling.- */- fun parseFieldMap(jsonString: String?): Map<String, String>? {- if (jsonString.isNullOrBlank()) return null-- return try {- val json = JSONObject(jsonString)- json.keys().asSequence().associateWith { json.getString(it) }- } catch (e: Exception) {- Log.e(TAG, "Failed to parse field map", e)- null- }- }-- /**- * Converts ReadableMap to JSON string with null safety.- */- fun convertFieldMapToJson(fieldMap: ReadableMap): String {- val json = JSONObject()- val iterator = fieldMap.keySetIterator()-- while (iterator.hasNextKey()) {- val key = iterator.nextKey()- fieldMap.getString(key)?.let { value ->- json.put(key, value)- }- }-- return json.toString()- }-- // ========================================- // GEOFENCING- // ========================================-- /**- * Refreshes geofence cache from database- */- private fun refreshGeofenceCache(): List<CachedGeofence> {- val fences = mutableListOf<CachedGeofence>()-- dbHelper.readableDatabase.query(- LocationDatabaseHelper.TABLE_GEOFENCES,- arrayOf("name", "latitude", "longitude", "radius"),- "enabled = 1 AND pause_tracking = 1",- null, null, null, null- ).use { cursor ->- val nameIdx = cursor.getColumnIndexOrThrow("name")- val latIdx = cursor.getColumnIndexOrThrow("latitude")- val lonIdx = cursor.getColumnIndexOrThrow("longitude")- val radiusIdx = cursor.getColumnIndexOrThrow("radius")-- while (cursor.moveToNext()) {- fences.add(CachedGeofence(- cursor.getString(nameIdx),- cursor.getDouble(latIdx),- cursor.getDouble(lonIdx),- cursor.getDouble(radiusIdx)- ))- }- }-- cachedGeofences = fences- lastGeofenceCacheTime = System.currentTimeMillis()-- if (BuildConfig.DEBUG) {- Log.d(TAG, "Geofence cache refreshed: ${fences.size} zones")- }-- return fences- }-- /**- * Gets geofences from cache or refreshes if stale- */- private fun getGeofences(): List<CachedGeofence> {- val now = System.currentTimeMillis()-- return if (cachedGeofences == null || (now - lastGeofenceCacheTime) > GEOFENCE_CACHE_MS) {- refreshGeofenceCache()- } else {- cachedGeofences!!- }- }-- /**- * Invalidates cache when geofences change- */- fun invalidateGeofenceCache() {- cachedGeofences = null- lastGeofenceCacheTime = 0-- if (BuildConfig.DEBUG) {- Log.d(TAG, "Geofence cache invalidated")- }- }-- /**- * Checks if location is within any active silent zone.- * Returns immediately on first match for better performance.- */- fun getSilentZone(location: Location): String? {- val fences = getGeofences()-- for (fence in fences) {- if (isWithinRadius(- location.latitude,- location.longitude,- fence.lat,- fence.lon,- fence.radius- )) {- return fence.name- }- }-- return null- }-- /**- * Fetches all geofences with optimized column index caching.- */- fun getGeofencesAsArray(): WritableArray {- val array = Arguments.createArray()-- dbHelper.readableDatabase.query(- LocationDatabaseHelper.TABLE_GEOFENCES,- null, null, null, null, null,- "created_at DESC"- ).use { cursor ->- // Cache column indices (faster than repeated getColumnIndexOrThrow calls)- val idIdx = cursor.getColumnIndexOrThrow("id")- val nameIdx = cursor.getColumnIndexOrThrow("name")- val latIdx = cursor.getColumnIndexOrThrow("latitude")- val lonIdx = cursor.getColumnIndexOrThrow("longitude")- val radiusIdx = cursor.getColumnIndexOrThrow("radius")- val enabledIdx = cursor.getColumnIndexOrThrow("enabled")- val pauseIdx = cursor.getColumnIndexOrThrow("pause_tracking")- val createdIdx = cursor.getColumnIndexOrThrow("created_at")-- while (cursor.moveToNext()) {- array.pushMap(Arguments.createMap().apply {- putInt("id", cursor.getInt(idIdx))- putString("name", cursor.getString(nameIdx))- putDouble("lat", cursor.getDouble(latIdx))- putDouble("lon", cursor.getDouble(lonIdx))- putDouble("radius", cursor.getDouble(radiusIdx))- putBoolean("enabled", cursor.getInt(enabledIdx) == 1)- putBoolean("pauseTracking", cursor.getInt(pauseIdx) == 1)- putDouble("createdAt", cursor.getLong(createdIdx).toDouble())- })- }- }-- return array- }-- /**- * Inserts a new geofence into the database.- */- fun insertGeofence(- name: String,- lat: Double,- lon: Double,- rad: Double,- pause: Boolean- ): Int {- val values = ContentValues().apply {- put("name", name)- put("latitude", lat)- put("longitude", lon)- put("radius", rad)- put("enabled", 1)- put("pause_tracking", if (pause) 1 else 0)- put("created_at", System.currentTimeMillis())- }-- return dbHelper.writableDatabase- .insert(LocationDatabaseHelper.TABLE_GEOFENCES, null, values)- .toInt()- }-- /**- * Updates geofence with only provided fields.- */- fun updateGeofence(- id: Int,- name: String?,- lat: Double?,- lon: Double?,- rad: Double?,- en: Boolean?,- pause: Boolean?- ): Boolean {- val values = ContentValues().apply {- name?.let { put("name", it) }- lat?.let { put("latitude", it) }- lon?.let { put("longitude", it) }- rad?.let { put("radius", it) }- en?.let { put("enabled", if (it) 1 else 0) }- pause?.let { put("pause_tracking", if (it) 1 else 0) }- }-- if (values.size() == 0) return false-- return dbHelper.writableDatabase.update(- LocationDatabaseHelper.TABLE_GEOFENCES,- values,- "id = ?",- arrayOf(id.toString())- ) > 0- }-- /**- * Deletes a geofence by ID.- */- fun deleteGeofence(id: Int): Boolean {- return dbHelper.writableDatabase.delete(- LocationDatabaseHelper.TABLE_GEOFENCES,- "id = ?",- arrayOf(id.toString())- ) > 0- }-}\ No newline at end of file