Colota - Android GPS Location tracker
Add deep link setup via colota://setup URL scheme
Max Dietrich7d2348b023fc
diff --git a/README.md b/README.mdindex 622a6c56..913e654f 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- **Geofencing** — Pause zones that automatically pause tracking.- **Tracking Profiles** — Automatically adjust GPS interval, distance filter, and sync settings based on conditions like charging, car mode, or speed.- **Flexible Sync** — Instant, batch, Wi-Fi only, or offline modes.+- **Quick Setup** — Configure devices via `colota://setup` deep links or QR codes.- **Authentication** — Basic Auth, Bearer Token, or custom headers with AES-256-GCM encryption.## Screenshotsdiff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.mdnew file mode 100644index 00000000..954505bf--- /dev/null+++ b/apps/docs/docs/guides/deep-link-setup.md@@ -0,0 +1,134 @@+---+sidebar_position: 7+---++# Deep Link Setup++Configure Colota instantly using a `colota://setup` URL. Generate a link or QR code with your server settings and share it with users — no manual typing required.++## URL Format++```+colota://setup?config=BASE64_ENCODED_JSON+```++The `config` parameter is a base64-encoded JSON object. Only include the settings you want to change — everything else keeps its current value.++## Supported Parameters++```json+{+ "endpoint": "https://my-server.com/api/locations",+ "interval": 10,+ "distance": 5,+ "syncInterval": 300,+ "maxRetries": 5,+ "retryInterval": 30,+ "accuracyThreshold": 50,+ "filterInaccurateLocations": true,+ "isOfflineMode": false,+ "isWifiOnlySync": false,+ "apiTemplate": "owntracks",+ "httpMethod": "POST",+ "fieldMap": {+ "lat": "lat",+ "lon": "lon",+ "acc": "acc",+ "alt": "alt",+ "vel": "vel",+ "batt": "batt",+ "bs": "bs",+ "tst": "tst",+ "bear": "cog"+ },+ "customFields": [+ { "key": "_type", "value": "location" },+ { "key": "tid", "value": "AA" }+ ],+ "auth": {+ "type": "bearer",+ "bearerToken": "my-secret-token-123"+ },+ "customHeaders": {+ "X-Api-Key": "abc123",+ "CF-Access-Client-Id": "my-cf-id"+ }+}+```++### Parameter Reference++| Parameter | Type | Description |+| --------------------------- | ------- | ----------------------------------------------------------------------- |+| `endpoint` | string | Server URL to send location data to |+| `interval` | number | GPS polling interval in seconds (must be > 0) |+| `distance` | number | Minimum movement in meters before recording a new location |+| `syncInterval` | number | Batch sync interval in seconds (0 = instant) |+| `maxRetries` | number | Max retry attempts for failed uploads |+| `retryInterval` | number | Seconds between retry attempts |+| `accuracyThreshold` | number | Discard locations less accurate than this (meters) |+| `filterInaccurateLocations` | boolean | Enable accuracy filtering |+| `isOfflineMode` | boolean | Store locally only, never sync |+| `isWifiOnlySync` | boolean | Only sync on Wi-Fi |+| `apiTemplate` | string | `custom`, `dawarich`, `owntracks`, `phonetrack`, `reitti`, or `traccar` |+| `httpMethod` | string | `POST` or `GET` |+| `fieldMap` | object | Custom field name mapping for the JSON payload |+| `customFields` | array | Static key-value pairs added to every payload |+| `auth.type` | string | `none`, `basic`, or `bearer` |+| `auth.username` | string | Username for Basic Auth |+| `auth.password` | string | Password for Basic Auth |+| `auth.bearerToken` | string | Token for Bearer Auth |+| `customHeaders` | object | Custom HTTP headers (e.g. Cloudflare Access) |++## Generating a Setup Link++### Using Node.js++```bash+node -e "+const config = {+ endpoint: 'https://my-server.com/api/locations',+ interval: 10,+ apiTemplate: 'owntracks',+ auth: { type: 'bearer', bearerToken: 'my-token' }+};+const encoded = Buffer.from(JSON.stringify(config)).toString('base64');+console.log('colota://setup?config=' + encoded);+"+```++### Using Python++```bash+python3 -c "+import json, base64+config = {'endpoint': 'https://my-server.com/api/locations', 'interval': 10}+encoded = base64.b64encode(json.dumps(config).encode()).decode()+print(f'colota://setup?config={encoded}')+"+```++### QR Code++Generate a QR code from the `colota://setup?config=...` URL using any QR generator. When scanned, Android opens Colota and navigates directly to the confirmation screen.++## How It Works++1. User taps the link or scans a QR code+2. Colota opens and shows a confirmation screen listing all settings that will be applied+3. Sensitive values (passwords, tokens) are masked in the preview+4. User taps **Apply Configuration** to save or **Cancel** to discard+5. Settings are persisted and the app navigates to the Dashboard++## Testing with ADB++```bash+adb shell am start -a android.intent.action.VIEW \+ -d "colota://setup?config=BASE64_HERE" com.Colota+```++## Security Notes++- The configuration URL is not encrypted. Avoid putting sensitive tokens in QR codes displayed in public.+- All settings are shown to the user for confirmation before being applied.+- Auth credentials are stored in AES-256-GCM encrypted storage on device after import.diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 4d8111b7..7e2357c3 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -18,11 +18,12 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Sync Modes** — Instant, batch, or offline. Wi-Fi only sync, configurable intervals with automatic retry.- **Data Export** — Export location history in CSV, GeoJSON, GPX, or KML formats.- **Authentication** — Basic Auth, Bearer Token, or custom HTTP headers with AES-256-GCM encrypted storage.+- **Quick Setup** — Configure devices instantly via `colota://setup` deep links or QR codes. No manual typing required.- **Dark Mode** — Full light and dark theme support.## App Screens-Colota has eleven screens, each focused on a specific task:+Colota has twelve screens, each focused on a specific task:| Screen | Purpose || --- | --- |@@ -36,6 +37,7 @@ Colota has eleven screens, each focused on a specific task:| **Location History** | Browse recorded locations on a track map with day picker and daily distance traveled, or as a paginated list with accuracy indicators || **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML || **Data Management** | Clear sent history, delete old data, vacuum the database |+| **Setup Import** | Confirmation screen for deep link configuration imports (`colota://setup`) || **About** | App version, device info, links to repository and privacy policy |## Screenshotsdiff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 00db322d..4bde08b2 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -44,6 +44,7 @@ const sidebars: SidebarsConfig = {"guides/tracking-profiles","guides/data-export","guides/data-management",+ "guides/deep-link-setup","guides/battery-optimization","guides/troubleshooting"]diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 935f8802..a8925393 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -22,7 +22,8 @@ import {ExportDataScreen,AboutScreen,TrackingProfilesScreen,- ProfileEditorScreen+ ProfileEditorScreen,+ SetupImportScreen} from "./src/screens/"const Stack = createNativeStackNavigator()@@ -82,6 +83,11 @@ const SCREEN_CONFIG = [name: "About Colota",component: AboutScreen,title: "About Colota"+ },+ {+ name: "Setup Import",+ component: SetupImportScreen,+ title: "Import Configuration"}] as const@@ -117,10 +123,22 @@ function AppNavigator() {}),[colors.background, isDark])+ const linking = useMemo(+ () => ({+ prefixes: ["colota://"],+ config: {+ screens: {+ "Setup Import": "setup"+ }+ }+ }),+ []+ )+return (<SafeAreaProvider><StatusBar {...statusBarConfig} />- <NavigationContainer>+ <NavigationContainer linking={linking}><Stack.Navigator initialRouteName="Dashboard" screenOptions={screenOptions}>{SCREEN_CONFIG.map((screen) => (<Stack.Screendiff --git a/apps/mobile/android/app/fastlane/metadata/android/en-US/full_description.txt b/apps/mobile/android/app/fastlane/metadata/android/en-US/full_description.txtindex 2608de1e..538a255a 100644--- a/apps/mobile/android/app/fastlane/metadata/android/en-US/full_description.txt+++ b/apps/mobile/android/app/fastlane/metadata/android/en-US/full_description.txt@@ -10,6 +10,7 @@ Colota is an open-source GPS tracking application that sends your location to yo<li><b>Geofencing</b> — Define pause zones to automatically stop tracking in specific areas</li><li><b>Flexible Sync</b> — Instant send, periodic batch sync, or fully offline mode</li><li><b>Authentication</b> — Basic Auth, Bearer Token, or custom headers with AES-256-GCM encryption</li>+<li><b>Quick Setup</b> — Configure devices instantly via colota:// deep links or QR codes</li><li><b>Configurable</b> — Custom field mapping, update intervals, distance filters, and accuracy thresholds</li></ul>diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xmlindex 42ba255a..3378d090 100644--- a/apps/mobile/android/app/src/main/AndroidManifest.xml+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml@@ -54,6 +54,12 @@<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>+ <intent-filter android:autoVerify="false">+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="colota" />+ </intent-filter></activity><!-- Foreground location service -->diff --git a/apps/mobile/src/screens/SetupImportScreen.tsx b/apps/mobile/src/screens/SetupImportScreen.tsxnew file mode 100644index 00000000..82263f83--- /dev/null+++ b/apps/mobile/src/screens/SetupImportScreen.tsx@@ -0,0 +1,460 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useState, useMemo } from "react"+import { View, Text, ScrollView, StyleSheet } from "react-native"+import { useTheme } from "../hooks/useTheme"+import { useTracking } from "../contexts/TrackingProvider"+import { Container, Card, Button, SectionTitle } from "../components"+import { fonts } from "../styles/typography"+import { CircleAlert, CircleCheck, Import } from "lucide-react-native"+import SettingsService from "../services/SettingsService"+import NativeLocationService from "../services/NativeLocationService"+import { showAlert } from "../services/modalService"+import { logger } from "../utils/logger"+import {+ TRACKING_PRESETS,+ type Settings,+ type AuthConfig,+ type AuthType,+ type FieldMap,+ type CustomField,+ type ApiTemplateName,+ type HttpMethod,+ type SelectablePreset,+ type SyncPreset+} from "../types/global"++// ============================================================================+// TYPES+// ============================================================================++interface ParsedConfig {+ settings: Partial<Settings>+ auth: Partial<AuthConfig> | null+}++interface ConfigEntry {+ label: string+ value: string+ category: "tracking" | "api" | "auth"+}++interface ValidationResult {+ valid: boolean+ config: ParsedConfig+ entries: ConfigEntry[]+ error?: string+}++// ============================================================================+// VALIDATION+// ============================================================================++const VALID_API_TEMPLATES: ApiTemplateName[] = ["custom", "dawarich", "owntracks", "phonetrack", "reitti", "traccar"]+const VALID_HTTP_METHODS: HttpMethod[] = ["POST", "GET"]+const VALID_AUTH_TYPES: AuthType[] = ["none", "basic", "bearer"]++function detectPreset(settings: Partial<Settings>): SyncPreset {+ for (const [name, config] of Object.entries(TRACKING_PRESETS)) {+ if (+ settings.interval === config.interval &&+ settings.distance === config.distance &&+ settings.syncInterval === config.syncInterval &&+ settings.retryInterval === config.retryInterval+ ) {+ return name as SelectablePreset+ }+ }+ return "custom"+}++function validateConfig(raw: unknown): ValidationResult {+ if (!raw || typeof raw !== "object") {+ return { valid: false, config: { settings: {}, auth: null }, entries: [], error: "Invalid configuration format" }+ }++ const obj = raw as Record<string, unknown>+ const settings: Partial<Settings> = {}+ const entries: ConfigEntry[] = []+ let auth: Partial<AuthConfig> | null = null++ // --- API settings (endpoint) ---++ if ("endpoint" in obj && typeof obj.endpoint === "string" && obj.endpoint.length > 0) {+ settings.endpoint = obj.endpoint+ entries.push({ label: "Endpoint", value: obj.endpoint, category: "api" })+ }++ // --- Tracking settings ---++ if ("interval" in obj && typeof obj.interval === "number" && obj.interval > 0) {+ settings.interval = obj.interval+ entries.push({ label: "Interval", value: `${obj.interval}s`, category: "tracking" })+ }++ if ("distance" in obj && typeof obj.distance === "number" && obj.distance >= 0) {+ settings.distance = obj.distance+ entries.push({ label: "Distance threshold", value: `${obj.distance}m`, category: "tracking" })+ }++ if ("syncInterval" in obj && typeof obj.syncInterval === "number" && obj.syncInterval >= 0) {+ settings.syncInterval = obj.syncInterval+ entries.push({+ label: "Sync interval",+ value: obj.syncInterval === 0 ? "Instant" : `${obj.syncInterval}s`,+ category: "tracking"+ })+ }++ if ("maxRetries" in obj && typeof obj.maxRetries === "number" && obj.maxRetries >= 0) {+ settings.maxRetries = obj.maxRetries+ entries.push({ label: "Max retries", value: `${obj.maxRetries}`, category: "tracking" })+ }++ if ("retryInterval" in obj && typeof obj.retryInterval === "number" && obj.retryInterval >= 0) {+ settings.retryInterval = obj.retryInterval+ entries.push({ label: "Retry interval", value: `${obj.retryInterval}s`, category: "tracking" })+ }++ if ("accuracyThreshold" in obj && typeof obj.accuracyThreshold === "number" && obj.accuracyThreshold > 0) {+ settings.accuracyThreshold = obj.accuracyThreshold+ entries.push({ label: "Accuracy threshold", value: `${obj.accuracyThreshold}m`, category: "tracking" })+ }++ if ("filterInaccurateLocations" in obj && typeof obj.filterInaccurateLocations === "boolean") {+ settings.filterInaccurateLocations = obj.filterInaccurateLocations+ entries.push({+ label: "Filter inaccurate",+ value: obj.filterInaccurateLocations ? "Yes" : "No",+ category: "tracking"+ })+ }++ if ("isOfflineMode" in obj && typeof obj.isOfflineMode === "boolean") {+ settings.isOfflineMode = obj.isOfflineMode+ entries.push({ label: "Offline mode", value: obj.isOfflineMode ? "Yes" : "No", category: "tracking" })+ }++ if ("isWifiOnlySync" in obj && typeof obj.isWifiOnlySync === "boolean") {+ settings.isWifiOnlySync = obj.isWifiOnlySync+ entries.push({ label: "Wi-Fi only sync", value: obj.isWifiOnlySync ? "Yes" : "No", category: "tracking" })+ }++ // --- API settings ---++ if (+ "apiTemplate" in obj &&+ typeof obj.apiTemplate === "string" &&+ VALID_API_TEMPLATES.includes(obj.apiTemplate as ApiTemplateName)+ ) {+ settings.apiTemplate = obj.apiTemplate as ApiTemplateName+ entries.push({ label: "API template", value: obj.apiTemplate, category: "api" })+ }++ if (+ "httpMethod" in obj &&+ typeof obj.httpMethod === "string" &&+ VALID_HTTP_METHODS.includes(obj.httpMethod as HttpMethod)+ ) {+ settings.httpMethod = obj.httpMethod as HttpMethod+ entries.push({ label: "HTTP method", value: obj.httpMethod, category: "api" })+ }++ if ("fieldMap" in obj && typeof obj.fieldMap === "object" && obj.fieldMap !== null) {+ const fm = obj.fieldMap as Record<string, unknown>+ const validFieldMap: Partial<FieldMap> = {}+ let hasValid = false+ for (const [key, val] of Object.entries(fm)) {+ if (typeof val === "string") {+ ;(validFieldMap as any)[key] = val+ hasValid = true+ }+ }+ if (hasValid) {+ settings.fieldMap = validFieldMap as FieldMap+ entries.push({ label: "Field mapping", value: `${Object.keys(validFieldMap).length} fields`, category: "api" })+ }+ }++ if ("customFields" in obj && Array.isArray(obj.customFields)) {+ const validFields: CustomField[] = obj.customFields.filter(+ (f: any) => f && typeof f.key === "string" && typeof f.value === "string" && f.key.length > 0+ )+ if (validFields.length > 0) {+ settings.customFields = validFields+ entries.push({ label: "Custom fields", value: `${validFields.length} fields`, category: "api" })+ }+ }++ // --- Auth settings ---++ if ("auth" in obj && typeof obj.auth === "object" && obj.auth !== null) {+ const authObj = obj.auth as Record<string, unknown>+ auth = {}++ if ("type" in authObj && typeof authObj.type === "string" && VALID_AUTH_TYPES.includes(authObj.type as AuthType)) {+ auth.authType = authObj.type as AuthType+ entries.push({ label: "Auth type", value: authObj.type, category: "auth" })+ }++ if ("username" in authObj && typeof authObj.username === "string" && authObj.username.length > 0) {+ auth.username = authObj.username+ entries.push({ label: "Username", value: authObj.username, category: "auth" })+ }++ if ("password" in authObj && typeof authObj.password === "string" && authObj.password.length > 0) {+ auth.password = authObj.password+ entries.push({ label: "Password", value: "\u2022".repeat(8), category: "auth" })+ }++ if ("bearerToken" in authObj && typeof authObj.bearerToken === "string" && authObj.bearerToken.length > 0) {+ auth.bearerToken = authObj.bearerToken+ const masked =+ authObj.bearerToken.length > 8+ ? authObj.bearerToken.slice(0, 4) + "\u2022".repeat(4) + authObj.bearerToken.slice(-4)+ : "\u2022".repeat(authObj.bearerToken.length)+ entries.push({ label: "Bearer token", value: masked, category: "auth" })+ }++ if (Object.keys(auth).length === 0) auth = null+ }++ if ("customHeaders" in obj && typeof obj.customHeaders === "object" && obj.customHeaders !== null) {+ const headers = obj.customHeaders as Record<string, unknown>+ const validHeaders: Record<string, string> = {}+ for (const [key, val] of Object.entries(headers)) {+ if (typeof val === "string") {+ validHeaders[key] = val+ }+ }+ if (Object.keys(validHeaders).length > 0) {+ if (!auth) auth = {}+ auth.customHeaders = validHeaders+ entries.push({ label: "Custom headers", value: `${Object.keys(validHeaders).length} headers`, category: "auth" })+ }+ }++ if (entries.length === 0) {+ return { valid: false, config: { settings, auth }, entries, error: "No valid settings found in configuration" }+ }++ return { valid: true, config: { settings, auth }, entries }+}++// ============================================================================+// SCREEN+// ============================================================================++export function SetupImportScreen({ route, navigation }: any) {+ const { colors } = useTheme()+ const { settings: currentSettings, setSettings } = useTracking()+ const [applying, setApplying] = useState(false)++ const result = useMemo(() => {+ try {+ const configParam = route.params?.config+ if (!configParam || typeof configParam !== "string") {+ return {+ valid: false,+ config: { settings: {}, auth: null },+ entries: [],+ error: "No configuration data in URL"+ } as ValidationResult+ }++ const decoded = atob(configParam)+ const parsed = JSON.parse(decoded)+ return validateConfig(parsed)+ } catch (e) {+ logger.error("[SetupImport] Failed to parse config:", e)+ return {+ valid: false,+ config: { settings: {}, auth: null },+ entries: [],+ error: "Invalid configuration data. The URL may be malformed."+ } as ValidationResult+ }+ }, [route.params?.config])++ const trackingEntries = result.entries.filter((e) => e.category === "tracking")+ const apiEntries = result.entries.filter((e) => e.category === "api")+ const authEntries = result.entries.filter((e) => e.category === "auth")++ const handleApply = async () => {+ setApplying(true)+ try {+ // Deep merge nested objects (fieldMap, customFields) instead of replacing them+ const incoming = result.config.settings+ const merged: Settings = { ...currentSettings, ...incoming, hasCompletedSetup: true }+ if (incoming.fieldMap) {+ merged.fieldMap = { ...currentSettings.fieldMap, ...incoming.fieldMap }+ }+ merged.syncPreset = detectPreset(merged)++ await SettingsService.updateMultiple(merged)+ await setSettings(merged)++ // Apply auth — deep merge customHeaders+ if (result.config.auth) {+ const currentAuth = await NativeLocationService.getAuthConfig()+ const mergedAuth = { ...currentAuth, ...result.config.auth }+ if (result.config.auth.customHeaders) {+ mergedAuth.customHeaders = { ...currentAuth.customHeaders, ...result.config.auth.customHeaders }+ }+ await NativeLocationService.saveAuthConfig(mergedAuth)+ }++ showAlert("Configuration Applied", "Settings have been updated successfully.", "success")+ navigation.navigate("Dashboard")+ } catch (e) {+ logger.error("[SetupImport] Failed to apply config:", e)+ showAlert("Error", "Failed to apply configuration. Please try again.", "error")+ } finally {+ setApplying(false)+ }+ }++ const renderSection = (title: string, entries: ConfigEntry[]) => {+ if (entries.length === 0) return null+ return (+ <View style={styles.section}>+ <SectionTitle>{title}</SectionTitle>+ <Card>+ {entries.map((entry, i) => (+ <View+ key={entry.label}+ style={[+ styles.settingRow,+ i < entries.length - 1 && styles.settingRowBorder,+ i < entries.length - 1 && { borderBottomColor: colors.border }+ ]}+ >+ <Text style={[styles.settingLabel, { color: colors.textSecondary }]}>{entry.label}</Text>+ <Text style={[styles.settingValue, { color: colors.text }]} numberOfLines={1}>+ {entry.value}+ </Text>+ </View>+ ))}+ </Card>+ </View>+ )+ }++ const handleCancel = () => {+ navigation.navigate("Dashboard")+ }++ // --- Error state ---+ if (!result.valid) {+ return (+ <Container>+ <ScrollView contentContainerStyle={styles.content}>+ <Card style={styles.headerCard}>+ <View style={styles.headerRow}>+ <CircleAlert size={28} color={colors.error} />+ <View style={styles.headerText}>+ <Text style={[styles.title, { color: colors.text }]}>Invalid Configuration</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>{result.error}</Text>+ </View>+ </View>+ </Card>+ <Button title="Go Back" onPress={handleCancel} variant="primary" />+ </ScrollView>+ </Container>+ )+ }++ // --- Confirmation state ---+ return (+ <Container>+ <ScrollView contentContainerStyle={styles.content}>+ <Card style={styles.headerCard}>+ <View style={styles.headerRow}>+ <Import size={28} color={colors.primary} />+ <View style={styles.headerText}>+ <Text style={[styles.title, { color: colors.text }]}>Import Configuration</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>+ A setup link wants to apply {result.entries.length} setting{result.entries.length !== 1 ? "s" : ""}+ </Text>+ </View>+ </View>+ </Card>++ {renderSection("TRACKING", trackingEntries)}+ {renderSection("API", apiEntries)}+ {renderSection("AUTHENTICATION", authEntries)}++ <View style={styles.actions}>+ <Button+ title="Apply Configuration"+ onPress={handleApply}+ variant="primary"+ icon={CircleCheck}+ loading={applying}+ disabled={applying}+ />+ <Button title="Cancel" onPress={handleCancel} variant="ghost" />+ </View>+ </ScrollView>+ </Container>+ )+}++// ============================================================================+// STYLES+// ============================================================================++const styles = StyleSheet.create({+ content: {+ padding: 16,+ paddingBottom: 40+ },+ headerCard: {+ marginBottom: 16+ },+ headerRow: {+ flexDirection: "row",+ alignItems: "center",+ gap: 12+ },+ headerText: {+ flex: 1+ },+ title: {+ fontSize: 18,+ ...fonts.bold+ },+ subtitle: {+ fontSize: 13,+ ...fonts.regular,+ marginTop: 2+ },+ section: {+ marginTop: 8+ },+ settingRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ paddingVertical: 10+ },+ settingRowBorder: {+ borderBottomWidth: StyleSheet.hairlineWidth+ },+ settingLabel: {+ fontSize: 13,+ ...fonts.semiBold+ },+ settingValue: {+ fontSize: 13,+ ...fonts.regular,+ maxWidth: "60%",+ textAlign: "right"+ },+ actions: {+ marginTop: 24+ }+})diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsxnew file mode 100644index 00000000..0a8f5dea--- /dev/null+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx@@ -0,0 +1,286 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"+import { DEFAULT_AUTH_CONFIG, TRACKING_PRESETS } from "../../types/global"++// --- Mocks ---++const mockSetSettings = jest.fn().mockResolvedValue(undefined)+const mockSaveSetting = jest.fn().mockResolvedValue(undefined)+const mockGetAuthConfig = jest.fn().mockResolvedValue({ ...DEFAULT_AUTH_CONFIG })+const mockSaveAuthConfig = jest.fn().mockResolvedValue(true)+const mockNavigate = jest.fn()+const mockShowAlert = jest.fn()++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getAuthConfig: (...args: any[]) => mockGetAuthConfig(...args),+ saveAuthConfig: (...args: any[]) => mockSaveAuthConfig(...args),+ saveSetting: (...args: any[]) => mockSaveSetting(...args)+ }+}))++jest.mock("../../services/SettingsService", () => ({+ __esModule: true,+ default: {+ updateMultiple: jest.fn().mockResolvedValue(undefined)+ }+}))++jest.mock("../../services/modalService", () => ({+ showAlert: (...args: any[]) => mockShowAlert(...args)+}))++jest.mock("../../contexts/TrackingProvider", () => ({+ useTracking: () => ({+ settings: { ...require("../../types/global").DEFAULT_SETTINGS },+ setSettings: mockSetSettings+ })+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ primary: "#0d9488",+ primaryDark: "#115E59",+ border: "#e5e7eb",+ text: "#000",+ textSecondary: "#6b7280",+ textLight: "#9ca3af",+ background: "#fff",+ info: "#3b82f6",+ success: "#22c55e",+ error: "#ef4444",+ card: "#fff",+ textOnPrimary: "#fff",+ textDisabled: "#d1d5db",+ borderRadius: 12+ }+ })+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, TouchableOpacity } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Button: ({ title, onPress, disabled }: any) =>+ R.createElement(+ TouchableOpacity,+ { onPress, disabled, accessibilityRole: "button" },+ R.createElement(Text, null, title)+ )+ }+})++jest.mock("../../utils/logger", () => ({+ logger: { debug: jest.fn(), error: jest.fn(), warn: jest.fn(), info: jest.fn() }+}))++import { SetupImportScreen } from "../SetupImportScreen"++// --- Helpers ---++function encode(obj: object): string {+ return btoa(JSON.stringify(obj))+}++function renderScreen(configParam?: string) {+ return render(+ <SetupImportScreen+ route={{ params: configParam !== undefined ? { config: configParam } : {} }}+ navigation={{ navigate: mockNavigate }}+ />+ )+}++// --- Tests ---++beforeEach(() => {+ jest.clearAllMocks()+})++describe("SetupImportScreen", () => {+ describe("parsing and validation", () => {+ it("shows error when no config param is provided", () => {+ const { getByText } = renderScreen()+ expect(getByText("Invalid Configuration")).toBeTruthy()+ expect(getByText("No configuration data in URL")).toBeTruthy()+ })++ it("shows error for invalid base64", () => {+ const { getByText } = renderScreen("!!!not-base64!!!")+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("shows error for valid base64 but invalid JSON", () => {+ const { getByText } = renderScreen(btoa("not json"))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("shows error when config has no valid settings", () => {+ const { getByText } = renderScreen(encode({ unknownKey: "value" }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ expect(getByText("No valid settings found in configuration")).toBeTruthy()+ })++ it("parses valid endpoint config", () => {+ const { getByText } = renderScreen(encode({ endpoint: "https://my-server.com/api" }))+ expect(getByText("Import Configuration")).toBeTruthy()+ expect(getByText("Endpoint")).toBeTruthy()+ expect(getByText("https://my-server.com/api")).toBeTruthy()+ })++ it("parses tracking settings", () => {+ const { getByText } = renderScreen(encode({ interval: 10, distance: 5, syncInterval: 0 }))+ expect(getByText("10s")).toBeTruthy()+ expect(getByText("5m")).toBeTruthy()+ expect(getByText("Instant")).toBeTruthy()+ })++ it("parses API settings", () => {+ const { getByText } = renderScreen(encode({ apiTemplate: "owntracks", httpMethod: "POST" }))+ expect(getByText("owntracks")).toBeTruthy()+ expect(getByText("POST")).toBeTruthy()+ })++ it("parses auth settings with masked token", () => {+ const { getByText } = renderScreen(encode({ auth: { type: "bearer", bearerToken: "abcdefghijkl" } }))+ expect(getByText("bearer")).toBeTruthy()+ // Token should be masked: first 4 + dots + last 4+ expect(getByText(/abcd.*ijkl/)).toBeTruthy()+ })++ it("parses custom headers", () => {+ const { getByText } = renderScreen(encode({ customHeaders: { "X-Api-Key": "secret" } }))+ expect(getByText("1 headers")).toBeTruthy()+ })++ it("rejects invalid interval (negative)", () => {+ const { getByText } = renderScreen(encode({ interval: -5 }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("rejects invalid auth type", () => {+ const { getByText } = renderScreen(encode({ auth: { type: "oauth" } }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("rejects invalid API template", () => {+ const { getByText } = renderScreen(encode({ apiTemplate: "invalid" }))+ expect(getByText("Invalid Configuration")).toBeTruthy()+ })++ it("counts settings correctly in subtitle", () => {+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com", interval: 10 }))+ expect(getByText(/2 settings/)).toBeTruthy()+ })++ it("shows singular 'setting' for single entry", () => {+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))+ // Text is split across nodes: "A setup link wants to apply " + "1" + " setting"+ expect(getByText(/1/)).toBeTruthy()+ expect(getByText(/setting$/)).toBeTruthy()+ })+ })++ describe("apply configuration", () => {+ it("applies settings and navigates to Dashboard", async () => {+ const config = { endpoint: "https://test.com", interval: 15 }+ const { getByText } = renderScreen(encode(config))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith(+ "Configuration Applied",+ "Settings have been updated successfully.",+ "success"+ )+ })++ expect(mockNavigate).toHaveBeenCalledWith("Dashboard")+ expect(mockSetSettings).toHaveBeenCalledWith(+ expect.objectContaining({ endpoint: "https://test.com", interval: 15, hasCompletedSetup: true })+ )+ })++ it("applies auth config when provided", async () => {+ const config = { endpoint: "https://test.com", auth: { type: "bearer", bearerToken: "mytoken" } }+ const { getByText } = renderScreen(encode(config))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockSaveAuthConfig).toHaveBeenCalledWith(+ expect.objectContaining({ authType: "bearer", bearerToken: "mytoken" })+ )+ })+ })++ it("marks hasCompletedSetup as true", async () => {+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ hasCompletedSetup: true }))+ })+ })++ it("sets syncPreset to 'custom' when values don't match a preset", async () => {+ const config = { interval: 15, distance: 3, syncInterval: 120 }+ const { getByText } = renderScreen(encode(config))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "custom" }))+ })+ })++ it("sets syncPreset to matching preset when values match", async () => {+ const balanced = TRACKING_PRESETS.balanced+ const config = {+ interval: balanced.interval,+ distance: balanced.distance,+ syncInterval: balanced.syncInterval,+ retryInterval: balanced.retryInterval+ }+ const { getByText } = renderScreen(encode(config))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ syncPreset: "balanced" }))+ })+ })++ it("shows error alert on failure", async () => {+ mockSetSettings.mockRejectedValueOnce(new Error("fail"))+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))++ fireEvent.press(getByText("Apply Configuration"))++ await waitFor(() => {+ expect(mockShowAlert).toHaveBeenCalledWith("Error", "Failed to apply configuration. Please try again.", "error")+ })+ })+ })++ describe("cancel", () => {+ it("navigates to Dashboard on cancel", () => {+ const { getByText } = renderScreen(encode({ endpoint: "https://test.com" }))+ fireEvent.press(getByText("Cancel"))+ expect(mockNavigate).toHaveBeenCalledWith("Dashboard")+ })++ it("navigates to Dashboard on Go Back (error state)", () => {+ const { getByText } = renderScreen()+ fireEvent.press(getByText("Go Back"))+ expect(mockNavigate).toHaveBeenCalledWith("Dashboard")+ })+ })+})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex bc591a12..c5943f26 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -14,3 +14,4 @@ export { SettingsScreen } from "./SettingsScreen"export { TrackingProfilesScreen } from "./TrackingProfilesScreen"export { ProfileEditorScreen } from "./ProfileEditorScreen"export { AboutScreen } from "./AboutScreen"+export { SetupImportScreen } from "./SetupImportScreen"