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(dashbard): add photo partial exif editing support (#103)

Timothy Yina6b70961668d
diff --git a/app/components/map/LocationPicker.vue b/app/components/map/LocationPicker.vue
new file mode 100644
index 00000000..fd95f6be
--- /dev/null
+++ b/app/components/map/LocationPicker.vue
@@ -0,0 +1,140 @@
+<script lang="ts" setup>
+import { onBeforeUnmount, ref, watch } from 'vue'
+import type { MapInstance } from '~~/shared/types/map'
+
+const props = withDefaults(
+ defineProps<{
+ modelValue?: { latitude: number; longitude: number } | null
+ zoom?: number
+ class?: string
+ }>(),
+ {
+ modelValue: null,
+ zoom: 4,
+ class: undefined,
+ },
+)
+
+const emit = defineEmits<{
+ 'update:modelValue': [{ latitude: number; longitude: number } | null]
+ pick: [{ latitude: number; longitude: number }]
+}>()
+
+const mapInstance = ref<MapInstance | null>(null)
+const markerCoordinates = ref<[number, number] | null>(null)
+const { locale } = useI18n()
+
+let clickHandler: ((event: any) => void) | null = null
+
+const syncFromProps = (value: { latitude: number; longitude: number } | null) => {
+ if (value) {
+ markerCoordinates.value = [value.longitude, value.latitude]
+ if (mapInstance.value) {
+ const map: any = mapInstance.value
+ map.flyTo?.({
+ center: markerCoordinates.value,
+ zoom: Math.max(props.zoom ?? 4, 4),
+ essential: true,
+ })
+ }
+ } else {
+ markerCoordinates.value = null
+ }
+}
+
+watch(
+ () => props.modelValue,
+ (value) => {
+ syncFromProps(value ?? null)
+ },
+ { immediate: true },
+)
+
+const updateValue = (
+ latitude: number,
+ longitude: number,
+ shouldEmitPick = true,
+) => {
+ markerCoordinates.value = [longitude, latitude]
+ emit('update:modelValue', { latitude, longitude })
+ if (shouldEmitPick) {
+ emit('pick', { latitude, longitude })
+ }
+}
+
+const handleMapClick = (event: any) => {
+ const point =
+ event?.lngLat ||
+ event?.latlng ||
+ (Array.isArray(event) ? { lng: event[0], lat: event[1] } : null)
+ if (!point) {
+ return
+ }
+ const latitude =
+ typeof point.lat === 'number' ? point.lat : point.latitude ?? point[1]
+ const longitude =
+ typeof point.lng === 'number' ? point.lng : point.longitude ?? point[0]
+ if (typeof latitude !== 'number' || typeof longitude !== 'number') {
+ return
+ }
+ updateValue(latitude, longitude)
+}
+
+const onMapLoad = (map: MapInstance) => {
+ mapInstance.value = map
+
+ if (markerCoordinates.value) {
+ const anyMap: any = map
+ anyMap.setCenter?.(markerCoordinates.value)
+ anyMap.setZoom?.(Math.max(props.zoom ?? 4, 4))
+ }
+
+ const anyMap: any = map
+ if (typeof anyMap.on === 'function') {
+ clickHandler = (event: any) => handleMapClick(event)
+ anyMap.on('click', clickHandler)
+ }
+}
+
+onBeforeUnmount(() => {
+ if (mapInstance.value && clickHandler) {
+ const anyMap: any = mapInstance.value
+ if (typeof anyMap.off === 'function') {
+ anyMap.off('click', clickHandler)
+ }
+ }
+})
+</script>
+
+<template>
+ <div :class="['relative w-full h-64 rounded-xl overflow-hidden', $props.class]">
+ <MapProvider
+ class="w-full h-full"
+ :map-id="'photo-location-picker'"
+ :center="markerCoordinates ?? undefined"
+ :zoom="markerCoordinates ? Math.max($props.zoom ?? 4, 4) : $props.zoom ?? 2"
+ :interactive="true"
+ :language="locale"
+ @load="onMapLoad"
+ >
+ <MapProviderMarker
+ v-if="markerCoordinates"
+ :lnglat="markerCoordinates"
+ >
+ <template #marker>
+ <div class="relative">
+ <div class="absolute inset-0 animate-ping rounded-full bg-primary/40" />
+ <div class="relative size-4 rounded-full bg-primary border-2 border-white shadow" />
+ </div>
+ </template>
+ </MapProviderMarker>
+ </MapProvider>
+
+ <div
+ v-if="!markerCoordinates"
+ class="absolute inset-0 pointer-events-none flex items-center justify-center text-sm text-neutral-600 dark:text-neutral-400"
+ >
+ <slot name="empty" />
+ </div>
+ </div>
+</template>
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index 03d646e7..f48afd8c 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -1,5 +1,5 @@
<script lang="ts" setup>
-import type { TableColumn } from '@nuxt/ui'
+import type { FormSubmitEvent, TableColumn } from '@nuxt/ui'
import type { Photo, PipelineQueueItem } from '~~/server/utils/db'
import { h, resolveComponent } from 'vue'
import { Icon, UBadge } from '#components'
@@ -83,6 +83,120 @@ interface UploadingFile {
const uploadingFiles = ref<Map<string, UploadingFile>>(new Map())
+interface EditFormState {
+ title: string
+ description: string
+ tags: string[]
+}
+
+const editingPhoto = ref<Photo | null>(null)
+const isEditModalOpen = ref(false)
+const isSavingMetadata = ref(false)
+
+const editFormState = reactive<EditFormState>({
+ title: '',
+ description: '',
+ tags: [],
+})
+
+const originalMetadata = ref<{
+ title: string
+ description: string
+ tags: string[]
+ location: { latitude: number; longitude: number } | null
+}>({
+ title: '',
+ description: '',
+ tags: [],
+ location: null,
+})
+
+const locationSelection = ref<{ latitude: number; longitude: number } | null>(null)
+const locationTouched = ref(false)
+
+const normalizeTagList = (tags: string[]): string[] => {
+ const seen = new Set<string>()
+ const normalized: string[] = []
+ for (const tag of tags) {
+ const trimmed = tag.trim()
+ if (!trimmed) continue
+ const key = trimmed.toLowerCase()
+ if (seen.has(key)) continue
+ seen.add(key)
+ normalized.push(trimmed)
+ }
+ return normalized
+}
+
+const areTagListsEqual = (a: string[], b: string[]): boolean => {
+ if (a.length !== b.length) {
+ return false
+ }
+ return a.every((tag, index) => tag === b[index])
+}
+
+const tagsModel = computed<string[]>({
+ get: () => editFormState.tags,
+ set: (value) => {
+ const next = Array.isArray(value) ? normalizeTagList(value) : []
+ if (!areTagListsEqual(editFormState.tags, next)) {
+ editFormState.tags = next
+ }
+ },
+})
+
+const normalizedTitle = computed(() => editFormState.title.trim())
+const normalizedDescription = computed(() => editFormState.description.trim())
+
+const tagsChanged = computed(() => {
+ const current = editFormState.tags
+ const original = originalMetadata.value.tags
+ return !areTagListsEqual(current, original)
+})
+
+const titleChanged = computed(
+ () => normalizedTitle.value !== originalMetadata.value.title,
+)
+const descriptionChanged = computed(
+ () => normalizedDescription.value !== originalMetadata.value.description,
+)
+
+const locationChanged = computed(() => {
+ if (!locationTouched.value) {
+ return false
+ }
+ const current = locationSelection.value
+ const original = originalMetadata.value.location
+ if (!current && !original) {
+ return false
+ }
+ if (!current || !original) {
+ return true
+ }
+ return (
+ Math.abs(current.latitude - original.latitude) > 1e-6 ||
+ Math.abs(current.longitude - original.longitude) > 1e-6
+ )
+})
+
+const isMetadataDirty = computed(
+ () =>
+ titleChanged.value ||
+ descriptionChanged.value ||
+ tagsChanged.value ||
+ locationChanged.value,
+)
+
+const formattedCoordinates = computed(() => {
+ if (!locationSelection.value) {
+ return null
+ }
+ return {
+ latitude: locationSelection.value.latitude.toFixed(6),
+ longitude: locationSelection.value.longitude.toFixed(6),
+ }
+})
+
const uploadImage = async (file: File, existingFileId?: string) => {
const fileName = file.name
const fileId = existingFileId || `${Date.now()}-${fileName}`
@@ -286,6 +400,23 @@ const openUploadSlideover = () => {
isUploadSlideoverOpen.value = true
}
+watch(isEditModalOpen, (open) => {
+ if (!open) {
+ editingPhoto.value = null
+ editFormState.title = ''
+ editFormState.description = ''
+ editFormState.tags = []
+ originalMetadata.value = {
+ title: '',
+ description: '',
+ tags: [],
+ location: null,
+ }
+ locationSelection.value = null
+ locationTouched.value = false
+ }
+})
+
// 表格多选状态
const rowSelection = ref({})
const table: any = useTemplateRef('table')
@@ -874,6 +1005,127 @@ const handleUpload = async () => {
isUploadSlideoverOpen.value = false
}
+const openMetadataEditor = (photo: Photo) => {
+ const initialTitle = photo.title?.trim() ?? ''
+ const initialDescription = photo.description?.trim() ?? ''
+ const initialTags = normalizeTagList(photo.tags ?? [])
+ const hasCoordinates =
+ typeof photo.latitude === 'number' && typeof photo.longitude === 'number'
+
+ editingPhoto.value = photo
+ editFormState.title = initialTitle
+ editFormState.description = initialDescription
+ editFormState.tags = [...initialTags]
+
+ const initialLocation =
+ hasCoordinates
+ ? {
+ latitude: photo.latitude as number,
+ longitude: photo.longitude as number,
+ }
+ : null
+
+ originalMetadata.value = {
+ title: initialTitle,
+ description: initialDescription,
+ tags: [...initialTags],
+ location: initialLocation ? { ...initialLocation } : null,
+ }
+
+ locationSelection.value = initialLocation ? { ...initialLocation } : null
+ locationTouched.value = false
+
+ isEditModalOpen.value = true
+}
+
+const handleLocationPick = () => {
+ locationTouched.value = true
+}
+
+const clearSelectedLocation = () => {
+ locationSelection.value = null
+ locationTouched.value = true
+}
+
+const saveMetadataChanges = async () => {
+ if (!editingPhoto.value || !isMetadataDirty.value) {
+ return
+ }
+
+ isSavingMetadata.value = true
+ try {
+ const payload: {
+ title?: string
+ description?: string
+ tags?: string[]
+ location?: { latitude: number; longitude: number } | null
+ } = {}
+
+ if (titleChanged.value) {
+ payload.title = normalizedTitle.value
+ }
+
+ if (descriptionChanged.value) {
+ payload.description = normalizedDescription.value
+ }
+
+ if (tagsChanged.value) {
+ payload.tags = [...editFormState.tags]
+ }
+
+ if (locationChanged.value) {
+ payload.location = locationSelection.value
+ ? {
+ latitude: locationSelection.value.latitude,
+ longitude: locationSelection.value.longitude,
+ }
+ : null
+ }
+
+ if (Object.keys(payload).length === 0) {
+ isEditModalOpen.value = false
+ return
+ }
+
+ await $fetch(`/api/photos/${editingPhoto.value.id}`, {
+ method: 'PUT',
+ body: payload,
+ })
+
+ toast.add({
+ title: $t('dashboard.photos.messages.metadataUpdateSuccess'),
+ description: '',
+ color: 'success',
+ })
+
+ await refresh()
+ isEditModalOpen.value = false
+ } catch (error: any) {
+ console.error('更新照片信息失败:', error)
+ const message =
+ error?.data?.statusMessage ||
+ error?.statusMessage ||
+ error?.message ||
+ $t('dashboard.photos.messages.metadataUpdateFailed')
+
+ toast.add({
+ title: $t('dashboard.photos.messages.metadataUpdateFailed'),
+ description: message,
+ color: 'error',
+ })
+ } finally {
+ isSavingMetadata.value = false
+ }
+}
+
+const handleEditSubmit = async (event: FormSubmitEvent<EditFormState>) => {
+ event.preventDefault()
+ if (!isMetadataDirty.value) {
+ return
+ }
+ await saveMetadataChanges()
+}
+
// LivePhoto 相关操作
const handleViewLivePhoto = async (photoId: string) => {
try {
@@ -1518,6 +1770,13 @@ onUnmounted(() => {
}"
:items="[
[
+ {
+ label: $t('dashboard.photos.actions.editMetadata'),
+ icon: 'tabler:pencil',
+ onSelect() {
+ openMetadataEditor(row.original)
+ },
+ },
{
label: $t('dashboard.photos.actions.reprocess'),
icon: 'tabler:refresh',
@@ -1595,6 +1854,116 @@ onUnmounted(() => {
</div>
</div>
+ <UModal v-model:open="isEditModalOpen">
+ <template #content>
+ <div class="p-6 space-y-6">
+ <div class="space-y-1">
+ <h2 class="text-lg font-semibold text-neutral-800 dark:text-neutral-100">
+ {{ $t('dashboard.photos.editModal.title') }}
+ </h2>
+ <p class="text-sm text-neutral-500 dark:text-neutral-400">
+ {{ $t('dashboard.photos.editModal.description') }}
+ </p>
+ <p
+ v-if="editingPhoto"
+ class="text-xs text-neutral-500 dark:text-neutral-500"
+ >
+ {{ editingPhoto.title || editingPhoto.id }}
+ </p>
+ </div>
+
+ <UForm :state="editFormState" class="space-y-5" @submit="handleEditSubmit">
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.title')"
+ name="title"
+ >
+ <UInput v-model="editFormState.title" class="w-full" />
+ </UFormField>
+
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.description')"
+ name="description"
+ >
+ <UTextarea v-model="editFormState.description" :rows="3" class="w-full" />
+ </UFormField>
+
+ <div class="space-y-2">
+ <UFormField
+ :label="$t('dashboard.photos.editModal.fields.tags')"
+ name="tags"
+ >
+ <UInputTags v-model="tagsModel" class="w-full" />
+ </UFormField>
+ <p class="text-xs text-neutral-500 dark:text-neutral-400">
+ {{ $t('dashboard.photos.editModal.fields.tagsHint') }}
+ </p>
+ </div>
+
+ <div class="space-y-3">
+ <div class="flex items-center justify-between">
+ <label class="text-sm font-medium text-neutral-700 dark:text-neutral-200">
+ {{ $t('dashboard.photos.editModal.fields.location') }}
+ </label>
+ <UButton
+ v-if="locationSelection"
+ variant="ghost"
+ color="neutral"
+ size="xs"
+ icon="tabler:map-off"
+ @click.prevent="clearSelectedLocation"
+ >
+ {{ $t('dashboard.photos.editModal.fields.clearLocation') }}
+ </UButton>
+ </div>
+
+ <MapLocationPicker
+ v-model="locationSelection"
+ class="border border-neutral-200 dark:border-neutral-800"
+ @pick="handleLocationPick"
+ >
+ <template #empty>
+ <span
+ class="px-3 py-2 rounded-full bg-white/80 text-neutral-600 dark:bg-neutral-900/80 dark:text-neutral-200 shadow"
+ >
+ {{ $t('dashboard.photos.editModal.fields.locationHint') }}
+ </span>
+ </template>
+ </MapLocationPicker>
+
+ <div class="text-xs text-neutral-500 dark:text-neutral-400 flex items-center gap-2">
+ <span>{{ $t('dashboard.photos.editModal.fields.coordinates') }}:</span>
+ <span v-if="formattedCoordinates">
+ {{ formattedCoordinates.latitude }},
+ {{ formattedCoordinates.longitude }}
+ </span>
+ <span v-else>
+ {{ $t('dashboard.photos.editModal.fields.noLocation') }}
+ </span>
+ </div>
+ </div>
+
+ <div class="flex items-center justify-end gap-2 pt-4 border-t border-neutral-200 dark:border-neutral-800">
+ <UButton
+ variant="ghost"
+ color="neutral"
+ @click.prevent="isEditModalOpen = false"
+ >
+ {{ $t('dashboard.photos.editModal.actions.cancel') }}
+ </UButton>
+ <UButton
+ type="submit"
+ :loading="isSavingMetadata"
+ :disabled="!isMetadataDirty || isSavingMetadata"
+ icon="tabler:device-floppy"
+ >
+ {{ $t('dashboard.photos.editModal.actions.save') }}
+ </UButton>
+ </div>
+ </UForm>
+ </div>
+ </template>
+ </UModal>
+
<UModal v-model:open="isDeleteConfirmOpen">
<template #content>
<div class="p-6 space-y-4">
diff --git a/app/pages/dashboard/queue.vue b/app/pages/dashboard/queue.vue
index 43205abe..c45d3a63 100644
--- a/app/pages/dashboard/queue.vue
+++ b/app/pages/dashboard/queue.vue
@@ -195,6 +195,10 @@ const typeOptions = [
label: $t('dashboard.queue.types.live-photo-video'),
value: 'live-photo-video',
},
+ {
+ label: $t('dashboard.queue.types.photo-reverse-geocoding'),
+ value: 'photo-reverse-geocoding',
+ },
]
// 表格列定义
diff --git a/i18n/locales/en.json b/i18n/locales/en.json
index 0c511716..fa4b040a 100644
--- a/i18n/locales/en.json
+++ b/i18n/locales/en.json
@@ -521,7 +521,8 @@
"actions": {
"reprocess": "Reprocess",
"viewLivePhoto": "Live Photo Preview",
- "delete": "Delete"
+ "delete": "Delete",
+ "editMetadata": "Edit Metadata"
},
"selection": {
"selected": "{count} / {total} rows selected",
@@ -582,7 +583,12 @@
"batchReprocessFailed": "Batch reprocess failed",
"reprocessFailed": "Failed to reprocess photo",
"livePhotoNotFound": "Not a Live Photo",
- "livePhotoLoadError": "Unable to load Live Photo information"
+ "livePhotoLoadError": "Unable to load Live Photo information",
+ "metadataUpdateSuccess": "Photo metadata updated",
+ "metadataUpdateFailed": "Failed to update photo metadata",
+ "photoNotFound": "Photo not found",
+ "photoFileMissing": "Photo file is missing",
+ "noChangesProvided": "No changes to apply"
},
"errors": {
"noSelection": "Please select photos to upload",
@@ -612,6 +618,25 @@
"taskCleared": "Completed tasks cleared",
"allTasksCleared": "All upload tasks cleared",
"tasksCleared": "{count} task(s) cleared"
+ },
+ "editModal": {
+ "title": "Edit photo details",
+ "description": "Update the title, description, tags and shooting location.",
+ "fields": {
+ "title": "Title",
+ "description": "Description",
+ "tags": "Tags",
+ "tagsHint": "Press Enter to add each tag.",
+ "location": "Location",
+ "locationHint": "Click on the map to set the shooting location.",
+ "clearLocation": "Clear location",
+ "coordinates": "Coordinates",
+ "noLocation": "No location selected"
+ },
+ "actions": {
+ "cancel": "Cancel",
+ "save": "Save changes"
+ }
}
},
"albums": {
@@ -775,7 +800,8 @@
},
"types": {
"photo": "Photo Processing",
- "live-photo-video": "LivePhoto Video"
+ "live-photo-video": "LivePhoto Video",
+ "photo-reverse-geocoding": "Photo Reverse Geocoding"
},
"stages": {
"preprocessing": "Preprocessing",
@@ -804,4 +830,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/i18n/locales/ja.json b/i18n/locales/ja.json
index eaf5c03e..2a642c66 100644
--- a/i18n/locales/ja.json
+++ b/i18n/locales/ja.json
@@ -464,7 +464,8 @@
"actions": {
"reprocess": "再処理",
"viewLivePhoto": "ライブフォトプレビュー",
- "delete": "削除"
+ "delete": "削除",
+ "editMetadata": "メタデータを編集"
},
"selection": {
"selected": "{count} / {total}行選択済み",
@@ -525,7 +526,12 @@
"batchReprocessFailed": "一括再処理に失敗しました",
"reprocessFailed": "写真の再処理に失敗しました",
"livePhotoNotFound": "ライブフォトではありません",
- "livePhotoLoadError": "ライブフォト情報を読み込めません"
+ "livePhotoLoadError": "ライブフォト情報を読み込めません",
+ "metadataUpdateSuccess": "写真のメタデータを更新しました",
+ "metadataUpdateFailed": "写真のメタデータを更新できませんでした",
+ "photoNotFound": "写真が見つかりません",
+ "photoFileMissing": "写真ファイルが見つかりません",
+ "noChangesProvided": "適用できる変更がありません"
},
"errors": {
"noSelection": "アップロードする写真を選択してください",
@@ -555,6 +561,25 @@
"taskCleared": "完了したタスクをクリアしました",
"allTasksCleared": "すべてのアップロードタスクをクリアしました",
"tasksCleared": "{count}個のタスクをクリアしました"
+ },
+ "editModal": {
+ "title": "写真情報を編集",
+ "description": "タイトル・説明・タグ・撮影場所を更新します。",
+ "fields": {
+ "title": "タイトル",
+ "description": "説明",
+ "tags": "タグ",
+ "tagsHint": "タグを入力し、Enter キーで追加してください。",
+ "location": "撮影場所",
+ "locationHint": "地図をクリックして撮影場所を選択してください。",
+ "clearLocation": "位置情報をクリア",
+ "coordinates": "座標",
+ "noLocation": "位置情報が未設定です"
+ },
+ "actions": {
+ "cancel": "キャンセル",
+ "save": "変更を保存"
+ }
}
},
"albums": {
@@ -718,7 +743,8 @@
},
"types": {
"photo": "写真処理",
- "live-photo-video": "LivePhoto動画"
+ "live-photo-video": "LivePhoto動画",
+ "photo-reverse-geocoding": "写真の逆ジオコーディング"
},
"stages": {
"preprocessing": "前処理",
@@ -747,4 +773,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.json
index 05fed86e..7c75c200 100644
--- a/i18n/locales/zh-Hans.json
+++ b/i18n/locales/zh-Hans.json
@@ -521,7 +521,8 @@
"actions": {
"reprocess": "重新处理",
"viewLivePhoto": "实况预览",
- "delete": "删除"
+ "delete": "删除",
+ "editMetadata": "编辑信息"
},
"selection": {
"selected": "{count} / {total} 行已选择",
@@ -582,7 +583,12 @@
"batchReprocessFailed": "批量重新处理失败",
"reprocessFailed": "重新处理失败",
"livePhotoNotFound": "不是 Live Photo",
- "livePhotoLoadError": "无法获取 Live Photo 信息"
+ "livePhotoLoadError": "无法获取 Live Photo 信息",
+ "metadataUpdateSuccess": "照片信息已更新",
+ "metadataUpdateFailed": "更新照片信息失败",
+ "photoNotFound": "找不到照片",
+ "photoFileMissing": "照片文件已丢失",
+ "noChangesProvided": "没有可应用的修改"
},
"errors": {
"noSelection": "请选择要上传的照片",
@@ -612,6 +618,25 @@
"taskCleared": "已完成的任务清理完成",
"allTasksCleared": "已清除全部上传任务",
"tasksCleared": "已清除 {count} 个任务"
+ },
+ "editModal": {
+ "title": "编辑照片信息",
+ "description": "更新标题、描述、标签和拍摄位置。",
+ "fields": {
+ "title": "标题",
+ "description": "描述",
+ "tags": "标签",
+ "tagsHint": "按下 Enter 键添加每个标签。",
+ "location": "拍摄位置",
+ "locationHint": "点击地图选择或更新拍摄位置。",
+ "clearLocation": "清除位置",
+ "coordinates": "坐标",
+ "noLocation": "未选择位置"
+ },
+ "actions": {
+ "cancel": "取消",
+ "save": "保存更改"
+ }
}
},
"albums": {
@@ -775,7 +800,8 @@
},
"types": {
"photo": "照片处理",
- "live-photo-video": "LivePhoto视频"
+ "live-photo-video": "LivePhoto视频",
+ "photo-reverse-geocoding": "照片逆地理编码"
},
"stages": {
"preprocessing": "预处理",
diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.json
index ff20e187..5e1c3de9 100644
--- a/i18n/locales/zh-Hant-HK.json
+++ b/i18n/locales/zh-Hant-HK.json
@@ -464,7 +464,8 @@
"actions": {
"reprocess": "重新處理",
"viewLivePhoto": "實況相片預覽",
- "delete": "刪除"
+ "delete": "刪除",
+ "editMetadata": "編輯資訊"
},
"selection": {
"selected": "已選擇 {count} / {total} 列",
@@ -525,7 +526,12 @@
"batchReprocessFailed": "批量重新處理失敗",
"reprocessFailed": "重新處理相片失敗",
"livePhotoNotFound": "不是實況相片",
- "livePhotoLoadError": "無法載入實況相片資料"
+ "livePhotoLoadError": "無法載入實況相片資料",
+ "metadataUpdateSuccess": "相片資訊已更新",
+ "metadataUpdateFailed": "更新相片資訊失敗",
+ "photoNotFound": "找不到相片",
+ "photoFileMissing": "找不到相片檔案",
+ "noChangesProvided": "沒有可套用的變更"
},
"errors": {
"noSelection": "請選擇相片進行上傳",
@@ -555,6 +561,25 @@
"taskCleared": "已清除已完成的任務",
"allTasksCleared": "已清除所有上傳任務",
"tasksCleared": "已清除 {count} 個任務"
+ },
+ "editModal": {
+ "title": "編輯相片資訊",
+ "description": "更新標題、描述、標籤與拍攝位置。",
+ "fields": {
+ "title": "標題",
+ "description": "描述",
+ "tags": "標籤",
+ "tagsHint": "按 Enter 鍵新增每個標籤。",
+ "location": "拍攝位置",
+ "locationHint": "點擊地圖選擇或更新拍攝位置。",
+ "clearLocation": "清除位置",
+ "coordinates": "座標",
+ "noLocation": "未選擇位置"
+ },
+ "actions": {
+ "cancel": "取消",
+ "save": "儲存變更"
+ }
}
},
"albums": {
@@ -718,7 +743,8 @@
},
"types": {
"photo": "照片處理",
- "live-photo-video": "LivePhoto視頻"
+ "live-photo-video": "LivePhoto視頻",
+ "photo-reverse-geocoding": "照片逆地理編碼"
},
"stages": {
"preprocessing": "預處理",
@@ -747,4 +773,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.json
index db45a696..c210720a 100644
--- a/i18n/locales/zh-Hant-TW.json
+++ b/i18n/locales/zh-Hant-TW.json
@@ -464,7 +464,8 @@
"actions": {
"reprocess": "重新處理",
"viewLivePhoto": "原況照片預覽",
- "delete": "刪除"
+ "delete": "刪除",
+ "editMetadata": "編輯資訊"
},
"selection": {
"selected": "已選擇 {count} / {total} 列",
@@ -525,7 +526,12 @@
"batchReprocessFailed": "批量重新處理失敗",
"reprocessFailed": "重新處理照片失敗",
"livePhotoNotFound": "不是原況照片",
- "livePhotoLoadError": "無法載入原況照片資訊"
+ "livePhotoLoadError": "無法載入原況照片資訊",
+ "metadataUpdateSuccess": "照片資訊已更新",
+ "metadataUpdateFailed": "更新照片資訊失敗",
+ "photoNotFound": "找不到照片",
+ "photoFileMissing": "找不到照片檔案",
+ "noChangesProvided": "沒有可套用的變更"
},
"errors": {
"noSelection": "請選擇照片進行上傳",
@@ -555,6 +561,25 @@
"taskCleared": "已清除已完成的任務",
"allTasksCleared": "已清除所有上傳任務",
"tasksCleared": "已清除 {count} 個任務"
+ },
+ "editModal": {
+ "title": "編輯照片資訊",
+ "description": "更新標題、描述、標籤與拍攝位置。",
+ "fields": {
+ "title": "標題",
+ "description": "描述",
+ "tags": "標籤",
+ "tagsHint": "按 Enter 鍵新增每個標籤。",
+ "location": "拍攝位置",
+ "locationHint": "點擊地圖選擇或更新拍攝位置。",
+ "clearLocation": "清除位置",
+ "coordinates": "座標",
+ "noLocation": "未選擇位置"
+ },
+ "actions": {
+ "cancel": "取消",
+ "save": "儲存變更"
+ }
}
},
"albums": {
@@ -718,7 +743,8 @@
},
"types": {
"photo": "照片處理",
- "live-photo-video": "LivePhoto影片"
+ "live-photo-video": "LivePhoto影片",
+ "photo-reverse-geocoding": "照片逆地理編碼"
},
"stages": {
"preprocessing": "預處理",
@@ -747,4 +773,4 @@
}
}
}
-}
\ No newline at end of file
+}
diff --git a/server/api/photos/[photoId]/index.put.ts b/server/api/photos/[photoId]/index.put.ts
new file mode 100644
index 00000000..db634cbf
--- /dev/null
+++ b/server/api/photos/[photoId]/index.put.ts
@@ -0,0 +1,262 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { z } from 'zod'
+import { exiftool } from 'exiftool-vendored'
+import { eq } from 'drizzle-orm'
+
+import { extractExifData } from '~~/server/services/image/exif'
+import { tables, useDB } from '~~/server/utils/db'
+import { useStorageProvider } from '~~/server/utils/useStorageProvider'
+
+const paramsSchema = z.object({
+ photoId: z.string().min(1),
+})
+
+const bodySchema = z.object({
+ title: z.string().trim().max(512).optional(),
+ description: z.string().trim().max(2000).optional(),
+ tags: z.array(z.string().trim().max(128)).max(64).optional(),
+ location: z
+ .union([
+ z.object({
+ latitude: z.number().min(-90).max(90),
+ longitude: z.number().min(-180).max(180),
+ }),
+ z.null(),
+ ])
+ .optional(),
+})
+
+const normalizeTags = (tags: string[] | undefined) => {
+ if (!tags) return undefined
+ const seen = new Set<string>()
+ const normalized: string[] = []
+ for (const rawTag of tags) {
+ const trimmed = rawTag.trim()
+ if (!trimmed) continue
+ const key = trimmed.toLowerCase()
+ if (seen.has(key)) continue
+ seen.add(key)
+ normalized.push(trimmed)
+ }
+ return normalized
+}
+
+export default eventHandler(async (event) => {
+ await requireUserSession(event)
+
+ const t = await useTranslation(event)
+ const { photoId } = paramsSchema.parse(event.context.params ?? {})
+ const payload = bodySchema.parse(await readBody(event))
+
+ if (
+ payload.title === undefined &&
+ payload.description === undefined &&
+ payload.tags === undefined &&
+ payload.location === undefined
+ ) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: t('dashboard.photos.messages.noChangesProvided'),
+ })
+ }
+
+ const db = useDB()
+ const photo = await db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ if (!photo) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: t('dashboard.photos.messages.photoNotFound'),
+ })
+ }
+
+ if (!photo.storageKey) {
+ throw createError({
+ statusCode: 400,
+ statusMessage: t('dashboard.photos.messages.noStorageKey'),
+ })
+ }
+
+ const { storageProvider } = useStorageProvider(event)
+ const originalBuffer = await storageProvider.get(photo.storageKey)
+
+ if (!originalBuffer) {
+ throw createError({
+ statusCode: 404,
+ statusMessage: t('dashboard.photos.messages.photoFileMissing'),
+ })
+ }
+
+ const normalizedTitle =
+ payload.title !== undefined ? payload.title.trim() : undefined
+ const normalizedDescription =
+ payload.description !== undefined ? payload.description.trim() : undefined
+ const normalizedTags = normalizeTags(payload.tags)
+ let pendingReverseGeocode:
+ | {
+ latitude: number
+ longitude: number
+ }
+ | null = null
+
+ const exifUpdates: Record<string, any> = {}
+
+ if (normalizedTitle !== undefined) {
+ const titleValue = normalizedTitle.length > 0 ? normalizedTitle : null
+ exifUpdates.Title = titleValue
+ exifUpdates.XPTitle = titleValue
+ }
+
+ if (normalizedDescription !== undefined) {
+ const descriptionValue =
+ normalizedDescription.length > 0 ? normalizedDescription : null
+ exifUpdates.Description = descriptionValue
+ exifUpdates.ImageDescription = descriptionValue
+ exifUpdates.CaptionAbstract = descriptionValue
+ exifUpdates.XPComment = descriptionValue
+ exifUpdates.UserComment = descriptionValue
+ }
+
+ if (normalizedTags !== undefined) {
+ const tagsValue = normalizedTags.length > 0 ? normalizedTags : null
+ exifUpdates.Subject = tagsValue
+ exifUpdates.Keywords = tagsValue
+ exifUpdates.XPKeywords =
+ normalizedTags.length > 0 ? normalizedTags.join('; ') : null
+ }
+
+ if (payload.location !== undefined) {
+ if (payload.location) {
+ const { latitude, longitude } = payload.location
+ const latAbs = Math.abs(latitude)
+ const lonAbs = Math.abs(longitude)
+ exifUpdates.GPSLatitude = latAbs
+ exifUpdates.GPSLatitudeRef = latitude >= 0 ? 'N' : 'S'
+ exifUpdates.GPSLongitude = lonAbs
+ exifUpdates.GPSLongitudeRef = longitude >= 0 ? 'E' : 'W'
+ exifUpdates.GPSPosition = `${latitude} ${longitude}`
+ } else {
+ exifUpdates.GPSLatitude = null
+ exifUpdates.GPSLatitudeRef = null
+ exifUpdates.GPSLongitude = null
+ exifUpdates.GPSLongitudeRef = null
+ exifUpdates.GPSPosition = null
+ }
+ }
+
+ const tempDir = await mkdtemp(path.join(tmpdir(), 'cframe-edit-'))
+ const ext = path.extname(photo.storageKey) || '.jpg'
+ const tempFile = path.join(tempDir, `edited${ext}`)
+
+ try {
+ await writeFile(tempFile, originalBuffer)
+
+ if (Object.keys(exifUpdates).length > 0) {
+ await exiftool.write(tempFile, exifUpdates, ['-overwrite_original'])
+ }
+
+ const updatedBuffer = await readFile(tempFile)
+ await storageProvider.create(
+ photo.storageKey.replace(storageProvider.config?.prefix || '', ''),
+ updatedBuffer,
+ )
+
+ const exifData = await extractExifData(updatedBuffer)
+
+ const updateData: Record<string, any> = {
+ exif: exifData,
+ fileSize: updatedBuffer.length,
+ lastModified: new Date().toISOString(),
+ }
+
+ if (normalizedTitle !== undefined) {
+ updateData.title = normalizedTitle || null
+ }
+
+ if (normalizedDescription !== undefined) {
+ updateData.description = normalizedDescription || null
+ }
+
+ if (normalizedTags !== undefined) {
+ updateData.tags = normalizedTags
+ }
+
+ if (payload.location !== undefined) {
+ if (payload.location) {
+ updateData.latitude = payload.location.latitude
+ updateData.longitude = payload.location.longitude
+ updateData.country = null
+ updateData.city = null
+ updateData.locationName = null
+ pendingReverseGeocode = {
+ latitude: payload.location.latitude,
+ longitude: payload.location.longitude,
+ }
+ } else {
+ updateData.latitude = null
+ updateData.longitude = null
+ updateData.country = null
+ updateData.city = null
+ updateData.locationName = null
+ }
+ }
+
+ await db
+ .update(tables.photos)
+ .set(updateData)
+ .where(eq(tables.photos.id, photoId))
+
+ const updatedPhoto = await db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ if (pendingReverseGeocode) {
+ const workerPool = globalThis.__workerPool
+ if (workerPool) {
+ try {
+ await workerPool.addTask(
+ {
+ type: 'photo-reverse-geocoding',
+ photoId,
+ latitude: pendingReverseGeocode.latitude,
+ longitude: pendingReverseGeocode.longitude,
+ },
+ {
+ priority: 1,
+ },
+ )
+ } catch (taskError) {
+ logger.location.warn(
+ `Failed to enqueue reverse geocoding for photo ${photoId}:`,
+ taskError,
+ )
+ }
+ } else {
+ logger.location.warn(
+ `Worker pool not initialized, skipping reverse geocoding enqueue for photo ${photoId}`,
+ )
+ }
+ }
+
+ return {
+ success: true,
+ photo: updatedPhoto,
+ }
+ } catch (error) {
+ logger.image.error('Failed to update photo metadata', error)
+ throw createError({
+ statusCode: 500,
+ statusMessage: t('dashboard.photos.messages.metadataUpdateFailed'),
+ })
+ } finally {
+ await rm(tempDir, { recursive: true, force: true })
+ }
+})
diff --git a/server/api/queue/task/list.get.ts b/server/api/queue/task/list.get.ts
index 9ba41346..bd6d25b0 100644
--- a/server/api/queue/task/list.get.ts
+++ b/server/api/queue/task/list.get.ts
@@ -9,13 +9,17 @@ export default defineEventHandler(async (event) => {
try {
const query = getQuery(event)
- const {
+ const {
status,
- type
- } = await z.object({
- status: z.enum(['pending', 'in-stages', 'completed', 'failed']).optional(),
- type: z.enum(['photo', 'live-photo-video']).optional()
- }).parseAsync(query)
+ type,
+ } = await z
+ .object({
+ status: z.enum(['pending', 'in-stages', 'completed', 'failed']).optional(),
+ type: z
+ .enum(['photo', 'live-photo-video', 'photo-reverse-geocoding'])
+ .optional(),
+ })
+ .parseAsync(query)
const db = useDB()
@@ -66,4 +70,4 @@ export default defineEventHandler(async (event) => {
statusMessage: 'Failed to fetch task list',
})
}
-})
\ No newline at end of file
+})
diff --git a/server/database/schema.ts b/server/database/schema.ts
index f976fdbb..700478a1 100644
--- a/server/database/schema.ts
+++ b/server/database/schema.ts
@@ -2,6 +2,22 @@ import { sql } from 'drizzle-orm'
import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core'
import type { NeededExif } from '~~/shared/types/photo'
+type PipelineQueuePayload =
+ | {
+ type: 'photo'
+ storageKey: string
+ }
+ | {
+ type: 'live-photo-video'
+ storageKey: string
+ }
+ | {
+ type: 'photo-reverse-geocoding'
+ photoId: string
+ latitude?: number | null
+ longitude?: number | null
+ }
+
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
username: text('name').notNull().unique(),
@@ -44,15 +60,12 @@ export const photos = sqliteTable('photos', {
export const pipelineQueue = sqliteTable('pipeline_queue', {
id: integer('id').primaryKey({ autoIncrement: true }),
payload: text('payload', { mode: 'json' })
- .$type<{
- type: 'photo' | 'live-photo-video'
- storageKey: string
- }>()
+ .$type<PipelineQueuePayload>()
.notNull()
.default({
type: 'photo',
storageKey: '',
- }),
+ } satisfies PipelineQueuePayload),
priority: integer('priority').default(0).notNull(),
attempts: integer('attempts').default(0).notNull(),
maxAttempts: integer('max_attempts').default(3).notNull(),
diff --git a/server/services/pipeline-queue/manager.ts b/server/services/pipeline-queue/manager.ts
index df38e547..dc969674 100644
--- a/server/services/pipeline-queue/manager.ts
+++ b/server/services/pipeline-queue/manager.ts
@@ -230,6 +230,11 @@ export class QueueManager {
return {
photo: async (task: PipelineQueueItem) => {
const { id: taskId, payload } = task
+ if (payload.type !== 'photo') {
+ throw new Error(
+ `Invalid payload type for photo task: ${payload.type}`,
+ )
+ }
const { storageKey } = payload
const storageProvider = getStorageManager().getProvider()
const photoId = generateSafePhotoId(storageKey)
@@ -427,11 +432,112 @@ export class QueueManager {
throw error
}
},
+ reverseGeocoding: async (task: PipelineQueueItem) => {
+ const db = useDB()
+ const { id: taskId, payload } = task
+
+ if (payload.type !== 'photo-reverse-geocoding') {
+ throw new Error(
+ `Invalid payload type for reverse geocoding task: ${payload.type}`,
+ )
+ }
+
+ const { photoId } = payload
+
+ try {
+ await this.updateTaskStage(taskId, 'reverse-geocoding')
+ this.logger.info(
+ `[${taskId}:in-stage] reverse geocoding for photo ${photoId}`,
+ )
+
+ const photo = await db
+ .select()
+ .from(tables.photos)
+ .where(eq(tables.photos.id, photoId))
+ .get()
+
+ if (!photo) {
+ this.logger.warn(
+ `[${taskId}:reverse-geocoding] photo ${photoId} not found`,
+ )
+ return
+ }
+
+ let latitude = payload.latitude ?? photo.latitude ?? undefined
+ let longitude = payload.longitude ?? photo.longitude ?? undefined
+
+ if (
+ (latitude === undefined || latitude === null) ||
+ (longitude === undefined || longitude === null)
+ ) {
+ if (photo.exif) {
+ const coords = parseGPSCoordinates(photo.exif)
+ if (latitude === undefined || latitude === null) {
+ latitude = coords.latitude
+ }
+ if (longitude === undefined || longitude === null) {
+ longitude = coords.longitude
+ }
+ }
+ }
+
+ const hasLatitude = latitude !== undefined && latitude !== null
+ const hasLongitude = longitude !== undefined && longitude !== null
+
+ if (!hasLatitude || !hasLongitude) {
+ this.logger.warn(
+ `[${taskId}:reverse-geocoding] missing coordinates for photo ${photoId}`,
+ )
+ await db
+ .update(tables.photos)
+ .set({
+ latitude: null,
+ longitude: null,
+ country: null,
+ city: null,
+ locationName: null,
+ })
+ .where(eq(tables.photos.id, photoId))
+ return
+ }
+
+ const locationInfo = await extractLocationFromGPS(
+ latitude!,
+ longitude!,
+ )
+
+ await db
+ .update(tables.photos)
+ .set({
+ latitude: latitude!,
+ longitude: longitude!,
+ country: locationInfo?.country ?? null,
+ city: locationInfo?.city ?? null,
+ locationName: locationInfo?.locationName ?? null,
+ })
+ .where(eq(tables.photos.id, photoId))
+
+ this.logger.success(
+ `[${taskId}:reverse-geocoding] updated location for photo ${photoId}`,
+ )
+ } catch (error) {
+ this.logger.error(
+ `[${taskId}:reverse-geocoding] failed for photo ${photoId}`,
+ error,
+ )
+ throw error
+ }
+ },
livePhotoDetect: async (task: PipelineQueueItem) => {
const db = useDB()
const storageProvider = getStorageManager().getProvider()
const { id: taskId, payload } = task
+ if (payload.type !== 'live-photo-video') {
+ throw new Error(
+ `Invalid payload type for live-photo task: ${payload.type}`,
+ )
+ }
const { storageKey: videoKey } = payload
try {
@@ -545,6 +651,9 @@ export class QueueManager {
case 'photo':
await this.processors.photo(task)
break
+ case 'photo-reverse-geocoding':
+ await this.processors.reverseGeocoding(task)
+ break
default:
throw new Error(`Unknown task type: ${type}`)
}