Skip to content

Colota - Android GPS Location tracker

refactor: split ExportConverters, NetworkMonitor and the rest of SyncManager into smaller files (#988)

Max Dietriche7bab6b808f3
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index 2ba5e5e3..ffcf715f 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -208,7 +208,7 @@ Orchestrates batch location uploads with:
- Configurable batch size (50 items per batch, 10 concurrent HTTP requests)
- Exponential backoff on failure
- A pass stops on a 429, and nothing is sent until its `Retry-After` wait is over (60 s without one, capped at 15 min): the periodic tick, a manual or zone-entry flush and an instant send all hold. In the per-point format a pass also stops on a 5xx or a network error once a group of 10 requests got nothing through, so an unreachable server costs one group of requests. A batch upload stops on its first 429, 5xx or network error
-- Overland batch uploads go through `OverlandBatchSender`, which halves a batch the server rejects with a 4xx until the refused row is alone. The rate-limit wait lives in `SyncState`, so it outlives the service that met the 429
+- Overland batch uploads go through `OverlandBatchSender`, which halves a batch the server rejects with a 4xx until the refused row is alone. The per-point format goes through `PointSender`, 10 requests at a time, and `SyncSchedule` times the periodic tick and the backoff. The rate-limit wait lives in `SyncState`, so it outlives the service that met the 429
- Periodic sync scheduling. A new interval (a profile switch) applies to the wait already running, measured from when it began; a send or a backoff in progress finishes first
- Manual flush support
- One pass at a time: a periodic tick and a manual flush wait for the running pass. An instant send leaves its row queued while a pass runs, and a pass skips rows an instant send is still posting
@@ -223,7 +223,7 @@ For mTLS-protected endpoints, builds the `HttpsURLConnection` with a custom `SSL
### NetworkMonitor
-Network state for the sync conditions and the profile Wi-Fi conditions. Caches connectivity checks and detects unmetered connections and VPN status. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the sync `wifi_ssid` condition is active; profile conditions read the name through a one-shot probe when the network changes. Connected Wi-Fi is tracked separately with a plain (unflagged) Wi-Fi-transport callback, so the profile conditions also see the network under a VPN.
+Network state for the sync conditions and the profile Wi-Fi conditions. Caches connectivity checks and detects unmetered connections and VPN status. SSID detection needs a location-flagged network callback, which is attributed as location access, so it is registered only while the sync `wifi_ssid` condition is active; profile conditions read the name through a one-shot probe (`WifiNameReader`) when the network changes. Connected Wi-Fi is tracked separately with a plain (unflagged) Wi-Fi-transport callback, so the profile conditions also see the network under a VPN.
### UrlSafety
@@ -305,7 +305,7 @@ For backups, two `internal` methods support the export/import flow without expos
| `AutoExportAlarmReceiver` | Broadcast receiver fired by AlarmManager at the configured time - hands off to `AutoExportWorker` because the receiver's 10s budget can't run an export |
| `AutoExportScheduler` | Arms `AlarmManager.setAndAllowWhileIdle` for the next configured wall-clock time. Called on enable, by the alarm receiver on every fire, after each worker run, after schedule edits and on boot |
| `AutoExportConfig` | Typed data class wrapping auto-export settings (interval, time-of-day, weekday, day-of-month, enabledAt) from the SQLite settings table with validation, `isExportDue()` and `nextExportTimestamp()` |
-| `ExportConverters` | Native CSV/GeoJSON/GPX/KML serialization for both "Export all" (flat, streamed via `exportToFile`) and per-trip / multi-select export (trip-segmented via `convertTrips`, reached through the `exportTripsToFile` bridge). In-memory, streaming, and file-based interfaces |
+| `ExportConverters` | Native CSV/GeoJSON/GPX/KML serialization for "Export all" (flat, streamed via `exportToFile`). In-memory, streaming, and file-based interfaces. `TripConverters` writes the per-trip / multi-select export (`convertTrips`, reached through the `exportTripsToFile` bridge), and `ExportFilenames` names auto-export files and picks the ones retention deletes |
| `ShortcutHandlerActivity` | Transparent activity handling app shortcut intents (start/stop tracking) without UI. Delegates to the shared `TrackingControl` helper |
| `TrackingControlReceiver` | Exported broadcast receiver for automation apps - `com.Colota.action.START_TRACKING` / `STOP_TRACKING` start or stop tracking from saved settings. Delegates to `TrackingControl` |
| `TrackingControl` | Shared start/stop tracking actions used by both triggers above: reads config from DB via `ServiceConfig.fromDatabase()`, starts the foreground service and fires the started event; stop is routed through the service so `stopForegroundServiceWithReason` runs |
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 269e6192..31a5d335 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
@@ -34,6 +34,9 @@ import com.Colota.export.AutoExportConfig
import com.Colota.export.AutoExportScheduler
import com.Colota.export.AutoExportWorker
import com.Colota.export.ExportConverters
+import com.Colota.export.ExportFilenames
+import com.Colota.export.TripConverters
+import com.Colota.export.TripExport
import com.Colota.util.AppFileLogger
import com.Colota.util.FileOperations
import com.Colota.util.LogExportMerger
@@ -1187,7 +1190,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun exportToFile(format: String, promise: Promise) = executeAsync(promise) {
val ext = ExportConverters.extensionFor(format)
- val tempFile = java.io.File(reactApplicationContext.cacheDir, "manual_export_${ExportConverters.exportFilenameStamp()}$ext")
+ val tempFile = java.io.File(reactApplicationContext.cacheDir, "manual_export_${ExportFilenames.exportFilenameStamp()}$ext")
val totalRows = ExportConverters.exportToFile(dbHelper, format, tempFile)
@@ -1210,13 +1213,13 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
*/
@ReactMethod
fun exportTripsToFile(trips: ReadableArray, format: String, fileName: String, promise: Promise) = executeAsync(promise) {
- val tripExports = ArrayList<ExportConverters.TripExport>(trips.size())
+ val tripExports = ArrayList<TripExport>(trips.size())
for (i in 0 until trips.size()) {
val t = trips.getMap(i) ?: continue
val rows = dbHelper.getLocationsByDateRange(t.getDouble("startTs").toLong(), t.getDouble("endTs").toLong())
- tripExports.add(ExportConverters.TripExport(t.getInt("index"), t.getString("color") ?: "#3B82F6", rows))
+ tripExports.add(TripExport(t.getInt("index"), t.getString("color") ?: "#3B82F6", rows))
}
- fileOps.writeFile(fileName, ExportConverters.convertTrips(format, tripExports))
+ fileOps.writeFile(fileName, TripConverters.convertTrips(format, tripExports))
}
@ReactMethod
@@ -1227,7 +1230,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
} else {
val dirUri = android.net.Uri.parse(config.uri)
val dir = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, dirUri)
- val matchers = ExportConverters.exportFileMatchers(config.filenameTemplate, android.os.Build.MODEL)
+ val matchers = ExportFilenames.exportFileMatchers(config.filenameTemplate, android.os.Build.MODEL)
// Every DocumentFile getter is a separate query, so read each file once up front
// rather than once per sort comparison. Ordering uses the stamp in the name, since a
// device prefix would break plain name order.
@@ -1238,7 +1241,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
else ExportFileInfo(name, file.length(), file.lastModified(), file.uri.toString())
}
?.sortedWith(
- compareByDescending<ExportFileInfo> { ExportConverters.stampOf(it.name, matchers) }
+ compareByDescending<ExportFileInfo> { ExportFilenames.stampOf(it.name, matchers) }
.thenByDescending { it.lastModified }
.thenByDescending { it.name }
)
@@ -1282,7 +1285,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
return try {
val dirUri = android.net.Uri.parse(config.uri)
val dir = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, dirUri)
- val matchers = ExportConverters.exportFileMatchers(config.filenameTemplate, android.os.Build.MODEL)
+ val matchers = ExportFilenames.exportFileMatchers(config.filenameTemplate, android.os.Build.MODEL)
dir?.listFiles()?.count { file ->
matchers.any { it.matches(file.name.orEmpty()) }
} ?: 0
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
index aa6a42e3..46fe07a0 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt
@@ -30,7 +30,7 @@ data class AutoExportConfig(
val weeklyDow: Int = 1,
val monthlyDom: Int = 1,
val enabledAt: Long = 0L,
- val filenameTemplate: String = ExportConverters.DEFAULT_FILENAME_TEMPLATE
+ val filenameTemplate: String = ExportFilenames.DEFAULT_FILENAME_TEMPLATE
) {
companion object {
private const val TAG = "AutoExportConfig"
@@ -84,8 +84,8 @@ data class AutoExportConfig(
// rejected; write the correction back so the UI stops showing one the exporter never
// uses. Best-effort, since saveSetting throws mid-restore.
val rawTemplate = db.getSetting(KEY_FILENAME_TEMPLATE)
- val filenameTemplate = rawTemplate?.takeIf { ExportConverters.isValidFilenameTemplate(it) }
- ?: ExportConverters.DEFAULT_FILENAME_TEMPLATE.also {
+ val filenameTemplate = rawTemplate?.takeIf { ExportFilenames.isValidFilenameTemplate(it) }
+ ?: ExportFilenames.DEFAULT_FILENAME_TEMPLATE.also {
if (rawTemplate != null) {
AppLogger.w(TAG, "Filename template '$rawTemplate' is not usable, reset to default")
try {
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
index 027f1d14..ac590916 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
@@ -136,7 +136,7 @@ class AutoExportWorker(
// points written mid-export aren't dropped and the name matches the range it covers.
val exportStartSec = System.currentTimeMillis() / 1000
- val fileName = ExportConverters.renderExportFilename(
+ val fileName = ExportFilenames.renderExportFilename(
config.filenameTemplate,
config.format,
Build.MODEL,
@@ -184,7 +184,7 @@ class AutoExportWorker(
val savedName = destDocFile.name ?: fileName
// A name cleanup cannot match would sit in the directory forever; say so rather than
// leaving the retention limit quietly broken.
- if (ExportConverters.exportFileMatchers(config.filenameTemplate, Build.MODEL).none { it.matches(savedName) }) {
+ if (ExportFilenames.exportFileMatchers(config.filenameTemplate, Build.MODEL).none { it.matches(savedName) }) {
AppLogger.w(TAG, "Saved as '$savedName', which retention will not recognise")
}
AppLogger.i(TAG, "Auto-export complete: $savedName ($rowCount locations)")
@@ -300,7 +300,7 @@ class AutoExportWorker(
/**
* Deletes only files the configured template could have produced, so subfolders and sync
- * artifacts are left alone. Selection lives in [ExportConverters.selectForDeletion] so it is
+ * artifacts are left alone. Selection lives in [ExportFilenames.selectForDeletion] so it is
* testable without SAF.
*/
private fun cleanupOldExports(dirUri: Uri, config: AutoExportConfig) {
@@ -311,7 +311,7 @@ class AutoExportWorker(
try {
val dir = DocumentFile.fromTreeUri(appContext, dirUri) ?: return
- val matchers = ExportConverters.exportFileMatchers(config.filenameTemplate, Build.MODEL)
+ val matchers = ExportFilenames.exportFileMatchers(config.filenameTemplate, Build.MODEL)
// Each DocumentFile getter is its own query, so only the names that already match pay
// for lastModified and isFile. A shared folder can hold far more files than ours.
@@ -320,9 +320,9 @@ class AutoExportWorker(
.map { it to it.name.orEmpty() }
.filter { (_, name) -> matchers.any { it.matches(name) } }
.map { (file, name) ->
- file to ExportConverters.ExportEntry(name, file.lastModified(), file.isFile)
+ file to ExportFilenames.ExportEntry(name, file.lastModified(), file.isFile)
}
- val selected = ExportConverters
+ val selected = ExportFilenames
.selectForDeletion(candidates.map { it.second }, config.retentionCount, matchers)
.map { it.name }
val doomed = selected.toMutableList()
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
index d22dea35..cbf3c4b3 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt
@@ -6,7 +6,6 @@
package com.Colota.export
import com.Colota.data.DatabaseHelper
-import com.Colota.util.BatteryStatus
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.File
@@ -14,10 +13,7 @@ import java.io.FileReader
import java.io.FileWriter
import java.io.OutputStreamWriter
import java.io.Writer
-import java.text.SimpleDateFormat
-import java.util.Date
import java.util.Locale
-import java.util.TimeZone
/** Spools KML LineString coords to a temp file to avoid OOM on large exports. */
class KmlCoordsCollector(cacheDir: File) : AutoCloseable {
@@ -51,230 +47,6 @@ object ExportConverters {
const val PAGE_SIZE = 10_000
- /** Filename-safe stamp for export files (e.g. `2026-05-28_1430`). */
- fun exportFilenameStamp(): String =
- SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date())
-
- // --- Auto-export filename templates ---
-
- const val FILENAME_MARKER = "colota_export"
- const val DEFAULT_FILENAME_TEMPLATE = "colota_export_{date}_{time}"
-
- // Together these stay well inside the 255-byte filesystem name limit.
- private const val MAX_TEMPLATE_LENGTH = 100
- private const val MAX_DEVICE_LENGTH = 32
-
- // Braces are escaped on both sides: Android compiles patterns with ICU, which rejects a bare
- // closing brace that the JDK engine used by unit tests accepts.
- private val FILENAME_TOKEN = Regex("""\{(date|time)\}""")
- private val ILLEGAL_FILENAME_CHARS = Regex("""[\\/:*?"<>|\{\}\x00-\x1F\x7F]""")
- private val FILENAME_WHITESPACE = Regex("""[\s\p{Z}\uFEFF]+""")
-
- // SAF renames a colliding file to "name (1).ext"; that is still our file.
- private const val DEDUPE_SUFFIX_PATTERN = """(?: \(\d+\))?"""
-
- /**
- * The marker lets cleanup tell Colota's files from the user's; `{date}` and `{time}` keep each
- * export uniquely named and chronologically sortable.
- */
- fun isValidFilenameTemplate(template: String): Boolean =
- template.length <= MAX_TEMPLATE_LENGTH &&
- template.contains(FILENAME_MARKER) &&
- template.contains("{date}") &&
- template.contains("{time}")
-
- /** [template] must already have passed [isValidFilenameTemplate]. */
- fun renderExportFilename(
- template: String,
- format: String,
- deviceName: String,
- now: Date = Date()
- ): String {
- val base = resolveTemplate(template, deviceName)
- .replace("{date}", SimpleDateFormat("yyyy-MM-dd", Locale.US).format(now))
- .replace("{time}", SimpleDateFormat("HHmm", Locale.US).format(now))
- .let { ILLEGAL_FILENAME_CHARS.replace(it, "") }
- .trim(::isTrimmable)
-
- return base + extensionFor(format)
- }
-
- /**
- * Substitutes `{device}` up front so the matcher and the renderer see the same literals. An
- * empty or dot-ending device name would otherwise shift where the end trim lands.
- */
- private fun resolveTemplate(template: String, deviceName: String): String =
- template.replace("{device}", sanitizeDevicePart(deviceName))
-
- /** Whitespace goes entirely (`Pixel 7` -> `Pixel7`), not just the illegal characters. */
- private fun sanitizeDevicePart(deviceName: String): String =
- ILLEGAL_FILENAME_CHARS.replace(FILENAME_WHITESPACE.replace(deviceName, ""), "").take(MAX_DEVICE_LENGTH)
-
- private fun isTrimmable(c: Char): Boolean = c == '.' || c.isWhitespace()
-
- /**
- * Recognizes files [renderExportFilename] produced from the same template. Anchored, so a
- * directory, a sync artifact or another device's export does not match. Any known export
- * extension is accepted so switching format does not orphan older files from retention.
- */
- class ExportFileMatcher internal constructor(
- private val regex: Regex,
- private val dateGroup: Int,
- private val timeGroup: Int
- ) {
- fun matches(name: String): Boolean = regex.matches(name)
-
- /** Sortable `yyyy-MM-ddHHmm` stamp, or null when [name] is not ours. */
- fun stamp(name: String): String? {
- val match = regex.matchEntire(name) ?: return null
- return match.groupValues[dateGroup] + match.groupValues[timeGroup]
- }
- }
-
- fun exportFileMatcher(template: String, deviceName: String): ExportFileMatcher {
- val resolved = resolveTemplate(template, deviceName)
- val tokens = FILENAME_TOKEN.findAll(resolved).toList()
-
- val pattern = StringBuilder()
- var dateGroup = 0
- var timeGroup = 0
- var group = 0
- var cursor = 0
-
- tokens.forEachIndexed { index, token ->
- pattern.append(literalPattern(resolved.substring(cursor, token.range.first), index == 0, false))
- group++
- if (token.groupValues[1] == "date") {
- pattern.append("""(\d{4}-\d{2}-\d{2})""")
- if (dateGroup == 0) dateGroup = group
- } else {
- pattern.append("""(\d{4})""")
- if (timeGroup == 0) timeGroup = group
- }
- cursor = token.range.last + 1
- }
- pattern.append(literalPattern(resolved.substring(cursor), tokens.isEmpty(), true))
- pattern.append(DEDUPE_SUFFIX_PATTERN)
- pattern.append(EXTENSION_PATTERN)
-
- return ExportFileMatcher(Regex(pattern.toString()), dateGroup, timeGroup)
- }
-
- // A SAF provider appends the canonical extension for the MIME it was given when the name does
- // not already end in one, so files written before the geo+json fix are named ".geojson.json".
- private const val PROVIDER_SUFFIX_PATTERN = "(?:\\.json|\\.xml|\\.txt)?"
-
- // lazy so it does not depend on where extensionFor's format objects sit in the init order.
- private val EXTENSION_PATTERN: String by lazy {
- listOf("csv", "geojson", "gpx", "kml").joinToString("|", "(?:", ")") { Regex.escape(extensionFor(it)) } +
- PROVIDER_SUFFIX_PATTERN
- }
-
- /** The rendered name is trimmed at both ends, so the outermost literals are trimmed too. */
- private fun literalPattern(raw: String, first: Boolean, last: Boolean): String {
- var literal = ILLEGAL_FILENAME_CHARS.replace(raw, "")
- if (first) literal = literal.trimStart(::isTrimmable)
- if (last) literal = literal.trimEnd(::isTrimmable)
- return if (literal.isEmpty()) "" else Regex.escape(literal)
- }
-
- /**
- * Falls back to the default template so files written before a template change stay managed.
- * Skipped for `{device}` templates: a default-named file could have come from any device, and
- * deleting another phone's exports is worse than leaving a few of our own behind.
- */
- fun exportFileMatchers(template: String, deviceName: String): List<ExportFileMatcher> =
- if (template == DEFAULT_FILENAME_TEMPLATE || template.contains("{device}")) {
- listOf(exportFileMatcher(template, deviceName))
- } else {
- listOf(exportFileMatcher(template, deviceName), exportFileMatcher(DEFAULT_FILENAME_TEMPLATE, deviceName))
- }
-
- data class ExportEntry(val name: String, val lastModified: Long, val isFile: Boolean)
-
- /**
- * Oldest-first selection of the entries beyond [retentionCount]. Ordering prefers the stamp in
- * the filename; lastModified is only a tiebreak because SAF providers may omit the column
- * (returning 0) and cloud providers restamp on sync.
- */
- fun selectForDeletion(
- entries: List<ExportEntry>,
- retentionCount: Int,
- matchers: List<ExportFileMatcher>
- ): List<ExportEntry> {
- if (retentionCount <= 0) return emptyList()
- val ours = entries.filter { entry -> matchers.any { it.matches(entry.name) } && entry.isFile }
- val toDelete = ours.size - retentionCount
- if (toDelete <= 0) return emptyList()
- return ours
- .sortedWith(compareBy({ stampOf(it.name, matchers) }, { it.lastModified }, { it.name }))
- .take(toDelete)
- }
-
- /** Sort key for an export filename; empty when no matcher recognizes it. */
- fun stampOf(name: String, matchers: List<ExportFileMatcher>): String =
- matchers.firstNotNullOfOrNull { it.stamp(name) } ?: ""
-
- private fun isoTime(unixSeconds: Long): String {
- val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
- sdf.timeZone = TimeZone.getTimeZone("UTC")
- return sdf.format(Date(unixSeconds * 1000))
- }
-
- private fun jsonValue(value: Any?): String = when (value) {
- null -> "null"
- is String -> "\"${escapeJson(value)}\""
- is Double, is Float -> jsNum(value)
- else -> value.toString()
- }
-
- /** Human-readable battery-status label for exports; null if not recorded. */
- private fun batteryStatusLabel(v: Any?): String? = when (v) {
- is Long -> BatteryStatus.toDisplayString(v.toInt())
- is Int -> BatteryStatus.toDisplayString(v)
- is Double -> BatteryStatus.toDisplayString(v.toInt())
- else -> null
- }
-
- /** Escape free text for XML element content (GPX/KML notes). */
- private fun xmlEscape(s: String): String = buildString(s.length) {
- for (c in s) {
- when (c) {
- '&' -> append("&amp;")
- '<' -> append("&lt;")
- '>' -> append("&gt;")
- '"' -> append("&quot;")
- '\'' -> append("&apos;")
- else -> append(c)
- }
- }
- }
-
- /** RFC-4180 CSV field: quote+double-escape only when the value contains a delimiter. */
- private fun csvField(value: Any?): String {
- val s = value?.toString() ?: return ""
- return if (s.any { it == ',' || it == '"' || it == '\n' || it == '\r' }) {
- "\"" + s.replace("\"", "\"\"") + "\""
- } else {
- s
- }
- }
-
- private fun escapeJson(s: String): String = buildString(s.length) {
- for (c in s) {
- when (c) {
- '"' -> append("\\\"")
- '\\' -> append("\\\\")
- '\n' -> append("\\n")
- '\r' -> append("\\r")
- '\t' -> append("\\t")
- '\b' -> append("\\b")
- '\u000C' -> append("\\f")
- else -> if (c < ' ') append("\\u${c.code.toString(16).padStart(4, '0')}") else append(c)
- }
- }
- }
-
private data class ExportRow(
val ts: Long,
val lat: Double,
@@ -564,196 +336,4 @@ object ExportConverters {
"csv", "geojson", "gpx", "kml" -> forFormat(format).mimeType
else -> "text/plain"
}
-
- // Trip-segmented export (one track/folder per trip), separate from the flat
- // FormatWriter above. Ports the former JS TRIP_CONVERTERS; parity pinned by golden tests.
-
- /** color is a #RRGGBB hex supplied by JS (getTripColor), not computed here. */
- data class TripExport(val index: Int, val color: String, val rows: List<Map<String, Any?>>)
-
- /** Match JS number formatting: whole-valued doubles drop the trailing ".0". */
- private fun jsNum(v: Any): String = when (v) {
- is Double -> if (v.isFinite() && v == Math.floor(v) && kotlin.math.abs(v) < 1e15) v.toLong().toString() else v.toString()
- is Float -> jsNum(v.toDouble())
- else -> v.toString()
- }
-
- /** Numeric field with a `0` default for null (mirrors JS `?? 0` / `|| 0`). */
- private fun numOrZero(v: Any?): String = if (v == null) "0" else jsNum(v)
-
- /** GeoJSON property value: `null` stays `null` (JSON), otherwise JS-formatted number. */
- private fun jsonNum(v: Any?): String = if (v == null) "null" else jsNum(v)
-
- private fun asDouble(v: Any?): Double = when (v) {
- is Double -> v
- is Float -> v.toDouble()
- is Long -> v.toDouble()
- is Int -> v.toDouble()
- else -> 0.0
- }
-
- /** Hex RGB (#RRGGBB) -> KML ABGR (ffBBGGRR). */
- private fun hexToKmlColor(hex: String): String {
- val h = hex.removePrefix("#")
- if (h.length < 6) return "ff0000ff"
- return "ff${h.substring(4, 6)}${h.substring(2, 4)}${h.substring(0, 2)}"
- }
-
- private fun rowTs(row: Map<String, Any?>): Long =
- (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
-
- fun convertTrips(format: String, trips: List<TripExport>): String = when (format) {
- "csv" -> tripsToCsv(trips)
- "geojson" -> tripsToGeoJson(trips)
- "gpx" -> tripsToGpx(trips)
- "kml" -> tripsToKml(trips)
- else -> throw IllegalArgumentException("Unknown export format: $format")
- }
-
- private fun tripsToCsv(trips: List<TripExport>): String {
- val sb = StringBuilder("trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note\n")
- val rows = ArrayList<String>()
- for (trip in trips) {
- trip.rows.forEachIndexed { i, row ->
- val ts = rowTs(row)
- rows.add(
- listOf(
- trip.index.toString(), i.toString(), ts.toString(), isoTime(ts),
- numOrZero(row["latitude"]), numOrZero(row["longitude"]),
- numOrZero(row["accuracy"]), numOrZero(row["altitude"]),
- numOrZero(row["speed"]), numOrZero(row["bearing"]), numOrZero(row["battery"]),
- batteryStatusLabel(row["battery_status"]) ?: "", csvField(row["note"])
- ).joinToString(",")
- )
- }
- }
- sb.append(rows.joinToString("\n"))
- return sb.toString()
- }
-
- /**
- * One Point feature per location, carrying the trip number it belongs to, so a GIS can colour
- * or filter by trip. The columnar MultiPoint this replaced put every attribute of a whole trip
- * into one feature, which reads back as a single unqueryable row.
- */
- private fun tripsToGeoJson(trips: List<TripExport>): String {
- val features = ArrayList<String>()
- for (trip in trips) {
- for (row in trip.rows) {
- val props = mutableListOf("\"trip\": ${trip.index}", "\"time\": \"${isoTime(rowTs(row))}\"")
- fun put(key: String, value: String) {
- if (value != "null") props.add("\"$key\": $value")
- }
- put("accuracy", jsonNum(row["accuracy"]))
- put("altitude", jsonNum(row["altitude"]))
- put("speed", jsonNum(row["speed"]))
- put("bearing", jsonNum(row["bearing"]))
- put("battery", jsonNum(row["battery"]))
- put("battery_status", jsonValue(batteryStatusLabel(row["battery_status"])))
- put("note", jsonValue(row["note"]))
- features.add(
- " {\n" +
- " \"type\": \"Feature\",\n" +
- " \"geometry\": {\n" +
- " \"type\": \"Point\",\n" +
- " \"coordinates\": [${numOrZero(row["longitude"])}, ${numOrZero(row["latitude"])}]\n" +
- " },\n" +
- " \"properties\": {\n" +
- " ${props.joinToString(", ")}\n" +
- " }\n" +
- " }"
- )
- }
- }
- val featuresBlock = if (features.isEmpty()) "[]" else "[\n${features.joinToString(",\n")}\n ]"
- return "{\n \"type\": \"FeatureCollection\",\n \"features\": $featuresBlock\n}"
- }
-
- private fun tripsToGpx(trips: List<TripExport>): String {
- val sb = StringBuilder()
- sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
- sb.append("<gpx version=\"1.1\" creator=\"Colota\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n")
- sb.append(" <metadata>\n")
- sb.append(" <name>Colota Trip Export</name>\n")
- sb.append(" <time>${isoTime(System.currentTimeMillis() / 1000)}</time>\n")
- sb.append(" </metadata>")
- for (trip in trips) {
- sb.append("\n <trk>\n <name>Trip ${trip.index}</name>\n <trkseg>")
- for (row in trip.rows) {
- val ts = rowTs(row)
- val lat = String.format(Locale.US, "%.6f", asDouble(row["latitude"]))
- val lon = String.format(Locale.US, "%.6f", asDouble(row["longitude"]))
- sb.append("\n <trkpt lat=\"$lat\" lon=\"$lon\">")
- sb.append("\n <ele>${numOrZero(row["altitude"])}</ele>")
- sb.append("\n <time>${isoTime(ts)}</time>")
- sb.append("\n <extensions>")
- sb.append("\n <accuracy>${numOrZero(row["accuracy"])}</accuracy>")
- sb.append("\n <speed>${numOrZero(row["speed"])}</speed>")
- sb.append("\n <bearing>${numOrZero(row["bearing"])}</bearing>")
- sb.append("\n <battery>${numOrZero(row["battery"])}</battery>")
- sb.append("\n <battery_status>${batteryStatusLabel(row["battery_status"]) ?: ""}</battery_status>")
- sb.append("\n <note>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</note>")
- sb.append("\n </extensions>")
- sb.append("\n </trkpt>")
- }
- sb.append("\n </trkseg>\n </trk>")
- }
- sb.append("\n</gpx>")
- return sb.toString()
- }
-
- private fun tripsToKml(trips: List<TripExport>): String {
- val sb = StringBuilder()
- sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
- sb.append("<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n")
- sb.append(" <Document>\n")
- sb.append(" <name>Colota Trip Export</name>\n")
- sb.append(" <description>Exported trips from Colota</description>")
- for (trip in trips) {
- val styleId = "tripStyle${trip.index}"
- val coords = trip.rows.joinToString("\n ") {
- "${numOrZero(it["longitude"])},${numOrZero(it["latitude"])},${numOrZero(it["altitude"])}"
- }
- sb.append("\n <Style id=\"$styleId\">")
- sb.append("\n <LineStyle>")
- sb.append("\n <color>${hexToKmlColor(trip.color)}</color>")
- sb.append("\n <width>4</width>")
- sb.append("\n </LineStyle>")
- sb.append("\n </Style>")
- sb.append("\n <Folder>")
- sb.append("\n <name>Trip ${trip.index}</name>")
- sb.append("\n <Placemark>")
- sb.append("\n <name>Trip ${trip.index} Path</name>")
- sb.append("\n <styleUrl>#$styleId</styleUrl>")
- sb.append("\n <LineString>")
- sb.append("\n <tessellate>1</tessellate>")
- sb.append("\n <coordinates>")
- sb.append("\n $coords")
- sb.append("\n </coordinates>")
- sb.append("\n </LineString>")
- sb.append("\n </Placemark>")
- for (row in trip.rows) {
- val ts = rowTs(row)
- sb.append("\n <Placemark>")
- sb.append("\n <TimeStamp><when>${isoTime(ts)}</when></TimeStamp>")
- sb.append("\n <description>Trip ${trip.index} - Accuracy: ${numOrZero(row["accuracy"])}m, Speed: ${numOrZero(row["speed"])}m/s</description>")
- sb.append("\n <ExtendedData>")
- sb.append("\n <Data name=\"accuracy\"><value>${numOrZero(row["accuracy"])}</value></Data>")
- sb.append("\n <Data name=\"altitude\"><value>${numOrZero(row["altitude"])}</value></Data>")
- sb.append("\n <Data name=\"speed\"><value>${numOrZero(row["speed"])}</value></Data>")
- sb.append("\n <Data name=\"bearing\"><value>${numOrZero(row["bearing"])}</value></Data>")
- sb.append("\n <Data name=\"battery\"><value>${numOrZero(row["battery"])}</value></Data>")
- sb.append("\n <Data name=\"battery_status\"><value>${batteryStatusLabel(row["battery_status"]) ?: ""}</value></Data>")
- sb.append("\n <Data name=\"note\"><value>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</value></Data>")
- sb.append("\n </ExtendedData>")
- sb.append("\n <Point>")
- sb.append("\n <coordinates>${numOrZero(row["longitude"])},${numOrZero(row["latitude"])},${numOrZero(row["altitude"])}</coordinates>")
- sb.append("\n </Point>")
- sb.append("\n </Placemark>")
- }
- sb.append("\n </Folder>")
- }
- sb.append("\n </Document>\n</kml>")
- return sb.toString()
- }
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportFilenames.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFilenames.kt
new file mode 100644
index 00000000..7a1778ae
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFilenames.kt
@@ -0,0 +1,175 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.export
+
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+object ExportFilenames {
+
+ /** Filename-safe stamp for export files (e.g. `2026-05-28_1430`). */
+ fun exportFilenameStamp(): String =
+ SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date())
+
+ const val FILENAME_MARKER = "colota_export"
+ const val DEFAULT_FILENAME_TEMPLATE = "colota_export_{date}_{time}"
+
+ // Together these stay well inside the 255-byte filesystem name limit.
+ private const val MAX_TEMPLATE_LENGTH = 100
+ private const val MAX_DEVICE_LENGTH = 32
+
+ // Braces are escaped on both sides: Android compiles patterns with ICU, which rejects a bare
+ // closing brace that the JDK engine used by unit tests accepts.
+ private val FILENAME_TOKEN = Regex("""\{(date|time)\}""")
+ private val ILLEGAL_FILENAME_CHARS = Regex("""[\\/:*?"<>|\{\}\x00-\x1F\x7F]""")
+ private val FILENAME_WHITESPACE = Regex("""[\s\p{Z}\uFEFF]+""")
+
+ // SAF renames a colliding file to "name (1).ext"; that is still our file.
+ private const val DEDUPE_SUFFIX_PATTERN = """(?: \(\d+\))?"""
+
+ /**
+ * The marker lets cleanup tell Colota's files from the user's; `{date}` and `{time}` keep each
+ * export uniquely named and chronologically sortable.
+ */
+ fun isValidFilenameTemplate(template: String): Boolean =
+ template.length <= MAX_TEMPLATE_LENGTH &&
+ template.contains(FILENAME_MARKER) &&
+ template.contains("{date}") &&
+ template.contains("{time}")
+
+ /** [template] must already have passed [isValidFilenameTemplate]. */
+ fun renderExportFilename(
+ template: String,
+ format: String,
+ deviceName: String,
+ now: Date = Date()
+ ): String {
+ val base = resolveTemplate(template, deviceName)
+ .replace("{date}", SimpleDateFormat("yyyy-MM-dd", Locale.US).format(now))
+ .replace("{time}", SimpleDateFormat("HHmm", Locale.US).format(now))
+ .let { ILLEGAL_FILENAME_CHARS.replace(it, "") }
+ .trim(::isTrimmable)
+
+ return base + ExportConverters.extensionFor(format)
+ }
+
+ /**
+ * Substitutes `{device}` up front so the matcher and the renderer see the same literals. An
+ * empty or dot-ending device name would otherwise shift where the end trim lands.
+ */
+ private fun resolveTemplate(template: String, deviceName: String): String =
+ template.replace("{device}", sanitizeDevicePart(deviceName))
+
+ /** Whitespace goes entirely (`Pixel 7` -> `Pixel7`), not just the illegal characters. */
+ private fun sanitizeDevicePart(deviceName: String): String =
+ ILLEGAL_FILENAME_CHARS.replace(FILENAME_WHITESPACE.replace(deviceName, ""), "").take(MAX_DEVICE_LENGTH)
+
+ private fun isTrimmable(c: Char): Boolean = c == '.' || c.isWhitespace()
+
+ /**
+ * Recognizes files [renderExportFilename] produced from the same template. Anchored, so a
+ * directory, a sync artifact or another device's export does not match. Any known export
+ * extension is accepted so switching format does not orphan older files from retention.
+ */
+ class ExportFileMatcher internal constructor(
+ private val regex: Regex,
+ private val dateGroup: Int,
+ private val timeGroup: Int
+ ) {
+ fun matches(name: String): Boolean = regex.matches(name)
+
+ /** Sortable `yyyy-MM-ddHHmm` stamp, or null when [name] is not ours. */
+ fun stamp(name: String): String? {
+ val match = regex.matchEntire(name) ?: return null
+ return match.groupValues[dateGroup] + match.groupValues[timeGroup]
+ }
+ }
+
+ fun exportFileMatcher(template: String, deviceName: String): ExportFileMatcher {
+ val resolved = resolveTemplate(template, deviceName)
+ val tokens = FILENAME_TOKEN.findAll(resolved).toList()
+
+ val pattern = StringBuilder()
+ var dateGroup = 0
+ var timeGroup = 0
+ var group = 0
+ var cursor = 0
+
+ tokens.forEachIndexed { index, token ->
+ pattern.append(literalPattern(resolved.substring(cursor, token.range.first), index == 0, false))
+ group++
+ if (token.groupValues[1] == "date") {
+ pattern.append("""(\d{4}-\d{2}-\d{2})""")
+ if (dateGroup == 0) dateGroup = group
+ } else {
+ pattern.append("""(\d{4})""")
+ if (timeGroup == 0) timeGroup = group
+ }
+ cursor = token.range.last + 1
+ }
+ pattern.append(literalPattern(resolved.substring(cursor), tokens.isEmpty(), true))
+ pattern.append(DEDUPE_SUFFIX_PATTERN)
+ pattern.append(EXTENSION_PATTERN)
+
+ return ExportFileMatcher(Regex(pattern.toString()), dateGroup, timeGroup)
+ }
+
+ // A SAF provider appends the canonical extension for the MIME it was given when the name does
+ // not already end in one, so files written before the geo+json fix are named ".geojson.json".
+ private const val PROVIDER_SUFFIX_PATTERN = "(?:\\.json|\\.xml|\\.txt)?"
+
+ // lazy so it does not depend on where extensionFor's format objects sit in the init order.
+ private val EXTENSION_PATTERN: String by lazy {
+ listOf("csv", "geojson", "gpx", "kml").joinToString("|", "(?:", ")") { Regex.escape(ExportConverters.extensionFor(it)) } +
+ PROVIDER_SUFFIX_PATTERN
+ }
+
+ /** The rendered name is trimmed at both ends, so the outermost literals are trimmed too. */
+ private fun literalPattern(raw: String, first: Boolean, last: Boolean): String {
+ var literal = ILLEGAL_FILENAME_CHARS.replace(raw, "")
+ if (first) literal = literal.trimStart(::isTrimmable)
+ if (last) literal = literal.trimEnd(::isTrimmable)
+ return if (literal.isEmpty()) "" else Regex.escape(literal)
+ }
+
+ /**
+ * Falls back to the default template so files written before a template change stay managed.
+ * Skipped for `{device}` templates: a default-named file could have come from any device, and
+ * deleting another phone's exports is worse than leaving a few of our own behind.
+ */
+ fun exportFileMatchers(template: String, deviceName: String): List<ExportFileMatcher> =
+ if (template == DEFAULT_FILENAME_TEMPLATE || template.contains("{device}")) {
+ listOf(exportFileMatcher(template, deviceName))
+ } else {
+ listOf(exportFileMatcher(template, deviceName), exportFileMatcher(DEFAULT_FILENAME_TEMPLATE, deviceName))
+ }
+
+ data class ExportEntry(val name: String, val lastModified: Long, val isFile: Boolean)
+
+ /**
+ * Oldest-first selection of the entries beyond [retentionCount]. Ordering prefers the stamp in
+ * the filename; lastModified is only a tiebreak because SAF providers may omit the column
+ * (returning 0) and cloud providers restamp on sync.
+ */
+ fun selectForDeletion(
+ entries: List<ExportEntry>,
+ retentionCount: Int,
+ matchers: List<ExportFileMatcher>
+ ): List<ExportEntry> {
+ if (retentionCount <= 0) return emptyList()
+ val ours = entries.filter { entry -> matchers.any { it.matches(entry.name) } && entry.isFile }
+ val toDelete = ours.size - retentionCount
+ if (toDelete <= 0) return emptyList()
+ return ours
+ .sortedWith(compareBy({ stampOf(it.name, matchers) }, { it.lastModified }, { it.name }))
+ .take(toDelete)
+ }
+
+ /** Sort key for an export filename; empty when no matcher recognizes it. */
+ fun stampOf(name: String, matchers: List<ExportFileMatcher>): String =
+ matchers.firstNotNullOfOrNull { it.stamp(name) } ?: ""
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportFormatting.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFormatting.kt
new file mode 100644
index 00000000..03194154
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFormatting.kt
@@ -0,0 +1,82 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.export
+
+import com.Colota.util.BatteryStatus
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+
+internal fun isoTime(unixSeconds: Long): String {
+ val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
+ sdf.timeZone = TimeZone.getTimeZone("UTC")
+ return sdf.format(Date(unixSeconds * 1000))
+}
+
+internal fun jsonValue(value: Any?): String = when (value) {
+ null -> "null"
+ is String -> "\"${escapeJson(value)}\""
+ is Double, is Float -> jsNum(value)
+ else -> value.toString()
+}
+
+/** Human-readable battery-status label for exports; null if not recorded. */
+internal fun batteryStatusLabel(v: Any?): String? = when (v) {
+ is Long -> BatteryStatus.toDisplayString(v.toInt())
+ is Int -> BatteryStatus.toDisplayString(v)
+ is Double -> BatteryStatus.toDisplayString(v.toInt())
+ else -> null
+}
+
+/** Escape free text for XML element content (GPX/KML notes). */
+internal fun xmlEscape(s: String): String = buildString(s.length) {
+ for (c in s) {
+ when (c) {
+ '&' -> append("&amp;")
+ '<' -> append("&lt;")
+ '>' -> append("&gt;")
+ '"' -> append("&quot;")
+ '\'' -> append("&apos;")
+ else -> append(c)
+ }
+ }
+}
+
+/** RFC-4180 CSV field: quote+double-escape only when the value contains a delimiter. */
+internal fun csvField(value: Any?): String {
+ val s = value?.toString() ?: return ""
+ return if (s.any { it == ',' || it == '"' || it == '\n' || it == '\r' }) {
+ "\"" + s.replace("\"", "\"\"") + "\""
+ } else {
+ s
+ }
+}
+
+private fun escapeJson(s: String): String = buildString(s.length) {
+ for (c in s) {
+ when (c) {
+ '"' -> append("\\\"")
+ '\\' -> append("\\\\")
+ '\n' -> append("\\n")
+ '\r' -> append("\\r")
+ '\t' -> append("\\t")
+ '\b' -> append("\\b")
+ '\u000C' -> append("\\f")
+ else -> if (c < ' ') append("\\u${c.code.toString(16).padStart(4, '0')}") else append(c)
+ }
+ }
+}
+
+/** Match JS number formatting: whole-valued doubles drop the trailing ".0". */
+internal fun jsNum(v: Any): String = when (v) {
+ is Double -> if (v.isFinite() && v == Math.floor(v) && kotlin.math.abs(v) < 1e15) v.toLong().toString() else v.toString()
+ is Float -> jsNum(v.toDouble())
+ else -> v.toString()
+}
+
+/** Numeric field with a `0` default for null (mirrors JS `?? 0` / `|| 0`). */
+internal fun numOrZero(v: Any?): String = if (v == null) "0" else jsNum(v)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/TripConverters.kt b/apps/mobile/android/app/src/main/java/com/colota/export/TripConverters.kt
new file mode 100644
index 00000000..ce45f3a3
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/TripConverters.kt
@@ -0,0 +1,187 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.export
+
+import java.util.Locale
+
+/** color is a #RRGGBB hex supplied by JS (getTripColor), not computed here. */
+data class TripExport(val index: Int, val color: String, val rows: List<Map<String, Any?>>)
+
+/** Trip-segmented export, one track or folder per trip. The golden files in `golden/export/` pin the output. */
+object TripConverters {
+
+ /** GeoJSON property value: `null` stays `null` (JSON), otherwise JS-formatted number. */
+ private fun jsonNum(v: Any?): String = if (v == null) "null" else jsNum(v)
+
+ private fun asDouble(v: Any?): Double = when (v) {
+ is Double -> v
+ is Float -> v.toDouble()
+ is Long -> v.toDouble()
+ is Int -> v.toDouble()
+ else -> 0.0
+ }
+
+ /** Hex RGB (#RRGGBB) -> KML ABGR (ffBBGGRR). */
+ private fun hexToKmlColor(hex: String): String {
+ val h = hex.removePrefix("#")
+ if (h.length < 6) return "ff0000ff"
+ return "ff${h.substring(4, 6)}${h.substring(2, 4)}${h.substring(0, 2)}"
+ }
+
+ private fun rowTs(row: Map<String, Any?>): Long =
+ (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)
+
+ fun convertTrips(format: String, trips: List<TripExport>): String = when (format) {
+ "csv" -> tripsToCsv(trips)
+ "geojson" -> tripsToGeoJson(trips)
+ "gpx" -> tripsToGpx(trips)
+ "kml" -> tripsToKml(trips)
+ else -> throw IllegalArgumentException("Unknown export format: $format")
+ }
+
+ private fun tripsToCsv(trips: List<TripExport>): String {
+ val sb = StringBuilder("trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note\n")
+ val rows = ArrayList<String>()
+ for (trip in trips) {
+ trip.rows.forEachIndexed { i, row ->
+ val ts = rowTs(row)
+ rows.add(
+ listOf(
+ trip.index.toString(), i.toString(), ts.toString(), isoTime(ts),
+ numOrZero(row["latitude"]), numOrZero(row["longitude"]),
+ numOrZero(row["accuracy"]), numOrZero(row["altitude"]),
+ numOrZero(row["speed"]), numOrZero(row["bearing"]), numOrZero(row["battery"]),
+ batteryStatusLabel(row["battery_status"]) ?: "", csvField(row["note"])
+ ).joinToString(",")
+ )
+ }
+ }
+ sb.append(rows.joinToString("\n"))
+ return sb.toString()
+ }
+
+ /** One Point feature per location, carrying its trip number, so a GIS can colour or filter by trip. */
+ private fun tripsToGeoJson(trips: List<TripExport>): String {
+ val features = ArrayList<String>()
+ for (trip in trips) {
+ for (row in trip.rows) {
+ val props = mutableListOf("\"trip\": ${trip.index}", "\"time\": \"${isoTime(rowTs(row))}\"")
+ fun put(key: String, value: String) {
+ if (value != "null") props.add("\"$key\": $value")
+ }
+ put("accuracy", jsonNum(row["accuracy"]))
+ put("altitude", jsonNum(row["altitude"]))
+ put("speed", jsonNum(row["speed"]))
+ put("bearing", jsonNum(row["bearing"]))
+ put("battery", jsonNum(row["battery"]))
+ put("battery_status", jsonValue(batteryStatusLabel(row["battery_status"])))
+ put("note", jsonValue(row["note"]))
+ features.add(
+ " {\n" +
+ " \"type\": \"Feature\",\n" +
+ " \"geometry\": {\n" +
+ " \"type\": \"Point\",\n" +
+ " \"coordinates\": [${numOrZero(row["longitude"])}, ${numOrZero(row["latitude"])}]\n" +
+ " },\n" +
+ " \"properties\": {\n" +
+ " ${props.joinToString(", ")}\n" +
+ " }\n" +
+ " }"
+ )
+ }
+ }
+ val featuresBlock = if (features.isEmpty()) "[]" else "[\n${features.joinToString(",\n")}\n ]"
+ return "{\n \"type\": \"FeatureCollection\",\n \"features\": $featuresBlock\n}"
+ }
+
+ private fun tripsToGpx(trips: List<TripExport>): String {
+ val sb = StringBuilder()
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
+ sb.append("<gpx version=\"1.1\" creator=\"Colota\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n")
+ sb.append(" <metadata>\n")
+ sb.append(" <name>Colota Trip Export</name>\n")
+ sb.append(" <time>${isoTime(System.currentTimeMillis() / 1000)}</time>\n")
+ sb.append(" </metadata>")
+ for (trip in trips) {
+ sb.append("\n <trk>\n <name>Trip ${trip.index}</name>\n <trkseg>")
+ for (row in trip.rows) {
+ val ts = rowTs(row)
+ val lat = String.format(Locale.US, "%.6f", asDouble(row["latitude"]))
+ val lon = String.format(Locale.US, "%.6f", asDouble(row["longitude"]))
+ sb.append("\n <trkpt lat=\"$lat\" lon=\"$lon\">")
+ sb.append("\n <ele>${numOrZero(row["altitude"])}</ele>")
+ sb.append("\n <time>${isoTime(ts)}</time>")
+ sb.append("\n <extensions>")
+ sb.append("\n <accuracy>${numOrZero(row["accuracy"])}</accuracy>")
+ sb.append("\n <speed>${numOrZero(row["speed"])}</speed>")
+ sb.append("\n <bearing>${numOrZero(row["bearing"])}</bearing>")
+ sb.append("\n <battery>${numOrZero(row["battery"])}</battery>")
+ sb.append("\n <battery_status>${batteryStatusLabel(row["battery_status"]) ?: ""}</battery_status>")
+ sb.append("\n <note>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</note>")
+ sb.append("\n </extensions>")
+ sb.append("\n </trkpt>")
+ }
+ sb.append("\n </trkseg>\n </trk>")
+ }
+ sb.append("\n</gpx>")
+ return sb.toString()
+ }
+
+ private fun tripsToKml(trips: List<TripExport>): String {
+ val sb = StringBuilder()
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
+ sb.append("<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n")
+ sb.append(" <Document>\n")
+ sb.append(" <name>Colota Trip Export</name>\n")
+ sb.append(" <description>Exported trips from Colota</description>")
+ for (trip in trips) {
+ val styleId = "tripStyle${trip.index}"
+ val coords = trip.rows.joinToString("\n ") {
+ "${numOrZero(it["longitude"])},${numOrZero(it["latitude"])},${numOrZero(it["altitude"])}"
+ }
+ sb.append("\n <Style id=\"$styleId\">")
+ sb.append("\n <LineStyle>")
+ sb.append("\n <color>${hexToKmlColor(trip.color)}</color>")
+ sb.append("\n <width>4</width>")
+ sb.append("\n </LineStyle>")
+ sb.append("\n </Style>")
+ sb.append("\n <Folder>")
+ sb.append("\n <name>Trip ${trip.index}</name>")
+ sb.append("\n <Placemark>")
+ sb.append("\n <name>Trip ${trip.index} Path</name>")
+ sb.append("\n <styleUrl>#$styleId</styleUrl>")
+ sb.append("\n <LineString>")
+ sb.append("\n <tessellate>1</tessellate>")
+ sb.append("\n <coordinates>")
+ sb.append("\n $coords")
+ sb.append("\n </coordinates>")
+ sb.append("\n </LineString>")
+ sb.append("\n </Placemark>")
+ for (row in trip.rows) {
+ val ts = rowTs(row)
+ sb.append("\n <Placemark>")
+ sb.append("\n <TimeStamp><when>${isoTime(ts)}</when></TimeStamp>")
+ sb.append("\n <description>Trip ${trip.index} - Accuracy: ${numOrZero(row["accuracy"])}m, Speed: ${numOrZero(row["speed"])}m/s</description>")
+ sb.append("\n <ExtendedData>")
+ sb.append("\n <Data name=\"accuracy\"><value>${numOrZero(row["accuracy"])}</value></Data>")
+ sb.append("\n <Data name=\"altitude\"><value>${numOrZero(row["altitude"])}</value></Data>")
+ sb.append("\n <Data name=\"speed\"><value>${numOrZero(row["speed"])}</value></Data>")
+ sb.append("\n <Data name=\"bearing\"><value>${numOrZero(row["bearing"])}</value></Data>")
+ sb.append("\n <Data name=\"battery\"><value>${numOrZero(row["battery"])}</value></Data>")
+ sb.append("\n <Data name=\"battery_status\"><value>${batteryStatusLabel(row["battery_status"]) ?: ""}</value></Data>")
+ sb.append("\n <Data name=\"note\"><value>${(row["note"] as? String)?.let { xmlEscape(it) } ?: ""}</value></Data>")
+ sb.append("\n </ExtendedData>")
+ sb.append("\n <Point>")
+ sb.append("\n <coordinates>${numOrZero(row["longitude"])},${numOrZero(row["latitude"])},${numOrZero(row["altitude"])}</coordinates>")
+ sb.append("\n </Point>")
+ sb.append("\n </Placemark>")
+ }
+ sb.append("\n </Folder>")
+ }
+ sb.append("\n </Document>\n</kml>")
+ return sb.toString()
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/network/NetworkMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/network/NetworkMonitor.kt
index 194f558a..b1d2d855 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/network/NetworkMonitor.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/network/NetworkMonitor.kt
@@ -10,14 +10,9 @@ import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
-import android.net.wifi.WifiInfo
-import android.net.wifi.WifiManager
import android.os.Build
-import android.os.Handler
-import android.os.Looper
import com.Colota.util.AppLogger
import com.Colota.util.TimedCache
-import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
@@ -28,9 +23,6 @@ class NetworkMonitor(context: Context) {
companion object {
private const val TAG = "NetworkMonitor"
private const val NETWORK_CHECK_CACHE_MS = 5000L
- private const val SSID_PROBE_TIMEOUT_MS = 3000L
- /** What Android returns instead of the SSID without location permission or with Location off. */
- private const val UNKNOWN_SSID = "<unknown ssid>"
}
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@@ -48,7 +40,7 @@ class NetworkMonitor(context: Context) {
private var notifiedSsid = ""
/** Connected Wi-Fi networks, counted so losing one of several does not clear the state. */
private val availableWifiNetworks = AtomicInteger(0)
- private val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager
+ private val wifiNames = WifiNameReader(context, connectivityManager)
private var networkCallback = createNetworkCallback(withSsid = false)
@@ -124,51 +116,12 @@ class NetworkMonitor(context: Context) {
return
}
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
- // Below S the SSID comes from WifiManager, not the callback, so waiting on one would
- // only stall. WifiManager reports the connected network regardless of the VPN.
- onResult(readSsid(null))
- return
- }
-
- val request = wifiRequest
- if (request == null) {
- onResult("")
- return
- }
-
- val done = AtomicBoolean(false)
- var probe: ConnectivityManager.NetworkCallback? = null
- fun finish(ssid: String) {
- if (!done.compareAndSet(false, true)) return
- probe?.let {
- try {
- connectivityManager.unregisterNetworkCallback(it)
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to unregister SSID probe", e)
- }
- }
- onResult(ssid)
- }
-
- probe = object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {
- override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = finish(readSsid(caps))
- }
-
- try {
- connectivityManager.registerNetworkCallback(request, probe)
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to register SSID probe", e)
- probe = null
- finish("")
- return
- }
- Handler(Looper.getMainLooper()).postDelayed({ finish("") }, SSID_PROBE_TIMEOUT_MS)
+ wifiNames.probe(wifiRequest, onResult)
}
private fun createNetworkCallback(withSsid: Boolean): ConnectivityManager.NetworkCallback {
fun update(caps: NetworkCapabilities) {
- if (withSsid) currentSsid = readSsid(caps)
+ if (withSsid) currentSsid = wifiNames.read(caps)
isVpn = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
notifyWifiStateIfChanged()
}
@@ -191,19 +144,6 @@ class NetworkMonitor(context: Context) {
}
}
- private fun readSsid(caps: NetworkCapabilities?): String {
- val raw = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- (caps?.transportInfo as? WifiInfo)?.ssid
- } else {
- @Suppress("DEPRECATION")
- wifiManager?.connectionInfo?.ssid
- }
- val ssid = raw?.removeSurrounding("\"") ?: ""
- // Android reports the placeholder without location permission or with Location off; treat
- // it as no name so the condition simply does not match (and the picker cannot offer it).
- return if (ssid == UNKNOWN_SSID) "" else ssid
- }
-
private fun refreshWifiTransport(force: Boolean) {
isWifi = availableWifiNetworks.get() > 0
notifyWifiStateIfChanged(force)
diff --git a/apps/mobile/android/app/src/main/java/com/colota/network/WifiNameReader.kt b/apps/mobile/android/app/src/main/java/com/colota/network/WifiNameReader.kt
new file mode 100644
index 00000000..077b0a1e
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/network/WifiNameReader.kt
@@ -0,0 +1,88 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.network
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.Network
+import android.net.NetworkCapabilities
+import android.net.NetworkRequest
+import android.net.wifi.WifiInfo
+import android.net.wifi.WifiManager
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import com.Colota.util.AppLogger
+import java.util.concurrent.atomic.AtomicBoolean
+
+/** Reads the connected Wi-Fi network's name, from the capabilities on S+ and from WifiManager below. */
+class WifiNameReader(context: Context, private val connectivityManager: ConnectivityManager) {
+
+ companion object {
+ private const val TAG = "NetworkMonitor"
+ private const val SSID_PROBE_TIMEOUT_MS = 3000L
+ /** What Android returns instead of the SSID without location permission or with Location off. */
+ private const val UNKNOWN_SSID = "<unknown ssid>"
+ }
+
+ private val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager
+
+ fun read(caps: NetworkCapabilities?): String {
+ val raw = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ (caps?.transportInfo as? WifiInfo)?.ssid
+ } else {
+ @Suppress("DEPRECATION")
+ wifiManager?.connectionInfo?.ssid
+ }
+ val ssid = raw?.removeSurrounding("\"") ?: ""
+ // Android reports the placeholder without location permission or with Location off; treat
+ // it as no name so the condition simply does not match (and the picker cannot offer it).
+ return if (ssid == UNKNOWN_SSID) "" else ssid
+ }
+
+ /** Registers a location-flagged callback on [request] for one answer, blank after a timeout. */
+ fun probe(request: NetworkRequest?, onResult: (String) -> Unit) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
+ // Below S the SSID comes from WifiManager, not the callback, so waiting on one would
+ // only stall. WifiManager reports the connected network regardless of the VPN.
+ onResult(read(null))
+ return
+ }
+
+ if (request == null) {
+ onResult("")
+ return
+ }
+
+ val done = AtomicBoolean(false)
+ var probe: ConnectivityManager.NetworkCallback? = null
+ fun finish(ssid: String) {
+ if (!done.compareAndSet(false, true)) return
+ probe?.let {
+ try {
+ connectivityManager.unregisterNetworkCallback(it)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to unregister SSID probe", e)
+ }
+ }
+ onResult(ssid)
+ }
+
+ probe = object : ConnectivityManager.NetworkCallback(FLAG_INCLUDE_LOCATION_INFO) {
+ override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) = finish(read(caps))
+ }
+
+ try {
+ connectivityManager.registerNetworkCallback(request, probe)
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to register SSID probe", e)
+ probe = null
+ finish("")
+ return
+ }
+ Handler(Looper.getMainLooper()).postDelayed({ finish("") }, SSID_PROBE_TIMEOUT_MS)
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/PointSender.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/PointSender.kt
new file mode 100644
index 00000000..44fb4c79
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/PointSender.kt
@@ -0,0 +1,91 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.sync
+
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.QueuedLocation
+import com.Colota.sync.http.BatchResult
+import com.Colota.sync.http.NetworkManager
+import com.Colota.util.AppLogger
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import org.json.JSONException
+import org.json.JSONObject
+
+/** Posts each queue row as its own request, a chunk of them in parallel. */
+class PointSender(
+ private val dbHelper: DatabaseHelper,
+ private val networkManager: NetworkManager,
+ private val onRateLimited: (retryAfterSeconds: Long?) -> Unit
+) {
+ companion object {
+ private const val TAG = "SyncManager"
+ }
+
+ /** [stopReason] is set when the pass should end after this chunk. */
+ data class ChunkResult(val sent: Int, val failed: Int, val stopReason: String?)
+
+ /** A row that fails without a bump joins [keptInPlace], so the rest of the pass does not post it again. */
+ suspend fun sendChunk(
+ chunk: List<QueuedLocation>,
+ endpoint: String,
+ authHeaders: Map<String, String>,
+ httpMethod: String,
+ apiFormat: ApiFormat,
+ keptInPlace: MutableSet<Long>,
+ ): ChunkResult = coroutineScope {
+ val successfulIds = mutableListOf<Long>()
+ var failed = 0
+
+ val results = chunk.map { item ->
+ async {
+ val result = try {
+ networkManager.sendToEndpoint(
+ JSONObject(item.payload),
+ endpoint,
+ authHeaders,
+ httpMethod,
+ apiFormat
+ )
+ } catch (e: JSONException) {
+ AppLogger.e(TAG, "Corrupt queue row ${item.queueId}", e)
+ null
+ } catch (e: Exception) {
+ AppLogger.e(TAG, "Failed to send item ${item.queueId}", e)
+ BatchResult.NetworkError
+ }
+ item.queueId to result
+ }
+ }.awaitAll()
+
+ results.forEach { (queueId, result) ->
+ if (result == BatchResult.Success) {
+ successfulIds.add(queueId)
+ } else {
+ val reason = if (result == null) "Corrupt payload" else retryReason(result)
+ if (reason != null) {
+ dbHelper.incrementRetryCount(queueId, reason)
+ } else {
+ keptInPlace.add(queueId)
+ }
+ failed++
+ }
+ }
+
+ if (successfulIds.isNotEmpty()) {
+ val sentLocationIds = chunk.filter { it.queueId in successfulIds }.map { it.locationId }
+ dbHelper.markLocationsSent(sentLocationIds)
+ dbHelper.removeBatchFromQueue(successfulIds)
+ }
+
+ val limited = results.mapNotNull { it.second as? BatchResult.RateLimited }
+ if (limited.isNotEmpty()) {
+ onRateLimited(limited.maxOf { it.retryAfterSeconds ?: SyncState.DEFAULT_RATE_LIMIT_WAIT_SECONDS })
+ }
+ ChunkResult(successfulIds.size, failed, stopReason(results.map { it.second }, anySent = successfulIds.isNotEmpty()))
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
index c5b050e2..04a9f23a 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt
@@ -13,7 +13,6 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import org.json.JSONException
import org.json.JSONObject
import java.util.concurrent.ConcurrentHashMap
import com.Colota.sync.http.NetworkManager
@@ -37,6 +36,8 @@ class SyncManager(
}
private val batchSender = OverlandBatchSender(dbHelper, networkManager, ::noteRateLimit)
+ private val pointSender = PointSender(dbHelper, networkManager, ::noteRateLimit)
+ private val schedule = SyncSchedule(clock)
@Volatile private var endpoint: String = ""
@Volatile private var syncIntervalSeconds: Int = 0
@@ -50,7 +51,6 @@ class SyncManager(
@Volatile private var overlandBatchSize: Int = 50
private var syncJob: Job? = null
- @Volatile private var lastSyncTime: Long = 0
@Volatile var lastSuccessfulSyncTime: Long = 0
private set
@@ -59,7 +59,6 @@ class SyncManager(
lastSuccessfulSyncTime = now
SyncState.recordSuccess(now)
}
- @Volatile private var syncInitialized = false
@Volatile private var consecutiveFailures = 0
private val queueCountCache = TimedCache(5000L) { dbHelper.getQueuedCount() }
@@ -284,12 +283,7 @@ class SyncManager(
}
private suspend fun applyBackoffDelay() {
- val backoffSeconds = when (consecutiveFailures) {
- 1 -> 30L
- 2 -> 60L
- 3 -> 300L
- else -> 900L
- }
+ val backoffSeconds = SyncSchedule.backoffSeconds(consecutiveFailures)
AppLogger.w(TAG, "Backoff: ${backoffSeconds}s")
@@ -350,58 +344,15 @@ class SyncManager(
} else {
var stopped: String? = null
for (chunk in queued.chunked(10)) {
- val successfulIds = mutableListOf<Long>()
-
- val results = chunk.map { item ->
- async {
- val result = try {
- networkManager.sendToEndpoint(
- JSONObject(item.payload),
- currentEndpoint,
- currentAuthHeaders,
- currentHttpMethod,
- currentApiFormat
- )
- } catch (e: JSONException) {
- AppLogger.e(TAG, "Corrupt queue row ${item.queueId}", e)
- null
- } catch (e: Exception) {
- AppLogger.e(TAG, "Failed to send item ${item.queueId}", e)
- BatchResult.NetworkError
- }
- item.queueId to result
- }
- }.awaitAll()
-
- results.forEach { (queueId, result) ->
- if (result == BatchResult.Success) {
- successfulIds.add(queueId)
- } else {
- val reason = if (result == null) "Corrupt payload" else retryReason(result)
- if (reason != null) {
- dbHelper.incrementRetryCount(queueId, reason)
- } else {
- keptInPlace.add(queueId)
- }
- totalFailed++
- }
- }
-
- if (successfulIds.isNotEmpty()) {
- val sentLocationIds = chunk.filter { it.queueId in successfulIds }.map { it.locationId }
- dbHelper.markLocationsSent(sentLocationIds)
- dbHelper.removeBatchFromQueue(successfulIds)
-
- totalProcessed += successfulIds.size
- totalSucceeded += successfulIds.size
- }
+ val result = pointSender.sendChunk(
+ chunk, currentEndpoint, currentAuthHeaders, currentHttpMethod, currentApiFormat, keptInPlace
+ )
+ totalProcessed += result.sent
+ totalSucceeded += result.sent
+ totalFailed += result.failed
reportProgress()
- val limited = results.mapNotNull { it.second as? BatchResult.RateLimited }
- if (limited.isNotEmpty()) {
- noteRateLimit(limited.maxOf { it.retryAfterSeconds ?: SyncState.DEFAULT_RATE_LIMIT_WAIT_SECONDS })
- }
- stopped = stopReason(results.map { it.second }, anySent = successfulIds.isNotEmpty())
+ stopped = result.stopReason
if (stopped != null) break
yield()
}
@@ -441,23 +392,6 @@ class SyncManager(
}
}
- val now = clock()
- if (!syncInitialized) {
- lastSyncTime = now
- syncInitialized = true
- return syncIntervalSeconds.toLong()
- }
-
- val elapsedSeconds = (now - lastSyncTime) / 1000
- val remaining = syncIntervalSeconds - elapsedSeconds
-
- return when {
- remaining > 0 -> remaining
- resumingWait -> 0L
- else -> {
- lastSyncTime = now
- syncIntervalSeconds.toLong()
- }
- }
+ return schedule.nextPeriodicDelaySeconds(syncIntervalSeconds, resumingWait)
}
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncSchedule.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncSchedule.kt
new file mode 100644
index 00000000..f8751ef8
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncSchedule.kt
@@ -0,0 +1,43 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.sync
+
+/** When the periodic sync loop next ticks, and how long it waits after failed passes. */
+class SyncSchedule(private val clock: () -> Long) {
+ companion object {
+ fun backoffSeconds(consecutiveFailures: Int): Long = when (consecutiveFailures) {
+ 1 -> 30L
+ 2 -> 60L
+ 3 -> 300L
+ else -> 900L
+ }
+ }
+
+ @Volatile private var lastSyncTime: Long = 0
+ @Volatile private var syncInitialized = false
+
+ /** Measured from when the running wait began, so a changed interval applies to it. */
+ fun nextPeriodicDelaySeconds(syncIntervalSeconds: Int, resumingWait: Boolean): Long {
+ val now = clock()
+ if (!syncInitialized) {
+ lastSyncTime = now
+ syncInitialized = true
+ return syncIntervalSeconds.toLong()
+ }
+
+ val elapsedSeconds = (now - lastSyncTime) / 1000
+ val remaining = syncIntervalSeconds - elapsedSeconds
+
+ return when {
+ remaining > 0 -> remaining
+ resumingWait -> 0L
+ else -> {
+ lastSyncTime = now
+ syncIntervalSeconds.toLong()
+ }
+ }
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
index 1fe20934..84020f05 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt
@@ -205,7 +205,7 @@ class AutoExportConfigTest {
@Test
fun `from defaults the filename template when unset`() {
val db = dbWith(null)
- assertEquals(ExportConverters.DEFAULT_FILENAME_TEMPLATE, AutoExportConfig.from(db).filenameTemplate)
+ assertEquals(ExportFilenames.DEFAULT_FILENAME_TEMPLATE, AutoExportConfig.from(db).filenameTemplate)
verify(exactly = 0) { db.saveSetting("autoExportFilenameTemplate", any()) }
}
@@ -219,9 +219,9 @@ class AutoExportConfigTest {
fun `from repairs a template that reached the DB without the marker`() {
// Restore or version skew can write one the settings screen would have rejected.
val db = dbWith("backup_{date}_{time}")
- assertEquals(ExportConverters.DEFAULT_FILENAME_TEMPLATE, AutoExportConfig.from(db).filenameTemplate)
+ assertEquals(ExportFilenames.DEFAULT_FILENAME_TEMPLATE, AutoExportConfig.from(db).filenameTemplate)
verify {
- db.saveSetting("autoExportFilenameTemplate", ExportConverters.DEFAULT_FILENAME_TEMPLATE)
+ db.saveSetting("autoExportFilenameTemplate", ExportFilenames.DEFAULT_FILENAME_TEMPLATE)
}
}
@@ -229,7 +229,7 @@ class AutoExportConfigTest {
fun `from repairs a template missing the time tokens`() {
// Without both tokens two exports in a day collide and retention cannot order them.
assertEquals(
- ExportConverters.DEFAULT_FILENAME_TEMPLATE,
+ ExportFilenames.DEFAULT_FILENAME_TEMPLATE,
AutoExportConfig.from(dbWith("colota_export_{date}")).filenameTemplate
)
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt
index 102a6606..aed37f19 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt
@@ -162,7 +162,7 @@ class ExportConvertersTest {
@Test
fun `convertTrips GeoJSON conforms to RFC 7946`() {
- assertRfc7946(ExportConverters.convertTrips("geojson", tripFixture), 4)
+ assertRfc7946(TripConverters.convertTrips("geojson", tripFixture), 4)
}
@Test
@@ -525,11 +525,11 @@ class ExportConvertersTest {
/** Mirrors the original JS golden-capture fixture, plus battery_status. */
private val tripFixture = listOf(
- ExportConverters.TripExport(1, "#3B82F6", listOf(
+ TripExport(1, "#3B82F6", listOf(
mapOf("latitude" to 48.137154, "longitude" to 11.576124, "timestamp" to 1700000000L, "accuracy" to 8.5, "altitude" to 520.2, "speed" to 1.4, "bearing" to 270.5, "battery" to 91L, "battery_status" to 2L),
mapOf("latitude" to 48.138001, "longitude" to 11.577003, "timestamp" to 1700000060L, "accuracy" to 12.0, "altitude" to 525.0, "speed" to 2.0, "bearing" to 275.0, "battery" to 90L, "battery_status" to 3L)
)),
- ExportConverters.TripExport(2, "#10B981", listOf(
+ TripExport(2, "#10B981", listOf(
mapOf("latitude" to 48.14, "longitude" to 11.58, "timestamp" to 1700001000L, "accuracy" to 5.0, "altitude" to 530.0, "speed" to 3.0, "bearing" to 10.0, "battery" to 88L, "battery_status" to 1L),
mapOf("latitude" to 48.1405, "longitude" to 11.5811, "timestamp" to 1700001060L, "accuracy" to 6.2, "altitude" to 0.0, "speed" to 0.0, "bearing" to 0.0, "battery" to 87L, "battery_status" to 0L)
))
@@ -544,42 +544,42 @@ class ExportConvertersTest {
@Test
fun `convertTrips csv matches JS golden`() {
- assertEquals(norm(golden("trip.csv")), norm(ExportConverters.convertTrips("csv", tripFixture)))
+ assertEquals(norm(golden("trip.csv")), norm(TripConverters.convertTrips("csv", tripFixture)))
}
@Test
fun `convertTrips geojson matches JS golden`() {
- assertEquals(norm(golden("trip.geojson")), norm(ExportConverters.convertTrips("geojson", tripFixture)))
+ assertEquals(norm(golden("trip.geojson")), norm(TripConverters.convertTrips("geojson", tripFixture)))
}
@Test
fun `convertTrips gpx matches JS golden`() {
- assertEquals(norm(golden("trip.gpx")), norm(ExportConverters.convertTrips("gpx", tripFixture)))
+ assertEquals(norm(golden("trip.gpx")), norm(TripConverters.convertTrips("gpx", tripFixture)))
}
@Test
fun `convertTrips kml matches JS golden`() {
- assertEquals(norm(golden("trip.kml")), norm(ExportConverters.convertTrips("kml", tripFixture)))
+ assertEquals(norm(golden("trip.kml")), norm(TripConverters.convertTrips("kml", tripFixture)))
}
@Test
fun `convertTrips writes the note in every format and escapes per format`() {
// Trip serializers are separate from the flat writers and the golden fixture is note-free,
// so cover note placement and per-format escaping here.
- val trips = listOf(ExportConverters.TripExport(1, "#3B82F6", listOf(
+ val trips = listOf(TripExport(1, "#3B82F6", listOf(
mapOf("latitude" to 52.52, "longitude" to 13.405, "timestamp" to 1700000000L, "note" to "deer, \"big\" <antlers>"),
mapOf("latitude" to 48.8566, "longitude" to 2.3522, "timestamp" to 1700003600L)
)))
- val csv = ExportConverters.convertTrips("csv", trips)
+ val csv = TripConverters.convertTrips("csv", trips)
assertTrue(csv.contains("\"deer, \"\"big\"\" <antlers>\""))
- val gj = ExportConverters.convertTrips("geojson", trips)
+ val gj = TripConverters.convertTrips("geojson", trips)
assertTrue(gj.contains("\\\"big\\\""))
assertEquals(1, Regex("\"note\":").findAll(gj).count())
- val gpx = ExportConverters.convertTrips("gpx", trips)
+ val gpx = TripConverters.convertTrips("gpx", trips)
assertTrue(gpx.contains("<note>deer, &quot;big&quot; &lt;antlers&gt;</note>"))
assertTrue(gpx.contains("<note></note>"))
assertEquals(2, Regex("<note>").findAll(gpx).count())
- val kml = ExportConverters.convertTrips("kml", trips)
+ val kml = TripConverters.convertTrips("kml", trips)
assertTrue(kml.contains("&lt;antlers&gt;"))
assertEquals(2, Regex("<Data name=\"note\">").findAll(kml).count())
}
@@ -590,23 +590,23 @@ class ExportConvertersTest {
fun `convertTrips with no trips produces valid empty output`() {
assertEquals(
"trip,id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,bearing,battery,battery_status,note",
- ExportConverters.convertTrips("csv", emptyList()).trim()
+ TripConverters.convertTrips("csv", emptyList()).trim()
)
- assertTrue(ExportConverters.convertTrips("geojson", emptyList()).contains("\"features\": []"))
- val gpx = ExportConverters.convertTrips("gpx", emptyList())
+ assertTrue(TripConverters.convertTrips("geojson", emptyList()).contains("\"features\": []"))
+ val gpx = TripConverters.convertTrips("gpx", emptyList())
assertTrue(gpx.startsWith("<?xml") && gpx.trimEnd().endsWith("</gpx>"))
- assertTrue(ExportConverters.convertTrips("kml", emptyList()).trimEnd().endsWith("</kml>"))
+ assertTrue(TripConverters.convertTrips("kml", emptyList()).trimEnd().endsWith("</kml>"))
}
@Test
fun `convertTrips with an empty trip emits no points and stays well-formed`() {
- val trips = listOf(ExportConverters.TripExport(1, "#3B82F6", emptyList()))
- assertEquals(1, ExportConverters.convertTrips("csv", trips).lines().filter { it.isNotBlank() }.size)
- assertTrue(ExportConverters.convertTrips("geojson", trips).contains("\"features\": []"))
+ val trips = listOf(TripExport(1, "#3B82F6", emptyList()))
+ assertEquals(1, TripConverters.convertTrips("csv", trips).lines().filter { it.isNotBlank() }.size)
+ assertTrue(TripConverters.convertTrips("geojson", trips).contains("\"features\": []"))
// GPX/KML still open the trip's track/folder with no points inside; just verify it stays well-formed
- val gpx = ExportConverters.convertTrips("gpx", trips)
+ val gpx = TripConverters.convertTrips("gpx", trips)
assertTrue(gpx.contains("<name>Trip 1</name>") && gpx.trimEnd().endsWith("</gpx>"))
- val kml = ExportConverters.convertTrips("kml", trips)
+ val kml = TripConverters.convertTrips("kml", trips)
assertTrue(kml.contains("<name>Trip 1</name>") && kml.trimEnd().endsWith("</kml>"))
}
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFilenameTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFilenameTest.kt
index b7ad6b23..606684a3 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFilenameTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFilenameTest.kt
@@ -1,6 +1,6 @@
package com.Colota.export
-import com.Colota.export.ExportConverters.ExportEntry
+import com.Colota.export.ExportFilenames.ExportEntry
import org.junit.Assert.*
import org.junit.Test
import java.util.Calendar
@@ -20,7 +20,7 @@ class ExportFilenameTest {
private val may20 = dateAt(2026, 5, 20, 8, 15)
private fun render(template: String, format: String = "geojson", device: String = "Pixel 7") =
- ExportConverters.renderExportFilename(template, format, device, may20)
+ ExportFilenames.renderExportFilename(template, format, device, may20)
// --- renderExportFilename ---
@@ -29,7 +29,7 @@ class ExportFilenameTest {
// Existing installs must keep byte-identical names, otherwise this is a silent migration.
assertEquals(
"colota_export_2026-05-20_0815.geojson",
- render(ExportConverters.DEFAULT_FILENAME_TEMPLATE)
+ render(ExportFilenames.DEFAULT_FILENAME_TEMPLATE)
)
}
@@ -85,32 +85,32 @@ class ExportFilenameTest {
@Test
fun `template validation requires the marker and both time tokens`() {
- assertTrue(ExportConverters.isValidFilenameTemplate(ExportConverters.DEFAULT_FILENAME_TEMPLATE))
- assertTrue(ExportConverters.isValidFilenameTemplate("{device}_colota_export-{date}_{time}"))
- assertFalse(ExportConverters.isValidFilenameTemplate("backup_{date}_{time}"))
- assertFalse(ExportConverters.isValidFilenameTemplate("colota_export_{time}"))
- assertFalse(ExportConverters.isValidFilenameTemplate("colota_export_{date}"))
+ assertTrue(ExportFilenames.isValidFilenameTemplate(ExportFilenames.DEFAULT_FILENAME_TEMPLATE))
+ assertTrue(ExportFilenames.isValidFilenameTemplate("{device}_colota_export-{date}_{time}"))
+ assertFalse(ExportFilenames.isValidFilenameTemplate("backup_{date}_{time}"))
+ assertFalse(ExportFilenames.isValidFilenameTemplate("colota_export_{time}"))
+ assertFalse(ExportFilenames.isValidFilenameTemplate("colota_export_{date}"))
// Case-sensitive: the marker is what cleanup keys off.
- assertFalse(ExportConverters.isValidFilenameTemplate("Colota_Export_{date}_{time}"))
+ assertFalse(ExportFilenames.isValidFilenameTemplate("Colota_Export_{date}_{time}"))
}
@Test
fun `template validation rejects a template that would overrun the filename limit`() {
// Rejected rather than truncated, because a truncated name would no longer match its own
// template and retention would never see it again.
- assertFalse(ExportConverters.isValidFilenameTemplate("x".repeat(120) + "colota_export_{date}_{time}"))
+ assertFalse(ExportFilenames.isValidFilenameTemplate("x".repeat(120) + "colota_export_{date}_{time}"))
}
// --- exportFileMatcher ---
- private val defaultMatcher = ExportConverters.exportFileMatcher(
- ExportConverters.DEFAULT_FILENAME_TEMPLATE,
+ private val defaultMatcher = ExportFilenames.exportFileMatcher(
+ ExportFilenames.DEFAULT_FILENAME_TEMPLATE,
"Pixel 7"
)
/** Every template a user can save, paired with device names that stress the boundaries. */
private val roundTripTemplates = listOf(
- ExportConverters.DEFAULT_FILENAME_TEMPLATE,
+ ExportFilenames.DEFAULT_FILENAME_TEMPLATE,
"{device}_colota_export-{date}_{time}",
"colota_export_{date}_{time}_{device}",
"colota_export_{device}_{date}_{time}",
@@ -128,8 +128,8 @@ class ExportFilenameTest {
for (template in roundTripTemplates) {
for (device in listOf("Pixel 7", "", "Moto G.", "X".repeat(80))) {
for (format in listOf("csv", "geojson", "gpx", "kml")) {
- val name = ExportConverters.renderExportFilename(template, format, device, may20)
- val matcher = ExportConverters.exportFileMatcher(template, device)
+ val name = ExportFilenames.renderExportFilename(template, format, device, may20)
+ val matcher = ExportFilenames.exportFileMatcher(template, device)
assertTrue(
"template='$template' device='$device' rendered '$name' but the matcher rejected it",
matcher.matches(name)
@@ -180,14 +180,14 @@ class ExportFilenameTest {
@Test
fun `device token scopes the matcher to this device`() {
- val matcher = ExportConverters.exportFileMatcher("{device}_colota_export-{date}_{time}", "Pixel 7")
+ val matcher = ExportFilenames.exportFileMatcher("{device}_colota_export-{date}_{time}", "Pixel 7")
assertTrue(matcher.matches("Pixel7_colota_export-2026-05-20_0815.gpx"))
assertFalse(matcher.matches("S23_colota_export-2026-05-20_0815.gpx"))
}
@Test
fun `a repeated date token reads the stamp from the first occurrence`() {
- val matcher = ExportConverters.exportFileMatcher("colota_export_{date}_{time}_{date}", "Pixel 7")
+ val matcher = ExportFilenames.exportFileMatcher("colota_export_{date}_{time}_{date}", "Pixel 7")
assertEquals(
"2026-05-200815",
matcher.stamp("colota_export_2026-05-20_0815_1999-01-01.geojson")
@@ -197,17 +197,17 @@ class ExportFilenameTest {
@Test
fun `stamp is chronologically sortable`() {
assertTrue(
- ExportConverters.stampOf("colota_export_2026-05-19_2359.gpx", listOf(defaultMatcher)) <
- ExportConverters.stampOf("colota_export_2026-05-20_0000.gpx", listOf(defaultMatcher))
+ ExportFilenames.stampOf("colota_export_2026-05-19_2359.gpx", listOf(defaultMatcher)) <
+ ExportFilenames.stampOf("colota_export_2026-05-20_0000.gpx", listOf(defaultMatcher))
)
- assertEquals("", ExportConverters.stampOf("unrelated.txt", listOf(defaultMatcher)))
+ assertEquals("", ExportFilenames.stampOf("unrelated.txt", listOf(defaultMatcher)))
}
// --- exportFileMatchers: which files a template claims ---
@Test
fun `a custom template still claims legacy default-named files`() {
- val matchers = ExportConverters.exportFileMatchers("backup_colota_export-{date}_{time}", "Pixel 7")
+ val matchers = ExportFilenames.exportFileMatchers("backup_colota_export-{date}_{time}", "Pixel 7")
assertTrue(matchers.any { it.matches("backup_colota_export-2026-05-20_0815.gpx") })
assertTrue(matchers.any { it.matches("colota_export_2026-01-01_0000.geojson") })
}
@@ -216,7 +216,7 @@ class ExportFilenameTest {
fun `a device template does not claim legacy default-named files`() {
// A plain colota_export_* file could have been written by any phone sharing the folder.
// Leaving a few of our own behind beats deleting someone else's.
- val matchers = ExportConverters.exportFileMatchers("{device}_colota_export-{date}_{time}", "Pixel 7")
+ val matchers = ExportFilenames.exportFileMatchers("{device}_colota_export-{date}_{time}", "Pixel 7")
assertTrue(matchers.any { it.matches("Pixel7_colota_export-2026-05-20_0815.gpx") })
assertFalse(matchers.any { it.matches("colota_export_2026-01-01_0000.geojson") })
}
@@ -231,20 +231,20 @@ class ExportFilenameTest {
@Test
fun `retention of zero keeps everything`() {
val entries = (1..5).map { entry("colota_export_2026-05-0${it}_0800.gpx", it * 1000L) }
- assertTrue(ExportConverters.selectForDeletion(entries, 0, defaultMatchers).isEmpty())
+ assertTrue(ExportFilenames.selectForDeletion(entries, 0, defaultMatchers).isEmpty())
}
@Test
fun `ordering follows the stamp even when it disagrees with alphabetical order`() {
// A user who moved from the default template to a prefixed one has both shapes in the
// folder, and there alphabetical order puts the newest file first.
- val matchers = ExportConverters.exportFileMatchers("backup_colota_export-{date}_{time}", "Pixel 7")
+ val matchers = ExportFilenames.exportFileMatchers("backup_colota_export-{date}_{time}", "Pixel 7")
val entries = listOf(
entry("backup_colota_export-2026-05-20_0800.gpx"),
entry("colota_export_2026-05-18_0800.gpx"),
entry("colota_export_2026-05-19_0800.gpx")
)
- val doomed = ExportConverters.selectForDeletion(entries, 2, matchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 2, matchers)
assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
}
@@ -257,7 +257,7 @@ class ExportFilenameTest {
entry("colota_export_2026-05-18_0800.gpx"),
entry("colota_export_2026-05-19_0800.gpx")
)
- val doomed = ExportConverters.selectForDeletion(entries, 2, defaultMatchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 2, defaultMatchers)
assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
}
@@ -269,7 +269,7 @@ class ExportFilenameTest {
entry("colota_export_2026-05-19_0800.gpx", lastModified = 2_000L),
entry("colota_export_2026-05-20_0800.gpx", lastModified = 1_000L)
)
- val doomed = ExportConverters.selectForDeletion(entries, 2, defaultMatchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 2, defaultMatchers)
assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
}
@@ -283,14 +283,14 @@ class ExportFilenameTest {
entry("colota_export_2026-05-19_0800.gpx"),
entry("colota_export_2026-05-20_0800.gpx")
)
- val doomed = ExportConverters.selectForDeletion(entries, 2, defaultMatchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 2, defaultMatchers)
assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
}
@Test
fun `a device-scoped template leaves other devices' exports alone`() {
// Several devices exporting into one shared folder.
- val matchers = ExportConverters.exportFileMatchers("{device}_colota_export-{date}_{time}", "Pixel 7")
+ val matchers = ExportFilenames.exportFileMatchers("{device}_colota_export-{date}_{time}", "Pixel 7")
val entries = listOf(
entry("Pixel7_colota_export-2026-05-18_0800.gpx"),
entry("Pixel7_colota_export-2026-05-19_0800.gpx"),
@@ -299,7 +299,7 @@ class ExportFilenameTest {
entry("S23_colota_export-2026-05-02_0800.gpx"),
entry("colota_export_2026-01-01_0000.geojson")
)
- val doomed = ExportConverters.selectForDeletion(entries, 2, matchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 2, matchers)
assertEquals(listOf("Pixel7_colota_export-2026-05-18_0800.gpx"), doomed.map { it.name })
}
@@ -311,7 +311,7 @@ class ExportFilenameTest {
entry("colota_export_2026-05-18_0800.gpx"),
entry("colota_export_2026-05-19_0800.gpx")
)
- val doomed = ExportConverters.selectForDeletion(entries, 1, defaultMatchers)
+ val doomed = ExportFilenames.selectForDeletion(entries, 1, defaultMatchers)
assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
}
}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/network/WifiNameReaderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/network/WifiNameReaderTest.kt
new file mode 100644
index 00000000..6c48c4d3
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/network/WifiNameReaderTest.kt
@@ -0,0 +1,48 @@
+package com.Colota.network
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.wifi.WifiInfo
+import android.net.wifi.WifiManager
+import io.mockk.*
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+/** The stubbed android.jar reports SDK 0, so these run the WifiManager path used below S. */
+class WifiNameReaderTest {
+
+ private val cm = mockk<ConnectivityManager>(relaxed = true)
+
+ private fun readerWith(ssid: String?): WifiNameReader {
+ val ctx = mockk<Context>(relaxed = true)
+ val wifi = ssid?.let { name ->
+ val info = mockk<WifiInfo>(relaxed = true)
+ every { info.ssid } returns name
+ mockk<WifiManager>(relaxed = true).also { every { it.connectionInfo } returns info }
+ }
+ every { ctx.getSystemService(Context.WIFI_SERVICE) } returns wifi
+ return WifiNameReader(ctx, cm)
+ }
+
+ /** Android wraps a UTF-8 name in quotes; the picker and the condition compare the bare name. */
+ @Test
+ fun `a name reads without its quotes`() {
+ assertEquals("Home", readerWith("\"Home\"").read(null))
+ }
+
+ @Test
+ fun `a device without Wi-Fi reads as no name`() {
+ assertEquals("", readerWith(null).read(null))
+ }
+
+ /** Below S the callback carries no name, so waiting on one would only stall the picker. */
+ @Test
+ fun `below S a probe answers from WifiManager without registering a callback`() {
+ var answer: String? = null
+
+ readerWith("\"Home\"").probe(mockk(relaxed = true)) { answer = it }
+
+ assertEquals("Home", answer)
+ verify(exactly = 0) { cm.registerNetworkCallback(any(), any<ConnectivityManager.NetworkCallback>()) }
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/PointSenderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/PointSenderTest.kt
new file mode 100644
index 00000000..7c890a03
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/PointSenderTest.kt
@@ -0,0 +1,111 @@
+package com.Colota.sync
+
+import com.Colota.data.DatabaseHelper
+import com.Colota.data.QueuedLocation
+import com.Colota.sync.http.BatchResult
+import com.Colota.sync.http.NetworkManager
+import com.Colota.util.AppLogger
+import io.mockk.*
+import kotlinx.coroutines.test.runTest
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+class PointSenderTest {
+
+ private lateinit var dbHelper: DatabaseHelper
+ private lateinit var networkManager: NetworkManager
+ private val rateLimits = mutableListOf<Long?>()
+ private lateinit var sender: PointSender
+ private val keptInPlace = mutableSetOf<Long>()
+
+ @Before
+ fun setUp() {
+ dbHelper = mockk(relaxed = true)
+ networkManager = mockk(relaxed = true)
+ rateLimits.clear()
+ keptInPlace.clear()
+ sender = PointSender(dbHelper, networkManager) { rateLimits.add(it) }
+
+ mockkObject(AppLogger)
+ every { AppLogger.e(any(), any(), any()) } just Runs
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ }
+
+ private fun rows(count: Long) = (1L..count).map { QueuedLocation(it, it + 100, """{"lat":52.$it}""", 0) }
+
+ /** Answers per row, keyed by the lat the payload carries. */
+ private fun answer(vararg byRow: Pair<Long, BatchResult>) {
+ val results = byRow.toMap()
+ coEvery { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) } answers {
+ val id = firstArg<JSONObject>().get("lat").toString().substringAfter(".").toLong()
+ results.getValue(id)
+ }
+ }
+
+ private suspend fun send(items: List<QueuedLocation>) =
+ sender.sendChunk(items, "https://example.com", emptyMap(), "POST", ApiFormat.FIELD_MAPPED, keptInPlace)
+
+ @Test
+ fun `sent rows leave the queue and a rejected one is bumped`() = runTest {
+ answer(1L to BatchResult.Success, 2L to BatchResult.ClientError(400), 3L to BatchResult.Success)
+
+ val result = send(rows(3))
+
+ verify { dbHelper.markLocationsSent(listOf(101L, 103L)) }
+ verify { dbHelper.removeBatchFromQueue(listOf(1L, 3L)) }
+ verify { dbHelper.incrementRetryCount(2L, "4xx: 400") }
+ assertEquals(PointSender.ChunkResult(sent = 2, failed = 1, stopReason = null), result)
+ }
+
+ /** A gateway error says nothing about the row, so it keeps its place and the pass must not post it again. */
+ @Test
+ fun `a gateway outage keeps the row in place without a bump`() = runTest {
+ answer(1L to BatchResult.ServerError(502), 2L to BatchResult.Success)
+
+ send(rows(2))
+
+ verify(exactly = 0) { dbHelper.incrementRetryCount(any(), any()) }
+ assertEquals(setOf(1L), keptInPlace)
+ }
+
+ @Test
+ fun `a corrupt row is bumped and the rest of the chunk still goes out`() = runTest {
+ answer(2L to BatchResult.Success)
+ val items = listOf(QueuedLocation(1L, 100L, "NOT_VALID_JSON", 0)) + rows(2).drop(1)
+
+ val result = send(items)
+
+ verify { dbHelper.incrementRetryCount(1L, "Corrupt payload") }
+ verify { dbHelper.markLocationsSent(listOf(102L)) }
+ assertEquals(1, result.sent)
+ }
+
+ /** The longest wait the server asked for wins, and the pass ends after this chunk. */
+ @Test
+ fun `a 429 hands the longest Retry-After to the caller and stops the pass`() = runTest {
+ answer(1L to BatchResult.RateLimited(null), 2L to BatchResult.RateLimited(600), 3L to BatchResult.Success)
+
+ val result = send(rows(3))
+
+ assertEquals(listOf<Long?>(600L), rateLimits)
+ assertTrue(result.stopReason!!.startsWith("rate limited"))
+ verify { dbHelper.removeBatchFromQueue(listOf(3L)) }
+ }
+
+ /** One chunk of a dead host is enough to know it; a chunk that got rows through keeps going. */
+ @Test
+ fun `an outage stops the pass only when nothing got through`() = runTest {
+ answer(1L to BatchResult.NetworkError, 2L to BatchResult.NetworkError)
+ assertEquals("server unreachable", send(rows(2)).stopReason)
+
+ answer(1L to BatchResult.NetworkError, 2L to BatchResult.Success)
+ assertNull(send(rows(2)).stopReason)
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
index e1bf96c7..648a29df 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncManagerTest.kt
@@ -13,7 +13,6 @@ import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
-import kotlin.coroutines.Continuation
import com.Colota.sync.http.NetworkManager
import com.Colota.sync.http.BatchResult
import com.Colota.network.NetworkMonitor
@@ -546,40 +545,6 @@ class SyncManagerTest {
assertEquals(20, second)
}
- // --- Backoff ---
-
- @Test
- fun `applyBackoffDelay waits 30s after 1 failure`() = scope.runTest {
- setField("consecutiveFailures", 1)
- val start = currentTime
- callApplyBackoffDelay()
- assertEquals(30_000L, currentTime - start)
- }
-
- @Test
- fun `applyBackoffDelay waits 60s after 2 failures`() = scope.runTest {
- setField("consecutiveFailures", 2)
- val start = currentTime
- callApplyBackoffDelay()
- assertEquals(60_000L, currentTime - start)
- }
-
- @Test
- fun `applyBackoffDelay waits 5min after 3 failures`() = scope.runTest {
- setField("consecutiveFailures", 3)
- val start = currentTime
- callApplyBackoffDelay()
- assertEquals(300_000L, currentTime - start)
- }
-
- @Test
- fun `applyBackoffDelay waits 15min after 4 or more failures`() = scope.runTest {
- setField("consecutiveFailures", 10)
- val start = currentTime
- callApplyBackoffDelay()
- assertEquals(900_000L, currentTime - start)
- }
-
// --- Batch limit and chunks ---
@Test
@@ -1367,20 +1332,6 @@ class SyncManagerTest {
coVerify(exactly = 1) { networkManager.sendToEndpoint(any(), any(), any(), any(), any()) }
}
- // --- Helpers ---
-
- @Suppress("UNCHECKED_CAST")
- private suspend fun callApplyBackoffDelay() {
- val method = SyncManager::class.java.getDeclaredMethod(
- "applyBackoffDelay",
- Continuation::class.java
- )
- method.isAccessible = true
- kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<Unit> { cont ->
- method.invoke(syncManager, cont)
- }
- }
-
// --- What a failed send tells the pass ---
private fun configurePerItem() {
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncScheduleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncScheduleTest.kt
new file mode 100644
index 00000000..8b7e2b21
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/SyncScheduleTest.kt
@@ -0,0 +1,48 @@
+package com.Colota.sync
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class SyncScheduleTest {
+
+ private var now = 0L
+ private val schedule = SyncSchedule { now }
+
+ /** A server that keeps failing is asked less and less often, never less than every 15 min. */
+ @Test
+ fun `the backoff grows from 30 s to 15 min and stays there`() {
+ assertEquals(listOf(30L, 60L, 300L, 900L, 900L), (1..5).map { SyncSchedule.backoffSeconds(it) })
+ }
+
+ @Test
+ fun `the first tick waits a full interval`() {
+ assertEquals(300L, schedule.nextPeriodicDelaySeconds(300, resumingWait = false))
+ }
+
+ /** A profile switch mid-wait shortens the wait already running, not the one after it. */
+ @Test
+ fun `a shorter interval counts from when the running wait began`() {
+ schedule.nextPeriodicDelaySeconds(900, resumingWait = false)
+ now += 100_000
+
+ assertEquals(200L, schedule.nextPeriodicDelaySeconds(300, resumingWait = true))
+ }
+
+ @Test
+ fun `a resumed wait the new interval already covers ticks at once`() {
+ schedule.nextPeriodicDelaySeconds(900, resumingWait = false)
+ now += 400_000
+
+ assertEquals(0L, schedule.nextPeriodicDelaySeconds(300, resumingWait = true))
+ }
+
+ @Test
+ fun `a wait that ran out starts the next full interval`() {
+ schedule.nextPeriodicDelaySeconds(300, resumingWait = false)
+ now += 300_000
+
+ assertEquals(300L, schedule.nextPeriodicDelaySeconds(300, resumingWait = false))
+ now += 100_000
+ assertEquals(200L, schedule.nextPeriodicDelaySeconds(300, resumingWait = false))
+ }
+}