Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(location): guard geocoding updates and handle Null Island

Timothy Yine25ff314f0ad
diff --git a/app/components/dashboard/LocationMigration.vue b/app/components/dashboard/LocationMigration.vue
index ba0e4d24..d35a0613 100644
--- a/app/components/dashboard/LocationMigration.vue
+++ b/app/components/dashboard/LocationMigration.vue
@@ -1,6 +1,5 @@
<script setup lang="ts">
const { user } = useUserSession()
-const router = useRouter()
const migrationOpen = ref(false)
const migrationCount = ref(0)
const migrationLoading = ref(false)
@@ -11,23 +10,20 @@ const migrationHandled = useState('location-migration-handled', () => false)
async function checkLocationMigration() {
if (!user.value?.isAdmin || migrationHandled.value) return
try {
- const stats = await $fetch('/api/system/stats')
+ const status = await $fetch('/api/location/migration-status')
if (migrationHandled.value) return
- migrationCount.value = stats.locationMigration.count
- migrationOpen.value = migrationCount.value > 0
+ migrationCount.value = status.count
+ migrationOpen.value = migrationCount.value > 0 && !status.requestActive
} catch (error) {
console.error('Failed to check location migration', error)
}
}
-let removeNavigationHook: (() => void) | undefined
+// The dashboard layout stays mounted during navigation. Check once per visit;
+// cancelling allows another prompt after leaving and returning to the dashboard.
onMounted(() => {
void checkLocationMigration()
- removeNavigationHook = router.afterEach(() => {
- void checkLocationMigration()
- })
})
-onUnmounted(() => removeNavigationHook?.())
async function confirmLocationMigration() {
migrationLoading.value = true
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vue
index 8f609821..d9fe3058 100644
--- a/app/components/photo/InfoPanel.vue
+++ b/app/components/photo/InfoPanel.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from 'vue'
+import { hasValidCoordinates } from '~~/shared/utils/location'
import { motion } from 'motion-v'
import type { NeededExif } from '../../../shared/types/photo'
import type { KVData } from './KVRenderer.vue'
@@ -101,23 +102,24 @@ const formatGPSCoordinatesMultiLine = (
const gpsCoordinates = computed(() => {
// 优先使用数据库中存储的坐标
if (
- props.currentPhoto.latitude != null &&
- props.currentPhoto.longitude != null
+ hasValidCoordinates(
+ props.currentPhoto.latitude,
+ props.currentPhoto.longitude,
+ )
) {
return {
- latitude: props.currentPhoto.latitude,
- longitude: props.currentPhoto.longitude,
+ latitude: props.currentPhoto.latitude!,
+ longitude: props.currentPhoto.longitude!,
}
}
// 如果数据库中没有,尝试从EXIF数据中获取
if (!props.exifData) return null
const { GPSLatitude, GPSLongitude } = props.exifData
- if (GPSLatitude && GPSLongitude) {
- return {
- latitude: parseFloat(`${GPSLatitude}`),
- longitude: parseFloat(`${GPSLongitude}`),
- }
+ if (GPSLatitude != null && GPSLongitude != null) {
+ const latitude = parseFloat(`${GPSLatitude}`)
+ const longitude = parseFloat(`${GPSLongitude}`)
+ if (hasValidCoordinates(latitude, longitude)) return { latitude, longitude }
}
return null
})
@@ -230,13 +232,15 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {
]
: []
}),
- props.currentPhoto.latitude != null &&
- props.currentPhoto.longitude != null
+ hasValidCoordinates(
+ props.currentPhoto.latitude,
+ props.currentPhoto.longitude,
+ )
? {
label: $t('exif.gps.title'),
value: formatGPSCoordinatesMultiLine(
- props.currentPhoto.latitude,
- props.currentPhoto.longitude,
+ props.currentPhoto.latitude!,
+ props.currentPhoto.longitude!,
),
icon: 'tabler:gps',
}
diff --git a/app/pages/globe.vue b/app/pages/globe.vue
index 34c4e8bc..7ecf1674 100644
--- a/app/pages/globe.vue
+++ b/app/pages/globe.vue
@@ -1,4 +1,5 @@
<script lang="ts" setup>
+import { hasValidCoordinates } from '~~/shared/utils/location'
import { motion } from 'motion-v'
import { clusterMarkers, photosToMarkers } from '~/utils/clustering'
@@ -14,11 +15,7 @@ const { photos } = usePhotos()
const photosWithLocation = computed(() => {
return photos.value.filter(
- (photo) =>
- photo.latitude !== null &&
- photo.longitude !== null &&
- photo.latitude !== undefined &&
- photo.longitude !== undefined,
+ (photo) => hasValidCoordinates(photo.latitude, photo.longitude),
)
})
diff --git a/app/utils/clustering.ts b/app/utils/clustering.ts
index 63ab1c9a..bcc25646 100644
--- a/app/utils/clustering.ts
+++ b/app/utils/clustering.ts
@@ -1,3 +1,4 @@
+import { hasValidCoordinates } from '../../shared/utils/location.ts'
import type { PhotoMarker, ClusterPoint } from '~~/shared/types/map'
/**
@@ -89,13 +90,7 @@ export function clusterMarkers(
export function photosToMarkers(photos: Photo[]): PhotoMarker[] {
return photos
- .filter(
- (photo) =>
- photo.latitude !== null &&
- photo.longitude !== null &&
- photo.latitude !== undefined &&
- photo.longitude !== undefined,
- )
+ .filter((photo) => hasValidCoordinates(photo.latitude, photo.longitude))
.map((photo) => ({
id: photo.id,
latitude: photo.latitude!,
diff --git a/server/api/location/migration-status.get.ts b/server/api/location/migration-status.get.ts
new file mode 100644
index 00000000..23ee695f
--- /dev/null
+++ b/server/api/location/migration-status.get.ts
@@ -0,0 +1,12 @@
+import { getLocationMigrationStatus } from '../../services/pipeline-queue/location-migration.ts'
+
+export default defineEventHandler(async (event) => {
+ const session = await requireUserSession(event)
+ if (!session.user.isAdmin) {
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+ }
+ return getLocationMigrationStatus(useDB())
+})
diff --git a/server/api/photos/[photoId]/index.put.ts b/server/api/photos/[photoId]/index.put.ts
index a27494c4..ad00390a 100644
--- a/server/api/photos/[photoId]/index.put.ts
+++ b/server/api/photos/[photoId]/index.put.ts
@@ -4,6 +4,7 @@ import path from 'node:path'
import { z } from 'zod'
import { exiftool } from 'exiftool-vendored'
import { eq } from 'drizzle-orm'
+import { hasValidCoordinates } from '../../../../shared/utils/location'
import { extractExifData } from '~~/server/services/image/exif'
import { tables, useDB } from '~~/server/utils/db'
@@ -19,10 +20,17 @@ const bodySchema = z.object({
tags: z.array(z.string().trim().max(128)).max(64).optional(),
location: z
.union([
- z.object({
- latitude: z.number().min(-90).max(90),
- longitude: z.number().min(-180).max(180),
- }),
+ z
+ .object({
+ latitude: z.number().min(-90).max(90),
+ longitude: z.number().min(-180).max(180),
+ })
+ .refine(
+ ({ latitude, longitude }) => hasValidCoordinates(latitude, longitude),
+ {
+ message: 'Coordinates (0, 0) are a missing-GPS placeholder',
+ },
+ ),
z.null(),
])
.optional(),
diff --git a/server/services/location/geocoding.ts b/server/services/location/geocoding.ts
index 8aa2ed5f..b358f602 100644
--- a/server/services/location/geocoding.ts
+++ b/server/services/location/geocoding.ts
@@ -285,6 +285,7 @@ export function parseGPSCoordinates(exifData: any): {
longitude = -Math.abs(longitude)
}
+ if (!hasValidCoordinates(latitude, longitude)) return {}
return { latitude, longitude }
} catch (error) {
logger.location.error('Failed to parse GPS coordinates:', error)
diff --git a/server/services/pipeline-queue/location-migration.ts b/server/services/pipeline-queue/location-migration.ts
index afdfd090..f26b4b5a 100644
--- a/server/services/pipeline-queue/location-migration.ts
+++ b/server/services/pipeline-queue/location-migration.ts
@@ -32,6 +32,7 @@ export const legacyLocationCondition = and(
isNull(photos.geocoding),
sql`${photos.latitude} BETWEEN -90 AND 90`,
sql`${photos.longitude} BETWEEN -180 AND 180`,
+ sql`NOT (${photos.latitude} = 0 AND ${photos.longitude} = 0)`,
or(
sql`length(trim(coalesce(${photos.city}, ''))) > 0`,
sql`length(trim(coalesce(${photos.country}, ''))) > 0`,
@@ -45,7 +46,23 @@ export function getLocationMigrationStatus(db: ReturnType<typeof useDB>) {
.from(photos)
.where(legacyLocationCondition)
.get()!
- return { count }
+ const active = db
+ .select({ id: pipelineQueue.id })
+ .from(pipelineQueue)
+ .where(
+ and(
+ sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
+ or(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
+ and(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'photo-reverse-geocoding'`,
+ sql`json_extract(${pipelineQueue.payload}, '$.migrationOnly') = 1`,
+ ),
+ ),
+ ),
+ )
+ .get()
+ return { count, requestActive: Boolean(active) }
}
export function enqueueLocationMigration(db: ReturnType<typeof useDB>) {
@@ -86,6 +103,7 @@ export function enqueueLocationMigration(db: ReturnType<typeof useDB>) {
continue
tx.insert(pipelineQueue)
.values({
+ priority: -1,
payload: {
type: 'photo-reverse-geocoding',
photoId: photo.id,
diff --git a/server/services/pipeline-queue/location-update.ts b/server/services/pipeline-queue/location-update.ts
new file mode 100644
index 00000000..86819cd5
--- /dev/null
+++ b/server/services/pipeline-queue/location-update.ts
@@ -0,0 +1,49 @@
+import { and, eq, isNull } from 'drizzle-orm'
+import { photos } from '../../database/schema.ts'
+import type { Photo, useDB } from '../../utils/db.ts'
+import type { LocationInfo } from '../location/geocoding.ts'
+
+type LocationSnapshot = Pick<Photo, 'id' | 'latitude' | 'longitude'>
+
+export function matchesLocationRequest(
+ photo: LocationSnapshot,
+ payload: { latitude?: number | null; longitude?: number | null },
+) {
+ return (
+ (payload.latitude == null || payload.latitude === photo.latitude) &&
+ (payload.longitude == null || payload.longitude === photo.longitude)
+ )
+}
+
+// Compare the values read before the network call, including NULL. Resolved
+// coordinates may come from EXIF and need not already exist in the database.
+export function updateGeocodedPhoto(
+ db: ReturnType<typeof useDB>,
+ photo: LocationSnapshot,
+ location: LocationInfo,
+ migrationOnly: boolean,
+) {
+ return db
+ .update(photos)
+ .set({
+ latitude: location.latitude,
+ longitude: location.longitude,
+ country: location.country ?? null,
+ city: location.city ?? null,
+ locationName: location.locationName ?? null,
+ geocoding: location.geocoding,
+ })
+ .where(
+ and(
+ eq(photos.id, photo.id),
+ photo.latitude == null
+ ? isNull(photos.latitude)
+ : eq(photos.latitude, photo.latitude),
+ photo.longitude == null
+ ? isNull(photos.longitude)
+ : eq(photos.longitude, photo.longitude),
+ migrationOnly ? isNull(photos.geocoding) : undefined,
+ ),
+ )
+ .run().changes
+}
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index 87ed2459..66a5e821 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -2,6 +2,7 @@ import {
enqueueLocationMigration,
enqueueLocationMigrationRequest,
} from './location-migration'
+import { matchesLocationRequest, updateGeocodedPhoto } from './location-update'
import { hasValidCoordinates } from '../../../shared/utils/location'
import type { ConsolaInstance } from 'consola'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
@@ -402,8 +403,8 @@ export class QueueManager {
if (!shouldAutoEraseLocationOnUpload && normalizedExifData) {
const { latitude, longitude } =
parseGPSCoordinates(normalizedExifData)
- coordinates = { latitude, longitude }
if (hasValidCoordinates(latitude, longitude)) {
+ coordinates = { latitude, longitude }
locationInfo = await extractLocationFromGPS(latitude, longitude)
}
}
@@ -578,6 +579,14 @@ export class QueueManager {
)
return
+ // An explicit queued coordinate must still belong to this photo. In
+ // particular, a refresh queued before erasure must not restore it.
+ if (!matchesLocationRequest(photo, payload)) {
+ throw new PermanentTaskError(
+ `Location changed for photo ${photoId}`,
+ )
+ }
+
let latitude = payload.latitude ?? photo.latitude ?? undefined
let longitude = payload.longitude ?? photo.longitude ?? undefined
@@ -621,6 +630,12 @@ export class QueueManager {
)
}
+ if (!hasValidCoordinates(latitude, longitude)) {
+ throw new PermanentTaskError(
+ `Invalid coordinates for photo ${photoId}`,
+ )
+ }
+
const locationInfo = await extractLocationFromGPS(
latitude!,
longitude!,
@@ -632,30 +647,17 @@ export class QueueManager {
)
}
- await db
- .update(tables.photos)
- .set({
- latitude: latitude!,
- longitude: longitude!,
- country: locationInfo.country ?? null,
- city: locationInfo.city ?? null,
- locationName: locationInfo.locationName ?? null,
- geocoding: locationInfo.geocoding,
- })
- .where(
- payload.migrationOnly
- ? and(
- eq(tables.photos.id, photoId),
- sql`${tables.photos.geocoding} IS NULL`,
- eq(tables.photos.latitude, photo.latitude!),
- eq(tables.photos.longitude, photo.longitude!),
- )
- : and(
- eq(tables.photos.id, photoId),
- eq(tables.photos.latitude, latitude!),
- eq(tables.photos.longitude, longitude!),
- ),
+ const changes = updateGeocodedPhoto(
+ db,
+ photo,
+ locationInfo,
+ Boolean(payload.migrationOnly),
+ )
+ if (changes === 0) {
+ throw new PermanentTaskError(
+ `Location changed for photo ${photoId}; result discarded`,
)
+ }
this.logger.success(
`[${taskId}:reverse-geocoding] updated location for photo ${photoId}`,
diff --git a/server/services/pipeline-queue/worker-pool.ts b/server/services/pipeline-queue/worker-pool.ts
index 0b343797..9236ff0b 100644
--- a/server/services/pipeline-queue/worker-pool.ts
+++ b/server/services/pipeline-queue/worker-pool.ts
@@ -1,6 +1,6 @@
import type { ConsolaInstance } from 'consola'
import { consola } from 'consola'
-import { eq } from 'drizzle-orm'
+import { eq, sql } from 'drizzle-orm'
import { useDB, tables } from '~~/server/utils/db'
import { QueueManager } from './manager'
import {
@@ -243,7 +243,7 @@ export class WorkerPool {
}
/**
- * 清理死任务 - 将 in-stages 状态的任务重置为 pending,并设置高优先级
+ * 清理死任务 - 重置为 pending,迁移任务保留后台优先级
*/
private async cleanupDeadTasks(): Promise<void> {
try {
@@ -257,21 +257,24 @@ export class WorkerPool {
if (deadTasks.length > 0) {
this.logger.warn(
- `Found ${deadTasks.length} dead tasks in 'in-stages' status, resetting to pending with priority 1`,
+ `Found ${deadTasks.length} dead tasks in 'in-stages' status, resetting to pending with migration priorities preserved`,
)
- // 将这些任务重置为 pending 状态,设置优先级为 1,清除状态阶段
+ // 重置为 pending,清除状态阶段;迁移任务保持低优先级
await db
.update(tables.pipelineQueue)
.set({
status: 'pending',
- priority: 1,
+ priority: sql`CASE
+ WHEN json_extract(${tables.pipelineQueue.payload}, '$.migrationOnly') = 1
+ AND json_extract(${tables.pipelineQueue.payload}, '$.type') = 'photo-reverse-geocoding'
+ THEN -1 ELSE 1 END`,
statusStage: null,
})
.where(eq(tables.pipelineQueue.status, 'in-stages'))
this.logger.success(
- `Successfully reset ${deadTasks.length} dead tasks to pending status with priority 1`,
+ `Successfully reset ${deadTasks.length} dead tasks to pending status with migration priorities preserved`,
)
} else {
this.logger.info('No dead tasks found in queue')
diff --git a/shared/utils/location.ts b/shared/utils/location.ts
index d8524eff..e2fe3967 100644
--- a/shared/utils/location.ts
+++ b/shared/utils/location.ts
@@ -33,6 +33,8 @@ export function hasValidCoordinates(lat: unknown, lon: unknown): boolean {
Math.abs(lat) <= 90 &&
typeof lon === 'number' &&
Number.isFinite(lon) &&
- Math.abs(lon) <= 180
+ Math.abs(lon) <= 180 &&
+ // Exact (0, 0) is treated as a missing-GPS placeholder.
+ !(lat === 0 && lon === 0)
)
}
diff --git a/tests/location-migration-status.test.ts b/tests/location-migration-status.test.ts
new file mode 100644
index 00000000..0bc67410
--- /dev/null
+++ b/tests/location-migration-status.test.ts
@@ -0,0 +1,74 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { photos, pipelineQueue } from '../server/database/schema.ts'
+
+test('lightweight migration status is admin-only and includes active parent and child tasks', async () => {
+ const sqlite = new Database(':memory:')
+ const db = drizzle(sqlite)
+ migrate(db, { migrationsFolder: 'server/database/migrations' })
+ let dbAccesses = 0
+ const globals = {
+ defineEventHandler: (handler: unknown) => handler,
+ requireUserSession: async (event: { admin: boolean }) => ({
+ user: { isAdmin: event.admin },
+ }),
+ createError: (options: { statusCode: number }) =>
+ Object.assign(new Error(), options),
+ useDB: () => {
+ dbAccesses++
+ return db
+ },
+ }
+ const previous = Object.getOwnPropertyDescriptors(globalThis)
+ Object.assign(globalThis, globals)
+ try {
+ const { default: status } =
+ await import('../server/api/location/migration-status.get.ts')
+ await assert.rejects(status({ admin: false } as never), { statusCode: 403 })
+ assert.equal(dbAccesses, 0)
+ assert.deepEqual(await status({ admin: true } as never), {
+ count: 0,
+ requestActive: false,
+ })
+ db.insert(photos)
+ .values({ id: 'legacy', latitude: 0, longitude: 121, city: 'Old' })
+ .run()
+ db.insert(pipelineQueue)
+ .values({ payload: { type: 'location-migration' } })
+ .run()
+ assert.deepEqual(await status({ admin: true } as never), {
+ count: 1,
+ requestActive: true,
+ })
+ db.update(pipelineQueue).set({ status: 'completed' }).run()
+ db.insert(pipelineQueue)
+ .values({
+ payload: {
+ type: 'photo-reverse-geocoding',
+ photoId: 'legacy',
+ migrationOnly: true,
+ },
+ status: 'in-stages',
+ priority: -1,
+ })
+ .run()
+ assert.deepEqual(await status({ admin: true } as never), {
+ count: 1,
+ requestActive: true,
+ })
+ db.update(pipelineQueue).set({ status: 'failed' }).run()
+ assert.deepEqual(await status({ admin: true } as never), {
+ count: 1,
+ requestActive: false,
+ })
+ } finally {
+ sqlite.close()
+ for (const key of Object.keys(globals)) {
+ if (previous[key]) Object.defineProperty(globalThis, key, previous[key])
+ else Reflect.deleteProperty(globalThis, key)
+ }
+ }
+})
diff --git a/tests/location-migration.test.ts b/tests/location-migration.test.ts
index ce11c2ba..604b5857 100644
--- a/tests/location-migration.test.ts
+++ b/tests/location-migration.test.ts
@@ -37,12 +37,13 @@ test('migration selects only old geocoded photos and deduplicates queue entries'
'legacy',
'/legacy.jpg',
0,
- 0,
+ 121,
'Country',
'Old district',
null,
null,
)
+ insert.run('null-island', '/null.jpg', 0, 0, 'Country', 'Old', null, null)
insert.run('gps-only', '/gps.jpg', 1, 1, null, null, null, null)
insert.run('erased', '/erased.jpg', null, null, null, null, null, null)
insert.run('invalid', '/invalid.jpg', 91, 0, null, 'Old', null, null)
@@ -62,7 +63,10 @@ test('migration selects only old geocoded photos and deduplicates queue entries'
.prepare('INSERT INTO pipeline_queue (payload) VALUES (?)')
.run(JSON.stringify({ type: 'photo-erase-location', photoId: 'busy' }))
try {
- assert.deepEqual(getLocationMigrationStatus(db), { count: 2 })
+ assert.deepEqual(getLocationMigrationStatus(db), {
+ count: 2,
+ requestActive: false,
+ })
assert.deepEqual(enqueueLocationMigration(db), {
count: 2,
queued: 1,
@@ -74,8 +78,15 @@ test('migration selects only old geocoded photos and deduplicates queue entries'
alreadyQueued: 2,
})
const task = sqlite
- .prepare('SELECT payload FROM pipeline_queue ORDER BY id DESC LIMIT 1')
- .get() as { payload: string }
+ .prepare(
+ 'SELECT payload, priority FROM pipeline_queue ORDER BY id DESC LIMIT 1',
+ )
+ .get() as { payload: string; priority: number }
+ assert.equal(task.priority, -1)
+ assert.deepEqual(getLocationMigrationStatus(db), {
+ count: 2,
+ requestActive: true,
+ })
assert.deepEqual(JSON.parse(task.payload), {
type: 'photo-reverse-geocoding',
photoId: 'legacy',
@@ -83,14 +94,20 @@ test('migration selects only old geocoded photos and deduplicates queue entries'
})
// Failed tasks can be retried on the next confirmed visit; checking alone never queues.
sqlite.exec("UPDATE pipeline_queue SET status = 'failed' WHERE id = 2")
- assert.deepEqual(getLocationMigrationStatus(db), { count: 2 })
+ assert.deepEqual(getLocationMigrationStatus(db), {
+ count: 2,
+ requestActive: false,
+ })
assert.deepEqual(enqueueLocationMigration(db), {
count: 2,
queued: 1,
alreadyQueued: 1,
})
sqlite.exec("UPDATE photos SET geocoding = '{}' WHERE id = 'legacy'")
- assert.deepEqual(getLocationMigrationStatus(db), { count: 1 })
+ assert.deepEqual(getLocationMigrationStatus(db), {
+ count: 1,
+ requestActive: true,
+ })
const requestId = enqueueLocationMigrationRequest(db)
assert.equal(enqueueLocationMigrationRequest(db), requestId)
sqlite
diff --git a/tests/location-update.test.ts b/tests/location-update.test.ts
new file mode 100644
index 00000000..2225e30c
--- /dev/null
+++ b/tests/location-update.test.ts
@@ -0,0 +1,77 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'
+import { eq } from 'drizzle-orm'
+import { photos } from '../server/database/schema.ts'
+import {
+ matchesLocationRequest,
+ updateGeocodedPhoto,
+} from '../server/services/pipeline-queue/location-update.ts'
+import type { LocationInfo } from '../server/services/location/geocoding.ts'
+import { photosToMarkers } from '../app/utils/clustering.ts'
+
+const location: LocationInfo = {
+ latitude: 31,
+ longitude: 121,
+ city: 'City',
+ geocoding: {
+ version: 1,
+ provider: 'nominatim',
+ language: 'en',
+ components: {},
+ },
+}
+
+test('EXIF recovery writes NULL coordinates; concurrent changes discard the result', () => {
+ const sqlite = new Database(':memory:')
+ const db = drizzle(sqlite)
+ migrate(db, { migrationsFolder: 'server/database/migrations' })
+ const typedDB = db as Parameters<typeof updateGeocodedPhoto>[0]
+ try {
+ db.insert(photos).values({ id: 'p' }).run()
+ const snapshot = db.select().from(photos).get()!
+ assert.equal(matchesLocationRequest(snapshot, {}), true)
+ assert.equal(
+ matchesLocationRequest(snapshot, { latitude: 31, longitude: 121 }),
+ false,
+ 'a stale explicit payload must not restore erased coordinates',
+ )
+ assert.equal(updateGeocodedPhoto(typedDB, snapshot, location, false), 1)
+ const located = db.select().from(photos).get()!
+ assert.equal(located.latitude, 31)
+ assert.equal(
+ matchesLocationRequest(located, { latitude: 31, longitude: 121 }),
+ true,
+ )
+ assert.equal(matchesLocationRequest(located, { latitude: 32 }), false)
+ // Erasure while the provider request is in flight invalidates the snapshot.
+ db.update(photos)
+ .set({ latitude: null, longitude: null, geocoding: null })
+ .run()
+ assert.equal(updateGeocodedPhoto(typedDB, located, location, false), 0)
+ assert.equal(db.select().from(photos).get()!.geocoding, null)
+ db.update(photos).set({ latitude: 32, longitude: 121 }).run()
+ assert.equal(updateGeocodedPhoto(typedDB, located, location, false), 0)
+ // Migration must not overwrite a result another worker has already filled.
+ db.update(photos).set({ latitude: 31, geocoding: location.geocoding }).run()
+ assert.equal(updateGeocodedPhoto(typedDB, located, location, true), 0)
+ db.delete(photos).where(eq(photos.id, 'p')).run()
+ assert.equal(updateGeocodedPhoto(typedDB, located, location, false), 0)
+ } finally {
+ sqlite.close()
+ }
+})
+
+test('map markers exclude existing Null Island placeholders but preserve either zero axis', () => {
+ const input = [
+ { id: 'placeholder', latitude: 0, longitude: 0 },
+ { id: 'equator', latitude: 0, longitude: 121 },
+ { id: 'meridian', latitude: 31, longitude: 0 },
+ ] as Parameters<typeof photosToMarkers>[0]
+ assert.deepEqual(
+ photosToMarkers(input).map((p) => p.id),
+ ['equator', 'meridian'],
+ )
+})
diff --git a/tests/location.test.ts b/tests/location.test.ts
index 0ee7e1b8..22e6b5b2 100644
--- a/tests/location.test.ts
+++ b/tests/location.test.ts
@@ -124,8 +124,12 @@ test('county, settlements, and neighborhood aliases preserve distinct roles', ()
assert.equal(normalizeNominatim({ address: {} }, 'en'), null)
})
-test('coordinates include the equator and prime meridian but reject nonfinite values', () => {
- assert.equal(hasValidCoordinates(0, 0), true)
+test('coordinates preserve either zero axis but reject Null Island and invalid values', () => {
+ assert.equal(hasValidCoordinates(0, 0), false)
+ assert.equal(hasValidCoordinates(-0, 0), false)
+ assert.equal(hasValidCoordinates(0, 121), true)
+ assert.equal(hasValidCoordinates(31, 0), true)
+ assert.equal(hasValidCoordinates(0, 0.000001), true)
assert.equal(hasValidCoordinates(-90, 180), true)
for (const [lat, lon] of [
[NaN, 1],