Skip to content

Colota - Android GPS Location tracker

feat(export): customisable auto-export file names

Max Dietrich31751180f4c9
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.md
index a2e71298..d0f82ede 100644
--- a/apps/docs/docs/guides/data-export.md
+++ b/apps/docs/docs/guides/data-export.md
@@ -75,6 +75,23 @@ You can also tap **Export Now** to trigger an immediate export using your curren
By default, auto-export keeps the last **10** export files and deletes older ones automatically. You can change this in the **File Retention** setting - enter any number or **0** for unlimited (no automatic cleanup).
+Retention counts the files your **file name template** matches, which is what decides its scope:
+
+| Template | Scope |
+| ------------------- | ------------------------------------------------------------------------------------ |
+| Contains `{device}` | Keeps N exports **per device model**. Other models sharing the folder are untouched. |
+| No `{device}` | Keeps N exports **per folder**, counting every Colota export in it. |
+
+Changing the template also means files exported under the previous one are no longer managed, since retention only recognises names the current template could have produced. Delete those once by hand. The one exception is switching away from the default `colota_export_{date}_{time}`, whose files stay managed unless the new template contains `{device}`.
+
+:::warning[Several devices, one folder]
+
+If several devices export into the same folder and none of the templates include `{device}`, their files are indistinguishable, so each device counts and deletes the others' exports. Add `{device}` to the file name to separate them.
+
+`{device}` expands to the device **model**, not a unique identifier, so two phones of the same model still share a name and still delete each other's exports. Give them distinct prefixes in the template if you run identical models.
+
+:::
+
### How it works
- Uses Android AlarmManager (`setAndAllowWhileIdle`) to fire at your configured wall-clock time. Typical accuracy is within minutes; Doze mode may delay by up to ~15 minutes
@@ -88,7 +105,7 @@ By default, auto-export keeps the last **10** export files and deletes older one
- Permanent errors (invalid config, directory access issues) fail immediately; transient errors (I/O failures) retry up to 3 times
- If the selected directory becomes inaccessible (permissions revoked), auto-export disables itself and a notification prompts you to re-select the directory
- A notification is shown after each export with the file name and location count
-- Old export files beyond the retention limit are cleaned up after each successful export
+- Old export files beyond the retention limit are cleaned up after each successful export. Cleanup only considers files matching Colota's own export naming pattern, so unrelated files and subfolders in the directory are never touched
:::note[Frequency]
@@ -98,7 +115,35 @@ By default, auto-export keeps the last **10** export files and deletes older one
### File naming
-Files are saved as `colota_export_<timestamp>.<ext>` in the selected directory.
+Auto-export files are named from a template you set in **File Name**. The default is `colota_export_{date}_{time}`, which produces the same names as before this setting existed, for example `colota_export_2026-05-20_0815.geojson`.
+
+| Placeholder | Expands to | Example |
+| ----------- | -------------------------------- | ------------ |
+| `{date}` | Export date, `YYYY-MM-DD` | `2026-05-20` |
+| `{time}` | Export time, `HHMM` (24h) | `0815` |
+| `{device}` | Device model, whitespace removed | `Pixel7` |
+
+Anything else in the template is used literally, so a prefix or suffix just gets typed in:
+
+```
+{device}_colota_export-{date}_{time}
+```
+
+produces `Pixel7_colota_export-2026-05-20_0815.gpx`. The settings screen shows a live preview of the name that will be written.
+
+Every template must contain three things, and the field rejects it otherwise:
+
+- **`colota_export`** - the marker that lets Colota recognise its own files when enforcing retention. Without it, cleanup could not tell your files from its own. Matching is **case-sensitive**, so `Colota_Export` is not accepted.
+- **`{date}` and `{time}`** - together they keep each export uniquely named and let Colota order files chronologically no matter where the timestamp sits in the name.
+
+Other notes:
+
+- The file extension is appended automatically from the selected format. Do not put it in the template.
+- Characters that filesystems or sync clients reject (`\ / : * ? " < > |`) are removed, as are leading and trailing dots and spaces.
+- Templates longer than 100 characters are rejected, and `{device}` is shortened to 32 characters, so the result stays inside the filesystem's name limit.
+- If a file of the same name already exists, Android adds a counter (`… (1).gpx`). Colota still recognises those as its own.
+
+Manual **Export Locations** and trip exports are unaffected. Those go through the Android share sheet, where you name the file yourself.
## Storage Reference
diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.md
index 85283311..3cc0354d 100644
--- a/apps/docs/src/pages/privacy-policy.md
+++ b/apps/docs/src/pages/privacy-policy.md
@@ -50,7 +50,11 @@ All data is stored **locally on your device** and is never sent anywhere unless
Collected data is stored in a local SQLite database on your device. The data is not accessible to other apps. The App checks available device storage before downloading offline map packs.
-If you configure auto-export, the App will write export files (CSV, GeoJSON, GPX, or KML) to a directory you select on your device. No data leaves your device as part of this process.
+If you configure auto-export, the App will write export files (CSV, GeoJSON, GPX, or KML) to a directory you select on your device. If you pick a cloud-synced folder, those files leave your device through that provider.
+
+To enforce the file-retention limit you configure, the App also deletes export files from that directory. It only ever deletes files whose names match its own export naming pattern; other files and subfolders in the directory are left untouched.
+
+The export file name is configurable and may include a `{device}` placeholder, which inserts your device model (for example `Pixel7`). If you use it and the directory is cloud-synced, your device model is visible to that provider and to anyone with access to the folder. It is not included unless you add the placeholder.
If you enable persistent file logging in Logging -> File, the App writes diagnostic log entries (which may include location coordinates and other sensitive information) to a private file in app storage. The file is removed when the App is uninstalled. Logs are never sent automatically; sharing them requires explicit user action via the "Export log file..." flow.
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 839fcda0..25acf037 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
@@ -989,7 +989,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun getAutoExportStatus(promise: Promise) = executeAsync(promise) {
val config = AutoExportConfig.from(dbHelper)
- val fileCount = config.uri?.let { countExportFiles(it) } ?: 0
+ val fileCount = if (config.uri != null) countExportFiles(config) else 0
Arguments.createMap().apply {
putBoolean("enabled", config.enabled)
@@ -1007,6 +1007,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
putString("timeOfDay", config.timeOfDay)
putInt("weeklyDow", config.weeklyDow)
putInt("monthlyDom", config.monthlyDom)
+ putString("filenameTemplate", config.filenameTemplate)
+ putString("deviceModel", android.os.Build.MODEL)
}
}
@@ -1053,18 +1055,30 @@ 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)
+ // 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.
val files = dir?.listFiles()
- ?.filter { it.name?.startsWith("colota_export_") == true }
- ?.sortedByDescending { it.name }
+ ?.mapNotNull { file ->
+ val name = file.name.orEmpty()
+ if (matchers.none { it.matches(name) }) null
+ else ExportFileInfo(name, file.length(), file.lastModified(), file.uri.toString())
+ }
+ ?.sortedWith(
+ compareByDescending<ExportFileInfo> { ExportConverters.stampOf(it.name, matchers) }
+ .thenByDescending { it.lastModified }
+ .thenByDescending { it.name }
+ )
?: emptyList()
Arguments.createArray().apply {
for (file in files) {
pushMap(Arguments.createMap().apply {
putString("name", file.name)
- putDouble("size", file.length().toDouble())
- putDouble("lastModified", (file.lastModified() / 1000).toDouble())
- putString("uri", file.uri.toString())
+ putDouble("size", file.size.toDouble())
+ putDouble("lastModified", (file.lastModified / 1000).toDouble())
+ putString("uri", file.uri)
})
}
}
@@ -1090,11 +1104,16 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
- private fun countExportFiles(uriString: String): Int {
+ private data class ExportFileInfo(val name: String, val size: Long, val lastModified: Long, val uri: String)
+
+ private fun countExportFiles(config: AutoExportConfig): Int {
return try {
- val dirUri = android.net.Uri.parse(uriString)
+ val dirUri = android.net.Uri.parse(config.uri)
val dir = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, dirUri)
- dir?.listFiles()?.count { it.name?.startsWith("colota_export_") == true } ?: 0
+ val matchers = ExportConverters.exportFileMatchers(config.filenameTemplate, android.os.Build.MODEL)
+ dir?.listFiles()?.count { file ->
+ matchers.any { it.matches(file.name.orEmpty()) }
+ } ?: 0
} catch (e: Exception) {
AppLogger.w(TAG, "Could not count export files: ${e.message}")
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 12e7ed78..aa6a42e3 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
@@ -6,6 +6,7 @@
package com.Colota.export
import com.Colota.data.DatabaseHelper
+import com.Colota.util.AppLogger
import java.util.Calendar
import java.util.TimeZone
@@ -28,9 +29,12 @@ data class AutoExportConfig(
val timeOfDay: String = "00:00",
val weeklyDow: Int = 1,
val monthlyDom: Int = 1,
- val enabledAt: Long = 0L
+ val enabledAt: Long = 0L,
+ val filenameTemplate: String = ExportConverters.DEFAULT_FILENAME_TEMPLATE
) {
companion object {
+ private const val TAG = "AutoExportConfig"
+
private const val KEY_ENABLED = "autoExportEnabled"
private const val KEY_FORMAT = "autoExportFormat"
private const val KEY_INTERVAL = "autoExportInterval"
@@ -46,6 +50,7 @@ data class AutoExportConfig(
private const val KEY_WEEKLY_DOW = "autoExportWeeklyDow"
private const val KEY_MONTHLY_DOM = "autoExportMonthlyDom"
private const val KEY_ENABLED_AT = "autoExportEnabledAt"
+ private const val KEY_FILENAME_TEMPLATE = "autoExportFilenameTemplate"
private val VALID_FORMATS = setOf("csv", "geojson", "gpx", "kml")
private val VALID_INTERVALS = setOf("daily", "weekly", "monthly")
@@ -75,6 +80,22 @@ data class AutoExportConfig(
val monthlyDom = rawDom?.coerceIn(1, 31)
?: derived.monthlyDom.also { if (shouldPersistMigration) db.saveSetting(KEY_MONTHLY_DOM, it.toString()) }
+ // Restore or version skew can leave a template the settings screen would have
+ // 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 {
+ if (rawTemplate != null) {
+ AppLogger.w(TAG, "Filename template '$rawTemplate' is not usable, reset to default")
+ try {
+ db.saveSetting(KEY_FILENAME_TEMPLATE, it)
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Could not persist template reset: ${e.message}")
+ }
+ }
+ }
+
return AutoExportConfig(
enabled = db.getSetting(KEY_ENABLED, "false") == "true",
format = if (format in VALID_FORMATS) format else "geojson",
@@ -90,7 +111,8 @@ data class AutoExportConfig(
timeOfDay = timeOfDay,
weeklyDow = weeklyDow,
monthlyDom = monthlyDom,
- enabledAt = db.getSetting(KEY_ENABLED_AT, "0")?.toLongOrNull() ?: 0L
+ enabledAt = db.getSetting(KEY_ENABLED_AT, "0")?.toLongOrNull() ?: 0L,
+ filenameTemplate = filenameTemplate
)
}
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 0a4990c1..9b77a838 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
@@ -24,6 +24,7 @@ import com.Colota.data.DatabaseHelper
import com.Colota.util.AppLogger
import java.io.File
import java.io.IOException
+import java.util.Date
/**
* Performs the actual export. Triggered by AutoExportAlarmReceiver when the
@@ -121,15 +122,21 @@ class AutoExportWorker(
val ext = ExportConverters.extensionFor(config.format)
val dirUri = Uri.parse(config.uri)
- val fileName = "colota_export_${ExportConverters.exportFilenameStamp()}$ext"
+
+ // Used for the incremental upper bound, the saved lastExport and the filename stamp, so
+ // points written mid-export aren't dropped and the name matches the range it covers.
+ val exportStartSec = System.currentTimeMillis() / 1000
+
+ val fileName = ExportConverters.renderExportFilename(
+ config.filenameTemplate,
+ config.format,
+ Build.MODEL,
+ Date(exportStartSec * 1000)
+ )
// Write to cache first, then copy to SAF.
val tempFile = File(appContext.cacheDir, "auto_export_temp$ext")
- // Used for both the incremental upper bound and the saved lastExport,
- // so points written mid-export aren't dropped.
- val exportStartSec = System.currentTimeMillis() / 1000
-
return try {
val rowCount = if (config.mode == "incremental" && config.lastExportTimestamp > 0) {
ExportConverters.exportToFile(config.format, tempFile, shouldCancel = { isStopped }) { limit, offset ->
@@ -151,7 +158,7 @@ class AutoExportWorker(
tempFile.delete()
AppLogger.i(TAG, "No locations to export")
showNotification("Auto-Export", "No new locations to export.")
- cleanupOldExports(dirUri, config.retentionCount)
+ cleanupOldExports(dirUri, config)
return Result.success()
}
@@ -171,16 +178,23 @@ class AutoExportWorker(
config.saveLastExportTimestamp(db, exportStartSec)
- cleanupOldExports(dirUri, config.retentionCount)
+ cleanupOldExports(dirUri, config)
- AppLogger.i(TAG, "Auto-export complete: $fileName ($rowCount locations)")
- config.saveLastResult(db, fileName, rowCount)
+ // SAF renames on collision (foo.gpx -> "foo (1).gpx"), so report what it created.
+ 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) }) {
+ AppLogger.w(TAG, "Saved as '$savedName', which retention will not recognise")
+ }
+ AppLogger.i(TAG, "Auto-export complete: $savedName ($rowCount locations)")
+ config.saveLastResult(db, savedName, rowCount)
showNotification(
"Auto-Export Complete",
- "Exported $rowCount locations to $fileName",
+ "Exported $rowCount locations to $savedName",
dirUri
)
- LocationServiceModule.sendAutoExportEvent(true, fileName, rowCount, null)
+ LocationServiceModule.sendAutoExportEvent(true, savedName, rowCount, null)
Result.success()
} catch (e: SecurityException) {
config.saveEnabled(db, false)
@@ -267,25 +281,45 @@ class AutoExportWorker(
return docFile
}
- private fun cleanupOldExports(dirUri: Uri, retentionCount: Int) {
- if (retentionCount <= 0) return // 0 = unlimited
+ /**
+ * 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
+ * testable without SAF.
+ */
+ private fun cleanupOldExports(dirUri: Uri, config: AutoExportConfig) {
+ if (config.retentionCount <= 0) return // 0 = unlimited
try {
val dir = DocumentFile.fromTreeUri(appContext, dirUri) ?: return
- // File names embed a sortable timestamp, so lexicographic == chronological.
- val exportFiles = dir.listFiles()
- .filter { it.name?.startsWith("colota_export_") == true }
- .sortedBy { it.name }
-
- val toDelete = exportFiles.size - retentionCount
- if (toDelete <= 0) return
-
- exportFiles.take(toDelete).forEach { file ->
- file.delete()
- AppLogger.d(TAG, "Cleaned up old export: ${file.name}")
+ val matchers = ExportConverters.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.
+ val candidates = dir.listFiles()
+ .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)
+ }
+ val doomed = ExportConverters
+ .selectForDeletion(candidates.map { it.second }, config.retentionCount, matchers)
+ .map { it.name }
+ .toMutableList()
+ if (doomed.isEmpty()) return
+
+ var deleted = 0
+ candidates.forEach { (file, entry) ->
+ // Re-checked here because the match is by display name: a directory sharing a name
+ // with a selected file would otherwise be deleted, recursively.
+ // remove() rather than contains() so duplicate display names delete one apiece.
+ if (entry.isFile && doomed.remove(entry.name)) {
+ file.delete()
+ deleted++
+ AppLogger.d(TAG, "Cleaned up old export: ${entry.name}")
+ }
}
- AppLogger.i(TAG, "Cleaned up $toDelete old export files (keeping $retentionCount)")
+ AppLogger.i(TAG, "Cleaned up $deleted old export files (keeping ${config.retentionCount})")
} catch (e: Exception) {
AppLogger.w(TAG, "Export cleanup failed (non-critical): ${e.message}")
}
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 27c6fa89..a3b4a6f0 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
@@ -98,6 +98,161 @@ object ExportConverters {
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)
+ }
+
+ // 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)) }
+ }
+
+ /** 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")
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 dd2d15c0..1fe20934 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
@@ -183,6 +183,57 @@ class AutoExportConfigTest {
assertEquals(0L, config.enabledAt)
}
+ // --- filename template ---
+
+ private fun dbWith(template: String?) = mockk<com.Colota.data.DatabaseHelper>(relaxed = true).also { db ->
+ every { db.getSetting(any(), any()) } answers {
+ when (firstArg<String>()) {
+ "autoExportEnabled" -> "false"
+ "autoExportFormat" -> "geojson"
+ "autoExportInterval" -> "daily"
+ "autoExportMode" -> "all"
+ "lastAutoExportTimestamp" -> "0"
+ "autoExportPermissionLost" -> "false"
+ "autoExportRetentionCount" -> "10"
+ "autoExportLastRowCount" -> "0"
+ "autoExportFilenameTemplate" -> template
+ else -> null
+ }
+ }
+ }
+
+ @Test
+ fun `from defaults the filename template when unset`() {
+ val db = dbWith(null)
+ assertEquals(ExportConverters.DEFAULT_FILENAME_TEMPLATE, AutoExportConfig.from(db).filenameTemplate)
+ verify(exactly = 0) { db.saveSetting("autoExportFilenameTemplate", any()) }
+ }
+
+ @Test
+ fun `from keeps a valid custom filename template`() {
+ val custom = "{device}_colota_export-{date}_{time}"
+ assertEquals(custom, AutoExportConfig.from(dbWith(custom)).filenameTemplate)
+ }
+
+ @Test
+ 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)
+ verify {
+ db.saveSetting("autoExportFilenameTemplate", ExportConverters.DEFAULT_FILENAME_TEMPLATE)
+ }
+ }
+
+ @Test
+ 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,
+ AutoExportConfig.from(dbWith("colota_export_{date}")).filenameTemplate
+ )
+ }
+
// --- migration: from() derives schedule from lastExportTimestamp ---
@Test
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
new file mode 100644
index 00000000..d2fe6ec4
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFilenameTest.kt
@@ -0,0 +1,307 @@
+package com.Colota.export
+
+import com.Colota.export.ExportConverters.ExportEntry
+import org.junit.Assert.*
+import org.junit.Test
+import java.util.Calendar
+import java.util.Date
+
+/** Filename templates, the matcher derived from them and retention selection. */
+class ExportFilenameTest {
+
+ /** Built through a default-timezone Calendar so it agrees with the renderer's SimpleDateFormat. */
+ private fun dateAt(year: Int, month: Int, day: Int, hour: Int, minute: Int): Date {
+ val cal = Calendar.getInstance()
+ cal.set(year, month - 1, day, hour, minute, 0)
+ cal.set(Calendar.MILLISECOND, 0)
+ return cal.time
+ }
+
+ 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)
+
+ // --- renderExportFilename ---
+
+ @Test
+ fun `default template reproduces the pre-template filename`() {
+ // 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)
+ )
+ }
+
+ @Test
+ fun `device token drops whitespace`() {
+ assertEquals(
+ "Pixel7_colota_export-2026-05-20_0815.gpx",
+ render("{device}_colota_export-{date}_{time}", format = "gpx")
+ )
+ }
+
+ @Test
+ fun `illegal characters are stripped`() {
+ assertEquals(
+ "abccolota_export_2026-05-20_0815.csv",
+ render("a/b:c*colota_export_{date}_{time}", format = "csv")
+ )
+ }
+
+ @Test
+ fun `unknown tokens lose their braces rather than reaching the filesystem`() {
+ assertEquals(
+ "devcie_colota_export_2026-05-20_0815.geojson",
+ render("{devcie}_colota_export_{date}_{time}")
+ )
+ }
+
+ @Test
+ fun `leading and trailing dots and spaces are trimmed`() {
+ // Nextcloud and SMB clients reject or rename names ending in a dot or space, so the file
+ // would appear to vanish on every other device.
+ assertEquals(
+ "colota_export_2026-05-20_0815.geojson",
+ render(" .colota_export_{date}_{time}. ")
+ )
+ }
+
+ @Test
+ fun `a device model ending in a dot does not produce a double dot`() {
+ assertEquals(
+ "colota_export_2026-05-20_0815_MotoG.gpx",
+ render("colota_export_{date}_{time}_{device}", format = "gpx", device = "Moto G.")
+ )
+ }
+
+ @Test
+ fun `long device models are capped`() {
+ val name = render("{device}_colota_export_{date}_{time}", device = "X".repeat(80))
+ assertEquals("${"X".repeat(32)}_colota_export_2026-05-20_0815.geojson", name)
+ }
+
+ // --- isValidFilenameTemplate ---
+
+ @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}"))
+ // Case-sensitive: the marker is what cleanup keys off.
+ assertFalse(ExportConverters.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}"))
+ }
+
+ // --- exportFileMatcher ---
+
+ private val defaultMatcher = ExportConverters.exportFileMatcher(
+ ExportConverters.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,
+ "{device}_colota_export-{date}_{time}",
+ "colota_export_{date}_{time}_{device}",
+ "colota_export_{device}_{date}_{time}",
+ "{date}_{time}_colota_export",
+ " .colota_export_{date}_{time}. ",
+ "colota_export_{date}_{time} {device}",
+ "{device}.colota_export_{date}_{time}",
+ "colota_export_{date}_{time}_{date}"
+ )
+
+ @Test
+ fun `every template the matcher builds accepts what the renderer writes`() {
+ // The renderer trims the whole name while the matcher trims per segment, so the two can
+ // drift apart at any boundary a token sits next to.
+ 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)
+ assertTrue(
+ "template='$template' device='$device' rendered '$name' but the matcher rejected it",
+ matcher.matches(name)
+ )
+ }
+ }
+ }
+ }
+
+ @Test
+ fun `matcher accepts any known export extension so a format switch keeps old files managed`() {
+ assertTrue(defaultMatcher.matches("colota_export_2026-05-20_0815.csv"))
+ assertTrue(defaultMatcher.matches("colota_export_2026-05-20_0815.kml"))
+ assertFalse(defaultMatcher.matches("colota_export_2026-05-20_0815.zip"))
+ }
+
+ @Test
+ fun `matcher accepts the copy suffix SAF adds on a name collision`() {
+ // Two exports in the same minute; without this the second file is invisible to both the
+ // history list and retention, forever.
+ assertTrue(defaultMatcher.matches("colota_export_2026-05-20_0815 (1).geojson"))
+ assertTrue(defaultMatcher.matches("colota_export_2026-05-20_0815 (12).geojson"))
+ }
+
+ @Test
+ fun `matcher rejects a directory sharing the marker`() {
+ assertFalse(defaultMatcher.matches("colota_exports"))
+ assertFalse(defaultMatcher.matches("colota_export_archive"))
+ }
+
+ @Test
+ fun `matcher rejects cloud-sync artifacts and protective renames`() {
+ assertFalse(defaultMatcher.matches("colota_export_2026-05-20_0815 (conflicted copy).gpx"))
+ assertFalse(defaultMatcher.matches(".colota_export_2026-05-20_0815.gpx.part"))
+ assertFalse(defaultMatcher.matches("~syncthing~colota_export_2026-05-20_0815.gpx.tmp"))
+ assertFalse(defaultMatcher.matches("KEEP_colota_export_2026-05-20_0815.gpx"))
+ }
+
+ @Test
+ fun `device token scopes the matcher to this device`() {
+ val matcher = ExportConverters.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")
+ assertEquals(
+ "2026-05-200815",
+ matcher.stamp("colota_export_2026-05-20_0815_1999-01-01.geojson")
+ )
+ }
+
+ @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))
+ )
+ assertEquals("", ExportConverters.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")
+ 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") })
+ }
+
+ @Test
+ 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")
+ 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") })
+ }
+
+ // --- selectForDeletion ---
+
+ private val defaultMatchers = listOf(defaultMatcher)
+
+ private fun entry(name: String, lastModified: Long = 0L, isFile: Boolean = true) =
+ ExportEntry(name, lastModified, isFile)
+
+ @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())
+ }
+
+ @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 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)
+ assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
+ }
+
+ @Test
+ fun `ordering survives a provider that reports no lastModified`() {
+ // DocumentFile.lastModified() returns 0 when the provider omits the column; sorting on it
+ // alone would collapse to arbitrary cursor order and delete the wrong files.
+ val entries = listOf(
+ entry("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, defaultMatchers)
+ assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
+ }
+
+ @Test
+ fun `filename stamp wins over a lastModified restamped by cloud sync`() {
+ // Sync clients restamp on download, which would otherwise make the oldest export look newest.
+ val entries = listOf(
+ entry("colota_export_2026-05-18_0800.gpx", lastModified = 9_000L),
+ 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)
+ assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
+ }
+
+ @Test
+ fun `directories are never selected even when the name would match`() {
+ // DocumentFile.delete() on a tree directory is recursive.
+ val entries = listOf(
+ entry("colota_exports", isFile = false),
+ entry("colota_export_2026-05-01_0800.gpx", isFile = false),
+ entry("colota_export_2026-05-18_0800.gpx"),
+ entry("colota_export_2026-05-19_0800.gpx"),
+ entry("colota_export_2026-05-20_0800.gpx")
+ )
+ val doomed = ExportConverters.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 entries = listOf(
+ entry("Pixel7_colota_export-2026-05-18_0800.gpx"),
+ entry("Pixel7_colota_export-2026-05-19_0800.gpx"),
+ entry("Pixel7_colota_export-2026-05-20_0800.gpx"),
+ entry("S23_colota_export-2026-05-01_0800.gpx"),
+ entry("S23_colota_export-2026-05-02_0800.gpx"),
+ entry("colota_export_2026-01-01_0000.geojson")
+ )
+ val doomed = ExportConverters.selectForDeletion(entries, 2, matchers)
+ assertEquals(listOf("Pixel7_colota_export-2026-05-18_0800.gpx"), doomed.map { it.name })
+ }
+
+ @Test
+ fun `unrelated files in a shared folder are never selected`() {
+ val entries = listOf(
+ entry("holiday-photos.zip"),
+ entry("notes.txt"),
+ entry("colota_export_2026-05-18_0800.gpx"),
+ entry("colota_export_2026-05-19_0800.gpx")
+ )
+ val doomed = ExportConverters.selectForDeletion(entries, 1, defaultMatchers)
+ assertEquals(listOf("colota_export_2026-05-18_0800.gpx"), doomed.map { it.name })
+ }
+}
diff --git a/apps/mobile/src/screens/AutoExportScreen.tsx b/apps/mobile/src/screens/AutoExportScreen.tsx
index ff430a5e..dd6413ac 100644
--- a/apps/mobile/src/screens/AutoExportScreen.tsx
+++ b/apps/mobile/src/screens/AutoExportScreen.tsx
@@ -5,7 +5,7 @@
import { useState, useCallback, useEffect } from "react"
import { useFocusEffect } from "@react-navigation/native"
-import { Text, StyleSheet, Switch, View, ScrollView, Pressable, DeviceEventEmitter } from "react-native"
+import { Text, StyleSheet, Switch, View, ScrollView, Pressable, DeviceEventEmitter, TextInput } from "react-native"
import { FolderOpen, CheckCircle, Share2, AlertTriangle } from "lucide-react-native"
import {
Container,
@@ -25,7 +25,15 @@ import { useTheme } from "../hooks/useTheme"
import { useTimeout } from "../hooks/useTimeout"
import { ScreenProps } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
-import { ExportFormat, EXPORT_FORMATS } from "../utils/exportConverters"
+import {
+ ExportFormat,
+ EXPORT_FORMATS,
+ DEFAULT_FILENAME_TEMPLATE,
+ FILENAME_TOKENS,
+ filenameTokenValues,
+ isValidFilenameTemplate,
+ renderFilenamePreview
+} from "../utils/exportConverters"
import { fonts } from "../styles/typography"
import { logger } from "../utils/logger"
import { formatExportDateTime, formatBytes } from "../utils/format"
@@ -83,6 +91,9 @@ export function AutoExportScreen(_props: ScreenProps) {
const [weeklyDow, setWeeklyDow] = useState<number>(1)
const [monthlyDom, setMonthlyDom] = useState<number>(1)
const [monthlyDomInput, setMonthlyDomInput] = useState<string>("1")
+ const [filenameTemplate, setFilenameTemplate] = useState<string>(DEFAULT_FILENAME_TEMPLATE)
+ const [filenameTemplateInput, setFilenameTemplateInput] = useState<string>(DEFAULT_FILENAME_TEMPLATE)
+ const [deviceModel, setDeviceModel] = useState<string>("")
const [exportFiles, setExportFiles] = useState<ExportFile[]>([])
const [loading, setLoading] = useState(true)
const [exporting, setExporting] = useState(false)
@@ -110,6 +121,9 @@ export function AutoExportScreen(_props: ScreenProps) {
setWeeklyDow(status.weeklyDow || 1)
setMonthlyDom(status.monthlyDom || 1)
setMonthlyDomInput((status.monthlyDom || 1).toString())
+ setFilenameTemplate(status.filenameTemplate || DEFAULT_FILENAME_TEMPLATE)
+ setFilenameTemplateInput(status.filenameTemplate || DEFAULT_FILENAME_TEMPLATE)
+ setDeviceModel(status.deviceModel || "")
const permissionLost = await NativeLocationService.getSetting("autoExportPermissionLost")
if (permissionLost === "true") {
@@ -278,6 +292,30 @@ export function AutoExportScreen(_props: ScreenProps) {
await loadStatus()
}, [monthlyDomInput, monthlyDom, saveSetting, loadStatus, reschedule])
+ const handleFilenameTemplateChange = useCallback((text: string) => {
+ setFilenameTemplateInput(text)
+ }, [])
+
+ const handleFilenameTemplateBlur = useCallback(async () => {
+ const next = filenameTemplateInput.trim()
+ if (next === filenameTemplate) return
+ if (!isValidFilenameTemplate(next)) {
+ setFilenameTemplateInput(filenameTemplate)
+ showAlert(
+ "Invalid Template",
+ "The template must contain colota_export, {date} and {time}. The marker lets Colota recognise its own files during cleanup, and the date and time keep every export uniquely named and correctly ordered. Matching is case-sensitive.",
+ "warning"
+ )
+ return
+ }
+ setFilenameTemplate(next)
+ setFilenameTemplateInput(next)
+ await saveSetting("autoExportFilenameTemplate", next)
+ // The file list and count are matched against the template natively, so both go stale here.
+ await loadStatus()
+ await loadExportFiles()
+ }, [filenameTemplateInput, filenameTemplate, saveSetting, loadStatus, loadExportFiles])
+
const handleRetentionChange = useCallback((text: string) => {
setRetentionInput(text.replace(/\D/g, ""))
}, [])
@@ -343,6 +381,8 @@ export function AutoExportScreen(_props: ScreenProps) {
</Container>
)
+ const tokenValues = filenameTokenValues(deviceModel)
+
return (
<Container>
<ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
@@ -399,6 +439,40 @@ export function AutoExportScreen(_props: ScreenProps) {
</Card>
</View>
+ {/* File Name */}
+ <View style={styles.section}>
+ <SectionTitle>File Name</SectionTitle>
+ <Card>
+ <TextInput
+ style={[styles.templateInput, { color: colors.text, borderColor: colors.border }]}
+ value={filenameTemplateInput}
+ onChangeText={handleFilenameTemplateChange}
+ onBlur={handleFilenameTemplateBlur}
+ placeholder={DEFAULT_FILENAME_TEMPLATE}
+ placeholderTextColor={colors.textSecondary}
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+ {FILENAME_TOKENS.map((token) => (
+ <View key={token} style={styles.templateTokenRow}>
+ <Text style={[styles.templateToken, { color: colors.text }]}>{`{${token}}`}</Text>
+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>{tokenValues[token]}</Text>
+ </View>
+ ))}
+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
+ Must contain colota_export, {"{date}"} and {"{time}"}. The extension is added automatically.
+ </Text>
+ <Text style={[styles.templatePreview, { color: colors.textSecondary }]}>
+ Preview:{" "}
+ {renderFilenamePreview(
+ isValidFilenameTemplate(filenameTemplateInput) ? filenameTemplateInput : filenameTemplate,
+ format,
+ deviceModel
+ )}
+ </Text>
+ </Card>
+ </View>
+
{/* Frequency */}
<View style={styles.section}>
<SectionTitle>Frequency</SectionTitle>
@@ -477,7 +551,11 @@ export function AutoExportScreen(_props: ScreenProps) {
placeholder="10"
min={0}
colors={colors}
- hint="Set to 0 for unlimited"
+ hint={
+ filenameTemplate.includes("{device}")
+ ? "Set to 0 for unlimited. Counts only exports named for this device model, so other models sharing the folder are untouched."
+ : "Set to 0 for unlimited. Counts every Colota export in the folder. Add {device} to the file name to keep files per device instead."
+ }
/>
</Card>
</View>
@@ -685,5 +763,34 @@ const styles = StyleSheet.create({
letterSpacing: 0.5,
marginTop: 12,
marginBottom: 8
+ },
+ templateInput: {
+ fontSize: 15,
+ ...fonts.regular,
+ borderWidth: 1,
+ borderRadius: 8,
+ paddingHorizontal: 12,
+ paddingVertical: 10
+ },
+ templateHint: {
+ fontSize: 13,
+ ...fonts.regular,
+ marginTop: 8
+ },
+ templateTokenRow: {
+ flexDirection: "row",
+ alignItems: "baseline",
+ gap: 8
+ },
+ templateToken: {
+ fontSize: 13,
+ ...fonts.semiBold,
+ marginTop: 8,
+ minWidth: 72
+ },
+ templatePreview: {
+ fontSize: 13,
+ ...fonts.semiBold,
+ marginTop: 8
}
})
diff --git a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
index 7f74d20d..1637ec6e 100644
--- a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx
@@ -44,7 +44,9 @@ const mockGetAutoExportStatus = jest.fn().mockResolvedValue({
lastError: null,
timeOfDay: "00:00",
weeklyDow: 1,
- monthlyDom: 1
+ monthlyDom: 1,
+ filenameTemplate: "colota_export_{date}_{time}",
+ deviceModel: "Pixel 7"
})
const mockSaveSetting = jest.fn().mockResolvedValue(undefined)
const mockScheduleAutoExport = jest.fn().mockResolvedValue(true)
@@ -109,6 +111,8 @@ jest.mock("../../utils/exportConverters", () => {
const { View } = require("react-native")
const icon = () => R.createElement(View, null)
return {
+ // Real template helpers so the preview assertion exercises the shipped renderer, not a stub.
+ ...jest.requireActual("../../utils/exportConverters"),
EXPORT_FORMAT_KEYS: ["csv", "geojson", "gpx", "kml"],
EXPORT_FORMATS: {
csv: { label: "CSV", extension: ".csv", subtitle: "Spreadsheet", description: "desc", icon },
@@ -230,7 +234,9 @@ describe("AutoExportScreen", () => {
lastError: null,
timeOfDay: "00:00",
weeklyDow: 1,
- monthlyDom: 1
+ monthlyDom: 1,
+ filenameTemplate: "colota_export_{date}_{time}",
+ deviceModel: "Pixel 7"
})
mockGetExportFiles.mockResolvedValue([])
})
@@ -496,7 +502,7 @@ describe("AutoExportScreen", () => {
const { getByTestId, getByText } = render(<AutoExportScreen {...mockProps} />)
await waitFor(() => {
- expect(getByText("Set to 0 for unlimited")).toBeTruthy()
+ expect(getByText(/Set to 0 for unlimited/)).toBeTruthy()
})
const input = getByTestId("numeric-input-Files to keep")
@@ -508,6 +514,99 @@ describe("AutoExportScreen", () => {
})
})
+ it("saves a valid filename template on blur", async () => {
+ const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
+ })
+
+ const input = getByDisplayValue("colota_export_{date}_{time}")
+ fireEvent.changeText(input, "{device}_colota_export-{date}_{time}")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportFilenameTemplate", "{device}_colota_export-{date}_{time}")
+ })
+ })
+
+ it("rejects a filename template without the marker and reverts the field", async () => {
+ const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
+ })
+
+ const input = getByDisplayValue("colota_export_{date}_{time}")
+ fireEvent.changeText(input, "backup_{date}_{time}")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Invalid Template", expect.any(String), "warning")
+ })
+ expect(mockSaveSetting).not.toHaveBeenCalledWith("autoExportFilenameTemplate", "backup_{date}_{time}")
+ expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
+ })
+
+ it("rejects a filename template missing the time token", async () => {
+ const { getByDisplayValue } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByDisplayValue("colota_export_{date}_{time}")).toBeTruthy()
+ })
+
+ const input = getByDisplayValue("colota_export_{date}_{time}")
+ fireEvent.changeText(input, "colota_export_{date}")
+ fireEvent(input, "blur")
+
+ await waitFor(() => {
+ expect(mockShowAlert).toHaveBeenCalledWith("Invalid Template", expect.any(String), "warning")
+ })
+ expect(mockSaveSetting).not.toHaveBeenCalledWith("autoExportFilenameTemplate", "colota_export_{date}")
+ })
+
+ it("previews the filename the exporter will actually write", async () => {
+ // Pins the JS mirror to the native renderer; drift would otherwise be invisible.
+ jest.useFakeTimers().setSystemTime(new Date(2026, 4, 20, 8, 15, 0))
+ try {
+ const { getByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByText("Preview: colota_export_2026-05-20_0815.geojson")).toBeTruthy()
+ })
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it("retention hint reflects per-device scope when the template has a device token", async () => {
+ mockGetAutoExportStatus.mockResolvedValue({
+ enabled: false,
+ format: "geojson",
+ interval: "daily",
+ uri: null,
+ mode: "all",
+ lastExportTimestamp: 0,
+ nextExportTimestamp: 0,
+ fileCount: 0,
+ retentionCount: 10,
+ lastFileName: null,
+ lastRowCount: 0,
+ lastError: null,
+ timeOfDay: "00:00",
+ weeklyDow: 1,
+ monthlyDom: 1,
+ filenameTemplate: "{device}_colota_export-{date}_{time}",
+ deviceModel: "Pixel 7"
+ })
+
+ const { getByText } = render(<AutoExportScreen {...mockProps} />)
+
+ await waitFor(() => {
+ expect(getByText(/Counts only exports named for this device model/)).toBeTruthy()
+ })
+ })
+
it("shows Export Now button when directory is set", async () => {
mockGetAutoExportStatus.mockResolvedValue({
enabled: false,
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index c2096834..0d5ef47f 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -834,13 +834,16 @@ class NativeLocationService {
timeOfDay: string
weeklyDow: number
monthlyDom: number
+ filenameTemplate: string
+ deviceModel: string
}> {
this.ensureModule()
return LocationServiceModule.getAutoExportStatus()
}
/**
- * Returns list of export files in the export directory, sorted newest first.
+ * Returns export files matching the configured filename template, newest first by the
+ * timestamp embedded in the name.
*/
static async getExportFiles(): Promise<{ name: string; size: number; lastModified: number; uri: string }[]> {
this.ensureModule()
diff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
index a8e32703..4e2183cb 100644
--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts
+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts
@@ -1,5 +1,12 @@
import { formatBytes } from "../format"
-import { EXPORT_FORMAT_KEYS, EXPORT_FORMATS } from "../exportConverters"
+import {
+ EXPORT_FORMAT_KEYS,
+ EXPORT_FORMATS,
+ DEFAULT_FILENAME_TEMPLATE,
+ filenameTokenValues,
+ isValidFilenameTemplate,
+ renderFilenamePreview
+} from "../exportConverters"
import { FILE_FORMATS } from "../fileFormats"
// Trip serialization moved to native ExportConverters.kt; parity is covered by
@@ -37,3 +44,94 @@ describe("export format registry", () => {
})
})
})
+
+// These expectations are duplicated in ExportFilenameTest.kt. The preview mirrors the native
+// renderer, so any disagreement shows the user a name that never gets written.
+describe("renderFilenamePreview", () => {
+ const may20 = new Date(2026, 4, 20, 8, 15, 0)
+
+ it("reproduces the pre-template filename for the default template", () => {
+ expect(renderFilenamePreview(DEFAULT_FILENAME_TEMPLATE, "geojson", "Pixel 7", may20)).toBe(
+ "colota_export_2026-05-20_0815.geojson"
+ )
+ })
+
+ it("drops whitespace from the device token", () => {
+ expect(renderFilenamePreview("{device}_colota_export-{date}_{time}", "gpx", "Pixel 7", may20)).toBe(
+ "Pixel7_colota_export-2026-05-20_0815.gpx"
+ )
+ })
+
+ it("strips illegal characters", () => {
+ expect(renderFilenamePreview("a/b:c*colota_export_{date}_{time}", "csv", "Pixel 7", may20)).toBe(
+ "abccolota_export_2026-05-20_0815.csv"
+ )
+ })
+
+ it("strips the braces of unknown tokens", () => {
+ expect(renderFilenamePreview("{devcie}_colota_export_{date}_{time}", "geojson", "Pixel 7", may20)).toBe(
+ "devcie_colota_export_2026-05-20_0815.geojson"
+ )
+ })
+
+ it("trims leading and trailing dots and spaces", () => {
+ expect(renderFilenamePreview(" .colota_export_{date}_{time}. ", "geojson", "Pixel 7", may20)).toBe(
+ "colota_export_2026-05-20_0815.geojson"
+ )
+ })
+
+ it("does not produce a double dot for a device model ending in a dot", () => {
+ expect(renderFilenamePreview("colota_export_{date}_{time}_{device}", "gpx", "Moto G.", may20)).toBe(
+ "colota_export_2026-05-20_0815_MotoG.gpx"
+ )
+ })
+
+ it("caps long device models", () => {
+ expect(renderFilenamePreview("{device}_colota_export_{date}_{time}", "geojson", "X".repeat(80), may20)).toBe(
+ `${"X".repeat(32)}_colota_export_2026-05-20_0815.geojson`
+ )
+ })
+
+ it("pads single-digit months, days, hours and minutes", () => {
+ expect(renderFilenamePreview(DEFAULT_FILENAME_TEMPLATE, "gpx", "Pixel 7", new Date(2026, 0, 5, 7, 4, 0))).toBe(
+ "colota_export_2026-01-05_0704.gpx"
+ )
+ })
+})
+
+describe("filenameTokenValues", () => {
+ // The settings hint renders these, so they have to be the same strings the renderer substitutes.
+ it("matches what renderFilenamePreview substitutes", () => {
+ const now = new Date(2026, 4, 20, 8, 15, 0)
+ const { date, time, device } = filenameTokenValues("Pixel 7", now)
+
+ expect(date).toBe("2026-05-20")
+ expect(time).toBe("0815")
+ expect(device).toBe("Pixel7")
+ expect(renderFilenamePreview("{device}_colota_export-{date}_{time}", "gpx", "Pixel 7", now)).toBe(
+ `${device}_colota_export-${date}_${time}.gpx`
+ )
+ })
+
+ it("caps the device value like the renderer does", () => {
+ expect(filenameTokenValues("X".repeat(80)).device).toBe("X".repeat(32))
+ })
+})
+
+describe("isValidFilenameTemplate", () => {
+ it("requires the marker and both time tokens", () => {
+ expect(isValidFilenameTemplate(DEFAULT_FILENAME_TEMPLATE)).toBe(true)
+ expect(isValidFilenameTemplate("{device}_colota_export-{date}_{time}")).toBe(true)
+ expect(isValidFilenameTemplate("backup_{date}_{time}")).toBe(false)
+ expect(isValidFilenameTemplate("colota_export_{time}")).toBe(false)
+ expect(isValidFilenameTemplate("colota_export_{date}")).toBe(false)
+ })
+
+ it("is case-sensitive on the marker", () => {
+ expect(isValidFilenameTemplate("Colota_Export_{date}_{time}")).toBe(false)
+ })
+
+ it("rejects a template that would overrun the filename limit", () => {
+ expect(isValidFilenameTemplate("x".repeat(120) + "colota_export_{date}_{time}")).toBe(false)
+ })
+})
diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.ts
index e11ec952..5cbf46d4 100644
--- a/apps/mobile/src/utils/exportConverters.ts
+++ b/apps/mobile/src/utils/exportConverters.ts
@@ -40,3 +40,74 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = EXPORT_F
},
{} as Record<ExportFormat, ExportFormatConfig>
)
+
+// Mirrors ExportConverters.renderExportFilename so the settings screen can preview a name without
+// a bridge call per keystroke. Native is authoritative; both suites assert the same expectations.
+
+export const FILENAME_MARKER = "colota_export"
+export const DEFAULT_FILENAME_TEMPLATE = "colota_export_{date}_{time}"
+
+const MAX_TEMPLATE_LENGTH = 100
+const MAX_DEVICE_LENGTH = 32
+const ILLEGAL_FILENAME_CHARS = /[\\/:*?"<>|{}]/g
+
+/**
+ * The marker lets cleanup tell Colota's files from the user's; {date} and {time} keep each export
+ * uniquely named and chronologically sortable.
+ */
+export function isValidFilenameTemplate(template: string): boolean {
+ return (
+ template.length <= MAX_TEMPLATE_LENGTH &&
+ template.includes(FILENAME_MARKER) &&
+ template.includes("{date}") &&
+ template.includes("{time}")
+ )
+}
+
+/** Control characters go by code point so this file stays ASCII. */
+function stripIllegal(value: string): string {
+ let kept = ""
+ for (const char of value) {
+ const cp = char.codePointAt(0)!
+ if (cp >= 0x20 && cp !== 0x7f) kept += char
+ }
+ return kept.replace(ILLEGAL_FILENAME_CHARS, "")
+}
+
+export const FILENAME_TOKENS = ["date", "time", "device"] as const
+export type FilenameToken = (typeof FILENAME_TOKENS)[number]
+
+/**
+ * What each placeholder expands to. The settings hint renders these rather than fixed samples, so
+ * it cannot drift from the name that actually gets written.
+ */
+export function filenameTokenValues(deviceModel: string, now: Date = new Date()): Record<FilenameToken, string> {
+ // Hand-padded: the native renderer pins Locale.US, so toLocaleDateString would show a name
+ // that never gets written on a non-Gregorian or non-Latin-digit locale.
+ const pad = (value: number) => String(value).padStart(2, "0")
+ return {
+ date: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
+ time: `${pad(now.getHours())}${pad(now.getMinutes())}`,
+ device: stripIllegal(deviceModel.replace(/\s+/g, "")).slice(0, MAX_DEVICE_LENGTH)
+ }
+}
+
+export function renderFilenamePreview(
+ template: string,
+ format: ExportFormat,
+ deviceModel: string,
+ now: Date = new Date()
+): string {
+ const { date, time, device } = filenameTokenValues(deviceModel, now)
+
+ const base = stripIllegal(
+ template
+ .replace(/\{device\}/g, device)
+ .replace(/\{date\}/g, date)
+ .replace(/\{time\}/g, time)
+ )
+ .replace(/^[.\s]+/, "")
+ .replace(/[.\s]+$/, "")
+
+ return base + EXPORT_FORMATS[format].extension
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/44.txt b/fastlane/metadata/android/en-US/changelogs/44.txt
index 4d5ce374..40b08d34 100644
--- a/fastlane/metadata/android/en-US/changelogs/44.txt
+++ b/fastlane/metadata/android/en-US/changelogs/44.txt
@@ -1 +1,3 @@
- The Stationary profile now records a point at each interval while the device is still
+- Auto-export file names are now customisable with {date}, {time} and {device} placeholders
+- Add {device} to the file name to keep retention per device model when several phones share an export folder