Skip to content

Colota - Android GPS Location tracker

Harden codebase for production readiness

Max Dietriche47ff0d66014
diff --git a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
index 554b13fb..e43b3996 100644
--- a/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
+++ b/apps/mobile/android/app/src/foss/java/com/Colota/location/NativeLocationProvider.kt
@@ -22,12 +22,20 @@ import android.os.Looper
@SuppressLint("MissingPermission")
class NativeLocationProvider(context: Context) : LocationProvider {
+ companion object {
+ /** Suppress network updates for this duration after the last GPS fix. */
+ private const val GPS_SUPPRESSION_MS = 10_000L
+ }
+
private val locationManager: LocationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
/** Maps each callback to its GPS listener and optional network listener. */
private val listenerMap = java.util.concurrent.ConcurrentHashMap<LocationUpdateCallback, List<LocationListener>>()
+ /** Timestamp of last GPS fix, used to suppress redundant network updates. */
+ @Volatile private var lastGpsTime: Long = 0
+
override fun requestLocationUpdates(
intervalMs: Long,
minDistanceMeters: Float,
@@ -36,6 +44,7 @@ class NativeLocationProvider(context: Context) : LocationProvider {
) {
val listener = object : LocationListener {
override fun onLocationChanged(location: Location) {
+ lastGpsTime = System.currentTimeMillis()
callback.onLocationUpdate(location)
}
@Deprecated("Deprecated in API 29")
@@ -60,7 +69,9 @@ class NativeLocationProvider(context: Context) : LocationProvider {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
val networkListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
- callback.onLocationUpdate(location)
+ if (System.currentTimeMillis() - lastGpsTime > GPS_SUPPRESSION_MS) {
+ callback.onLocationUpdate(location)
+ }
}
@Deprecated("Deprecated in API 29")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
index c3905b04..b9e8833a 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt
@@ -250,10 +250,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
fun startService(config: ReadableMap, promise: Promise) {
Log.d(TAG, "Starting Service with config")
- moduleScope.launch(Dispatchers.IO) {
- dbHelper.saveSetting("tracking_enabled", "true")
- }
-
val serviceConfig = ServiceConfig.fromReadableMap(config, dbHelper)
val serviceIntent = Intent(reactApplicationContext, LocationForegroundService::class.java)
serviceConfig.toIntent(serviceIntent)
@@ -264,6 +260,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
} else {
reactApplicationContext.startService(serviceIntent)
}
+ moduleScope.launch(Dispatchers.IO) {
+ dbHelper.saveSetting("tracking_enabled", "true")
+ }
promise.resolve(null)
} catch (e: Exception) {
Log.e(TAG, "Failed to start service", e)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
index 4882b285..6eab35f2 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt
@@ -251,17 +251,11 @@ class DatabaseHelper private constructor(context: Context) :
return writableDatabase.insert(TABLE_LOCATIONS, null, values)
}
- /** Checks both sent and unsent locations to find the most recent one. */
+ /** Returns the most recent location (all locations live in the locations table). */
fun getRawMostRecentLocation(): Map<String, Any?>? {
val query = """
- SELECT latitude, longitude, accuracy, timestamp
- FROM (
- SELECT latitude, longitude, accuracy, timestamp FROM $TABLE_LOCATIONS
- UNION ALL
- SELECT l.latitude, l.longitude, l.accuracy, l.timestamp
- FROM $TABLE_QUEUE q
- JOIN $TABLE_LOCATIONS l ON q.location_id = l.id
- ) ORDER BY timestamp DESC LIMIT 1
+ SELECT latitude, longitude, accuracy, timestamp
+ FROM $TABLE_LOCATIONS ORDER BY timestamp DESC LIMIT 1
""".trimIndent()
return try {
@@ -523,11 +517,7 @@ class DatabaseHelper private constructor(context: Context) :
fun deleteOlderThan(days: Int): Int {
val cutoff = (System.currentTimeMillis() - days * 24 * 60 * 60 * 1000L) / 1000
- return writableDatabase.delete(
- TABLE_LOCATIONS,
- "timestamp < ?",
- arrayOf(cutoff.toString())
- )
+ return writableDatabase.delete(TABLE_LOCATIONS, "timestamp < ?", arrayOf(cutoff.toString()))
}
/** Reclaims unused space. Call from background thread only. */
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
index 251baa96..64c6800a 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt
@@ -157,16 +157,21 @@ class NetworkManager(private val context: Context) {
return true
}
+ private val privateHostCache = java.util.concurrent.ConcurrentHashMap<String, Boolean>()
+
/**
* Checks if the given host is private or local.
+ * Results are cached to avoid repeated DNS lookups on every request.
*/
private fun isPrivateHost(host: String): Boolean {
if (host == "localhost") return true
- return try {
- val address = java.net.InetAddress.getByName(host)
- address.isAnyLocalAddress || address.isLoopbackAddress || address.isSiteLocalAddress
- } catch (e: Exception) {
- false
+ return privateHostCache.getOrPut(host) {
+ try {
+ val address = java.net.InetAddress.getByName(host)
+ address.isAnyLocalAddress || address.isLoopbackAddress || address.isSiteLocalAddress
+ } catch (e: Exception) {
+ false
+ }
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
index 1134a652..2750009e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/FileOperations.kt
@@ -25,8 +25,8 @@ class FileOperations(private val context: ReactApplicationContext) {
* @return Full file path
*/
fun writeFile(fileName: String, content: String): String {
- val cacheDir = context.cacheDir
- val file = File(cacheDir, fileName)
+ val sanitized = File(fileName).name
+ val file = File(context.cacheDir, sanitized)
file.writeText(content)
return file.absolutePath
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
index 174926ab..9bc80dc4 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt
@@ -45,11 +45,21 @@ class SecureStorageHelper private constructor(context: Context) {
private val prefs: SharedPreferences
init {
+ prefs = try {
+ createEncryptedPrefs(context)
+ } catch (e: Exception) {
+ Log.e(TAG, "EncryptedSharedPreferences corrupted, clearing and retrying", e)
+ context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit().clear().commit()
+ createEncryptedPrefs(context)
+ }
+ }
+
+ private fun createEncryptedPrefs(context: Context): SharedPreferences {
val masterKey = MasterKey.Builder(context.applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
- prefs = EncryptedSharedPreferences.create(
+ return EncryptedSharedPreferences.create(
context.applicationContext,
PREFS_NAME,
masterKey,
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index c5bac7dc..84dc2431 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -10,6 +10,8 @@ import { Settings, ThemeColors } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
import { isPrivateHost, isEndpointAllowed } from "../../../utils/settingsValidation"
import { fonts } from "../../../styles/typography"
+import { useTimeout } from "../../../hooks/useTimeout"
+import { CONNECTION_TEST_TIMEOUT, TEST_RESULT_DISPLAY_MS } from "../../../constants"
import { Button, Card, SectionTitle, Divider } from "../../index"
interface ConnectionSettingsProps {
@@ -32,6 +34,7 @@ export function ConnectionSettings({
const [testing, setTesting] = useState(false)
const [testResponse, setTestResponse] = useState<string | null>(null)
const [testError, setTestError] = useState(false)
+ const timeout = useTimeout()
const handleOfflineModeChange = useCallback(
(enabled: boolean) => {
@@ -86,11 +89,15 @@ export function ConnectionSettings({
const params = new URLSearchParams(Object.entries(payload).map(([k, v]) => [k, String(v)]))
const url =
method === "GET" ? `${endpointInput}${endpointInput.includes("?") ? "&" : "?"}${params}` : endpointInput
+ const controller = new AbortController()
+ timeout.set(() => controller.abort(), CONNECTION_TEST_TIMEOUT)
const response = await fetch(url, {
method,
headers: method === "GET" ? authHeaders : { "Content-Type": "application/json", ...authHeaders },
- ...(method === "GET" ? {} : { body: JSON.stringify(payload) })
+ ...(method === "GET" ? {} : { body: JSON.stringify(payload) }),
+ signal: controller.signal
})
+ timeout.clear()
if (response.ok) {
setTestResponse("Connection successful")
@@ -101,14 +108,19 @@ export function ConnectionSettings({
}
} catch (err: any) {
const msg = err.message?.toLowerCase() || ""
- const userMessage = msg.includes("network request failed") ? "No internet connection" : "Connection failed"
+ const userMessage =
+ err.name === "AbortError"
+ ? "Connection timed out"
+ : msg.includes("network request failed")
+ ? "No internet connection"
+ : "Connection failed"
setTestResponse(userMessage)
setTestError(true)
} finally {
setTesting(false)
- setTimeout(() => setTestResponse(null), 3000)
+ timeout.set(() => setTestResponse(null), TEST_RESULT_DISPLAY_MS)
}
- }, [endpointInput, settings, onSettingsChange])
+ }, [endpointInput, settings, onSettingsChange, timeout])
return (
<View style={styles.section}>
diff --git a/apps/mobile/src/constants/index.ts b/apps/mobile/src/constants/index.ts
index 230c11a5..e8d3f145 100644
--- a/apps/mobile/src/constants/index.ts
+++ b/apps/mobile/src/constants/index.ts
@@ -11,8 +11,12 @@ export const AUTOSAVE_DEBOUNCE_MS = 1500
export const STATS_REFRESH_IDLE = 30_000
export const STATS_REFRESH_FAST = 3_000
export const SERVER_TIMEOUT = 5_000
+export const CONNECTION_TEST_TIMEOUT = 10_000
export const SERVER_CHECK_INTERVAL = 5 * 60 * 1000
export const SAVE_SUCCESS_DISPLAY_MS = 2000
+export const TEST_RESULT_DISPLAY_MS = 3_000
+export const SERVICE_RESTART_DELAY_MS = 500
+export const RESTART_DEBOUNCE_MS = 100
// Map
export const DEFAULT_MAP_ZOOM = 17
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index c345bc90..fae4391d 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -56,9 +56,21 @@ function parseRawSettings(allRaw: Record<string, string>): Settings {
syncPreset: (allRaw.syncPreset as any) ?? DEFAULT_SETTINGS.syncPreset,
filterInaccurateLocations: allRaw.filterInaccurateLocations === "true",
- fieldMap: allRaw.fieldMap ? JSON.parse(allRaw.fieldMap) : DEFAULT_SETTINGS.fieldMap,
+ fieldMap: (() => {
+ try {
+ return allRaw.fieldMap ? JSON.parse(allRaw.fieldMap) : DEFAULT_SETTINGS.fieldMap
+ } catch {
+ return DEFAULT_SETTINGS.fieldMap
+ }
+ })(),
- customFields: allRaw.customFields ? JSON.parse(allRaw.customFields) : DEFAULT_SETTINGS.customFields,
+ customFields: (() => {
+ try {
+ return allRaw.customFields ? JSON.parse(allRaw.customFields) : DEFAULT_SETTINGS.customFields
+ } catch {
+ return DEFAULT_SETTINGS.customFields
+ }
+ })(),
apiTemplate: (allRaw.apiTemplate as ApiTemplateName) ?? DEFAULT_SETTINGS.apiTemplate,
httpMethod: (allRaw.httpMethod as HttpMethod) ?? DEFAULT_SETTINGS.httpMethod,
diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.ts
index 9bbbe336..a1644b01 100644
--- a/apps/mobile/src/hooks/useLocationTracking.ts
+++ b/apps/mobile/src/hooks/useLocationTracking.ts
@@ -9,6 +9,7 @@ import NativeLocationService from "../services/NativeLocationService"
import { showAlert } from "../services/modalService"
import { LocationCoords, Settings, LocationTrackingResult } from "../types/global"
import { ensurePermissions } from "../services/LocationServicePermission"
+import { SERVICE_RESTART_DELAY_MS, RESTART_DEBOUNCE_MS } from "../constants"
import { logger } from "../utils/logger"
const { LocationServiceModule } = NativeModules
@@ -251,7 +252,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult
stopTracking()
// Android requires delay to fully release foreground service
- await new Promise<void>((resolve) => setTimeout(resolve, 500))
+ await new Promise<void>((resolve) => setTimeout(resolve, SERVICE_RESTART_DELAY_MS))
await startTracking(newSettings ?? settingsRef.current)
} finally {
@@ -262,7 +263,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult
if (restartQueuedRef.current) {
restartQueuedRef.current = false
logger.debug("[useLocationTracking] Processing queued restart")
- setTimeout(() => restartTracking(settingsRef.current), 100)
+ setTimeout(() => restartTracking(settingsRef.current), RESTART_DEBOUNCE_MS)
}
}
},
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index 618b2033..96ad1954 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -27,37 +27,48 @@ export function ExportDataScreen() {
const loadStats = useCallback(async () => {
try {
- const data = await NativeLocationService.getExportData()
-
- if (data && data.length > 0) {
- cachedData.current = data.map((item) => ({
- ...item,
- timestamp: item.timestamp ? item.timestamp * 1000 : Date.now()
- }))
-
- setTotalLocations(data.length)
- }
+ const stats = await NativeLocationService.getStats()
+ setTotalLocations(stats.total ?? 0)
} catch (error) {
logger.error("[ExportDataScreen] Failed to load stats:", error)
}
}, [])
+ const loadExportData = useCallback(async () => {
+ if (cachedData.current.length > 0) return
+ const data = await NativeLocationService.getExportData()
+ if (data && data.length > 0) {
+ cachedData.current = data.map((item) => ({
+ ...item,
+ timestamp: item.timestamp ? item.timestamp * 1000 : Date.now()
+ }))
+ }
+ }, [])
+
useEffect(() => {
loadStats()
}, [loadStats])
// Convert once on format selection, cache the result for both size preview and export
useEffect(() => {
- if (!selectedFormat || cachedData.current.length === 0) {
+ if (!selectedFormat || totalLocations === 0) {
setFileSize(null)
cachedContent.current = null
return
}
- const content = EXPORT_FORMATS[selectedFormat].convert(cachedData.current)
- cachedContent.current = { format: selectedFormat, content }
- setFileSize(formatBytes(getByteSize(content)))
- }, [selectedFormat, totalLocations])
+ let cancelled = false
+ ;(async () => {
+ await loadExportData()
+ if (cancelled || cachedData.current.length === 0) return
+ const content = EXPORT_FORMATS[selectedFormat].convert(cachedData.current)
+ cachedContent.current = { format: selectedFormat, content }
+ setFileSize(formatBytes(getByteSize(content)))
+ })()
+ return () => {
+ cancelled = true
+ }
+ }, [selectedFormat, totalLocations, loadExportData])
const handleExport = async (format: ExportFormat) => {
if (totalLocations === 0) {
@@ -69,6 +80,7 @@ export function ExportDataScreen() {
setExportProgress("Preparing export...")
try {
+ await loadExportData()
setExportProgress(`Converting ${cachedData.current.length} locations...`)
// Reuse cached conversion if format matches, otherwise convert fresh
diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsx
index 66f62e8a..7799e4cc 100644
--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx
+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx
@@ -137,24 +137,25 @@ export function LocationHistoryScreen() {
return formatDistance(meters)
}, [trackLocations])
- const fetchIdRef = useRef(0)
+ const fetchListIdRef = useRef(0)
+ const fetchTrackIdRef = useRef(0)
/** Fetches data based on current pagination */
const fetchData = useCallback(async () => {
- const id = ++fetchIdRef.current
+ const id = ++fetchListIdRef.current
try {
const offset = page * limit
const result = await NativeLocationService.getTableData("locations", limit, offset)
- if (id === fetchIdRef.current) setData(result || [])
+ if (id === fetchListIdRef.current) setData(result || [])
} catch (err) {
logger.error("[LocationHistory] Fetch error:", err)
- if (id === fetchIdRef.current) setData([])
+ if (id === fetchListIdRef.current) setData([])
}
}, [limit, page])
/** Fetch track data for the selected day */
const fetchTrackData = useCallback(async () => {
- const id = ++fetchIdRef.current
+ const id = ++fetchTrackIdRef.current
try {
const start = new Date(mapDate)
start.setHours(0, 0, 0, 0)
@@ -165,10 +166,10 @@ export function LocationHistoryScreen() {
const endTimestamp = Math.floor(end.getTime() / 1000)
const result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)
- if (id === fetchIdRef.current) setTrackLocations(result || [])
+ if (id === fetchTrackIdRef.current) setTrackLocations(result || [])
} catch (err) {
logger.error("[LocationHistory] Track fetch error:", err)
- if (id === fetchIdRef.current) setTrackLocations([])
+ if (id === fetchTrackIdRef.current) setTrackLocations([])
}
}, [mapDate])
diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
index f14bd449..e7537042 100644
--- a/apps/mobile/src/screens/TrackingProfilesScreen.tsx
+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx
@@ -127,6 +127,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
<View style={styles.actions}>
<Switch
+ testID={`toggle-profile-${item.id}`}
value={item.enabled}
onValueChange={(val) => toggleEnabled(item.id, val)}
trackColor={{ false: colors.border, true: colors.primary + "80" }}
@@ -134,6 +135,7 @@ export function TrackingProfilesScreen({ navigation }: ScreenProps) {
/>
<TouchableOpacity
+ testID={`delete-profile-${item.id}`}
onPress={() => handleDelete(item)}
style={[styles.deleteBtn, { backgroundColor: colors.error + "15" }]}
activeOpacity={0.7}
diff --git a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
index 9624c825..9b83914d 100644
--- a/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/TrackingProfilesScreen.test.tsx
@@ -176,16 +176,21 @@ describe("TrackingProfilesScreen", () => {
})
it("shows confirmation dialog before deleting", async () => {
- const { getByText } = renderScreen()
+ const { getByText, getByTestId } = renderScreen()
await waitFor(() => {
expect(getByText("Charging")).toBeTruthy()
})
- // The delete buttons are X icons — simulate by finding the delete touchable
- // Since we can't easily target the X button, verify the confirm dialog is called
- // when handleDelete is triggered
- expect(mockDeleteProfile).not.toHaveBeenCalled()
+ fireEvent.press(getByTestId("delete-profile-1"))
+
+ await waitFor(() => {
+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Delete Profile" }))
+ })
+
+ await waitFor(() => {
+ expect(mockDeleteProfile).toHaveBeenCalledWith(1)
+ })
})
it("shows section title with profile count", async () => {
@@ -199,10 +204,16 @@ describe("TrackingProfilesScreen", () => {
it("shows error when toggle fails", async () => {
mockUpdateProfile.mockRejectedValueOnce(new Error("Network error"))
- const { getByText } = renderScreen()
+ const { getByText, getByTestId } = renderScreen()
await waitFor(() => {
- expect(getByText("Charging")).toBeTruthy()
+ expect(getByText("Driving")).toBeTruthy()
+ })
+
+ fireEvent(getByTestId("toggle-profile-2"), "onValueChange", true)
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Error", expect.any(String), "error")
})
})