Colota - Android GPS Location tracker
Fix bugs and improve codebase consistency
Max Dietrich5a95050acc44
diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.mdindex b620cb0b..936aac4b 100644--- a/apps/docs/docs/guides/data-export.md+++ b/apps/docs/docs/guides/data-export.md@@ -29,15 +29,7 @@ Export your location history in multiple formats.</figure></div>-## Data Management--In the Data Management screen you can also:--- **Clear Sent History** - Remove locations that have already been synced-- **Delete Older Than X Days** - Clean up old data-- **Vacuum Database** - Reclaim disk space after deletions--### Storage Reference+## Storage Reference- ~200 bytes per location- ~2 MB per 10,000 locationsdiff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.mdnew file mode 100644index 00000000..e673ff3c--- /dev/null+++ b/apps/docs/docs/guides/data-management.md@@ -0,0 +1,23 @@+---+sidebar_position: 3+---++# Data Management++Manage your location database from the Data Management screen.++## Actions++| Action | Description |+| ---------------------------- | ----------------------------------------------------------- |+| **Sync Now** | Manually flush the queue and upload pending locations |+| **Clear Sent History** | Remove locations that have already been synced |+| **Clear Queue** | Remove unsent locations from the upload queue |+| **Delete Older Than X Days** | Clean up old data past a specified age |+| **Vacuum Database** | Reclaim disk space after deletions |+| **Export Data** | Export location history — see [Data Export](data-export.md) |++## Storage Reference++- ~200 bytes per location+- ~2 MB per 10,000 locationsdiff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.tsindex 62747e3e..9bbbe336 100644--- a/apps/mobile/src/hooks/useLocationTracking.ts+++ b/apps/mobile/src/hooks/useLocationTracking.ts@@ -262,7 +262,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResultif (restartQueuedRef.current) {restartQueuedRef.current = falselogger.debug("[useLocationTracking] Processing queued restart")- setTimeout(() => restartTracking(newSettings), 100)+ setTimeout(() => restartTracking(settingsRef.current), 100)}}},diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsxindex 06f963ba..8e6a7e59 100644--- a/apps/mobile/src/screens/AboutScreen.tsx+++ b/apps/mobile/src/screens/AboutScreen.tsx@@ -10,6 +10,7 @@ import { useTheme } from "../hooks/useTheme"import { ChevronRight, Bug, FileText, Code, ScrollText, MessageCircle, Copy, Check } from "lucide-react-native"import { fonts } from "../styles/typography"import { Card, Container, Divider, SectionTitle, Footer } from "../components"+import { useTimeout } from "../hooks/useTimeout"import NativeLocationService from "../services/NativeLocationService"import icon from "../assets/icons/icon.png"import { REPO_URL, ISSUES_URL, PRIVACY_POLICY_URL } from "../constants"@@ -79,6 +80,7 @@ export function AboutScreen({}: ScreenProps) {const [showDebugInfo, setShowDebugInfo] = useState(false)const [tapCount, setTapCount] = useState(0)const [copied, setCopied] = useState(false)+ const copiedTimeout = useTimeout()const [deviceInfo, setDeviceInfo] = useState<{model: stringbrand: string@@ -167,11 +169,11 @@ export function AboutScreen({}: ScreenProps) {try {await NativeLocationService.copyToClipboard(lines.join("\n"), "Debug Info")setCopied(true)- setTimeout(() => setCopied(false), 2000)+ copiedTimeout.set(() => setCopied(false), 2000)} catch (err) {logger.error("Failed to copy debug info:", err)}- }, [buildConfig, deviceInfo])+ }, [buildConfig, deviceInfo, copiedTimeout])// Fallback if buildConfig is not availableif (!buildConfig) {diff --git a/apps/mobile/src/screens/ApiSettingsScreen.tsx b/apps/mobile/src/screens/ApiSettingsScreen.tsxindex d8b115db..da9c3cd4 100644--- a/apps/mobile/src/screens/ApiSettingsScreen.tsx+++ b/apps/mobile/src/screens/ApiSettingsScreen.tsx@@ -16,10 +16,12 @@ import {} from "../types/global"import { useTheme } from "../hooks/useTheme"import { useAutoSave } from "../hooks/useAutoSave"+import { useTimeout } from "../hooks/useTimeout"import { useTracking } from "../contexts/TrackingProvider"import NativeLocationService from "../services/NativeLocationService"import { fonts } from "../styles/typography"import { SectionTitle, FloatingSaveIndicator, Container, Divider, ChipGroup } from "../components"+import { findDuplicates } from "../utils/settingsValidation"type LocalCustomField = CustomField & { id: number }@@ -82,7 +84,7 @@ export function ApiSettingsScreen({}: ScreenProps) {const [localTemplate, setLocalTemplate] = useState<ApiTemplateName>(settings.apiTemplate || "custom")const [localHttpMethod, setLocalHttpMethod] = useState<HttpMethod>(settings.httpMethod || "POST")const [copied, setCopied] = useState(false)- const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const copiedTimeout = useTimeout()const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()const referenceFieldMap = getReferenceFieldMap(localTemplate)@@ -107,13 +109,7 @@ export function ApiSettingsScreen({}: ScreenProps) {for (const f of localCustomFields) {if (f.key.trim()) allNames.push(f.key.trim())}- const seen = new Set<string>()- const dupes = new Set<string>()- for (const name of allNames) {- if (seen.has(name)) dupes.add(name)- seen.add(name)- }- return dupes+ return findDuplicates(allNames)}, [localFieldMap, localCustomFields])/** Example payload string showing all fields */@@ -340,13 +336,12 @@ export function ApiSettingsScreen({}: ScreenProps) {const handleCopyPayload = useCallback(async () => {try {await NativeLocationService.copyToClipboard(examplePayload, "API Payload")- if (copiedTimerRef.current) clearTimeout(copiedTimerRef.current)setCopied(true)- copiedTimerRef.current = setTimeout(() => setCopied(false), 2000)+ copiedTimeout.set(() => setCopied(false), 2000)} catch {// Copy failed — no action needed}- }, [examplePayload])+ }, [examplePayload, copiedTimeout])return (<Container>diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsxindex 69348bbf..c8d6f8cb 100644--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx@@ -13,6 +13,7 @@ import { fonts, fontSizes } from "../styles/typography"import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider, ChipGroup } from "../components"import NativeLocationService from "../services/NativeLocationService"import { logger } from "../utils/logger"+import { findDuplicates } from "../utils/settingsValidation"const AUTH_TYPES: { value: AuthType; label: string }[] = [{ value: "none", label: "None" },@@ -55,15 +56,8 @@ export function AuthSettingsScreen({}: ScreenProps) {/** Detect duplicate header keys */const duplicateKeys = useMemo(() => {- const seen = new Set<string>()- const dupes = new Set<string>()- for (const h of localHeaders) {- const k = h.key.trim()- if (!k) continue- if (seen.has(k)) dupes.add(k)- seen.add(k)- }- return dupes+ const keys = localHeaders.map((h) => h.key.trim()).filter(Boolean)+ return findDuplicates(keys)}, [localHeaders])/** Convert local headers array to Record for saving */diff --git a/apps/mobile/src/screens/LocationInspectorScreen.tsx b/apps/mobile/src/screens/LocationInspectorScreen.tsxindex 41f5fde2..66f62e8a 100644--- a/apps/mobile/src/screens/LocationInspectorScreen.tsx+++ b/apps/mobile/src/screens/LocationInspectorScreen.tsx@@ -137,20 +137,24 @@ export function LocationHistoryScreen() {return formatDistance(meters)}, [trackLocations])+ const fetchIdRef = useRef(0)+/** Fetches data based on current pagination */const fetchData = useCallback(async () => {+ const id = ++fetchIdRef.currenttry {const offset = page * limitconst result = await NativeLocationService.getTableData("locations", limit, offset)- setData(result || [])+ if (id === fetchIdRef.current) setData(result || [])} catch (err) {logger.error("[LocationHistory] Fetch error:", err)- setData([])+ if (id === fetchIdRef.current) setData([])}}, [limit, page])/** Fetch track data for the selected day */const fetchTrackData = useCallback(async () => {+ const id = ++fetchIdRef.currenttry {const start = new Date(mapDate)start.setHours(0, 0, 0, 0)@@ -161,10 +165,10 @@ export function LocationHistoryScreen() {const endTimestamp = Math.floor(end.getTime() / 1000)const result = await NativeLocationService.getLocationsByDateRange(startTimestamp, endTimestamp)- setTrackLocations(result || [])+ if (id === fetchIdRef.current) setTrackLocations(result || [])} catch (err) {logger.error("[LocationHistory] Track fetch error:", err)- setTrackLocations([])+ if (id === fetchIdRef.current) setTrackLocations([])}}, [mapDate])diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex cb20a55d..c214d63d 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -491,12 +491,22 @@ class NativeLocationService {static async getAuthConfig(): Promise<AuthConfig> {this.ensureModule()const raw = await LocationServiceModule.getAllAuthConfig()++ let customHeaders: Record<string, string> = {}+ if (raw.customHeaders) {+ try {+ customHeaders = JSON.parse(raw.customHeaders)+ } catch {+ // Corrupted JSON — reset to empty+ }+ }+return {authType: raw.authType || "none",username: raw.username || "",password: raw.password || "",bearerToken: raw.bearerToken || "",- customHeaders: raw.customHeaders ? JSON.parse(raw.customHeaders) : {}+ customHeaders}}diff --git a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts b/apps/mobile/src/services/__tests__/NativeLocationService.test.tsindex 0b4416ea..9b52f7e9 100644--- a/apps/mobile/src/services/__tests__/NativeLocationService.test.ts+++ b/apps/mobile/src/services/__tests__/NativeLocationService.test.ts@@ -12,6 +12,7 @@ jest.mock("react-native", () => ({databaseSizeMB: 1.5}),getTableData: jest.fn().mockResolvedValue([]),+ getLocationsByDateRange: jest.fn().mockResolvedValue([]),getMostRecentLocation: jest.fn().mockResolvedValue(null),manualFlush: jest.fn().mockResolvedValue(true),clearSentHistory: jest.fn().mockResolvedValue(undefined),@@ -52,7 +53,8 @@ jest.mock("react-native", () => ({customHeaders: "{}"}),saveAuthConfig: jest.fn().mockResolvedValue(true),- getAuthHeaders: jest.fn().mockResolvedValue({})+ getAuthHeaders: jest.fn().mockResolvedValue({}),+ isNetworkAvailable: jest.fn().mockResolvedValue(true)},BuildConfigModule: {MIN_SDK_VERSION: 26,diff --git a/apps/mobile/src/utils/settingsValidation.ts b/apps/mobile/src/utils/settingsValidation.tsindex c92156ce..55413991 100644--- a/apps/mobile/src/utils/settingsValidation.ts+++ b/apps/mobile/src/utils/settingsValidation.ts@@ -3,6 +3,19 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/+/**+ * Returns the set of strings that appear more than once in the input.+ */+export function findDuplicates(values: string[]): Set<string> {+ const seen = new Set<string>()+ const dupes = new Set<string>()+ for (const v of values) {+ if (seen.has(v)) dupes.add(v)+ seen.add(v)+ }+ return dupes+}+export function isPrivateHost(url: string) {try {// Strip protocol