Colota - Android GPS Location tracker
Add HTTP GET request support and Traccar template
Max Dietrich1493f9b095f4
diff --git a/README.md b/README.mdindex a76b6210..ee86cb14 100644--- a/README.md+++ b/README.md@@ -10,7 +10,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su## Features-- **Self-Hosted** — Send location data to your own server. Works with Dawarich, OwnTracks, Reitti, or any custom backend.+- **Self-Hosted** — Send location data to your own server. Works with Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, 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.- **Reliable Tracking** — Foreground service, auto-start on boot, exponential backoff retry.@@ -49,7 +49,7 @@ For full setup, server configuration, and integration guides, see the [documenta## Documentation-Full docs at **[colota.app](https://colota.app)** covers configuration, server integration (Dawarich, OwnTracks, Reitti, PhoneTracks and custom backends), geofencing, data export, API reference, battery optimization, troubleshooting, and development setup.+Full docs at **[colota.app](https://colota.app)** covers configuration, server integration (Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, and custom backends), geofencing, data export, API reference, battery optimization, troubleshooting, and development setup.## Build from Sourcediff --git a/apps/docs/docs/api-reference.md b/apps/docs/docs/api-reference.mdindex 86f08058..90cd2b78 100644--- a/apps/docs/docs/api-reference.md+++ b/apps/docs/docs/api-reference.md@@ -8,7 +8,11 @@ Reference for the HTTP requests Colota sends to your server.## Request-**Method:** `POST`+**Method:** `POST` (default) or `GET`++Configure the HTTP method in **Settings > API Settings > HTTP Method**.++### POST (default)**Headers:**@@ -35,6 +39,16 @@ Additional headers may be included based on your [authentication](/docs/configur}```+### GET++Fields are sent as URL query parameters instead of a JSON body. No `Content-Type` header is set. Authentication headers are still included if configured.++```+GET https://your-server.com:5055/?id=colota&lat=48.135124&lon=11.581981&accuracy=12&altitude=519&speed=0&batt=85&charge=2×tamp=1704067200&bearing=180.5+```++Values are URL-encoded. If the endpoint URL already contains query parameters, additional parameters are appended with `&`.+All field names are [customizable](/docs/configuration/field-mapping).### Field Types@@ -67,6 +81,8 @@ Your server should handle multiple simultaneous POST requests. If you have rate## Testing with curl+**POST (default):**+```bashcurl -X POST https://your-server.com/api/location \-H "Content-Type: application/json; charset=UTF-8" \@@ -74,7 +90,13 @@ curl -X POST https://your-server.com/api/location \-d '{"lat":48.135,"lon":11.582,"acc":12,"vel":0,"batt":85,"bs":2,"tst":1704067200}'```-With Basic Auth:+**GET (e.g., Traccar):**++```bash+curl "https://your-server.com:5055/?id=colota&lat=48.135&lon=11.582&accuracy=12&speed=0&batt=85×tamp=1704067200"+```++**With Basic Auth:**```bashcurl -X POST https://your-server.com/api/location \diff --git a/apps/docs/docs/configuration/field-mapping.md b/apps/docs/docs/configuration/field-mapping.mdindex 7f186e86..27270965 100644--- a/apps/docs/docs/configuration/field-mapping.md+++ b/apps/docs/docs/configuration/field-mapping.md@@ -4,7 +4,7 @@ sidebar_position: 4# Field Mapping-Customize the JSON field names in the payload to match your server's API.+Customize field names sent to your server. Field names apply to both POST (JSON body) and GET (query parameters) requests.## Default Fieldsdiff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.mdindex 81cabf8b..6f0e5476 100644--- a/apps/docs/docs/configuration/server-settings.md+++ b/apps/docs/docs/configuration/server-settings.md@@ -7,13 +7,14 @@ sidebar_position: 3| Setting | Description | Default | Range || -------------------- | ----------------------------------------- | --------------- | ---------- || Endpoint | HTTPS URL of your server | Empty (offline) | -- |+| HTTP Method | POST (JSON body) or GET (query params) | POST | POST / GET || Sync Interval | Batch mode interval | Instant (0) | 0s - 15min || Retry Failed Uploads | Keep retrying failed uploads indefinitely | Off | On/Off || Offline Mode | Disable all network activity | Disabled | On/Off |## Endpoint URL-Your server endpoint must accept HTTPS POST requests. HTTP is only allowed for private/local addresses:+Your server endpoint must accept HTTPS requests (POST or GET depending on your HTTP Method setting). HTTP is only allowed for private/local addresses:- `127.0.0.1` / `localhost`- `192.168.x.x`diff --git a/apps/docs/docs/integrations/api-templates.md b/apps/docs/docs/integrations/api-templates.mdindex 1f4dd844..5e2492d4 100644--- a/apps/docs/docs/integrations/api-templates.md+++ b/apps/docs/docs/integrations/api-templates.md@@ -6,13 +6,15 @@ sidebar_position: 1Colota includes built-in templates for popular backends. Select a template in **Settings > API Settings** to auto-configure field mappings and custom fields.-| Template | Bearing Field | Custom Fields | Notes |-| ------------- | ------------- | -------------------------------- | ------------------------------ |-| **Dawarich** | `cog` | `_type: "location"` | OwnTracks-compatible format |-| **OwnTracks** | `cog` | `_type: "location"`, `tid: "AA"` | Standard OwnTracks HTTP format |-| **Reitti** | `bear` | `_type: "location"` | Standard field names |-| **Custom** | `bear` | _(none)_ | Fully user-defined |+| Template | HTTP Method | Bearing Field | Custom Fields | Notes |+| -------------- | ----------- | ------------- | -------------------------------- | --------------------------------- |+| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks-compatible format |+| **OwnTracks** | POST | `cog` | `_type: "location"`, `tid: "AA"` | Standard OwnTracks HTTP format |+| **PhoneTrack** | POST | `bearing` | `_type: "location"` | Nextcloud PhoneTrack format |+| **Reitti** | POST | `bear` | `_type: "location"` | Standard field names |+| **Traccar** | GET | `bearing` | `id: "colota"` | OsmAnd protocol with query params |+| **Custom** | POST | `bear` | _(none)_ | Fully user-defined |-All templates share the same base fields: `lat`, `lon`, `acc`, `alt`, `vel`, `batt`, `bs`, `tst`. The key differences are the bearing field name and auto-included custom fields.+All templates share the same base fields (`lat`, `lon`, `acc`, `alt`, `vel`, `batt`, `bs`, `tst`) with different field names. Key differences are the HTTP method, bearing field name, and auto-included custom fields.-When you select a template, field mapping and custom fields are automatically configured. You can still customize individual fields after applying a template.+When you select a template, field mapping, custom fields, and HTTP method are automatically configured. You can still customize individual fields or switch the HTTP method after applying a template — doing so switches the template to "Custom".diff --git a/apps/docs/docs/integrations/custom-backend.md b/apps/docs/docs/integrations/custom-backend.mdindex 2dcc82db..220efde0 100644--- a/apps/docs/docs/integrations/custom-backend.md+++ b/apps/docs/docs/integrations/custom-backend.md@@ -4,14 +4,13 @@ sidebar_position: 5# Custom Backend-Colota works with any backend that accepts JSON over HTTP.+Colota works with any backend that accepts HTTP requests (POST with JSON body or GET with query parameters).## Minimum RequirementsYour server needs to:-- Accept `POST` requests with `Content-Type: application/json; charset=UTF-8`-- Parse the JSON body (see [field types](/docs/api-reference#field-types))+- Accept `POST` requests with JSON body, or `GET` requests with query parameters- Return a 2xx status code on success- Handle `alt` and `bear` fields being absent (they are conditional)- Handle up to 10 concurrent requests during batch sync@@ -101,12 +100,19 @@ your-domain.com {## Compatible Backends-Colota works with any service that accepts JSON POST requests, including:+Colota works with any service that accepts HTTP POST or GET requests. Built-in templates are available for:++- **[Dawarich](/docs/integrations/dawarich)** - Self-hosted location history+- **[OwnTracks](/docs/integrations/owntracks)** - Self-hosted presence tracking+- **[PhoneTrack](/docs/integrations/phonetrack)** - Nextcloud location tracking+- **[Reitti](/docs/integrations/reitti)** - Self-hosted location tracking+- **[Traccar](/docs/integrations/traccar)** - GPS tracking platform (HTTP GET)++Also works with:- **Home Assistant** - via webhook or REST API-- **Traccar** - GPS tracking platform- **Node-RED** - flow-based automation-- **Custom APIs** - any server you build+- **Any HTTP server** - that accepts POST (JSON) or GET (query params)## Configurationdiff --git a/apps/docs/docs/integrations/phonetrack.md b/apps/docs/docs/integrations/phonetrack.mdnew file mode 100644index 00000000..464f21eb--- /dev/null+++ b/apps/docs/docs/integrations/phonetrack.md@@ -0,0 +1,54 @@+---+sidebar_position: 5+---++# PhoneTrack (Nextcloud)++[PhoneTrack](https://apps.nextcloud.com/apps/phonetrack) is a Nextcloud app for tracking mobile devices.++## Setup++1. **Install PhoneTrack** from the Nextcloud app store+2. **Create a session** in PhoneTrack and get the logging URL+3. **Configure Colota**:+ - Go to **Settings > API Settings**+ - Select the **PhoneTrack** template+ - Set your endpoint to the PhoneTrack logging URL:+ ```+ https://nextcloud.yourdomain.com/apps/phonetrack/log/gps/SESSION_TOKEN/DEVICE_NAME+ ```++## Payload Format++The PhoneTrack template auto-configures the following payload:++```json+{+ "_type": "location",+ "lat": 51.495065,+ "lon": -0.043945,+ "acc": 12,+ "alt": 519,+ "speed": 0,+ "bat": 85,+ "bs": 2,+ "timestamp": 1704067200,+ "bearing": 180.5+}+```++## Field Mapping++| Colota Field | PhoneTrack Field | Description |+| ------------ | ---------------- | --------------------- |+| `lat` | `lat` | Latitude |+| `lon` | `lon` | Longitude |+| `acc` | `acc` | GPS accuracy (meters) |+| `alt` | `alt` | Altitude (meters) |+| `vel` | `speed` | Speed (m/s) |+| `batt` | `bat` | Battery level (0-100) |+| `bs` | `bs` | Battery status |+| `tst` | `timestamp` | Unix timestamp |+| `bear` | `bearing` | Bearing (degrees) |++Note: PhoneTrack uses `speed`, `bat`, `timestamp`, and `bearing` instead of the default `vel`, `batt`, `tst`, and `bear` field names.diff --git a/apps/docs/docs/integrations/traccar.md b/apps/docs/docs/integrations/traccar.mdnew file mode 100644index 00000000..23106b45--- /dev/null+++ b/apps/docs/docs/integrations/traccar.md@@ -0,0 +1,52 @@+---+sidebar_position: 6+---++# Traccar++[Traccar](https://www.traccar.org/) is an open source GPS tracking platform.++Colota connects to Traccar using the OsmAnd protocol, which sends location data as HTTP GET query parameters.++## Setup++1. **Install Traccar** - follow the [Traccar documentation](https://www.traccar.org/documentation/)+2. **Create a device** in the Traccar web interface and note the device identifier+3. **Configure Colota**:+ - Go to **Settings > API Settings**+ - Select the **Traccar** template (this auto-selects GET as HTTP method)+ - Set the `id` custom field to your Traccar device identifier+ - Set your endpoint:+ ```+ https://traccar.yourdomain.com:5055/+ ```++The default OsmAnd protocol port is **5055**. Adjust if you changed it in your Traccar configuration.++## Request Format++The Traccar template uses HTTP GET with query parameters:++```+GET https://traccar.yourdomain.com:5055/?id=colota&lat=51.495065&lon=-0.043945&accuracy=12&altitude=519&speed=0&batt=85&charge=2×tamp=1704067200&bearing=180.5+```++## Field Mapping++| Colota Field | Traccar Parameter | Description |+| ------------ | ----------------- | --------------------- |+| `lat` | `lat` | Latitude |+| `lon` | `lon` | Longitude |+| `acc` | `accuracy` | GPS accuracy (meters) |+| `alt` | `altitude` | Altitude (meters) |+| `vel` | `speed` | Speed (m/s) |+| `batt` | `batt` | Battery level (0-100) |+| `bs` | `charge` | Charging status |+| `tst` | `timestamp` | Unix timestamp |+| `bear` | `bearing` | Bearing (degrees) |++## Notes++- The `id` custom field is required — Traccar uses it to identify the device+- Traccar also supports POST with JSON, but the OsmAnd GET protocol is the simplest integration+- If you need POST, switch the HTTP method to POST and adjust field names as neededdiff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 301ecf10..c3f85b84 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -9,7 +9,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to## Key Features-- **Self-Hosted** — Send location data to your own server via REST API. Works with Dawarich, OwnTracks, Reitti, or any custom backend that accepts JSON over HTTP.+- **Self-Hosted** — Send location data to your own server via REST API. Works with Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or any custom backend.- **Privacy First** — No analytics, no telemetry, no third-party SDKs, no cloud services. Open source under AGPL-3.0.- **Works Offline** — Works without a server. Store location history locally and export as CSV, GeoJSON, GPX, or KML.- **Background Tracking** — Foreground service, auto-start on boot, retry with exponential backoff, battery-critical shutdown.@@ -23,17 +23,17 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location toColota has nine screens, each focused on a specific task:-| Screen | Purpose |-| ---------------------- | ----------------------------------------------------------------------------------------- |-| **Dashboard** | Live map with current coordinates, tracking controls, database stats, and geofence status |-| **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold |-| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, Reitti, or custom backends |-| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |-| **Geofences** | Create, edit, and delete pause zones on an interactive map |-| **Location Inspector** | Debug view for sent and queued locations with pagination and accuracy indicators |-| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |-| **Data Management** | Clear sent history, delete old data, vacuum the database |-| **About** | App version, device info, links to repository and privacy policy |+| Screen | Purpose |+| --- | --- |+| **Dashboard** | Live map with current coordinates, tracking controls, database stats, and geofence status |+| **Settings** | GPS polling interval, distance filter, sync strategy, offline mode, accuracy threshold |+| **API Config** | Endpoint field mapping with templates for Dawarich, OwnTracks, PhoneTrack, Reitti, Traccar, or custom backends |+| **Auth Settings** | Endpoint authentication (None, Basic Auth, Bearer Token) and custom HTTP headers |+| **Geofences** | Create, edit, and delete pause zones on an interactive map |+| **Location Inspector** | Debug view for sent and queued locations with pagination and accuracy indicators |+| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML |+| **Data Management** | Clear sent history, delete old data, vacuum the database |+| **About** | App version, device info, links to repository and privacy policy |## Screenshotsdiff --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 68b591fc..0e005b2f 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@@ -138,7 +138,8 @@ class DatabaseHelper private constructor(context: Context) :"hasCompletedSetup" to "false","tracking_enabled" to "false","apiTemplate" to "custom",- "syncPreset" to "instant"+ "syncPreset" to "instant",+ "httpMethod" to "POST")db.beginTransaction()diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex f20e765b..1604940f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt@@ -568,7 +568,8 @@ class LocationForegroundService : Service() {retryIntervalSeconds = config.retryIntervalSeconds,maxRetries = config.maxRetries,isOfflineMode = config.isOfflineMode,- authHeaders = secureStorage.getAuthHeaders()+ authHeaders = secureStorage.getAuthHeaders(),+ httpMethod = config.httpMethod)config.fieldMap?.let {diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.ktindex 4b34e42d..8a95d6ae 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ServiceConfig.kt@@ -25,7 +25,8 @@ data class ServiceConfig(val retryIntervalSeconds: Int = 30,val isOfflineMode: Boolean = false,val fieldMap: String? = null,- val customFields: String? = null+ val customFields: String? = null,+ val httpMethod: String = "POST") {companion object {fun fromDatabase(dbHelper: DatabaseHelper): ServiceConfig {@@ -42,10 +43,11 @@ data class ServiceConfig(retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 300,isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false,fieldMap = saved["fieldMap"],- customFields = saved["customFields"]+ customFields = saved["customFields"],+ httpMethod = saved["httpMethod"] ?: "POST")}-+fun fromReadableMap(config: ReadableMap, dbHelper: DatabaseHelper): ServiceConfig {val dbConfig = fromDatabase(dbHelper)@@ -80,7 +82,8 @@ data class ServiceConfig(retryIntervalSeconds = config.getIntOrNull("retryInterval") ?: dbConfig.retryIntervalSeconds,isOfflineMode = config.getBooleanOrNull("isOfflineMode") ?: dbConfig.isOfflineMode,fieldMap = fieldMapJson ?: dbConfig.fieldMap,- customFields = customFieldsJson ?: dbConfig.customFields+ customFields = customFieldsJson ?: dbConfig.customFields,+ httpMethod = config.getStringOrNull("httpMethod") ?: dbConfig.httpMethod)}@@ -99,7 +102,8 @@ data class ServiceConfig(retryIntervalSeconds = extras.getIntOrDefault("retryInterval", dbConfig.retryIntervalSeconds),isOfflineMode = extras.getBooleanOrDefault("isOfflineMode", dbConfig.isOfflineMode),fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap),- customFields = extras.getStringOrDefault("customFields", dbConfig.customFields)+ customFields = extras.getStringOrDefault("customFields", dbConfig.customFields),+ httpMethod = extras.getStringOrDefault("httpMethod", dbConfig.httpMethod) ?: "POST")}}@@ -117,6 +121,7 @@ data class ServiceConfig(putExtra("isOfflineMode", isOfflineMode)fieldMap?.let { putExtra("fieldMap", it) }customFields?.let { putExtra("customFields", it) }+ putExtra("httpMethod", httpMethod)}}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.ktindex 889e98d7..7474cb53 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt@@ -11,6 +11,7 @@ import kotlinx.coroutines.withContextimport org.json.JSONObjectimport java.net.HttpURLConnectionimport java.net.URL+import java.net.URLEncoderimport java.nio.charset.StandardCharsets/**@@ -41,12 +42,14 @@ class NetworkManager(private val context: Context) {}/**- * Executes an asynchronous POST request to the server.+ * Sends a location payload to the configured endpoint.+ * POST sends JSON in the body; GET appends fields as query parameters.*/suspend fun sendToEndpoint(payload: JSONObject,endpoint: String,- extraHeaders: Map<String, String> = emptyMap()+ extraHeaders: Map<String, String> = emptyMap(),+ httpMethod: String = "POST"): Boolean = withContext(Dispatchers.IO) {if (endpoint.isBlank()) {if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")@@ -70,17 +73,29 @@ class NetworkManager(private val context: Context) {return@withContext false}+ val isGet = httpMethod.equals("GET", ignoreCase = true)++ val targetUrl = if (isGet) {+ val query = buildQueryString(payload)+ val separator = if (url.query != null) "&" else "?"+ URL("$endpoint$separator$query")+ } else {+ url+ }+var connection: HttpURLConnection? = nulltry {- connection = url.openConnection() as HttpURLConnection+ connection = targetUrl.openConnection() as HttpURLConnectionconnection.apply {- requestMethod = "POST"- setRequestProperty("Content-Type", "application/json; charset=UTF-8")- setRequestProperty("Accept", "application/json")+ requestMethod = if (isGet) "GET" else "POST"+ if (!isGet) {+ setRequestProperty("Content-Type", "application/json; charset=UTF-8")+ setRequestProperty("Accept", "application/json")+ doOutput = true+ }extraHeaders.forEach { (key, value) ->setRequestProperty(key, value)}- doOutput = trueconnectTimeout = CONNECTION_TIMEOUTreadTimeout = READ_TIMEOUTuseCaches = false@@ -88,20 +103,24 @@ class NetworkManager(private val context: Context) {if (BuildConfig.DEBUG) {Log.d(TAG, "=== HTTP REQUEST ===")- Log.d(TAG, "Endpoint: $endpoint")- Log.d(TAG, "Method: POST")+ Log.d(TAG, "Endpoint: ${if (isGet) targetUrl else endpoint}")+ Log.d(TAG, "Method: ${connection.requestMethod}")Log.d(TAG, "Headers:")connection.requestProperties.forEach { (key, values) ->val masked = values.map { maskSensitiveHeaderValue(key, it) }Log.d(TAG, "$key: ${masked.joinToString()}")}- Log.d(TAG, "Body: ${payload.toString(2)}") // Pretty print JSON+ if (!isGet) {+ Log.d(TAG, "Body: ${payload.toString(2)}")+ }Log.d(TAG, "===================")}- val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)- connection.setFixedLengthStreamingMode(bodyBytes.size)- connection.outputStream.use { it.write(bodyBytes) }+ if (!isGet) {+ val bodyBytes = payload.toString().toByteArray(StandardCharsets.UTF_8)+ connection.setFixedLengthStreamingMode(bodyBytes.size)+ connection.outputStream.use { it.write(bodyBytes) }+ }val responseCode = connection.responseCodereturn@withContext if (responseCode in 200..299) {@@ -111,7 +130,7 @@ class NetworkManager(private val context: Context) {val errorBody = try {connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"} catch (_: Exception) { "Could not read error body" }- Log.e(TAG, "POST failed: $responseCode - $errorBody")+ Log.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")false}} catch (e: Exception) {@@ -171,6 +190,17 @@ class NetworkManager(private val context: Context) {}}+ private fun buildQueryString(payload: JSONObject): String {+ val params = mutableListOf<String>()+ val keys = payload.keys()+ while (keys.hasNext()) {+ val key = keys.next()+ val value = payload.opt(key)?.toString() ?: continue+ params.add("${URLEncoder.encode(key, "UTF-8")}=${URLEncoder.encode(value, "UTF-8")}")+ }+ return params.joinToString("&")+ }+/*** Checks for an active, validated internet connection with caching.*/diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.ktindex 6a83f3ad..23f8c25b 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/SyncManager.kt@@ -32,6 +32,7 @@ class SyncManager(private var maxRetries: Int = 5private var isOfflineMode: Boolean = falseprivate var authHeaders: Map<String, String> = emptyMap()+ private var httpMethod: String = "POST"private var syncJob: Job? = null@Volatile private var lastSyncTime: Long = 0@@ -50,7 +51,8 @@ class SyncManager(retryIntervalSeconds: Int,maxRetries: Int,isOfflineMode: Boolean,- authHeaders: Map<String, String>+ authHeaders: Map<String, String>,+ httpMethod: String = "POST") {this.endpoint = endpointthis.syncIntervalSeconds = syncIntervalSeconds@@ -58,6 +60,7 @@ class SyncManager(this.maxRetries = maxRetriesthis.isOfflineMode = isOfflineModethis.authHeaders = authHeaders+ this.httpMethod = httpMethod}fun startPeriodicSync() {@@ -129,7 +132,7 @@ class SyncManager(// Immediate send mode (syncInterval = 0)if (syncIntervalSeconds == 0 && networkManager.isNetworkAvailable()) {Log.d(TAG, "Instant send")- val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders)+ val success = networkManager.sendToEndpoint(payload, endpoint, authHeaders, httpMethod)if (success) {dbHelper.removeFromQueueByLocationId(locationId)@@ -211,7 +214,8 @@ class SyncManager(val success = networkManager.sendToEndpoint(JSONObject(item.payload),endpoint,- authHeaders+ authHeaders,+ httpMethod)item.queueId to success}diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsxindex dc198324..7394b49b 100644--- a/apps/mobile/src/contexts/TrackingProvider.tsx+++ b/apps/mobile/src/contexts/TrackingProvider.tsx@@ -4,7 +4,7 @@*/import React, { createContext, useContext, useState, useEffect, useMemo, useCallback, useRef } from "react"-import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName } from "../types/global"+import { Settings, DEFAULT_SETTINGS, LocationCoords, ApiTemplateName, HttpMethod } from "../types/global"import { useLocationTracking } from "../hooks/useLocationTracking"import NativeLocationService from "../services/NativeLocationService"import SettingsService from "../services/SettingsService"@@ -55,6 +55,7 @@ function parseRawSettings(allRaw: Record<string, string>): Settings {customFields: allRaw.customFields ? JSON.parse(allRaw.customFields) : DEFAULT_SETTINGS.customFields,apiTemplate: (allRaw.apiTemplate as ApiTemplateName) ?? DEFAULT_SETTINGS.apiTemplate,+ httpMethod: (allRaw.httpMethod as HttpMethod) ?? DEFAULT_SETTINGS.httpMethod,hasCompletedSetup: allRaw.hasCompletedSetup === "true"}diff --git a/apps/mobile/src/screens/ApiSettingsScreen.tsx b/apps/mobile/src/screens/ApiSettingsScreen.tsxindex ffd71ed9..d306c93c 100644--- a/apps/mobile/src/screens/ApiSettingsScreen.tsx+++ b/apps/mobile/src/screens/ApiSettingsScreen.tsx@@ -5,7 +5,15 @@import React, { useState, useCallback } from "react"import { Text, StyleSheet, TextInput, View, ScrollView, TouchableOpacity } from "react-native"-import { FieldMap, DEFAULT_FIELD_MAP, ScreenProps, CustomField, ApiTemplateName, API_TEMPLATES } from "../types/global"+import {+ FieldMap,+ DEFAULT_FIELD_MAP,+ ScreenProps,+ CustomField,+ ApiTemplateName,+ API_TEMPLATES,+ HttpMethod+} from "../types/global"import { useTheme } from "../hooks/useTheme"import { useAutoSave } from "../hooks/useAutoSave"import { useTracking } from "../contexts/TrackingProvider"@@ -30,7 +38,13 @@ const TEMPLATE_OPTIONS: { value: ApiTemplateName; label: string }[] = [{ value: "dawarich", label: "Dawarich" },{ value: "owntracks", label: "OwnTracks" },{ value: "phonetrack", label: "PhoneTrack" },- { value: "reitti", label: "Reitti" }+ { value: "reitti", label: "Reitti" },+ { value: "traccar", label: "Traccar" }+]++const HTTP_METHOD_OPTIONS: { value: HttpMethod; label: string }[] = [+ { value: "POST", label: "POST" },+ { value: "GET", label: "GET" }]/**@@ -58,6 +72,7 @@ export function ApiSettingsScreen({}: ScreenProps) {const [localFieldMap, setLocalFieldMap] = useState<FieldMap>(settings.fieldMap || DEFAULT_FIELD_MAP)const [localCustomFields, setLocalCustomFields] = useState<CustomField[]>(settings.customFields || [])const [localTemplate, setLocalTemplate] = useState<ApiTemplateName>(settings.apiTemplate || "custom")+ const [localHttpMethod, setLocalHttpMethod] = useState<HttpMethod>(settings.httpMethod || "POST")const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()const referenceFieldMap = getReferenceFieldMap(localTemplate)@@ -74,7 +89,12 @@ export function ApiSettingsScreen({}: ScreenProps) {* Returns null if validation fails (empty field mappings).*/const buildSanitizedSettings = useCallback(- (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {+ (+ newFieldMap: FieldMap,+ newCustomFields: CustomField[],+ newTemplate: ApiTemplateName,+ newHttpMethod: HttpMethod+ ) => {const sanitizedMap = Object.fromEntries(Object.entries(newFieldMap).map(([key, value]) => [key, value.trim()])) as FieldMap@@ -91,7 +111,8 @@ export function ApiSettingsScreen({}: ScreenProps) {...settings,fieldMap: sanitizedMap,customFields: sanitizedCustomFields,- apiTemplate: newTemplate+ apiTemplate: newTemplate,+ httpMethod: newHttpMethod}},[settings]@@ -101,8 +122,13 @@ export function ApiSettingsScreen({}: ScreenProps) {* Debounced save + restart for continuous changes (typing)*/const debouncedSave = useCallback(- (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {- const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate)+ (+ newFieldMap: FieldMap,+ newCustomFields: CustomField[],+ newTemplate: ApiTemplateName,+ newHttpMethod: HttpMethod+ ) => {+ const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate, newHttpMethod)if (!newSettings) returndebouncedSaveAndRestart(@@ -117,8 +143,13 @@ export function ApiSettingsScreen({}: ScreenProps) {* Immediate save + restart for discrete changes (template switch, reset, remove)*/const saveImmediately = useCallback(- (newFieldMap: FieldMap, newCustomFields: CustomField[], newTemplate: ApiTemplateName) => {- const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate)+ (+ newFieldMap: FieldMap,+ newCustomFields: CustomField[],+ newTemplate: ApiTemplateName,+ newHttpMethod: HttpMethod+ ) => {+ const newSettings = buildSanitizedSettings(newFieldMap, newCustomFields, newTemplate, newHttpMethod)if (!newSettings) returnimmediateSaveAndRestart(@@ -137,15 +168,17 @@ export function ApiSettingsScreen({}: ScreenProps) {setLocalTemplate(template)if (template === "custom") {- saveImmediately(localFieldMap, localCustomFields, template)+ saveImmediately(localFieldMap, localCustomFields, template, localHttpMethod)} else {const tmpl = API_TEMPLATES[template]+ const method = tmpl.httpMethod ?? "POST"setLocalFieldMap(tmpl.fieldMap)setLocalCustomFields(tmpl.customFields)- saveImmediately(tmpl.fieldMap, tmpl.customFields, template)+ setLocalHttpMethod(method)+ saveImmediately(tmpl.fieldMap, tmpl.customFields, template, method)}},- [localFieldMap, localCustomFields, saveImmediately]+ [localFieldMap, localCustomFields, localHttpMethod, saveImmediately])/**@@ -160,9 +193,9 @@ export function ApiSettingsScreen({}: ScreenProps) {const newTemplate = localTemplate !== "custom" ? "custom" : localTemplateif (newTemplate !== localTemplate) setLocalTemplate(newTemplate)- debouncedSave(newFieldMap, localCustomFields, newTemplate)+ debouncedSave(newFieldMap, localCustomFields, newTemplate, localHttpMethod)},- [localFieldMap, localCustomFields, localTemplate, debouncedSave]+ [localFieldMap, localCustomFields, localTemplate, localHttpMethod, debouncedSave])/**@@ -172,9 +205,9 @@ export function ApiSettingsScreen({}: ScreenProps) {(key: keyof FieldMap) => {const newFieldMap = { ...localFieldMap, [key]: referenceFieldMap[key] }setLocalFieldMap(newFieldMap)- saveImmediately(newFieldMap, localCustomFields, localTemplate)+ saveImmediately(newFieldMap, localCustomFields, localTemplate, localHttpMethod)},- [localFieldMap, localCustomFields, localTemplate, referenceFieldMap, saveImmediately]+ [localFieldMap, localCustomFields, localTemplate, localHttpMethod, referenceFieldMap, saveImmediately])/**@@ -184,8 +217,8 @@ export function ApiSettingsScreen({}: ScreenProps) {const refFields = getReferenceCustomFields(localTemplate)setLocalFieldMap(referenceFieldMap)setLocalCustomFields(refFields)- saveImmediately(referenceFieldMap, refFields, localTemplate)- }, [referenceFieldMap, localTemplate, saveImmediately])+ saveImmediately(referenceFieldMap, refFields, localTemplate, localHttpMethod)+ }, [referenceFieldMap, localTemplate, localHttpMethod, saveImmediately])// --- Custom Fields handlers ---@@ -203,9 +236,9 @@ export function ApiSettingsScreen({}: ScreenProps) {const newTemplate = localTemplate !== "custom" ? "custom" : localTemplateif (newTemplate !== localTemplate) setLocalTemplate(newTemplate)- debouncedSave(localFieldMap, newFields, newTemplate)+ debouncedSave(localFieldMap, newFields, newTemplate, localHttpMethod)},- [localCustomFields, localFieldMap, localTemplate, debouncedSave]+ [localCustomFields, localFieldMap, localTemplate, localHttpMethod, debouncedSave])const handleRemoveCustomField = useCallback(@@ -216,9 +249,21 @@ export function ApiSettingsScreen({}: ScreenProps) {const newTemplate = localTemplate !== "custom" ? "custom" : localTemplateif (newTemplate !== localTemplate) setLocalTemplate(newTemplate)- saveImmediately(localFieldMap, newFields, newTemplate)+ saveImmediately(localFieldMap, newFields, newTemplate, localHttpMethod)+ },+ [localCustomFields, localFieldMap, localTemplate, localHttpMethod, saveImmediately]+ )++ const handleHttpMethodChange = useCallback(+ (method: HttpMethod) => {+ setLocalHttpMethod(method)++ const newTemplate = localTemplate !== "custom" ? "custom" : localTemplate+ if (newTemplate !== localTemplate) setLocalTemplate(newTemplate)++ saveImmediately(localFieldMap, localCustomFields, newTemplate, method)},- [localCustomFields, localFieldMap, localTemplate, saveImmediately]+ [localFieldMap, localCustomFields, localTemplate, saveImmediately])// Check if any field mapping is modified from the reference@@ -226,26 +271,30 @@ export function ApiSettingsScreen({}: ScreenProps) {// Build example payload string showing all fieldsconst examplePayload = (() => {- const entries: string[] = []+ const params: { key: string; value: string }[] = []// Custom static fields firstlocalCustomFields.forEach((f) => {- if (f.key) {- entries.push(` "${f.key}": "${f.value}"`)- }+ if (f.key) params.push({ key: f.key, value: f.value })})// All mapped fields with realistic example values- entries.push(` "${localFieldMap.lat}": 52.12345`)- entries.push(` "${localFieldMap.lon}": -2.12345`)- entries.push(` "${localFieldMap.acc}": 15`)- if (localFieldMap.alt) entries.push(` "${localFieldMap.alt}": 380`)- if (localFieldMap.vel) entries.push(` "${localFieldMap.vel}": 5`)- if (localFieldMap.batt) entries.push(` "${localFieldMap.batt}": 85`)- if (localFieldMap.bs) entries.push(` "${localFieldMap.bs}": 2`)- if (localFieldMap.tst) entries.push(` "${localFieldMap.tst}": 1739362800`)- if (localFieldMap.bear) entries.push(` "${localFieldMap.bear}": 180.0`)-+ params.push({ key: localFieldMap.lat, value: "52.12345" })+ params.push({ key: localFieldMap.lon, value: "-2.12345" })+ params.push({ key: localFieldMap.acc, value: "15" })+ if (localFieldMap.alt) params.push({ key: localFieldMap.alt, value: "380" })+ if (localFieldMap.vel) params.push({ key: localFieldMap.vel, value: "5" })+ if (localFieldMap.batt) params.push({ key: localFieldMap.batt, value: "85" })+ if (localFieldMap.bs) params.push({ key: localFieldMap.bs, value: "2" })+ if (localFieldMap.tst) params.push({ key: localFieldMap.tst, value: "1739362800" })+ if (localFieldMap.bear) params.push({ key: localFieldMap.bear, value: "180.0" })++ if (localHttpMethod === "GET") {+ const query = params.map((p) => `${p.key}=${p.value}`).join("&")+ return `GET https://...?${query}`+ }++ const entries = params.map((p) => ` "${p.key}": ${isNaN(Number(p.value)) ? `"${p.value}"` : p.value}`)return "{\n" + entries.join(",\n") + "\n}"})()@@ -304,6 +353,50 @@ export function ApiSettingsScreen({}: ScreenProps) {)}</View>+ {/* HTTP Method Selector */}+ <View style={styles.section}>+ <SectionTitle>HTTP METHOD</SectionTitle>+ <View style={styles.chipRow}>+ {HTTP_METHOD_OPTIONS.map(({ value, label }) => {+ const isSelected = localHttpMethod === value+ return (+ <TouchableOpacity+ key={value}+ style={[+ styles.chip,+ {+ borderColor: colors.border,+ backgroundColor: colors.background+ },+ isSelected && {+ borderColor: colors.primary,+ backgroundColor: colors.primary + "20"+ }+ ]}+ onPress={() => handleHttpMethodChange(value)}+ activeOpacity={0.7}+ >+ <Text+ style={[+ styles.chipText,+ {+ color: isSelected ? colors.primary : colors.text+ }+ ]}+ >+ {label}+ </Text>+ </TouchableOpacity>+ )+ })}+ </View>+ {localHttpMethod === "GET" && (+ <Text style={[styles.templateHint, { color: colors.textSecondary }]}>+ Fields sent as URL query parameters instead of JSON body+ </Text>+ )}+ </View>+{/* Field Mapping Section */}<View style={styles.fieldsSection}><View style={styles.sectionHeader}>@@ -439,7 +532,7 @@ export function ApiSettingsScreen({}: ScreenProps) {{/* Example payload preview */}<View style={styles.exampleSection}>- <SectionTitle>EXAMPLE PAYLOAD</SectionTitle>+ <SectionTitle>{localHttpMethod === "GET" ? "EXAMPLE REQUEST" : "EXAMPLE PAYLOAD"}</SectionTitle><Viewstyle={[styles.exampleCard,diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 0b3bcc5f..fac7fc29 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -62,7 +62,8 @@ class NativeLocationService {maxRetries: settings.maxRetries,filterInaccurateLocations: settings.filterInaccurateLocations,accuracyThreshold: settings.accuracyThreshold,- isOfflineMode: settings.isOfflineMode+ isOfflineMode: settings.isOfflineMode,+ httpMethod: settings.httpMethod}logger.debug(diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 36fa695b..e6cfdca0 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -92,6 +92,7 @@ describe("NativeLocationService", () => {customFields: [],apiTemplate: "custom" as const,syncPreset: "instant" as const,+ httpMethod: "POST" as const,hasCompletedSetup: false}@@ -100,7 +101,36 @@ describe("NativeLocationService", () => {expect(nativeMock.startService).toHaveBeenCalledWith(expect.objectContaining({interval: 5000,- minUpdateDistance: 10+ minUpdateDistance: 10,+ httpMethod: "POST"+ })+ )+ })++ it("passes httpMethod GET to native", async () => {+ const settings = {+ interval: 5,+ distance: 10,+ endpoint: "https://traccar.example.com:5055/",+ fieldMap: { lat: "lat", lon: "lon", acc: "accuracy" },+ syncInterval: 0,+ retryInterval: 30,+ maxRetries: 5,+ filterInaccurateLocations: false,+ accuracyThreshold: 50,+ isOfflineMode: false,+ customFields: [],+ apiTemplate: "traccar" as const,+ syncPreset: "instant" as const,+ httpMethod: "GET" as const,+ hasCompletedSetup: false+ }++ await NativeLocationService.start(settings)++ expect(nativeMock.startService).toHaveBeenCalledWith(+ expect.objectContaining({+ httpMethod: "GET"}))})diff --git a/apps/mobile/src/services/__tests__/SettingsService.test.ts b/apps/mobile/src/services/__tests__/SettingsService.test.tsindex 8a5c068a..e159ed2d 100644--- a/apps/mobile/src/services/__tests__/SettingsService.test.ts+++ b/apps/mobile/src/services/__tests__/SettingsService.test.ts@@ -64,6 +64,14 @@ describe("SettingsService", () => {expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://example.com/api")})+ it("saves httpMethod as string", async () => {+ await SettingsService.updateSetting("httpMethod", "GET")+ expect(mockSaveSetting).toHaveBeenCalledWith("httpMethod", "GET")++ await SettingsService.updateSetting("httpMethod", "POST")+ expect(mockSaveSetting).toHaveBeenCalledWith("httpMethod", "POST")+ })+it("does not throw on success", async () => {await SettingsService.updateSetting("endpoint", "https://test.com")expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://test.com")diff --git a/apps/mobile/src/types/__tests__/defaults.test.ts b/apps/mobile/src/types/__tests__/defaults.test.tsindex 3301d662..7c1c2200 100644--- a/apps/mobile/src/types/__tests__/defaults.test.ts+++ b/apps/mobile/src/types/__tests__/defaults.test.ts@@ -55,6 +55,10 @@ describe("DEFAULT_SETTINGS", () => {expect(DEFAULT_SETTINGS.isOfflineMode).toBe(false)})+ it("defaults to POST httpMethod", () => {+ expect(DEFAULT_SETTINGS.httpMethod).toBe("POST")+ })+it("has all required Settings keys", () => {const requiredKeys: (keyof Settings)[] = ["interval",@@ -69,7 +73,8 @@ describe("DEFAULT_SETTINGS", () => {"isOfflineMode","syncPreset","filterInaccurateLocations",- "accuracyThreshold"+ "accuracyThreshold",+ "httpMethod"]for (const key of requiredKeys) {@@ -118,7 +123,7 @@ describe("TRACKING_PRESETS", () => {})describe("API_TEMPLATES", () => {- const templateNames = ["dawarich", "owntracks", "phonetrack", "reitti"] as const+ const templateNames = ["dawarich", "owntracks", "phonetrack", "reitti", "traccar"] as constit.each(templateNames)("%s has valid fieldMap with required keys", (name) => {const template = API_TEMPLATES[name]@@ -158,4 +163,17 @@ describe("API_TEMPLATES", () => {expect(API_TEMPLATES.phonetrack.fieldMap.tst).toBe("timestamp")expect(API_TEMPLATES.phonetrack.fieldMap.bear).toBe("bearing")})++ it("traccar uses GET method", () => {+ expect(API_TEMPLATES.traccar.httpMethod).toBe("GET")+ })++ it("traccar maps fields for OsmAnd protocol", () => {+ expect(API_TEMPLATES.traccar.fieldMap.acc).toBe("accuracy")+ expect(API_TEMPLATES.traccar.fieldMap.alt).toBe("altitude")+ expect(API_TEMPLATES.traccar.fieldMap.vel).toBe("speed")+ expect(API_TEMPLATES.traccar.fieldMap.bs).toBe("charge")+ expect(API_TEMPLATES.traccar.fieldMap.tst).toBe("timestamp")+ expect(API_TEMPLATES.traccar.fieldMap.bear).toBe("bearing")+ })})diff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex eb3c52dd..cf675df9 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -93,7 +93,9 @@ export interface CustomField {value: string}-export type ApiTemplateName = "custom" | "dawarich" | "owntracks" | "phonetrack" | "reitti"+export type HttpMethod = "POST" | "GET"++export type ApiTemplateName = "custom" | "dawarich" | "owntracks" | "phonetrack" | "reitti" | "traccar"export interface ApiTemplate {name: ApiTemplateName@@ -101,6 +103,7 @@ export interface ApiTemplate {description: stringfieldMap: FieldMapcustomFields: CustomField[]+ httpMethod?: HttpMethod}export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTemplate> = {@@ -174,6 +177,24 @@ export const API_TEMPLATES: Record<Exclude<ApiTemplateName, "custom">, ApiTemplabear: "bear"},customFields: [{ key: "_type", value: "location" }]+ },+ traccar: {+ name: "traccar",+ label: "Traccar",+ description: "Traccar OsmAnd protocol (HTTP GET)",+ httpMethod: "GET",+ fieldMap: {+ lat: "lat",+ lon: "lon",+ acc: "accuracy",+ alt: "altitude",+ vel: "speed",+ batt: "batt",+ bs: "charge",+ tst: "timestamp",+ bear: "bearing"+ },+ customFields: [{ key: "id", value: "colota" }]}}@@ -242,6 +263,7 @@ export interface Settings {fieldMap: FieldMapcustomFields: CustomField[]apiTemplate: ApiTemplateName+ httpMethod: HttpMethod// Sync & UploadsyncInterval: number@@ -268,7 +290,8 @@ export const DEFAULT_SETTINGS: Settings = {syncPreset: "instant",maxRetries: 5,isOfflineMode: false,- hasCompletedSetup: false+ hasCompletedSetup: false,+ httpMethod: "POST"} as const// ============================================================================