Skip to content

Colota - Android GPS Location tracker

test: add unit test suite with 125 tests across 7 suites

Max Dietrich541382a0797b
diff --git a/jest.config.js b/jest.config.js
index 3abb3a4c..8b7634eb 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -1,3 +1,4 @@
module.exports = {
- preset: "react-native"
+ preset: "react-native",
+ setupFiles: ["./jest.setup.js"]
}
diff --git a/jest.setup.js b/jest.setup.js
new file mode 100644
index 00000000..980dcbd1
--- /dev/null
+++ b/jest.setup.js
@@ -0,0 +1,17 @@
+/* eslint-env node */
+/**
+ * Jest setup file
+ * Provides mocks for React Native native modules and browser APIs
+ */
+
+// Blob polyfill for getByteSize tests (RN test env doesn't have Blob)
+if (typeof global.Blob === "undefined") {
+ global.Blob = class Blob {
+ constructor(parts) {
+ this._content = parts.map((p) => String(p)).join("")
+ }
+ get size() {
+ return Buffer.byteLength(this._content, "utf8")
+ }
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index ef328e28..b6b15762 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,18 +1,17 @@
{
"name": "Colota",
- "version": "1.3.1",
+ "version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "Colota",
- "version": "1.3.1",
+ "version": "1.0.0",
"dependencies": {
"@react-navigation/native": "^7.1.26",
"@react-navigation/native-stack": "^7.9.0",
"react": "19.2.0",
"react-native": "0.83.1",
- "react-native-permissions": "^5.4.4",
"react-native-safe-area-context": "^5.6.2",
"react-native-screens": "^4.19.0",
"react-native-webview": "^13.16.0"
@@ -21,7 +20,6 @@
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.3",
"@babel/runtime": "^7.25.0",
- "@react-icons/all-files": "https://github.com/react-icons/react-icons/releases/download/v5.5.0/react-icons-all-files-5.5.0.tgz",
"@react-native-community/cli": "20.0.0",
"@react-native-community/cli-platform-android": "20.0.0",
"@react-native-community/cli-platform-ios": "20.0.0",
@@ -29,6 +27,7 @@
"@react-native/eslint-config": "0.83.1",
"@react-native/metro-config": "0.83.1",
"@react-native/typescript-config": "0.83.1",
+ "@testing-library/react-native": "^13.3.3",
"@types/jest": "^29.5.13",
"@types/react": "^19.2.0",
"@types/react-test-renderer": "^19.1.0",
@@ -2374,6 +2373,16 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
+ "node_modules/@jest/diff-sequences": {
+ "version": "30.0.1",
+ "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.0.1.tgz",
+ "integrity": "sha512-n5H8QLDJ47QqbCNn5SuFjCRDrOLEZ0h8vAHCK5RL9Ls7Xa8AQLa/YxAc9UjFqoEDM48muwtBGjtMY5cr0PLDCw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
"node_modules/@jest/environment": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz",
@@ -2433,6 +2442,16 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
+ "node_modules/@jest/get-type": {
+ "version": "30.1.0",
+ "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz",
+ "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
"node_modules/@jest/globals": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz",
@@ -2698,23 +2717,12 @@
"node": ">= 8"
}
},
- "node_modules/@react-icons/all-files": {
- "version": "5.5.0",
- "resolved": "https://github.com/react-icons/react-icons/releases/download/v5.5.0/react-icons-all-files-5.5.0.tgz",
- "integrity": "sha512-SFs2VrQaybncj7qsOjGch23QQc3nJvWtiZXzXGDqPZk2Vw06tw0aRbLuppg74MMYgmLnzkbIgZZYPkoFYP/DZw==",
- "dev": true,
- "license": "MIT",
- "peerDependencies": {
- "react": "*"
- }
- },
"node_modules/@react-native-community/cli": {
"version": "20.0.0",
"resolved": "https://registry.npmjs.org/@react-native-community/cli/-/cli-20.0.0.tgz",
"integrity": "sha512-/cMnGl5V1rqnbElY1Fvga1vfw0d3bnqiJLx2+2oh7l9ulnXfVRWb5tU2kgBqiMxuDOKA+DQoifC9q/tvkj5K2w==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@react-native-community/cli-clean": "20.0.0",
"@react-native-community/cli-config": "20.0.0",
@@ -3452,6 +3460,113 @@
"@sinonjs/commons": "^3.0.0"
}
},
+ "node_modules/@testing-library/react-native": {
+ "version": "13.3.3",
+ "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-13.3.3.tgz",
+ "integrity": "sha512-k6Mjsd9dbZgvY4Bl7P1NIpePQNi+dfYtlJ5voi9KQlynxSyQkfOgJmYGCYmw/aSgH/rUcFvG8u5gd4npzgRDyg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "jest-matcher-utils": "^30.0.5",
+ "picocolors": "^1.1.1",
+ "pretty-format": "^30.0.5",
+ "redent": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "jest": ">=29.0.0",
+ "react": ">=18.2.0",
+ "react-native": ">=0.71",
+ "react-test-renderer": ">=18.2.0"
+ },
+ "peerDependenciesMeta": {
+ "jest": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@testing-library/react-native/node_modules/@jest/schemas": {
+ "version": "30.0.5",
+ "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.0.5.tgz",
+ "integrity": "sha512-DmdYgtezMkh3cpU8/1uyXakv3tJRcmcXxBOcO0tbaozPwpmh4YMsnWrQm9ZmZMfa5ocbxzbFk6O4bDPEc/iAnA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@sinclair/typebox": "^0.34.0"
+ },
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@testing-library/react-native/node_modules/@sinclair/typebox": {
+ "version": "0.34.48",
+ "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.48.tgz",
+ "integrity": "sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@testing-library/react-native/node_modules/ansi-styles": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/@testing-library/react-native/node_modules/jest-diff": {
+ "version": "30.2.0",
+ "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.2.0.tgz",
+ "integrity": "sha512-dQHFo3Pt4/NLlG5z4PxZ/3yZTZ1C7s9hveiOj+GCN+uT109NC2QgsoVZsVOAvbJ3RgKkvyLGXZV9+piDpWbm6A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jest/diff-sequences": "30.0.1",
+ "@jest/get-type": "30.1.0",
+ "chalk": "^4.1.2",
+ "pretty-format": "30.2.0"
+ },
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@testing-library/react-native/node_modules/jest-matcher-utils": {
+ "version": "30.2.0",
+ "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.2.0.tgz",
+ "integrity": "sha512-dQ94Nq4dbzmUWkQ0ANAWS9tBRfqCrn0bV9AMYdOi/MHW726xn7eQmMeRTpX2ViC00bpNaWXq+7o4lIQ3AX13Hg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jest/get-type": "30.1.0",
+ "chalk": "^4.1.2",
+ "jest-diff": "30.2.0",
+ "pretty-format": "30.2.0"
+ },
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@testing-library/react-native/node_modules/pretty-format": {
+ "version": "30.2.0",
+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.2.0.tgz",
+ "integrity": "sha512-9uBdv/B4EefsuAL+pWqueZyZS2Ba+LxfFeQ9DN14HU4bN8bhaxKdkpjpB6fs9+pSjIBu+FXQHImEg8j/Lw0+vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jest/schemas": "30.0.5",
+ "ansi-styles": "^5.2.0",
+ "react-is": "^18.3.1"
+ },
+ "engines": {
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
+ }
+ },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -3552,7 +3667,6 @@
"integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -7053,6 +7167,16 @@
"node": ">=0.8.19"
}
},
+ "node_modules/indent-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
+ "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -9185,6 +9309,16 @@
"node": ">=6"
}
},
+ "node_modules/min-indent": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
+ "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/minimatch": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz",
@@ -10109,22 +10243,6 @@
}
}
},
- "node_modules/react-native-permissions": {
- "version": "5.4.4",
- "resolved": "https://registry.npmjs.org/react-native-permissions/-/react-native-permissions-5.4.4.tgz",
- "integrity": "sha512-WB5lRCBGXETfuaUhem2vgOceb9+URCeyfKpLGFSwoOffLuyJCA6+NTR3l1KLkrK4Ykxsig37z16/shUVufmt7A==",
- "license": "MIT",
- "peerDependencies": {
- "react": ">=18.1.0",
- "react-native": ">=0.70.0",
- "react-native-windows": ">=0.70.0"
- },
- "peerDependenciesMeta": {
- "react-native-windows": {
- "optional": true
- }
- }
- },
"node_modules/react-native-safe-area-context": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-5.6.2.tgz",
@@ -10252,6 +10370,20 @@
"node": ">= 6"
}
},
+ "node_modules/redent": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
+ "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "indent-string": "^4.0.0",
+ "strip-indent": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/reflect.getprototypeof": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
@@ -11266,6 +11398,19 @@
"node": ">=6"
}
},
+ "node_modules/strip-indent": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
+ "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "min-indent": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/strip-json-comments": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
@@ -11620,7 +11765,7 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
+ "devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
diff --git a/package.json b/package.json
index ca4dd6f4..d73d7631 100644
--- a/package.json
+++ b/package.json
@@ -40,6 +40,7 @@
"@react-native/eslint-config": "0.83.1",
"@react-native/metro-config": "0.83.1",
"@react-native/typescript-config": "0.83.1",
+ "@testing-library/react-native": "^13.3.3",
"@types/jest": "^29.5.13",
"@types/react": "^19.2.0",
"@types/react-test-renderer": "^19.1.0",
diff --git a/src/components/features/databases/DatabaseStatistics.tsx b/src/components/features/databases/DatabaseStatistics.tsx
index 905ffa3e..22193975 100644
--- a/src/components/features/databases/DatabaseStatistics.tsx
+++ b/src/components/features/databases/DatabaseStatistics.tsx
@@ -6,7 +6,7 @@ import React from "react"
import { Text, StyleSheet, View } from "react-native"
import { SectionTitle, Card } from "../.."
import { useTheme } from "../../../hooks/useTheme"
-import { getQueueColor } from "../../../services/queueStatus"
+import { getQueueColor } from "../../../utils/queueStatus"
type DatabaseStatisticsProps = {
stats: any
diff --git a/src/components/features/settings/StatsCard.tsx b/src/components/features/settings/StatsCard.tsx
index 99ec0b4d..a7bb5f13 100644
--- a/src/components/features/settings/StatsCard.tsx
+++ b/src/components/features/settings/StatsCard.tsx
@@ -5,7 +5,7 @@
import React from "react"
import { View, Text, StyleSheet, TouchableOpacity } from "react-native"
import { ThemeColors } from "../../../types/global"
-import { getQueueColor } from "../../../services/queueStatus"
+import { getQueueColor } from "../../../utils/queueStatus"
interface StatsCardProps {
queueCount: number
diff --git a/src/contexts/__tests__/TrackingProvider.test.tsx b/src/contexts/__tests__/TrackingProvider.test.tsx
new file mode 100644
index 00000000..349578ea
--- /dev/null
+++ b/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -0,0 +1,112 @@
+import React from "react"
+import { renderHook, act } from "@testing-library/react-native"
+import { DEFAULT_SETTINGS } from "../../types/global"
+
+// Mock the services
+jest.mock("../../services/NativeLocationService", () => ({
+ getAllSettings: jest.fn().mockResolvedValue({}),
+ start: jest.fn().mockResolvedValue(undefined),
+ stop: jest.fn(),
+ saveSetting: jest.fn().mockResolvedValue(undefined),
+ isServiceRunning: jest.fn().mockResolvedValue(false),
+ isTrackingActive: jest.fn().mockResolvedValue(false)
+}))
+
+jest.mock("../../services/SettingsService", () => ({
+ updateMultiple: jest.fn().mockResolvedValue(undefined),
+ updateSetting: jest.fn().mockResolvedValue(true)
+}))
+
+// Mock useLocationTracking hook — use require() inside factory to avoid out-of-scope reference
+jest.mock("../../hooks/useLocationTracking", () => ({
+ useLocationTracking: jest.fn(() => ({
+ coords: null,
+ tracking: false,
+ startTracking: jest.fn().mockResolvedValue(undefined),
+ stopTracking: jest.fn(),
+ restartTracking: jest.fn().mockResolvedValue(undefined),
+ reconnect: jest.fn(),
+ settings: require("../../types/global").DEFAULT_SETTINGS
+ }))
+}))
+
+import { TrackingProvider, useTracking } from "../TrackingProvider"
+import NativeLocationService from "../../services/NativeLocationService"
+import SettingsService from "../../services/SettingsService"
+
+const mockGetAllSettings = NativeLocationService.getAllSettings as jest.Mock
+const mockUpdateMultiple = SettingsService.updateMultiple as jest.Mock
+
+beforeEach(() => {
+ jest.clearAllMocks()
+})
+
+describe("useTracking", () => {
+ it("throws when used outside TrackingProvider", () => {
+ const spy = jest.spyOn(console, "error").mockImplementation()
+
+ expect(() => {
+ renderHook(() => useTracking())
+ }).toThrow("useTracking must be used within TrackingProvider")
+
+ spy.mockRestore()
+ })
+
+ it("provides default settings on initial render", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({})
+
+ const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ expect(result.current.settings.interval).toBe(DEFAULT_SETTINGS.interval)
+ expect(result.current.settings.endpoint).toBe(DEFAULT_SETTINGS.endpoint)
+ })
+
+ it("hydrates settings from native storage", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({
+ interval: "10000",
+ minUpdateDistance: "25.5",
+ endpoint: "https://test.com/api",
+ isOfflineMode: "true",
+ filterInaccurateLocations: "false",
+ syncPreset: "balanced",
+ fieldMap: '{"lat":"latitude","lon":"longitude","acc":"accuracy"}',
+ customFields: '[{"key":"_type","value":"location"}]',
+ apiTemplate: "dawarich"
+ })
+
+ const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ })
+
+ expect(result.current.settings.interval).toBe(10)
+ expect(result.current.settings.distance).toBe(25.5)
+ expect(result.current.settings.endpoint).toBe("https://test.com/api")
+ expect(result.current.settings.isOfflineMode).toBe(true)
+ expect(result.current.settings.filterInaccurateLocations).toBe(false)
+ expect(result.current.settings.fieldMap.lat).toBe("latitude")
+ expect(result.current.settings.customFields).toEqual([{ key: "_type", value: "location" }])
+ expect(result.current.settings.apiTemplate).toBe("dawarich")
+ })
+
+ it("calls SettingsService.updateMultiple when setSettings is called", async () => {
+ mockGetAllSettings.mockResolvedValueOnce({})
+
+ const wrapper = ({ children }: { children: React.ReactNode }) => <TrackingProvider>{children}</TrackingProvider>
+
+ const { result } = renderHook(() => useTracking(), { wrapper })
+
+ const newSettings = { ...DEFAULT_SETTINGS, interval: 30, endpoint: "https://new.com" }
+
+ await act(async () => {
+ await result.current.setSettings(newSettings)
+ })
+
+ expect(mockUpdateMultiple).toHaveBeenCalledWith(newSettings)
+ })
+})
diff --git a/src/screens/ExportDataScreen.tsx b/src/screens/ExportDataScreen.tsx
index 236ec33f..9fe69bae 100644
--- a/src/screens/ExportDataScreen.tsx
+++ b/src/screens/ExportDataScreen.tsx
@@ -9,6 +9,15 @@ import { Container, Card, SectionTitle, Divider } from "../components"
import { useTheme } from "../hooks/useTheme"
import { ThemeColors, LocationCoords } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
+import {
+ LARGE_FILE_THRESHOLD,
+ formatBytes,
+ getByteSize,
+ convertToCSV,
+ convertToGeoJSON,
+ convertToGPX,
+ convertToKML
+} from "../utils/exportConverters"
type ExportFormat = "csv" | "geojson" | "gpx" | "kml"
@@ -16,18 +25,6 @@ interface ExportStats {
totalLocations: number
}
-const LARGE_FILE_THRESHOLD = 10 * 1024 * 1024 // 10 MB
-
-const formatBytes = (bytes: number): string => {
- if (bytes < 1024) return `${bytes} B`
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
-}
-
-const getByteSize = (content: string): number => {
- return new Blob([content]).size
-}
-
export function ExportDataScreen() {
const { colors } = useTheme()
const [exporting, setExporting] = useState(false)
@@ -385,137 +382,6 @@ const FormatOption = ({
)
}
-// --- Format Conversion Functions ---
-
-const convertToCSV = (data: LocationCoords[]): string => {
- const headers = "id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"
- const rows = data
- .map((item, i) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
- return [
- i,
- item.timestamp,
- isoTime,
- item.latitude,
- item.longitude,
- item.accuracy,
- item.altitude ?? 0,
- item.speed ?? 0,
- item.battery ?? 0
- ].join(",")
- })
- .join("\n")
- return headers + rows
-}
-
-const convertToGeoJSON = (data: LocationCoords[]): string => {
- const features = data.map((item, i) => {
- const timestamp = item.timestamp ? new Date(item.timestamp) : new Date()
- const timeStr = isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString()
-
- return {
- type: "Feature",
- geometry: {
- type: "Point",
- coordinates: [item.longitude || 0, item.latitude || 0]
- },
- properties: {
- id: i,
- accuracy: item.accuracy,
- altitude: item.altitude,
- speed: item.speed,
- battery: item.battery,
- time: timeStr
- }
- }
- })
-
- return JSON.stringify(
- {
- type: "FeatureCollection",
- features
- },
- null,
- 2
- )
-}
-
-const convertToGPX = (data: LocationCoords[]): string => {
- let gpx = `<?xml version="1.0" encoding="UTF-8"?>
-<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
- <metadata>
- <name>Colota Location Export</name>
- <time>${new Date().toISOString()}</time>
- </metadata>
- <trk>
- <name>Colota Track Export</name>
- <trkseg>`
-
- data.forEach((item) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
- gpx += `
- <trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">
- <ele>${item.altitude || 0}</ele>
- <time>${isoTime}</time>
- <extensions>
- <accuracy>${item.accuracy || 0}</accuracy>
- <speed>${item.speed || 0}</speed>
- <battery>${item.battery || 0}</battery>
- </extensions>
- </trkpt>`
- })
-
- gpx += `
- </trkseg>
- </trk>
-</gpx>`
- return gpx
-}
-
-const convertToKML = (data: LocationCoords[]): string => {
- let kml = `<?xml version="1.0" encoding="UTF-8"?>
-<kml xmlns="http://www.opengis.net/kml/2.2">
- <Document>
- <name>Colota Location Export</name>
- <description>Exported tracks from Colota Tracking</description>
- <Style id="pathStyle">
- <LineStyle>
- <color>ff0000ff</color>
- <width>4</width>
- </LineStyle>
- </Style>
- <Placemark>
- <name>Track Path</name>
- <styleUrl>#pathStyle</styleUrl>
- <LineString>
- <tessellate>1</tessellate>
- <coordinates>
- ${data.map((item) => `${item.longitude},${item.latitude},${item.altitude || 0}`).join("\n ")}
- </coordinates>
- </LineString>
- </Placemark>`
-
- data.forEach((item) => {
- const timestamp = item.timestamp ?? Date.now()
- const isoTime = new Date(timestamp).toISOString()
- kml += `
- <Placemark>
- <TimeStamp><when>${isoTime}</when></TimeStamp>
- <description>Accuracy: ${item.accuracy}m, Speed: ${item.speed}m/s</description>
- <Point>
- <coordinates>${item.longitude},${item.latitude},${item.altitude || 0}</coordinates>
- </Point>
- </Placemark>`
- })
-
- kml += `
- </Document>
-</kml>`
- return kml
-}
-
const styles = StyleSheet.create({
scrollContent: {
paddingBottom: 40
diff --git a/src/screens/SettingsScreen.tsx b/src/screens/SettingsScreen.tsx
index 8ffe2b4e..1611e15c 100644
--- a/src/screens/SettingsScreen.tsx
+++ b/src/screens/SettingsScreen.tsx
@@ -12,42 +12,10 @@ import { useTracking } from "../contexts/TrackingProvider"
import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"
import { Button, SectionTitle, Card, Container, Divider, Footer } from "../components"
import { StatsCard, PresetOption, NumericInput } from "../components"
+import { isPrivateHost, isEndpointAllowed } from "../utils/settingsValidation"
const AUTOSAVE_DEBOUNCE_MS = 1500
-function isPrivateHost(url: string) {
- try {
- // Strip protocol
- const stripped = url.replace(/^https?:\/\//, "").split(/[/?#]/)[0]
- // Extract host (before any port)
- const host = stripped.split(":")[0]
-
- // Validate host: must be valid IP or hostname
- const ipRegex =
- /^(127\.0\.0\.1|10\.(\d{1,3}\.){2}\d{1,3}|192\.168\.(\d{1,3}\.)\d{1,3}|172\.(1[6-9]|2\d|3[0-1])\.(\d{1,3}\.)\d{1,3})$/
- const hostnameRegex = /^localhost$/
-
- return ipRegex.test(host) || hostnameRegex.test(host)
- } catch {
- return false
- }
-}
-
-function isEndpointAllowed(url: string) {
- if (!url) return false
-
- const match = url.match(/^(https?):\/\/([^/:]+)(:\d+)?/)
- if (!match) return false
-
- const protocol = match[1] // http or https
- const host = match[2]
-
- if (protocol === "https") return true
- if (protocol === "http" && isPrivateHost(host)) return true
-
- return false
-}
-
/**
* Settings screen for configuring location tracking.
* Features auto-save, presets, and advanced customization.
diff --git a/src/services/__tests__/NativeLocationService.test.ts b/src/services/__tests__/NativeLocationService.test.ts
new file mode 100644
index 00000000..010dc507
--- /dev/null
+++ b/src/services/__tests__/NativeLocationService.test.ts
@@ -0,0 +1,226 @@
+jest.mock("react-native", () => ({
+ NativeModules: {
+ LocationServiceModule: {
+ startService: jest.fn().mockResolvedValue(undefined),
+ stopService: jest.fn(),
+ isServiceRunning: jest.fn().mockResolvedValue(true),
+ getStats: jest.fn().mockResolvedValue({
+ queued: 5,
+ sent: 100,
+ total: 105,
+ today: 20,
+ databaseSizeMB: 1.5
+ }),
+ getTableData: jest.fn().mockResolvedValue([]),
+ getMostRecentLocation: jest.fn().mockResolvedValue(null),
+ manualFlush: jest.fn().mockResolvedValue(true),
+ clearSentHistory: jest.fn().mockResolvedValue(undefined),
+ clearQueue: jest.fn().mockResolvedValue(10),
+ clearAllLocations: jest.fn().mockResolvedValue(50),
+ deleteOlderThan: jest.fn().mockResolvedValue(25),
+ vacuumDatabase: jest.fn().mockResolvedValue(undefined),
+ getGeofences: jest.fn().mockResolvedValue([]),
+ createGeofence: jest.fn().mockResolvedValue(1),
+ updateGeofence: jest.fn().mockResolvedValue(true),
+ deleteGeofence: jest.fn().mockResolvedValue(true),
+ checkCurrentSilentZone: jest.fn().mockResolvedValue(null),
+ recheckZoneSettings: jest.fn().mockResolvedValue(undefined),
+ saveSetting: jest.fn().mockResolvedValue(undefined),
+ getSetting: jest.fn().mockResolvedValue(null),
+ getAllSettings: jest.fn().mockResolvedValue({}),
+ isIgnoringBatteryOptimizations: jest.fn().mockResolvedValue(false),
+ requestIgnoreBatteryOptimizations: jest.fn().mockResolvedValue(true),
+ getDeviceInfo: jest.fn().mockResolvedValue({
+ model: "Pixel 7",
+ brand: "Google",
+ manufacturer: "Google",
+ device: "panther",
+ deviceId: "panther",
+ systemVersion: "14",
+ apiLevel: 34
+ }),
+ writeFile: jest.fn().mockResolvedValue("/cache/test.csv"),
+ shareFile: jest.fn().mockResolvedValue(true),
+ deleteFile: jest.fn().mockResolvedValue(true),
+ getCacheDirectory: jest.fn().mockResolvedValue("/cache"),
+ getAllAuthConfig: jest.fn().mockResolvedValue({
+ authType: "none",
+ username: "",
+ password: "",
+ bearerToken: "",
+ customHeaders: "{}"
+ }),
+ saveAuthConfig: jest.fn().mockResolvedValue(true),
+ getAuthHeaders: jest.fn().mockResolvedValue({})
+ },
+ BuildConfigModule: {
+ MIN_SDK_VERSION: 26,
+ TARGET_SDK_VERSION: 34,
+ COMPILE_SDK_VERSION: 34,
+ BUILD_TOOLS_VERSION: "34.0.0",
+ KOTLIN_VERSION: "1.9.0",
+ NDK_VERSION: "25.1.8937393",
+ VERSION_NAME: "1.0.0",
+ VERSION_CODE: 1
+ }
+ }
+}))
+
+import { NativeModules } from "react-native"
+import NativeLocationService from "../NativeLocationService"
+
+const nativeMock = NativeModules.LocationServiceModule as Record<string, jest.Mock>
+
+beforeEach(() => {
+ jest.clearAllMocks()
+})
+
+describe("NativeLocationService", () => {
+ describe("start", () => {
+ it("converts interval from seconds to milliseconds", async () => {
+ const settings = {
+ interval: 5,
+ distance: 10,
+ endpoint: "https://example.com",
+ fieldMap: { lat: "lat", lon: "lon", acc: "acc" },
+ syncInterval: 0,
+ retryInterval: 30,
+ maxRetries: 5,
+ filterInaccurateLocations: false,
+ accuracyThreshold: 50,
+ isOfflineMode: false,
+ customFields: [],
+ apiTemplate: "custom" as const,
+ syncPreset: "instant" as const
+ }
+
+ await NativeLocationService.start(settings)
+
+ expect(nativeMock.startService).toHaveBeenCalledWith(
+ expect.objectContaining({
+ interval: 5000,
+ minUpdateDistance: 10
+ })
+ )
+ })
+ })
+
+ describe("stop", () => {
+ it("calls native stopService", () => {
+ NativeLocationService.stop()
+ expect(nativeMock.stopService).toHaveBeenCalled()
+ })
+ })
+
+ describe("getStats", () => {
+ it("returns database stats", async () => {
+ const stats = await NativeLocationService.getStats()
+ expect(stats).toEqual({
+ queued: 5,
+ sent: 100,
+ total: 105,
+ today: 20,
+ databaseSizeMB: 1.5
+ })
+ })
+ })
+
+ describe("getTableData", () => {
+ it("returns empty array on error", async () => {
+ nativeMock.getTableData.mockRejectedValueOnce(new Error("DB error"))
+ const result = await NativeLocationService.getTableData("locations", 10)
+ expect(result).toEqual([])
+ })
+
+ it("passes table name, limit, and offset", async () => {
+ await NativeLocationService.getTableData("queue", 50, 10)
+ expect(nativeMock.getTableData).toHaveBeenCalledWith("queue", 50, 10)
+ })
+ })
+
+ describe("getAuthConfig", () => {
+ it("parses JSON customHeaders from raw string", async () => {
+ nativeMock.getAllAuthConfig.mockResolvedValueOnce({
+ authType: "basic",
+ username: "user",
+ password: "pass",
+ bearerToken: "",
+ customHeaders: '{"X-Custom":"value"}'
+ })
+
+ const config = await NativeLocationService.getAuthConfig()
+ expect(config.customHeaders).toEqual({ "X-Custom": "value" })
+ expect(config.authType).toBe("basic")
+ })
+
+ it("returns empty object when customHeaders is null", async () => {
+ nativeMock.getAllAuthConfig.mockResolvedValueOnce({
+ authType: "none",
+ username: "",
+ password: "",
+ bearerToken: "",
+ customHeaders: null
+ })
+
+ const config = await NativeLocationService.getAuthConfig()
+ expect(config.customHeaders).toEqual({})
+ })
+ })
+
+ describe("saveAuthConfig", () => {
+ it("stringifies customHeaders before saving", async () => {
+ await NativeLocationService.saveAuthConfig({
+ authType: "bearer",
+ username: "",
+ password: "",
+ bearerToken: "tok123",
+ customHeaders: { "X-Api-Key": "abc" }
+ })
+
+ expect(nativeMock.saveAuthConfig).toHaveBeenCalledWith(
+ expect.objectContaining({
+ customHeaders: '{"X-Api-Key":"abc"}'
+ })
+ )
+ })
+ })
+
+ describe("getBuildConfig", () => {
+ it("returns build config when module is available", () => {
+ const config = NativeLocationService.getBuildConfig()
+ expect(config).toEqual(
+ expect.objectContaining({
+ MIN_SDK_VERSION: 26,
+ VERSION_NAME: "1.0.0"
+ })
+ )
+ })
+ })
+
+ describe("geofence operations", () => {
+ it("createGeofence passes correct parameters", async () => {
+ await NativeLocationService.createGeofence({
+ name: "Home",
+ lat: 48.1,
+ lon: 11.5,
+ radius: 100,
+ enabled: true,
+ pauseTracking: true
+ })
+
+ expect(nativeMock.createGeofence).toHaveBeenCalledWith("Home", 48.1, 11.5, 100, true)
+ })
+
+ it("deleteGeofence passes id", async () => {
+ await NativeLocationService.deleteGeofence(42)
+ expect(nativeMock.deleteGeofence).toHaveBeenCalledWith(42)
+ })
+ })
+
+ describe("file operations", () => {
+ it("writeFile returns file path", async () => {
+ const path = await NativeLocationService.writeFile("test.csv", "data")
+ expect(path).toBe("/cache/test.csv")
+ })
+ })
+})
diff --git a/src/services/__tests__/SettingsService.test.ts b/src/services/__tests__/SettingsService.test.ts
new file mode 100644
index 00000000..f8899175
--- /dev/null
+++ b/src/services/__tests__/SettingsService.test.ts
@@ -0,0 +1,96 @@
+import SettingsService from "../SettingsService"
+import NativeLocationService from "../NativeLocationService"
+
+jest.mock("../NativeLocationService", () => ({
+ saveSetting: jest.fn().mockResolvedValue(undefined)
+}))
+
+const mockSaveSetting = NativeLocationService.saveSetting as jest.Mock
+
+beforeEach(() => {
+ jest.clearAllMocks()
+})
+
+describe("SettingsService", () => {
+ describe("updateSetting", () => {
+ it("converts interval from seconds to milliseconds", async () => {
+ await SettingsService.updateSetting("interval", 5)
+
+ // Should save interval * 1000
+ expect(mockSaveSetting).toHaveBeenCalledWith("interval", "5000")
+ })
+
+ it("saves distance to both 'minUpdateDistance' and 'distance' keys", async () => {
+ await SettingsService.updateSetting("distance", 10)
+
+ expect(mockSaveSetting).toHaveBeenCalledWith("minUpdateDistance", "10")
+ expect(mockSaveSetting).toHaveBeenCalledWith("distance", "10")
+ })
+
+ it("stringifies fieldMap as JSON", async () => {
+ const fieldMap = { lat: "latitude", lon: "longitude", acc: "accuracy" }
+ await SettingsService.updateSetting("fieldMap", fieldMap)
+
+ expect(mockSaveSetting).toHaveBeenCalledWith("fieldMap", JSON.stringify(fieldMap))
+ })
+
+ it("stringifies customFields as JSON", async () => {
+ const customFields = [{ key: "_type", value: "location" }]
+ await SettingsService.updateSetting("customFields", customFields)
+
+ expect(mockSaveSetting).toHaveBeenCalledWith("customFields", JSON.stringify(customFields))
+ })
+
+ it("saves boolean isOfflineMode as string", async () => {
+ await SettingsService.updateSetting("isOfflineMode", true)
+ expect(mockSaveSetting).toHaveBeenCalledWith("isOfflineMode", "true")
+
+ await SettingsService.updateSetting("isOfflineMode", false)
+ expect(mockSaveSetting).toHaveBeenCalledWith("isOfflineMode", "false")
+ })
+
+ it("saves boolean filterInaccurateLocations as string", async () => {
+ await SettingsService.updateSetting("filterInaccurateLocations", true)
+ expect(mockSaveSetting).toHaveBeenCalledWith("filterInaccurateLocations", "true")
+ })
+
+ it("saves syncInterval as string number", async () => {
+ await SettingsService.updateSetting("syncInterval", 300)
+ expect(mockSaveSetting).toHaveBeenCalledWith("syncInterval", "300")
+ })
+
+ it("saves endpoint as string", async () => {
+ await SettingsService.updateSetting("endpoint", "https://example.com/api")
+ expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://example.com/api")
+ })
+
+ it("returns true on success", async () => {
+ const result = await SettingsService.updateSetting("endpoint", "https://test.com")
+ expect(result).toBe(true)
+ })
+
+ it("returns false on error", async () => {
+ mockSaveSetting.mockRejectedValueOnce(new Error("Native error"))
+ const result = await SettingsService.updateSetting("endpoint", "test")
+ expect(result).toBe(false)
+ })
+ })
+
+ describe("updateMultiple", () => {
+ it("calls updateSetting for each key", async () => {
+ await SettingsService.updateMultiple({
+ interval: 10,
+ endpoint: "https://test.com"
+ })
+
+ // interval saves as ms
+ expect(mockSaveSetting).toHaveBeenCalledWith("interval", "10000")
+ expect(mockSaveSetting).toHaveBeenCalledWith("endpoint", "https://test.com")
+ })
+
+ it("handles empty update object", async () => {
+ await SettingsService.updateMultiple({})
+ expect(mockSaveSetting).not.toHaveBeenCalled()
+ })
+ })
+})
diff --git a/src/types/__tests__/defaults.test.ts b/src/types/__tests__/defaults.test.ts
new file mode 100644
index 00000000..40dcbb11
--- /dev/null
+++ b/src/types/__tests__/defaults.test.ts
@@ -0,0 +1,155 @@
+import { DEFAULT_SETTINGS, DEFAULT_FIELD_MAP, TRACKING_PRESETS, API_TEMPLATES, Settings } from "../global"
+
+describe("DEFAULT_FIELD_MAP", () => {
+ const requiredKeys = ["lat", "lon", "acc"]
+ const optionalKeys = ["alt", "vel", "batt", "bs", "tst", "bear"]
+
+ it("has all required field keys", () => {
+ for (const key of requiredKeys) {
+ expect(DEFAULT_FIELD_MAP).toHaveProperty(key)
+ expect(DEFAULT_FIELD_MAP[key as keyof typeof DEFAULT_FIELD_MAP]).toBeTruthy()
+ }
+ })
+
+ it("has all optional field keys", () => {
+ for (const key of optionalKeys) {
+ expect(DEFAULT_FIELD_MAP).toHaveProperty(key)
+ }
+ })
+
+ it("has exactly 9 keys", () => {
+ expect(Object.keys(DEFAULT_FIELD_MAP)).toHaveLength(9)
+ })
+})
+
+describe("DEFAULT_SETTINGS", () => {
+ it("has positive interval", () => {
+ expect(DEFAULT_SETTINGS.interval).toBeGreaterThan(0)
+ })
+
+ it("has non-negative distance", () => {
+ expect(DEFAULT_SETTINGS.distance).toBeGreaterThanOrEqual(0)
+ })
+
+ it("has empty endpoint by default", () => {
+ expect(DEFAULT_SETTINGS.endpoint).toBe("")
+ })
+
+ it("uses DEFAULT_FIELD_MAP", () => {
+ expect(DEFAULT_SETTINGS.fieldMap).toEqual(DEFAULT_FIELD_MAP)
+ })
+
+ it("has empty customFields array", () => {
+ expect(DEFAULT_SETTINGS.customFields).toEqual([])
+ })
+
+ it("has 'custom' apiTemplate", () => {
+ expect(DEFAULT_SETTINGS.apiTemplate).toBe("custom")
+ })
+
+ it("has positive maxRetries", () => {
+ expect(DEFAULT_SETTINGS.maxRetries).toBeGreaterThan(0)
+ })
+
+ it("has offline mode disabled", () => {
+ expect(DEFAULT_SETTINGS.isOfflineMode).toBe(false)
+ })
+
+ it("has all required Settings keys", () => {
+ const requiredKeys: (keyof Settings)[] = [
+ "interval",
+ "distance",
+ "endpoint",
+ "fieldMap",
+ "customFields",
+ "apiTemplate",
+ "syncInterval",
+ "retryInterval",
+ "maxRetries",
+ "isOfflineMode",
+ "syncPreset",
+ "filterInaccurateLocations",
+ "accuracyThreshold"
+ ]
+
+ for (const key of requiredKeys) {
+ expect(DEFAULT_SETTINGS).toHaveProperty(key)
+ }
+ })
+})
+
+describe("TRACKING_PRESETS", () => {
+ const presetNames = ["instant", "balanced", "powersaver"] as const
+
+ it("has all expected presets", () => {
+ for (const name of presetNames) {
+ expect(TRACKING_PRESETS).toHaveProperty(name)
+ }
+ })
+
+ it.each(presetNames)("%s has positive interval", (name) => {
+ expect(TRACKING_PRESETS[name].interval).toBeGreaterThan(0)
+ })
+
+ it.each(presetNames)("%s has non-negative distance", (name) => {
+ expect(TRACKING_PRESETS[name].distance).toBeGreaterThanOrEqual(0)
+ })
+
+ it.each(presetNames)("%s has non-negative syncInterval", (name) => {
+ expect(TRACKING_PRESETS[name].syncInterval).toBeGreaterThanOrEqual(0)
+ })
+
+ it.each(presetNames)("%s has positive retryInterval", (name) => {
+ expect(TRACKING_PRESETS[name].retryInterval).toBeGreaterThan(0)
+ })
+
+ it.each(presetNames)("%s has a label and emoji", (name) => {
+ expect(TRACKING_PRESETS[name].label).toBeTruthy()
+ expect(TRACKING_PRESETS[name].emoji).toBeTruthy()
+ })
+
+ it.each(presetNames)("%s has valid batteryImpact", (name) => {
+ expect(["Low", "Medium", "High"]).toContain(TRACKING_PRESETS[name].batteryImpact)
+ })
+
+ it("instant has shortest interval", () => {
+ expect(TRACKING_PRESETS.instant.interval).toBeLessThan(TRACKING_PRESETS.balanced.interval)
+ expect(TRACKING_PRESETS.balanced.interval).toBeLessThan(TRACKING_PRESETS.powersaver.interval)
+ })
+})
+
+describe("API_TEMPLATES", () => {
+ const templateNames = ["dawarich", "owntracks", "reitti"] as const
+
+ it.each(templateNames)("%s has valid fieldMap with required keys", (name) => {
+ const template = API_TEMPLATES[name]
+ expect(template.fieldMap).toHaveProperty("lat")
+ expect(template.fieldMap).toHaveProperty("lon")
+ expect(template.fieldMap).toHaveProperty("acc")
+ })
+
+ it.each(templateNames)("%s has non-empty customFields", (name) => {
+ expect(API_TEMPLATES[name].customFields.length).toBeGreaterThan(0)
+ })
+
+ it.each(templateNames)("%s has label and description", (name) => {
+ expect(API_TEMPLATES[name].label).toBeTruthy()
+ expect(API_TEMPLATES[name].description).toBeTruthy()
+ })
+
+ it.each(templateNames)("%s customFields have key and value", (name) => {
+ for (const field of API_TEMPLATES[name].customFields) {
+ expect(field.key).toBeTruthy()
+ expect(field.value).toBeTruthy()
+ }
+ })
+
+ it("dawarich and owntracks use 'cog' for bearing", () => {
+ expect(API_TEMPLATES.dawarich.fieldMap.bear).toBe("cog")
+ expect(API_TEMPLATES.owntracks.fieldMap.bear).toBe("cog")
+ })
+
+ it("reitti uses 'bear' for bearing", () => {
+ expect(API_TEMPLATES.reitti.fieldMap.bear).toBe("bear")
+ })
+})
diff --git a/src/utils/__tests__/exportConverters.test.ts b/src/utils/__tests__/exportConverters.test.ts
new file mode 100644
index 00000000..fd828b97
--- /dev/null
+++ b/src/utils/__tests__/exportConverters.test.ts
@@ -0,0 +1,205 @@
+import {
+ formatBytes,
+ getByteSize,
+ convertToCSV,
+ convertToGeoJSON,
+ convertToGPX,
+ convertToKML,
+ LARGE_FILE_THRESHOLD
+} from "../exportConverters"
+import { LocationCoords } from "../../types/global"
+
+const sampleLocation: LocationCoords = {
+ latitude: 48.137154,
+ longitude: 11.576124,
+ accuracy: 10,
+ altitude: 520,
+ speed: 1.5,
+ bearing: 180,
+ battery: 85,
+ battery_status: 2,
+ timestamp: 1700000000000
+}
+
+const minimalLocation: LocationCoords = {
+ latitude: 0,
+ longitude: 0
+}
+
+describe("formatBytes", () => {
+ it("formats bytes", () => {
+ expect(formatBytes(0)).toBe("0 B")
+ expect(formatBytes(500)).toBe("500 B")
+ expect(formatBytes(1023)).toBe("1023 B")
+ })
+
+ it("formats kilobytes", () => {
+ expect(formatBytes(1024)).toBe("1.0 KB")
+ expect(formatBytes(1536)).toBe("1.5 KB")
+ })
+
+ it("formats megabytes", () => {
+ expect(formatBytes(1048576)).toBe("1.0 MB")
+ expect(formatBytes(1572864)).toBe("1.5 MB")
+ })
+})
+
+describe("getByteSize", () => {
+ it("returns correct size for ASCII string", () => {
+ expect(getByteSize("hello")).toBe(5)
+ })
+
+ it("returns correct size for empty string", () => {
+ expect(getByteSize("")).toBe(0)
+ })
+
+ it("handles multi-byte characters", () => {
+ // UTF-8: ö = 2 bytes
+ expect(getByteSize("ö")).toBeGreaterThan(1)
+ })
+})
+
+describe("LARGE_FILE_THRESHOLD", () => {
+ it("is 10 MB", () => {
+ expect(LARGE_FILE_THRESHOLD).toBe(10 * 1024 * 1024)
+ })
+})
+
+describe("convertToCSV", () => {
+ it("returns headers for empty data", () => {
+ const csv = convertToCSV([])
+ expect(csv).toContain("id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery")
+ })
+
+ it("converts a single location", () => {
+ const csv = convertToCSV([sampleLocation])
+ const lines = csv.split("\n")
+ expect(lines).toHaveLength(2) // header + 1 row
+
+ const row = lines[1]
+ expect(row).toContain("48.137154")
+ expect(row).toContain("11.576124")
+ expect(row).toContain("10") // accuracy
+ })
+
+ it("defaults missing optional fields to 0", () => {
+ const csv = convertToCSV([minimalLocation])
+ const row = csv.split("\n")[1]
+ // altitude, speed, battery should be 0
+ expect(row).toMatch(/,0,0,0$/)
+ })
+
+ it("handles multiple locations", () => {
+ const csv = convertToCSV([sampleLocation, sampleLocation])
+ const lines = csv.split("\n")
+ expect(lines).toHaveLength(3) // header + 2 rows
+ expect(lines[1]).toMatch(/^0,/) // first row id=0
+ expect(lines[2]).toMatch(/^1,/) // second row id=1
+ })
+})
+
+describe("convertToGeoJSON", () => {
+ it("returns valid FeatureCollection for empty data", () => {
+ const result = JSON.parse(convertToGeoJSON([]))
+ expect(result.type).toBe("FeatureCollection")
+ expect(result.features).toEqual([])
+ })
+
+ it("creates Point features with [lon, lat] order", () => {
+ const result = JSON.parse(convertToGeoJSON([sampleLocation]))
+ const coords = result.features[0].geometry.coordinates
+ expect(coords[0]).toBe(11.576124) // longitude first
+ expect(coords[1]).toBe(48.137154) // latitude second
+ })
+
+ it("includes properties", () => {
+ const result = JSON.parse(convertToGeoJSON([sampleLocation]))
+ const props = result.features[0].properties
+ expect(props.accuracy).toBe(10)
+ expect(props.altitude).toBe(520)
+ expect(props.speed).toBe(1.5)
+ expect(props.battery).toBe(85)
+ })
+
+ it("handles missing timestamp gracefully", () => {
+ const result = JSON.parse(convertToGeoJSON([minimalLocation]))
+ const time = result.features[0].properties.time
+ // Should be a valid ISO string (falls back to current date)
+ expect(() => new Date(time)).not.toThrow()
+ })
+
+ it("defaults missing coordinates to 0", () => {
+ const result = JSON.parse(convertToGeoJSON([minimalLocation]))
+ const coords = result.features[0].geometry.coordinates
+ expect(coords).toEqual([0, 0])
+ })
+})
+
+describe("convertToGPX", () => {
+ it("returns valid GPX XML structure", () => {
+ const gpx = convertToGPX([])
+ expect(gpx).toContain('<?xml version="1.0"')
+ expect(gpx).toContain("<gpx")
+ expect(gpx).toContain("</gpx>")
+ expect(gpx).toContain("<trkseg>")
+ expect(gpx).toContain("</trkseg>")
+ })
+
+ it("includes trackpoints with lat/lon to 6 decimals", () => {
+ const gpx = convertToGPX([sampleLocation])
+ expect(gpx).toContain('lat="48.137154"')
+ expect(gpx).toContain('lon="11.576124"')
+ })
+
+ it("includes elevation and extensions", () => {
+ const gpx = convertToGPX([sampleLocation])
+ expect(gpx).toContain("<ele>520</ele>")
+ expect(gpx).toContain("<accuracy>10</accuracy>")
+ expect(gpx).toContain("<speed>1.5</speed>")
+ expect(gpx).toContain("<battery>85</battery>")
+ })
+
+ it("defaults missing fields to 0", () => {
+ const gpx = convertToGPX([minimalLocation])
+ expect(gpx).toContain("<ele>0</ele>")
+ expect(gpx).toContain("<accuracy>0</accuracy>")
+ expect(gpx).toContain("<speed>0</speed>")
+ expect(gpx).toContain("<battery>0</battery>")
+ })
+})
+
+describe("convertToKML", () => {
+ it("returns valid KML XML structure", () => {
+ const kml = convertToKML([])
+ expect(kml).toContain('<?xml version="1.0"')
+ expect(kml).toContain("<kml")
+ expect(kml).toContain("</kml>")
+ expect(kml).toContain("<Document>")
+ expect(kml).toContain("</Document>")
+ })
+
+ it("includes LineString track path", () => {
+ const kml = convertToKML([sampleLocation])
+ expect(kml).toContain("<LineString>")
+ expect(kml).toContain("11.576124,48.137154,520")
+ })
+
+ it("includes individual Placemarks with timestamps", () => {
+ const kml = convertToKML([sampleLocation])
+ expect(kml).toContain("<TimeStamp>")
+ expect(kml).toContain("<Point>")
+ expect(kml).toContain("Accuracy: 10m")
+ expect(kml).toContain("Speed: 1.5m/s")
+ })
+
+ it("includes style definition", () => {
+ const kml = convertToKML([sampleLocation])
+ expect(kml).toContain('<Style id="pathStyle">')
+ expect(kml).toContain("<color>ff0000ff</color>")
+ })
+
+ it("defaults missing altitude to 0", () => {
+ const kml = convertToKML([minimalLocation])
+ expect(kml).toContain("0,0,0") // lon,lat,alt
+ })
+})
diff --git a/src/utils/__tests__/queueStatus.test.ts b/src/utils/__tests__/queueStatus.test.ts
new file mode 100644
index 00000000..280b06cf
--- /dev/null
+++ b/src/utils/__tests__/queueStatus.test.ts
@@ -0,0 +1,38 @@
+import { getQueueColor } from "../queueStatus"
+import { ThemeColors } from "../../types/global"
+
+const mockColors = {
+ text: "#202124",
+ warning: "#FF9800",
+ error: "#D32F2F"
+} as ThemeColors
+
+describe("getQueueColor", () => {
+ it("returns text color for zero items", () => {
+ expect(getQueueColor(0, mockColors)).toBe(mockColors.text)
+ })
+
+ it("returns text color for count at threshold boundary (50)", () => {
+ expect(getQueueColor(50, mockColors)).toBe(mockColors.text)
+ })
+
+ it("returns warning color when count exceeds 50", () => {
+ expect(getQueueColor(51, mockColors)).toBe(mockColors.warning)
+ })
+
+ it("returns warning color at critical boundary (100)", () => {
+ expect(getQueueColor(100, mockColors)).toBe(mockColors.warning)
+ })
+
+ it("returns error color when count exceeds 100", () => {
+ expect(getQueueColor(101, mockColors)).toBe(mockColors.error)
+ })
+
+ it("returns error color for very large counts", () => {
+ expect(getQueueColor(10000, mockColors)).toBe(mockColors.error)
+ })
+
+ it("returns text color for negative numbers", () => {
+ expect(getQueueColor(-1, mockColors)).toBe(mockColors.text)
+ })
+})
diff --git a/src/utils/__tests__/settingsValidation.test.ts b/src/utils/__tests__/settingsValidation.test.ts
new file mode 100644
index 00000000..f026b97b
--- /dev/null
+++ b/src/utils/__tests__/settingsValidation.test.ts
@@ -0,0 +1,106 @@
+import { isPrivateHost, isEndpointAllowed } from "../settingsValidation"
+
+describe("isPrivateHost", () => {
+ describe("private IPs", () => {
+ it("detects localhost IP", () => {
+ expect(isPrivateHost("127.0.0.1")).toBe(true)
+ })
+
+ it("detects 10.x.x.x range", () => {
+ expect(isPrivateHost("10.0.0.1")).toBe(true)
+ expect(isPrivateHost("10.255.255.255")).toBe(true)
+ })
+
+ it("detects 192.168.x.x range", () => {
+ expect(isPrivateHost("192.168.1.1")).toBe(true)
+ expect(isPrivateHost("192.168.0.100")).toBe(true)
+ })
+
+ it("detects 172.16-31.x.x range", () => {
+ expect(isPrivateHost("172.16.0.1")).toBe(true)
+ expect(isPrivateHost("172.31.255.255")).toBe(true)
+ })
+
+ it("detects localhost hostname", () => {
+ expect(isPrivateHost("localhost")).toBe(true)
+ })
+ })
+
+ describe("public IPs and hosts", () => {
+ it("rejects public IPs", () => {
+ expect(isPrivateHost("8.8.8.8")).toBe(false)
+ expect(isPrivateHost("1.1.1.1")).toBe(false)
+ })
+
+ it("rejects public hostnames", () => {
+ expect(isPrivateHost("google.com")).toBe(false)
+ expect(isPrivateHost("example.com")).toBe(false)
+ })
+
+ it("rejects 172.32+ (outside private range)", () => {
+ expect(isPrivateHost("172.32.0.1")).toBe(false)
+ })
+ })
+
+ describe("URL handling", () => {
+ it("strips http protocol", () => {
+ expect(isPrivateHost("http://192.168.1.1")).toBe(true)
+ })
+
+ it("strips https protocol", () => {
+ expect(isPrivateHost("https://localhost")).toBe(true)
+ })
+
+ it("handles URLs with ports", () => {
+ expect(isPrivateHost("192.168.1.1:3000")).toBe(true)
+ expect(isPrivateHost("http://10.0.0.1:8080")).toBe(true)
+ })
+
+ it("handles URLs with paths", () => {
+ expect(isPrivateHost("http://192.168.1.1/api/locations")).toBe(true)
+ })
+ })
+
+ describe("edge cases", () => {
+ it("returns false for empty string", () => {
+ expect(isPrivateHost("")).toBe(false)
+ })
+ })
+})
+
+describe("isEndpointAllowed", () => {
+ describe("HTTPS endpoints", () => {
+ it("allows any HTTPS endpoint", () => {
+ expect(isEndpointAllowed("https://example.com/api")).toBe(true)
+ expect(isEndpointAllowed("https://api.server.io:443/v1")).toBe(true)
+ })
+ })
+
+ describe("HTTP endpoints", () => {
+ it("allows HTTP to private hosts", () => {
+ expect(isEndpointAllowed("http://192.168.1.1/api")).toBe(true)
+ expect(isEndpointAllowed("http://localhost:3000/locations")).toBe(true)
+ expect(isEndpointAllowed("http://10.0.0.1:8080")).toBe(true)
+ })
+
+ it("rejects HTTP to public hosts", () => {
+ expect(isEndpointAllowed("http://google.com")).toBe(false)
+ expect(isEndpointAllowed("http://api.example.com/v1")).toBe(false)
+ })
+ })
+
+ describe("invalid inputs", () => {
+ it("rejects empty string", () => {
+ expect(isEndpointAllowed("")).toBe(false)
+ })
+
+ it("rejects URLs without protocol", () => {
+ expect(isEndpointAllowed("example.com/api")).toBe(false)
+ })
+
+ it("rejects non-HTTP protocols", () => {
+ expect(isEndpointAllowed("ftp://example.com")).toBe(false)
+ expect(isEndpointAllowed("ws://example.com")).toBe(false)
+ })
+ })
+})
diff --git a/src/utils/exportConverters.ts b/src/utils/exportConverters.ts
new file mode 100644
index 00000000..ca092003
--- /dev/null
+++ b/src/utils/exportConverters.ts
@@ -0,0 +1,147 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { LocationCoords } from "../types/global"
+
+export const LARGE_FILE_THRESHOLD = 10 * 1024 * 1024 // 10 MB
+
+export const formatBytes = (bytes: number): string => {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+export const getByteSize = (content: string): number => {
+ return new Blob([content]).size
+}
+
+export const convertToCSV = (data: LocationCoords[]): string => {
+ const headers = "id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n"
+ const rows = data
+ .map((item, i) => {
+ const timestamp = item.timestamp ?? Date.now()
+ const isoTime = new Date(timestamp).toISOString()
+ return [
+ i,
+ item.timestamp,
+ isoTime,
+ item.latitude,
+ item.longitude,
+ item.accuracy,
+ item.altitude ?? 0,
+ item.speed ?? 0,
+ item.battery ?? 0
+ ].join(",")
+ })
+ .join("\n")
+ return headers + rows
+}
+
+export const convertToGeoJSON = (data: LocationCoords[]): string => {
+ const features = data.map((item, i) => {
+ const timestamp = item.timestamp ? new Date(item.timestamp) : new Date()
+ const timeStr = isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString()
+
+ return {
+ type: "Feature",
+ geometry: {
+ type: "Point",
+ coordinates: [item.longitude || 0, item.latitude || 0]
+ },
+ properties: {
+ id: i,
+ accuracy: item.accuracy,
+ altitude: item.altitude,
+ speed: item.speed,
+ battery: item.battery,
+ time: timeStr
+ }
+ }
+ })
+
+ return JSON.stringify(
+ {
+ type: "FeatureCollection",
+ features
+ },
+ null,
+ 2
+ )
+}
+
+export const convertToGPX = (data: LocationCoords[]): string => {
+ let gpx = `<?xml version="1.0" encoding="UTF-8"?>
+<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
+ <metadata>
+ <name>Colota Location Export</name>
+ <time>${new Date().toISOString()}</time>
+ </metadata>
+ <trk>
+ <name>Colota Track Export</name>
+ <trkseg>`
+
+ data.forEach((item) => {
+ const timestamp = item.timestamp ?? Date.now()
+ const isoTime = new Date(timestamp).toISOString()
+ gpx += `
+ <trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(6)}">
+ <ele>${item.altitude || 0}</ele>
+ <time>${isoTime}</time>
+ <extensions>
+ <accuracy>${item.accuracy || 0}</accuracy>
+ <speed>${item.speed || 0}</speed>
+ <battery>${item.battery || 0}</battery>
+ </extensions>
+ </trkpt>`
+ })
+
+ gpx += `
+ </trkseg>
+ </trk>
+</gpx>`
+ return gpx
+}
+
+export const convertToKML = (data: LocationCoords[]): string => {
+ let kml = `<?xml version="1.0" encoding="UTF-8"?>
+<kml xmlns="http://www.opengis.net/kml/2.2">
+ <Document>
+ <name>Colota Location Export</name>
+ <description>Exported tracks from Colota Tracking</description>
+ <Style id="pathStyle">
+ <LineStyle>
+ <color>ff0000ff</color>
+ <width>4</width>
+ </LineStyle>
+ </Style>
+ <Placemark>
+ <name>Track Path</name>
+ <styleUrl>#pathStyle</styleUrl>
+ <LineString>
+ <tessellate>1</tessellate>
+ <coordinates>
+ ${data.map((item) => `${item.longitude},${item.latitude},${item.altitude || 0}`).join("\n ")}
+ </coordinates>
+ </LineString>
+ </Placemark>`
+
+ data.forEach((item) => {
+ const timestamp = item.timestamp ?? Date.now()
+ const isoTime = new Date(timestamp).toISOString()
+ kml += `
+ <Placemark>
+ <TimeStamp><when>${isoTime}</when></TimeStamp>
+ <description>Accuracy: ${item.accuracy}m, Speed: ${item.speed}m/s</description>
+ <Point>
+ <coordinates>${item.longitude},${item.latitude},${item.altitude || 0}</coordinates>
+ </Point>
+ </Placemark>`
+ })
+
+ kml += `
+ </Document>
+</kml>`
+ return kml
+}
diff --git a/src/services/queueStatus.ts b/src/utils/queueStatus.ts
similarity index 100%
rename from src/services/queueStatus.ts
rename to src/utils/queueStatus.ts
diff --git a/src/utils/settingsValidation.ts b/src/utils/settingsValidation.ts
new file mode 100644
index 00000000..c92156ce
--- /dev/null
+++ b/src/utils/settingsValidation.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+export function isPrivateHost(url: string) {
+ try {
+ // Strip protocol
+ const stripped = url.replace(/^https?:\/\//, "").split(/[/?#]/)[0]
+ // Extract host (before any port)
+ const host = stripped.split(":")[0]
+
+ // Validate host: must be valid IP or hostname
+ const ipRegex =
+ /^(127\.0\.0\.1|10\.(\d{1,3}\.){2}\d{1,3}|192\.168\.(\d{1,3}\.)\d{1,3}|172\.(1[6-9]|2\d|3[0-1])\.(\d{1,3}\.)\d{1,3})$/
+ const hostnameRegex = /^localhost$/
+
+ return ipRegex.test(host) || hostnameRegex.test(host)
+ } catch {
+ return false
+ }
+}
+
+export function isEndpointAllowed(url: string) {
+ if (!url) return false
+
+ const match = url.match(/^(https?):\/\/([^/:]+)(:\d+)?/)
+ if (!match) return false
+
+ const protocol = match[1] // http or https
+ const host = match[2]
+
+ if (protocol === "https") return true
+ if (protocol === "http" && isPrivateHost(host)) return true
+
+ return false
+}