Colota - Android GPS Location tracker
feat: add scheduled auto-export with native WorkManager
Max Dietrichab2229dedf4b
diff --git a/README.md b/README.mdindex 3b7b55fb..f104b7d6 100644--- a/README.md+++ b/README.md@@ -17,6 +17,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su- **Self-Hosted** - Send location data to your own server. Works with GeoPulse, Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, Home Assistant, or any custom backend.- **Privacy First** - No analytics, no telemetry, no third-party SDKs. Open source (AGPL-3.0).- **Works Offline** - Fully functional without a server. Export as CSV, GeoJSON, GPX, or KML.+- **Scheduled Export** - Automatic daily, weekly, or monthly exports to a local directory with file retention management.- **Location History** - View daily summaries, trip segmentation, calendar with activity dots, and per-trip export.- **Reliable Tracking** - Foreground service, auto-start on boot, exponential backoff retry.- **Geofencing** - Pause zones that automatically stop recording locations.diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 8f912596..a63686d8 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -70,6 +70,7 @@ Emits events back to JavaScript:- `onSyncProgress` - batch sync progress updates with `{sent, failed, total}`- `onPauseZoneChange` - entered or exited a geofence pause zone- `onProfileSwitch` - a tracking profile was activated or deactivated+- `onAutoExportComplete` - auto-export finished with `{success, fileName, rowCount, error}`### LocationProvider Abstraction@@ -154,16 +155,20 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A### Other Modules-| Module | Purpose |-| ---------------------- | ------------------------------------------------------------------------------------------- |-| `LocationBootReceiver` | Auto-restarts tracking after device reboot |-| `DeviceInfoHelper` | Device metadata and battery status with caching |-| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |-| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |-| `ServiceConfig` | Centralized configuration data class |-| `TimedCache` | Generic TTL cache used for queue count, device info, geofences, profiles, and network state |-| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |-| `AppLogger` | Centralized logger - logs when debug mode is enabled or in debug builds, errors always log |+| Module | Purpose |+| --- | --- |+| `LocationBootReceiver` | Auto-restarts tracking after device reboot |+| `DeviceInfoHelper` | Device metadata and battery status with caching |+| `FileOperations` | File I/O, sharing via FileProvider, and clipboard access |+| `PayloadBuilder` | Builds JSON payloads with dynamic field mapping |+| `ServiceConfig` | Centralized configuration data class |+| `TimedCache` | Generic TTL cache used for queue count, device info, geofences, profiles, and network state |+| `BuildConfigModule` | Exposes build constants (SDK versions, app version) to JS |+| `AppLogger` | Centralized logger - logs when debug mode is enabled or in debug builds, errors always log |+| `AutoExportWorker` | WorkManager `CoroutineWorker` for scheduled exports - checks `AutoExportConfig.isExportDue()` on each run, streams chunked writes, verifies output, and cleans up old files beyond retention limit |+| `AutoExportScheduler` | Schedules a daily (24h) check worker via WorkManager with battery-not-low constraint - frequency logic (daily/weekly/monthly) is handled at runtime by the worker |+| `AutoExportConfig` | Typed data class wrapping auto-export settings from the SQLite settings table with validation, `isExportDue()`, and `nextExportTimestamp()` |+| `ExportConverters` | Native Kotlin export converters (CSV, GeoJSON, GPX, KML) with in-memory, streaming, and file-based (`exportToFile`) interfaces |## React Native Layer@@ -181,7 +186,8 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A| `LocationInspectorScreen` | Calendar day picker with activity dots, map tab with trip-colored tracks, trips tab with trip cards and export || `TripDetailScreen` | Full trip view with dedicated map, stats grid, speed and elevation profile charts, and per-trip export || `LocationSummaryScreen` | Aggregated stats for selectable periods (week/month/30 days) with daily breakdown and tap-to-inspect navigation |-| `ExportDataScreen` | Export all tracked locations as CSV, GeoJSON, GPX, or KML |+| `ExportDataScreen` | Export all tracked locations via native streaming converters as CSV, GeoJSON, GPX, or KML |+| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, export range, and file retention || `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls || `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports || `AboutScreen` | App version, device info, links to repository and privacy policy |diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.mdindex 088e26c0..b29d7eb0 100644--- a/apps/docs/docs/guides/data-export.md+++ b/apps/docs/docs/guides/data-export.md@@ -37,6 +37,50 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'<ScreenshotGallery screenshots={[ { src: "/img/screenshots/ExportData.png", label: "Export Data" }, ]} />+## Scheduled Export (Auto-Export)++Automatically export your location data on a schedule without opening the app.++### Setup++1. Go to **Data Management** > **Export Data**+2. Tap the **Auto-Export** card at the bottom+3. Select an export directory (files are saved there via Android's Storage Access Framework)+4. Choose a format (CSV, GeoJSON, GPX, or KML)+5. Set the frequency: **Daily**, **Weekly**, or **Monthly**+6. Enable the toggle++You can also tap **Export Now** to trigger an immediate export using your current auto-export settings, without waiting for the next scheduled run.++### Export Range++- **All data** - exports every stored location each time+- **Since last export** - only exports locations recorded since the previous auto-export++### File Retention++By default, auto-export keeps the last **10** export files and deletes older ones automatically. You can change this in the **File Retention** setting (1, 5, 10, 30, or Unlimited).++### How it works++- Uses Android WorkManager with a daily check interval - the worker runs every 24 hours and checks whether an export is actually due based on your chosen frequency+- Promotes to a foreground service during export, preventing Android from killing long-running exports+- Streams data in chunks (10,000 locations at a time) to keep memory usage low even with very large datasets+- Writes to a temporary file first, then copies to the export directory - if something goes wrong mid-export, you never get a partial or corrupted file+- After copying, verifies the destination file exists and has the correct size before deleting the temp file+- Requires battery not low - exports are deferred when battery is critically low+- If the export loop is cancelled (e.g. by disabling auto-export), it cleans up gracefully without leaving partial files+- 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++:::note **Monthly** frequency uses a calendar month (e.g. Jan 15 to Feb 15), not a fixed 30-day interval. **Daily** and **Weekly** use fixed 24h and 168h intervals respectively. All schedules are approximate due to Android battery optimization. :::++### File naming++Files are saved as `colota_export_<timestamp>.<ext>` in the selected directory.+## Storage Reference- ~200 bytes per locationdiff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.mdindex 4df56639..e7b420b6 100644--- a/apps/docs/docs/guides/troubleshooting.md+++ b/apps/docs/docs/guides/troubleshooting.md@@ -48,13 +48,14 @@ adb logcat | grep -E "LocationDB|NetworkManager|SyncManager|LocationService|GeofKey log tags:-| Tag | What it shows |-| ----------------- | ---------------------------------- |-| `LocationService` | GPS fixes, service lifecycle |-| `SyncManager` | Queue processing, retry attempts |-| `NetworkManager` | HTTP requests, endpoint validation |-| `LocationDB` | Database operations |-| `GeofenceHelper` | Zone detection |+| Tag | What it shows |+| ------------------ | ---------------------------------- |+| `LocationService` | GPS fixes, service lifecycle |+| `SyncManager` | Queue processing, retry attempts |+| `NetworkManager` | HTTP requests, endpoint validation |+| `LocationDB` | Database operations |+| `GeofenceHelper` | Zone detection |+| `AutoExportWorker` | Scheduled export execution |You can also use the **Location History** screen in the app to see recorded locations on a track map or as a list with their accuracy and timestamps.@@ -79,6 +80,17 @@ If **Wi-Fi Only Sync** is enabled, uploads are skipped while on cellular data. LTo disable: **Settings > Advanced Settings > Network Settings > Wi-Fi Only Sync**.+## Auto-export not working++- Verify a directory is selected in **Export Data > Auto-Export**+- Check that the toggle is enabled+- Make sure battery is not critically low (exports are deferred when battery is low)+- If you see a "Directory permission lost" notification, re-select the export directory+- Check that the selected directory still exists and is accessible+- Transient errors (I/O failures) retry up to 3 times automatically; permanent errors (invalid config, directory issues) fail immediately without retrying+- If old exports seem to disappear, check the **File Retention** setting - by default only the last 10 files are kept+- Check the `AutoExportWorker` log tag in native logs for details+## Database growing too large- Use **Clear Sent History** to remove synced locationsdiff --git a/apps/docs/src/pages/index.tsx b/apps/docs/src/pages/index.tsxindex 256f03a3..a48468d8 100644--- a/apps/docs/src/pages/index.tsx+++ b/apps/docs/src/pages/index.tsx@@ -49,7 +49,7 @@ const features = [{title: "Works Offline",description:- "Locations queue locally and sync when connectivity returns. Export anytime as CSV, GeoJSON, GPX, or KML."+ "Locations queue locally and sync when connectivity returns. Export anytime or scheduled as CSV, GeoJSON, GPX, or KML."},{title: "Tracking Profiles",diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 661645ec..bdab5043 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -17,6 +17,7 @@ import {SettingsScreen,ApiSettingsScreen,AuthSettingsScreen,+ AutoExportScreen,GeofenceScreen,DataManagementScreen,LocationHistoryScreen,@@ -83,6 +84,11 @@ const SCREEN_CONFIG = [component: ExportDataScreen,title: "Export Data"},+ {+ name: "Auto-Export",+ component: AutoExportScreen,+ title: "Auto-Export"+ },{name: "Data Management",component: DataManagementScreen,diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 4a2f0265..23c42741 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -197,6 +197,8 @@ dependencies {implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2'implementation 'androidx.security:security-crypto:1.1.0'implementation 'androidx.car.app:app:1.7.0'+ implementation 'androidx.work:work-runtime:2.11.1'+ implementation 'androidx.documentfile:documentfile:1.0.1'if (isHermesEnabled) {implementation("com.facebook.react:hermes-android")diff --git a/apps/mobile/android/app/proguard-rules.pro b/apps/mobile/android/app/proguard-rules.proindex 235b117f..37c6afc8 100644--- a/apps/mobile/android/app/proguard-rules.pro+++ b/apps/mobile/android/app/proguard-rules.pro@@ -23,6 +23,9 @@# Keep location provider abstraction-keep class com.Colota.location.** { *; }+# Keep WorkManager worker (instantiated by class name)+-keep class com.Colota.export.AutoExportWorker { *; }+# Standard optimization settings-dontwarn com.facebook.react.**-keepattributes Signature\ No newline at end of filediff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xmlindex e94ac9eb..a217d03e 100644--- a/apps/mobile/android/app/src/main/AndroidManifest.xml+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml@@ -20,6 +20,7 @@<!-- Foreground service type (Android 10+) --><uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" /><!-- Notification permission (Android 13+) --><uses-permission android:name="android.permission.POST_NOTIFICATIONS" />@@ -74,6 +75,12 @@</intent-filter></service>+ <!-- WorkManager foreground service (auto-export) -->+ <service+ android:name="androidx.work.impl.foreground.SystemForegroundService"+ android:foregroundServiceType="dataSync"+ android:exported="false" />+<!-- Boot Receiver --><receiverandroid:name=".service.LocationBootReceiver"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.ktindex 8aaafc93..6b920b1f 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@@ -5,6 +5,7 @@package com.Colota.bridge+import android.app.Activityimport android.content.Intentimport com.Colota.BuildConfigimport com.Colota.data.DatabaseHelper@@ -20,10 +21,14 @@ import com.Colota.service.getBooleanOrNullimport com.Colota.sync.NetworkManagerimport com.Colota.sync.PayloadBuilderimport com.Colota.util.DeviceInfoHelper+import com.Colota.export.AutoExportConfig+import com.Colota.export.AutoExportScheduler+import com.Colota.export.ExportConvertersimport com.Colota.util.FileOperationsimport com.Colota.util.AppLoggerimport com.Colota.util.SecureStorageHelperimport com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.BaseActivityEventListenerimport com.facebook.react.bridge.LifecycleEventListenerimport com.facebook.react.bridge.Promiseimport com.facebook.react.bridge.ReactApplicationContext@@ -59,9 +64,33 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())+ // SAF directory picker+ private var safPickerPromise: Promise? = null+ private val SAF_PICKER_REQUEST = 9002++ private val activityEventListener = object : BaseActivityEventListener() {+ override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {+ if (requestCode != SAF_PICKER_REQUEST) return+ val promise = safPickerPromise ?: return+ safPickerPromise = null++ if (resultCode != Activity.RESULT_OK || data?.data == null) {+ promise.resolve(null)+ return+ }++ val uri = data.data!!+ // Persist permission so WorkManager can access it later+ val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ reactApplicationContext.contentResolver.takePersistableUriPermission(uri, flags)+ promise.resolve(uri.toString())+ }+ }+init {reactContextRef = WeakReference(reactContext)reactContext.addLifecycleEventListener(this)+ reactContext.addActivityEventListener(activityEventListener)}companion object {@@ -204,6 +233,29 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ /** Emits auto-export completion events to JS for real-time status updates. */+ @JvmStatic+ fun sendAutoExportEvent(success: Boolean, fileName: String?, rowCount: Int, error: String?): Boolean {+ val context = reactContextRef.get() ?: return false+ if (!context.hasActiveCatalystInstance()) return false++ return try {+ val params = Arguments.createMap().apply {+ putBoolean("success", success)+ if (fileName != null) putString("fileName", fileName) else putNull("fileName")+ putInt("rowCount", rowCount)+ if (error != null) putString("error", error) else putNull("error")+ }+ context+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)+ .emit("onAutoExportComplete", params)+ true+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to send auto-export event", e)+ false+ }+ }+/** Emits pause zone entry/exit events for the JS geofence UI. */@JvmStaticfun sendPauseZoneEvent(entered: Boolean, zoneName: String?): Boolean {@@ -752,16 +804,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.resolve(null)}- @ReactMethod- fun forceExitZone(promise: Promise) {- try {- startServiceWithAction(LocationForegroundService.ACTION_FORCE_EXIT_ZONE)- promise.resolve(true)- } catch (e: Exception) {- promise.reject("FORCE_EXIT_ERROR", e.message, e)- }- }-@ReactMethodfun saveSetting(key: String, value: String, promise: Promise) =executeAsync(promise) {@@ -918,5 +960,153 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :process.destroy()}}++ // =========================================================================+ // AUTO-EXPORT+ // =========================================================================++ @ReactMethod+ fun pickExportDirectory(promise: Promise) {+ val activity = reactApplicationContext.currentActivity+ if (activity == null) {+ promise.reject("E_NO_ACTIVITY", "No current activity")+ return+ }+ safPickerPromise = promise+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)+ }+ activity.startActivityForResult(intent, SAF_PICKER_REQUEST)+ }++ @ReactMethod+ fun scheduleAutoExport(promise: Promise) = executeAsync(promise) {+ // Validate that the export directory URI is still accessible+ val config = AutoExportConfig.from(dbHelper)+ if (config.uri != null) {+ val uri = android.net.Uri.parse(config.uri)+ val hasPermission = reactApplicationContext.contentResolver.persistedUriPermissions.any {+ it.uri == uri && it.isReadPermission && it.isWritePermission+ }+ if (!hasPermission) {+ config.saveEnabled(dbHelper, false)+ config.savePermissionLost(dbHelper, true)+ throw Exception("Export directory permission lost. Please re-select the directory.")+ }+ }+ AutoExportScheduler.schedule(reactApplicationContext)+ true+ }++ @ReactMethod+ fun runAutoExportNow(promise: Promise) = executeAsync(promise) {+ AutoExportScheduler.runNow(reactApplicationContext)+ true+ }++ @ReactMethod+ fun cancelAutoExport(promise: Promise) = executeAsync(promise) {+ AutoExportScheduler.cancel(reactApplicationContext)+ true+ }++ @ReactMethod+ fun getAutoExportStatus(promise: Promise) = executeAsync(promise) {+ val config = AutoExportConfig.from(dbHelper)+ val fileCount = config.uri?.let { countExportFiles(it) } ?: 0++ Arguments.createMap().apply {+ putBoolean("enabled", config.enabled)+ putString("format", config.format)+ putString("interval", config.interval)+ putString("uri", config.uri)+ putString("mode", config.mode)+ putDouble("lastExportTimestamp", config.lastExportTimestamp.toDouble())+ putDouble("nextExportTimestamp", config.nextExportTimestamp().toDouble())+ putInt("fileCount", fileCount)+ putInt("retentionCount", config.retentionCount)+ putString("lastFileName", config.lastFileName)+ putInt("lastRowCount", config.lastRowCount)+ putString("lastError", config.lastError)+ }+ }++ @ReactMethod+ fun exportToFile(format: String, promise: Promise) = executeAsync(promise) {+ val ext = ExportConverters.extensionFor(format)+ val dateStr = java.text.SimpleDateFormat("yyyy-MM-dd_HHmm", java.util.Locale.US)+ .format(java.util.Date())+ val tempFile = java.io.File(reactApplicationContext.cacheDir, "manual_export_$dateStr$ext")++ val totalRows = ExportConverters.exportToFile(dbHelper, format, tempFile)++ if (totalRows == 0) {+ tempFile.delete()+ null+ } else {+ Arguments.createMap().apply {+ putString("filePath", tempFile.absolutePath)+ putString("mimeType", ExportConverters.mimeTypeFor(format))+ putInt("rowCount", totalRows)+ }+ }+ }++ @ReactMethod+ fun getExportFiles(promise: Promise) = executeAsync(promise) {+ val config = AutoExportConfig.from(dbHelper)+ if (config.uri == null) {+ Arguments.createArray()+ } else {+ val dirUri = android.net.Uri.parse(config.uri)+ val dir = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, dirUri)+ val files = dir?.listFiles()+ ?.filter { it.name?.startsWith("colota_export_") == true }+ ?.sortedByDescending { 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())+ })+ }+ }+ }+ }++ @ReactMethod+ fun shareExportFile(fileUri: String, mimeType: String, promise: Promise) {+ try {+ val uri = android.net.Uri.parse(fileUri)+ val intent = Intent(Intent.ACTION_SEND).apply {+ type = mimeType+ putExtra(Intent.EXTRA_STREAM, uri)+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ val chooser = Intent.createChooser(intent, "Share Export")+ chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ reactApplicationContext.startActivity(chooser)+ promise.resolve(true)+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to share export file", e)+ promise.reject("SHARE_ERROR", e.message, e)+ }+ }++ private fun countExportFiles(uriString: String): Int {+ return try {+ val dirUri = android.net.Uri.parse(uriString)+ val dir = androidx.documentfile.provider.DocumentFile.fromTreeUri(reactApplicationContext, dirUri)+ dir?.listFiles()?.count { it.name?.startsWith("colota_export_") == true } ?: 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/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex d2e5eee9..233ed694 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -6,6 +6,7 @@package com.Colota.dataimport android.content.ContentValues+import android.database.Cursorimport com.Colota.util.AppLoggerimport android.content.Contextimport android.database.sqlite.SQLiteDatabase@@ -288,11 +289,28 @@ class DatabaseHelper private constructor(context: Context) :private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES, TABLE_PROFILES)+ private fun Cursor.toMapList(): List<Map<String, Any?>> = buildList {+ val columns = columnNames+ while (moveToNext()) {+ add(buildMap {+ for (col in columns) {+ val idx = getColumnIndex(col)+ if (idx != -1) {+ put(col, when (getType(idx)) {+ Cursor.FIELD_TYPE_INTEGER -> getLong(idx)+ Cursor.FIELD_TYPE_FLOAT -> getDouble(idx)+ Cursor.FIELD_TYPE_STRING -> getString(idx)+ else -> null+ })+ }+ }+ })+ }+ }+fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {require(tableName in ALLOWED_TABLES) { "Invalid table name: $tableName" }- val data = mutableListOf<Map<String, Any?>>()-val orderBy = when(tableName) {TABLE_LOCATIONS -> "timestamp DESC"TABLE_QUEUE -> "created_at DESC"@@ -300,38 +318,31 @@ class DatabaseHelper private constructor(context: Context) :else -> "ROWID DESC"}- try {+ return try {readableDatabase.query(- tableName,- null,- null, null, null, null,- orderBy,- "$limit OFFSET $offset"- ).use { cursor ->- val columnNames = cursor.columnNames-- while (cursor.moveToNext()) {- val row = mutableMapOf<String, Any?>()-- for (column in columnNames) {- val idx = cursor.getColumnIndex(column)- if (idx != -1) {- row[column] = when (cursor.getType(idx)) {- android.database.Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(idx)- android.database.Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(idx)- android.database.Cursor.FIELD_TYPE_STRING -> cursor.getString(idx)- else -> null- }- }- }- data.add(row)- }- }+ tableName, null, null, null, null, null,+ orderBy, "$limit OFFSET $offset"+ ).use { it.toMapList() }} catch (e: Exception) {AppLogger.e(TAG, "Error reading table $tableName", e)+ emptyList()+ }+ }++ /**+ * Returns all locations ordered chronologically (ASC) with pagination.+ * Used for export operations where chronological order is required.+ */+ fun getLocationsChronological(limit: Int, offset: Int): List<Map<String, Any?>> {+ return try {+ readableDatabase.query(+ TABLE_LOCATIONS, null, null, null, null, null,+ "timestamp ASC, id ASC", "$limit OFFSET $offset"+ ).use { it.toMapList() }+ } catch (e: Exception) {+ AppLogger.e(TAG, "Error reading locations chronologically", e)+ emptyList()}-- return data}/**@@ -342,43 +353,28 @@ class DatabaseHelper private constructor(context: Context) :* @param endTimestamp End of range (Unix seconds, inclusive)* @return Locations ordered by timestamp ASC for polyline drawing*/- fun getLocationsByDateRange(startTimestamp: Long, endTimestamp: Long): List<Map<String, Any?>> {- val data = mutableListOf<Map<String, Any?>>()-- try {+ fun getLocationsByDateRange(+ startTimestamp: Long,+ endTimestamp: Long,+ limit: Int = 0,+ offset: Int = 0+ ): List<Map<String, Any?>> {+ return try {readableDatabase.query(- TABLE_LOCATIONS,- null,+ TABLE_LOCATIONS, null,"timestamp >= ? AND timestamp <= ?",arrayOf(startTimestamp.toString(), endTimestamp.toString()),null, null,- "timestamp ASC, id ASC"- ).use { cursor ->- val columnNames = cursor.columnNames-- while (cursor.moveToNext()) {- val row = mutableMapOf<String, Any?>()- for (column in columnNames) {- val idx = cursor.getColumnIndex(column)- if (idx != -1) {- row[column] = when (cursor.getType(idx)) {- android.database.Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(idx)- android.database.Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(idx)- android.database.Cursor.FIELD_TYPE_STRING -> cursor.getString(idx)- else -> null- }- }- }- data.add(row)- }- }+ "timestamp ASC, id ASC",+ if (limit > 0) "$limit OFFSET $offset" else null+ ).use { it.toMapList() }} catch (e: Exception) {AppLogger.e(TAG, "Error reading locations by date range", e)+ emptyList()}-- return data}+/*** Adds location to transmission queue.* @return The queue ID of the inserted rowdiff --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.ktnew file mode 100644index 00000000..d822588d--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportConfig.kt@@ -0,0 +1,114 @@+/**+ * 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.data.DatabaseHelper++/**+ * Typed wrapper for auto-export settings stored in the SQLite settings table.+ * Centralizes all setting key access and provides type-safe defaults.+ */+data class AutoExportConfig(+ val enabled: Boolean = false,+ val format: String = "geojson",+ val interval: String = "daily",+ val mode: String = "all",+ val uri: String? = null,+ val lastExportTimestamp: Long = 0L,+ val permissionLost: Boolean = false,+ val retentionCount: Int = 10,+ val lastFileName: String? = null,+ val lastRowCount: Int = 0,+ val lastError: String? = null+) {+ companion object {+ private const val KEY_ENABLED = "autoExportEnabled"+ private const val KEY_FORMAT = "autoExportFormat"+ private const val KEY_INTERVAL = "autoExportInterval"+ private const val KEY_MODE = "autoExportMode"+ private const val KEY_URI = "autoExportUri"+ private const val KEY_LAST_TIMESTAMP = "lastAutoExportTimestamp"+ private const val KEY_PERMISSION_LOST = "autoExportPermissionLost"+ private const val KEY_RETENTION_COUNT = "autoExportRetentionCount"+ private const val KEY_LAST_FILE_NAME = "autoExportLastFileName"+ private const val KEY_LAST_ROW_COUNT = "autoExportLastRowCount"+ private const val KEY_LAST_ERROR = "autoExportLastError"++ private val VALID_FORMATS = setOf("csv", "geojson", "gpx", "kml")+ private val VALID_INTERVALS = setOf("daily", "weekly", "monthly")+ private val VALID_MODES = setOf("all", "incremental")++ fun from(db: DatabaseHelper): AutoExportConfig {+ val format = db.getSetting(KEY_FORMAT, "geojson") ?: "geojson"+ val interval = db.getSetting(KEY_INTERVAL, "daily") ?: "daily"+ val mode = db.getSetting(KEY_MODE, "all") ?: "all"++ return AutoExportConfig(+ enabled = db.getSetting(KEY_ENABLED, "false") == "true",+ format = if (format in VALID_FORMATS) format else "geojson",+ interval = if (interval in VALID_INTERVALS) interval else "daily",+ mode = if (mode in VALID_MODES) mode else "all",+ uri = db.getSetting(KEY_URI),+ lastExportTimestamp = db.getSetting(KEY_LAST_TIMESTAMP, "0")?.toLongOrNull() ?: 0L,+ permissionLost = db.getSetting(KEY_PERMISSION_LOST, "false") == "true",+ retentionCount = db.getSetting(KEY_RETENTION_COUNT, "10")?.toIntOrNull() ?: 10,+ lastFileName = db.getSetting(KEY_LAST_FILE_NAME),+ lastRowCount = db.getSetting(KEY_LAST_ROW_COUNT, "0")?.toIntOrNull() ?: 0,+ lastError = db.getSetting(KEY_LAST_ERROR)+ )+ }+ }++ fun saveEnabled(db: DatabaseHelper, value: Boolean) {+ db.saveSetting(KEY_ENABLED, value.toString())+ }++ fun saveLastExportTimestamp(db: DatabaseHelper, timestamp: Long) {+ db.saveSetting(KEY_LAST_TIMESTAMP, timestamp.toString())+ }++ fun savePermissionLost(db: DatabaseHelper, value: Boolean) {+ db.saveSetting(KEY_PERMISSION_LOST, value.toString())+ }++ fun saveLastResult(db: DatabaseHelper, fileName: String, rowCount: Int) {+ db.saveSetting(KEY_LAST_FILE_NAME, fileName)+ db.saveSetting(KEY_LAST_ROW_COUNT, rowCount.toString())+ db.saveSetting(KEY_LAST_ERROR, "")+ }++ fun saveLastError(db: DatabaseHelper, error: String) {+ db.saveSetting(KEY_LAST_ERROR, error)+ }++ /**+ * Calculates the next export timestamp based on interval and last export time.+ * Uses Calendar for monthly to handle variable month lengths.+ */+ fun nextExportTimestamp(): Long {+ if (!enabled || lastExportTimestamp == 0L) return 0L+ return when (interval) {+ "daily" -> lastExportTimestamp + (24 * 3600)+ "weekly" -> lastExportTimestamp + (168 * 3600)+ "monthly" -> {+ val cal = java.util.Calendar.getInstance()+ cal.timeInMillis = lastExportTimestamp * 1000+ cal.add(java.util.Calendar.MONTH, 1)+ cal.timeInMillis / 1000+ }+ else -> lastExportTimestamp + (24 * 3600)+ }+ }++ /**+ * Checks if an export is currently due based on interval timing.+ */+ fun isExportDue(): Boolean {+ if (lastExportTimestamp == 0L) return true // never exported, do it now+ val now = System.currentTimeMillis() / 1000+ return now >= nextExportTimestamp()+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.ktnew file mode 100644index 00000000..5ad01321--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportScheduler.kt@@ -0,0 +1,74 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.export++import android.content.Context+import androidx.work.Constraints+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import com.Colota.util.AppLogger+import java.util.concurrent.TimeUnit++/**+ * Manages scheduling/cancelling of periodic auto-export via WorkManager.+ *+ * Always schedules a daily (24h) worker. The worker itself checks+ * AutoExportConfig.isExportDue() to determine whether an export should+ * actually run (daily/weekly/monthly). This avoids unreliable long-interval+ * periodic work (e.g. 720h for monthly) and ensures calendar-accurate+ * monthly scheduling.+ */+object AutoExportScheduler {++ private const val TAG = "AutoExportScheduler"+ private const val WORK_NAME = "colota_auto_export"+ private const val CHECK_INTERVAL_HOURS = 24L++ /**+ * Schedules the daily auto-export check worker.+ */+ fun schedule(context: Context) {+ val constraints = Constraints.Builder()+ .setRequiresBatteryNotLow(true)+ .build()++ val request = PeriodicWorkRequestBuilder<AutoExportWorker>(+ CHECK_INTERVAL_HOURS, TimeUnit.HOURS+ )+ .setConstraints(constraints)+ .build()++ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ WORK_NAME,+ ExistingPeriodicWorkPolicy.UPDATE,+ request+ )++ AppLogger.i(TAG, "Scheduled auto-export check (every ${CHECK_INTERVAL_HOURS}h)")+ }++ /**+ * Enqueues a one-time auto-export that runs immediately, bypassing isExportDue().+ */+ fun runNow(context: Context) {+ val request = OneTimeWorkRequestBuilder<AutoExportWorker>()+ .addTag("colota_auto_export_now")+ .build()++ WorkManager.getInstance(context).enqueue(request)+ AppLogger.i(TAG, "Enqueued immediate auto-export")+ }++ /**+ * Cancels any scheduled auto-export work.+ */+ fun cancel(context: Context) {+ WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)+ AppLogger.i(TAG, "Cancelled auto-export")+ }+}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.ktnew file mode 100644index 00000000..65dfffec--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt@@ -0,0 +1,355 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.export++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.net.Uri+import android.os.Build+import android.provider.DocumentsContract+import androidx.core.app.NotificationCompat+import androidx.documentfile.provider.DocumentFile+import androidx.work.CoroutineWorker+import androidx.work.ForegroundInfo+import androidx.work.WorkerParameters+import com.Colota.bridge.LocationServiceModule+import com.Colota.data.DatabaseHelper+import com.Colota.util.AppLogger+import java.io.File+import java.io.IOException+import java.io.OutputStreamWriter++/**+ * WorkManager worker that performs automatic location data export.+ * Runs without the React Native JS runtime - uses native Kotlin converters.+ *+ * Scheduled as a daily periodic worker. On each run it checks whether an+ * export is actually due (daily/weekly/monthly) via AutoExportConfig.isExportDue().+ */+class AutoExportWorker(+ private val appContext: Context,+ params: WorkerParameters+) : CoroutineWorker(appContext, params) {++ companion object {+ private const val TAG = "AutoExportWorker"+ private const val CHANNEL_ID = "auto_export"+ private const val NOTIFICATION_ID = 9001+ private const val FOREGROUND_NOTIFICATION_ID = 9002+ private const val MAX_RETRIES = 3+ private const val PAGE_SIZE = 10_000+ }++ override suspend fun getForegroundInfo(): ForegroundInfo {+ ensureNotificationChannel()+ val notification = NotificationCompat.Builder(appContext, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_menu_save)+ .setContentTitle("Auto-Export")+ .setContentText("Exporting location data...")+ .setOngoing(true)+ .build()+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ ForegroundInfo(FOREGROUND_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)+ } else {+ ForegroundInfo(FOREGROUND_NOTIFICATION_ID, notification)+ }+ }++ override suspend fun doWork(): Result {+ if (runAttemptCount >= MAX_RETRIES) {+ AppLogger.e(TAG, "Auto-export failed after $MAX_RETRIES attempts, giving up")+ showNotification("Auto-Export Failed", "Export failed after multiple attempts. Please check your settings.")+ return Result.failure()+ }++ val db = DatabaseHelper.getInstance(appContext)+ val config = AutoExportConfig.from(db)++ if (config.uri == null) {+ AppLogger.e(TAG, "No export directory configured")+ return Result.failure()+ }++ // One-time "run now" workers skip the due check+ val isManualRun = tags.contains("colota_auto_export_now")+ if (!isManualRun && !config.isExportDue()) {+ AppLogger.d(TAG, "Export not yet due, skipping")+ return Result.success()+ }++ AppLogger.i(TAG, "Starting auto-export: format=${config.format}, mode=${config.mode}")++ // Promote to foreground service to prevent OS from killing long exports+ try {+ setForeground(getForegroundInfo())+ } catch (e: Exception) {+ // Some OEMs (Samsung, Xiaomi) throw when background restrictions are aggressive.+ // Continue with the export anyway - it may still complete.+ AppLogger.w(TAG, "Could not promote to foreground service: ${e.message}")+ }++ val ext = ExportConverters.extensionFor(config.format)+ val dirUri = Uri.parse(config.uri)+ val dateStr = java.text.SimpleDateFormat("yyyy-MM-dd_HHmm", java.util.Locale.US)+ .format(java.util.Date())+ val fileName = "colota_export_$dateStr$ext"++ // Write to temp file first for atomic writes+ val tempFile = File(appContext.cacheDir, "auto_export_temp$ext")++ return try {+ val rowCount = if (config.mode == "incremental" && config.lastExportTimestamp > 0) {+ val now = System.currentTimeMillis() / 1000+ writePaginatedExport(config.format, tempFile) { limit, offset ->+ db.getLocationsByDateRange(config.lastExportTimestamp, now, limit, offset)+ }+ } else {+ writePaginatedExport(config.format, tempFile) { limit, offset ->+ db.getLocationsChronological(limit, offset)+ }+ }++ // Check cancellation before copying+ if (isStopped) {+ tempFile.delete()+ AppLogger.w(TAG, "Auto-export cancelled")+ return Result.success()+ }++ if (rowCount == 0) {+ tempFile.delete()+ AppLogger.i(TAG, "No locations to export")+ showNotification("Auto-Export", "No new locations to export.")+ cleanupOldExports(dirUri, config.retentionCount)+ return Result.success()+ }++ // Atomic: copy completed temp file to SAF directory, then verify+ val tempSize = tempFile.length()+ val destDocFile = copyToSafDirectory(dirUri, fileName, tempFile, config.format)++ // Verify the destination file+ val destSize = destDocFile.length()+ if (!destDocFile.exists() || destSize == 0L) {+ tempFile.delete()+ throw IOException("Export verification failed: destination file missing or empty")+ }+ if (destSize != tempSize) {+ AppLogger.w(TAG, "Export size mismatch: temp=$tempSize, dest=$destSize")+ }++ tempFile.delete()++ val now = System.currentTimeMillis() / 1000+ config.saveLastExportTimestamp(db, now)++ // Clean up old export files beyond retention limit+ cleanupOldExports(dirUri, config.retentionCount)++ AppLogger.i(TAG, "Auto-export complete: $fileName ($rowCount locations)")+ config.saveLastResult(db, fileName, rowCount)+ showNotification(+ "Auto-Export Complete",+ "Exported $rowCount locations to $fileName",+ dirUri+ )+ sendExportBroadcast(true, fileName, rowCount, null)+ Result.success()+ } catch (e: SecurityException) {+ tempFile.delete()+ val error = "Directory permission lost"+ AppLogger.e(TAG, "Auto-export failed - permission denied", e)+ config.saveEnabled(db, false)+ config.savePermissionLost(db, true)+ config.saveLastError(db, error)+ showNotification("Auto-Export Failed", "$error. Please re-select the export directory.")+ sendExportBroadcast(false, null, 0, error)+ Result.failure()+ } catch (e: IllegalArgumentException) {+ tempFile.delete()+ val error = "Invalid configuration: ${e.message}"+ AppLogger.e(TAG, "Auto-export failed - invalid configuration", e)+ config.saveLastError(db, error)+ showNotification("Auto-Export Failed", "Invalid export configuration: ${e.message}")+ sendExportBroadcast(false, null, 0, error)+ Result.failure()+ } catch (e: IllegalStateException) {+ tempFile.delete()+ val error = "Directory access failed: ${e.message}"+ AppLogger.e(TAG, "Auto-export failed - directory access issue", e)+ config.saveLastError(db, error)+ showNotification("Auto-Export Failed", "Could not access export directory: ${e.message}")+ sendExportBroadcast(false, null, 0, error)+ Result.failure()+ } catch (e: IOException) {+ tempFile.delete()+ val error = "IO error: ${e.message}"+ AppLogger.e(TAG, "Auto-export failed - IO error, will retry", e)+ config.saveLastError(db, error)+ showNotification("Auto-Export Failed", "Could not save export file. Will retry.")+ sendExportBroadcast(false, null, 0, error)+ Result.retry()+ } catch (e: Exception) {+ tempFile.delete()+ val error = "Export failed: ${e.message}"+ AppLogger.e(TAG, "Auto-export failed", e)+ config.saveLastError(db, error)+ showNotification("Auto-Export Failed", "Could not save export file. Will retry.")+ sendExportBroadcast(false, null, 0, error)+ Result.retry()+ }+ }++ /**+ * Streams a paginated export to temp file, fetching rows via the provided lambda.+ * Checks isStopped between chunks for graceful cancellation.+ */+ private fun writePaginatedExport(+ format: String,+ tempFile: File,+ fetchPage: (limit: Int, offset: Int) -> List<Map<String, Any?>>+ ): Int {+ val coordsCollector = if (format == "kml") KmlCoordsCollector(appContext.cacheDir) else null+ var totalRows = 0+ var offset = 0++ coordsCollector.use {+ OutputStreamWriter(tempFile.outputStream(), Charsets.UTF_8).use { writer ->+ ExportConverters.writeHeader(writer, format)++ while (true) {+ if (isStopped) {+ AppLogger.w(TAG, "Auto-export cancelled during write")+ break+ }+ val page = fetchPage(PAGE_SIZE, offset)+ if (page.isEmpty()) break+ ExportConverters.writeRows(writer, format, page, offset, coordsCollector)+ totalRows += page.size+ offset += PAGE_SIZE+ }++ if (!isStopped) {+ ExportConverters.writeFooter(writer, format, coordsCollector)+ }+ }+ }++ if (isStopped) {+ tempFile.delete()+ return 0+ }++ return totalRows+ }++ /**+ * Copies temp file to SAF directory and returns the destination DocumentFile+ * for verification.+ */+ private fun copyToSafDirectory(+ dirUri: Uri,+ fileName: String,+ sourceFile: File,+ format: String+ ): DocumentFile {+ val resolver = appContext.contentResolver+ val mimeType = ExportConverters.mimeTypeFor(format)++ val docFile = DocumentFile.fromTreeUri(appContext, dirUri)+ ?.createFile(mimeType, fileName)+ ?: throw IllegalStateException("Failed to create file in selected directory")++ resolver.openOutputStream(docFile.uri)?.use { outStream ->+ sourceFile.inputStream().use { inStream ->+ inStream.copyTo(outStream)+ }+ } ?: throw IllegalStateException("Failed to open output stream")++ return docFile+ }++ /**+ * Deletes oldest export files beyond the retention limit.+ * Only touches files matching the colota_export_ prefix.+ */+ private fun cleanupOldExports(dirUri: Uri, retentionCount: Int) {+ if (retentionCount <= 0) return // 0 = unlimited++ try {+ val dir = DocumentFile.fromTreeUri(appContext, dirUri) ?: return+ val exportFiles = dir.listFiles()+ .filter { it.name?.startsWith("colota_export_") == true }+ .sortedBy { it.name } // lexicographic = chronological (timestamp in 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}")+ }++ AppLogger.i(TAG, "Cleaned up $toDelete old export files (keeping $retentionCount)")+ } catch (e: Exception) {+ AppLogger.w(TAG, "Export cleanup failed (non-critical): ${e.message}")+ }+ }++ private fun ensureNotificationChannel() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val channel = NotificationChannel(+ CHANNEL_ID,+ "Auto-Export",+ NotificationManager.IMPORTANCE_LOW+ ).apply {+ description = "Notifications for automatic data exports"+ }+ nm.createNotificationChannel(channel)+ }+ }++ private fun showNotification(title: String, message: String, directoryUri: Uri? = null) {+ ensureNotificationChannel()+ val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val builder = NotificationCompat.Builder(appContext, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_menu_save)+ .setContentTitle(title)+ .setContentText(message)+ .setAutoCancel(true)++ if (directoryUri != null) {+ try {+ val docUri = DocumentsContract.buildDocumentUriUsingTree(+ directoryUri,+ DocumentsContract.getTreeDocumentId(directoryUri)+ )+ val intent = Intent(Intent.ACTION_VIEW).apply {+ setDataAndType(docUri, DocumentsContract.Document.MIME_TYPE_DIR)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)+ }+ val pendingIntent = PendingIntent.getActivity(+ appContext, 0, intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ builder.setContentIntent(pendingIntent)+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not create directory open intent: ${e.message}")+ }+ }++ nm.notify(NOTIFICATION_ID, builder.build())+ }++ private fun sendExportBroadcast(success: Boolean, fileName: String?, rowCount: Int, error: String?) {+ LocationServiceModule.sendAutoExportEvent(success, fileName, rowCount, error)+ }+}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.ktnew file mode 100644index 00000000..f656f9e9--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportConverters.kt@@ -0,0 +1,304 @@+/**+ * 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.data.DatabaseHelper+import java.io.BufferedReader+import java.io.BufferedWriter+import java.io.File+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++/**+ * Native export converters for location data.+ * Used by AutoExportWorker (background) and manual export (via bridge).+ *+ * Streaming API (writeHeader/writeRows/writeFooter) for memory-efficient+ * chunked export. The in-memory convert() delegates to the streaming API.+ */+/**+ * File-backed collector for KML LineString coordinates.+ * Writes coordinates to a temp file instead of accumulating in memory,+ * preventing OOM on large exports.+ */+class KmlCoordsCollector(cacheDir: File) : AutoCloseable {+ private val tempFile = File(cacheDir, "kml_coords_temp.txt")+ private val writer = BufferedWriter(FileWriter(tempFile))++ fun add(coord: String) {+ writer.write(coord)+ writer.newLine()+ }++ fun writeTo(writer: Writer) {+ this.writer.close()+ BufferedReader(FileReader(tempFile)).use { reader ->+ var first = true+ reader.forEachLine { line ->+ if (!first) writer.write("\n ")+ writer.write(line)+ first = false+ }+ }+ }++ override fun close() {+ try { writer.close() } catch (_: Exception) {}+ tempFile.delete()+ }+}++object ExportConverters {++ private const val PAGE_SIZE = 10_000++ 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))+ }++ /** Formats a value as a valid JSON value (null-safe, properly escaped). */+ private fun jsonValue(value: Any?): String = when (value) {+ null -> "null"+ is String -> "\"${escapeJson(value)}\""+ else -> value.toString()+ }++ /** Escapes special characters for JSON string values. */+ 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)+ }+ }+ }++ // -- Shared chunked export to file --++ /**+ * Exports all locations from the database to a file using streaming chunks.+ * Shared between AutoExportWorker and the manual export bridge method.+ *+ * @return Number of rows exported+ */+ fun exportToFile(db: DatabaseHelper, format: String, outputFile: File, pageSize: Int = PAGE_SIZE): Int {+ val coordsCollector = if (format == "kml") KmlCoordsCollector(outputFile.parentFile!!) else null+ var totalRows = 0+ var offset = 0++ coordsCollector.use {+ OutputStreamWriter(outputFile.outputStream(), Charsets.UTF_8).use { writer ->+ writeHeader(writer, format)++ while (true) {+ val page = db.getLocationsChronological(pageSize, offset)+ if (page.isEmpty()) break+ writeRows(writer, format, page, offset, coordsCollector)+ totalRows += page.size+ offset += pageSize+ }++ writeFooter(writer, format, coordsCollector)+ }+ }+ return totalRows+ }++ // -- Streaming interface for chunked export --++ fun writeHeader(writer: Writer, format: String) {+ when (format) {+ "csv" -> writer.write("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n")+ "geojson" -> writer.write("{\n \"type\": \"FeatureCollection\",\n \"features\": [\n")+ "gpx" -> writer.write("""<?xml version="1.0" encoding="UTF-8"?>+<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">+ <metadata>+ <name>Colota Location Export</name>+ <time>${isoTime(System.currentTimeMillis() / 1000)}</time>+ </metadata>+ <trk>+ <name>Colota Track Export</name>+ <trkseg>+""")+ "kml" -> writer.write("""<?xml version="1.0" encoding="UTF-8"?>+<kml xmlns="http://www.opengis.net/kml/2.2">+ <Document>+ <name>Colota Location Export</name>+ <description>Exported tracks from Colota Tracking</description>+ <Style id="pathStyle">+ <LineStyle>+ <color>ff0000ff</color>+ <width>4</width>+ </LineStyle>+ </Style>+""")+ else -> throw IllegalArgumentException("Unknown export format: $format")+ }+ }++ /**+ * Write a chunk of rows. For KML, coordsCollector writes LineString+ * coordinates to a temp file to avoid unbounded memory growth.+ */+ fun writeRows(+ writer: Writer,+ format: String,+ rows: List<Map<String, Any?>>,+ globalOffset: Int,+ coordsCollector: KmlCoordsCollector?+ ) {+ when (format) {+ "csv" -> {+ rows.forEachIndexed { i, row ->+ val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)+ writer.write(listOf(+ globalOffset + i,+ ts,+ isoTime(ts),+ row["latitude"] ?: 0.0,+ row["longitude"] ?: 0.0,+ row["accuracy"] ?: 0,+ row["altitude"] ?: 0,+ row["speed"] ?: 0,+ row["battery"] ?: 0+ ).joinToString(","))+ writer.write("\n")+ }+ }+ "geojson" -> {+ rows.forEachIndexed { i, row ->+ if (globalOffset + i > 0) writer.write(",\n")+ val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)+ val lon = row["longitude"] ?: 0.0+ val lat = row["latitude"] ?: 0.0+ writer.write(""" {+ "type": "Feature",+ "geometry": {+ "type": "Point",+ "coordinates": [$lon, $lat]+ },+ "properties": {+ "id": ${globalOffset + i},+ "accuracy": ${jsonValue(row["accuracy"])},+ "altitude": ${jsonValue(row["altitude"])},+ "speed": ${jsonValue(row["speed"])},+ "battery": ${jsonValue(row["battery"])},+ "time": "${isoTime(ts)}"+ }+ }""")+ }+ }+ "gpx" -> {+ for (row in rows) {+ val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)+ val lat = (row["latitude"] as? Double)?.let { String.format(Locale.US, "%.6f", it) } ?: "0.000000"+ val lon = (row["longitude"] as? Double)?.let { String.format(Locale.US, "%.6f", it) } ?: "0.000000"+ writer.write(""" <trkpt lat="$lat" lon="$lon">+ <ele>${row["altitude"] ?: 0}</ele>+ <time>${isoTime(ts)}</time>+ <extensions>+ <accuracy>${row["accuracy"] ?: 0}</accuracy>+ <speed>${row["speed"] ?: 0}</speed>+ <battery>${row["battery"] ?: 0}</battery>+ </extensions>+ </trkpt>+""")+ }+ }+ "kml" -> {+ for (row in rows) {+ coordsCollector?.add("${row["longitude"] ?: 0},${row["latitude"] ?: 0},${row["altitude"] ?: 0}")+ val ts = (row["timestamp"] as? Long) ?: (System.currentTimeMillis() / 1000)+ writer.write(""" <Placemark>+ <TimeStamp><when>${isoTime(ts)}</when></TimeStamp>+ <description>Accuracy: ${row["accuracy"] ?: 0}m, Speed: ${row["speed"] ?: 0}m/s</description>+ <Point>+ <coordinates>${row["longitude"] ?: 0},${row["latitude"] ?: 0},${row["altitude"] ?: 0}</coordinates>+ </Point>+ </Placemark>+""")+ }+ }+ }+ }++ fun writeFooter(writer: Writer, format: String, coordsCollector: KmlCoordsCollector?) {+ when (format) {+ "csv" -> { /* no footer */ }+ "geojson" -> writer.write("\n ]\n}\n")+ "gpx" -> writer.write(""" </trkseg>+ </trk>+</gpx>+""")+ "kml" -> {+ writer.write(""" <Placemark>+ <name>Track Path</name>+ <styleUrl>#pathStyle</styleUrl>+ <LineString>+ <tessellate>1</tessellate>+ <coordinates>+ """)+ coordsCollector?.writeTo(writer)+ writer.write("""+ </coordinates>+ </LineString>+ </Placemark>+ </Document>+</kml>+""")+ }+ }+ }++ /**+ * Converts rows to the given format using the streaming API with a StringWriter.+ * Single source of truth for all format output.+ */+ fun convert(format: String, rows: List<Map<String, Any?>>): String {+ val sw = java.io.StringWriter()+ val coordsCollector = if (format == "kml") {+ // In-memory: use a temp list to collect coords (small datasets only)+ KmlCoordsCollector(java.io.File(System.getProperty("java.io.tmpdir")!!))+ } else null++ coordsCollector.use {+ writeHeader(sw, format)+ writeRows(sw, format, rows, 0, coordsCollector)+ writeFooter(sw, format, coordsCollector)+ }+ return sw.toString()+ }++ fun extensionFor(format: String): String = when (format) {+ "csv" -> ".csv"+ "geojson" -> ".geojson"+ "gpx" -> ".gpx"+ "kml" -> ".kml"+ else -> ".txt"+ }++ fun mimeTypeFor(format: String): String = when (format) {+ "csv" -> "text/csv"+ "geojson" -> "application/json"+ "gpx" -> "application/gpx+xml"+ "kml" -> "application/vnd.google-earth.kml+xml"+ else -> "text/plain"+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex 396d2f3d..eb7754e1 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -196,6 +196,34 @@ class LocationServiceModuleTest {assertFalse(LocationServiceModule.sendSyncProgressEvent(0, 0, 0))}+ // ========================================================================+ // sendAutoExportEvent+ // ========================================================================++ @Test+ fun `sendAutoExportEvent emits onAutoExportComplete on success`() {+ assertTrue(LocationServiceModule.sendAutoExportEvent(true, "export.geojson", 42, null))+ verify { mockEmitter.emit("onAutoExportComplete", any()) }+ }++ @Test+ fun `sendAutoExportEvent emits onAutoExportComplete on failure`() {+ assertTrue(LocationServiceModule.sendAutoExportEvent(false, null, 0, "IO error"))+ verify { mockEmitter.emit("onAutoExportComplete", any()) }+ }++ @Test+ fun `sendAutoExportEvent returns false when no context`() {+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))+ assertFalse(LocationServiceModule.sendAutoExportEvent(true, "file.csv", 10, null))+ }++ @Test+ fun `sendAutoExportEvent returns false when no catalyst`() {+ every { mockContext.hasActiveCatalystInstance() } returns false+ assertFalse(LocationServiceModule.sendAutoExportEvent(true, "file.csv", 10, null))+ }+// ========================================================================// sendPauseZoneEvent// ========================================================================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.ktnew file mode 100644index 00000000..dd8e4c05--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportConfigTest.kt@@ -0,0 +1,186 @@+package com.Colota.export++import io.mockk.mockk+import io.mockk.verify+import org.junit.Assert.*+import org.junit.Test++class AutoExportConfigTest {++ // --- isExportDue ---++ @Test+ fun `isExportDue returns true when never exported`() {+ val config = AutoExportConfig(enabled = true, lastExportTimestamp = 0L)+ assertTrue(config.isExportDue())+ }++ @Test+ fun `isExportDue returns true when daily interval has passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "daily",+ lastExportTimestamp = now - (25 * 3600) // 25 hours ago+ )+ assertTrue(config.isExportDue())+ }++ @Test+ fun `isExportDue returns false when daily interval has not passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "daily",+ lastExportTimestamp = now - (23 * 3600) // 23 hours ago+ )+ assertFalse(config.isExportDue())+ }++ @Test+ fun `isExportDue returns true when weekly interval has passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "weekly",+ lastExportTimestamp = now - (169 * 3600) // 169 hours ago (> 168)+ )+ assertTrue(config.isExportDue())+ }++ @Test+ fun `isExportDue returns false when weekly interval has not passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "weekly",+ lastExportTimestamp = now - (167 * 3600) // 167 hours ago (< 168)+ )+ assertFalse(config.isExportDue())+ }++ @Test+ fun `isExportDue returns true when monthly interval has passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "monthly",+ lastExportTimestamp = now - (32L * 24 * 3600) // 32 days ago+ )+ assertTrue(config.isExportDue())+ }++ @Test+ fun `isExportDue returns false when monthly interval has not passed`() {+ val now = System.currentTimeMillis() / 1000+ val config = AutoExportConfig(+ enabled = true,+ interval = "monthly",+ lastExportTimestamp = now - (27L * 24 * 3600) // 27 days ago+ )+ assertFalse(config.isExportDue())+ }++ // --- nextExportTimestamp ---++ @Test+ fun `nextExportTimestamp returns 0 when disabled`() {+ val config = AutoExportConfig(enabled = false, lastExportTimestamp = 1000L)+ assertEquals(0L, config.nextExportTimestamp())+ }++ @Test+ fun `nextExportTimestamp returns 0 when never exported`() {+ val config = AutoExportConfig(enabled = true, lastExportTimestamp = 0L)+ assertEquals(0L, config.nextExportTimestamp())+ }++ @Test+ fun `nextExportTimestamp adds 24h for daily`() {+ val last = 1700000000L+ val config = AutoExportConfig(+ enabled = true,+ interval = "daily",+ lastExportTimestamp = last+ )+ assertEquals(last + (24 * 3600), config.nextExportTimestamp())+ }++ @Test+ fun `nextExportTimestamp adds 168h for weekly`() {+ val last = 1700000000L+ val config = AutoExportConfig(+ enabled = true,+ interval = "weekly",+ lastExportTimestamp = last+ )+ assertEquals(last + (168 * 3600), config.nextExportTimestamp())+ }++ @Test+ fun `nextExportTimestamp adds one month for monthly`() {+ // Jan 15 2024 -> Feb 15 2024+ val jan15 = 1705276800L // 2024-01-15 00:00:00 UTC+ val config = AutoExportConfig(+ enabled = true,+ interval = "monthly",+ lastExportTimestamp = jan15+ )+ val next = config.nextExportTimestamp()+ // Should be approximately 31 days later (Feb 15)+ val diff = next - jan15+ assertTrue("Monthly interval should be between 28 and 31 days, was ${diff / 86400} days",+ diff in (28L * 86400)..(31L * 86400))+ }++ @Test+ fun `nextExportTimestamp defaults to 24h for unknown interval`() {+ val last = 1700000000L+ val config = AutoExportConfig(+ enabled = true,+ interval = "unknown",+ lastExportTimestamp = last+ )+ assertEquals(last + (24 * 3600), config.nextExportTimestamp())+ }++ // --- defaults ---++ @Test+ fun `default config is disabled with sensible defaults`() {+ val config = AutoExportConfig()+ assertFalse(config.enabled)+ assertEquals("geojson", config.format)+ assertEquals("daily", config.interval)+ assertEquals("all", config.mode)+ assertNull(config.uri)+ assertEquals(0L, config.lastExportTimestamp)+ assertFalse(config.permissionLost)+ assertEquals(10, config.retentionCount)+ assertNull(config.lastFileName)+ assertEquals(0, config.lastRowCount)+ assertNull(config.lastError)+ }++ // --- saveLastResult / saveLastError ---++ @Test+ fun `saveLastResult stores fileName, rowCount, and clears error`() {+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ val config = AutoExportConfig()+ config.saveLastResult(db, "colota_export_2026-03-10_1200.geojson", 42)++ verify { db.saveSetting("autoExportLastFileName", "colota_export_2026-03-10_1200.geojson") }+ verify { db.saveSetting("autoExportLastRowCount", "42") }+ verify { db.saveSetting("autoExportLastError", "") }+ }++ @Test+ fun `saveLastError stores error message`() {+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ val config = AutoExportConfig()+ config.saveLastError(db, "IO error: disk full")++ verify { db.saveSetting("autoExportLastError", "IO error: disk full") }+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.ktnew file mode 100644index 00000000..0b97b374--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportSchedulerTest.kt@@ -0,0 +1,51 @@+package com.Colota.export++import com.Colota.util.AppLogger+import io.mockk.*+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test++/**+ * Tests for AutoExportScheduler constants and configuration.+ * WorkManager integration is verified at the integration/instrumented test level;+ * these tests validate the scheduler's public contract and constants.+ */+class AutoExportSchedulerTest {++ @Before+ fun setUp() {+ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ }++ @After+ fun tearDown() {+ unmockkObject(AppLogger)+ }++ @Test+ fun `work name constant is colota_auto_export`() {+ val field = AutoExportScheduler::class.java.getDeclaredField("WORK_NAME")+ field.isAccessible = true+ assertEquals("colota_auto_export", field.get(null))+ }++ @Test+ fun `check interval is 24 hours`() {+ val field = AutoExportScheduler::class.java.getDeclaredField("CHECK_INTERVAL_HOURS")+ field.isAccessible = true+ assertEquals(24L, field.getLong(null))+ }++ @Test+ fun `scheduler is a singleton object`() {+ // Verify AutoExportScheduler is an object (singleton)+ val instance1 = AutoExportScheduler+ val instance2 = AutoExportScheduler+ assertSame(instance1, instance2)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerTest.ktnew file mode 100644index 00000000..3540f2a7--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/AutoExportWorkerTest.kt@@ -0,0 +1,152 @@+package com.Colota.export++import com.Colota.util.AppLogger+import io.mockk.*+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder++class AutoExportWorkerTest {++ @get:Rule+ val tempFolder = TemporaryFolder()++ @Before+ fun setUp() {+ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ every { AppLogger.e(any(), any()) } just Runs+ every { AppLogger.e(any(), any(), any()) } just Runs+ }++ @After+ fun tearDown() {+ unmockkObject(AppLogger)+ }++ // --- exportToFile ---++ @Test+ fun `exportToFile writes CSV to temp file`() {+ val tempFile = tempFolder.newFile("test_export.csv")+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ val sampleRows = listOf(+ mapOf<String, Any?>(+ "latitude" to 52.52, "longitude" to 13.405, "accuracy" to 10,+ "altitude" to 34, "speed" to 1.2, "battery" to 85, "timestamp" to 1700000000L+ )+ )+ every { db.getLocationsChronological(any(), eq(0)) } returns sampleRows+ every { db.getLocationsChronological(any(), eq(10000)) } returns emptyList()++ val rows = ExportConverters.exportToFile(db, "csv", tempFile)++ assertEquals(1, rows)+ val content = tempFile.readText()+ assertTrue(content.startsWith("id,timestamp,"))+ assertTrue(content.contains("52.52"))+ }++ @Test+ fun `exportToFile returns 0 when no locations`() {+ val tempFile = tempFolder.newFile("test_empty.csv")+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ every { db.getLocationsChronological(any(), any()) } returns emptyList()++ val rows = ExportConverters.exportToFile(db, "csv", tempFile)+ assertEquals(0, rows)+ }++ @Test+ fun `exportToFile produces valid GeoJSON`() {+ val tempFile = tempFolder.newFile("test_export.geojson")+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ val sampleRows = listOf(+ mapOf<String, Any?>(+ "latitude" to 52.52, "longitude" to 13.405, "accuracy" to 10,+ "altitude" to 34, "speed" to 1.2, "battery" to 85, "timestamp" to 1700000000L+ )+ )+ every { db.getLocationsChronological(any(), eq(0)) } returns sampleRows+ every { db.getLocationsChronological(any(), eq(10000)) } returns emptyList()++ ExportConverters.exportToFile(db, "geojson", tempFile)++ val content = tempFile.readText()+ assertTrue(content.contains("FeatureCollection"))+ assertTrue(content.contains("[13.405, 52.52]"))+ assertTrue(content.trimEnd().endsWith("}"))+ }++ @Test+ fun `exportToFile produces valid KML with LineString`() {+ val tempFile = tempFolder.newFile("test_export.kml")+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)+ val sampleRows = listOf(+ mapOf<String, Any?>(+ "latitude" to 52.52, "longitude" to 13.405, "accuracy" to 10,+ "altitude" to 34, "speed" to 1.2, "battery" to 85, "timestamp" to 1700000000L+ )+ )+ every { db.getLocationsChronological(any(), eq(0)) } returns sampleRows+ every { db.getLocationsChronological(any(), eq(10000)) } returns emptyList()++ ExportConverters.exportToFile(db, "kml", tempFile)++ val content = tempFile.readText()+ assertTrue(content.contains("<LineString>"))+ assertTrue(content.contains("13.405,52.52,34"))+ assertTrue(content.trimEnd().endsWith("</kml>"))+ }++ @Test+ fun `exportToFile paginates across multiple pages`() {+ val tempFile = tempFolder.newFile("test_paginated.csv")+ val db = mockk<com.Colota.data.DatabaseHelper>(relaxed = true)++ val page = (0 until 100).map { i ->+ mapOf<String, Any?>(+ "latitude" to 52.0 + i * 0.001, "longitude" to 13.0,+ "accuracy" to 10, "altitude" to 0, "speed" to 0,+ "battery" to 50, "timestamp" to (1700000000L + i)+ )+ }++ every { db.getLocationsChronological(100, 0) } returns page+ every { db.getLocationsChronological(100, 100) } returns emptyList()++ val rows = ExportConverters.exportToFile(db, "csv", tempFile, pageSize = 100)++ assertEquals(100, rows)+ verify(exactly = 1) { db.getLocationsChronological(100, 0) }+ verify(exactly = 1) { db.getLocationsChronological(100, 100) }+ }++ // --- JSON escaping ---++ @Test+ fun `GeoJSON escapes double quotes in string values`() {+ val rows = listOf(mapOf<String, Any?>(+ "latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L,+ "accuracy" to "test\"quoted\"value"+ ))+ val json = ExportConverters.convert("geojson", rows)+ assertTrue(json.contains("test\\\"quoted\\\"value"))+ }++ @Test+ fun `GeoJSON escapes backslashes and control characters`() {+ val rows = listOf(mapOf<String, Any?>(+ "latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L,+ "accuracy" to "path\\to\\file\nnewline"+ ))+ val json = ExportConverters.convert("geojson", rows)+ assertTrue(json.contains("path\\\\to\\\\file"))+ assertTrue(json.contains("\\n"))+ }+}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.ktnew file mode 100644index 00000000..b4a54d1c--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportConvertersTest.kt@@ -0,0 +1,316 @@+package com.Colota.export++import org.junit.Assert.*+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import java.io.StringWriter++class ExportConvertersTest {++ @get:Rule+ val tempFolder = TemporaryFolder()++ private val sampleRows: List<Map<String, Any?>> = listOf(+ mapOf("latitude" to 52.52, "longitude" to 13.405, "accuracy" to 10, "altitude" to 34, "speed" to 1.2, "battery" to 85, "timestamp" to 1700000000L),+ mapOf("latitude" to 48.8566, "longitude" to 2.3522, "accuracy" to 15, "altitude" to 40, "speed" to 0.5, "battery" to 72, "timestamp" to 1700003600L)+ )++ // --- extensionFor ---++ @Test+ fun `extensionFor returns correct extensions`() {+ assertEquals(".csv", ExportConverters.extensionFor("csv"))+ assertEquals(".geojson", ExportConverters.extensionFor("geojson"))+ assertEquals(".gpx", ExportConverters.extensionFor("gpx"))+ assertEquals(".kml", ExportConverters.extensionFor("kml"))+ assertEquals(".txt", ExportConverters.extensionFor("unknown"))+ }++ // --- mimeTypeFor ---++ @Test+ fun `mimeTypeFor returns correct mime types`() {+ assertEquals("text/csv", ExportConverters.mimeTypeFor("csv"))+ assertEquals("application/json", ExportConverters.mimeTypeFor("geojson"))+ assertEquals("application/gpx+xml", ExportConverters.mimeTypeFor("gpx"))+ assertEquals("application/vnd.google-earth.kml+xml", ExportConverters.mimeTypeFor("kml"))+ assertEquals("text/plain", ExportConverters.mimeTypeFor("unknown"))+ }++ // --- convert (delegates to streaming API) ---++ @Test+ fun `convert dispatches to correct format`() {+ val csv = ExportConverters.convert("csv", sampleRows)+ assertTrue(csv.startsWith("id,timestamp,"))++ val geojson = ExportConverters.convert("geojson", sampleRows)+ assertTrue(geojson.contains("FeatureCollection"))++ val gpx = ExportConverters.convert("gpx", sampleRows)+ assertTrue(gpx.contains("<gpx"))++ val kml = ExportConverters.convert("kml", sampleRows)+ assertTrue(kml.contains("<kml"))+ }++ @Test(expected = IllegalArgumentException::class)+ fun `convert throws for unknown format`() {+ ExportConverters.convert("xml", sampleRows)+ }++ // --- CSV ---++ @Test+ fun `convert CSV contains header row`() {+ val csv = ExportConverters.convert("csv", sampleRows)+ val lines = csv.lines()+ assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery", lines[0])+ }++ @Test+ fun `convert CSV contains correct data rows`() {+ val csv = ExportConverters.convert("csv", sampleRows)+ val lines = csv.lines().filter { it.isNotBlank() }+ assertEquals(3, lines.size) // header + 2 data rows+ assertTrue(lines[1].startsWith("0,1700000000,"))+ assertTrue(lines[1].contains("52.52"))+ assertTrue(lines[1].contains("13.405"))+ }++ @Test+ fun `convert CSV handles empty input`() {+ val csv = ExportConverters.convert("csv", emptyList())+ val lines = csv.lines().filter { it.isNotBlank() }+ assertEquals(1, lines.size) // header only+ }++ // --- GeoJSON ---++ @Test+ fun `convert GeoJSON produces valid structure`() {+ val json = ExportConverters.convert("geojson", sampleRows)+ assertTrue(json.contains("\"type\": \"FeatureCollection\""))+ assertTrue(json.contains("\"type\": \"Feature\""))+ assertTrue(json.contains("\"type\": \"Point\""))+ }++ @Test+ fun `convert GeoJSON contains coordinates in lon-lat order`() {+ val json = ExportConverters.convert("geojson", sampleRows)+ assertTrue(json.contains("[13.405, 52.52]"))+ }++ @Test+ fun `convert GeoJSON contains properties`() {+ val json = ExportConverters.convert("geojson", sampleRows)+ assertTrue(json.contains("\"accuracy\": 10"))+ assertTrue(json.contains("\"speed\": 1.2"))+ assertTrue(json.contains("\"battery\": 85"))+ }++ // --- GPX ---++ @Test+ fun `convert GPX contains XML header and gpx root`() {+ val gpx = ExportConverters.convert("gpx", sampleRows)+ assertTrue(gpx.startsWith("<?xml version=\"1.0\""))+ assertTrue(gpx.contains("<gpx version=\"1.1\""))+ }++ @Test+ fun `convert GPX contains track points with coordinates`() {+ val gpx = ExportConverters.convert("gpx", sampleRows)+ assertTrue(gpx.contains("<trkpt lat=\"52.520000\" lon=\"13.405000\">"))+ assertTrue(gpx.contains("<trkpt lat=\"48.856600\" lon=\"2.352200\">"))+ }++ @Test+ fun `convert GPX contains elevation and time`() {+ val gpx = ExportConverters.convert("gpx", sampleRows)+ assertTrue(gpx.contains("<ele>34</ele>"))+ assertTrue(gpx.contains("<time>"))+ }++ // --- KML ---++ @Test+ fun `convert KML contains XML header and kml root`() {+ val kml = ExportConverters.convert("kml", sampleRows)+ assertTrue(kml.startsWith("<?xml version=\"1.0\""))+ assertTrue(kml.contains("<kml xmlns="))+ }++ @Test+ fun `convert KML contains LineString coordinates`() {+ val kml = ExportConverters.convert("kml", sampleRows)+ assertTrue(kml.contains("<LineString>"))+ assertTrue(kml.contains("13.405,52.52,34"))+ assertTrue(kml.contains("2.3522,48.8566,40"))+ }++ @Test+ fun `convert KML contains individual placemarks`() {+ val kml = ExportConverters.convert("kml", sampleRows)+ val placemarkCount = Regex("<Placemark>").findAll(kml).count()+ assertEquals(3, placemarkCount) // 1 track + 2 point placemarks+ }++ // --- JSON escaping ---++ @Test+ fun `convert GeoJSON escapes quotes in string values`() {+ val rows = listOf(mapOf<String, Any?>(+ "latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L,+ "accuracy" to "test\"quoted\"value"+ ))+ val json = ExportConverters.convert("geojson", rows)+ assertTrue(json.contains("test\\\"quoted\\\"value"))+ }++ @Test+ fun `convert GeoJSON escapes backslashes`() {+ val rows = listOf(mapOf<String, Any?>(+ "latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L,+ "accuracy" to "path\\to\\file"+ ))+ val json = ExportConverters.convert("geojson", rows)+ assertTrue(json.contains("path\\\\to\\\\file"))+ }++ @Test+ fun `convert GeoJSON escapes newlines and control characters`() {+ val rows = listOf(mapOf<String, Any?>(+ "latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L,+ "accuracy" to "line1\nline2\ttab"+ ))+ val json = ExportConverters.convert("geojson", rows)+ assertTrue(json.contains("line1\\nline2\\ttab"))+ }++ // --- Null handling ---++ @Test+ fun `convert handles missing fields gracefully`() {+ val sparse = listOf(mapOf<String, Any?>("latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L))++ // Should not throw+ for (format in listOf("csv", "geojson", "gpx", "kml")) {+ ExportConverters.convert(format, sparse)+ }+ }++ // --- Streaming interface ---++ private fun streamToString(format: String, rows: List<Map<String, Any?>>, chunks: List<List<Map<String, Any?>>>? = null): String {+ val writer = StringWriter()+ val coordsCollector = if (format == "kml") KmlCoordsCollector(tempFolder.root) else null+ coordsCollector.use {+ ExportConverters.writeHeader(writer, format)+ if (chunks != null) {+ var offset = 0+ for (chunk in chunks) {+ ExportConverters.writeRows(writer, format, chunk, offset, coordsCollector)+ offset += chunk.size+ }+ } else {+ ExportConverters.writeRows(writer, format, rows, 0, coordsCollector)+ }+ ExportConverters.writeFooter(writer, format, coordsCollector)+ }+ return writer.toString()+ }++ @Test+ fun `streaming CSV produces header and data rows`() {+ val result = streamToString("csv", sampleRows)+ val lines = result.lines().filter { it.isNotBlank() }+ assertEquals("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery", lines[0])+ assertEquals(3, lines.size)+ assertTrue(lines[1].startsWith("0,1700000000,"))+ assertTrue(lines[1].contains("52.52"))+ }++ @Test+ fun `streaming GeoJSON produces valid structure`() {+ val result = streamToString("geojson", sampleRows)+ assertTrue(result.contains("\"type\": \"FeatureCollection\""))+ assertTrue(result.contains("\"type\": \"Feature\""))+ assertTrue(result.contains("[13.405, 52.52]"))+ }++ @Test+ fun `streaming GPX produces valid XML`() {+ val result = streamToString("gpx", sampleRows)+ assertTrue(result.contains("<?xml version=\"1.0\""))+ assertTrue(result.contains("<trkpt lat=\"52.520000\" lon=\"13.405000\">"))+ assertTrue(result.contains("</trkseg>"))+ assertTrue(result.trimEnd().endsWith("</gpx>"))+ }++ @Test+ fun `streaming KML collects coords and writes LineString in footer`() {+ val result = streamToString("kml", sampleRows)+ assertTrue(result.contains("<kml xmlns="))+ assertTrue(result.contains("<LineString>"))+ assertTrue(result.contains("13.405,52.52,34"))+ // Point placemarks written inline+ val placemarkCount = Regex("<Placemark>").findAll(result).count()+ assertEquals(3, placemarkCount) // 2 point placemarks + 1 LineString placemark+ assertTrue(result.trimEnd().endsWith("</kml>"))+ }++ @Test+ fun `streaming with multiple chunks produces correct output`() {+ val chunk1 = listOf(sampleRows[0])+ val chunk2 = listOf(sampleRows[1])++ val csvResult = streamToString("csv", emptyList(), chunks = listOf(chunk1, chunk2))+ val csvLines = csvResult.lines().filter { it.isNotBlank() }+ assertEquals(3, csvLines.size)+ assertTrue(csvLines[1].startsWith("0,"))+ assertTrue(csvLines[2].startsWith("1,"))++ val geojsonResult = streamToString("geojson", emptyList(), chunks = listOf(chunk1, chunk2))+ assertTrue(geojsonResult.contains("\"id\": 0"))+ assertTrue(geojsonResult.contains("\"id\": 1"))++ val gpxResult = streamToString("gpx", emptyList(), chunks = listOf(chunk1, chunk2))+ assertTrue(gpxResult.contains("lat=\"52.520000\""))+ assertTrue(gpxResult.contains("lat=\"48.856600\""))++ val kmlResult = streamToString("kml", emptyList(), chunks = listOf(chunk1, chunk2))+ assertTrue(kmlResult.contains("13.405,52.52,34"))+ assertTrue(kmlResult.contains("2.3522,48.8566,40"))+ }++ @Test+ fun `streaming with empty rows produces valid structure`() {+ for (format in listOf("csv", "geojson", "gpx", "kml")) {+ val result = streamToString(format, emptyList())+ assertTrue("$format should produce non-empty output", result.isNotBlank())+ }++ val csvResult = streamToString("csv", emptyList())+ val csvLines = csvResult.lines().filter { it.isNotBlank() }+ assertEquals(1, csvLines.size) // header only++ val geojsonResult = streamToString("geojson", emptyList())+ assertTrue(geojsonResult.contains("FeatureCollection"))+ }++ @Test+ fun `streaming handles missing fields gracefully`() {+ val sparse = listOf(mapOf<String, Any?>("latitude" to 52.0, "longitude" to 13.0, "timestamp" to 1700000000L))+ for (format in listOf("csv", "geojson", "gpx", "kml")) {+ // Should not throw+ streamToString(format, sparse)+ }+ }++ @Test(expected = IllegalArgumentException::class)+ fun `writeHeader throws for unknown format`() {+ ExportConverters.writeHeader(StringWriter(), "xml")+ }+}diff --git a/apps/mobile/src/screens/AutoExportScreen.tsx b/apps/mobile/src/screens/AutoExportScreen.tsxnew file mode 100644index 00000000..775dbcb8--- /dev/null+++ b/apps/mobile/src/screens/AutoExportScreen.tsx@@ -0,0 +1,599 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { useState, useCallback, useEffect } from "react"+import { useFocusEffect } from "@react-navigation/native"+import { Text, StyleSheet, Switch, View, ScrollView, Pressable, DeviceEventEmitter } from "react-native"+import { FolderOpen, CheckCircle, Share2, AlertTriangle } from "lucide-react-native"+import {+ Container,+ Card,+ SectionTitle,+ Divider,+ FormatSelector,+ ChipGroup,+ RadioDot,+ FloatingSaveIndicator,+ SettingRow,+ Button+} from "../components"+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 { fonts } from "../styles/typography"+import { logger } from "../utils/logger"+import { showAlert } from "../services/modalService"++type ExportInterval = "daily" | "weekly" | "monthly"+type ExportMode = "all" | "incremental"++type ExportFile = {+ name: string+ size: number+ lastModified: number+ uri: string+}++const INTERVAL_OPTIONS: readonly { value: ExportInterval; label: string }[] = [+ { value: "daily", label: "Daily" },+ { value: "weekly", label: "Weekly" },+ { value: "monthly", label: "Monthly" }+]++const MODE_OPTIONS: { key: ExportMode; label: string; description: string }[] = [+ { key: "all", label: "All data", description: "Export all stored locations each time" },+ { key: "incremental", label: "Since last export", description: "Only export new locations" }+]++const RETENTION_OPTIONS: readonly { value: string; label: string }[] = [+ { value: "1", label: "1 file" },+ { value: "5", label: "5 files" },+ { value: "10", label: "10 files" },+ { value: "30", label: "30 files" },+ { value: "0", label: "Unlimited" }+]++function formatFileSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`+}++export function AutoExportScreen(_props: ScreenProps) {+ const { colors } = useTheme()+ const [enabled, setEnabled] = useState(false)+ const [format, setFormat] = useState<ExportFormat>("geojson")+ const [interval, setInterval] = useState<ExportInterval>("daily")+ const [mode, setMode] = useState<ExportMode>("all")+ const [directoryUri, setDirectoryUri] = useState<string | null>(null)+ const [lastExport, setLastExport] = useState<number>(0)+ const [nextExport, setNextExport] = useState<number>(0)+ const [fileCount, setFileCount] = useState<number>(0)+ const [retentionCount, setRetentionCount] = useState<number>(10)+ const [lastFileName, setLastFileName] = useState<string | null>(null)+ const [lastRowCount, setLastRowCount] = useState<number>(0)+ const [lastError, setLastError] = useState<string | null>(null)+ const [exportFiles, setExportFiles] = useState<ExportFile[]>([])+ const [loading, setLoading] = useState(true)+ const [exporting, setExporting] = useState(false)+ const [saving, setSaving] = useState(false)+ const [saveSuccess, setSaveSuccess] = useState(false)+ const successTimeout = useTimeout()+ const statusRefreshTimeout = useTimeout()++ const loadStatus = useCallback(async () => {+ try {+ const status = await NativeLocationService.getAutoExportStatus()+ setEnabled(status.enabled)+ setFormat((status.format as ExportFormat) || "geojson")+ setInterval((status.interval as ExportInterval) || "daily")+ setMode((status.mode as ExportMode) || "all")+ setDirectoryUri(status.uri)+ setLastExport(status.lastExportTimestamp)+ setNextExport(status.nextExportTimestamp)+ setFileCount(status.fileCount)+ setRetentionCount(status.retentionCount ?? 10)+ setLastFileName(status.lastFileName || null)+ setLastRowCount(status.lastRowCount ?? 0)+ setLastError(status.lastError || null)++ const permissionLost = await NativeLocationService.getSetting("autoExportPermissionLost")+ if (permissionLost === "true") {+ await NativeLocationService.saveSetting("autoExportPermissionLost", "false")+ showAlert(+ "Export Directory Access Lost",+ "The app lost access to the export directory. Please re-select it to resume auto-exports.",+ "warning"+ )+ }+ } catch (error) {+ logger.error("[AutoExportScreen] Failed to load status:", error)+ } finally {+ setLoading(false)+ }+ }, [])++ const loadExportFiles = useCallback(async () => {+ try {+ const files = await NativeLocationService.getExportFiles()+ setExportFiles(files)+ } catch (error) {+ logger.error("[AutoExportScreen] Failed to load export files:", error)+ }+ }, [])++ useFocusEffect(+ useCallback(() => {+ loadStatus()+ loadExportFiles()+ }, [loadStatus, loadExportFiles])+ )++ // Listen for real-time export completion events+ useEffect(() => {+ const listener = DeviceEventEmitter.addListener(+ "onAutoExportComplete",+ (event: { success: boolean; fileName: string | null; rowCount: number; error: string | null }) => {+ if (event.success) {+ setLastFileName(event.fileName)+ setLastRowCount(event.rowCount)+ setLastError(null)+ showAlert("Export Complete", `Exported ${event.rowCount} locations to ${event.fileName}`, "success")+ } else {+ setLastError(event.error)+ showAlert("Export Failed", event.error || "Unknown error", "error")+ }+ loadStatus()+ loadExportFiles()+ }+ )+ return () => listener.remove()+ }, [loadStatus, loadExportFiles])++ const saveSetting = useCallback(+ async (key: string, value: string) => {+ setSaving(true)+ try {+ await NativeLocationService.saveSetting(key, value)+ setSaving(false)+ setSaveSuccess(true)+ successTimeout.set(() => setSaveSuccess(false), 2000)+ } catch (error) {+ setSaving(false)+ logger.error("[AutoExportScreen] Save failed:", error)+ showAlert("Error", "Failed to save setting. Please try again.", "error")+ }+ },+ [successTimeout]+ )++ const handleToggle = useCallback(+ async (value: boolean) => {+ if (value && !directoryUri) {+ showAlert("No Directory", "Please select an export directory first.", "info")+ return+ }++ try {+ await NativeLocationService.saveSetting("autoExportEnabled", value.toString())++ if (value) {+ await NativeLocationService.scheduleAutoExport()+ } else {+ await NativeLocationService.cancelAutoExport()+ }++ setEnabled(value)+ await loadStatus()+ } catch (error) {+ logger.error("[AutoExportScreen] Toggle failed:", error)+ await loadStatus()+ showAlert("Error", "Failed to update auto-export schedule. Please check the export directory.", "error")+ }+ },+ [directoryUri, loadStatus]+ )++ const handleFormatChange = useCallback(+ async (newFormat: ExportFormat) => {+ setFormat(newFormat)+ await saveSetting("autoExportFormat", newFormat)+ },+ [saveSetting]+ )++ const handleIntervalChange = useCallback(+ async (newInterval: ExportInterval) => {+ setInterval(newInterval)+ await saveSetting("autoExportInterval", newInterval)+ },+ [saveSetting]+ )++ const handleModeChange = useCallback(+ async (newMode: ExportMode) => {+ setMode(newMode)+ await saveSetting("autoExportMode", newMode)+ },+ [saveSetting]+ )++ const handleRetentionChange = useCallback(+ async (newRetention: string) => {+ const count = parseInt(newRetention, 10)+ setRetentionCount(count)+ await saveSetting("autoExportRetentionCount", newRetention)+ },+ [saveSetting]+ )++ const handlePickDirectory = useCallback(async () => {+ try {+ const uri = await NativeLocationService.pickExportDirectory()+ if (uri) {+ setDirectoryUri(uri)+ await saveSetting("autoExportUri", uri)+ loadExportFiles()+ }+ } catch (error) {+ logger.error("[AutoExportScreen] Directory pick failed:", error)+ showAlert("Error", "Failed to select directory.", "error")+ }+ }, [saveSetting, loadExportFiles])++ const handleExportNow = useCallback(async () => {+ if (!directoryUri) {+ showAlert("No Directory", "Please select an export directory first.", "info")+ return+ }+ setExporting(true)+ try {+ await NativeLocationService.runAutoExportNow()+ showAlert("Export Started", "Export is running in the background. The status will update when complete.", "info")+ statusRefreshTimeout.set(() => loadStatus(), 3000)+ } catch (error) {+ logger.error("[AutoExportScreen] Export now failed:", error)+ showAlert("Error", "Failed to start export.", "error")+ } finally {+ setExporting(false)+ }+ }, [directoryUri, loadStatus, statusRefreshTimeout])++ const handleShareFile = useCallback(async (file: ExportFile) => {+ const ext = file.name.split(".").pop() || ""+ const formatKey = Object.keys(EXPORT_FORMATS).find(+ (k) => EXPORT_FORMATS[k as ExportFormat].extension === `.${ext}`+ ) as ExportFormat | undefined+ const mimeType = formatKey ? EXPORT_FORMATS[formatKey].mimeType : "application/octet-stream"++ try {+ await NativeLocationService.shareExportFile(file.uri, mimeType)+ } catch (error) {+ logger.error("[AutoExportScreen] Share failed:", error)+ showAlert("Error", "Failed to share file.", "error")+ }+ }, [])++ const formatTimestamp = (timestamp: number): string => {+ if (timestamp === 0) return "Never"+ return new Date(timestamp * 1000).toLocaleString()+ }++ if (loading)+ return (+ <Container>+ <View />+ </Container>+ )++ return (+ <Container>+ <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.text }]}>Auto-Export</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>+ Automatically export your location data on a schedule+ </Text>+ </View>++ {/* Enable Toggle */}+ <Card>+ <SettingRow+ label="Enable Auto-Export"+ hint={enabled ? "Auto-Exports are scheduled" : "Auto-Exports are disabled"}+ >+ <Switch+ value={enabled}+ onValueChange={handleToggle}+ trackColor={{ false: colors.border, true: colors.primary + "80" }}+ thumbColor={enabled ? colors.primary : colors.border}+ />+ </SettingRow>+ </Card>++ {/* Export Directory */}+ <View style={styles.section}>+ <SectionTitle>Export Directory</SectionTitle>+ <Card>+ <Pressable+ style={({ pressed }) => [styles.directoryRow, pressed && { opacity: 0.6 }]}+ onPress={handlePickDirectory}+ >+ <FolderOpen size={22} color={colors.primary} />+ <View style={styles.directoryContent}>+ <Text style={[styles.settingLabel, { color: colors.text }]}>+ {directoryUri ? "Directory Selected" : "Select Directory"}+ </Text>+ <Text style={[styles.settingDescription, { color: colors.textSecondary }]} numberOfLines={1}>+ {directoryUri+ ? decodeURIComponent(directoryUri.split("%3A").pop() || directoryUri)+ : "Tap to choose where files are saved"}+ </Text>+ </View>+ {directoryUri && <CheckCircle size={18} color={colors.success} />}+ </Pressable>+ </Card>+ </View>++ {/* Format */}+ <View style={styles.section}>+ <SectionTitle>Format</SectionTitle>+ <Card>+ <FormatSelector selectedFormat={format} onSelectFormat={handleFormatChange} />+ </Card>+ </View>++ {/* Frequency */}+ <View style={styles.section}>+ <SectionTitle>Frequency</SectionTitle>+ <Card>+ <ChipGroup options={INTERVAL_OPTIONS} selected={interval} onSelect={handleIntervalChange} colors={colors} />+ </Card>+ </View>++ {/* Export Range */}+ <View style={styles.section}>+ <SectionTitle>Export Range</SectionTitle>+ <Card>+ {MODE_OPTIONS.map((option, i) => (+ <View key={option.key}>+ {i > 0 && <Divider />}+ <Pressable+ style={({ pressed }) => [styles.modeRow, pressed && { opacity: 0.6 }]}+ onPress={() => handleModeChange(option.key)}+ >+ <View style={styles.modeContent}>+ <Text style={[styles.settingLabel, { color: mode === option.key ? colors.primary : colors.text }]}>+ {option.label}+ </Text>+ <Text style={[styles.settingDescription, { color: colors.textSecondary }]}>+ {option.description}+ </Text>+ </View>+ <RadioDot selected={mode === option.key} />+ </Pressable>+ </View>+ ))}+ </Card>+ </View>++ {/* File Retention */}+ <View style={styles.section}>+ <SectionTitle>File Retention</SectionTitle>+ <Card>+ <ChipGroup+ options={RETENTION_OPTIONS}+ selected={retentionCount.toString()}+ onSelect={handleRetentionChange}+ colors={colors}+ />+ </Card>+ </View>++ {/* Status */}+ <View style={styles.section}>+ <SectionTitle>Status</SectionTitle>+ <Card>+ <View style={styles.statusRow}>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last Export</Text>+ <Text style={[styles.statusValue, { color: colors.text }]}>{formatTimestamp(lastExport)}</Text>+ </View>+ {lastFileName && (+ <>+ <Divider />+ <View style={styles.statusRow}>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Last File</Text>+ <Text style={[styles.statusValue, { color: colors.text }]} numberOfLines={1}>+ {lastFileName}+ </Text>+ </View>+ <Divider />+ <View style={styles.statusRow}>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Locations Exported</Text>+ <Text style={[styles.statusValue, { color: colors.text }]}>{lastRowCount}</Text>+ </View>+ </>+ )}+ {lastError ? (+ <>+ <Divider />+ <View style={styles.errorRow}>+ <AlertTriangle size={14} color={colors.error} />+ <Text style={[styles.errorText, { color: colors.error }]} numberOfLines={2}>+ {lastError}+ </Text>+ </View>+ </>+ ) : null}+ {enabled && nextExport > 0 && (+ <>+ <Divider />+ <View style={styles.statusRow}>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Next Export</Text>+ <Text style={[styles.statusValue, { color: colors.text }]}>{formatTimestamp(nextExport)}</Text>+ </View>+ </>+ )}+ {directoryUri && (+ <>+ <Divider />+ <View style={styles.statusRow}>+ <Text style={[styles.statusLabel, { color: colors.textSecondary }]}>Export Files</Text>+ <Text style={[styles.statusValue, { color: colors.text }]}>{fileCount}</Text>+ </View>+ </>+ )}+ </Card>+ </View>++ {/* Export Now */}+ {directoryUri && (+ <View style={styles.section}>+ <Button+ title={exporting ? "Exporting..." : "Export Now"}+ onPress={handleExportNow}+ disabled={exporting}+ loading={exporting}+ />+ </View>+ )}++ {/* Export History */}+ {exportFiles.length > 0 && (+ <View style={styles.section}>+ <SectionTitle>Export History</SectionTitle>+ <Card>+ {exportFiles.map((file, i) => (+ <View key={file.name}>+ {i > 0 && <Divider />}+ <View style={styles.fileRow}>+ <View style={styles.fileInfo}>+ <Text style={[styles.fileName, { color: colors.text }]} numberOfLines={1}>+ {file.name}+ </Text>+ <Text style={[styles.fileMeta, { color: colors.textSecondary }]}>+ {formatFileSize(file.size)} - {formatTimestamp(file.lastModified)}+ </Text>+ </View>+ <Pressable+ style={({ pressed }) => [styles.shareButton, pressed && { opacity: 0.5 }]}+ onPress={() => handleShareFile(file)}+ >+ <Share2 size={18} color={colors.primary} />+ </Pressable>+ </View>+ </View>+ ))}+ </Card>+ </View>+ )}+ </ScrollView>+ <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: {+ paddingHorizontal: 16,+ paddingBottom: 40+ },+ header: {+ marginTop: 20,+ marginBottom: 20+ },+ title: {+ fontSize: 28,+ ...fonts.bold,+ letterSpacing: -0.5+ },+ subtitle: {+ fontSize: 14,+ marginTop: 4,+ lineHeight: 20+ },+ section: {+ marginTop: 24+ },+ settingLabel: {+ fontSize: 16,+ ...fonts.semiBold,+ marginBottom: 2+ },+ settingDescription: {+ fontSize: 13,+ ...fonts.regular+ },+ directoryRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: 12,+ paddingVertical: 4+ },+ directoryContent: {+ flex: 1+ },+ statusRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ paddingVertical: 4+ },+ statusLabel: {+ fontSize: 14,+ ...fonts.regular+ },+ statusValue: {+ fontSize: 14,+ ...fonts.semiBold,+ flexShrink: 1,+ textAlign: "right",+ marginLeft: 12+ },+ errorRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: 8,+ paddingVertical: 6+ },+ errorText: {+ fontSize: 13,+ ...fonts.regular,+ flex: 1+ },+ modeRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ paddingVertical: 10+ },+ modeContent: {+ flex: 1,+ marginRight: 16+ },+ fileRow: {+ flexDirection: "row",+ alignItems: "center",+ paddingVertical: 8+ },+ fileInfo: {+ flex: 1,+ marginRight: 12+ },+ fileName: {+ fontSize: 13,+ ...fonts.semiBold,+ marginBottom: 2+ },+ fileMeta: {+ fontSize: 12,+ ...fonts.regular+ },+ shareButton: {+ padding: 8+ }+})diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsxindex b38d748b..931e818b 100644--- a/apps/mobile/src/screens/ExportDataScreen.tsx+++ b/apps/mobile/src/screens/ExportDataScreen.tsx@@ -3,27 +3,28 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import { useState, useEffect, useCallback, useRef } from "react"-import { Text, StyleSheet, View, ActivityIndicator, ScrollView } from "react-native"+import { useState, useEffect, useCallback } from "react"+import { Text, StyleSheet, View, ActivityIndicator, ScrollView, Pressable } from "react-native"import { fonts } from "../styles/typography"-import { Download, MapPinOff } from "lucide-react-native"+import { Download, MapPinOff, Clock, ChevronRight } from "lucide-react-native"import { Container, Card, SectionTitle, Button, FormatSelector } from "../components"import { useTheme } from "../hooks/useTheme"-import { LocationCoords } from "../types/global"import NativeLocationService from "../services/NativeLocationService"-import { LARGE_FILE_THRESHOLD, formatBytes, getByteSize, EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"+import { EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"import { logger } from "../utils/logger"-import { showAlert, showConfirm } from "../services/modalService"+import { showAlert } from "../services/modalService"+import { ScreenProps } from "../types/global"-export function ExportDataScreen() {+export function ExportDataScreen({ navigation }: ScreenProps) {const { colors } = useTheme()const [exporting, setExporting] = useState(false)const [exportProgress, setExportProgress] = useState<string>("")const [totalLocations, setTotalLocations] = useState(0)const [selectedFormat, setSelectedFormat] = useState<ExportFormat | null>(null)- const [fileSize, setFileSize] = useState<string | null>(null)- const cachedData = useRef<LocationCoords[]>([])- const cachedContent = useRef<{ format: ExportFormat; content: string } | null>(null)+ const [autoExportEnabled, setAutoExportEnabled] = useState(false)+ const [autoExportInterval, setAutoExportInterval] = useState("")+ const [autoExportFormat, setAutoExportFormat] = useState("")+ const [lastExportTs, setLastExportTs] = useState(0)const loadStats = useCallback(async () => {try {@@ -34,38 +35,22 @@ export function ExportDataScreen() {}}, [])- const loadExportData = useCallback(async () => {- if (cachedData.current.length > 0) return- const data = await NativeLocationService.getExportData()- if (data && data.length > 0) {- cachedData.current = data+ const loadAutoExportStatus = useCallback(async () => {+ try {+ const status = await NativeLocationService.getAutoExportStatus()+ setAutoExportEnabled(status.enabled)+ setAutoExportInterval(status.interval)+ setAutoExportFormat(status.format)+ setLastExportTs(status.lastExportTimestamp)+ } catch (error) {+ logger.error("[ExportDataScreen] Failed to load auto-export status:", error)}}, [])useEffect(() => {loadStats()- }, [loadStats])-- // Convert once on format selection, cache the result for both size preview and export- useEffect(() => {- if (!selectedFormat || totalLocations === 0) {- setFileSize(null)- cachedContent.current = null- return- }-- let cancelled = false- ;(async () => {- await loadExportData()- if (cancelled || cachedData.current.length === 0) return- const content = EXPORT_FORMATS[selectedFormat].convert(cachedData.current)- cachedContent.current = { format: selectedFormat, content }- setFileSize(formatBytes(getByteSize(content)))- })()- return () => {- cancelled = true- }- }, [selectedFormat, totalLocations, loadExportData])+ loadAutoExportStatus()+ }, [loadStats, loadAutoExportStatus])const handleExport = async (format: ExportFormat) => {if (totalLocations === 0) {@@ -74,53 +59,26 @@ export function ExportDataScreen() {}setExporting(true)- setExportProgress("Preparing export...")+ setExportProgress("Exporting locations...")try {- await loadExportData()- setExportProgress(`Converting ${cachedData.current.length} locations...`)-- // Reuse cached conversion if format matches, otherwise convert fresh- const content =- cachedContent.current?.format === format- ? cachedContent.current.content- : EXPORT_FORMATS[format].convert(cachedData.current)-- const formatConfig = EXPORT_FORMATS[format]- const exportSize = getByteSize(content)+ const result = await NativeLocationService.exportToFile(format)- if (exportSize > LARGE_FILE_THRESHOLD) {- setExporting(false)- setExportProgress("")-- const confirmed = await showConfirm({- title: "Large Export",- message: `The export file is ${formatBytes(exportSize)}. This may take a moment to save and share. Continue?`,- confirmText: "Continue"- })-- if (!confirmed) {- setSelectedFormat(null)- return- }-- setExporting(true)+ if (!result) {+ showAlert("No Data", "There are no locations in the database to export.", "info")+ return}- const fileName = `colota_export_${Date.now()}${formatConfig.extension}`-- setExportProgress(`Saving file (${formatBytes(exportSize)})...`)-- const filePath = await NativeLocationService.writeFile(fileName, content)+ setExportProgress(`Exported ${result.rowCount.toLocaleString()} locations`)setExporting(false)setExportProgress("")try {await NativeLocationService.shareFile(- filePath,- formatConfig.mimeType,- `Colota Export - ${totalLocations} locations`+ result.filePath,+ result.mimeType,+ `Colota Export - ${result.rowCount} locations`)} catch (shareError: any) {logger.warn("[ExportDataScreen] Share error:", shareError)@@ -144,7 +102,7 @@ export function ExportDataScreen() {</View>{totalLocations === 0 ? (- <Card>+ <Card style={styles.emptyCard}><View style={styles.emptyState}><MapPinOff size={40} color={colors.textLight} /><Text style={[styles.emptyTitle, { color: colors.text }]}>No Locations</Text>@@ -159,18 +117,11 @@ export function ExportDataScreen() {<View style={[styles.statsContainer, { backgroundColor: colors.card, borderColor: colors.border }]}><View style={styles.statsGrid}><View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total</Text>+ <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Total Locations</Text><Text style={[styles.statValue, { color: colors.primaryDark }]}>{totalLocations.toLocaleString()}</Text></View>-- <View style={[styles.statsDivider, { backgroundColor: colors.border }]} />-- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>File Size</Text>- <Text style={[styles.statValue, { color: colors.success }]}>{fileSize ?? "–"}</Text>- </View></View></View>@@ -184,15 +135,39 @@ export function ExportDataScreen() {{/* Export Button */}{selectedFormat && (- <Button- onPress={() => handleExport(selectedFormat)}- disabled={exporting}- title={`Export ${EXPORT_FORMATS[selectedFormat].label}`}- icon={Download}- />+ <View style={styles.exportButtonWrapper}>+ <Button+ onPress={() => handleExport(selectedFormat)}+ disabled={exporting}+ title={`Export ${EXPORT_FORMATS[selectedFormat].label}`}+ icon={Download}+ />+ </View>)}</>)}++ {/* Auto-Export */}+ <View style={styles.section}>+ <SectionTitle>Scheduled Export</SectionTitle>+ <Card>+ <Pressable+ style={({ pressed }) => [styles.autoExportRow, pressed && { opacity: 0.6 }]}+ onPress={() => navigation.navigate("Auto-Export")}+ >+ <Clock size={22} color={autoExportEnabled ? colors.primary : colors.textLight} />+ <View style={styles.autoExportContent}>+ <Text style={[styles.autoExportLabel, { color: colors.text }]}>Auto-Export</Text>+ <Text style={[styles.autoExportSub, { color: colors.textSecondary }]}>+ {autoExportEnabled+ ? `${autoExportInterval === "daily" ? "Daily" : autoExportInterval === "weekly" ? "Weekly" : "Monthly"} - ${autoExportFormat.toUpperCase()}${lastExportTs > 0 ? ` - Last: ${new Date(lastExportTs * 1000).toLocaleDateString()}` : ""}`+ : "Schedule automatic exports"}+ </Text>+ </View>+ <ChevronRight size={20} color={colors.textLight} />+ </Pressable>+ </Card>+ </View></ScrollView>{/* Loading Overlay */}@@ -223,6 +198,9 @@ const styles = StyleSheet.create({...fonts.bold,letterSpacing: -0.5},+ emptyCard: {+ marginBottom: 24+ },emptyState: {alignItems: "center",paddingVertical: 32@@ -265,11 +243,6 @@ const styles = StyleSheet.create({letterSpacing: -0.5,textAlign: "center"},- statsDivider: {- width: 1,- marginHorizontal: 12,- opacity: 0.3- },section: {marginBottom: 24},@@ -302,5 +275,26 @@ const styles = StyleSheet.create({loaderText: {fontSize: 13,textAlign: "center"+ },+ autoExportRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: 12,+ paddingVertical: 8+ },+ autoExportContent: {+ flex: 1+ },+ autoExportLabel: {+ fontSize: 16,+ ...fonts.semiBold,+ marginBottom: 2+ },+ autoExportSub: {+ fontSize: 13,+ ...fonts.regular+ },+ exportButtonWrapper: {+ marginBottom: 16}})diff --git a/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsxnew file mode 100644index 00000000..1fa94761--- /dev/null+++ b/apps/mobile/src/screens/__tests__/AutoExportScreen.test.tsx@@ -0,0 +1,653 @@+import React from "react"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"+import { DeviceEventEmitter } from "react-native"++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ card: "#fff",+ border: "#e5e7eb",+ background: "#fff",+ backgroundElevated: "#f9fafb",+ success: "#22c55e",+ warning: "#f59e0b",+ info: "#3b82f6",+ error: "#ef4444",+ placeholder: "#9ca3af",+ textOnPrimary: "#fff",+ overlay: "rgba(0,0,0,0.5)"+ }+ })+}))++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: jest.fn((cb) => cb())+}))++const mockGetAutoExportStatus = jest.fn().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+})+const mockSaveSetting = jest.fn().mockResolvedValue(undefined)+const mockScheduleAutoExport = jest.fn().mockResolvedValue(true)+const mockCancelAutoExport = jest.fn().mockResolvedValue(true)+const mockPickExportDirectory = jest.fn().mockResolvedValue(null)+const mockRunAutoExportNow = jest.fn().mockResolvedValue(true)+const mockGetSetting = jest.fn().mockResolvedValue(null)+const mockGetExportFiles = jest.fn().mockResolvedValue([])+const mockShareExportFile = jest.fn().mockResolvedValue(true)++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getAutoExportStatus: function () {+ return mockGetAutoExportStatus.apply(null, arguments)+ },+ saveSetting: function () {+ return mockSaveSetting.apply(null, arguments)+ },+ getSetting: function () {+ return mockGetSetting.apply(null, arguments)+ },+ scheduleAutoExport: function () {+ return mockScheduleAutoExport.apply(null, arguments)+ },+ cancelAutoExport: function () {+ return mockCancelAutoExport.apply(null, arguments)+ },+ pickExportDirectory: function () {+ return mockPickExportDirectory.apply(null, arguments)+ },+ runAutoExportNow: function () {+ return mockRunAutoExportNow.apply(null, arguments)+ },+ getExportFiles: function () {+ return mockGetExportFiles.apply(null, arguments)+ },+ shareExportFile: function () {+ return mockShareExportFile.apply(null, arguments)+ }+ }+}))++const mockShowAlert = jest.fn()++jest.mock("../../services/modalService", () => ({+ showAlert: function () {+ return mockShowAlert.apply(null, arguments)+ }+}))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), warn: jest.fn() }+}))++jest.mock("../../utils/exportConverters", () => {+ const R = require("react")+ const { View } = require("react-native")+ const icon = () => R.createElement(View, null)+ return {+ EXPORT_FORMAT_KEYS: ["csv", "geojson", "gpx", "kml"],+ EXPORT_FORMATS: {+ csv: { label: "CSV", extension: ".csv", subtitle: "Spreadsheet", description: "desc", icon },+ geojson: { label: "GeoJSON", extension: ".geojson", subtitle: "Geographic", description: "desc", icon },+ gpx: { label: "GPX", extension: ".gpx", subtitle: "GPS Exchange", description: "desc", icon },+ kml: { label: "KML", extension: ".kml", subtitle: "Keyhole", description: "desc", icon }+ }+ }+})++jest.mock("../../components", () => {+ const R = require("react")+ const RN = require("react-native")+ const { EXPORT_FORMATS, EXPORT_FORMAT_KEYS } = require("../../utils/exportConverters")+ return {+ Container: (props: any) => R.createElement(RN.View, null, props.children),+ Card: (props: any) => R.createElement(RN.View, null, props.children),+ SectionTitle: (props: any) => R.createElement(RN.Text, null, props.children),+ Divider: () => R.createElement(RN.View, null),+ RadioDot: (props: any) => R.createElement(RN.View, { testID: props.selected ? "radio-selected" : "radio" }),+ ChipGroup: (props: any) =>+ R.createElement(+ RN.View,+ null,+ props.options.map((opt: any) =>+ R.createElement(+ RN.Pressable,+ { key: opt.value, onPress: () => props.onSelect(opt.value), testID: `chip-${opt.value}` },+ R.createElement(RN.Text, null, opt.label)+ )+ )+ ),+ FormatSelector: (props: any) =>+ R.createElement(+ RN.View,+ null,+ EXPORT_FORMAT_KEYS.map((key: any) =>+ R.createElement(+ RN.Pressable,+ { key, onPress: () => props.onSelectFormat(key), testID: `format-${key}` },+ R.createElement(RN.Text, null, EXPORT_FORMATS[key].label),+ R.createElement(RN.Text, null, EXPORT_FORMATS[key].extension)+ )+ )+ ),+ FloatingSaveIndicator: () => null,+ SettingRow: (props: any) =>+ R.createElement(+ RN.View,+ null,+ R.createElement(RN.Text, null, props.label),+ props.hint && R.createElement(RN.Text, null, props.hint),+ props.children+ ),+ Button: (props: any) =>+ R.createElement(+ RN.Pressable,+ { onPress: props.onPress, disabled: props.disabled },+ R.createElement(RN.Text, null, props.title)+ )+ }+})++jest.mock("lucide-react-native", () => {+ const R = require("react")+ const RN = require("react-native")+ const stub = (name: any) => () => R.createElement(RN.Text, null, name)+ return {+ FolderOpen: stub("FolderOpen"),+ CheckCircle: stub("CheckCircle"),+ Share2: stub("Share2"),+ AlertTriangle: stub("AlertTriangle")+ }+})++import { AutoExportScreen } from "../AutoExportScreen"++describe("AutoExportScreen", () => {+ const mockProps = { navigation: { navigate: jest.fn() } }++ beforeEach(() => {+ jest.clearAllMocks()+ 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+ })+ mockGetExportFiles.mockResolvedValue([])+ })++ it("renders title and subtitle", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Auto-Export")).toBeTruthy()+ expect(getByText("Automatically export your location data on a schedule")).toBeTruthy()+ })+ })++ it("renders all format options", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("CSV")).toBeTruthy()+ expect(getByText("GeoJSON")).toBeTruthy()+ expect(getByText("GPX")).toBeTruthy()+ expect(getByText("KML")).toBeTruthy()+ })+ })++ it("renders all interval options including monthly", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Daily")).toBeTruthy()+ expect(getByText("Weekly")).toBeTruthy()+ expect(getByText("Monthly")).toBeTruthy()+ })+ })++ it("renders export mode options", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("All data")).toBeTruthy()+ expect(getByText("Since last export")).toBeTruthy()+ })+ })++ it("shows 'Never' when no export has occurred", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Never")).toBeTruthy()+ })+ })++ it("shows last export date when available", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "csv",+ interval: "weekly",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700604800,+ fileCount: 5+ })++ const { queryByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(queryByText("Never")).toBeNull()+ })+ })++ it("shows alert when enabling without directory", async () => {+ const { getByRole } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByRole("switch")).toBeTruthy()+ })++ fireEvent(getByRole("switch"), "valueChange", true)++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith("No Directory", "Please select an export directory first.", "info")+ })+ })++ it("enables auto-export when directory is set", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: false,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ const { getByRole } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByRole("switch")).toBeTruthy()+ })++ fireEvent(getByRole("switch"), "valueChange", true)++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportEnabled", "true")+ expect(mockScheduleAutoExport).toHaveBeenCalled()+ })+ })++ it("disabling auto-export cancels the schedule", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 86400,+ fileCount: 0+ })++ const { getByRole } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByRole("switch")).toBeTruthy()+ })++ fireEvent(getByRole("switch"), "valueChange", false)++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportEnabled", "false")+ expect(mockCancelAutoExport).toHaveBeenCalled()+ })+ })++ it("selecting directory picker calls native module", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Select Directory")).toBeTruthy()+ })++ fireEvent.press(getByText("Select Directory"))++ await waitFor(() => {+ expect(mockPickExportDirectory).toHaveBeenCalled()+ })+ })++ it("changing format saves the setting", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("CSV")).toBeTruthy()+ })++ fireEvent.press(getByText("CSV"))++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportFormat", "csv")+ })+ })++ it("changing interval saves the setting", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 86400,+ fileCount: 0+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Weekly")).toBeTruthy()+ })++ fireEvent.press(getByText("Weekly"))++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportInterval", "weekly")+ })+ })++ it("shows next export when enabled with last export", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700086400,+ fileCount: 3+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Next Export")).toBeTruthy()+ expect(getByText("Export Files")).toBeTruthy()+ expect(getByText("3")).toBeTruthy()+ })+ })++ it("hides next export when disabled", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: false,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 0,+ fileCount: 3+ })++ const { queryByText, getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(queryByText("Next Export")).toBeNull()+ expect(getByText("Export Files")).toBeTruthy()+ })+ })++ it("changing mode saves the setting", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Since last export")).toBeTruthy()+ })++ fireEvent.press(getByText("Since last export"))++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportMode", "incremental")+ })+ })++ it("changing retention saves the setting", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("5 files")).toBeTruthy()+ })++ fireEvent.press(getByText("5 files"))++ await waitFor(() => {+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportRetentionCount", "5")+ })+ })++ it("shows Export Now button when directory is set", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: false,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Export Now")).toBeTruthy()+ })+ })++ it("hides Export Now button when no directory is set", async () => {+ const { queryByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(queryByText("Export Now")).toBeNull()+ })+ })++ it("Export Now triggers runAutoExportNow", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: false,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Export Now")).toBeTruthy()+ })++ fireEvent.press(getByText("Export Now"))++ await waitFor(() => {+ expect(mockRunAutoExportNow).toHaveBeenCalled()+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Export Started",+ "Export is running in the background. The status will update when complete.",+ "info"+ )+ })+ })++ it("shows permission lost alert when flag is set", async () => {+ mockGetSetting.mockResolvedValue("true")++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Auto-Export")).toBeTruthy()+ })++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Export Directory Access Lost",+ "The app lost access to the export directory. Please re-select it to resume auto-exports.",+ "warning"+ )+ expect(mockSaveSetting).toHaveBeenCalledWith("autoExportPermissionLost", "false")+ })+ })++ it("shows last file name and row count in status", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700086400,+ fileCount: 3,+ retentionCount: 10,+ lastFileName: "colota_export_2026-03-10_1200.geojson",+ lastRowCount: 42,+ lastError: null+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Last File")).toBeTruthy()+ expect(getByText("colota_export_2026-03-10_1200.geojson")).toBeTruthy()+ expect(getByText("Locations Exported")).toBeTruthy()+ expect(getByText("42")).toBeTruthy()+ })+ })++ it("shows error message when lastError is set", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700086400,+ fileCount: 0,+ retentionCount: 10,+ lastFileName: null,+ lastRowCount: 0,+ lastError: "IO error: disk full"+ })++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("IO error: disk full")).toBeTruthy()+ })+ })++ it("renders export history with file list", async () => {+ mockGetExportFiles.mockResolvedValue([+ { name: "colota_export_2026-03-10.geojson", size: 1024, lastModified: 1700000000, uri: "content://file1" },+ { name: "colota_export_2026-03-09.geojson", size: 2048, lastModified: 1699913600, uri: "content://file2" }+ ])++ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Export History")).toBeTruthy()+ expect(getByText("colota_export_2026-03-10.geojson")).toBeTruthy()+ expect(getByText("colota_export_2026-03-09.geojson")).toBeTruthy()+ })+ })++ it("does not show export history when no files", async () => {+ mockGetExportFiles.mockResolvedValue([])++ const { queryByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(queryByText("Export History")).toBeNull()+ })+ })++ it("handles onAutoExportComplete event for success", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Auto-Export")).toBeTruthy()+ })++ await act(async () => {+ DeviceEventEmitter.emit("onAutoExportComplete", {+ success: true,+ fileName: "colota_export_2026-03-10.csv",+ rowCount: 100,+ error: null+ })+ })++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Export Complete",+ "Exported 100 locations to colota_export_2026-03-10.csv",+ "success"+ )+ })+ })++ it("handles onAutoExportComplete event for failure", async () => {+ const { getByText } = render(<AutoExportScreen {...mockProps} />)++ await waitFor(() => {+ expect(getByText("Auto-Export")).toBeTruthy()+ })++ await act(async () => {+ DeviceEventEmitter.emit("onAutoExportComplete", {+ success: false,+ fileName: null,+ rowCount: 0,+ error: "Directory permission lost"+ })+ })++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith("Export Failed", "Directory permission lost", "error")+ })+ })+})diff --git a/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsxindex 82ca373d..fe980c4d 100644--- a/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/ExportDataScreen.test.tsx@@ -27,11 +27,11 @@ jest.mock("../../hooks/useTheme", () => ({}))const mockGetStats = jest.fn().mockResolvedValue({ total: 100 })-const mockGetExportData = jest.fn().mockResolvedValue([- { latitude: 52.52, longitude: 13.405, accuracy: 10, altitude: 34, speed: 1.2, battery: 85, timestamp: 1700000000 },- { latitude: 48.8566, longitude: 2.3522, accuracy: 15, altitude: 40, speed: 0.5, battery: 72, timestamp: 1700003600 }-])-const mockWriteFile = jest.fn().mockResolvedValue("/path/file.csv")+const mockExportToFile = jest.fn().mockResolvedValue({+ filePath: "/path/file.csv",+ mimeType: "text/csv",+ rowCount: 100+})const mockShareFile = jest.fn().mockResolvedValue(undefined)jest.mock("../../services/NativeLocationService", () => ({@@ -40,15 +40,23 @@ jest.mock("../../services/NativeLocationService", () => ({getStats: function () {return mockGetStats.apply(null, arguments)},- getExportData: function () {- return mockGetExportData.apply(null, arguments)- },- writeFile: function () {- return mockWriteFile.apply(null, arguments)+ exportToFile: function () {+ return mockExportToFile.apply(null, arguments)},shareFile: function () {return mockShareFile.apply(null, arguments)- }+ },+ getAutoExportStatus: jest.fn().mockResolvedValue({+ enabled: false,+ format: "geojson",+ interval: "daily",+ uri: null,+ mode: "all",+ lastExportTimestamp: 0,+ nextExportTimestamp: 0,+ fileCount: 0,+ retentionCount: 10+ })}}))@@ -65,15 +73,6 @@ jest.mock("../../services/modalService", () => ({}))jest.mock("../../utils/exportConverters", () => ({- LARGE_FILE_THRESHOLD: 10 * 1024 * 1024,- formatBytes: function (bytes: any) {- if (bytes < 1024) return bytes + " B"- if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"- return (bytes / (1024 * 1024)).toFixed(1) + " MB"- },- getByteSize: function (content: any) {- return content.length- },EXPORT_FORMATS: {csv: {label: "CSV",@@ -83,10 +82,7 @@ jest.mock("../../utils/exportConverters", () => ({return null},extension: ".csv",- mimeType: "text/csv",- convert: function () {- return "id,lat,lon\n1,52.52,13.405"- }+ mimeType: "text/csv"},geojson: {label: "GeoJSON",@@ -96,10 +92,7 @@ jest.mock("../../utils/exportConverters", () => ({return null},extension: ".geojson",- mimeType: "application/json",- convert: function () {- return '{"type":"FeatureCollection","features":[]}'- }+ mimeType: "application/json"},gpx: {label: "GPX",@@ -109,10 +102,7 @@ jest.mock("../../utils/exportConverters", () => ({return null},extension: ".gpx",- mimeType: "application/gpx+xml",- convert: function () {- return "<gpx></gpx>"- }+ mimeType: "application/gpx+xml"},kml: {label: "KML",@@ -122,10 +112,7 @@ jest.mock("../../utils/exportConverters", () => ({return null},extension: ".kml",- mimeType: "application/vnd.google-earth.kml+xml",- convert: function () {- return "<kml></kml>"- }+ mimeType: "application/vnd.google-earth.kml+xml"}}}))@@ -190,6 +177,8 @@ jest.mock("lucide-react-native", () => {return {Download: stub("Download"),MapPinOff: stub("MapPinOff"),+ ChevronRight: stub("ChevronRight"),+ Clock: stub("Clock"),Table2: stub("Table2"),Globe: stub("Globe"),MapPin: stub("MapPin"),@@ -203,30 +192,17 @@ describe("ExportDataScreen", () => {beforeEach(() => {jest.clearAllMocks()mockGetStats.mockResolvedValue({ total: 100 })- mockGetExportData.mockResolvedValue([- {- latitude: 52.52,- longitude: 13.405,- accuracy: 10,- altitude: 34,- speed: 1.2,- battery: 85,- timestamp: 1700000000- },- {- latitude: 48.8566,- longitude: 2.3522,- accuracy: 15,- altitude: 40,- speed: 0.5,- battery: 72,- timestamp: 1700003600- }- ])+ mockExportToFile.mockResolvedValue({+ filePath: "/path/file.csv",+ mimeType: "text/csv",+ rowCount: 100+ })})+ const mockNavigation = { navigate: jest.fn() } as any+function renderScreen() {- return render(<ExportDataScreen />)+ return render(<ExportDataScreen navigation={mockNavigation} />)}it("shows Export Data title", async () => {@@ -252,7 +228,7 @@ describe("ExportDataScreen", () => {const { getByText } = renderScreen()await waitFor(() => {- expect(getByText("Total")).toBeTruthy()+ expect(getByText("Total Locations")).toBeTruthy()expect(getByText("100")).toBeTruthy()})})@@ -283,8 +259,8 @@ describe("ExportDataScreen", () => {})it("shows loading overlay during export", async () => {- // Make writeFile hang so we can observe the loading state- mockWriteFile.mockImplementation(() => new Promise(() => {}))+ // Make exportToFile hang so we can observe the loading state+ mockExportToFile.mockImplementation(() => new Promise(() => {}))const { getByText } = renderScreen()@@ -317,4 +293,45 @@ describe("ExportDataScreen", () => {// totalLocations is 0 so the format cards are not rendered and no export button existsexpect(queryByText("CSV")).toBeNull()})++ it("shows auto-export section with status", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Scheduled Export")).toBeTruthy()+ expect(getByText("Auto-Export")).toBeTruthy()+ })+ })++ it("shows auto-export summary when enabled", async () => {+ const mockModule = require("../../services/NativeLocationService").default+ mockModule.getAutoExportStatus.mockResolvedValueOnce({+ enabled: true,+ format: "csv",+ interval: "weekly",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700604800,+ fileCount: 5+ })++ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText(/Weekly/)).toBeTruthy()+ })+ })++ it("navigates to Auto-Export screen on press", async () => {+ const { getByText } = renderScreen()++ await waitFor(() => {+ expect(getByText("Auto-Export")).toBeTruthy()+ })++ fireEvent.press(getByText("Auto-Export"))++ expect(mockNavigation.navigate).toHaveBeenCalledWith("Auto-Export")+ })})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex f5b9e108..56cac680 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -4,6 +4,7 @@*/export { ApiSettingsScreen } from "./ApiSettingsScreen"+export { AutoExportScreen } from "./AutoExportScreen"export { AuthSettingsScreen } from "./AuthSettingsScreen"export { DashboardScreen } from "./DashboardScreen"export { DataManagementScreen } from "./DataManagementScreen"diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 86eddeb4..8317d0bd 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -159,18 +159,6 @@ class NativeLocationService {return LocationServiceModule.getStats()}- /**- * Fetches all locations for export- */- static async getExportData(): Promise<any[]> {- this.ensureModule()- return this.safeExecute(- () => LocationServiceModule.getTableData("locations", 1000000, 0),- [],- "getExportData failed"- )- }-/*** Fetches locations within a date range, ordered chronologically.* Used for track polyline rendering on the map view.@@ -627,6 +615,95 @@ class NativeLocationService {return LocationServiceModule.getNativeLogs()}+ // ============================================================================+ // AUTO-EXPORT+ // ============================================================================++ /**+ * Opens SAF directory picker for auto-export destination.+ * @returns URI string of selected directory, or null if cancelled+ */+ static async pickExportDirectory(): Promise<string | null> {+ this.ensureModule()+ return LocationServiceModule.pickExportDirectory()+ }++ /**+ * Schedules the daily auto-export check worker via WorkManager.+ * The worker checks AutoExportConfig.isExportDue() to determine+ * if an export should actually run (daily/weekly/monthly).+ */+ static async scheduleAutoExport(): Promise<boolean> {+ this.ensureModule()+ return LocationServiceModule.scheduleAutoExport()+ }++ /**+ * Triggers an immediate one-time auto-export, bypassing the interval check.+ */+ static async runAutoExportNow(): Promise<boolean> {+ this.ensureModule()+ return LocationServiceModule.runAutoExportNow()+ }++ /**+ * Cancels any scheduled auto-export.+ */+ static async cancelAutoExport(): Promise<boolean> {+ this.ensureModule()+ return LocationServiceModule.cancelAutoExport()+ }++ /**+ * Returns current auto-export configuration and status.+ */+ static async getAutoExportStatus(): Promise<{+ enabled: boolean+ format: string+ interval: string+ uri: string | null+ mode: string+ lastExportTimestamp: number+ nextExportTimestamp: number+ fileCount: number+ retentionCount: number+ lastFileName: string | null+ lastRowCount: number+ lastError: string | null+ }> {+ this.ensureModule()+ return LocationServiceModule.getAutoExportStatus()+ }++ /**+ * Returns list of export files in the export directory, sorted newest first.+ */+ static async getExportFiles(): Promise<{ name: string; size: number; lastModified: number; uri: string }[]> {+ this.ensureModule()+ return LocationServiceModule.getExportFiles()+ }++ /**+ * Shares an export file via the system share sheet.+ */+ static async shareExportFile(fileUri: string, mimeType: string): Promise<boolean> {+ this.ensureModule()+ return LocationServiceModule.shareExportFile(fileUri, mimeType)+ }++ /**+ * Exports all locations to a file using native streaming converters.+ * Returns file path, mime type, and row count, or null if no data.+ */+ static async exportToFile(format: string): Promise<{+ filePath: string+ mimeType: string+ rowCount: number+ } | null> {+ this.ensureModule()+ return LocationServiceModule.exportToFile(format)+ }+// ============================================================================// SECURE STORAGE (Auth & Headers)// ============================================================================diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 83f197d4..f076b22a 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -42,6 +42,25 @@ jest.mock("react-native", () => ({}),writeFile: jest.fn().mockResolvedValue("/cache/test.csv"),shareFile: jest.fn().mockResolvedValue(true),+ pickExportDirectory: jest.fn().mockResolvedValue("content://com.android.externalstorage/tree/primary%3AExports"),+ scheduleAutoExport: jest.fn().mockResolvedValue(true),+ cancelAutoExport: jest.fn().mockResolvedValue(true),+ runAutoExportNow: jest.fn().mockResolvedValue(true),+ exportToFile: jest.fn().mockResolvedValue({+ filePath: "/cache/manual_export_2024-01-15_0930.geojson",+ mimeType: "application/json",+ rowCount: 150+ }),+ getAutoExportStatus: jest.fn().mockResolvedValue({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700086400,+ fileCount: 3+ }),copyToClipboard: jest.fn().mockResolvedValue(undefined),deleteFile: jest.fn().mockResolvedValue(true),getCacheDirectory: jest.fn().mockResolvedValue("/cache"),@@ -282,4 +301,60 @@ describe("NativeLocationService", () => {expect(path).toBe("/cache/test.csv")})})++ describe("auto-export", () => {+ it("pickExportDirectory returns SAF URI", async () => {+ const uri = await NativeLocationService.pickExportDirectory()+ expect(uri).toBe("content://com.android.externalstorage/tree/primary%3AExports")+ expect(nativeMock.pickExportDirectory).toHaveBeenCalled()+ })++ it("scheduleAutoExport calls native module", async () => {+ const result = await NativeLocationService.scheduleAutoExport()+ expect(result).toBe(true)+ expect(nativeMock.scheduleAutoExport).toHaveBeenCalled()+ })++ it("cancelAutoExport calls native module", async () => {+ const result = await NativeLocationService.cancelAutoExport()+ expect(result).toBe(true)+ expect(nativeMock.cancelAutoExport).toHaveBeenCalled()+ })++ it("getAutoExportStatus returns status object", async () => {+ const status = await NativeLocationService.getAutoExportStatus()+ expect(status).toEqual({+ enabled: true,+ format: "geojson",+ interval: "daily",+ uri: "content://some-uri",+ mode: "all",+ lastExportTimestamp: 1700000000,+ nextExportTimestamp: 1700086400,+ fileCount: 3+ })+ })++ it("runAutoExportNow calls native module", async () => {+ const result = await NativeLocationService.runAutoExportNow()+ expect(result).toBe(true)+ expect(nativeMock.runAutoExportNow).toHaveBeenCalled()+ })++ it("exportToFile returns file info", async () => {+ const result = await NativeLocationService.exportToFile("geojson")+ expect(result).toEqual({+ filePath: "/cache/manual_export_2024-01-15_0930.geojson",+ mimeType: "application/json",+ rowCount: 150+ })+ expect(nativeMock.exportToFile).toHaveBeenCalledWith("geojson")+ })++ it("exportToFile returns null when no data", async () => {+ nativeMock.exportToFile.mockResolvedValueOnce(null)+ const result = await NativeLocationService.exportToFile("csv")+ expect(result).toBeNull()+ })+ })})diff --git a/apps/mobile/src/utils/__tests__/exportConverters.test.ts b/apps/mobile/src/utils/__tests__/exportConverters.test.tsindex 02f95cc7..e54b7b93 100644--- a/apps/mobile/src/utils/__tests__/exportConverters.test.ts+++ b/apps/mobile/src/utils/__tests__/exportConverters.test.ts@@ -1,10 +1,6 @@import {formatBytes,getByteSize,- convertToCSV,- convertToGeoJSON,- convertToGPX,- convertToKML,convertTripsToCSV,convertTripsToGeoJSON,convertTripsToGPX,@@ -12,23 +8,6 @@ import {LARGE_FILE_THRESHOLD} from "../exportConverters"-const sampleLocation = {- latitude: 48.137154,- longitude: 11.576124,- accuracy: 10,- altitude: 520,- speed: 1.5,- bearing: 180,- battery: 85,- battery_status: 2,- timestamp: 1700000000-}--const minimalLocation = {- latitude: 0,- longitude: 0-}-const sampleTrips = [{index: 1,@@ -90,145 +69,6 @@ describe("LARGE_FILE_THRESHOLD", () => {})})-describe("convertToCSV", () => {- it("returns headers for empty data", () => {- const csv = convertToCSV([])- expect(csv).toContain("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery")- })-- it("converts a single location", () => {- const csv = convertToCSV([sampleLocation])- const lines = csv.split("\n")- expect(lines).toHaveLength(2) // header + 1 row-- const row = lines[1]- expect(row).toContain("48.137154")- expect(row).toContain("11.576124")- expect(row).toContain("10") // accuracy- })-- it("defaults missing optional fields to 0", () => {- const csv = convertToCSV([minimalLocation])- const row = csv.split("\n")[1]- // altitude, speed, battery should be 0- expect(row).toMatch(/,0,0,0$/)- })-- it("handles multiple locations", () => {- const csv = convertToCSV([sampleLocation, sampleLocation])- const lines = csv.split("\n")- expect(lines).toHaveLength(3) // header + 2 rows- expect(lines[1]).toMatch(/^0,/) // first row id=0- expect(lines[2]).toMatch(/^1,/) // second row id=1- })-})--describe("convertToGeoJSON", () => {- it("returns valid FeatureCollection for empty data", () => {- const result = JSON.parse(convertToGeoJSON([]))- expect(result.type).toBe("FeatureCollection")- expect(result.features).toEqual([])- })-- it("creates Point features with [lon, lat] order", () => {- const result = JSON.parse(convertToGeoJSON([sampleLocation]))- const coords = result.features[0].geometry.coordinates- expect(coords[0]).toBe(11.576124) // longitude first- expect(coords[1]).toBe(48.137154) // latitude second- })-- it("includes properties", () => {- const result = JSON.parse(convertToGeoJSON([sampleLocation]))- const props = result.features[0].properties- expect(props.accuracy).toBe(10)- expect(props.altitude).toBe(520)- expect(props.speed).toBe(1.5)- expect(props.battery).toBe(85)- })-- it("handles missing timestamp gracefully", () => {- const result = JSON.parse(convertToGeoJSON([minimalLocation]))- const time = result.features[0].properties.time- // Should be a valid ISO string (falls back to current date)- expect(() => new Date(time)).not.toThrow()- })-- it("defaults missing coordinates to 0", () => {- const result = JSON.parse(convertToGeoJSON([minimalLocation]))- const coords = result.features[0].geometry.coordinates- expect(coords).toEqual([0, 0])- })-})--describe("convertToGPX", () => {- it("returns valid GPX XML structure", () => {- const gpx = convertToGPX([])- expect(gpx).toContain('<?xml version="1.0"')- expect(gpx).toContain("<gpx")- expect(gpx).toContain("</gpx>")- expect(gpx).toContain("<trkseg>")- expect(gpx).toContain("</trkseg>")- })-- it("includes trackpoints with lat/lon to 6 decimals", () => {- const gpx = convertToGPX([sampleLocation])- expect(gpx).toContain('lat="48.137154"')- expect(gpx).toContain('lon="11.576124"')- })-- it("includes elevation and extensions", () => {- const gpx = convertToGPX([sampleLocation])- expect(gpx).toContain("<ele>520</ele>")- expect(gpx).toContain("<accuracy>10</accuracy>")- expect(gpx).toContain("<speed>1.5</speed>")- expect(gpx).toContain("<battery>85</battery>")- })-- it("defaults missing fields to 0", () => {- const gpx = convertToGPX([minimalLocation])- expect(gpx).toContain("<ele>0</ele>")- expect(gpx).toContain("<accuracy>0</accuracy>")- expect(gpx).toContain("<speed>0</speed>")- expect(gpx).toContain("<battery>0</battery>")- })-})--describe("convertToKML", () => {- it("returns valid KML XML structure", () => {- const kml = convertToKML([])- expect(kml).toContain('<?xml version="1.0"')- expect(kml).toContain("<kml")- expect(kml).toContain("</kml>")- expect(kml).toContain("<Document>")- expect(kml).toContain("</Document>")- })-- it("includes LineString track path", () => {- const kml = convertToKML([sampleLocation])- expect(kml).toContain("<LineString>")- expect(kml).toContain("11.576124,48.137154,520")- })-- it("includes individual Placemarks with timestamps", () => {- const kml = convertToKML([sampleLocation])- expect(kml).toContain("<TimeStamp>")- expect(kml).toContain("<Point>")- expect(kml).toContain("Accuracy: 10m")- expect(kml).toContain("Speed: 1.5m/s")- })-- it("includes style definition", () => {- const kml = convertToKML([sampleLocation])- expect(kml).toContain('<Style id="pathStyle">')- expect(kml).toContain("<color>ff0000ff</color>")- })-- it("defaults missing altitude to 0", () => {- const kml = convertToKML([minimalLocation])- expect(kml).toContain("0,0,0") // lon,lat,alt- })-})-describe("convertTripsToCSV", () => {it("includes trip column in header", () => {const csv = convertTripsToCSV([])diff --git a/apps/mobile/src/utils/exportConverters.ts b/apps/mobile/src/utils/exportConverters.tsindex 6fda2d6e..51a6f513 100644--- a/apps/mobile/src/utils/exportConverters.ts+++ b/apps/mobile/src/utils/exportConverters.ts@@ -5,7 +5,7 @@import { type LucideIcon } from "lucide-react-native"import { Table2, Globe, MapPin, Earth } from "lucide-react-native"-import { LocationCoords, Trip } from "../types/global"+import { Trip } from "../types/global"import { getTripColor } from "./trips"export const LARGE_FILE_THRESHOLD = 10 * 1024 * 1024 // 10 MB@@ -41,142 +41,6 @@ export const getByteSize = (content: string): number => {return bytes}-// ============================================================================-// FLAT CONVERTERS (timestamps in Unix seconds)-// ============================================================================--export const convertToCSV = (data: LocationCoords[]): string => {- const headers = "id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"- const rows = data- .map((item, i) => {- const ts = item.timestamp ?? Math.floor(Date.now() / 1000)- const isoTime = new Date(ts * 1000).toISOString()- return [- i,- ts,- isoTime,- item.latitude,- item.longitude,- item.accuracy,- item.altitude ?? 0,- item.speed ?? 0,- item.battery ?? 0- ].join(",")- })- .join("\n")- return headers + rows-}--export const convertToGeoJSON = (data: LocationCoords[]): string => {- const features = data.map((item, i) => {- const ts = item.timestamp ?? Math.floor(Date.now() / 1000)- const timeStr = new Date(ts * 1000).toISOString()-- return {- type: "Feature",- geometry: {- type: "Point",- coordinates: [item.longitude ?? 0, item.latitude ?? 0]- },- properties: {- id: i,- accuracy: item.accuracy,- altitude: item.altitude,- speed: item.speed,- battery: item.battery,- time: timeStr- }- }- })-- return JSON.stringify(- {- type: "FeatureCollection",- features- },- null,- 2- )-}--export const convertToGPX = (data: LocationCoords[]): string => {- const parts: string[] = [- `<?xml version="1.0" encoding="UTF-8"?>-<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">- <metadata>- <name>Colota Location Export</name>- <time>${new Date().toISOString()}</time>- </metadata>- <trk>- <name>Colota Track Export</name>- <trkseg>`- ]-- for (const item of data) {- const ts = item.timestamp ?? Math.floor(Date.now() / 1000)- parts.push(`- <trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">- <ele>${item.altitude ?? 0}</ele>- <time>${new Date(ts * 1000).toISOString()}</time>- <extensions>- <accuracy>${item.accuracy ?? 0}</accuracy>- <speed>${item.speed ?? 0}</speed>- <battery>${item.battery ?? 0}</battery>- </extensions>- </trkpt>`)- }-- parts.push(`- </trkseg>- </trk>-</gpx>`)- return parts.join("")-}--export const convertToKML = (data: LocationCoords[]): string => {- const coords = data.map((item) => `${item.longitude},${item.latitude},${item.altitude ?? 0}`).join("\n ")- const parts: string[] = [- `<?xml version="1.0" encoding="UTF-8"?>-<kml xmlns="http://www.opengis.net/kml/2.2">- <Document>- <name>Colota Location Export</name>- <description>Exported tracks from Colota Tracking</description>- <Style id="pathStyle">- <LineStyle>- <color>ff0000ff</color>- <width>4</width>- </LineStyle>- </Style>- <Placemark>- <name>Track Path</name>- <styleUrl>#pathStyle</styleUrl>- <LineString>- <tessellate>1</tessellate>- <coordinates>- ${coords}- </coordinates>- </LineString>- </Placemark>`- ]-- for (const item of data) {- const ts = item.timestamp ?? Math.floor(Date.now() / 1000)- parts.push(`- <Placemark>- <TimeStamp><when>${new Date(ts * 1000).toISOString()}</when></TimeStamp>- <description>Accuracy: ${item.accuracy}m, Speed: ${item.speed ?? 0}m/s</description>- <Point>- <coordinates>${item.longitude},${item.latitude},${item.altitude ?? 0}</coordinates>- </Point>- </Placemark>`)- }-- parts.push(`- </Document>-</kml>`)- return parts.join("")-}-// ============================================================================// TRIP-AWARE CONVERTERS (timestamps in Unix seconds)// ============================================================================@@ -343,7 +207,6 @@ export interface ExportFormatConfig {icon: LucideIconextension: stringmimeType: string- convert: (data: LocationCoords[]) => string}export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {@@ -353,8 +216,7 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {description: "Excel, Google Sheets, data analysis",icon: Table2,extension: ".csv",- mimeType: "text/csv",- convert: convertToCSV+ mimeType: "text/csv"},geojson: {label: "GeoJSON",@@ -362,8 +224,7 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {description: "Mapbox, Leaflet, QGIS, ArcGIS",icon: Globe,extension: ".geojson",- mimeType: "application/json",- convert: convertToGeoJSON+ mimeType: "application/json"},gpx: {label: "GPX",@@ -371,8 +232,7 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {description: "Garmin, Strava, Google Earth",icon: MapPin,extension: ".gpx",- mimeType: "application/gpx+xml",- convert: convertToGPX+ mimeType: "application/gpx+xml"},kml: {label: "KML",@@ -380,7 +240,6 @@ export const EXPORT_FORMATS: Record<ExportFormat, ExportFormatConfig> = {description: "Google Earth, Google Maps, ArcGIS",icon: Earth,extension: ".kml",- mimeType: "application/vnd.google-earth.kml+xml",- convert: convertToKML+ mimeType: "application/vnd.google-earth.kml+xml"}}