Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
refactor: remove dashboard locations page (#104)
Timothy Yine7764b22f282
diff --git a/app/components/ui/UploadQueuePanel.vue b/app/components/ui/UploadQueuePanel.vueindex f70a5fc5..63f42c8e 100644--- a/app/components/ui/UploadQueuePanel.vue+++ b/app/components/ui/UploadQueuePanel.vue@@ -129,7 +129,7 @@ const clearAllFiles = () => {<template><divv-if="uploadingFiles.size > 0"- class="fixed bottom-2 inset-x-2 sm:inset-x-6 sm:bottom-6 sm:left-auto z-50 min-w-sm"+ class="fixed bottom-2 inset-x-2 sm:inset-x-6 sm:bottom-6 sm:left-auto z-50 min-w-sm sm:w-md"><motion.divclass="bg-white dark:bg-neutral-900 rounded-xl shadow-2xl border border-neutral-200 dark:border-neutral-700 overflow-hidden"diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vueindex a3b3d5c7..6724472c 100644--- a/app/layouts/dashboard.vue+++ b/app/layouts/dashboard.vue@@ -18,11 +18,6 @@ const items = ref<NavigationMenuItem[]>([icon: 'tabler:album',to: '/dashboard/albums',},- {- label: $t('title.locations'),- icon: 'tabler:map-pin-cog',- to: '/dashboard/location',- },{label: $t('title.queue'),icon: 'tabler:list-check',diff --git a/app/pages/dashboard/location.vue b/app/pages/dashboard/location.vuedeleted file mode 100644index 57616d16..00000000--- a/app/pages/dashboard/location.vue+++ /dev/null@@ -1,360 +0,0 @@-<script lang="ts" setup>-definePageMeta({- layout: 'dashboard',-})--useHead({- title: $t('title.locations'),-})--interface LocationStats {- statistics: {- totalPhotosWithGps: number- photosWithCity: number- photosNeedingReindex: number- photosNeedingGpsReindex: number- photosNeedingLocationReindex: number- coveragePercentage: string- }- message: string-}--interface ReindexResult {- message: string- processed: number- updated: number- gpsUpdated: number- locationUpdated: number- errors?: Array<{ photoId: string; error: string }>- statistics: {- totalFound: number- successRate: string- }-}--const isLoading = ref(false)-const isReindexing = ref(false)-const reindexResult = ref<ReindexResult | null>(null)--const { data: locationStats, refresh: refreshStats } =- await useFetch<LocationStats>('/api/photos/locations/geocode', {- server: false,- })--const refreshData = async () => {- isLoading.value = true- try {- await refreshStats()- } finally {- isLoading.value = false- }-}--const startReindex = async (force = false) => {- if (isReindexing.value) return-- isReindexing.value = true- reindexResult.value = null-- try {- const data = await $fetch<ReindexResult>('/api/photos/locations/geocode', {- method: 'POST',- body: { force },- })-- reindexResult.value = data- await refreshStats()-- // 显示成功通知- if (data.updated > 0) {- useToast().add({- title: '重新索引完成',- description: `成功更新了 ${data.updated} 张照片的城市信息`,- color: 'success',- })- } else {- useToast().add({- title: '重新索引完成',- description: '没有照片需要更新',- color: 'info',- })- }- } catch (error: any) {- console.error('Reindex failed:', error)- useToast().add({- title: '重新索引失败',- description: error?.message || '未知错误',- color: 'error',- })- } finally {- isReindexing.value = false- }-}--// 格式化百分比-const formatPercentage = (value: string) => {- return `${value}%`-}-</script>--<template>- <div class="flex flex-col gap-6 h-full p-4">- <div class="flex items-center justify-between">- <h1 class="text-2xl font-bold">位置信息管理</h1>- <UButton- icon="i-tabler-refresh"- variant="outline"- :loading="isLoading"- @click="refreshData"- >- 刷新统计- </UButton>- </div>-- <!-- 统计信息 -->- <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">- <!-- 总GPS照片数 -->- <UCard>- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- EXIF中有GPS的照片- </p>- <p class="text-2xl font-bold">- {{ locationStats?.statistics.totalPhotosWithGps || 0 }}- </p>- </div>- <UIcon- name="i-tabler-map-pin"- class="w-8 h-8 text-info"- />- </div>- </UCard>-- <!-- 有城市信息的照片 -->- <UCard>- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- 已有城市信息- </p>- <p class="text-2xl font-bold">- {{ locationStats?.statistics.photosWithCity || 0 }}- </p>- </div>- <UIcon- name="i-tabler-building"- class="w-8 h-8 text-success"- />- </div>- </UCard>-- <!-- 需要GPS重新索引的照片 -->- <UCard>- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- 需要GPS重新提取- </p>- <p class="text-2xl font-bold text-orange-500">- {{ locationStats?.statistics.photosNeedingGpsReindex || 0 }}- </p>- </div>- <UIcon- name="i-tabler-gps"- class="w-8 h-8 text-orange-500"- />- </div>- </UCard>-- <!-- 需要城市信息重新索引的照片 -->- <UCard>- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- 需要城市重新索引- </p>- <p class="text-2xl font-bold text-warning-500">- {{ locationStats?.statistics.photosNeedingLocationReindex || 0 }}- </p>- </div>- <UIcon- name="i-tabler-building-skyscraper"- class="w-8 h-8 text-warning-500"- />- </div>- </UCard>-- <!-- 覆盖率 -->- <UCard>- <div class="flex items-center justify-between">- <div>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- 城市信息覆盖率- </p>- <p class="text-2xl font-bold">- {{- formatPercentage(- locationStats?.statistics.coveragePercentage || '0',- )- }}- </p>- </div>- <UIcon- name="i-tabler-percentage"- class="w-8 h-8 text-primary"- />- </div>- </UCard>- </div>-- <!-- 操作区域 -->- <UCard>- <template #header>- <h2 class="text-lg font-semibold">重新索引操作</h2>- </template>-- <div class="space-y-4">- <div class="bg-neutral-50 dark:bg-neutral-800 p-4 rounded-lg">- <p class="text-sm text-neutral-600 dark:text-neutral-300 mb-3">- {{ locationStats?.message }}- </p>-- <div class="flex gap-3">- <UButton- size="sm"- icon="i-tabler-refresh"- :loading="isReindexing"- :disabled="- (locationStats?.statistics.photosNeedingReindex || 0) === 0- "- @click="startReindex(false)"- >- 索引缺少的城市信息- </UButton>-- <UButton- size="sm"- icon="i-tabler-reload"- variant="outline"- :loading="isReindexing"- :disabled="- (locationStats?.statistics.totalPhotosWithGps || 0) === 0- "- @click="startReindex(true)"- >- 重建位置信息- </UButton>- </div>- </div>-- <!-- 说明信息 -->- <UAlert- icon="i-tabler-info-circle"- color="info"- variant="soft"- title="操作说明"- description="重新索引操作将从EXIF中重新提取GPS坐标,并为有GPS坐标但缺少城市信息的照片获取地理位置信息。由于API限制,处理速度较慢,请耐心等待。"- />- </div>- </UCard>-- <!-- 重新索引结果 -->- <UCard v-if="reindexResult">- <template #header>- <h2 class="text-lg font-semibold">重新索引结果</h2>- </template>-- <div class="space-y-4">- <div class="grid grid-cols-1 md:grid-cols-5 gap-4">- <div class="bg-blue-50 dark:bg-blue-950 p-3 rounded-lg">- <p class="text-sm text-blue-600 dark:text-blue-400">处理总数</p>- <p class="text-xl font-bold text-blue-700 dark:text-blue-300">- {{ reindexResult.processed }}- </p>- </div>-- <div class="bg-green-50 dark:bg-green-950 p-3 rounded-lg">- <p class="text-sm text-green-600 dark:text-green-400">更新数量</p>- <p class="text-xl font-bold text-green-700 dark:text-green-300">- {{ reindexResult.updated }}- </p>- </div>-- <div class="bg-orange-50 dark:bg-orange-950 p-3 rounded-lg">- <p class="text-sm text-orange-600 dark:text-orange-400">GPS更新</p>- <p class="text-xl font-bold text-orange-700 dark:text-orange-300">- {{ reindexResult.gpsUpdated }}- </p>- </div>-- <div class="bg-yellow-50 dark:bg-yellow-950 p-3 rounded-lg">- <p class="text-sm text-yellow-600 dark:text-yellow-400">位置更新</p>- <p class="text-xl font-bold text-yellow-700 dark:text-yellow-300">- {{ reindexResult.locationUpdated }}- </p>- </div>-- <div class="bg-purple-50 dark:bg-purple-950 p-3 rounded-lg">- <p class="text-sm text-purple-600 dark:text-purple-400">成功率</p>- <p class="text-xl font-bold text-purple-700 dark:text-purple-300">- {{ reindexResult.statistics.successRate }}- </p>- </div>- </div>-- <div class="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg">- <p class="font-medium mb-2">{{ reindexResult.message }}</p>- <p class="text-sm text-gray-600 dark:text-gray-400">- 在 {{ reindexResult.statistics.totalFound }} 张照片中,成功处理了- {{ reindexResult.processed }} 张, 更新了- {{ reindexResult.updated }} 张照片的位置信息 ({{- reindexResult.gpsUpdated- }}- 张GPS坐标,{{ reindexResult.locationUpdated }} 张城市信息)。- </p>- </div>-- <!-- 错误信息 -->- <div- v-if="reindexResult.errors && reindexResult.errors.length > 0"- class="bg-red-50 dark:bg-red-950 p-4 rounded-lg"- >- <h3 class="font-medium text-red-700 dark:text-red-300 mb-2">- 处理错误 ({{ reindexResult.errors.length }})- </h3>- <div class="space-y-2 max-h-48 overflow-y-auto">- <div- v-for="error in reindexResult.errors"- :key="error.photoId"- class="text-sm bg-white dark:bg-red-900 p-2 rounded"- >- <span class="font-mono text-red-600 dark:text-red-400">{{- error.photoId- }}</span- >: {{ error.error }}- </div>- </div>- </div>- </div>- </UCard>-- <!-- 进度提示 -->- <UCard v-if="isReindexing">- <div class="flex items-center gap-3 p-4">- <UIcon- name="i-tabler-loader-2"- class="w-6 h-6 animate-spin text-primary"- />- <div>- <p class="font-medium">正在重新索引城市信息...</p>- <p class="text-sm text-neutral-500 dark:text-neutral-400">- 这可能需要几分钟时间,请不要关闭页面。由于API限制,每张照片之间有1秒延迟。- </p>- </div>- </div>- </UCard>- </div>-</template>--<style scoped></style>diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vueindex f48afd8c..8d1aae81 100644--- a/app/pages/dashboard/photos.vue+++ b/app/pages/dashboard/photos.vue@@ -29,6 +29,20 @@ const totalSelectedFilters = computed(() => {)})+const reverseGeocodeLoading = ref<Record<string, boolean>>({})++const setReverseGeocodeLoading = (photoId: string, loading: boolean) => {+ if (loading) {+ reverseGeocodeLoading.value = {+ ...reverseGeocodeLoading.value,+ [photoId]: true,+ }+ } else {+ const { [photoId]: _removed, ...rest } = reverseGeocodeLoading.value+ reverseGeocodeLoading.value = rest+ }+}+// 表态数据const reactionsData = ref<Record<string, Record<string, number>>>({})const reactionsLoading = ref(false)@@ -963,7 +977,7 @@ const handleUpload = async () => {const startUpload = async (file: File): Promise<void> => {const fileId = fileIdMapping.get(file)!try {- await uploadImage(file, fileId)+ uploadImage(file, fileId)} catch (error: any) {errors.push(`${file.name}: ${error.message || '上传失败'}`)console.error('上传错误:', error)@@ -1157,6 +1171,68 @@ const handleViewLivePhoto = async (photoId: string) => {}}+const handleReverseGeocodeRequest = async (photo: Photo) => {+ if (!photo?.id) {+ return+ }++ setReverseGeocodeLoading(photo.id, true)++ try {+ const result = await $fetch('/api/queue/add-task', {+ method: 'POST',+ body: {+ payload: {+ type: 'photo-reverse-geocoding',+ photoId: photo.id,+ latitude:+ typeof photo.latitude === 'number' ? photo.latitude : undefined,+ longitude:+ typeof photo.longitude === 'number' ? photo.longitude : undefined,+ },+ priority: 1,+ maxAttempts: 3,+ },+ })++ if (result.success) {+ toast.add({+ title: $t('dashboard.photos.messages.reverseGeocodeQueued'),+ description:+ typeof result.taskId === 'number'+ ? $t('dashboard.photos.messages.reprocessTaskId', {+ taskId: result.taskId,+ })+ : '',+ color: 'success',+ })+ } else {+ toast.add({+ title: $t('dashboard.photos.messages.reverseGeocodeFailed'),+ description:+ result?.message ||+ $t('dashboard.photos.messages.reverseGeocodeFailed'),+ color: 'error',+ })+ }+ } catch (error: any) {+ console.error('Failed to enqueue reverse geocoding task:', error)+ const message =+ error?.data?.statusMessage ||+ error?.statusMessage ||+ error?.message ||+ $t('dashboard.photos.messages.reverseGeocodeFailed')++ toast.add({+ title: $t('dashboard.photos.messages.reverseGeocodeFailed'),+ description: message,+ color: 'error',+ })+ } finally {+ setReverseGeocodeLoading(photo.id, false)+ }+}+// 重新处理单张照片const handleReprocessSingle = async (photo: Photo) => {try {@@ -1210,6 +1286,53 @@ const handleReprocessSingle = async (photo: Photo) => {}}+const getRowActions = (photo: Photo) => {+ const isReverseLoading = !!reverseGeocodeLoading.value[photo.id]++ return [+ [+ {+ label: $t('dashboard.photos.actions.editMetadata'),+ icon: 'tabler:pencil',+ onSelect() {+ openMetadataEditor(photo)+ },+ },+ {+ label: $t('dashboard.photos.actions.reprocess'),+ icon: 'tabler:refresh',+ onSelect() {+ handleReprocessSingle(photo)+ },+ },+ {+ label: $t('dashboard.photos.actions.refreshLocation'),+ icon: isReverseLoading ? 'tabler:loader-2' : 'tabler:map-pin',+ disabled: isReverseLoading,+ onSelect() {+ handleReverseGeocodeRequest(photo)+ },+ },+ {+ label: $t('dashboard.photos.actions.viewLivePhoto'),+ icon: 'tabler:live-photo',+ disabled: !photo.isLivePhoto,+ onSelect() {+ handleViewLivePhoto(photo.id)+ },+ },+ ],+ [+ {+ color: 'error',+ label: $t('dashboard.photos.actions.delete'),+ icon: 'tabler:trash',+ onSelect: () => handleSingleDeleteRequest(photo),+ },+ ],+ ]+}+// LivePhoto Modalconst isLivePhotoModalOpen = ref(false)const selectedLivePhoto = ref<{@@ -1768,40 +1891,7 @@ onUnmounted(() => {:content="{align: 'end',}"- :items="[- [- {- label: $t('dashboard.photos.actions.editMetadata'),- icon: 'tabler:pencil',- onSelect() {- openMetadataEditor(row.original)- },- },- {- label: $t('dashboard.photos.actions.reprocess'),- icon: 'tabler:refresh',- onSelect() {- handleReprocessSingle(row.original)- },- },- {- label: $t('dashboard.photos.actions.viewLivePhoto'),- icon: 'tabler:live-photo',- disabled: !row.original.isLivePhoto,- onSelect() {- handleViewLivePhoto(row.original.id)- },- },- ],- [- {- color: 'error',- label: $t('dashboard.photos.actions.delete'),- icon: 'tabler:trash',- onSelect: () => handleSingleDeleteRequest(row.original),- },- ],- ]"+ :items="getRowActions(row.original)"><UButtonvariant="outline"diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex fa4b040a..f3b49c0c 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -521,6 +521,7 @@"actions": {"reprocess": "Reprocess","viewLivePhoto": "Live Photo Preview",+ "refreshLocation": "Re-fetch City","delete": "Delete","editMetadata": "Edit Metadata"},@@ -588,7 +589,10 @@"metadataUpdateFailed": "Failed to update photo metadata","photoNotFound": "Photo not found","photoFileMissing": "Photo file is missing",- "noChangesProvided": "No changes to apply"+ "noChangesProvided": "No changes to apply",+ "queueUnavailable": "Task queue is not available",+ "reverseGeocodeQueued": "Reverse geocoding task queued",+ "reverseGeocodeFailed": "Failed to queue reverse geocoding"},"errors": {"noSelection": "Please select photos to upload",diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex 2a642c66..053fb94f 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -464,6 +464,7 @@"actions": {"reprocess": "再処理","viewLivePhoto": "ライブフォトプレビュー",+ "refreshLocation": "都市情報を再取得","delete": "削除","editMetadata": "メタデータを編集"},@@ -531,7 +532,10 @@"metadataUpdateFailed": "写真のメタデータを更新できませんでした","photoNotFound": "写真が見つかりません","photoFileMissing": "写真ファイルが見つかりません",- "noChangesProvided": "適用できる変更がありません"+ "noChangesProvided": "適用できる変更がありません",+ "queueUnavailable": "タスクキューを利用できません",+ "reverseGeocodeQueued": "都市情報の再取得タスクをキューに追加しました",+ "reverseGeocodeFailed": "都市情報の再取得タスクの追加に失敗しました"},"errors": {"noSelection": "アップロードする写真を選択してください",diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex 7c75c200..cbdd3e3e 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -521,6 +521,7 @@"actions": {"reprocess": "重新处理","viewLivePhoto": "实况预览",+ "refreshLocation": "重新获取城市","delete": "删除","editMetadata": "编辑信息"},@@ -588,7 +589,10 @@"metadataUpdateFailed": "更新照片信息失败","photoNotFound": "找不到照片","photoFileMissing": "照片文件已丢失",- "noChangesProvided": "没有可应用的修改"+ "noChangesProvided": "没有可应用的修改",+ "queueUnavailable": "任务队列不可用",+ "reverseGeocodeQueued": "已加入重新获取城市任务",+ "reverseGeocodeFailed": "重新获取城市任务添加失败"},"errors": {"noSelection": "请选择要上传的照片",diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex 5e1c3de9..c469acee 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -464,6 +464,7 @@"actions": {"reprocess": "重新處理","viewLivePhoto": "實況相片預覽",+ "refreshLocation": "重新取得城市","delete": "刪除","editMetadata": "編輯資訊"},@@ -531,7 +532,10 @@"metadataUpdateFailed": "更新相片資訊失敗","photoNotFound": "找不到相片","photoFileMissing": "找不到相片檔案",- "noChangesProvided": "沒有可套用的變更"+ "noChangesProvided": "沒有可套用的變更",+ "queueUnavailable": "任務隊列不可用",+ "reverseGeocodeQueued": "已新增重新取得城市的任務",+ "reverseGeocodeFailed": "重新取得城市任務新增失敗"},"errors": {"noSelection": "請選擇相片進行上傳",diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex c210720a..2b96ad46 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -464,6 +464,7 @@"actions": {"reprocess": "重新處理","viewLivePhoto": "原況照片預覽",+ "refreshLocation": "重新取得城市","delete": "刪除","editMetadata": "編輯資訊"},@@ -531,7 +532,10 @@"metadataUpdateFailed": "更新照片資訊失敗","photoNotFound": "找不到照片","photoFileMissing": "找不到照片檔案",- "noChangesProvided": "沒有可套用的變更"+ "noChangesProvided": "沒有可套用的變更",+ "queueUnavailable": "任務佇列不可用",+ "reverseGeocodeQueued": "已新增重新取得城市的任務",+ "reverseGeocodeFailed": "重新取得城市任務新增失敗"},"errors": {"noSelection": "請選擇照片進行上傳",diff --git a/server/api/photos/locations/geocode.get.ts b/server/api/photos/locations/geocode.get.tsdeleted file mode 100644index 36ec2412..00000000--- a/server/api/photos/locations/geocode.get.ts+++ /dev/null@@ -1,83 +0,0 @@-import { isNotNull } from 'drizzle-orm'--export default eventHandler(async (event) => {- await requireUserSession(event)-- try {- // 获取统计信息:EXIF中有GPS坐标但数据库中缺少位置信息的照片- const photosWithExif = await useDB()- .select({- id: tables.photos.id,- exif: tables.photos.exif,- latitude: tables.photos.latitude,- longitude: tables.photos.longitude,- city: tables.photos.city,- country: tables.photos.country,- })- .from(tables.photos)- .where(isNotNull(tables.photos.exif))-- // 分析照片的GPS和位置信息状态- let totalWithGpsInExif = 0- let needsLocationReindex = 0- let needsGpsReindex = 0- let photosWithCity = 0-- for (const photo of photosWithExif) {- const exif = photo.exif as any- if (!exif) continue-- // 检查EXIF中是否有GPS数据- const hasGpsInExif =- (exif.GPSLatitude && exif.GPSLongitude) || exif.GPSCoordinates-- if (hasGpsInExif) {- totalWithGpsInExif++-- // 检查数据库中是否缺少GPS坐标(需要从EXIF重新提取)- if (!photo.latitude || !photo.longitude) {- needsGpsReindex++- }- // 检查是否缺少城市信息(需要地理编码)- else if (- !photo.city ||- !photo.country ||- photo.city === '' ||- photo.country === ''- ) {- needsLocationReindex++- }- // 已有完整信息- else {- photosWithCity++- }- }- }-- const needsReindex = needsGpsReindex + needsLocationReindex-- return {- statistics: {- totalPhotosWithGps: totalWithGpsInExif,- photosWithCity: photosWithCity,- photosNeedingReindex: needsReindex,- photosNeedingGpsReindex: needsGpsReindex,- photosNeedingLocationReindex: needsLocationReindex,- coveragePercentage:- totalWithGpsInExif > 0- ? ((photosWithCity / totalWithGpsInExif) * 100).toFixed(1)- : '0',- },- message:- needsReindex > 0- ? `发现 ${needsReindex} 张照片需要重新索引 (${needsGpsReindex} 张需要GPS重新提取, ${needsLocationReindex} 张需要城市信息重新索引)`- : '所有有GPS信息的照片都已完成索引',- }- } catch (error) {- logger.chrono.error('Failed to get reindex city statistics:', error)- throw createError({- statusCode: 500,- statusMessage: 'Failed to get statistics',- })- }-})diff --git a/server/api/photos/locations/geocode.post.ts b/server/api/photos/locations/geocode.post.tsdeleted file mode 100644index ab4c245c..00000000--- a/server/api/photos/locations/geocode.post.ts+++ /dev/null@@ -1,193 +0,0 @@-import { isNotNull, eq } from 'drizzle-orm'-import {- extractLocationFromGPS,- parseGPSCoordinates,-} from '~~/server/services/location/geocoding'--export default eventHandler(async (event) => {- await requireUserSession(event)-- const body = await readBody(event)- const { force = false } = body-- try {- // 查找EXIF中有GPS坐标但数据库中缺少完整位置信息的照片- const photosWithExif = await useDB()- .select({- id: tables.photos.id,- exif: tables.photos.exif,- latitude: tables.photos.latitude,- longitude: tables.photos.longitude,- city: tables.photos.city,- country: tables.photos.country,- locationName: tables.photos.locationName,- })- .from(tables.photos)- .where(isNotNull(tables.photos.exif))-- // 筛选需要处理的照片- const photosToUpdate: typeof photosWithExif = []-- for (const photo of photosWithExif) {- const exif = photo.exif as any- if (!exif) continue-- // 检查EXIF中是否有GPS数据- const hasGpsInExif =- (exif.GPSLatitude && exif.GPSLongitude) || exif.GPSCoordinates-- if (!hasGpsInExif) continue-- // 根据force参数决定处理条件- let shouldProcess = false-- if (force) {- // 强制重新索引所有有GPS的照片- shouldProcess = true- } else {- // 只处理缺少GPS坐标或城市信息的照片- const needsGpsReindex = !photo.latitude || !photo.longitude- const needsLocationReindex =- !photo.city ||- !photo.country ||- photo.city === '' ||- photo.country === ''- shouldProcess = needsGpsReindex || needsLocationReindex- }-- if (shouldProcess) {- photosToUpdate.push(photo)- }- }-- if (photosToUpdate.length === 0) {- return {- message: '没有需要重新索引的照片',- processed: 0,- updated: 0,- }- }-- logger.chrono.info(- `Found ${photosToUpdate.length} photos to reindex city information`,- )-- let processed = 0- let updated = 0- const errors: Array<{ photoId: string; error: string }> = []-- // 批量处理照片,添加延迟以避免API限制- for (const photo of photosToUpdate) {- try {- processed++-- logger.chrono.info(- `Processing photo ${photo.id} (${processed}/${photosToUpdate.length})`,- )-- const exif = photo.exif as any- let latitude = photo.latitude- let longitude = photo.longitude-- // 如果数据库中没有GPS坐标,从EXIF重新提取- if (!latitude || !longitude) {- const gpsCoords = parseGPSCoordinates(exif)- latitude = gpsCoords.latitude || null- longitude = gpsCoords.longitude || null-- if (!latitude || !longitude) {- logger.chrono.warn(- `No valid GPS coordinates found in EXIF for photo ${photo.id}`,- )- continue- }-- logger.chrono.info(- `Extracted GPS coordinates from EXIF: ${latitude}, ${longitude}`,- )- }-- // 重新获取地理位置信息- const locationInfo = await extractLocationFromGPS(latitude, longitude)-- if (locationInfo && (locationInfo.city || locationInfo.country)) {- // 只有当获取到新的位置信息时才更新- const shouldUpdate =- force ||- !photo.city ||- !photo.country ||- photo.city !== locationInfo.city ||- photo.country !== locationInfo.country ||- !photo.latitude ||- !photo.longitude-- if (shouldUpdate) {- await useDB()- .update(tables.photos)- .set({- latitude: latitude,- longitude: longitude,- city: locationInfo.city || photo.city,- country: locationInfo.country || photo.country,- locationName: locationInfo.locationName || photo.locationName,- })- .where(eq(tables.photos.id, photo.id))-- updated++-- logger.chrono.success(- `Updated photo ${photo.id}: ${latitude}, ${longitude} -> ${locationInfo.city}, ${locationInfo.country}`,- )- } else {- logger.chrono.info(- `Photo ${photo.id} already has up-to-date location info`,- )- }- } else {- logger.chrono.warn(- `No location info found for photo ${photo.id} at ${latitude}, ${longitude}`,- )- }-- // 添加延迟以遵守API速率限制(Nominatim要求至少1秒间隔)- if (processed < photosToUpdate.length) {- await new Promise((resolve) => setTimeout(resolve, 1100))- }- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Unknown error'- logger.chrono.error(`Failed to process photo ${photo.id}:`, error)- errors.push({- photoId: photo.id,- error: errorMessage,- })- }- }-- const result = {- message: `位置信息重新索引完成`,- processed,- updated,- errors: errors.length > 0 ? errors : undefined,- statistics: {- totalFound: photosToUpdate.length,- successRate:- processed > 0- ? (((processed - errors.length) / processed) * 100).toFixed(1) + '%'- : '0%',- },- }-- logger.chrono.success(- `Location reindexing completed: ${updated} photos updated out of ${processed} processed`,- )-- return result- } catch (error) {- logger.chrono.error('Failed to reindex location information:', error)- throw createError({- statusCode: 500,- statusMessage: 'Failed to reindex location information',- })- }-})diff --git a/server/api/photos/locations/index.get.ts b/server/api/photos/locations/index.get.tsdeleted file mode 100644index 2a154587..00000000--- a/server/api/photos/locations/index.get.ts+++ /dev/null@@ -1,55 +0,0 @@-import { eq, and, sql, desc } from 'drizzle-orm'--export default eventHandler(async (event) => {- await requireUserSession(event)-- const query = getQuery(event)- const { country, city, hasLocation } = query-- const whereConditions = []-- // 如果指定了只显示有位置信息的照片- if (hasLocation === 'true') {- whereConditions.push(sql`latitude IS NOT NULL AND longitude IS NOT NULL`)- }-- // 如果指定了国家筛选- if (country && typeof country === 'string') {- whereConditions.push(eq(tables.photos.country, country))- }-- // 如果指定了城市筛选- if (city && typeof city === 'string') {- whereConditions.push(eq(tables.photos.city, city))- }-- try {- const photos = await useDB()- .select({- id: tables.photos.id,- title: tables.photos.title,- thumbnailUrl: tables.photos.thumbnailUrl,- dateTaken: tables.photos.dateTaken,- latitude: tables.photos.latitude,- longitude: tables.photos.longitude,- country: tables.photos.country,- city: tables.photos.city,- locationName: tables.photos.locationName,- tags: tables.photos.tags,- })- .from(tables.photos)- .where(whereConditions.length > 0 ? and(...whereConditions) : undefined)- .orderBy(desc(tables.photos.dateTaken))-- return {- photos,- total: photos.length,- }- } catch (error) {- logger.chrono.error('Failed to fetch photos with location:', error)- throw createError({- statusCode: 500,- statusMessage: 'Failed to fetch photos',- })- }-})diff --git a/server/api/photos/locations/stats.get.ts b/server/api/photos/locations/stats.get.tsdeleted file mode 100644index b2c6332f..00000000--- a/server/api/photos/locations/stats.get.ts+++ /dev/null@@ -1,62 +0,0 @@-import { sql } from 'drizzle-orm'--export default eventHandler(async (event) => {- await requireUserSession(event)-- try {- // 获取有地理位置信息的照片总数- const photosWithLocationResult = await useDB()- .select({ count: sql<number>`count(*)` })- .from(tables.photos)- .where(sql`latitude IS NOT NULL AND longitude IS NOT NULL`)-- const photosWithLocation = photosWithLocationResult[0]?.count || 0-- // 获取总照片数- const totalPhotosResult = await useDB()- .select({ count: sql<number>`count(*)` })- .from(tables.photos)-- const totalPhotos = totalPhotosResult[0]?.count || 0-- // 获取按国家分组的统计- const countriesResult = await useDB()- .select({- country: tables.photos.country,- count: sql<number>`count(*)`- })- .from(tables.photos)- .where(sql`country IS NOT NULL`)- .groupBy(tables.photos.country)- .orderBy(sql`count(*) DESC`)-- // 获取按城市分组的统计- const citiesResult = await useDB()- .select({- city: tables.photos.city,- country: tables.photos.country,- count: sql<number>`count(*)`- })- .from(tables.photos)- .where(sql`city IS NOT NULL`)- .groupBy(tables.photos.city, tables.photos.country)- .orderBy(sql`count(*) DESC`)- .limit(20) // 只返回前20个最常见的城市-- return {- statistics: {- totalPhotos,- photosWithLocation,- locationCoverage: totalPhotos > 0 ? (photosWithLocation / totalPhotos * 100).toFixed(1) : '0',- },- countries: countriesResult,- cities: citiesResult,- }- } catch (error) {- logger.chrono.error('Failed to fetch location statistics:', error)- throw createError({- statusCode: 500,- statusMessage: 'Failed to fetch location statistics',- })- }-})diff --git a/server/api/queue/add-task.post.ts b/server/api/queue/add-task.post.tsindex a13a9019..66fa0f0e 100644--- a/server/api/queue/add-task.post.ts+++ b/server/api/queue/add-task.post.ts@@ -4,13 +4,27 @@ export default defineEventHandler(async (event) => {await requireUserSession(event)try {+ const payloadSchema = z.discriminatedUnion('type', [+ z.object({+ type: z.literal('photo'),+ storageKey: z.string().nonempty(),+ }),+ z.object({+ type: z.literal('live-photo-video'),+ storageKey: z.string().nonempty(),+ }),+ z.object({+ type: z.literal('photo-reverse-geocoding'),+ photoId: z.string().min(1),+ latitude: z.number().min(-90).max(90).optional(),+ longitude: z.number().min(-180).max(180).optional(),+ }),+ ])+const { payload, priority, maxAttempts } = await readValidatedBody(event,z.object({- payload: z.object({- type: z.enum(['photo', 'live-photo-video']).default('photo'),- storageKey: z.string().nonempty(),- }),+ payload: payloadSchema,priority: z.number().min(0).max(9).optional().default(0),maxAttempts: z.number().min(1).max(5).optional().default(3),}).parse,@@ -34,11 +48,7 @@ export default defineEventHandler(async (event) => {success: true,taskId,message: 'Task added to queue successfully',- payload: {- storageKey: payload.storageKey,- priority,- maxAttempts,- },+ payload,}} catch (error: any) {if (error.statusCode) {diff --git a/server/api/queue/add-tasks.post.ts b/server/api/queue/add-tasks.post.tsindex ff654b7e..9a4933b1 100644--- a/server/api/queue/add-tasks.post.ts+++ b/server/api/queue/add-tasks.post.ts@@ -4,6 +4,23 @@ export default defineEventHandler(async (event) => {await requireUserSession(event)try {+ const payloadSchema = z.discriminatedUnion('type', [+ z.object({+ type: z.literal('photo'),+ storageKey: z.string().nonempty(),+ }),+ z.object({+ type: z.literal('live-photo-video'),+ storageKey: z.string().nonempty(),+ }),+ z.object({+ type: z.literal('photo-reverse-geocoding'),+ photoId: z.string().min(1),+ latitude: z.number().min(-90).max(90).optional(),+ longitude: z.number().min(-180).max(180).optional(),+ }),+ ])+const { tasks, defaultPriority, defaultMaxAttempts } =await readValidatedBody(event,@@ -11,10 +28,7 @@ export default defineEventHandler(async (event) => {tasks: z.array(z.object({- payload: z.object({- type: z.enum(['photo', 'live-photo-video']).default('photo'),- storageKey: z.string().nonempty(),- }),+ payload: payloadSchema,priority: z.number().min(0).max(9).optional(),maxAttempts: z.number().min(1).max(5).optional(),}),@@ -47,18 +61,13 @@ export default defineEventHandler(async (event) => {maxAttempts: task.maxAttempts ?? defaultMaxAttempts,})- results.push({- index: i,- taskId,- storageKey: task.payload.storageKey,- success: true,- })+ results.push({ index: i, taskId, payload: task.payload, success: true })} catch (error) {const errorMessage =error instanceof Error ? error.message : `Task ${i}: Unknown error`errors.push({index: i,- storageKey: task.payload?.storageKey || 'unknown',+ payload: task.payload,error: errorMessage,success: false,})