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.

feat(location): normalize geocoding and configure display preferences

Timothy Yin8cfa7c6eaabb
diff --git a/app/components/OgImage/Photo.takumi.vue b/app/components/OgImage/Photo.takumi.vue
index 2debc4bc..0e26ce16 100644
--- a/app/components/OgImage/Photo.takumi.vue
+++ b/app/components/OgImage/Photo.takumi.vue
@@ -13,6 +13,7 @@ interface PhotoProps {
const { photo, appTitle: appTitleProp } = defineProps<PhotoProps>()
const { $i18n } = useNuxtApp()
+const locationLabel = useLocationLabel()
const resolvedAppTitle = computed(() => {
if (typeof appTitleProp === 'string' && appTitleProp.length > 0) {
@@ -77,7 +78,7 @@ const thumbnailUrl = computed(() =>
class="flex flex-row items-center gap-3 text-neutral-300 text-3xl font-bold mt-6"
>
<div
- v-if="photo.city"
+ v-if="locationLabel(photo)"
class="flex flex-row items-center gap-1"
>
<span
@@ -93,7 +94,7 @@ const thumbnailUrl = computed(() =>
/>
</span>
<span class="truncate">
- {{ photo.city }}
+ {{ locationLabel(photo) }}
</span>
</div>
<div
diff --git a/app/components/dashboard/LocationMigration.vue b/app/components/dashboard/LocationMigration.vue
new file mode 100644
index 00000000..9b834caf
--- /dev/null
+++ b/app/components/dashboard/LocationMigration.vue
@@ -0,0 +1,89 @@
+<script setup lang="ts">
+const { user } = useUserSession()
+const router = useRouter()
+const migrationOpen = ref(false)
+const migrationCount = ref(0)
+const migrationLoading = ref(false)
+const migrationError = ref(false)
+const toast = useToast()
+
+async function checkLocationMigration() {
+ if (!user.value?.isAdmin) return
+ try {
+ const stats = await $fetch('/api/system/stats')
+ migrationCount.value = stats.locationMigration.count
+ migrationOpen.value = migrationCount.value > 0
+ } catch (error) {
+ console.error('Failed to check location migration', error)
+ }
+}
+
+let removeNavigationHook: (() => void) | undefined
+onMounted(() => {
+ void checkLocationMigration()
+ removeNavigationHook = router.afterEach(() => {
+ void checkLocationMigration()
+ })
+})
+onUnmounted(() => removeNavigationHook?.())
+
+async function confirmLocationMigration() {
+ migrationLoading.value = true
+ migrationError.value = false
+ try {
+ await $fetch('/api/queue/add-task', {
+ method: 'POST',
+ body: { payload: { type: 'location-migration' } },
+ })
+ toast.add({
+ title: $t('dashboard.locationMigration.queued'),
+ color: 'success',
+ })
+ migrationOpen.value = false
+ } catch {
+ migrationError.value = true
+ } finally {
+ migrationLoading.value = false
+ }
+}
+</script>
+
+<template>
+ <UModal
+ v-model:open="migrationOpen"
+ :dismissible="!migrationLoading"
+ :title="$t('dashboard.locationMigration.title')"
+ >
+ <template #body>
+ <p>
+ {{
+ $t('dashboard.locationMigration.description', {
+ count: migrationCount,
+ })
+ }}
+ </p>
+ <p
+ v-if="migrationError"
+ class="text-error mt-3"
+ >
+ {{ $t('dashboard.locationMigration.error') }}
+ </p>
+ </template>
+ <template #footer>
+ <div class="flex items-center justify-end gap-2 w-full">
+ <UButton
+ color="neutral"
+ variant="ghost"
+ :disabled="migrationLoading"
+ @click="migrationOpen = false"
+ >{{ $t('dashboard.locationMigration.cancel') }}</UButton
+ >
+ <UButton
+ :loading="migrationLoading"
+ @click="confirmLocationMigration"
+ >{{ $t('dashboard.locationMigration.confirm') }}</UButton
+ >
+ </div>
+ </template>
+ </UModal>
+</template>
diff --git a/app/components/map/ClusterPin.vue b/app/components/map/ClusterPin.vue
index bb39acb3..fab9f4b5 100644
--- a/app/components/map/ClusterPin.vue
+++ b/app/components/map/ClusterPin.vue
@@ -22,6 +22,7 @@ const emit = defineEmits<{
}>()
const dayjs = useDayjs()
+const locationLabel = useLocationLabel()
const onClick = () => {
emit('click', props.clusterPoint)
@@ -217,7 +218,7 @@ const sizeDelta = computed(() => {
<div
v-if="
clusteredPhotos.length &&
- clusteredPhotos.some((p) => p.city)
+ clusteredPhotos.some((p) => locationLabel(p))
"
class="flex items-center gap-1 text-xs text-neutral-600 dark:text-muted font-medium mt-2"
>
@@ -228,7 +229,7 @@ const sizeDelta = computed(() => {
<span class="truncate">
{{
clusteredPhotos
- .map((p) => p.city)
+ .map((p) => locationLabel(p))
.filter((v, i, a) => v && a.indexOf(v) === i)
.join(', ')
}}
diff --git a/app/components/map/PhotoPin.vue b/app/components/map/PhotoPin.vue
index 98e5952e..1616999e 100644
--- a/app/components/map/PhotoPin.vue
+++ b/app/components/map/PhotoPin.vue
@@ -24,6 +24,7 @@ const emit = defineEmits<{
}>()
const dayjs = useDayjs()
+const locationLabel = useLocationLabel()
const marker = computed(() => props.clusterPoint.properties.marker!)
const hoverOpen = ref(false)
@@ -414,15 +415,15 @@ const onClick = () => {
<!-- Metadata -->
<div class="space-y-1">
<div
- v-if="marker.city || marker.exif?.DateTimeOriginal"
+ v-if="locationLabel(marker) || marker.exif?.DateTimeOriginal"
class="flex items-center gap-1 text-xs text-neutral-600 dark:text-muted font-medium mb-2"
>
- <div v-if="marker.city">
+ <div v-if="locationLabel(marker)">
<span class="truncate">
- {{ marker.city }}
+ {{ locationLabel(marker) }}
</span>
</div>
- <span v-if="marker.city">·</span>
+ <span v-if="locationLabel(marker)">·</span>
<div v-if="marker.exif?.DateTimeOriginal">
<span class="truncate">
{{ dayjs(marker.exif.DateTimeOriginal).format('ll') }}
diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vue
index 20527bde..2b8115ec 100644
--- a/app/components/masonry/Root.vue
+++ b/app/components/masonry/Root.vue
@@ -12,6 +12,7 @@ const props = withDefaults(defineProps<Props>(), {
const dayjs = useDayjs()
const router = useRouter()
const route = useRoute()
+const locationLabel = useLocationLabel()
const { filteredPhotos, hasActiveFilters } = usePhotoFilters()
const { sortedPhotos } = usePhotoSort()
@@ -252,7 +253,11 @@ const updateDateRange = () => {
// Calculate visible cities
const cities = visiblePhotosArray
- .map((index) => displayPhotos.value[index]?.city)
+ .map((index) =>
+ displayPhotos.value[index]
+ ? locationLabel(displayPhotos.value[index]!)
+ : undefined,
+ )
.filter((city): city is string => Boolean(city))
const uniqueCities = [...new Set(cities)]
diff --git a/app/components/masonry/item/Photo.vue b/app/components/masonry/item/Photo.vue
index 72d9a1ce..224cf95c 100644
--- a/app/components/masonry/item/Photo.vue
+++ b/app/components/masonry/item/Photo.vue
@@ -16,6 +16,7 @@ const emit = defineEmits<{
}>()
const { gtag } = useGtag()
+const locationLabel = useLocationLabel()
const isLoading = ref(true)
const photoRef = ref<HTMLElement>()
@@ -589,14 +590,15 @@ onUnmounted(() => {
{{ photo.description }}
</p>
<p
- v-if="photo.dateTaken || photo.city"
+ v-if="photo.dateTaken || locationLabel(photo)"
class="text-xs font-medium opacity-80"
>
<span v-if="photo.dateTaken">
{{ $dayjs(photo.dateTaken).format('YYYY-MM-DD') }}
</span>
- <span v-if="photo.city">
- <span v-if="photo.dateTaken"> · </span>{{ photo.city }}
+ <span v-if="locationLabel(photo)">
+ <span v-if="photo.dateTaken"> · </span
+ >{{ locationLabel(photo) }}
</span>
</p>
</div>
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vue
index 03287632..8f609821 100644
--- a/app/components/photo/InfoPanel.vue
+++ b/app/components/photo/InfoPanel.vue
@@ -100,7 +100,10 @@ const formatGPSCoordinatesMultiLine = (
const gpsCoordinates = computed(() => {
// 优先使用数据库中存储的坐标
- if (props.currentPhoto.latitude && props.currentPhoto.longitude) {
+ if (
+ props.currentPhoto.latitude != null &&
+ props.currentPhoto.longitude != null
+ ) {
return {
latitude: props.currentPhoto.latitude,
longitude: props.currentPhoto.longitude,
@@ -207,7 +210,28 @@ const formatedExifData = computed<Record<string, KVData[]>>(() => {
icon: 'tabler:building',
}
: null,
- props.currentPhoto.latitude && props.currentPhoto.longitude
+ ...(
+ [
+ 'region',
+ 'subregion',
+ 'district',
+ 'locality',
+ 'neighborhood',
+ ] as const
+ ).flatMap((level) => {
+ const component = props.currentPhoto.geocoding?.components[level]
+ return component
+ ? [
+ {
+ label: $t('settings.location.levels.' + level),
+ value: component.name,
+ icon: 'tabler:map-pin',
+ },
+ ]
+ : []
+ }),
+ props.currentPhoto.latitude != null &&
+ props.currentPhoto.longitude != null
? {
label: $t('exif.gps.title'),
value: formatGPSCoordinatesMultiLine(
diff --git a/app/components/setting/SettingField.vue b/app/components/setting/SettingField.vue
index 33f40015..b3be1bb2 100644
--- a/app/components/setting/SettingField.vue
+++ b/app/components/setting/SettingField.vue
@@ -85,7 +85,12 @@ const getComponentProps = (): Record<string, any> => {
break
case 'select':
propsMap.items = props.field.ui.options
- ? Array.from(props.field.ui.options)
+ ? Array.from(props.field.ui.options).map((option) => ({
+ ...option,
+ label: option.label.startsWith('settings.location.levels.')
+ ? $t(option.label)
+ : option.label,
+ }))
: []
propsMap['label-key'] = 'label'
propsMap['value-key'] = 'value'
diff --git a/app/composables/useLocationLabel.ts b/app/composables/useLocationLabel.ts
new file mode 100644
index 00000000..40a74ba4
--- /dev/null
+++ b/app/composables/useLocationLabel.ts
@@ -0,0 +1,21 @@
+import {
+ resolveLocationLabel,
+ defaultLocationFallback,
+} from '~~/shared/utils/location'
+import type { NormalizedLocation } from '~~/shared/types/location'
+
+export function useLocationLabel() {
+ const settings = useSettingsStore()
+ return (photo: {
+ geocoding?: NormalizedLocation | null
+ city?: string | null
+ }) =>
+ resolveLocationLabel(
+ photo,
+ String(settings.getSetting('location:preferredLevel') || 'city'),
+ String(
+ settings.getSetting('location:fallbackOrder') ||
+ defaultLocationFallback,
+ ),
+ ).label
+}
diff --git a/app/composables/usePhotoFilters.ts b/app/composables/usePhotoFilters.ts
index d0e1c82f..4b1f9a26 100644
--- a/app/composables/usePhotoFilters.ts
+++ b/app/composables/usePhotoFilters.ts
@@ -136,6 +136,9 @@ export function usePhotoFilters() {
photo.description || '',
photo.storageKey || '',
photo.locationName || '',
+ ...Object.values(photo.geocoding?.components || {}).map(
+ (component) => component.name,
+ ),
]
.join(' ')
.toLowerCase()
diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vue
index cb851087..9828a305 100644
--- a/app/layouts/dashboard.vue
+++ b/app/layouts/dashboard.vue
@@ -259,6 +259,8 @@ const handleLogin = () => {
</template>
</UDashboardSidebar>
+
+ <DashboardLocationMigration />
<NuxtPage />
</UDashboardGroup>
</template>
diff --git a/app/pages/dashboard/albums.vue b/app/pages/dashboard/albums.vue
index 44026601..6906190d 100644
--- a/app/pages/dashboard/albums.vue
+++ b/app/pages/dashboard/albums.vue
@@ -30,6 +30,8 @@ interface AlbumFormState {
passwordEnabled: boolean
}
+const locationLabel = useLocationLabel()
+
const { data: currentStorageProvider } = await useFetch<{
namespace: string
key: string
@@ -1270,8 +1272,8 @@ const columns = computed<any[]>(() => [
</p>
<p class="truncate text-[9px] text-white/72">
{{
- photo.city
- ? `${photo.city} · ${dayjs(photo.createdAt).format('MM-DD')}`
+ locationLabel(photo)
+ ? `${locationLabel(photo)} · ${dayjs(photo.createdAt).format('MM-DD')}`
: dayjs(photo.createdAt).format('YYYY-MM-DD')
}}
</p>
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index 0ea08b44..e9400c9b 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -53,6 +53,7 @@ const systemUploadEraseLocationDefault = computed(() => {
})
const dayjs = useDayjs()
+const locationLabel = useLocationLabel()
const { status, refresh } = usePhotos()
const { filteredPhotos, selectedCounts, hasActiveFilters } = usePhotoFilters()
@@ -1008,7 +1009,7 @@ const columns = computed<TableColumn<Photo>[]>(() => [
accessorKey: 'location',
header: $t('dashboard.photos.table.columns.location'),
cell: ({ row }) => {
- const { exif, city, country } = row.original
+ const { exif, country } = row.original
if (!exif?.GPSLongitude && !exif?.GPSLatitude) {
return h(
@@ -1018,7 +1019,7 @@ const columns = computed<TableColumn<Photo>[]>(() => [
)
}
- const location = [city, country].filter(Boolean).join(', ')
+ const location = [locationLabel(row.original), country].filter(Boolean).join(', ')
return h(
'span',
{
diff --git a/app/pages/dashboard/queue.vue b/app/pages/dashboard/queue.vue
index 07e4a7f7..69326d68 100644
--- a/app/pages/dashboard/queue.vue
+++ b/app/pages/dashboard/queue.vue
@@ -194,6 +194,7 @@ const statusOptions = computed(() => [
// 类型选项
const typeOptions = computed(() => [
{ label: $t('dashboard.queue.filters.all'), value: 'all' },
+ { label: $t('dashboard.queue.types.location-migration'), value: 'location-migration' },
{ label: $t('dashboard.queue.types.photo'), value: 'photo' },
{
label: $t('dashboard.queue.types.live-photo-video'),
diff --git a/app/pages/globe.vue b/app/pages/globe.vue
index a7c6cbe9..34c4e8bc 100644
--- a/app/pages/globe.vue
+++ b/app/pages/globe.vue
@@ -467,7 +467,7 @@ const onMapLoaded = (map: any) => {
const { photoId } = route.query
if (photoId && typeof photoId === 'string') {
const photo = photosWithLocation.value.find((photo) => photo.id === photoId)
- if (photo && photo.latitude && photo.longitude) {
+ if (photo && photo.latitude != null && photo.longitude != null) {
setTimeout(() => {
map.flyTo({
center: [photo.longitude, photo.latitude],
diff --git a/app/utils/clustering.ts b/app/utils/clustering.ts
index 866b0b6a..63ab1c9a 100644
--- a/app/utils/clustering.ts
+++ b/app/utils/clustering.ts
@@ -105,6 +105,7 @@ export function photosToMarkers(photos: Photo[]): PhotoMarker[] {
thumbnailHash: photo.thumbnailHash || undefined,
dateTaken: photo.dateTaken || undefined,
city: photo.city || undefined,
+ geocoding: photo.geocoding,
exif: photo.exif || undefined,
}))
}
diff --git a/docs/configuration/location-providers.md b/docs/configuration/location-providers.md
deleted file mode 100644
index c339f21b..00000000
--- a/docs/configuration/location-providers.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Location Services
-
-Location services and maps are managed on the same dashboard page. Read [Maps and locations](/configuration/map-providers#place-name-lookup) for place-name language, Mapbox reverse geocoding and Nominatim settings.
diff --git a/docs/zh/configuration/location-providers.md b/docs/zh/configuration/location-providers.md
deleted file mode 100644
index 468bef5b..00000000
--- a/docs/zh/configuration/location-providers.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# 位置服务
-
-位置服务与地图配置在同一个后台页面管理。请查看[地图和位置](/zh/configuration/map-providers#地点识别),了解地名语言、Mapbox 反向地理编码和 Nominatim 的设置。
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 0c61ff71..3913d43f 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -1109,7 +1109,8 @@
"photo": "Photo Processing",
"live-photo-video": "LivePhoto Video",
"photo-reverse-geocoding": "Photo Reverse Geocoding",
- "photo-erase-location": "Photo Location Erasure"
+ "photo-erase-location": "Photo Location Erasure",
+ "location-migration": "Location format migration"
},
"stages": {
"preprocessing": "Preprocessing",
@@ -1179,6 +1180,14 @@
"nav": {
"documentation": "Documentation",
"viewGallery": "View Gallery"
+ },
+ "locationMigration": {
+ "title": "Update stored location information",
+ "description": "The storage format for photo locations has changed. Administrative area details need to be fetched again for {count} photos. Migrate now? You can track progress in Queue Management after confirming.",
+ "confirm": "Confirm migration",
+ "cancel": "Cancel",
+ "error": "Could not queue migration. Please try again.",
+ "queued": "Migration task queued. Track its progress in the task queue."
}
},
"settings": {
@@ -1337,6 +1346,24 @@
"description": "Base URL for Nominatim reverse geocoding API",
"help": "Leave empty to use the public Nominatim service by default"
}
+ },
+ "levels": {
+ "country": "Country / territory",
+ "region": "Province / state",
+ "subregion": "Intermediate administrative area",
+ "city": "City / settlement",
+ "district": "City district",
+ "locality": "Local area",
+ "neighborhood": "Neighborhood"
+ },
+ "preferredLevel": {
+ "label": "Preferred location level",
+ "description": "Choose the location shown on photos and maps. City filters continue to use cities."
+ },
+ "fallbackOrder": {
+ "label": "Location fallback order",
+ "description": "If the preferred level is missing, try these fields in order.",
+ "help": "Comma-separated fields: city, subregion, region, country, district, locality, neighborhood. Example: city,subregion,region,country"
}
},
"privacy": {
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index 65f7bdb6..6c75624c 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -1034,7 +1034,8 @@
"photo": "写真処理",
"live-photo-video": "LivePhoto動画",
"photo-reverse-geocoding": "写真の逆ジオコーディング",
- "photo-erase-location": "写真位置情報の抹消"
+ "photo-erase-location": "写真位置情報の抹消",
+ "location-migration": "位置情報の形式移行"
},
"stages": {
"preprocessing": "前処理",
@@ -1104,6 +1105,14 @@
"nav": {
"documentation": "ドキュメント",
"viewGallery": "ギャラリーを表示"
+ },
+ "locationMigration": {
+ "title": "位置情報の更新",
+ "description": "写真の位置情報の保存形式が更新されました。{count} 枚の写真の行政区画情報を再取得する必要があります。今すぐ移行しますか?確認後、「キュー管理」で進捗を確認できます。",
+ "confirm": "移行する",
+ "cancel": "キャンセル",
+ "error": "移行タスクをキューに追加できませんでした。もう一度お試しください。",
+ "queued": "移行タスクをキューに追加しました。「キュー管理」で進捗を確認できます。"
}
},
"settings": {
@@ -1262,6 +1271,24 @@
"description": "Nominatim リバースジオコーディング API のベース URL",
"help": "空のままにすると、デフォルトで公開 Nominatim サービスを使用します"
}
+ },
+ "levels": {
+ "country": "国 / 地域",
+ "region": "都道府県 / 州",
+ "subregion": "中間行政区画",
+ "city": "市町村 / 集落",
+ "district": "市内の行政区",
+ "locality": "地区 / 郊外",
+ "neighborhood": "近隣地区"
+ },
+ "preferredLevel": {
+ "label": "優先する位置情報の階層",
+ "description": "写真と地図に表示する位置情報の階層を選択します。都市フィルターは引き続き都市単位で集計します。"
+ },
+ "fallbackOrder": {
+ "label": "位置情報の代替順序",
+ "description": "優先する階層がない場合、この順序で利用可能な項目を選択します。",
+ "help": "項目名を半角カンマで区切ります:city、subregion、region、country、district、locality、neighborhood。例:city,subregion,region,country"
}
},
"privacy": {
diff --git a/i18n/locales/ru.json b/i18n/locales/ru.json
index e70cf384..c2a102d8 100644
--- a/i18n/locales/ru.json
+++ b/i18n/locales/ru.json
@@ -1109,7 +1109,8 @@
"photo": "Обработка фотографии",
"live-photo-video": "Обработка видео Live Photo",
"photo-reverse-geocoding": "Обратное геокодирование фотографии",
- "photo-erase-location": "Удаление геоданных фотографии"
+ "photo-erase-location": "Удаление геоданных фотографии",
+ "location-migration": "Миграция формата местоположения"
},
"stages": {
"preprocessing": "Предварительная обработка",
@@ -1179,6 +1180,14 @@
"nav": {
"documentation": "Документация",
"viewGallery": "Открыть галерею"
+ },
+ "locationMigration": {
+ "title": "Обновление данных о местоположении",
+ "description": "Формат хранения местоположений фотографий изменён. Для {count} фотографий нужно повторно получить сведения об административных районах. Выполнить миграцию сейчас? После подтверждения ход выполнения можно отслеживать в разделе управления очередью.",
+ "confirm": "Начать миграцию",
+ "cancel": "Отмена",
+ "error": "Не удалось добавить задачу миграции в очередь. Попробуйте ещё раз.",
+ "queued": "Задача миграции добавлена в очередь. Ход выполнения доступен в разделе управления очередью."
}
},
"settings": {
@@ -1337,6 +1346,24 @@
"description": "Базовый URL API обратного геокодирования Nominatim",
"help": "Оставьте поле пустым, чтобы использовать общедоступный сервис Nominatim"
}
+ },
+ "levels": {
+ "country": "Страна / территория",
+ "region": "Область / штат",
+ "subregion": "Промежуточная административная единица",
+ "city": "Город / населённый пункт",
+ "district": "Городской район",
+ "locality": "Местность / пригород",
+ "neighborhood": "Микрорайон / квартал"
+ },
+ "preferredLevel": {
+ "label": "Предпочтительный уровень местоположения",
+ "description": "Выберите уровень местоположения для фотографий и карты. Фильтр по городам продолжает использовать города."
+ },
+ "fallbackOrder": {
+ "label": "Порядок замены полей местоположения",
+ "description": "Если предпочтительный уровень отсутствует, доступные поля проверяются в этом порядке.",
+ "help": "Укажите поля через запятую: city, subregion, region, country, district, locality, neighborhood. Пример: city,subregion,region,country"
}
},
"privacy": {
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index e968cf5f..3fd2cef4 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -1109,7 +1109,8 @@
"photo": "照片处理",
"live-photo-video": "LivePhoto视频",
"photo-reverse-geocoding": "照片逆地理编码",
- "photo-erase-location": "照片位置信息抹除"
+ "photo-erase-location": "照片位置信息抹除",
+ "location-migration": "位置区划格式迁移"
},
"stages": {
"preprocessing": "预处理",
@@ -1179,6 +1180,14 @@
"nav": {
"documentation": "文档",
"viewGallery": "查看画廊"
+ },
+ "locationMigration": {
+ "title": "更新地理位置信息",
+ "description": "照片位置信息存储格式已更新,{count} 张照片需要重新获取区划信息。是否现在迁移?确认后可在“队列管理”中查看进度",
+ "confirm": "确认迁移",
+ "cancel": "取消",
+ "error": "迁移任务入队失败,请重试。",
+ "queued": "迁移任务已加入队列,可在任务队列中查看处理进度。"
}
},
"settings": {
@@ -1337,6 +1346,24 @@
"description": "Nominatim 反向地理编码 API 的基础 URL",
"help": "留空则默认使用公共 Nominatim 服务"
}
+ },
+ "levels": {
+ "country": "国家 / 地区",
+ "region": "省 / 州",
+ "subregion": "中间行政区划",
+ "city": "城市 / 居民点",
+ "district": "城市区县",
+ "locality": "地方 / 郊区",
+ "neighborhood": "社区 / 街区"
+ },
+ "preferredLevel": {
+ "label": "首选位置层级",
+ "description": "选择照片和地图显示的位置层级,城市筛选仍按城市统计。"
+ },
+ "fallbackOrder": {
+ "label": "位置字段回退顺序",
+ "description": "首选层级缺失时,按此顺序选择可用字段。",
+ "help": "使用英文逗号分隔:city(城市)、subregion(中间区划)、region(省州)、country(国家地区)、district(区县)、locality(地方)、neighborhood(社区)。示例:city,subregion,region,country"
}
},
"privacy": {
diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.json
index f47f4588..0cbe3b9f 100644
--- a/i18n/locales/zh-Hant-HK.json
+++ b/i18n/locales/zh-Hant-HK.json
@@ -1034,7 +1034,8 @@
"photo": "照片處理",
"live-photo-video": "LivePhoto視頻",
"photo-reverse-geocoding": "照片逆地理編碼",
- "photo-erase-location": "照片位置資訊抹除"
+ "photo-erase-location": "照片位置資訊抹除",
+ "location-migration": "位置區劃格式遷移"
},
"stages": {
"preprocessing": "預處理",
@@ -1104,6 +1105,14 @@
"nav": {
"documentation": "文件",
"viewGallery": "查看畫廊"
+ },
+ "locationMigration": {
+ "title": "更新地理位置資訊",
+ "description": "相片位置資訊儲存格式已更新,{count} 張相片需要重新取得區劃資訊。是否現在遷移?確認後可在「佇列管理」中查看進度",
+ "confirm": "確認遷移",
+ "cancel": "取消",
+ "error": "遷移任務加入佇列失敗,請重試。",
+ "queued": "遷移任務已加入佇列,可在任務佇列中查看處理進度。"
}
},
"settings": {
@@ -1262,6 +1271,24 @@
"description": "Nominatim 反向地理編碼 API 嘅基礎 URL",
"help": "留空則預設使用公開 Nominatim 服務"
}
+ },
+ "levels": {
+ "country": "國家 / 地區",
+ "region": "省 / 州",
+ "subregion": "中間行政區劃",
+ "city": "城市 / 居民點",
+ "district": "城市區縣",
+ "locality": "地方 / 郊區",
+ "neighborhood": "社區 / 街區"
+ },
+ "preferredLevel": {
+ "label": "首選位置層級",
+ "description": "選擇照片和地圖顯示的位置層級,城市篩選仍按城市統計。"
+ },
+ "fallbackOrder": {
+ "label": "位置欄位回退順序",
+ "description": "首選層級缺失時,按此順序選擇可用欄位。",
+ "help": "使用英文逗號分隔:city、subregion、region、country、district、locality、neighborhood。範例:city,subregion,region,country"
}
},
"privacy": {
diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.json
index 1d9adb56..e33d5d7c 100644
--- a/i18n/locales/zh-Hant-TW.json
+++ b/i18n/locales/zh-Hant-TW.json
@@ -1034,7 +1034,8 @@
"photo": "照片處理",
"live-photo-video": "LivePhoto影片",
"photo-reverse-geocoding": "照片逆地理編碼",
- "photo-erase-location": "照片位置資訊抹除"
+ "photo-erase-location": "照片位置資訊抹除",
+ "location-migration": "位置區劃格式遷移"
},
"stages": {
"preprocessing": "預處理",
@@ -1104,6 +1105,14 @@
"nav": {
"documentation": "文件",
"viewGallery": "檢視畫廊"
+ },
+ "locationMigration": {
+ "title": "更新地理位置資訊",
+ "description": "相片位置資訊儲存格式已更新,{count} 張相片需要重新取得區劃資訊。是否現在遷移?確認後可在「佇列管理」中查看進度",
+ "confirm": "確認遷移",
+ "cancel": "取消",
+ "error": "遷移任務加入佇列失敗,請重試。",
+ "queued": "遷移任務已加入佇列,可在任務佇列中查看處理進度。"
}
},
"settings": {
@@ -1262,6 +1271,24 @@
"description": "Nominatim 反向地理編碼 API 的基礎 URL",
"help": "留空則預設使用公開 Nominatim 服務"
}
+ },
+ "levels": {
+ "country": "國家 / 地區",
+ "region": "省 / 州",
+ "subregion": "中間行政區劃",
+ "city": "城市 / 居民點",
+ "district": "城市區縣",
+ "locality": "地方 / 郊區",
+ "neighborhood": "社區 / 街區"
+ },
+ "preferredLevel": {
+ "label": "首選位置層級",
+ "description": "選擇照片和地圖顯示的位置層級,城市篩選仍按城市統計。"
+ },
+ "fallbackOrder": {
+ "label": "位置欄位回退順序",
+ "description": "首選層級缺失時,按此順序選擇可用欄位。",
+ "help": "使用英文逗號分隔:city、subregion、region、country、district、locality、neighborhood。範例:city,subregion,region,country"
}
},
"privacy": {
diff --git a/server/api/photos/[photoId]/index.put.ts b/server/api/photos/[photoId]/index.put.ts
index 9d35783a..a27494c4 100644
--- a/server/api/photos/[photoId]/index.put.ts
+++ b/server/api/photos/[photoId]/index.put.ts
@@ -204,6 +204,7 @@ export default eventHandler(async (event) => {
updateData.country = null
updateData.city = null
updateData.locationName = null
+ updateData.geocoding = null
pendingReverseGeocode = {
latitude: payload.location.latitude,
longitude: payload.location.longitude,
@@ -214,6 +215,7 @@ export default eventHandler(async (event) => {
updateData.country = null
updateData.city = null
updateData.locationName = null
+ updateData.geocoding = null
}
}
diff --git a/server/api/queue/add-task.post.ts b/server/api/queue/add-task.post.ts
index cc19faeb..2bb6b6fb 100644
--- a/server/api/queue/add-task.post.ts
+++ b/server/api/queue/add-task.post.ts
@@ -2,10 +2,10 @@ import { z } from 'zod'
import {
photoTaskAlbumExists,
queuePayloadSchema,
-} from '../../utils/queue-payload'
+} from '../../utils/queue-payload.ts'
export default defineEventHandler(async (event) => {
- await requireUserSession(event)
+ const session = await requireUserSession(event)
try {
const { payload, priority, maxAttempts } = await readValidatedBody(
@@ -20,6 +20,11 @@ export default defineEventHandler(async (event) => {
if (!photoTaskAlbumExists(payload)) {
throw createError({ statusCode: 404, statusMessage: 'Album not found' })
}
+ if (payload.type === 'location-migration' && !session.user.isAdmin)
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
const workerPool = globalThis.__workerPool
diff --git a/server/api/queue/add-tasks.post.ts b/server/api/queue/add-tasks.post.ts
index 2ee91b16..a2f213dc 100644
--- a/server/api/queue/add-tasks.post.ts
+++ b/server/api/queue/add-tasks.post.ts
@@ -2,10 +2,10 @@ import { z } from 'zod'
import {
createPhotoTaskAlbumChecker,
queuePayloadSchema,
-} from '../../utils/queue-payload'
+} from '../../utils/queue-payload.ts'
export default defineEventHandler(async (event) => {
- await requireUserSession(event)
+ const session = await requireUserSession(event)
try {
const { tasks, defaultPriority, defaultMaxAttempts } =
@@ -27,6 +27,15 @@ export default defineEventHandler(async (event) => {
}).parse,
)
+ if (
+ tasks.some((task) => task.payload.type === 'location-migration') &&
+ !session.user.isAdmin
+ )
+ throw createError({
+ statusCode: 403,
+ statusMessage: 'Admin privileges required',
+ })
+
const workerPool = globalThis.__workerPool
if (!workerPool) {
diff --git a/server/api/queue/task/list.get.ts b/server/api/queue/task/list.get.ts
index d04f3825..8293cde7 100644
--- a/server/api/queue/task/list.get.ts
+++ b/server/api/queue/task/list.get.ts
@@ -16,6 +16,7 @@ export default defineEventHandler(async (event) => {
.optional(),
type: z
.enum([
+ 'location-migration',
'photo',
'live-photo-video',
'photo-reverse-geocoding',
diff --git a/server/api/queue/task/retry-batch.post.ts b/server/api/queue/task/retry-batch.post.ts
index e45b61f5..bc52f065 100644
--- a/server/api/queue/task/retry-batch.post.ts
+++ b/server/api/queue/task/retry-batch.post.ts
@@ -76,7 +76,9 @@ export default defineEventHandler(async (event) => {
retriedTasks: failedTasks.map((task) => ({
id: task.id,
type: task.payload.type,
- storageKey: task.payload.storageKey,
+ payload: task.payload,
+ storageKey:
+ 'storageKey' in task.payload ? task.payload.storageKey : undefined,
})),
skippedTasks: nonFailedTasks.map((task) => ({
id: task.id,
diff --git a/server/api/queue/task/retry.post.ts b/server/api/queue/task/retry.post.ts
index b20b668b..6c859b1e 100644
--- a/server/api/queue/task/retry.post.ts
+++ b/server/api/queue/task/retry.post.ts
@@ -55,10 +55,7 @@ export default defineEventHandler(async (event) => {
success: true,
message: `Task ${taskId} has been reset and will be retried`,
taskId,
- payload: {
- type: task.payload.type,
- storageKey: task.payload.storageKey,
- },
+ payload: task.payload,
}
} catch (error) {
if (error && typeof error === 'object' && 'statusCode' in error) {
diff --git a/server/api/system/stats.get.ts b/server/api/system/stats.get.ts
index 829fa76d..fa3975da 100644
--- a/server/api/system/stats.get.ts
+++ b/server/api/system/stats.get.ts
@@ -1,3 +1,4 @@
+import { getLocationMigrationStatus } from '../../services/pipeline-queue/location-migration'
import { settingsManager } from '~~/server/services/settings/settingsManager'
import { sql, gte } from 'drizzle-orm'
import * as si from 'systeminformation'
@@ -121,7 +122,7 @@ function mapSystemInfo(distribution: string): string {
}
export default eventHandler(async (event) => {
- await requireUserSession(event)
+ const session = await requireUserSession(event)
const queue = await useDB()
.select({
@@ -234,6 +235,9 @@ export default eventHandler(async (event) => {
const activeStorage = await settingsManager.storage.getActiveProvider()
return {
+ locationMigration: session.user.isAdmin
+ ? getLocationMigrationStatus(useDB())
+ : { count: 0 },
uptime: process.uptime() || 0,
runningOn: systemInfo,
memory: (await getMemoryStats()) || { used: 0, total: 0 },
diff --git a/server/database/migrations/0017_location_components.sql b/server/database/migrations/0017_location_components.sql
new file mode 100644
index 00000000..f29d031d
--- /dev/null
+++ b/server/database/migrations/0017_location_components.sql
@@ -0,0 +1 @@
+ALTER TABLE `photos` ADD `geocoding` text;
\ No newline at end of file
diff --git a/server/database/migrations/meta/0017_snapshot.json b/server/database/migrations/meta/0017_snapshot.json
new file mode 100644
index 00000000..1b5591d0
--- /dev/null
+++ b/server/database/migrations/meta/0017_snapshot.json
@@ -0,0 +1,907 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "4281d475-0459-4004-a705-2569326ec752",
+ "prevId": "1e0252aa-1354-4133-a0de-6e8f2928afae",
+ "tables": {
+ "album_photos": {
+ "name": "album_photos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "album_id": {
+ "name": "album_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "photo_id": {
+ "name": "photo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1000000
+ },
+ "added_at": {
+ "name": "added_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ }
+ },
+ "indexes": {
+ "album_photos_album_photo_unique": {
+ "name": "album_photos_album_photo_unique",
+ "columns": [
+ "album_id",
+ "photo_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "album_photos_album_id_albums_id_fk": {
+ "name": "album_photos_album_id_albums_id_fk",
+ "tableFrom": "album_photos",
+ "tableTo": "albums",
+ "columnsFrom": [
+ "album_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "album_photos_photo_id_photos_id_fk": {
+ "name": "album_photos_photo_id_photos_id_fk",
+ "tableFrom": "album_photos",
+ "tableTo": "photos",
+ "columnsFrom": [
+ "photo_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "albums": {
+ "name": "albums",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cover_photo_id": {
+ "name": "cover_photo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_hidden": {
+ "name": "is_hidden",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "albums_cover_photo_id_photos_id_fk": {
+ "name": "albums_cover_photo_id_photos_id_fk",
+ "tableFrom": "albums",
+ "tableTo": "photos",
+ "columnsFrom": [
+ "cover_photo_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "photo_access_keys": {
+ "name": "photo_access_keys",
+ "columns": {
+ "access_key": {
+ "name": "access_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "photo_id": {
+ "name": "photo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_photo_access_keys_photo_id": {
+ "name": "idx_photo_access_keys_photo_id",
+ "columns": [
+ "photo_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "photo_access_keys_photo_id_photos_id_fk": {
+ "name": "photo_access_keys_photo_id_photos_id_fk",
+ "tableFrom": "photo_access_keys",
+ "tableTo": "photos",
+ "columnsFrom": [
+ "photo_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "photo_access_keys_access_key_photo_id_pk": {
+ "columns": [
+ "access_key",
+ "photo_id"
+ ],
+ "name": "photo_access_keys_access_key_photo_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "photo_reactions": {
+ "name": "photo_reactions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "photo_id": {
+ "name": "photo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reaction_type": {
+ "name": "reaction_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "fingerprint": {
+ "name": "fingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "photo_reactions_photo_id_photos_id_fk": {
+ "name": "photo_reactions_photo_id_photos_id_fk",
+ "tableFrom": "photo_reactions",
+ "tableTo": "photos",
+ "columnsFrom": [
+ "photo_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "photos": {
+ "name": "photos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "aspect_ratio": {
+ "name": "aspect_ratio",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "date_taken": {
+ "name": "date_taken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storage_key": {
+ "name": "storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thumbnail_key": {
+ "name": "thumbnail_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "file_size": {
+ "name": "file_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_modified": {
+ "name": "last_modified",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "original_url": {
+ "name": "original_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thumbnail_url": {
+ "name": "thumbnail_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thumbnail_hash": {
+ "name": "thumbnail_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exif": {
+ "name": "exif",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "latitude": {
+ "name": "latitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "longitude": {
+ "name": "longitude",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "country": {
+ "name": "country",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "city": {
+ "name": "city",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "location_name": {
+ "name": "location_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "geocoding": {
+ "name": "geocoding",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_live_photo": {
+ "name": "is_live_photo",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "live_photo_video_url": {
+ "name": "live_photo_video_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "live_photo_video_key": {
+ "name": "live_photo_video_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "photos_id_unique": {
+ "name": "photos_id_unique",
+ "columns": [
+ "id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "pipeline_queue": {
+ "name": "pipeline_queue",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{\"type\":\"photo\",\"storageKey\":\"\"}'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "available_at": {
+ "name": "available_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "0"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "max_attempts": {
+ "name": "max_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 3
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "status_stage": {
+ "name": "status_stage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "warning_code": {
+ "name": "warning_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_pipeline_queue_pending": {
+ "name": "idx_pipeline_queue_pending",
+ "columns": [
+ "\"priority\" DESC",
+ "created_at",
+ "id"
+ ],
+ "isUnique": false,
+ "where": "\"pipeline_queue\".\"status\" = 'pending'"
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "namespace": {
+ "name": "namespace",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'common'"
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "default_value": {
+ "name": "default_value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_readonly": {
+ "name": "is_readonly",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "is_secret": {
+ "name": "is_secret",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "enum": {
+ "name": "enum",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_namespace_key": {
+ "name": "idx_namespace_key",
+ "columns": [
+ "namespace",
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "settings_updated_by_users_id_fk": {
+ "name": "settings_updated_by_users_id_fk",
+ "tableFrom": "settings",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings_storage_providers": {
+ "name": "settings_storage_providers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config": {
+ "name": "config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(unixepoch())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar": {
+ "name": "avatar",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_admin": {
+ "name": "is_admin",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "users_name_unique": {
+ "name": "users_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ },
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {
+ "idx_pipeline_queue_pending": {
+ "columns": {
+ "\"priority\" DESC": {
+ "isExpression": true
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/server/database/migrations/meta/_journal.json b/server/database/migrations/meta/_journal.json
index 30410abb..ed7c4de2 100644
--- a/server/database/migrations/meta/_journal.json
+++ b/server/database/migrations/meta/_journal.json
@@ -120,6 +120,13 @@
"when": 1792244529968,
"tag": "0016_upload_album_membership",
"breakpoints": true
+ },
+ {
+ "idx": 17,
+ "version": "6",
+ "when": 1792307735436,
+ "tag": "0017_location_components",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/server/database/schema.ts b/server/database/schema.ts
index feee41e4..6b0ee008 100644
--- a/server/database/schema.ts
+++ b/server/database/schema.ts
@@ -1,3 +1,4 @@
+import type { NormalizedLocation } from '../../shared/types/location'
import { sql } from 'drizzle-orm'
import {
index,
@@ -13,6 +14,7 @@ import type { NeededExif } from '~~/shared/types/photo'
import type { StorageConfig } from '../services/storage'
type PipelineQueuePayload =
+ | { type: 'location-migration' }
| {
type: 'photo'
storageKey: string
@@ -25,6 +27,7 @@ type PipelineQueuePayload =
}
| {
type: 'photo-reverse-geocoding'
+ migrationOnly?: boolean
photoId: string
latitude?: number | null
longitude?: number | null
@@ -67,6 +70,7 @@ export const photos = sqliteTable('photos', {
country: text('country'),
city: text('city'),
locationName: text('location_name'),
+ geocoding: text('geocoding', { mode: 'json' }).$type<NormalizedLocation>(),
// LivePhoto 相关字段
isLivePhoto: integer('is_live_photo').default(0).notNull(),
livePhotoVideoUrl: text('live_photo_video_url'),
diff --git a/server/services/location/geocoding.ts b/server/services/location/geocoding.ts
index 24a98e4b..8aa2ed5f 100644
--- a/server/services/location/geocoding.ts
+++ b/server/services/location/geocoding.ts
@@ -1,3 +1,7 @@
+import { waitForGeocodingSlot } from './rate-limit'
+import type { NormalizedLocation } from '../../../shared/types/location'
+import { hasValidCoordinates } from '../../../shared/utils/location'
+import { normalizeMapbox, normalizeNominatim } from './normalize'
import { withRetry, RetryPresets } from '../../utils/retry'
import { settingsManager } from '../settings/settingsManager'
@@ -6,6 +10,7 @@ export interface LocationInfo {
longitude: number
country?: string
city?: string
+ geocoding: NormalizedLocation
locationName?: string
}
@@ -20,7 +25,6 @@ export interface GeocodingProvider {
export class MapboxGeocodingProvider implements GeocodingProvider {
private accessToken: string
private readonly baseUrl = 'https://api.mapbox.com'
- private lastRequestTime = 0
private readonly rateLimitMs = 100 // Mapbox 默认速率限制为 1000/分钟,约60ms间隔
constructor(accessToken: string) {
@@ -32,7 +36,7 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
return await withRetry(
async (signal) => {
// 应用速率限制
- await this.applyRateLimit()
+ await waitForGeocodingSlot(this.baseUrl, this.rateLimitMs, signal)
// 获取设置的地理编码语言,默认 'en'
const language =
@@ -42,7 +46,10 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
url.searchParams.set('access_token', this.accessToken)
url.searchParams.set('longitude', lon.toString())
url.searchParams.set('latitude', lat.toString())
- url.searchParams.set('types', 'address,place,district,region,country')
+ url.searchParams.set(
+ 'types',
+ 'address,place,locality,neighborhood,district,region,country',
+ )
// 映射 Mapbox 首选语言格式
let mapboxLang = language
@@ -53,7 +60,7 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
}
url.searchParams.set('language', mapboxLang)
- logger.location.info(`Mapbox API URL: ${url.toString()}`)
+ logger.location.info('Requesting Mapbox reverse geocoding')
const response = await fetch(url.toString(), { signal })
@@ -70,34 +77,15 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
return null
}
- // 取第一个最相关的结果
- const feature = data.features[0]
- const properties = feature.properties || {}
- const context = properties.context || {}
-
- // 提取国家信息
- const country = context.country?.name
-
- // 提取城市信息(优先级:locality > place > locality > district > region)
- const city =
- context.locality?.name ||
- context.place?.name ||
- context.locality?.name ||
- context.district?.name ||
- context.region?.name
-
- // 构建位置名称
- const locationName = properties.place_formatted || properties.name
-
- logger.location.success(
- `Successfully geocoded location: ${city}, ${country}`,
- )
+ const geocoding = normalizeMapbox(data, language)
+ if (!geocoding) return null
return {
latitude: lat,
longitude: lon,
- country,
- city,
- locationName,
+ geocoding,
+ country: geocoding.components.country?.name,
+ city: geocoding.components.city?.name,
+ locationName: geocoding.formattedAddress,
}
},
{
@@ -115,18 +103,6 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
return null
}
}
-
- private async applyRateLimit(): Promise<void> {
- const now = Date.now()
- const timeSinceLastRequest = now - this.lastRequestTime
-
- if (timeSinceLastRequest < this.rateLimitMs) {
- const delay = this.rateLimitMs - timeSinceLastRequest
- await new Promise((resolve) => setTimeout(resolve, delay))
- }
-
- this.lastRequestTime = Date.now()
- }
}
/**
@@ -136,7 +112,6 @@ export class MapboxGeocodingProvider implements GeocodingProvider {
export class NominatimGeocodingProvider implements GeocodingProvider {
private readonly baseUrl: string
private readonly userAgent = 'chronoframe/1.0'
- private lastRequestTime = 0
private readonly rateLimitMs = 1000 // Nominatim 要求至少1秒间隔
constructor(baseUrl?: string) {
@@ -148,7 +123,7 @@ export class NominatimGeocodingProvider implements GeocodingProvider {
return await withRetry(
async (signal) => {
// 应用速率限制
- await this.applyRateLimit()
+ await waitForGeocodingSlot(this.baseUrl, this.rateLimitMs, signal)
// 获取设置的地理编码语言,默认 'en'
const language =
@@ -180,31 +155,15 @@ export class NominatimGeocodingProvider implements GeocodingProvider {
throw new Error(`Nominatim API returned error: ${data?.error}`)
}
- const address = data.address || {}
-
- // 提取国家信息
- const country = address.country || address.country_code?.toUpperCase()
-
- // 提取城市信息(优先级:district > city > town > county > state > village > hamlet)
- // 适配中国行政区划
- const city =
- address.district ||
- address.city ||
- address.town ||
- address.county ||
- address.state ||
- address.village ||
- address.hamlet
-
- // 构建位置名称
- const locationName = data.display_name
-
+ const geocoding = normalizeNominatim(data, language)
+ if (!geocoding) return null
return {
latitude: lat,
longitude: lon,
- country,
- city,
- locationName,
+ geocoding,
+ country: geocoding.components.country?.name,
+ city: geocoding.components.city?.name,
+ locationName: geocoding.formattedAddress,
}
},
{
@@ -222,18 +181,6 @@ export class NominatimGeocodingProvider implements GeocodingProvider {
return null
}
}
-
- private async applyRateLimit(): Promise<void> {
- const now = Date.now()
- const timeSinceLastRequest = now - this.lastRequestTime
-
- if (timeSinceLastRequest < this.rateLimitMs) {
- const delay = this.rateLimitMs - timeSinceLastRequest
- await new Promise((resolve) => setTimeout(resolve, delay))
- }
-
- this.lastRequestTime = Date.now()
- }
}
/**
@@ -263,12 +210,12 @@ export async function extractLocationFromGPS(
gpsLongitude?: number,
provider?: GeocodingProvider,
): Promise<LocationInfo | null> {
- if (!gpsLatitude || !gpsLongitude) {
+ if (gpsLatitude == null || gpsLongitude == null) {
return null
}
// 验证坐标范围
- if (Math.abs(gpsLatitude) > 90 || Math.abs(gpsLongitude) > 180) {
+ if (!hasValidCoordinates(gpsLatitude, gpsLongitude)) {
logger.location.warn(
`Invalid GPS coordinates: ${gpsLatitude}, ${gpsLongitude}`,
)
@@ -315,13 +262,13 @@ export function parseGPSCoordinates(exifData: any): {
let longitude: number | undefined
// 尝试从GPSLatitude和GPSLongitude获取
- if (exifData.GPSLatitude && exifData.GPSLongitude) {
+ if (exifData.GPSLatitude != null && exifData.GPSLongitude != null) {
latitude = parseFloat(exifData.GPSLatitude.toString())
longitude = parseFloat(exifData.GPSLongitude.toString())
}
// 如果上面的方法失败,尝试从GPSCoordinates获取
- if ((!latitude || !longitude) && exifData.GPSCoordinates) {
+ if ((latitude == null || longitude == null) && exifData.GPSCoordinates) {
const coords = exifData.GPSCoordinates.toString()
const match = coords.match(/([-+]?\d+\.?\d*)[°,\s]+([-+]?\d+\.?\d*)/)
if (match) {
diff --git a/server/services/location/normalize.ts b/server/services/location/normalize.ts
new file mode 100644
index 00000000..bd2cf34a
--- /dev/null
+++ b/server/services/location/normalize.ts
@@ -0,0 +1,110 @@
+import type {
+ LocationLevel,
+ NormalizedLocation,
+} from '../../../shared/types/location'
+
+type ObjectValue = Record<string, any>
+const name = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.trim() ? value.trim() : undefined
+
+const municipalityCodes = new Set(['CN-BJ', 'CN-TJ', 'CN-SH', 'CN-CQ'])
+
+function applyMunicipality(result: NormalizedLocation, code: unknown) {
+ // A direct-administered municipality also acts as the city. Use the explicit
+ // ISO subdivision code, rather than guessing from translated name suffixes.
+ if (
+ result.countryCode === 'CN' &&
+ typeof code === 'string' &&
+ municipalityCodes.has(code.toUpperCase()) &&
+ !result.components.city
+ ) {
+ result.components.city = result.components.region
+ }
+}
+
+function put(
+ result: NormalizedLocation,
+ level: LocationLevel,
+ value: unknown,
+ sourceField: string,
+) {
+ const text = name(value)
+ if (text && !result.components[level])
+ result.components[level] = { name: text, sourceField }
+}
+
+export function normalizeMapbox(
+ data: ObjectValue,
+ language: string,
+): NormalizedLocation | null {
+ if (!Array.isArray(data?.features) || !data.features.length) return null
+ const result: NormalizedLocation = {
+ version: 1,
+ provider: 'mapbox',
+ language,
+ components: {},
+ }
+ const mapping: Record<string, LocationLevel> = {
+ country: 'country',
+ region: 'region',
+ district: 'subregion',
+ place: 'city',
+ locality: 'district',
+ neighborhood: 'neighborhood',
+ }
+ for (const feature of data.features) {
+ const p = feature.properties || {}
+ const context = p.context || {}
+ // A country/place response may carry its own name only on the feature.
+ const level = mapping[p.feature_type]
+ if (level) put(result, level, p.name, `feature.${p.feature_type}`)
+ for (const [field, target] of Object.entries(mapping)) {
+ put(result, target, context[field]?.name, `context.${field}`)
+ }
+ result.countryCode ||= name(context.country?.country_code)?.toUpperCase()
+ if (p.feature_type === 'country')
+ result.countryCode ||= name(p.country_code)?.toUpperCase()
+ result.formattedAddress ||=
+ name(p.full_address) || name(p.place_formatted) || name(p.name)
+ }
+ for (const feature of data.features) {
+ const p = feature.properties || {}
+ applyMunicipality(
+ result,
+ p.context?.region?.region_code_full ||
+ (p.feature_type === 'region' ? p.region_code_full : undefined),
+ )
+ }
+ return Object.keys(result.components).length ? result : null
+}
+
+export function normalizeNominatim(
+ data: ObjectValue,
+ language: string,
+): NormalizedLocation | null {
+ if (!data || data.error) return null
+ const result: NormalizedLocation = {
+ version: 1,
+ provider: 'nominatim',
+ language,
+ components: {},
+ countryCode: name(data.address?.country_code)?.toUpperCase(),
+ formattedAddress: name(data.display_name),
+ }
+ // Preserve source tags: county/state_district must not be treated as city districts.
+ const mapping: Array<[LocationLevel, string[]]> = [
+ ['country', ['country']],
+ ['region', ['state', 'region']],
+ ['subregion', ['state_district', 'county']],
+ ['city', ['city', 'town', 'municipality', 'village', 'hamlet']],
+ ['district', ['city_district', 'district', 'borough']],
+ ['locality', ['suburb', 'subdivision']],
+ ['neighborhood', ['neighbourhood', 'quarter']],
+ ]
+ for (const [level, fields] of mapping) {
+ for (const field of fields)
+ put(result, level, data.address?.[field], `address.${field}`)
+ }
+ applyMunicipality(result, data.address?.['ISO3166-2-lvl4'])
+ return Object.keys(result.components).length ? result : null
+}
diff --git a/server/services/location/rate-limit.ts b/server/services/location/rate-limit.ts
new file mode 100644
index 00000000..840190cc
--- /dev/null
+++ b/server/services/location/rate-limit.ts
@@ -0,0 +1,16 @@
+import { setTimeout } from 'node:timers/promises'
+
+const nextRequestAt = new Map<string, number>()
+
+// Reserve synchronously before waiting so separate providers/workers cannot
+// start together after the same delay. Providers are recreated for each photo.
+export async function waitForGeocodingSlot(
+ key: string,
+ intervalMs: number,
+ signal?: AbortSignal,
+) {
+ const now = Date.now()
+ const start = Math.max(now, nextRequestAt.get(key) || 0)
+ nextRequestAt.set(key, start + intervalMs)
+ if (start > now) await setTimeout(start - now, undefined, { signal })
+}
diff --git a/server/services/pipeline-queue/location-migration.ts b/server/services/pipeline-queue/location-migration.ts
new file mode 100644
index 00000000..afdfd090
--- /dev/null
+++ b/server/services/pipeline-queue/location-migration.ts
@@ -0,0 +1,104 @@
+import { and, eq, isNull, or, sql } from 'drizzle-orm'
+import type { useDB } from '../../utils/db'
+import { photos, pipelineQueue } from '../../database/schema.ts'
+
+export function enqueueLocationMigrationRequest(
+ db: ReturnType<typeof useDB>,
+ options: { priority?: number; maxAttempts?: number } = {},
+) {
+ return db.transaction((tx) => {
+ const existing = tx
+ .select({ id: pipelineQueue.id })
+ .from(pipelineQueue)
+ .where(
+ and(
+ sql`json_extract(${pipelineQueue.payload}, '$.type') = 'location-migration'`,
+ sql`${pipelineQueue.status} IN ('pending', 'in-stages')`,
+ ),
+ )
+ .get()
+ if (existing) return existing.id
+ return tx
+ .insert(pipelineQueue)
+ .values({ ...options, payload: { type: 'location-migration' } })
+ .returning({ id: pipelineQueue.id })
+ .get().id
+ })
+}
+
+// Only old records with stored coordinates and an existing geocoding result qualify.
+// Photos with GPS alone may never have been geocoded and are not migration candidates.
+export const legacyLocationCondition = and(
+ isNull(photos.geocoding),
+ sql`${photos.latitude} BETWEEN -90 AND 90`,
+ sql`${photos.longitude} BETWEEN -180 AND 180`,
+ or(
+ sql`length(trim(coalesce(${photos.city}, ''))) > 0`,
+ sql`length(trim(coalesce(${photos.country}, ''))) > 0`,
+ sql`length(trim(coalesce(${photos.locationName}, ''))) > 0`,
+ ),
+)
+
+export function getLocationMigrationStatus(db: ReturnType<typeof useDB>) {
+ const { count } = db
+ .select({ count: sql<number>`count(*)` })
+ .from(photos)
+ .where(legacyLocationCondition)
+ .get()!
+ return { count }
+}
+
+export function enqueueLocationMigration(db: ReturnType<typeof useDB>) {
+ // Synchronous transaction makes repeated confirmations (including other tabs)
+ // idempotent and avoids racing the worker's pending-task claim.
+ return db.transaction((tx) => {
+ const candidates = tx
+ .select({ id: photos.id, storageKey: photos.storageKey })
+ .from(photos)
+ .where(legacyLocationCondition)
+ .all()
+ const active = tx
+ .select({ payload: pipelineQueue.payload })
+ .from(pipelineQueue)
+ .where(
+ or(
+ eq(pipelineQueue.status, 'pending'),
+ eq(pipelineQueue.status, 'in-stages'),
+ ),
+ )
+ .all()
+ const busyPhotos = new Set(
+ active.flatMap(({ payload }) =>
+ 'photoId' in payload ? [payload.photoId] : [],
+ ),
+ )
+ const busyKeys = new Set(
+ active.flatMap(({ payload }) =>
+ 'storageKey' in payload ? [payload.storageKey] : [],
+ ),
+ )
+ let queued = 0
+ for (const photo of candidates) {
+ if (
+ busyPhotos.has(photo.id) ||
+ (photo.storageKey && busyKeys.has(photo.storageKey))
+ )
+ continue
+ tx.insert(pipelineQueue)
+ .values({
+ payload: {
+ type: 'photo-reverse-geocoding',
+ photoId: photo.id,
+ migrationOnly: true,
+ },
+ })
+ .run()
+ queued++
+ }
+ return {
+ count: candidates.length,
+ queued,
+ alreadyQueued: candidates.length - queued,
+ }
+ })
+}
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index e9ed317c..0606d375 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -1,3 +1,8 @@
+import {
+ enqueueLocationMigration,
+ enqueueLocationMigrationRequest,
+} from './location-migration'
+import { hasValidCoordinates } from '../../../shared/utils/location'
import type { ConsolaInstance } from 'consola'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
@@ -126,6 +131,8 @@ export class QueueManager {
options?: Partial<NewPipelineQueueItem>,
): Promise<number> {
const db = useDB()
+ if (payload.type === 'location-migration')
+ return enqueueLocationMigrationRequest(db, options)
const result = db
.insert(tables.pipelineQueue)
.values({
@@ -396,7 +403,7 @@ export class QueueManager {
const { latitude, longitude } =
parseGPSCoordinates(normalizedExifData)
coordinates = { latitude, longitude }
- if (latitude && longitude) {
+ if (hasValidCoordinates(latitude, longitude)) {
locationInfo = await extractLocationFromGPS(latitude, longitude)
}
}
@@ -477,6 +484,7 @@ export class QueueManager {
country: locationInfo?.country || null,
city: locationInfo?.city || null,
locationName: locationInfo?.locationName || null,
+ geocoding: locationInfo?.geocoding || null,
// LivePhoto 相关字段
isLivePhoto:
motionPhotoInfo?.isMotionPhoto || livePhotoInfo?.isLivePhoto
@@ -563,6 +571,13 @@ export class QueueManager {
throw new PermanentTaskError(`Photo ${photoId} not found`)
}
+ if (
+ payload.migrationOnly &&
+ (photo.geocoding ||
+ !hasValidCoordinates(photo.latitude, photo.longitude))
+ )
+ return
+
let latitude = payload.latitude ?? photo.latitude ?? undefined
let longitude = payload.longitude ?? photo.longitude ?? undefined
@@ -598,6 +613,7 @@ export class QueueManager {
country: null,
city: null,
locationName: null,
+ geocoding: null,
})
.where(eq(tables.photos.id, photoId))
throw new PermanentTaskError(
@@ -624,8 +640,18 @@ export class QueueManager {
country: locationInfo.country ?? null,
city: locationInfo.city ?? null,
locationName: locationInfo.locationName ?? null,
+ geocoding: locationInfo.geocoding,
})
- .where(eq(tables.photos.id, photoId))
+ .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!),
+ )
+ : eq(tables.photos.id, photoId),
+ )
this.logger.success(
`[${taskId}:reverse-geocoding] updated location for photo ${photoId}`,
@@ -725,6 +751,7 @@ export class QueueManager {
country: null,
city: null,
locationName: null,
+ geocoding: null,
})
.where(eq(tables.photos.id, payload.photoId))
@@ -854,6 +881,9 @@ export class QueueManager {
let warningCode: PipelineQueueItem['warningCode'] = null
switch (type) {
+ case 'location-migration':
+ enqueueLocationMigration(useDB())
+ break
case 'live-photo-video':
await this.processors.livePhotoDetect(task)
break
diff --git a/server/services/settings/contants.ts b/server/services/settings/contants.ts
index 742142d3..9dfad9f4 100644
--- a/server/services/settings/contants.ts
+++ b/server/services/settings/contants.ts
@@ -220,6 +220,33 @@ export const DEFAULT_SETTINGS = [
isPublic: true,
},
// NAMESPACE: location
+ {
+ namespace: 'location',
+ key: 'preferredLevel',
+ type: 'string',
+ defaultValue: 'city',
+ enum: [
+ 'country',
+ 'region',
+ 'subregion',
+ 'city',
+ 'district',
+ 'locality',
+ 'neighborhood',
+ ],
+ label: 'settings.location.preferredLevel.label',
+ description: 'settings.location.preferredLevel.description',
+ isPublic: true,
+ },
+ {
+ namespace: 'location',
+ key: 'fallbackOrder',
+ type: 'string',
+ defaultValue: 'city,subregion,region,country',
+ label: 'settings.location.fallbackOrder.label',
+ description: 'settings.location.fallbackOrder.description',
+ isPublic: true,
+ },
{
namespace: 'location',
key: 'language',
diff --git a/server/services/settings/settingsManager.ts b/server/services/settings/settingsManager.ts
index 028c2e0b..a21b6308 100644
--- a/server/services/settings/settingsManager.ts
+++ b/server/services/settings/settingsManager.ts
@@ -282,6 +282,23 @@ export class SettingsManager {
)
}
+ if (namespace === 'location' && key === 'fallbackOrder') {
+ const levels = [
+ 'country',
+ 'region',
+ 'subregion',
+ 'city',
+ 'district',
+ 'locality',
+ 'neighborhood',
+ ]
+ if (
+ typeof value !== 'string' ||
+ value.split(',').some((level) => !levels.includes(level.trim()))
+ ) {
+ throw new Error('Invalid location fallback order')
+ }
+ }
const serializedValue = this.serialize(value)
if (namespace === 'system' && key === 'queue.workerCount') {
validateQueueWorkerCount(value)
diff --git a/server/services/settings/ui-config.ts b/server/services/settings/ui-config.ts
index ef37f447..b42941a2 100644
--- a/server/services/settings/ui-config.ts
+++ b/server/services/settings/ui-config.ts
@@ -103,6 +103,23 @@ export const MAP_SETTINGS_UI: Record<string, FieldUIConfig> = {
}
export const LOCATION_SETTINGS_UI: Record<string, FieldUIConfig> = {
+ preferredLevel: {
+ type: 'select',
+ options: [
+ 'country',
+ 'region',
+ 'subregion',
+ 'city',
+ 'district',
+ 'locality',
+ 'neighborhood',
+ ].map((value) => ({ value, label: 'settings.location.levels.' + value })),
+ },
+ fallbackOrder: {
+ type: 'input',
+ placeholder: 'city,subregion,region,country',
+ help: 'settings.location.fallbackOrder.help',
+ },
language: {
type: 'select',
options: i18nOptions.locales.map((locale) => ({
diff --git a/server/utils/queue-payload.ts b/server/utils/queue-payload.ts
index 7935cb09..1ba485be 100644
--- a/server/utils/queue-payload.ts
+++ b/server/utils/queue-payload.ts
@@ -4,6 +4,7 @@ import * as tables from '../database/schema.ts'
import { useDB } from './db.ts'
export const queuePayloadSchema = z.discriminatedUnion('type', [
+ z.object({ type: z.literal('location-migration') }),
z.object({
type: z.literal('photo'),
storageKey: z.string().nonempty(),
@@ -30,11 +31,11 @@ export const queuePayloadSchema = z.discriminatedUnion('type', [
export const photoTaskAlbumExists = (
payload: z.infer<typeof queuePayloadSchema>,
- db: ReturnType<typeof useDB> = useDB(),
+ db?: ReturnType<typeof useDB>,
): boolean => {
if (payload.type !== 'photo' || payload.albumId === undefined) return true
- const album = db
+ const album = (db ?? useDB())
.select({ id: tables.albums.id })
.from(tables.albums)
.where(eq(tables.albums.id, payload.albumId))
@@ -44,7 +45,7 @@ export const photoTaskAlbumExists = (
}
export const createPhotoTaskAlbumChecker = (
- db: ReturnType<typeof useDB> = useDB(),
+ db?: ReturnType<typeof useDB>,
) => {
const cache = new Map<number, boolean>()
diff --git a/shared/types/location.ts b/shared/types/location.ts
new file mode 100644
index 00000000..1e0af031
--- /dev/null
+++ b/shared/types/location.ts
@@ -0,0 +1,25 @@
+export const locationLevels = [
+ 'country',
+ 'region',
+ 'subregion',
+ 'city',
+ 'district',
+ 'locality',
+ 'neighborhood',
+] as const
+
+export type LocationLevel = (typeof locationLevels)[number]
+
+export interface LocationComponent {
+ name: string
+ sourceField: string
+}
+
+export interface NormalizedLocation {
+ version: 1
+ provider: 'mapbox' | 'nominatim'
+ language: string
+ countryCode?: string
+ components: Partial<Record<LocationLevel, LocationComponent>>
+ formattedAddress?: string
+}
diff --git a/shared/types/map.ts b/shared/types/map.ts
index ebda99dd..856962f6 100644
--- a/shared/types/map.ts
+++ b/shared/types/map.ts
@@ -1,3 +1,4 @@
+import type { NormalizedLocation } from './location'
import type { Map as _MaplibreMap } from 'maplibre-gl'
import type { Map as _MapboxMap } from 'mapbox-gl'
@@ -28,6 +29,7 @@ export interface PhotoMarker {
thumbnailUrl?: string
thumbnailHash?: string
dateTaken?: string
+ geocoding?: NormalizedLocation | null
city?: string
exif?: any
}
diff --git a/shared/utils/location.ts b/shared/utils/location.ts
new file mode 100644
index 00000000..d8524eff
--- /dev/null
+++ b/shared/utils/location.ts
@@ -0,0 +1,38 @@
+import {
+ locationLevels,
+ type LocationLevel,
+ type NormalizedLocation,
+} from '../types/location.ts'
+
+export const defaultLocationFallback = 'city,subregion,region,country'
+
+export function parseLocationOrder(value: string): LocationLevel[] {
+ return [...new Set(value.split(',').map((s) => s.trim()))].filter(
+ (s): s is LocationLevel => locationLevels.includes(s as LocationLevel),
+ )
+}
+
+export function resolveLocationLabel(
+ photo: { geocoding?: NormalizedLocation | null; city?: string | null },
+ preferred: string = 'city',
+ fallback: string = defaultLocationFallback,
+): { label: string; level?: LocationLevel } {
+ if (!photo.geocoding) return { label: photo.city || '' }
+ const order = parseLocationOrder(`${preferred},${fallback}`)
+ for (const level of order) {
+ const name = photo.geocoding.components[level]?.name.trim()
+ if (name) return { label: name, level }
+ }
+ return { label: '' }
+}
+
+export function hasValidCoordinates(lat: unknown, lon: unknown): boolean {
+ return (
+ typeof lat === 'number' &&
+ Number.isFinite(lat) &&
+ Math.abs(lat) <= 90 &&
+ typeof lon === 'number' &&
+ Number.isFinite(lon) &&
+ Math.abs(lon) <= 180
+ )
+}
diff --git a/tests/location-migration.test.ts b/tests/location-migration.test.ts
new file mode 100644
index 00000000..ce11c2ba
--- /dev/null
+++ b/tests/location-migration.test.ts
@@ -0,0 +1,166 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import test from 'node:test'
+import Database from 'better-sqlite3'
+import { drizzle } from 'drizzle-orm/better-sqlite3'
+import {
+ enqueueLocationMigration,
+ enqueueLocationMigrationRequest,
+ getLocationMigrationStatus,
+} from '../server/services/pipeline-queue/location-migration.ts'
+
+test('migration selects only old geocoded photos and deduplicates queue entries', () => {
+ const sqlite = new Database(':memory:')
+ sqlite.exec(`CREATE TABLE photos (
+ id TEXT PRIMARY KEY, storage_key TEXT, latitude REAL, longitude REAL,
+ country TEXT, city TEXT, location_name TEXT
+ ); CREATE TABLE pipeline_queue (
+ id INTEGER PRIMARY KEY, payload TEXT NOT NULL, priority INTEGER DEFAULT 0,
+ attempts INTEGER DEFAULT 0, max_attempts INTEGER DEFAULT 3,
+ status TEXT DEFAULT 'pending', status_stage TEXT, error_message TEXT, warning_code TEXT,
+ available_at INTEGER DEFAULT 0, created_at INTEGER DEFAULT (unixepoch()), completed_at INTEGER
+ );`)
+ sqlite.exec(
+ readFileSync(
+ new URL(
+ '../server/database/migrations/0017_location_components.sql',
+ import.meta.url,
+ ),
+ 'utf8',
+ ),
+ )
+ const db = drizzle(sqlite) as Parameters<typeof enqueueLocationMigration>[0]
+ const insert = sqlite.prepare(
+ 'INSERT INTO photos VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+ )
+ insert.run(
+ 'legacy',
+ '/legacy.jpg',
+ 0,
+ 0,
+ 'Country',
+ 'Old district',
+ 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)
+ insert.run('empty', '/empty.jpg', 1, 1, ' ', '', '', null)
+ insert.run(
+ 'modern',
+ '/modern.jpg',
+ 1,
+ 1,
+ 'Country',
+ 'City',
+ null,
+ JSON.stringify({ version: 1, components: {} }),
+ )
+ insert.run('busy', '/busy.jpg', 1, 1, null, null, 'Old address', null)
+ sqlite
+ .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(enqueueLocationMigration(db), {
+ count: 2,
+ queued: 1,
+ alreadyQueued: 1,
+ })
+ assert.deepEqual(enqueueLocationMigration(db), {
+ count: 2,
+ queued: 0,
+ alreadyQueued: 2,
+ })
+ const task = sqlite
+ .prepare('SELECT payload FROM pipeline_queue ORDER BY id DESC LIMIT 1')
+ .get() as { payload: string }
+ assert.deepEqual(JSON.parse(task.payload), {
+ type: 'photo-reverse-geocoding',
+ photoId: 'legacy',
+ migrationOnly: true,
+ })
+ // 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(enqueueLocationMigration(db), {
+ count: 2,
+ queued: 1,
+ alreadyQueued: 1,
+ })
+ sqlite.exec("UPDATE photos SET geocoding = '{}' WHERE id = 'legacy'")
+ assert.deepEqual(getLocationMigrationStatus(db), { count: 1 })
+ const requestId = enqueueLocationMigrationRequest(db)
+ assert.equal(enqueueLocationMigrationRequest(db), requestId)
+ sqlite
+ .prepare("UPDATE pipeline_queue SET status = 'in-stages' WHERE id = ?")
+ .run(requestId)
+ assert.equal(enqueueLocationMigrationRequest(db), requestId)
+ sqlite
+ .prepare("UPDATE pipeline_queue SET status = 'completed' WHERE id = ?")
+ .run(requestId)
+ assert.notEqual(enqueueLocationMigrationRequest(db), requestId)
+ } finally {
+ sqlite.close()
+ }
+})
+
+test('existing queue APIs accept migration tasks only for administrators', async () => {
+ const previous = Object.getOwnPropertyDescriptors(globalThis)
+ const submitted: unknown[] = []
+ Object.assign(globalThis, {
+ defineEventHandler: (handler: unknown) => handler,
+ requireUserSession: async (event: { admin: boolean }) => ({
+ user: { isAdmin: event.admin },
+ }),
+ readValidatedBody: async (
+ event: { body: unknown },
+ parse: (body: unknown) => unknown,
+ ) => parse(event.body),
+ createError: (options: { statusCode: number; statusMessage: string }) =>
+ Object.assign(new Error(options.statusMessage), options),
+ __workerPool: {
+ addTask: async (payload: unknown) => {
+ submitted.push(payload)
+ return 42
+ },
+ },
+ })
+ try {
+ const { default: single } =
+ await import('../server/api/queue/add-task.post.ts')
+ const { default: batch } =
+ await import('../server/api/queue/add-tasks.post.ts')
+ const payload = { type: 'location-migration' }
+ await assert.rejects(single({ admin: false, body: { payload } } as never), {
+ statusCode: 403,
+ })
+ await assert.rejects(
+ batch({ admin: false, body: { tasks: [{ payload }] } } as never),
+ { statusCode: 403 },
+ )
+ assert.equal(submitted.length, 0)
+ assert.equal(
+ (await single({ admin: true, body: { payload } } as never)).taskId,
+ 42,
+ )
+ assert.equal(
+ (await batch({ admin: true, body: { tasks: [{ payload }] } } as never))
+ .successCount,
+ 1,
+ )
+ assert.deepEqual(submitted, [payload, payload])
+ } finally {
+ for (const key of [
+ 'defineEventHandler',
+ 'requireUserSession',
+ 'readValidatedBody',
+ 'createError',
+ '__workerPool',
+ ]) {
+ if (previous[key]) Object.defineProperty(globalThis, key, previous[key])
+ else Reflect.deleteProperty(globalThis, key)
+ }
+ }
+})
diff --git a/tests/location.test.ts b/tests/location.test.ts
new file mode 100644
index 00000000..0ee7e1b8
--- /dev/null
+++ b/tests/location.test.ts
@@ -0,0 +1,179 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ normalizeMapbox,
+ normalizeNominatim,
+} from '../server/services/location/normalize.ts'
+import {
+ hasValidCoordinates,
+ resolveLocationLabel,
+} from '../shared/utils/location.ts'
+import { waitForGeocodingSlot } from '../server/services/location/rate-limit.ts'
+
+test('providers preserve city and district separately with source fields', () => {
+ const mapbox = normalizeMapbox(
+ {
+ features: [
+ {
+ properties: {
+ feature_type: 'address',
+ name: 'Some street',
+ context: {
+ country: { name: 'France', country_code: 'fr' },
+ region: { name: 'Île-de-France' },
+ place: { name: 'Paris' },
+ locality: { name: '9e arrondissement' },
+ },
+ },
+ },
+ ],
+ },
+ 'fr',
+ )!
+ const nominatim = normalizeNominatim(
+ {
+ address: {
+ country: 'France',
+ country_code: 'fr',
+ state: 'Île-de-France',
+ city: 'Paris',
+ city_district: '9e arrondissement',
+ },
+ },
+ 'fr',
+ )!
+ for (const geocoding of [mapbox, nominatim]) {
+ assert.equal(geocoding.countryCode, 'FR')
+ assert.equal(resolveLocationLabel({ geocoding }).label, 'Paris')
+ assert.deepEqual(resolveLocationLabel({ geocoding }, 'district'), {
+ label: '9e arrondissement',
+ level: 'district',
+ })
+ }
+ assert.equal(mapbox.components.district?.sourceField, 'context.locality')
+ assert.equal(
+ nominatim.components.district?.sourceField,
+ 'address.city_district',
+ )
+})
+
+test('top-level Mapbox features contribute their own names', () => {
+ const geocoding = normalizeMapbox(
+ {
+ features: [
+ {
+ properties: {
+ feature_type: 'place',
+ name: 'Hangzhou',
+ context: { country: { name: 'China' } },
+ },
+ },
+ ],
+ },
+ 'en',
+ )!
+ assert.equal(geocoding.components.city?.name, 'Hangzhou')
+ assert.equal(normalizeMapbox({ features: [] }, 'en'), null)
+})
+
+test('missing fields remain missing; preference changes do not need geocoding', () => {
+ const geocoding = normalizeNominatim(
+ {
+ address: {
+ country: '中国',
+ state: '浙江省',
+ district: '西湖区',
+ },
+ },
+ 'zh-CN',
+ )!
+ assert.equal(geocoding.components.city, undefined)
+ assert.equal(resolveLocationLabel({ geocoding }).label, '浙江省')
+ assert.equal(resolveLocationLabel({ geocoding }, 'district').label, '西湖区')
+ assert.equal(
+ resolveLocationLabel({ geocoding }, 'city', 'country,region').label,
+ '中国',
+ )
+ assert.equal(
+ resolveLocationLabel({ geocoding }, 'city', 'neighborhood').label,
+ '',
+ )
+ assert.equal(resolveLocationLabel({ city: '旧位置' }).label, '旧位置')
+})
+
+test('county, settlements, and neighborhood aliases preserve distinct roles', () => {
+ const geocoding = normalizeNominatim(
+ {
+ address: {
+ country: 'United States',
+ state: 'California',
+ county: 'Marin County',
+ town: 'Fairfax',
+ suburb: 'Local area',
+ neighbourhood: 'Neighborhood',
+ },
+ },
+ 'en',
+ )!
+ assert.equal(geocoding.components.subregion?.name, 'Marin County')
+ assert.equal(geocoding.components.city?.sourceField, 'address.town')
+ assert.equal(geocoding.components.district, undefined)
+ assert.equal(geocoding.components.locality?.name, 'Local area')
+ assert.equal(geocoding.components.neighborhood?.name, 'Neighborhood')
+ assert.equal(normalizeNominatim({ error: 'not found' }, 'en'), null)
+ assert.equal(normalizeNominatim({ address: {} }, 'en'), null)
+})
+
+test('coordinates include the equator and prime meridian but reject nonfinite values', () => {
+ assert.equal(hasValidCoordinates(0, 0), true)
+ assert.equal(hasValidCoordinates(-90, 180), true)
+ for (const [lat, lon] of [
+ [NaN, 1],
+ [1, Infinity],
+ [91, 0],
+ [0, -181],
+ [null, 0],
+ ]) {
+ assert.equal(hasValidCoordinates(lat, lon), false)
+ }
+})
+
+test('direct-administered municipalities use explicit subdivision codes', () => {
+ const geocoding = normalizeNominatim(
+ {
+ address: {
+ country: '中国',
+ country_code: 'cn',
+ state: '北京市',
+ 'ISO3166-2-lvl4': 'CN-BJ',
+ city_district: '朝阳区',
+ },
+ },
+ 'zh-CN',
+ )!
+ assert.equal(resolveLocationLabel({ geocoding }).label, '北京市')
+ assert.equal(geocoding.components.city?.sourceField, 'address.state')
+ const ordinary = normalizeNominatim(
+ {
+ address: {
+ country: '中国',
+ country_code: 'cn',
+ state: '浙江省',
+ 'ISO3166-2-lvl4': 'CN-ZJ',
+ },
+ },
+ 'zh-CN',
+ )!
+ assert.equal(ordinary.components.city, undefined)
+})
+
+test('parallel geocoding callers share request spacing', async () => {
+ const start = Date.now()
+ await Promise.all(
+ Array.from({ length: 3 }, () => waitForGeocodingSlot('test-provider', 25)),
+ )
+ assert.ok(
+ Date.now() - start >= 45,
+ 'requests must reserve distinct time slots',
+ )
+})