Colota - Android GPS Location tracker
/**
* Copyright (C) 2026 Max Dietrich
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
import { NativeModules } from "react-native"
import {
AuthConfig,
BluetoothDeviceInfo,
ClientCertInfo,
ClientCertInfoResult,
DailyStat,
DatabaseStats,
Geofence,
KeyChainPickResult,
SavedTrackingProfile,
Settings,
TestEndpointArgs,
TestEndpointResult,
TrackingProfile,
TripBoundaryOverride
} from "../types/global"
import { logger } from "../utils/logger"
import { parseSystemPalette, type SystemPalette } from "../styles/dynamicColors"
import { SETTINGS_READ_ATTEMPTS, SETTINGS_READ_RETRY_DELAY_MS } from "../constants"
const { LocationServiceModule, MtlsBridgeModule, BuildConfigModule } = NativeModules
/**
* Native location service bridge.
* Provides a TypeScript-safe interface to the native Android location tracking module.
*
* Handles:
* - Data normalization (seconds → milliseconds)
* - Bridge safety checks
* - SQLite persistence operations
*/
class NativeLocationService {
/**
* Validates that the native module is available
* @throws {Error} If LocationServiceModule is undefined
*/
private static ensureModule(): void {
if (!LocationServiceModule) {
throw new Error("[NativeLocationService] Module not available. Check native linking.")
}
}
/**
* Wraps async native calls with error handling
*/
private static async safeExecute<T>(operation: () => Promise<T>, fallback: T, errorPrefix: string): Promise<T> {
try {
return await operation()
} catch (error) {
logger.error(`[NativeLocationService] ${errorPrefix}:`, error)
return fallback
}
}
// ============================================================================
// SERVICE CONTROL
// ============================================================================
/**
* Starts the Android foreground location service
* @param settings Configuration for GPS polling and data transmission
*/
static async start(settings: Settings): Promise<void> {
this.ensureModule()
const config = {
interval: settings.interval * 1000, // s → ms
minUpdateDistance: settings.distance,
endpoint: settings.endpoint,
fieldMap: settings.fieldMap,
syncInterval: settings.syncInterval,
retryInterval: settings.retryInterval,
filterInaccurateLocations: settings.filterInaccurateLocations,
accuracyThreshold: settings.accuracyThreshold,
accuracyMode: settings.accuracyMode,
isOfflineMode: settings.isOfflineMode,
syncCondition: settings.syncCondition,
syncSsid: settings.syncSsid,
httpMethod: settings.httpMethod,
apiTemplate: settings.apiTemplate,
dawarichMode: settings.dawarichMode,
overlandBatchSize: settings.overlandBatchSize,
customFields: Object.fromEntries(settings.customFields.filter((f) => f.key).map((f) => [f.key, f.value]))
}
logger.debug(
`[NativeLocationService] Starting service - interval: ${settings.interval}s, distance: ${settings.distance}m, sync: ${settings.syncInterval}s`
)
try {
await LocationServiceModule.startService(config)
logger.debug("[NativeLocationService] Service started")
} catch (error) {
logger.error("[NativeLocationService] Start failed:", error)
throw error
}
}
/**
* Stops the foreground service and GPS polling
*/
static stop(): void {
if (!LocationServiceModule) {
logger.warn("[NativeLocationService] Module not available")
return
}
logger.debug("[NativeLocationService] Stopping service")
LocationServiceModule.stopService()
}
/**
* Checks if tracking is enabled (from persistent settings)
*/
static async isTrackingActive(): Promise<boolean> {
this.ensureModule()
const state = await this.getSetting("tracking_enabled", "false")
return state === "true"
}
/**
* Whether a started native service instance is alive right now.
* Null means the answer is unknown - callers must not read that as "dead".
*/
static async isServiceRunning(): Promise<boolean | null> {
return this.safeExecute(
() => {
this.ensureModule()
return LocationServiceModule.isServiceRunning()
},
null,
"isServiceRunning failed"
)
}
// ============================================================================
// QUEUE OPERATIONS
// ============================================================================
/**
* Forces immediate upload of all pending locations
* @returns True if flush succeeded
*/
static async manualFlush(): Promise<boolean> {
this.ensureModule()
logger.debug("[NativeLocationService] Triggering manual flush")
try {
const result = await LocationServiceModule.manualFlush()
logger.debug("[NativeLocationService] Flush completed")
return result
} catch (error) {
logger.error("[NativeLocationService] Flush failed:", error)
throw error
}
}
// ============================================================================
// DATABASE QUERIES
// ============================================================================
/**
* Fetches raw rows from a database table
* @param tableName 'locations', 'queue', or 'geofences'
* @param limit Maximum rows to return
* @param offset Pagination offset
*/
static async getTableData(tableName: string, limit: number, offset: number = 0): Promise<any[]> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.getTableData(tableName, limit, offset),
[],
`getTableData(${tableName}) failed`
)
}
/**
* Returns database health summary
*/
static async getStats(): Promise<DatabaseStats> {
this.ensureModule()
return LocationServiceModule.getStats()
}
/**
* Fetches locations within a date range, ordered chronologically.
* Used for track polyline rendering on the map view.
* @param startTimestamp Start of range (Unix seconds, inclusive)
* @param endTimestamp End of range (Unix seconds, inclusive)
*/
static async getLocationsByDateRange(startTimestamp: number, endTimestamp: number): Promise<any[]> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.getLocationsByDateRange(startTimestamp, endTimestamp),
[],
"getLocationsByDateRange failed"
)
}
/**
* Sets or clears the free-text note on a single location. Pass null to clear.
*/
static async updateLocationNote(id: number, note: string | null): Promise<void> {
this.ensureModule()
logger.debug(`[NativeLocationService] Updating note for location ${id}`)
await LocationServiceModule.updateLocationNote(id, note)
}
/**
* Gets the most recent location from the database
*/
static async getMostRecentLocation(): Promise<any | null> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getMostRecentLocation(), null, "getMostRecentLocation failed")
}
/**
* Returns date strings (YYYY-MM-DD) that have location data in the range.
* Used by the calendar view to show activity dots.
*/
static async getDaysWithData(startTimestamp: number, endTimestamp: number): Promise<string[]> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.getDaysWithData(startTimestamp, endTimestamp),
[],
"getDaysWithData failed"
)
}
/**
* Returns date strings (YYYY-MM-DD) in the range that have at least one annotated point.
* Used by the calendar view to flag days with notes.
*/
static async getDaysWithNotes(startTimestamp: number, endTimestamp: number): Promise<string[]> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.getDaysWithNotes(startTimestamp, endTimestamp),
[],
"getDaysWithNotes failed"
)
}
/**
* Returns per-day aggregated stats for a date range.
* Each entry: { day, count, startTime, endTime, distanceMeters, tripCount }
*/
static async getDailyStats(startTimestamp: number, endTimestamp: number): Promise<DailyStat[]> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.getDailyStats(startTimestamp, endTimestamp),
[],
"getDailyStats failed"
)
}
// ============================================================================
// CLEANUP OPERATIONS
// ============================================================================
/** Deletes the locations themselves where `sent = 1`, imported rows included. Resolves how many went. */
static async clearSentHistory(): Promise<number> {
this.ensureModule()
logger.debug("[NativeLocationService] Deleting synced locations")
return LocationServiceModule.clearSentHistory()
}
/**
* Deletes all queued (unsent) locations
* @returns Count of deleted records
*/
static async clearQueue(): Promise<number> {
this.ensureModule()
logger.debug("[NativeLocationService] Clearing queue")
return LocationServiceModule.clearQueue()
}
/**
* Deletes all location data (sent + queued)
* @returns Count of deleted records
*/
static async clearAllLocations(): Promise<number> {
this.ensureModule()
logger.debug("[NativeLocationService] Clearing all locations")
return LocationServiceModule.clearAllLocations()
}
/**
* Deletes locations older than specified days
* @param days Age threshold in days
* @returns Count of deleted records
*/
static async deleteOlderThan(days: number): Promise<number> {
this.ensureModule()
logger.debug(`[NativeLocationService] Deleting locations older than ${days} days`)
return LocationServiceModule.deleteOlderThan(days)
}
/**
* What `deleteOlderThan(days)` would take, plus the boundary it used, so a preview cannot name a
* different one. The timestamp index answers this, so it is safe to call as the user types.
*/
static async countOlderThan(days: number): Promise<{ total: number; cutoffSeconds: number }> {
this.ensureModule()
return LocationServiceModule.countOlderThan(days)
}
/** How many of those have never been uploaded. Reads every match, so call it only on a press. */
static async countUnsentOlderThan(days: number): Promise<number> {
this.ensureModule()
return LocationServiceModule.countUnsentOlderThan(days)
}
/**
* Deletes locations within an inclusive timestamp range (seconds since epoch)
* @returns Count of deleted records
*/
static async deleteLocationsInRange(startTs: number, endTs: number): Promise<number> {
this.ensureModule()
logger.debug(`[NativeLocationService] Deleting locations in range ${startTs}-${endTs}`)
return LocationServiceModule.deleteLocationsInRange(startTs, endTs)
}
/**
* Deletes locations across multiple inclusive timestamp ranges in one transaction (seconds since epoch)
* @returns Count of deleted records
*/
static async deleteLocationsInRanges(ranges: Array<{ start: number; end: number }>): Promise<number> {
this.ensureModule()
if (ranges.length === 0) return 0
logger.debug(`[NativeLocationService] Deleting locations across ${ranges.length} ranges`)
return LocationServiceModule.deleteLocationsInRanges(ranges)
}
/**
* Deletes individual locations by row id
* @returns Count of deleted records
*/
static async deleteLocationsByIds(ids: number[]): Promise<number> {
this.ensureModule()
if (ids.length === 0) return 0
logger.debug(`[NativeLocationService] Deleting ${ids.length} locations by id`)
return LocationServiceModule.deleteLocationsByIds(ids)
}
/**
* Persists manual trip boundary edits. Writing the same boundary twice keeps the latest action,
* so a split over a previous merge (or the reverse) resolves without a separate cleanup step.
*/
static async addBoundaryOverrides(overrides: TripBoundaryOverride[]): Promise<void> {
this.ensureModule()
if (overrides.length === 0) return
logger.debug(`[NativeLocationService] Writing ${overrides.length} trip boundary overrides`)
await LocationServiceModule.addBoundaryOverrides(overrides)
}
/** Falls back to an empty list so a read failure degrades to plain automatic segmentation. */
static async getBoundaryOverrides(): Promise<TripBoundaryOverride[]> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getBoundaryOverrides(), [], "getBoundaryOverrides failed")
}
/**
* Runs SQLite VACUUM to reclaim disk space
*/
static async vacuumDatabase(): Promise<void> {
this.ensureModule()
logger.debug("[NativeLocationService] Vacuuming database")
await LocationServiceModule.vacuumDatabase()
}
// ============================================================================
// GEOFENCE OPERATIONS
// ============================================================================
/**
* Fetches all geofences
*/
static async getGeofences(): Promise<Geofence[]> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getGeofences(), [], "getGeofences failed")
}
/**
* Creates a new geofence
* @returns Geofence ID
*/
static async createGeofence(geofence: Omit<Geofence, "id" | "createdAt">): Promise<number> {
this.ensureModule()
logger.debug("[NativeLocationService] Creating geofence:", geofence.name)
return LocationServiceModule.createGeofence(
geofence.name,
geofence.lat,
geofence.lon,
geofence.radius,
geofence.pauseTracking,
geofence.pauseOnWifi ?? false,
geofence.pauseOnMotionless ?? false,
geofence.motionlessTimeoutMinutes ?? 10,
geofence.heartbeatEnabled ?? false,
geofence.heartbeatIntervalMinutes ?? 15
)
}
/**
* Updates an existing geofence (partial updates supported)
*/
static async updateGeofence(update: Partial<Geofence> & { id: number }): Promise<boolean> {
this.ensureModule()
if (!update.id) {
throw new Error("Geofence ID is required")
}
logger.debug("[NativeLocationService] Updating geofence:", update.id)
return LocationServiceModule.updateGeofence(
update.id,
update.name ?? null,
update.lat ?? null,
update.lon ?? null,
update.radius ?? null,
update.enabled ?? null,
update.pauseTracking ?? null,
update.pauseOnWifi ?? null,
update.pauseOnMotionless ?? null,
update.motionlessTimeoutMinutes ?? null,
update.heartbeatEnabled ?? null,
update.heartbeatIntervalMinutes ?? null
)
}
/**
* Deletes a geofence
*/
static async deleteGeofence(id: number): Promise<boolean> {
this.ensureModule()
logger.debug("[NativeLocationService] Deleting geofence:", id)
return LocationServiceModule.deleteGeofence(id)
}
/**
* Checks if device is currently inside a pause zone
* @returns Pause zone info with name and reason, or null
*/
static async checkCurrentPauseZone(): Promise<{ zoneName: string; pauseReason: string | null } | null> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.checkCurrentPauseZone(), null, "checkCurrentPauseZone failed")
}
/**
* Triggers immediate recheck of pause zone settings
* Use after modifying geofence pause settings to update notification instantly
*/
static async recheckZoneSettings(): Promise<void> {
this.ensureModule()
logger.debug("[NativeLocationService] Triggering zone settings recheck")
try {
await LocationServiceModule.recheckZoneSettings()
} catch (error) {
logger.error("[NativeLocationService] Recheck failed:", error)
}
}
// ============================================================================
// TRACKING PROFILES
// ============================================================================
/**
* Fetches all tracking profiles
*/
static async getProfiles(): Promise<SavedTrackingProfile[]> {
this.ensureModule()
const raw = await this.safeExecute(() => LocationServiceModule.getProfiles(), [], "getProfiles failed")
return raw.map((p: any) => ({
id: p.id,
name: p.name,
interval: p.intervalMs / 1000, // ms → seconds for UI
distance: p.minUpdateDistance,
syncInterval: p.syncIntervalSeconds,
priority: p.priority,
condition: {
type: p.conditionType,
...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {}),
...(p.wifiSsid != null ? { ssid: p.wifiSsid } : {}),
...(p.bluetoothAddress != null ? { bluetoothAddress: p.bluetoothAddress } : {}),
...(p.bluetoothName != null ? { bluetoothName: p.bluetoothName } : {})
},
activationDelay: p.activationDelaySeconds,
deactivationDelay: p.deactivationDelaySeconds,
enabled: p.enabled,
createdAt: p.createdAt
}))
}
/**
* Creates a new tracking profile
* @returns Profile ID
*/
static async createProfile(profile: Omit<TrackingProfile, "id" | "createdAt">): Promise<number> {
this.ensureModule()
logger.debug("[NativeLocationService] Creating profile:", profile.name)
return LocationServiceModule.createProfile({
name: profile.name,
intervalMs: profile.interval * 1000, // seconds → ms
minUpdateDistance: profile.distance,
syncIntervalSeconds: profile.syncInterval,
priority: profile.priority,
conditionType: profile.condition.type,
speedThreshold: profile.condition.speedThreshold ?? null,
wifiSsid: profile.condition.ssid ?? null,
bluetoothAddress: profile.condition.bluetoothAddress ?? null,
bluetoothName: profile.condition.bluetoothName ?? null,
deactivationDelaySeconds: profile.deactivationDelay,
activationDelaySeconds: profile.activationDelay
})
}
/**
* Updates an existing tracking profile (partial updates supported)
*/
static async updateProfile(update: Partial<TrackingProfile> & { id: number }): Promise<boolean> {
this.ensureModule()
logger.debug("[NativeLocationService] Updating profile:", update.id)
const config: any = { id: update.id }
if (update.name !== undefined) config.name = update.name
if (update.interval !== undefined) config.intervalMs = update.interval * 1000
if (update.distance !== undefined) config.minUpdateDistance = update.distance
if (update.syncInterval !== undefined) config.syncIntervalSeconds = update.syncInterval
if (update.priority !== undefined) config.priority = update.priority
if (update.condition !== undefined) {
config.conditionType = update.condition.type
config.speedThreshold = update.condition.speedThreshold ?? null
config.wifiSsid = update.condition.ssid ?? null
config.bluetoothAddress = update.condition.bluetoothAddress ?? null
config.bluetoothName = update.condition.bluetoothName ?? null
}
if (update.deactivationDelay !== undefined) config.deactivationDelaySeconds = update.deactivationDelay
if (update.activationDelay !== undefined) config.activationDelaySeconds = update.activationDelay
if (update.enabled !== undefined) config.enabled = update.enabled
return LocationServiceModule.updateProfile(config)
}
/**
* Deletes a tracking profile
*/
static async deleteProfile(id: number): Promise<boolean> {
this.ensureModule()
logger.debug("[NativeLocationService] Deleting profile:", id)
return LocationServiceModule.deleteProfile(id)
}
/**
* Triggers profile re-evaluation in the foreground service
*/
static async recheckProfiles(): Promise<void> {
this.ensureModule()
try {
await LocationServiceModule.recheckProfiles()
} catch (error) {
logger.error("[NativeLocationService] Profile recheck failed:", error)
}
}
/**
* Returns the name and id of the currently active tracking profile, or null if using defaults
*/
static async getActiveProfile(): Promise<{ name: string; id: number | null } | null> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getActiveProfile(), null, "getActiveProfile failed")
}
// ============================================================================
// SETTINGS OPERATIONS
// ============================================================================
/**
* Saves a persistent setting
*/
static async saveSetting(key: string, value: string): Promise<void> {
this.ensureModule()
await LocationServiceModule.saveSetting(key, value)
}
/**
* Retrieves a setting by key
*/
static async getSetting(key: string, defaultValue: string = ""): Promise<string | null> {
this.ensureModule()
return LocationServiceModule.getSetting(key, defaultValue || null)
}
/**
* Retrieves all settings as key-value pairs.
* A few retries, then the rejection goes through: JS seeds defaults into the table on an empty result.
*/
static async getAllSettings(): Promise<Record<string, string>> {
this.ensureModule()
for (let attempt = 1; attempt < SETTINGS_READ_ATTEMPTS; attempt++) {
try {
return await LocationServiceModule.getAllSettings()
} catch (err) {
logger.warn(`[NativeLocationService] Settings read failed, retry ${attempt}/${SETTINGS_READ_ATTEMPTS}:`, err)
await new Promise<void>((resolve) => setTimeout(resolve, SETTINGS_READ_RETRY_DELAY_MS))
}
}
return LocationServiceModule.getAllSettings()
}
// ============================================================================
// NETWORK
// ============================================================================
/**
* Validates that the endpoint uses an allowed protocol.
* HTTPS is required for public hosts; HTTP is only allowed for private/local addresses.
* Uses DNS resolution on the native side to detect hostnames that resolve to private IPs.
*/
static async isValidEndpointProtocol(endpoint: string): Promise<boolean> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.isValidEndpointProtocol(endpoint),
false,
"isValidEndpointProtocol failed"
)
}
/**
* Returns true if the endpoint's host resolves to a private/local address via native DNS.
* Used to decide whether to prompt for local network permission (Android 15+).
*/
static async isPrivateEndpoint(endpoint: string): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.isPrivateEndpoint(endpoint), false, "isPrivateEndpoint failed")
}
/**
* Checks if the device has an active internet connection
*/
static async isNetworkAvailable(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.isNetworkAvailable(), false, "isNetworkAvailable failed")
}
/**
* Returns true if the current connection is unmetered (WiFi or ethernet).
* Returns false on mobile data or when offline.
*/
static async isUnmeteredConnection(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.isUnmeteredConnection(), false, "isUnmeteredConnection failed")
}
/**
* Returns the SSID of the currently connected Wi-Fi network, or empty string if unavailable.
*/
static async getCurrentSsid(): Promise<string> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getCurrentSsid(), "", "getCurrentSsid failed")
}
/**
* Returns the paired Bluetooth devices, null while Bluetooth is off, or an empty list without the Nearby devices permission.
*/
static async getBondedBluetoothDevices(): Promise<BluetoothDeviceInfo[] | null> {
this.ensureModule()
return this.safeExecute<BluetoothDeviceInfo[] | null>(
() => LocationServiceModule.getBondedBluetoothDevices(),
[],
"getBondedBluetoothDevices failed"
)
}
/**
* Returns available device storage in MB, or -1 if the check fails.
*/
static async getAvailableStorageMB(): Promise<number> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.getAvailableStorageMB(), -1, "getAvailableStorageMB failed")
}
// ============================================================================
// BATTERY OPTIMIZATION
// ============================================================================
/**
* Checks if app is exempt from battery optimization
*/
static async isIgnoringBatteryOptimizations(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(
() => LocationServiceModule.isIgnoringBatteryOptimizations(),
false,
"isIgnoringBatteryOptimizations failed"
)
}
/**
* Checks if battery is critically low (below 5% and discharging)
*/
static async isBatteryCritical(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.isBatteryCritical(), false, "isBatteryCritical failed")
}
/**
* Requests battery optimization exemption
* Opens system dialog for user approval
*/
static async requestIgnoreBatteryOptimizations(): Promise<boolean> {
this.ensureModule()
logger.debug("[NativeLocationService] Requesting battery optimization exemption")
return this.safeExecute(
() => LocationServiceModule.requestIgnoreBatteryOptimizations(),
false,
"requestIgnoreBatteryOptimizations failed"
)
}
/** Whether the system location toggle is on. App permission is separate. */
static async isLocationEnabled(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.isLocationEnabled(), false, "isLocationEnabled failed")
}
/** Opens system Location settings. */
static async openLocationSettings(): Promise<boolean> {
this.ensureModule()
return this.safeExecute(() => LocationServiceModule.openLocationSettings(), false, "openLocationSettings failed")
}
// ============================================================================
// BUILD CONFIGURATION
// ============================================================================
/**
* Gets build configuration constants
* @returns Build config object with SDK versions, tools versions, etc.
*/
static getBuildConfig(): {
VERSION_NAME: string
VERSION_CODE: number
FLAVOR: string
APP_LANGUAGE: string
} | null {
if (!BuildConfigModule) {
logger.warn("[NativeLocationService] BuildConfigModule not available")
return null
}
return BuildConfigModule
}
/** `picked` is "" while the app follows the system; `effective` is the language it runs in. Null when unreadable. */
static async getAppLanguage(): Promise<{ picked: string; effective: string } | null> {
if (!BuildConfigModule) return null
return this.safeExecute(() => BuildConfigModule.getAppLanguage(), null, "Failed to read the app language")
}
/** "" follows the system. Resolves with the tag of the language the app now runs in. */
static async setAppLanguage(tag: string): Promise<string> {
if (!BuildConfigModule) throw new Error("BuildConfigModule not available")
return BuildConfigModule.setAppLanguage(tag)
}
/**
* The wallpaper-derived tonal steps, or null below API 31 and whenever the map is not the
* complete set the theme reads.
*/
static async getSystemPalette(): Promise<SystemPalette | null> {
if (!BuildConfigModule) return null
return this.safeExecute(
async () => parseSystemPalette(await BuildConfigModule.getSystemPalette()),
null,
"Failed to read the system palette"
)
}
// ============================================================================
// DEVICE INFORMATION
// ============================================================================
/**
* Get all device information at once
*/
static async getDeviceInfo(): Promise<{
model: string
brand: string
systemVersion: string
apiLevel: number
}> {
this.ensureModule()
return LocationServiceModule.getDeviceInfo()
}
// ============================================================================
// FILE MANAGEMENT
// ============================================================================
/**
* Writes content to a file in cache directory
*/
static async writeFile(fileName: string, content: string): Promise<string> {
this.ensureModule()
return LocationServiceModule.writeFile(fileName, content)
}
/**
* Shares a file using native share sheet
*/
static async shareFile(filePath: string, mimeType: string, title: string): Promise<boolean> {
this.ensureModule()
return LocationServiceModule.shareFile(filePath, mimeType, title)
}
/**
* Copies text to the system clipboard
*/
static async copyToClipboard(text: string, label: string = "Colota"): Promise<void> {
this.ensureModule()
await LocationServiceModule.copyToClipboard(text, label)
}
/**
* Deletes a file
*/
static async deleteFile(filePath: string): Promise<boolean> {
this.ensureModule()
return LocationServiceModule.deleteFile(filePath)
}
/**
* Gets cache directory path
*/
static async getCacheDirectory(): Promise<string> {
this.ensureModule()
return LocationServiceModule.getCacheDirectory()
}
/** Logcat entries for the app's process, or file-log entries when file logging is enabled. */
static async getNativeLogs(): Promise<string[]> {
this.ensureModule()
return LocationServiceModule.getNativeLogs()
}
// ============================================================================
// FILE LOGGING (debug)
// ============================================================================
static async setFileLoggingEnabled(enabled: boolean): Promise<void> {
this.ensureModule()
await LocationServiceModule.setFileLoggingEnabled(enabled)
}
static async clearFileLog(): Promise<void> {
this.ensureModule()
await LocationServiceModule.clearFileLog()
}
static async getFileLogSize(): Promise<number> {
this.ensureModule()
return LocationServiceModule.getFileLogSize()
}
/** Returns null if there are no entries to export. */
static async exportFileLogToUri(treeUri: string, header: string, appLog: string): Promise<string | null> {
this.ensureModule()
return LocationServiceModule.exportFileLogToUri(treeUri, header, appLog)
}
// ============================================================================
// 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()
}
/**
* Marks enabledAt and arms the first auto-export alarm.
*/
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()
}
/**
* Re-arms the auto-export alarm after a schedule-affecting setting change.
*/
static async rescheduleAutoExport(): Promise<boolean> {
this.ensureModule()
return LocationServiceModule.rescheduleAutoExport()
}
/**
* Returns current auto-export configuration and status.
*/
static async getAutoExportStatus(): Promise<{
enabled: boolean
running: 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
timeOfDay: string
weeklyDow: number
monthlyDom: number
filenameTemplate: string
deviceModel: string
}> {
this.ensureModule()
return LocationServiceModule.getAutoExportStatus()
}
/**
* Returns export files matching the configured filename template, newest first by the
* timestamp embedded in the name.
*/
static async getExportFiles(): Promise<{ name: string; size: number; lastModified: number; uri: string }[]> {
this.ensureModule()
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)
}
/**
* Exports the given trips as a trip-segmented file (CSV/GeoJSON/GPX/KML).
* Rows are queried natively per trip range. Returns the written file path.
*/
static async exportTripsToFile(
trips: { index: number; color: string; startTs: number; endTs: number }[],
format: string,
fileName: string
): Promise<string> {
this.ensureModule()
return LocationServiceModule.exportTripsToFile(trips, format, fileName)
}
// ============================================================================
// SECURE STORAGE (Auth & Headers)
// ============================================================================
/**
* Retrieves the full auth configuration from encrypted storage
*/
static async getAuthConfig(): Promise<AuthConfig> {
this.ensureModule()
const raw = await LocationServiceModule.getAllAuthConfig()
let customHeaders: Record<string, string> = {}
if (raw.customHeaders) {
try {
customHeaders = JSON.parse(raw.customHeaders)
} catch {
// Corrupted JSON - reset to empty
}
}
return {
authType: raw.authType || "none",
username: raw.username || "",
password: raw.password || "",
bearerToken: raw.bearerToken || "",
customHeaders
}
}
/**
* Saves auth configuration to encrypted storage
*/
static async saveAuthConfig(config: AuthConfig): Promise<boolean> {
this.ensureModule()
return LocationServiceModule.saveAuthConfig({
authType: config.authType,
username: config.username,
password: config.password,
bearerToken: config.bearerToken,
customHeaders: JSON.stringify(config.customHeaders)
})
}
/**
* Returns computed auth + custom headers for HTTP requests
*/
static async getAuthHeaders(): Promise<Record<string, string>> {
this.ensureModule()
return LocationServiceModule.getAuthHeaders()
}
// ============================================================================
// mTLS CLIENT CERTIFICATE (delegates to MtlsBridgeModule)
// ============================================================================
private static ensureMtlsModule(): void {
if (!MtlsBridgeModule) {
throw new Error("[NativeLocationService] MtlsBridgeModule not available. Check native linking.")
}
}
static async pickClientCertFile(): Promise<string | null> {
this.ensureMtlsModule()
return MtlsBridgeModule.pickClientCertFile()
}
/**
* Opens Android's system KeyChain picker. Returns cert info on selection,
* null on cancel. The private key stays in the OS keystore.
*/
static async pickKeyChainCert(): Promise<KeyChainPickResult | null> {
this.ensureMtlsModule()
return MtlsBridgeModule.pickKeyChainCert()
}
/**
* Rejects with `E_CERT_PASSWORD` on a bad password or `E_CERT_INVALID` on a
* malformed PKCS12.
*/
static async importClientCert(b64: string, password: string): Promise<ClientCertInfo> {
this.ensureMtlsModule()
return MtlsBridgeModule.importClientCert(b64, password)
}
static async clearClientCert(): Promise<boolean> {
this.ensureMtlsModule()
return MtlsBridgeModule.clearClientCert()
}
static async getClientCertInfo(): Promise<ClientCertInfoResult> {
this.ensureMtlsModule()
return MtlsBridgeModule.getClientCertInfo()
}
static async testEndpoint(args: TestEndpointArgs): Promise<TestEndpointResult> {
this.ensureMtlsModule()
return MtlsBridgeModule.testEndpoint(args)
}
static async pickServerCaFile(): Promise<string | null> {
this.ensureMtlsModule()
return MtlsBridgeModule.pickServerCaFile()
}
/** Rejects with `E_CA_INVALID` if the bytes don't parse as X.509 (PEM or DER). */
static async importServerCa(b64: string): Promise<ClientCertInfo> {
this.ensureMtlsModule()
return MtlsBridgeModule.importServerCa(b64)
}
static async clearServerCa(): Promise<boolean> {
this.ensureMtlsModule()
return MtlsBridgeModule.clearServerCa()
}
static async getServerCaInfo(): Promise<ClientCertInfoResult> {
this.ensureMtlsModule()
return MtlsBridgeModule.getServerCaInfo()
}
}
export default NativeLocationService