Colota - Android GPS Location tracker
first commit
Max Dietrichb406c595b5b5
diff --git a/.github/workflows/android-build.yml b/.github/workflows/android-build.ymldeleted file mode 100644index 8b058b73..00000000--- a/.github/workflows/android-build.yml+++ /dev/null@@ -1,160 +0,0 @@-name: Android Build and Test--on:- push:- branches: [ main, develop ]- pull_request:- branches: [ main, develop ]- workflow_dispatch:--jobs:- lint-and-test:- name: Lint & Test- runs-on: ubuntu-latest-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'-- - name: Install dependencies- run: npm ci-- - name: Run ESLint- run: npm run lint-- - name: Run TypeScript check- run: npx tsc --noEmit-- - name: Run tests- run: npm test -- --coverage-- - name: Upload coverage- uses: codecov/codecov-action@v3- with:- files: ./coverage/lcov.info- flags: unittests- name: codecov-umbrella-- build-android:- name: Build Android APK- runs-on: ubuntu-latest- needs: lint-and-test-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'-- - name: Setup Java- uses: actions/setup-java@v4- with:- distribution: 'temurin'- java-version: '17'- cache: 'gradle'-- - name: Install dependencies- run: npm ci-- - name: Cache Gradle- uses: actions/cache@v3- with:- path: |- ~/.gradle/caches- ~/.gradle/wrapper- key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}- restore-keys: |- ${{ runner.os }}-gradle--- - name: Make gradlew executable- run: chmod +x android/gradlew-- - name: Build debug APK- run: |- cd android- ./gradlew assembleDebug --no-daemon-- - name: Upload debug APK- uses: actions/upload-artifact@v4- with:- name: app-debug- path: android/app/build/outputs/apk/debug/app-debug.apk- retention-days: 7-- build-android-release:- name: Build Android Release- runs-on: ubuntu-latest- needs: lint-and-test- if: github.ref == 'refs/heads/main'-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'-- - name: Setup Java- uses: actions/setup-java@v4- with:- distribution: 'temurin'- java-version: '17'- cache: 'gradle'-- - name: Install dependencies- run: npm ci-- - name: Decode keystore- env:- KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}- run: |- echo $KEYSTORE_BASE64 | base64 -d > android/app/release.keystore-- - name: Build release APK- env:- KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}- KEY_ALIAS: ${{ secrets.KEY_ALIAS }}- KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}- run: |- cd android- ./gradlew assembleRelease --no-daemon-- - name: Upload release APK- uses: actions/upload-artifact@v4- with:- name: app-release- path: android/app/build/outputs/apk/release/app-release.apk- retention-days: 30-- - name: Build release AAB- env:- KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}- KEY_ALIAS: ${{ secrets.KEY_ALIAS }}- KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}- run: |- cd android- ./gradlew bundleRelease --no-daemon-- - name: Upload release AAB- uses: actions/upload-artifact@v4- with:- name: app-release-bundle- path: android/app/build/outputs/bundle/release/app-release.aab- retention-days: 30-- - name: Clean up keystore- if: always()- run: rm -f android/app/release.keystore\ No newline at end of filediff --git a/.github/workflows/lint-test.yml b/.github/workflows/lint-test.ymlnew file mode 100644index 00000000..a71e3200--- /dev/null+++ b/.github/workflows/lint-test.yml@@ -0,0 +1,42 @@+name: Lint & Test++on:+ push:+ branches: [ main, develop ]+ pull_request:+ branches: [ main, develop ]+ workflow_dispatch:++jobs:+ lint-and-test:+ name: Lint & Test+ runs-on: ubuntu-latest++ steps:+ - name: Checkout code+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '20'+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Run ESLint+ run: npm run lint++ - name: Run TypeScript check+ run: npx tsc --noEmit++ - name: Run tests+ run: npm test -- --coverage++ - name: Upload coverage+ uses: codecov/codecov-action@v3+ with:+ files: ./coverage/lcov.info+ flags: unittests+ name: codecov-umbrella\ No newline at end of filediff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.ymldeleted file mode 100644index b45193c2..00000000--- a/.github/workflows/pr-checks.yml+++ /dev/null@@ -1,102 +0,0 @@-name: Pull Request Checks--on:- pull_request:- branches: [ main, develop ]--jobs:- pr-checks:- name: PR Quality Checks- runs-on: ubuntu-latest-- steps:- - name: Checkout code- uses: actions/checkout@v4- with:- fetch-depth: 0-- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'-- - name: Install dependencies- run: npm ci-- - name: Check code formatting- run: |- npm run format:check || echo "::warning::Code formatting issues found. Run 'npm run format' locally."-- - name: Run linter- run: npm run lint-- - name: Check TypeScript- run: npx tsc --noEmit-- - name: Run tests with coverage- run: npm test -- --coverage --watchAll=false-- - name: Check test coverage- run: |- COVERAGE=$(cat coverage/coverage-summary.json | jq '.total.lines.pct')- echo "Test coverage: $COVERAGE%"- if (( $(echo "$COVERAGE < 70" | bc -l) )); then- echo "::warning::Test coverage is below 70%"- fi-- - name: Size analysis- run: |- npm run build || echo "Build command not found, skipping"- du -sh node_modules/ || true-- - name: Comment PR with build info- uses: actions/github-script@v7- with:- script: |- const fs = require('fs');- let coverage = 'N/A';- try {- const coverageData = JSON.parse(fs.readFileSync('coverage/coverage-summary.json', 'utf8'));- coverage = `${coverageData.total.lines.pct.toFixed(2)}%`;- } catch (e) {}-- const comment = `## Build Status ✅-- - **Linting**: Passed- - **TypeScript**: Passed- - **Tests**: Passed- - **Coverage**: ${coverage}-- Ready for review!`;-- github.rest.issues.createComment({- issue_number: context.issue.number,- owner: context.repo.owner,- repo: context.repo.repo,- body: comment- });-- security-check:- name: Security Audit- runs-on: ubuntu-latest-- steps:- - name: Checkout code- uses: actions/checkout@v4-- - name: Setup Node.js- uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'-- - name: Run npm audit- run: npm audit --audit-level=moderate- continue-on-error: true-- - name: Check for vulnerable dependencies- run: |- npm install -g npm-audit-resolver- npm audit --json | npm-audit-resolver --audit-level=moderate- continue-on-error: true\ No newline at end of filediff --git a/android/app/build.gradle b/android/app/build.gradleindex 37cdbed7..27bacbb4 100644--- a/android/app/build.gradle+++ b/android/app/build.gradle@@ -146,5 +146,9 @@ dependencies {implementation 'com.google.android.gms:play-services-location:21.0.1'implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'- implementation jscFlavor+ if (hermesEnabled.toBoolean()) {+ implementation("com.facebook.react:hermes-android")+ } else {+ implementation jscFlavor+ }}\ No newline at end of filediff --git a/android/app/src/main/java/com/locata/DeviceInfoHelper.kt b/android/app/src/main/java/com/locata/DeviceInfoHelper.ktindex 65b90982..ac20c395 100644--- a/android/app/src/main/java/com/locata/DeviceInfoHelper.kt+++ b/android/app/src/main/java/com/locata/DeviceInfoHelper.kt@@ -2,12 +2,13 @@* Copyright (C) 2026 Max Dietrich* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-package com.Colotaimport android.content.Contextimport android.content.Intent+import android.content.IntentFilterimport android.net.Uri+import android.os.BatteryManagerimport android.os.Buildimport android.os.PowerManagerimport android.provider.Settings@@ -24,6 +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+companion object {private const val TAG = "DeviceInfoHelper"}@@ -45,15 +52,95 @@ class DeviceInfoHelper(private val context: Context) {}fun getSystemVersion(): String = Build.VERSION.RELEASE-fun getApiLevel(): Int = Build.VERSION.SDK_INT-fun getModel(): String = Build.MODEL-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+ */+ 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)+ }++ /**+ * 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))++ val level = batteryIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1+ val scale = batteryIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1+ val batteryPct = if (level >= 0 && scale > 0) {+ (level * 100) / scale+ } else {+ 100 // Default to full if unable to read+ }++ val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1+ val batteryStatus = when (status) {+ BatteryManager.BATTERY_STATUS_CHARGING -> 2 // Charging+ BatteryManager.BATTERY_STATUS_FULL -> 3 // Full+ BatteryManager.BATTERY_STATUS_DISCHARGING -> 1 // Unplugged/Discharging+ BatteryManager.BATTERY_STATUS_NOT_CHARGING -> 1 // Unplugged/Discharging+ else -> 0 // Unknown+ }++ return Pair(batteryPct, batteryStatus)+ }++ /**+ * Get battery status as human-readable string.+ */+ fun getBatteryStatusString(): String {+ val (level, status) = getCachedBatteryStatus()+ val statusText = when (status) {+ 0 -> "Unknown"+ 1 -> "Unplugged/Discharging"+ 2 -> "Charging"+ 3 -> "Full"+ else -> "Unknown ($status)"+ }+ 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// ============================================================================diff --git a/android/app/src/main/java/com/locata/LocationForegroundService.kt b/android/app/src/main/java/com/locata/LocationForegroundService.ktindex 9ca77f4e..5a6c7adb 100644--- a/android/app/src/main/java/com/locata/LocationForegroundService.kt+++ b/android/app/src/main/java/com/locata/LocationForegroundService.kt@@ -24,6 +24,7 @@ class LocationForegroundService : Service() {private lateinit var notificationManager: NotificationManagerprivate lateinit var dbHelper: LocationDatabaseHelperprivate lateinit var locationUtils: LocationUtils+ private lateinit var deviceInfoHelper: DeviceInfoHelper// Properly manage scope lifecycle to prevent memory leakprivate var serviceScope: CoroutineScope? = null@@ -32,6 +33,7 @@ class LocationForegroundService : Service() {private var locationCallback: LocationCallback? = nullprivate var syncJob: Job? = nullprivate var lastSyncTime: Long = 0+ private var lastSuccessfulSyncTime: Long = 0private var syncInitialized = falseprivate var insideSilentZone = falseprivate var currentZoneName: String? = null@@ -49,12 +51,6 @@ class LocationForegroundService : Service() {// Location cachingprivate var lastKnownLocation: android.location.Location? = nullprivate var lastNotificationCoords: Pair<Double, Double>? = null-- // Battery check throttling- private var cachedBatteryLevel: Int = 100- private var cachedBatteryStatus: Int = 0- private var lastBatteryCheck: Long = 0- private val BATTERY_CHECK_INTERVAL_MS = 60000L// Batch limit to prevent infinite syncingprivate val MAX_BATCHES_PER_SYNC = 10 // Max 500 items per sync cycle@@ -90,6 +86,7 @@ class LocationForegroundService : Service() {notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManagerdbHelper = LocationDatabaseHelper.getInstance(this)locationUtils = LocationUtils(this)+ deviceInfoHelper = DeviceInfoHelper(this)createNotificationChannel()}@@ -192,13 +189,11 @@ class LocationForegroundService : Service() {}}- // Use cached battery status- val (batteryLevel, batteryStatus) = getCachedBatteryStatus()-- // Stop service if battery critical AND not charging- if (batteryLevel < 5 && batteryStatus == 1) {+ // 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 ($batteryLevel%) and unplugged - stopping service")+ Log.d(TAG, "Battery critical ($level%) and unplugged - stopping service")}stopForegroundServiceWithReason("Battery critical")return // Exit early - don't setup location updates@@ -348,8 +343,8 @@ class LocationForegroundService : Service() {}}- // Use cached battery- val (battery, batteryStatus) = getCachedBatteryStatus()+ // Use cached battery from DeviceInfoHelper+ val (battery, batteryStatus) = deviceInfoHelper.getCachedBatteryStatus()val timestampSec = location.time / 1000// Save to database@@ -438,24 +433,11 @@ class LocationForegroundService : Service() {}// ========================================- // BATTERY OPTIMIZATIONS (New Methods)+ // BATTERY OPTIMIZATIONS// ========================================-- /**- * Cached battery status.- */- private fun getCachedBatteryStatus(): Pair<Int, Int> {- val now = System.currentTimeMillis()-- if (now - lastBatteryCheck > BATTERY_CHECK_INTERVAL_MS) {- val (level, batteryStatus) = locationUtils.getBatteryStatus()- cachedBatteryLevel = level- cachedBatteryStatus = batteryStatus // Now stores Int instead of Boolean- lastBatteryCheck = now- }-- return Pair(cachedBatteryLevel, cachedBatteryStatus)- }+ // Battery-related functionality has been moved to DeviceInfoHelper.kt+ // Use deviceInfoHelper.getCachedBatteryStatus() for cached battery info+ // Use deviceInfoHelper.isBatteryCritical() to check critical battery state/*** Cached queue count.@@ -517,7 +499,13 @@ class LocationForegroundService : Service() {// Invalidate cache after synclastQueueCountCheck = 0- return countAfter < countBefore || countAfter == 0+ // Update last successful sync time if queue was reduced+ val success = countAfter < countBefore || countAfter == 0+ if (success && countAfter == 0) {+ lastSuccessfulSyncTime = System.currentTimeMillis()+ }++ return success}private suspend fun applyBackoffDelay() {@@ -622,6 +610,11 @@ class LocationForegroundService : Service() {// Invalidate cache after all syncing is donelastQueueCountCheck = 0++ // Update last successful sync time if we processed items+ if (totalProcessed > 0) {+ lastSuccessfulSyncTime = System.currentTimeMillis()+ }}private suspend fun queueAndSend(@@ -651,6 +644,7 @@ class LocationForegroundService : Service() {if (success) {dbHelper.removeFromQueueByLocationId(locationId)lastQueueCountCheck = 0+ lastSuccessfulSyncTime = System.currentTimeMillis()} else {// Increment retry count using the queue ID we got from insertdbHelper.incrementRetryCount(queueId, "Send failed")@@ -724,6 +718,26 @@ class LocationForegroundService : Service() {.build()}+ /**+ * Format time since last sync in human-readable format.+ */+ private fun getTimeSinceLastSync(): String {+ if (lastSuccessfulSyncTime == 0L) {+ return "Never synced"+ }++ val elapsedMs = System.currentTimeMillis() - lastSuccessfulSyncTime+ val elapsedMinutes = (elapsedMs / 60000).toInt()++ return when {+ elapsedMinutes < 1 -> "Just now"+ elapsedMinutes == 1 -> "1 min ago"+ elapsedMinutes < 60 -> "$elapsedMinutes min ago"+ elapsedMinutes < 120 -> "1h ago"+ else -> "${elapsedMinutes / 60} h ago"+ }+ }+/*** Smart notification updates with throttling and distance checking.* Only updates when:@@ -782,7 +796,11 @@ class LocationForegroundService : Service() {isCurrentlyPaused -> "Paused: ${activeZone ?: "Unknown"}"lat != null && lon != null -> {val coords = "%.5f, %.5f".format(lat, lon)- if (queuedCount > 0) "$coords ($queuedCount pending)" else "$coords (Synced)"+ if (queuedCount > 0) {+ "$coords (Last sync: ${getTimeSinceLastSync()})"+ } else {+ "$coords (Synced)"+ }}else -> "Searching GPS..."}@@ -857,13 +875,7 @@ class LocationForegroundService : Service() {}if (BuildConfig.DEBUG) {- val batteryStatus = when(cachedBatteryStatus) {- 0 -> "Unknown"- 1 -> "Unplugged/Discharging"- 2 -> "Charging"- 3 -> "Full"- else -> "Unknown ($cachedBatteryStatus)"- }+ val batteryStatusStr = deviceInfoHelper.getBatteryStatusString()Log.d(TAG, """╔════════════════════════════════════════════════════════════════╗@@ -888,7 +900,7 @@ class LocationForegroundService : Service() {║ PERFORMANCE OPTIMIZATION ║╟────────────────────────────────────────────────────────────────╢║ Queue Count Cache: ${QUEUE_COUNT_CACHE_MS/1000}s- ║ Battery Check Cache: ${BATTERY_CHECK_INTERVAL_MS/1000}s+ ║ Battery Check Cache: 60s (managed by DeviceInfoHelper)║ Notification Throttle: ${NOTIFICATION_THROTTLE_MS/1000}s╟────────────────────────────────────────────────────────────────╢║ FIELD MAPPING ║@@ -904,8 +916,9 @@ class LocationForegroundService : Service() {╟────────────────────────────────────────────────────────────────╢║ Tracking Status: ✓ ACTIVE║ Silent Zone: ${if(insideSilentZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}- ║ Battery Level: $cachedBatteryLevel% ($batteryStatus)+ ║ Battery Level: $batteryStatusStr║ Queued Locations: $cachedQueuedCount items+ ║ Last Sync: ${getTimeSinceLastSync()}║ Last Location: ${if(lastKnownLocation != null) "%.5f, %.5f".format(lastKnownLocation!!.latitude, lastKnownLocation!!.longitude) else "N/A"}╚════════════════════════════════════════════════════════════════╝""".trimIndent())