Skip to content

Colota - Android GPS Location tracker

Refactor Android native layer: sub-packages, aligned defaults, docs - Reorganize flat 17-file com.Colota package into sub-packages (bridge/, service/, data/, sync/, util/) - Align ServiceConfig fallbacks and DB prepopulation with JS defaults - Fix notification showing "Last sync: Never" after active syncs - Add useful comments across all native modules - Fix gradlew scripts for Windows compatibility - Update docs to reflect new package structure and modules

Max Dietrich74a2422dbb65
diff --git a/apps/docs/docs/configuration/gps-settings.md b/apps/docs/docs/configuration/gps-settings.md
index 081a591c..bb1323ec 100644
--- a/apps/docs/docs/configuration/gps-settings.md
+++ b/apps/docs/docs/configuration/gps-settings.md
@@ -6,19 +6,19 @@ sidebar_position: 2
## Available Settings
-| Setting | Description | Default | Range |
-| ------------------ | ------------------------------------ | --------- | ----------- |
-| Tracking Interval | Time between GPS fixes | 5 seconds | 1s -- hours |
-| Movement Threshold | Minimum movement to trigger update | 0 meters | 0m -- 1000m |
-| Accuracy Threshold | Filter out fixes above this accuracy | 50 meters | 0m -- 1000m |
-| Filter Inaccurate | Enable/disable accuracy filtering | Disabled | On/Off |
+| Setting | Description | Default | Range |
+| ------------------ | ------------------------------------ | --------- | ---------- |
+| Tracking Interval | Time between GPS fixes | 5 seconds | 1s - hours |
+| Movement Threshold | Minimum movement to trigger update | 0 meters | 0m - 1000m |
+| Accuracy Threshold | Filter out fixes above this accuracy | 50 meters | 0m - 1000m |
+| Filter Inaccurate | Enable/disable accuracy filtering | Disabled | On/Off |
## Tracking Interval
How often the app requests a GPS fix. Shorter intervals give denser track points but drain more battery.
-- **1--5 seconds**: High detail, suitable for driving or cycling
-- **15--30 seconds**: Good balance for walking or commuting
+- **1-5 seconds**: High detail, suitable for driving or cycling
+- **15-30 seconds**: Good balance for walking or commuting
- **60+ seconds**: Low battery usage, suitable for long trips
## Movement Threshold
@@ -26,7 +26,7 @@ How often the app requests a GPS fix. Shorter intervals give denser track points
Only records a new location if you've moved at least this many meters since the last recorded point. Useful for filtering out stationary noise.
- **0m**: Record every GPS fix (default)
-- **10--50m**: Skip stationary updates, good for daily use
+- **10-50m**: Skip stationary updates, good for daily use
## Accuracy Filter
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index f580b693..81cabf8b 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -4,12 +4,12 @@ sidebar_position: 3
# Server Settings
-| Setting | Description | Default | Range |
-| -------------------- | ----------------------------------------- | --------------- | ----------- |
-| Endpoint | HTTPS URL of your server | Empty (offline) | -- |
-| Sync Interval | Batch mode interval | Instant (0) | 0s -- 15min |
-| Retry Failed Uploads | Keep retrying failed uploads indefinitely | Off | On/Off |
-| Offline Mode | Disable all network activity | Disabled | On/Off |
+| Setting | Description | Default | Range |
+| -------------------- | ----------------------------------------- | --------------- | ---------- |
+| Endpoint | HTTPS URL of your server | Empty (offline) | -- |
+| Sync Interval | Batch mode interval | Instant (0) | 0s - 15min |
+| Retry Failed Uploads | Keep retrying failed uploads indefinitely | Off | On/Off |
+| Offline Mode | Disable all network activity | Disabled | On/Off |
## Endpoint URL
@@ -18,15 +18,15 @@ Your server endpoint must accept HTTPS POST requests. HTTP is only allowed for p
- `127.0.0.1` / `localhost`
- `192.168.x.x`
- `10.x.x.x`
-- `172.16--31.x.x`
+- `172.16.x.x – 172.31.x.x`
Use the **Test Connection** button in settings to verify your server is reachable.
## Sync Modes
- **Instant (0s)**: Each location is sent immediately after recording
-- **Batch (1--60 min)**: Locations are queued and sent in batches at the configured interval
-- **Offline**: No network activity -- data is stored locally only
+- **Batch (1-60 min)**: Locations are queued and sent in batches at the configured interval
+- **Offline**: No network activity - data is stored locally only
## Retry Behavior
diff --git a/apps/docs/docs/configuration/sync-presets.md b/apps/docs/docs/configuration/sync-presets.md
index 94075f37..7b40241b 100644
--- a/apps/docs/docs/configuration/sync-presets.md
+++ b/apps/docs/docs/configuration/sync-presets.md
@@ -11,6 +11,6 @@ Colota includes built-in presets that configure tracking interval, movement thre
| **Instant** | 5s | 0m | Instant (0s) | City navigation |
| **Balanced** | 30s | 1m | 5 minutes | Daily commute |
| **Power Saver** | 60s | 2m | 15 minutes | Long trips |
-| **Custom** | 1s--∞ | 0m--∞ | 0s--∞ | Advanced users |
+| **Custom** | 1s-∞ | 0m-∞ | 0s-∞ | Advanced users |
Select a preset in **Settings** or choose **Custom** to configure each parameter individually.
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 4888e935..9958d8cb 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -46,7 +46,7 @@ The mobile app has a **React Native** UI layer and **native Kotlin** modules for
## Native Kotlin Modules
-All native code lives in `apps/mobile/android/app/src/main/java/com/colota/`.
+All native code lives in `apps/mobile/android/app/src/main/java/com/colota/`, organized into sub-packages: `bridge/`, `service/`, `data/`, `sync/`, and `util/`.
### LocationServiceModule
@@ -58,9 +58,11 @@ The primary React Native bridge module (exposed as `"LocationServiceModule"`). H
- Settings persistence
- Device info, file operations, authentication
-Emits two events back to JavaScript:
+Emits events back to JavaScript:
- `onLocationUpdate` — new GPS fix received
+- `onTrackingStopped` — service stopped (user action or OOM kill)
+- `onSyncError` — 3+ consecutive sync failures
- `onPauseZoneChange` — entered or exited a geofence pause zone
### LocationForegroundService
@@ -114,8 +116,9 @@ Wraps Android's `EncryptedSharedPreferences` for AES-256-GCM encrypted credentia
| `LocationBootReceiver` | Auto-restarts tracking after device reboot |
| `DeviceInfoHelper` | Device metadata and battery status with caching |
| `FileOperations` | File I/O for data export via FileProvider |
-| `LocationUtils` | Builds JSON payloads with dynamic field mapping |
+| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |
| `ServiceConfig` | Centralized configuration data class |
+| `TimedCache` | Generic TTL cache used for queue count and device info |
| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |
## React Native Layer
diff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.md
index 4e1de281..f26994c4 100644
--- a/apps/docs/docs/development/local-setup.md
+++ b/apps/docs/docs/development/local-setup.md
@@ -90,14 +90,13 @@ colota/
│ ├── mobile/
│ │ ├── android/ # Android native project
│ │ │ └── app/src/main/java/com/colota/
-│ │ │ ├── LocationServiceModule.kt # RN bridge
-│ │ │ ├── LocationForegroundService.kt # GPS service
-│ │ │ ├── DatabaseHelper.kt # SQLite
-│ │ │ ├── SyncManager.kt # HTTP sync
-│ │ │ ├── NetworkManager.kt # Network layer
-│ │ │ ├── GeofenceHelper.kt # Pause zones
-│ │ │ ├── SecureStorageHelper.kt # Encrypted storage
-│ │ │ └── ...
+│ │ │ ├── bridge/ # React Native bridge
+│ │ │ ├── service/ # Foreground service & config
+│ │ │ ├── data/ # SQLite & geofencing
+│ │ │ ├── sync/ # Network sync & payloads
+│ │ │ ├── util/ # Helpers & encryption
+│ │ │ ├── MainActivity.kt
+│ │ │ └── MainApplication.kt
│ │ ├── src/
│ │ │ ├── screens/ # 9 app screens
│ │ │ ├── components/ # UI and feature components
@@ -129,8 +128,8 @@ colota/
### Modifying Native Modules
-1. Edit the Kotlin file in `apps/mobile/android/app/src/main/java/com/colota/`
-2. If adding a new method to `LocationServiceModule`, expose it via `@ReactMethod`
+1. Edit the Kotlin file in `apps/mobile/android/app/src/main/java/com/colota/<subpackage>/`
+2. If adding a new method to `LocationServiceModule` (`bridge/`), expose it via `@ReactMethod`
3. Add the corresponding TypeScript method in `apps/mobile/src/services/NativeLocationService.ts`
4. Rebuild the Android app (`npx react-native run-android`)
diff --git a/apps/docs/docs/faq.md b/apps/docs/docs/faq.md
index 5f926472..77769e20 100644
--- a/apps/docs/docs/faq.md
+++ b/apps/docs/docs/faq.md
@@ -18,7 +18,7 @@ No, but you can use [Dawarich](/docs/integrations/dawarich) or a custom backend
### Does this work without Google Play Services?
-Not currently -- Colota uses Android's `FusedLocationProvider` which requires Google Play Services.
+Not currently. Colota uses Android's `FusedLocationProvider` which requires Google Play Services.
### Why AGPL-3.0?
@@ -26,7 +26,7 @@ To ensure modifications stay open source, especially server-side components.
### How accurate is the tracking?
-3--10 meters in open sky, 10--50 meters in urban areas. The [accuracy filter](/docs/configuration/gps-settings#accuracy-filter) helps remove poor fixes.
+3-10 meters in open sky, 10-50 meters in urban areas. The [accuracy filter](/docs/configuration/gps-settings#accuracy-filter) helps remove poor fixes.
### Can I export my location history?
diff --git a/apps/docs/docs/getting-started/build-from-source.md b/apps/docs/docs/getting-started/build-from-source.md
index 0ee7fa2d..e94b6fe0 100644
--- a/apps/docs/docs/getting-started/build-from-source.md
+++ b/apps/docs/docs/getting-started/build-from-source.md
@@ -17,7 +17,7 @@ git clone https://github.com/dietrichmax/colota.git
cd colota
npm install
cd apps/mobile/android
-./gradlew assembleRelease
+gradlew assembleRelease # or ./gradlew on Linux/macOS
```
The APK will be at `apps/mobile/android/app/build/outputs/apk/release/`.
diff --git a/apps/docs/docs/guides/battery-optimization.md b/apps/docs/docs/guides/battery-optimization.md
index 523e2d65..344a2d2a 100644
--- a/apps/docs/docs/guides/battery-optimization.md
+++ b/apps/docs/docs/guides/battery-optimization.md
@@ -15,11 +15,11 @@ Settings and tips to reduce battery usage without losing GPS fixes.
## Tips
-1. **Increase GPS interval** -- 5s to 30s saves significant battery
-2. **Enable accuracy filtering** -- Reject poor GPS fixes to avoid unnecessary processing
-3. **Use batch sync** instead of instant -- Reduces network usage and wake-ups
-4. **Create geofences** for home/work -- GPS stops completely in zones
-5. **Enable movement threshold** -- 10--50m, skip stationary updates
+1. **Increase GPS interval** - 5s to 30s saves significant battery
+2. **Enable accuracy filtering** - Reject poor GPS fixes to avoid unnecessary processing
+3. **Use batch sync** instead of instant - Reduces network usage and wake-ups
+4. **Create geofences** for home/work - GPS stops completely in zones
+5. **Enable movement threshold** - 10-50m, skip stationary updates
6. **Disable battery optimization** for Colota in Android settings to prevent the OS from killing the service
## Android Battery Settings
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index 447346b1..b620cb0b 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -33,9 +33,9 @@ Export your location history in multiple formats.
In the Data Management screen you can also:
-- **Clear Sent History** -- Remove locations that have already been synced
-- **Delete Older Than X Days** -- Clean up old data
-- **Vacuum Database** -- Reclaim disk space after deletions
+- **Clear Sent History** - Remove locations that have already been synced
+- **Delete Older Than X Days** - Clean up old data
+- **Vacuum Database** - Reclaim disk space after deletions
### Storage Reference
diff --git a/apps/docs/docs/guides/geofencing.md b/apps/docs/docs/guides/geofencing.md
index 90b64d8e..c357f2c8 100644
--- a/apps/docs/docs/guides/geofencing.md
+++ b/apps/docs/docs/guides/geofencing.md
@@ -8,9 +8,9 @@ Create zones where tracking pauses automatically. These "pause zones" save batte
## Use Cases
-- **Home** -- Don't track when at home
-- **Work** -- Pause tracking during work hours
-- **Frequent locations** -- Save battery in places you visit often
+- **Home** - Don't track when at home
+- **Work** - Pause tracking during work hours
+- **Frequent locations** - Save battery in places you visit often
## Setup
@@ -28,7 +28,7 @@ Create zones where tracking pauses automatically. These "pause zones" save batte
## How It Works
-- Zone detection uses the Haversine formula (1--2ms per check)
+- Zone detection uses the Haversine formula (1-2ms per check)
- When entering a pause zone, GPS stops updating
- The notification shows "Paused: [Zone Name]"
- When exiting the zone, tracking automatically resumes
diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.md
index 1f1f9da4..34d00422 100644
--- a/apps/docs/docs/guides/troubleshooting.md
+++ b/apps/docs/docs/guides/troubleshooting.md
@@ -12,14 +12,14 @@ sidebar_position: 4
## GPS accuracy is poor
-- Wait for GPS lock (can take 30--60 seconds)
+- Wait for GPS lock (can take 30-60 seconds)
- Move to an open area away from buildings
- Check if **High Accuracy** is enabled in device location settings
- Enable **Filter Inaccurate Locations** in app settings
## Server sync not working
-1. Check endpoint URL format -- must be `https://` or `http://localhost`
+1. Check endpoint URL format - must be `https://` or `http://localhost`
2. Use the **Test Connection** button in settings
3. Check server logs for incoming requests
4. Verify network connectivity
diff --git a/apps/docs/docs/integrations/custom-backend.md b/apps/docs/docs/integrations/custom-backend.md
index ec0260ed..2dcc82db 100644
--- a/apps/docs/docs/integrations/custom-backend.md
+++ b/apps/docs/docs/integrations/custom-backend.md
@@ -103,10 +103,10 @@ your-domain.com {
Colota works with any service that accepts JSON POST requests, including:
-- **Home Assistant** -- via webhook or REST API
-- **Traccar** -- GPS tracking platform
-- **Node-RED** -- flow-based automation
-- **Custom APIs** -- any server you build
+- **Home Assistant** - via webhook or REST API
+- **Traccar** - GPS tracking platform
+- **Node-RED** - flow-based automation
+- **Custom APIs** - any server you build
## Configuration
diff --git a/apps/docs/docs/integrations/dawarich.md b/apps/docs/docs/integrations/dawarich.md
index 80402bb8..7f5ea609 100644
--- a/apps/docs/docs/integrations/dawarich.md
+++ b/apps/docs/docs/integrations/dawarich.md
@@ -8,7 +8,7 @@ sidebar_position: 2
## Setup
-1. **Install Dawarich** -- follow the [Dawarich documentation](https://github.com/Freika/dawarich)
+1. **Install Dawarich** - follow the [Dawarich documentation](https://github.com/Freika/dawarich)
2. **Get your API Key** from Dawarich settings
3. **Configure Colota**:
- Go to **Settings > API Settings**
diff --git a/apps/docs/docs/integrations/owntracks.md b/apps/docs/docs/integrations/owntracks.md
index 31e74886..aa08c624 100644
--- a/apps/docs/docs/integrations/owntracks.md
+++ b/apps/docs/docs/integrations/owntracks.md
@@ -8,7 +8,7 @@ sidebar_position: 3
## Setup
-1. **Install OwnTracks Recorder** -- follow the [OwnTracks documentation](https://owntracks.org/booklet/)
+1. **Install OwnTracks Recorder** - follow the [OwnTracks documentation](https://owntracks.org/booklet/)
2. **Configure Colota**:
- Go to **Settings > API Settings**
- Select the **OwnTracks** template
diff --git a/apps/docs/docs/integrations/reitti.md b/apps/docs/docs/integrations/reitti.md
index 7a56a9f1..c4c83443 100644
--- a/apps/docs/docs/integrations/reitti.md
+++ b/apps/docs/docs/integrations/reitti.md
@@ -8,7 +8,7 @@ sidebar_position: 4
## Setup
-1. **Install Reitti** -- follow the [Reitti documentation](https://github.com/Moo-Ack-Productions/reitti)
+1. **Install Reitti** - follow the [Reitti documentation](https://github.com/Moo-Ack-Productions/reitti)
2. **Configure Colota**:
- Go to **Settings > API Settings**
- Select the **Reitti** template
diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml
index c768a8cd..aa1a4507 100644
--- a/apps/mobile/android/app/src/main/AndroidManifest.xml
+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml
@@ -58,7 +58,7 @@
<!-- Foreground location service -->
<service
- android:name=".LocationForegroundService"
+ android:name=".service.LocationForegroundService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="location"
@@ -71,7 +71,7 @@
<!-- Boot Receiver -->
<receiver
- android:name=".LocationBootReceiver"
+ android:name=".service.LocationBootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
diff --git a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
index 3d654ebb..38330e67 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt
@@ -12,6 +12,7 @@ import com.facebook.react.ReactHost
import com.facebook.react.ReactPackage
import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
+import com.Colota.bridge.LocationServicePackage
class MainApplication : Application(), ReactApplication {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/BuildConfigModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt
similarity index 95%
rename from apps/mobile/android/app/src/main/java/com/colota/BuildConfigModule.kt
rename to apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt
index 04fde540..68306f3d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/BuildConfigModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt
@@ -3,9 +3,10 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
- package com.Colota
+ package com.Colota.bridge
import com.facebook.react.bridge.ReactApplicationContext
+import com.Colota.BuildConfig
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
similarity index 72%
rename from apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt
rename to apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index e5d3f3fd..372cf2ae 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -3,13 +3,19 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.bridge
-import android.content.Context
-import android.os.PowerManager
-import android.provider.Settings
-import android.net.Uri
import android.content.Intent
+import com.Colota.BuildConfig
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.GeofenceHelper
+import com.Colota.service.LocationForegroundService
+import com.Colota.service.ServiceConfig
+import com.Colota.sync.NetworkManager
+import com.Colota.sync.PayloadBuilder
+import com.Colota.util.DeviceInfoHelper
+import com.Colota.util.FileOperations
+import com.Colota.util.SecureStorageHelper
import android.os.Build
import android.util.Log
import com.facebook.react.bridge.*
@@ -26,7 +32,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext),
LifecycleEventListener {
- private val locationUtils = LocationUtils()
+ private val payloadBuilder = PayloadBuilder()
private val dbHelper = DatabaseHelper.getInstance(reactContext)
private val fileOps = FileOperations(reactContext)
private val deviceInfo = DeviceInfoHelper(reactContext)
@@ -34,7 +40,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
private val secureStorage = SecureStorageHelper.getInstance(reactContext)
private val networkManager = NetworkManager(reactContext)
- // Coroutine scope for async operations
private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
init {
@@ -49,12 +54,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@Volatile
private var isAppInForeground: Boolean = true
- /**
- * Emits location updates to the React Native 'onLocationUpdate' listener.
- */
+ /** Skips when app is backgrounded to avoid unnecessary bridge overhead. */
@JvmStatic
fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {
- // Check foreground state first (cheapest check)
if (!isAppInForeground) return false
val context = reactContextStatic ?: return false
@@ -89,9 +91,48 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- /**
- * Emits pause zone entry/exit events to the React Native 'onPauseZoneChange' listener.
- */
+ /** Fires when service stops for non-user reasons (OOM kill, system cleanup). */
+ @JvmStatic
+ fun sendTrackingStoppedEvent(reason: String): Boolean {
+ val context = reactContextStatic ?: return false
+ if (!context.hasActiveCatalystInstance()) return false
+
+ return try {
+ val params = Arguments.createMap().apply {
+ putString("reason", reason)
+ }
+ context
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
+ .emit("onTrackingStopped", params)
+ true
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to send tracking stopped event", e)
+ false
+ }
+ }
+
+ /** Only fires after 3+ consecutive sync failures — see SyncManager.startPeriodicSync(). */
+ @JvmStatic
+ fun sendSyncErrorEvent(message: String, queuedCount: Int): Boolean {
+ val context = reactContextStatic ?: return false
+ if (!context.hasActiveCatalystInstance()) return false
+
+ return try {
+ val params = Arguments.createMap().apply {
+ putString("message", message)
+ putInt("queuedCount", queuedCount)
+ }
+ context
+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
+ .emit("onSyncError", params)
+ true
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to send sync error event", e)
+ false
+ }
+ }
+
+ /** Emits pause zone entry/exit events for the JS geofence UI. */
@JvmStatic
fun sendPauseZoneEvent(entered: Boolean, zoneName: String?): Boolean {
val context = reactContextStatic ?: return false
@@ -115,7 +156,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
override fun getName(): String = "LocationServiceModule"
- // Lifecycle
override fun onHostResume() {
isAppInForeground = true
}
@@ -130,19 +170,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
override fun invalidate() {
moduleScope.cancel()
+ reactContextStatic = null
super.invalidate()
}
- // ==============================================================
- // HELPERS
- // ==============================================================
-
- /**
- * Standardized wrapper to resolve or reject a Promise.
- * Runs operation on database executor to avoid blocking main thread.
- * Checks if executor is active to prevent RejectedExecutionException.
- */
+ /** Runs on IO thread and resolves/rejects the JS promise. */
private fun executeAsync(promise: Promise, operation: suspend () -> Any?) {
moduleScope.launch {
try {
@@ -155,38 +188,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // ==============================================================
- // SERVICE CONTROL
- // ==============================================================
-
- /**
- * Starts the Foreground Tracking Service with the provided configuration.
- */
@ReactMethod
fun startService(config: ReadableMap) {
Log.d(TAG, "Starting Service with config")
-
- // Don't block on DB write - do it async
- moduleScope.launch(Dispatchers.IO) {
+
+ moduleScope.launch(Dispatchers.IO) {
dbHelper.saveSetting("tracking_enabled", "true")
}
- val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- config.getDoubleOrNull("interval")?.let { putExtra("interval", it.toLong()) }
- config.getDoubleOrNull("minUpdateDistance")?.let { putExtra("minUpdateDistance", it.toFloat()) }
- config.getStringOrNull("endpoint")?.let { putExtra("endpoint", it) }
- config.getIntOrNull("syncInterval")?.let { putExtra("syncInterval", it) }
- config.getDoubleOrNull("accuracyThreshold")?.let { putExtra("accuracyThreshold", it.toFloat()) }
- config.getBooleanOrNull("filterInaccurateLocations")?.let { putExtra("filterInaccurateLocations", it) }
- config.getIntOrNull("maxRetries")?.let { putExtra("maxRetries", it) }
- config.getIntOrNull("retryInterval")?.let { putExtra("retryInterval", it) }
- config.getBooleanOrNull("isOfflineMode")?.let { putExtra("isOfflineMode", it) }
-
- config.getMap("fieldMap")?.let { map ->
- val jsonString = locationUtils.convertFieldMapToJson(map)
- putExtra("fieldMap", jsonString)
- }
- }
+ val serviceConfig = ServiceConfig.fromReadableMap(config, dbHelper)
+ val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java)
+ serviceConfig.toIntent(serviceIntent)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@@ -199,48 +211,22 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- /**
- * Stops the background service and persists the disabled state.
- */
@ReactMethod
fun stopService() {
Log.d(TAG, "Stopping Service via UI")
-
- // Stop service first (immediate), then save to DB
+
val intent = Intent(reactApplicationContext, LocationForegroundService::class.java)
reactApplicationContext.stopService(intent)
-
- // Save disabled state async (don't block)
- moduleScope.launch(Dispatchers.IO) {
+
+ moduleScope.launch(Dispatchers.IO) {
dbHelper.saveSetting("tracking_enabled", "false")
}
}
- // ==============================================================
- // STATS & DATA RETRIEVAL
- // ==============================================================
-
- @ReactMethod
- fun getQueuedLocationsCount(promise: Promise) =
- executeAsync(promise) { dbHelper.getQueuedCount() }
-
- @ReactMethod
- fun getSentCount(promise: Promise) =
- executeAsync(promise) { dbHelper.getSentCount() }
-
- @ReactMethod
- fun getTotalCount(promise: Promise) =
- executeAsync(promise) { dbHelper.getTotalCount() }
-
- @ReactMethod
- fun getTodayCount(promise: Promise) =
- executeAsync(promise) { dbHelper.getTodayCount() }
-
- @ReactMethod
- fun getDatabaseSize(promise: Promise) =
+ @ReactMethod
+ fun getDatabaseSize(promise: Promise) =
executeAsync(promise) { dbHelper.getDatabaseSizeMB() }
- // Combined stats query for better performance
@ReactMethod
fun getStats(promise: Promise) = executeAsync(promise) {
val (queued, total, today) = dbHelper.getStats()
@@ -263,10 +249,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // ==============================================================
- // DATABASE MANAGEMENT
- // ==============================================================
-
@ReactMethod
fun manualFlush(promise: Promise) {
try {
@@ -312,11 +294,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
true
}
- // ==============================================================
- // GEOFENCE OPERATIONS
- // ==============================================================
-
- // Helper function to trigger zone Rechecks
private fun triggerZoneRecheck() {
try {
startServiceWithAction(LocationForegroundService.ACTION_RECHECK_ZONE)
@@ -388,10 +365,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
result
}
- // ==============================================================
- // PAUSE ZONE LOGIC
- // ==============================================================
-
@ReactMethod
fun checkCurrentPauseZone(promise: Promise) {
val fusedClient = LocationServices.getFusedLocationProviderClient(reactApplicationContext)
@@ -431,10 +404,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // ==============================================================
- // SETTINGS PERSISTENCE
- // ==============================================================
-
@ReactMethod
fun saveSetting(key: String, value: String, promise: Promise) =
executeAsync(promise) {
@@ -456,19 +425,11 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // ==============================================================
- // NETWORK
- // ==============================================================
-
@ReactMethod
fun isNetworkAvailable(promise: Promise) {
promise.resolve(networkManager.isNetworkAvailable())
}
- // ==============================================================
- // UTILITY
- // ==============================================================
-
@ReactMethod
fun getMostRecentLocation(promise: Promise) = executeAsync(promise) {
dbHelper.getRawMostRecentLocation()?.let { data ->
@@ -476,15 +437,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // Cache power manager
- private val powerManager by lazy {
- reactApplicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager
- }
-
- // ==============================================================
- // BATTERY OPTIMIZATION (Delegated to DeviceInfoHelper)
- // ==============================================================
-
@ReactMethod
fun isIgnoringBatteryOptimizations(promise: Promise) {
promise.resolve(deviceInfo.isIgnoringBatteryOptimizations())
@@ -500,7 +452,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // helper for all service intents
private fun startServiceWithAction(action: String) {
try {
val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
@@ -518,13 +469,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- // ==============================================================
- // DEVICE INFORMATION (Delegated to DeviceInfoHelper)
- // ==============================================================
-
- /**
- * Returns device information as a map
- */
@ReactMethod
fun getDeviceInfo(promise: Promise) {
try {
@@ -534,9 +478,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- /**
- * Individual getters for compatibility
- */
@ReactMethod
fun getSystemVersion(promise: Promise) {
promise.resolve(deviceInfo.getSystemVersion())
@@ -562,10 +503,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise.resolve(deviceInfo.getDeviceId())
}
- // ==============================================================
- // File Operations (Delegated to FileOperations)
- // ==============================================================
-
@ReactMethod
fun writeFile(fileName: String, content: String, promise: Promise) =
executeAsync(promise) { fileOps.writeFile(fileName, content) }
@@ -584,10 +521,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
fun getCacheDirectory(promise: Promise) =
executeAsync(promise) { fileOps.getCacheDirectory() }
- // ==============================================================
- // SECURE STORAGE (Delegated to SecureStorageHelper)
- // ==============================================================
-
@ReactMethod
fun getAllAuthConfig(promise: Promise) = executeAsync(promise) {
Arguments.createMap().apply {
@@ -628,15 +561,3 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
-// Extension functions for safer ReadableMap access
-private fun ReadableMap.getDoubleOrNull(key: String): Double? =
- if (hasKey(key)) getDouble(key) else null
-
-private fun ReadableMap.getIntOrNull(key: String): Int? =
- if (hasKey(key)) getInt(key) else null
-
-private fun ReadableMap.getStringOrNull(key: String): String? =
- if (hasKey(key)) getString(key) else null
-
-private fun ReadableMap.getBooleanOrNull(key: String): Boolean? =
- if (hasKey(key)) getBoolean(key) else null
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationServicePackage.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt
similarity index 97%
rename from apps/mobile/android/app/src/main/java/com/colota/LocationServicePackage.kt
rename to apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt
index ccd438a6..8fbdc16e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/LocationServicePackage.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.bridge
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
diff --git a/apps/mobile/android/app/src/main/java/com/colota/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
similarity index 85%
rename from apps/mobile/android/app/src/main/java/com/colota/DatabaseHelper.kt
rename to apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index 92cb9271..68b591fc 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -3,9 +3,10 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.data
import android.content.ContentValues
+import com.Colota.BuildConfig
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
@@ -18,15 +19,6 @@ import org.json.JSONObject
/**
* SQLite database helper for Colota location tracking.
- *
- * Optimized for:
- * - No cursor leaks (proper resource management)
- * - Efficient batch operations
- * - Prepared statements for security & speed
- * - Strategic indexing for query performance
- * - Async VACUUM to prevent UI blocking
- *
- * @param context The Android [Context] used to open or create the database.
*/
class DatabaseHelper private constructor(context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
@@ -65,15 +57,9 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- // Cached prepared statements for better performance
private var incrementRetryStmt: SQLiteStatement? = null
- /**
- * Called when the database is created for the first time.
- * Creates schema with optimized indexes.
- */
override fun onCreate(db: SQLiteDatabase) {
- // Create Locations Table
db.execSQL("""
CREATE TABLE $TABLE_LOCATIONS (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -91,7 +77,6 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- // Create Queue Table with Foreign Key
db.execSQL("""
CREATE TABLE $TABLE_QUEUE (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -104,7 +89,6 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- // Create Settings Table
db.execSQL("""
CREATE TABLE $TABLE_SETTINGS (
key TEXT PRIMARY KEY,
@@ -112,7 +96,6 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- // Create Geofences Table
db.execSQL("""
CREATE TABLE $TABLE_GEOFENCES (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -128,7 +111,6 @@ class DatabaseHelper private constructor(context: Context) :
)
""")
- // Optimized indexes
db.execSQL("CREATE INDEX idx_queue_created ON $TABLE_QUEUE(created_at)")
db.execSQL("CREATE INDEX idx_queue_location ON $TABLE_QUEUE(location_id)")
db.execSQL("CREATE INDEX idx_locations_timestamp ON $TABLE_LOCATIONS(timestamp DESC)")
@@ -139,9 +121,6 @@ class DatabaseHelper private constructor(context: Context) :
prepopulateSettings(db)
}
- /**
- * Seeds settings with default values.
- */
private fun prepopulateSettings(db: SQLiteDatabase) {
val fieldMapJson = JSONObject(DEFAULT_FIELD_MAP).toString()
val defaults = mapOf(
@@ -155,7 +134,11 @@ class DatabaseHelper private constructor(context: Context) :
"maxRetries" to "5",
"retryInterval" to "30",
"isOfflineMode" to "false",
- "customFields" to "[]"
+ "customFields" to "[]",
+ "hasCompletedSetup" to "false",
+ "tracking_enabled" to "false",
+ "apiTemplate" to "custom",
+ "syncPreset" to "instant"
)
db.beginTransaction()
@@ -175,36 +158,23 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- /**
- * Configures database connection.
- */
override fun onConfigure(db: SQLiteDatabase) {
super.onConfigure(db)
- db.enableWriteAheadLogging()
-
- // Close cursor after PRAGMA query
+ db.enableWriteAheadLogging() // allows concurrent reads during writes
db.rawQuery("PRAGMA busy_timeout = 5000", null).use { it.moveToFirst() }
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
- db.execSQL("DROP TABLE IF EXISTS $TABLE_QUEUE")
- db.execSQL("DROP TABLE IF EXISTS $TABLE_LOCATIONS")
- db.execSQL("DROP TABLE IF EXISTS $TABLE_SETTINGS")
- db.execSQL("DROP TABLE IF EXISTS $TABLE_GEOFENCES")
- onCreate(db)
+ // Future migrations go here
}
- /**
- * Finalizes database settings after opening.
- */
override fun onOpen(db: SQLiteDatabase) {
super.onOpen(db)
if (!db.isReadOnly) {
- db.execSQL("PRAGMA synchronous = NORMAL")
+ db.execSQL("PRAGMA synchronous = NORMAL") // faster writes, safe with WAL
db.execSQL("PRAGMA foreign_keys = ON")
}
- // Prepare cached statements
incrementRetryStmt = db.compileStatement(
"UPDATE $TABLE_QUEUE SET retry_count = retry_count + 1, last_error = ? WHERE id = ?"
)
@@ -216,11 +186,7 @@ class DatabaseHelper private constructor(context: Context) :
super.close()
}
- // ========================== LOCATION OPERATIONS ==========================
- /**
- * Persists a new location coordinate and metadata.
- */
fun saveLocation(
latitude: Double,
longitude: Double,
@@ -249,9 +215,7 @@ class DatabaseHelper private constructor(context: Context) :
return writableDatabase.insert(TABLE_LOCATIONS, null, values)
}
- /**
- * Retrieves the most recent location.
- */
+ /** Checks both sent and unsent locations to find the most recent one. */
fun getRawMostRecentLocation(): Map<String, Any?>? {
val query = """
SELECT latitude, longitude, accuracy, timestamp
@@ -283,9 +247,6 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- /**
- * Universal table data getter for debugging.
- */
fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {
val data = mutableListOf<Map<String, Any?>>()
@@ -330,7 +291,6 @@ class DatabaseHelper private constructor(context: Context) :
return data
}
- // ========================== QUEUE OPERATIONS ==========================
/**
* Adds location to transmission queue.
@@ -341,14 +301,11 @@ class DatabaseHelper private constructor(context: Context) :
put("location_id", locationId)
put("payload", payload)
put("retry_count", 0)
- put("created_at", System.currentTimeMillis())
+ put("created_at", System.currentTimeMillis() / 1000)
}
return writableDatabase.insert(TABLE_QUEUE, null, values)
}
- /**
- * Retrieves queued locations for batch sync.
- */
fun getQueuedLocations(limit: Int = 10): List<QueuedLocation> {
val locations = mutableListOf<QueuedLocation>()
@@ -374,9 +331,6 @@ class DatabaseHelper private constructor(context: Context) :
return locations
}
- /**
- * Removes queue entry by location ID.
- */
fun removeFromQueueByLocationId(locationId: Long): Int {
return writableDatabase.delete(
TABLE_QUEUE,
@@ -385,9 +339,6 @@ class DatabaseHelper private constructor(context: Context) :
)
}
- /**
- * Batch delete using single query with IN clause.
- */
fun removeBatchFromQueue(queueIds: List<Long>) {
if (queueIds.isEmpty()) return
@@ -405,10 +356,6 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- /**
- * Uses prepared statement for better performance.
- * Thread-safe with synchronized access.
- */
@Synchronized
fun incrementRetryCount(queueId: Long, error: String? = null) {
val stmt = incrementRetryStmt ?: return // Exit if statement is null
@@ -419,11 +366,7 @@ class DatabaseHelper private constructor(context: Context) :
stmt.executeUpdateDelete()
}
- // ========================== STATS OPERATIONS ==========================
- /**
- * Combined stats query
- */
fun getStats(): Triple<Int, Int, Int> {
val query = """
SELECT
@@ -447,7 +390,6 @@ class DatabaseHelper private constructor(context: Context) :
}
}
- /** Individual stat methods for backward compatibility */
fun getQueuedCount(): Int {
return readableDatabase.rawQuery("SELECT COUNT(*) FROM $TABLE_QUEUE", null).use {
if (it.moveToFirst()) it.getInt(0) else 0
@@ -477,11 +419,7 @@ class DatabaseHelper private constructor(context: Context) :
return java.io.File(dbPath).length() / (1024.0 * 1024.0)
}
- // ========================== CLEANUP OPERATIONS ==========================
- /**
- * Purges synchronized history records.
- */
fun clearSentHistory(): Int {
return writableDatabase.delete(
TABLE_LOCATIONS,
@@ -495,7 +433,7 @@ class DatabaseHelper private constructor(context: Context) :
}
fun clearAllLocations(): Int {
- writableDatabase.delete(TABLE_QUEUE, null, null)
+ writableDatabase.delete(TABLE_QUEUE, null, null) // FK constraint: queue references locations
return writableDatabase.delete(TABLE_LOCATIONS, null, null)
}
@@ -508,17 +446,12 @@ class DatabaseHelper private constructor(context: Context) :
)
}
- /**
- * Optimizes database by reclaiming unused space.
- * WARNING: Can block for several seconds on large databases.
- * Call from background thread only.
- */
+ /** Reclaims unused space. Call from background thread only. */
fun vacuum() {
writableDatabase.execSQL("VACUUM")
writableDatabase.execSQL("ANALYZE")
}
- // ========================== SETTINGS OPERATIONS ==========================
fun saveSetting(key: String, value: String) {
val values = ContentValues().apply {
@@ -572,7 +505,6 @@ class DatabaseHelper private constructor(context: Context) :
return settings
}
- // ========================== HELPER METHODS ==========================
private fun getTodayStartTimestamp(): Long {
return Calendar.getInstance().apply {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
similarity index 69%
rename from apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt
rename to apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
index f4390003..87774713 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/GeofenceHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/GeofenceHelper.kt
@@ -3,9 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.data
import android.content.ContentValues
+import com.Colota.BuildConfig
+import com.Colota.util.TimedCache
import android.content.Context
import android.location.Location
import android.util.Log
@@ -17,10 +19,7 @@ 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
+ private val geofenceCache = TimedCache(30000L) { loadGeofencesFromDB() }
data class CachedGeofence(
val name: String,
@@ -34,8 +33,7 @@ class GeofenceHelper(private val context: Context) {
private const val EARTH_RADIUS_METERS = 6371000.0
}
- // --- Math Engine ---
-
+ /** Haversine formula — accurate at any distance on Earth. */
private fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val dLat = Math.toRadians(lat2 - lat1)
val dLon = Math.toRadians(lon2 - lon1)
@@ -45,18 +43,13 @@ class GeofenceHelper(private val context: Context) {
}
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
+ // Fast bounding-box rejection (lon degrees shrink at higher latitudes)
+ val maxLatDeg = radius / 111000.0
+ val maxLonDeg = radius / (111000.0 * cos(Math.toRadians(lat1)))
+ if (Math.abs(lat1 - lat2) > maxLatDeg || Math.abs(lon1 - lon2) > maxLonDeg) return false
return calculateDistance(lat1, lon1, lat2, lon2) <= radius
}
- // --- Core Logic ---
-
- /**
- * Checks if location is within any active pause zone.
- * Returns immediately on first match for better performance.
- */
fun getPauseZone(location: Location): String? {
val fences = getGeofences()
return fences.find {
@@ -64,63 +57,45 @@ class GeofenceHelper(private val context: Context) {
}?.name
}
- /**
- * Invalidates cache when geofences change
- */
fun invalidateCache() {
- cachedGeofences = null
- lastGeofenceCacheTime = 0
-
+ geofenceCache.invalidate()
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)
- ))
+ private fun getGeofences(): List<CachedGeofence> = geofenceCache.get()
+
+ private fun loadGeofencesFromDB(): List<CachedGeofence> {
+ return try {
+ 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)
+ ))
+ }
}
+ fences
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to refresh geofence cache", e)
+ emptyList()
}
- 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()
@@ -129,7 +104,6 @@ class GeofenceHelper(private val context: Context) {
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")
diff --git a/apps/mobile/android/app/src/main/java/com/colota/BootReceiver.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
similarity index 97%
rename from apps/mobile/android/app/src/main/java/com/colota/BootReceiver.kt
rename to apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
index b967d6bb..abf5d375 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/BootReceiver.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BootReceiver.kt
@@ -3,9 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.service
import android.content.BroadcastReceiver
+import com.Colota.BuildConfig
+import com.Colota.data.DatabaseHelper
import android.content.Context
import android.content.Intent
import android.os.Build
diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
similarity index 80%
rename from apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt
rename to apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
index 1e756999..f20e765b 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/LocationForegroundService.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt
@@ -3,9 +3,20 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.service
import android.app.*
+import com.Colota.BuildConfig
+import com.Colota.MainActivity
+import com.Colota.R
+import com.Colota.bridge.LocationServiceModule
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.GeofenceHelper
+import com.Colota.sync.NetworkManager
+import com.Colota.sync.PayloadBuilder
+import com.Colota.sync.SyncManager
+import com.Colota.util.DeviceInfoHelper
+import com.Colota.util.SecureStorageHelper
import android.content.Intent
import android.os.*
import android.util.Log
@@ -19,35 +30,27 @@ import org.json.JSONObject
*/
class LocationForegroundService : Service() {
- // --- Core Components ---
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var notificationManager: NotificationManager
private lateinit var dbHelper: DatabaseHelper
- private lateinit var locationUtils: LocationUtils
+ private lateinit var payloadBuilder: PayloadBuilder
private lateinit var deviceInfoHelper: DeviceInfoHelper
private lateinit var networkManager: NetworkManager
private lateinit var geofenceHelper: GeofenceHelper
private lateinit var secureStorage: SecureStorageHelper
private lateinit var syncManager: SyncManager
- // Properly manage scope lifecycle to prevent memory leak
- private var serviceScope: CoroutineScope? = null
-
- // --- State ---
- private var locationCallback: LocationCallback? = null
+ @Volatile private var serviceScope: CoroutineScope? = null
+ @Volatile private var locationCallback: LocationCallback? = null
private var insidePauseZone = false
private var currentZoneName: String? = null
private var lastNotificationText: String? = null
-
- // Notification throttling
+
private var lastNotificationTime: Long = 0
- private val NOTIFICATION_THROTTLE_MS = 10000L // Max 1 per 5 seconds
-
- // Location caching
- private var lastKnownLocation: android.location.Location? = null
- private var lastNotificationCoords: Pair<Double, Double>? = null
+ private val NOTIFICATION_THROTTLE_MS = 10000L
+ @Volatile private var lastKnownLocation: android.location.Location? = null
+ private var lastNotificationCoords: Pair<Double, Double>? = null
- // --- Configuration (use ServiceConfig) ---
private lateinit var config: ServiceConfig
private var fieldMap: Map<String, String>? = null
private var customFields: Map<String, String>? = null
@@ -62,22 +65,15 @@ class LocationForegroundService : Service() {
const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"
}
- data class GeofenceInfo(val id: Int, val name: String)
-
- // ========================================
- // SERVICE LIFECYCLE
- // ========================================
-
override fun onCreate() {
super.onCreate()
- // Create scope once in onCreate
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
dbHelper = DatabaseHelper.getInstance(this)
- locationUtils = LocationUtils()
+ payloadBuilder = PayloadBuilder()
deviceInfoHelper = DeviceInfoHelper(this)
networkManager = NetworkManager(this)
geofenceHelper = GeofenceHelper(this)
@@ -95,6 +91,7 @@ class LocationForegroundService : Service() {
val savedSettings = dbHelper.getAllSettings()
val shouldBeTracking = savedSettings["tracking_enabled"]?.toBoolean() ?: false
+ // intent == null: Android restarted the service after OOM kill
if (intent == null && !shouldBeTracking) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "System restart prevented")
@@ -136,6 +133,7 @@ class LocationForegroundService : Service() {
}
else -> {
serviceScope?.launch {
+ // FusedLocationClient requires Main looper
withContext(Dispatchers.Main) {
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -161,7 +159,6 @@ class LocationForegroundService : Service() {
stopLocationUpdates()
syncManager.stopPeriodicSync()
- // Properly cancel scope to prevent memory leak
serviceScope?.cancel()
serviceScope = null
@@ -171,10 +168,6 @@ class LocationForegroundService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
- // ========================================
- // LOCATION UPDATES (GPS QUALITY)
- // ========================================
-
private fun setupLocationUpdates() {
locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
@@ -182,21 +175,16 @@ class LocationForegroundService : Service() {
}
}
- // Check if battery is critically low using DeviceInfoHelper
if (deviceInfoHelper.isBatteryCritical(threshold = 5)) {
val (level, _) = deviceInfoHelper.getCachedBatteryStatus()
if (BuildConfig.DEBUG) {
Log.d(TAG, "Battery critical ($level%) and unplugged - stopping service")
}
stopForegroundServiceWithReason("Battery critical")
- return // Exit early - don't setup location updates
+ return
}
- // Battery is OK or charging - use high accuracy
- val priority = Priority.PRIORITY_HIGH_ACCURACY
-
- // Request parameters
- val locationRequest = LocationRequest.Builder(priority, config.interval * 2)
+ val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, config.interval * 2)
.setMinUpdateIntervalMillis(config.interval)
.setMinUpdateDistanceMeters(config.minUpdateDistance)
.setMaxUpdateDelayMillis(config.interval * 2)
@@ -215,7 +203,7 @@ class LocationForegroundService : Service() {
// Check if starting in a pause zone
geofenceHelper.getPauseZone(it)?.let { zoneName ->
- enterPauseZone(GeofenceInfo(-1, zoneName))
+ enterPauseZone(zoneName)
} ?: run {
// Not in zone - show coordinates immediately
updateNotification(it.latitude, it.longitude, forceUpdate = true)
@@ -274,7 +262,7 @@ class LocationForegroundService : Service() {
when {
// Just entered a pause zone or changed zones
zoneName != null && (!insidePauseZone || zoneName != currentZoneName) -> {
- enterPauseZone(GeofenceInfo(-1, zoneName))
+ enterPauseZone(zoneName)
}
// Just exited pause zone
@@ -304,104 +292,85 @@ class LocationForegroundService : Service() {
}
}
- // ========================================
- // DATA PROCESSING (GPS QUALITY)
- // ========================================
-
private fun handleLocationUpdate(location: android.location.Location) {
- // Early returns for filtering
if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
return
}
-
- // Cache location
+
lastKnownLocation = location
- // Pause Zone Logic - CHECK IF IT'S A PAUSE ZONE
val zoneName = geofenceHelper.getPauseZone(location)
-
when {
zoneName != null && !insidePauseZone -> {
- // Entering a pause zone
- enterPauseZone(GeofenceInfo(-1, zoneName))
- return // Don't record location in pause zone
- }
- zoneName == null && insidePauseZone -> {
- // Exiting pause zone
- exitPauseZone()
- }
- zoneName != null && insidePauseZone -> {
- // Still in pause zone, skip recording
+ enterPauseZone(zoneName)
return
}
+ zoneName == null && insidePauseZone -> exitPauseZone()
+ zoneName != null && insidePauseZone -> return
}
- // Use cached battery from DeviceInfoHelper
val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()
val timestampSec = location.time / 1000
+ val currentFieldMap = fieldMap ?: emptyMap()
- // Save to database
- val locationId = dbHelper.saveLocation(
- latitude = location.latitude,
- longitude = location.longitude,
- accuracy = location.accuracy.toDouble(),
- altitude = if (location.hasAltitude()) location.altitude.toInt() else null,
- speed = location.speed.toDouble(),
- bearing = if (location.hasBearing()) location.bearing.toDouble() else 0.0,
- battery = battery,
- battery_status = batteryStatus,
- timestamp = timestampSec,
- endpoint = config.endpoint
- )
+ // DB + network on IO thread; notification dispatches back to Main
+ serviceScope?.launch {
+ val locationId = dbHelper.saveLocation(
+ latitude = location.latitude,
+ longitude = location.longitude,
+ accuracy = location.accuracy.toDouble(),
+ altitude = if (location.hasAltitude()) location.altitude.toInt() else null,
+ speed = location.speed.toDouble(),
+ bearing = if (location.hasBearing()) location.bearing.toDouble() else 0.0,
+ battery = battery,
+ battery_status = batteryStatus,
+ timestamp = timestampSec,
+ endpoint = config.endpoint
+ )
- // Send to React Native
- LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
+ LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
+
+ val payload = payloadBuilder.buildPayload(
+ location,
+ battery,
+ batteryStatus,
+ currentFieldMap,
+ timestampSec,
+ customFields
+ )
- // Build payload once
- val currentFieldMap = fieldMap ?: emptyMap()
- val payload = locationUtils.buildPayload(
- location,
- battery,
- batteryStatus,
- currentFieldMap,
- timestampSec,
- customFields
- )
-
- // Queue and optionally send
- serviceScope?.launch {
syncManager.queueAndSend(locationId, payload)
+
+ withContext(Dispatchers.Main) {
+ updateNotification(location.latitude, location.longitude)
+ }
}
-
- // Update notification (throttled)
- updateNotification(location.latitude, location.longitude)
}
- private fun enterPauseZone(zone: GeofenceInfo) {
+ private fun enterPauseZone(zoneName: String) {
insidePauseZone = true
- currentZoneName = zone.name
-
- // Always show paused status when entering a pause zone
+ currentZoneName = zoneName
+
lastKnownLocation?.let { loc ->
updateNotification(
- lat = loc.latitude,
- lon = loc.longitude,
+ lat = loc.latitude,
+ lon = loc.longitude,
pausedInZone = true,
- zoneName = zone.name,
+ zoneName = zoneName,
forceUpdate = true
)
} ?: run {
updateNotification(
- pausedInZone = true,
- zoneName = zone.name,
+ pausedInZone = true,
+ zoneName = zoneName,
forceUpdate = true
)
}
-
- LocationServiceModule.sendPauseZoneEvent(true, zone.name)
-
+
+ LocationServiceModule.sendPauseZoneEvent(true, zoneName)
+
if (BuildConfig.DEBUG) {
- Log.d(TAG, "Entered pause zone: ${zone.name}")
+ Log.d(TAG, "Entered pause zone: $zoneName")
}
}
@@ -410,14 +379,9 @@ class LocationForegroundService : Service() {
insidePauseZone = false
val exited = currentZoneName
currentZoneName = null
-
- // Show coordinates when exiting pause zone
+
lastKnownLocation?.let { loc ->
- updateNotification(
- loc.latitude,
- loc.longitude,
- forceUpdate = true // ← Force immediate update on zone exit
- )
+ updateNotification(loc.latitude, loc.longitude, forceUpdate = true)
} ?: run {
updateNotification(forceUpdate = true)
}
@@ -426,10 +390,6 @@ class LocationForegroundService : Service() {
if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")
}
- // ========================================
- // UI & NOTIFICATIONS
- // ========================================
-
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
@@ -463,13 +423,10 @@ class LocationForegroundService : Service() {
.build()
}
- /**
- * Format time since last sync in human-readable format.
- */
private fun getTimeSinceLastSync(): String {
val lastSuccessfulSyncTime = syncManager.lastSuccessfulSyncTime
if (lastSuccessfulSyncTime == 0L) {
- return "Never synced"
+ return "Never"
}
val elapsedMs = System.currentTimeMillis() - lastSuccessfulSyncTime
@@ -485,12 +442,9 @@ class LocationForegroundService : Service() {
}
/**
- * Smart notification updates with throttling and distance checking.
- * Only updates when:
- * - Zone status changes (immediate)
- * - Moved >10 meters
- * - Time throttle passed (10s)
- */
+ * Throttled notification updates. Skips unless forceUpdate, zone change,
+ * or both 10s elapsed AND moved >2m. Deduplicates via text comparison.
+ */
private fun updateNotification(
lat: Double? = null,
lon: Double? = null,
@@ -527,13 +481,11 @@ class LocationForegroundService : Service() {
}
}
- // Update last notification time and coordinates
lastNotificationTime = now
if (lat != null && lon != null) {
lastNotificationCoords = Pair(lat, lon)
}
- // Build notification text
val queuedCount = syncManager.getCachedQueuedCount()
val isCurrentlyPaused = pausedInZone || insidePauseZone
val activeZone = zoneName ?: currentZoneName
@@ -542,16 +494,19 @@ class LocationForegroundService : Service() {
isCurrentlyPaused -> "Paused: ${activeZone ?: "Unknown"}"
lat != null && lon != null -> {
val coords = "%.5f, %.5f".format(lat, lon)
- if (queuedCount > 0) {
+ if (queuedCount > 0 && syncManager.lastSuccessfulSyncTime > 0) {
"$coords (Last sync: ${getTimeSinceLastSync()})"
- } else {
+ } else if (queuedCount > 0) {
+ "$coords (Queued: $queuedCount)"
+ } else if (syncManager.lastSuccessfulSyncTime > 0) {
"$coords (Synced)"
+ } else {
+ coords
}
}
else -> "Searching GPS..."
}
- // Only update if text changed
val cacheKey = "$statusText-$queuedCount"
if (cacheKey != lastNotificationText) {
lastNotificationText = cacheKey
@@ -559,17 +514,16 @@ class LocationForegroundService : Service() {
}
}
+ /** Must be called within 5s of startForegroundService() per Android requirement. */
private fun startForegroundServiceWithNotification() {
val initialStatus = if (insidePauseZone) {
"Paused: ${currentZoneName ?: "Unknown"}"
} else {
- "Initializing..."
+ "Searching GPS..."
}
val notification = buildNotification(initialStatus)
startForeground(NOTIFICATION_ID, notification)
-
- updateNotification()
}
private fun stopForegroundServiceWithReason(reason: String) {
@@ -577,6 +531,7 @@ class LocationForegroundService : Service() {
Log.i(TAG, "Stopping: $reason")
}
+ LocationServiceModule.sendTrackingStoppedEvent(reason)
dbHelper.saveSetting("tracking_enabled", "false")
val finalNotification = NotificationCompat.Builder(this, CHANNEL_ID)
@@ -600,22 +555,13 @@ class LocationForegroundService : Service() {
stopSelf()
}
- // ========================================
- // CONFIGURATION HANDLING
- // ========================================
-
- /**
- * Use ServiceConfig for cleaner configuration management.
- */
private fun loadConfigFromIntent(intent: Intent?) {
- // Load config using ServiceConfig utility
config = if (intent != null) {
ServiceConfig.fromIntent(intent, dbHelper)
} else {
ServiceConfig.fromDatabase(dbHelper)
}
- // Configure sync manager with current settings
syncManager.updateConfig(
endpoint = config.endpoint,
syncIntervalSeconds = config.syncIntervalSeconds,
@@ -625,14 +571,12 @@ class LocationForegroundService : Service() {
authHeaders = secureStorage.getAuthHeaders()
)
- // Parse fieldMap separately (remains as Map for payload building)
config.fieldMap?.let {
- if (it.isNotBlank()) fieldMap = locationUtils.parseFieldMap(it)
+ if (it.isNotBlank()) fieldMap = payloadBuilder.parseFieldMap(it)
}
- // Parse customFields (static key-value pairs added to every payload)
config.customFields?.let {
- if (it.isNotBlank()) customFields = locationUtils.parseCustomFields(it)
+ if (it.isNotBlank()) customFields = payloadBuilder.parseCustomFields(it)
}
if (BuildConfig.DEBUG) {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
similarity index 59%
rename from apps/mobile/android/app/src/main/java/com/colota/ServiceConfig.kt
rename to apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
index 7a1e994a..4b34e42d 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/ServiceConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt
@@ -3,34 +3,31 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.service
import android.content.Intent
+import com.Colota.data.DatabaseHelper
import android.os.Bundle
+import com.facebook.react.bridge.ReadableMap
+import org.json.JSONObject
/**
- * Centralized service configuration to eliminate duplication across:
- * - LocationBootReceiver
- * - LocationServiceModule
- * - LocationForegroundService
+ * Centralized service configuration shared across all native components.
*/
data class ServiceConfig(
val endpoint: String = "",
- val interval: Long = 1000L,
+ val interval: Long = 5000L,
val minUpdateDistance: Float = 0f,
val syncIntervalSeconds: Int = 0,
val maxRetries: Int = 5,
val accuracyThreshold: Float = 50.0f,
- val filterInaccurateLocations: Boolean = true,
- val retryIntervalSeconds: Int = 300,
+ val filterInaccurateLocations: Boolean = false,
+ val retryIntervalSeconds: Int = 30,
val isOfflineMode: Boolean = false,
val fieldMap: String? = null,
val customFields: String? = null
) {
companion object {
- /**
- * Loads configuration from database settings.
- */
fun fromDatabase(dbHelper: DatabaseHelper): ServiceConfig {
val saved = dbHelper.getAllSettings()
@@ -49,13 +46,46 @@ data class ServiceConfig(
)
}
- /**
- * Loads configuration from Intent extras (for service start).
- */
+ fun fromReadableMap(config: ReadableMap, dbHelper: DatabaseHelper): ServiceConfig {
+ val dbConfig = fromDatabase(dbHelper)
+
+ val fieldMapJson = config.getMap("fieldMap")?.let { map ->
+ val json = JSONObject()
+ val iterator = map.keySetIterator()
+ while (iterator.hasNextKey()) {
+ val key = iterator.nextKey()
+ map.getString(key)?.let { json.put(key, it) }
+ }
+ json.toString()
+ }
+
+ val customFieldsJson = config.getMap("customFields")?.let { map ->
+ val json = JSONObject()
+ val iterator = map.keySetIterator()
+ while (iterator.hasNextKey()) {
+ val key = iterator.nextKey()
+ map.getString(key)?.let { json.put(key, it) }
+ }
+ json.toString()
+ }
+
+ return ServiceConfig(
+ endpoint = config.getStringOrNull("endpoint") ?: dbConfig.endpoint,
+ interval = config.getDoubleOrNull("interval")?.toLong() ?: dbConfig.interval,
+ minUpdateDistance = config.getDoubleOrNull("minUpdateDistance")?.toFloat() ?: dbConfig.minUpdateDistance,
+ syncIntervalSeconds = config.getIntOrNull("syncInterval") ?: dbConfig.syncIntervalSeconds,
+ maxRetries = config.getIntOrNull("maxRetries") ?: dbConfig.maxRetries,
+ accuracyThreshold = config.getDoubleOrNull("accuracyThreshold")?.toFloat() ?: dbConfig.accuracyThreshold,
+ filterInaccurateLocations = config.getBooleanOrNull("filterInaccurateLocations") ?: dbConfig.filterInaccurateLocations,
+ retryIntervalSeconds = config.getIntOrNull("retryInterval") ?: dbConfig.retryIntervalSeconds,
+ isOfflineMode = config.getBooleanOrNull("isOfflineMode") ?: dbConfig.isOfflineMode,
+ fieldMap = fieldMapJson ?: dbConfig.fieldMap,
+ customFields = customFieldsJson ?: dbConfig.customFields
+ )
+ }
+
fun fromIntent(intent: Intent, dbHelper: DatabaseHelper): ServiceConfig {
val extras = intent.extras ?: return fromDatabase(dbHelper)
-
- // Load from database first, then override with intent extras
val dbConfig = fromDatabase(dbHelper)
return ServiceConfig(
@@ -74,9 +104,6 @@ data class ServiceConfig(
}
}
- /**
- * Converts config to Intent extras for service communication.
- */
fun toIntent(intent: Intent): Intent {
return intent.apply {
putExtra("interval", interval)
@@ -94,7 +121,6 @@ data class ServiceConfig(
}
}
-// Extension functions for safer Bundle access
private fun Bundle.getStringOrDefault(key: String, default: String?): String? =
if (containsKey(key)) getString(key) else default
@@ -108,4 +134,16 @@ private fun Bundle.getIntOrDefault(key: String, default: Int): Int =
if (containsKey(key)) getInt(key) else default
private fun Bundle.getBooleanOrDefault(key: String, default: Boolean): Boolean =
- if (containsKey(key)) getBoolean(key) else default
\ No newline at end of file
+ if (containsKey(key)) getBoolean(key) else default
+
+internal fun ReadableMap.getDoubleOrNull(key: String): Double? =
+ if (hasKey(key)) getDouble(key) else null
+
+internal fun ReadableMap.getIntOrNull(key: String): Int? =
+ if (hasKey(key)) getInt(key) else null
+
+internal fun ReadableMap.getStringOrNull(key: String): String? =
+ if (hasKey(key)) getString(key) else null
+
+internal fun ReadableMap.getBooleanOrNull(key: String): Boolean? =
+ if (hasKey(key)) getBoolean(key) else null
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
similarity index 90%
rename from apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt
rename to apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index d288a1d8..889e98d7 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -1,6 +1,8 @@
-package com.Colota
+package com.Colota.sync
import android.content.Context
+import com.Colota.BuildConfig
+import com.Colota.util.TimedCache
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log
@@ -25,9 +27,18 @@ class NetworkManager(private val context: Context) {
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
+ private val networkCache = TimedCache(NETWORK_CHECK_CACHE_MS) {
+ 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
+ }
+ }
/**
* Executes an asynchronous POST request to the server.
@@ -75,7 +86,6 @@ class NetworkManager(private val context: Context) {
useCaches = false
}
- // Log request details
if (BuildConfig.DEBUG) {
Log.d(TAG, "=== HTTP REQUEST ===")
Log.d(TAG, "Endpoint: $endpoint")
@@ -89,7 +99,6 @@ class NetworkManager(private val context: Context) {
Log.d(TAG, "===================")
}
- // Write payload
val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)
connection.setFixedLengthStreamingMode(bodyBytes.size)
connection.outputStream.use { it.write(bodyBytes) }
@@ -122,7 +131,7 @@ class NetworkManager(private val context: Context) {
if (protocol != "http" && protocol != "https") return false
- // Enforce HTTPS for anything that isn't a local/private IP
+ // HTTP only allowed for local dev (localhost, 192.168.x.x, 10.x.x.x)
if (protocol == "http" && !isPrivateHost(host)) {
return false
}
@@ -165,25 +174,5 @@ class NetworkManager(private val context: Context) {
/**
* 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
- }
+ fun isNetworkAvailable(): Boolean = networkCache.get()
}
\ No newline at end of file
diff --git a/apps/mobile/android/app/src/main/java/com/colota/LocationUtils.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
similarity index 80%
rename from apps/mobile/android/app/src/main/java/com/colota/LocationUtils.kt
rename to apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
index 39a264d1..23aefb0f 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/LocationUtils.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/PayloadBuilder.kt
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.sync
import android.location.Location
import android.util.Log
@@ -12,20 +12,16 @@ import org.json.JSONObject
import kotlin.math.*
/**
- * Utility class for building and parsing location payloads.
+ * Builds and parses location payloads with dynamic field mapping.
*/
-class LocationUtils {
+class PayloadBuilder {
companion object {
- private const val TAG = "LocationUtils"
+ private const val TAG = "PayloadBuilder"
}
- // ========================================
- // DATA CONVERSION
- // ========================================
-
/**
- * Maps native location data into JSONObject with dynamic field mapping.
+ * Builds a JSON payload from location data, applying field name mapping and custom fields.
*/
fun buildPayload(
location: Location,
@@ -36,7 +32,6 @@ class LocationUtils {
customFields: Map<String, String>? = null
): JSONObject {
return JSONObject().apply {
- // Add custom static fields first
customFields?.forEach { (key, value) ->
put(key, value)
}
@@ -60,9 +55,6 @@ class LocationUtils {
}
}
- /**
- * Parses JSON string to Map with error handling.
- */
fun parseFieldMap(jsonString: String?): Map<String, String>? {
if (jsonString.isNullOrBlank()) return null
@@ -75,10 +67,7 @@ class LocationUtils {
}
}
- /**
- * Parses JSON array string of custom fields into a Map.
- * Expected format: [{"key":"_type","value":"location"},...]
- */
+ /** Expected format: [{"key":"_type","value":"location"},...] */
fun parseCustomFields(jsonString: String?): Map<String, String>? {
if (jsonString.isNullOrBlank() || jsonString == "[]") return null
return try {
@@ -95,9 +84,6 @@ class LocationUtils {
}
}
- /**
- * Converts ReadableMap to JSON string with null safety.
- */
fun convertFieldMapToJson(fieldMap: ReadableMap): String {
val json = JSONObject()
val iterator = fieldMap.keySetIterator()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
similarity index 83%
rename from apps/mobile/android/app/src/main/java/com/colota/SyncManager.kt
rename to apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
index 2f204ee8..6a83f3ad 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/SyncManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
@@ -3,15 +3,19 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.sync
import android.util.Log
+import com.Colota.BuildConfig
+import com.Colota.bridge.LocationServiceModule
+import com.Colota.data.DatabaseHelper
+import com.Colota.util.TimedCache
import kotlinx.coroutines.*
import org.json.JSONObject
/**
- * Manages location sync queue processing, batch uploads, and retry logic.
- * Extracted from LocationForegroundService for separation of concerns.
+ * Two sync modes: instant (syncInterval=0) sends each location on arrival,
+ * periodic (syncInterval>0) batches uploads at the configured interval.
*/
class SyncManager(
private val dbHelper: DatabaseHelper,
@@ -22,7 +26,6 @@ class SyncManager(
private const val TAG = "SyncManager"
}
- // --- Config (set via updateConfig) ---
private var endpoint: String = ""
private var syncIntervalSeconds: Int = 0
private var retryIntervalSeconds: Int = 300
@@ -30,21 +33,16 @@ class SyncManager(
private var isOfflineMode: Boolean = false
private var authHeaders: Map<String, String> = emptyMap()
- // --- Sync state ---
private var syncJob: Job? = null
- private var lastSyncTime: Long = 0
- var lastSuccessfulSyncTime: Long = 0
+ @Volatile private var lastSyncTime: Long = 0
+ @Volatile var lastSuccessfulSyncTime: Long = 0
private set
- private var syncInitialized = false
- private var consecutiveFailures = 0
+ @Volatile private var syncInitialized = false
+ @Volatile private var consecutiveFailures = 0
- // --- Queue count cache ---
- private var cachedQueuedCount: Int = 0
- private var lastQueueCountCheck: Long = 0
- private val QUEUE_COUNT_CACHE_MS = 5000L
+ private val queueCountCache = TimedCache(5000L) { dbHelper.getQueuedCount() }
- // Batch limit to prevent infinite syncing
- private val MAX_BATCHES_PER_SYNC = 10 // Max 500 items per sync cycle
+ private val MAX_BATCHES_PER_SYNC = 10
fun updateConfig(
endpoint: String,
@@ -62,10 +60,6 @@ class SyncManager(
this.authHeaders = authHeaders
}
- // ========================================
- // PUBLIC API
- // ========================================
-
fun startPeriodicSync() {
syncJob = scope.launch {
while (isActive) {
@@ -77,7 +71,7 @@ class SyncManager(
}
if (endpoint.isNotBlank() && getCachedQueuedCount() > 0) {
- try {
+ val errorMessage: String? = try {
val success = performSyncAndCheckSuccess()
if (success) {
@@ -85,14 +79,24 @@ class SyncManager(
Log.i(TAG, "Sync restored")
}
consecutiveFailures = 0
+ null
} else {
- consecutiveFailures++
- applyBackoffDelay()
+ "Sync failed"
}
} catch (e: Exception) {
Log.e(TAG, "Sync error", e)
+ e.message ?: "Sync error"
+ }
+
+ if (errorMessage != null) {
consecutiveFailures++
- delay(30000)
+ if (consecutiveFailures >= 3) {
+ LocationServiceModule.sendSyncErrorEvent(
+ "$errorMessage ($consecutiveFailures consecutive failures)",
+ getCachedQueuedCount()
+ )
+ }
+ applyBackoffDelay()
}
}
}
@@ -138,24 +142,9 @@ class SyncManager(
// If syncInterval > 0, the periodic sync job will handle it
}
- fun getCachedQueuedCount(): Int {
- val now = System.currentTimeMillis()
-
- if (now - lastQueueCountCheck > QUEUE_COUNT_CACHE_MS) {
- cachedQueuedCount = dbHelper.getQueuedCount()
- lastQueueCountCheck = now
- }
-
- return cachedQueuedCount
- }
-
- fun invalidateQueueCache() {
- lastQueueCountCheck = 0
- }
+ fun getCachedQueuedCount(): Int = queueCountCache.get()
- // ========================================
- // INTERNAL SYNC LOGIC
- // ========================================
+ fun invalidateQueueCache() = queueCountCache.invalidate()
private suspend fun performSyncAndCheckSuccess(): Boolean {
val countBefore = dbHelper.getQueuedCount()
@@ -172,6 +161,7 @@ class SyncManager(
return success
}
+ // Exponential backoff: 30s → 60s → 5min → 15min
private suspend fun applyBackoffDelay() {
val backoffSeconds = when (consecutiveFailures) {
1 -> 30L
@@ -187,10 +177,6 @@ class SyncManager(
delay(backoffSeconds * 1000L)
}
- /**
- * Batch limit to prevent infinite syncing.
- * Processes max 500 items (10 batches x 50 items) per sync cycle.
- */
private suspend fun syncQueue() = coroutineScope {
var totalProcessed = 0
var batchNumber = 1
@@ -208,6 +194,7 @@ class SyncManager(
Log.d(TAG, "Processing batch $batchNumber/$MAX_BATCHES_PER_SYNC: ${queued.size} items")
}
+ // Chunks of 10 concurrent HTTP requests to avoid flooding the server
for (chunk in queued.chunked(10)) {
val successfulIds = mutableListOf<Long>()
val permanentlyFailedIds = mutableListOf<Long>()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/DeviceInfoHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
similarity index 65%
rename from apps/mobile/android/app/src/main/java/com/colota/DeviceInfoHelper.kt
rename to apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
index ac20c395..148fa944 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/DeviceInfoHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
@@ -2,7 +2,7 @@
* Copyright (C) 2026 Max Dietrich
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.util
import android.content.Context
import android.content.Intent
@@ -25,20 +25,12 @@ class DeviceInfoHelper(private val context: Context) {
context.getSystemService(Context.POWER_SERVICE) as PowerManager
}
- // Battery status caching
- private var cachedBatteryLevel: Int = 100
- private var cachedBatteryStatus: Int = 0
- private var lastBatteryCheck: Long = 0
- private val BATTERY_CHECK_INTERVAL_MS = 60000L // 1 minute cache
+ private val batteryCache = TimedCache(60000L) { getBatteryStatus() }
companion object {
private const val TAG = "DeviceInfoHelper"
}
- // ============================================================================
- // DEVICE INFORMATION
- // ============================================================================
-
fun getDeviceInfo(): WritableMap {
return Arguments.createMap().apply {
putString("model", Build.MODEL)
@@ -57,36 +49,11 @@ class DeviceInfoHelper(private val context: Context) {
fun getBrand(): String = Build.BRAND
fun getDeviceId(): String = Build.DEVICE
- // ============================================================================
- // BATTERY STATUS
- // ============================================================================
-
/**
- * Get current battery status with caching to reduce system calls.
- * Cache is valid for 1 minute.
- *
- * @return Pair of (battery level percentage, battery status code)
- * Status codes: 0=Unknown, 1=Unplugged/Discharging, 2=Charging, 3=Full
+ * @return Pair of (battery level %, status code: 0=Unknown, 1=Discharging, 2=Charging, 3=Full)
*/
- fun getCachedBatteryStatus(): Pair<Int, Int> {
- val now = System.currentTimeMillis()
-
- if (now - lastBatteryCheck > BATTERY_CHECK_INTERVAL_MS) {
- val (level, status) = getBatteryStatus()
- cachedBatteryLevel = level
- cachedBatteryStatus = status
- lastBatteryCheck = now
- }
-
- return Pair(cachedBatteryLevel, cachedBatteryStatus)
- }
+ fun getCachedBatteryStatus(): Pair<Int, Int> = batteryCache.get()
- /**
- * Get real-time battery status from system (uncached).
- *
- * @return Pair of (battery level percentage, battery status code)
- * Status codes: 0=Unknown, 1=Unplugged/Discharging, 2=Charging, 3=Full
- */
fun getBatteryStatus(): Pair<Int, Int> {
val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
@@ -110,9 +77,6 @@ class DeviceInfoHelper(private val context: Context) {
return Pair(batteryPct, batteryStatus)
}
- /**
- * Get battery status as human-readable string.
- */
fun getBatteryStatusString(): String {
val (level, status) = getCachedBatteryStatus()
val statusText = when (status) {
@@ -125,30 +89,13 @@ class DeviceInfoHelper(private val context: Context) {
return "$level% ($statusText)"
}
- /**
- * Check if battery is critically low AND not charging.
- * Used to determine if service should stop to preserve battery.
- */
fun isBatteryCritical(threshold: Int = 5): Boolean {
val (level, status) = getCachedBatteryStatus()
return level < threshold && status == 1 // Discharging
}
- /**
- * Invalidate battery cache to force fresh read on next call.
- */
- fun invalidateBatteryCache() {
- lastBatteryCheck = 0
- }
-
- // ============================================================================
- // BATTERY OPTIMIZATION
- // ============================================================================
+ fun invalidateBatteryCache() = batteryCache.invalidate()
- /**
- * Checks if the app is exempt from battery optimization.
- * @return true if exempt, false otherwise (or true on Android < M)
- */
fun isIgnoringBatteryOptimizations(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
powerManager.isIgnoringBatteryOptimizations(context.packageName)
@@ -157,11 +104,6 @@ class DeviceInfoHelper(private val context: Context) {
}
}
- /**
- * Requests battery optimization exemption.
- * Opens system settings dialog.
- * @return true if dialog opened successfully, false if fallback used
- */
fun requestIgnoreBatteryOptimizations(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true // Not applicable on older versions
diff --git a/apps/mobile/android/app/src/main/java/com/colota/FileOperations.kt b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
similarity index 98%
rename from apps/mobile/android/app/src/main/java/com/colota/FileOperations.kt
rename to apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
index 32cf37cd..49e8a506 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/FileOperations.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
@@ -3,9 +3,10 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.util
import android.content.Intent
+import com.Colota.BuildConfig
import android.net.Uri
import android.util.Log
import androidx.core.content.FileProvider
diff --git a/apps/mobile/android/app/src/main/java/com/colota/SecureStorageHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
similarity index 99%
rename from apps/mobile/android/app/src/main/java/com/colota/SecureStorageHelper.kt
rename to apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
index d36aebf5..174926ab 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/SecureStorageHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
@@ -3,7 +3,7 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-package com.Colota
+package com.Colota.util
import android.content.Context
import android.content.SharedPreferences
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt b/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt
new file mode 100644
index 00000000..3537301a
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/TimedCache.kt
@@ -0,0 +1,33 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+package com.Colota.util
+
+/**
+ * Generic time-based cache that reloads its value after a configurable TTL.
+ * Thread-safe via @Volatile annotations.
+ *
+ * @param ttlMs Time-to-live in milliseconds before the cached value is refreshed
+ * @param loader Function that produces a fresh value when the cache is stale
+ */
+class TimedCache<T>(
+ private val ttlMs: Long,
+ private val loader: () -> T
+) {
+ @Volatile private var value: T? = null
+ @Volatile private var lastCheck: Long = 0
+
+ fun get(): T {
+ val now = System.currentTimeMillis()
+ if (value == null || (now - lastCheck) > ttlMs) {
+ value = loader()
+ lastCheck = now
+ }
+ return value!!
+ }
+
+ fun invalidate() {
+ lastCheck = 0
+ }
+}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index ce210724..6884149f 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -4,10 +4,10 @@
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
- "android:debug": "cd android && ./gradlew assembleDebug",
- "android:release": "cd android && ./gradlew assembleRelease",
- "android:bundle": "cd android && ./gradlew bundleRelease",
- "clean": "cd android && ./gradlew clean",
+ "android:debug": "cd android && gradlew assembleDebug",
+ "android:release": "cd android && gradlew assembleRelease",
+ "android:bundle": "cd android && gradlew bundleRelease",
+ "clean": "cd android && gradlew clean",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"test": "jest --passWithNoTests",
"test:coverage": "jest --coverage",
diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.ts
index 1428c354..fc0e52fb 100644
--- a/apps/mobile/src/hooks/useLocationTracking.ts
+++ b/apps/mobile/src/hooks/useLocationTracking.ts
@@ -110,6 +110,32 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult
}
}, [tracking])
+ /**
+ * Listens for unexpected tracking stops (e.g. battery critical)
+ */
+ useEffect(() => {
+ const sub = locationEventEmitter.addListener("onTrackingStopped", (event: { reason: string }) => {
+ logger.warn(`[useLocationTracking] Tracking stopped by native: ${event.reason}`)
+ if (listenerRef.current) {
+ listenerRef.current.remove()
+ listenerRef.current = null
+ }
+ setTracking(false)
+ setCoords(null)
+ })
+ return () => sub.remove()
+ }, [])
+
+ /**
+ * Listens for sync errors from native service
+ */
+ useEffect(() => {
+ const sub = locationEventEmitter.addListener("onSyncError", (event: { message: string; queuedCount: number }) => {
+ logger.warn(`[useLocationTracking] Sync error: ${event.message} (${event.queuedCount} queued)`)
+ })
+ return () => sub.remove()
+ }, [])
+
/**
* Starts location tracking
* @param overrideSettings Optional one-time settings override