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
feat(albums): add context-aware uploads and bulk photo assignment
Ahmet Ömer9460b7b97a9e
diff --git a/app/pages/albums/[albumId].vue b/app/pages/albums/[albumId].vueindex f0550ac0..8c817a82 100644--- a/app/pages/albums/[albumId].vue+++ b/app/pages/albums/[albumId].vue@@ -4,6 +4,7 @@ import { motion } from 'motion-v'const route = useRoute()const router = useRouter()const dayjs = useDayjs()+const { user } = useUserSession()const { albumListPath } = useHomeView()const albumId = computed(() => {@@ -38,7 +39,8 @@ const unlockAlbum = async () => {unlockSucceeded.value = falsetry {await $fetch(`/api/albums/${albumId.value}/unlock`, {- method: 'POST', body: { password: albumPassword.value },+ method: 'POST',+ body: { password: albumPassword.value },})albumPassword.value = ''await refresh()@@ -142,12 +144,14 @@ watch(([requestedPhoto, photos]) => {const viewer = useViewerState()if (typeof requestedPhoto !== 'string' || !photos) {- if (viewer.returnRoute === `/albums/${albumId.value}`) viewer.closeViewer()+ if (viewer.returnRoute === `/albums/${albumId.value}`)+ viewer.closeViewer()return}const index = photos.findIndex((photo) => photo.id === requestedPhoto)if (index < 0) {- if (viewer.returnRoute === `/albums/${albumId.value}`) viewer.closeViewer()+ if (viewer.returnRoute === `/albums/${albumId.value}`)+ viewer.closeViewer()return}const { openViewer } = viewer@@ -197,8 +201,11 @@ onUnmounted(() => {})useHead({- title: () => albumData.value?.title ||- (error.value?.statusCode === 403 ? $t('album.passwordRequired') : $t('album.notFound')),+ title: () =>+ albumData.value?.title ||+ (error.value?.statusCode === 403+ ? $t('album.passwordRequired')+ : $t('album.notFound')),})</script>@@ -220,47 +227,95 @@ useHead({<motion.divv-else-if="error?.statusCode === 403 || isUnlocking"class="relative mx-auto flex min-h-[65vh] max-w-md items-center justify-center overflow-hidden px-6 py-16"- :initial="prefersReducedMotion ? false : { opacity: 0, y: 20, scale: 0.97 }"- :animate="unlockSucceeded && !prefersReducedMotion- ? { opacity: 0, y: -12, scale: 0.98 }- : { opacity: 1, y: 0, scale: 1 }"- :transition="{ duration: prefersReducedMotion ? 0 : 0.42, ease: 'easeOut' }"+ :initial="+ prefersReducedMotion ? false : { opacity: 0, y: 20, scale: 0.97 }+ "+ :animate="+ unlockSucceeded && !prefersReducedMotion+ ? { opacity: 0, y: -12, scale: 0.98 }+ : { opacity: 1, y: 0, scale: 1 }+ "+ :transition="{+ duration: prefersReducedMotion ? 0 : 0.42,+ ease: 'easeOut',+ }">- <div class="relative w-full rounded-3xl border border-neutral-200/70 bg-white/80 p-8 shadow-xl shadow-neutral-900/5 backdrop-blur-xl dark:border-neutral-700/70 dark:bg-neutral-900/80 dark:shadow-black/20 sm:p-10">+ <div+ class="relative w-full rounded-3xl border border-neutral-200/70 bg-white/80 p-8 shadow-xl shadow-neutral-900/5 backdrop-blur-xl dark:border-neutral-700/70 dark:bg-neutral-900/80 dark:shadow-black/20 sm:p-10"+ ><motion.divclass="mx-auto mb-4 flex size-16 items-center justify-center text-primary-600 dark:text-primary-400"- :initial="prefersReducedMotion ? false : { opacity: 0, scale: 0.7, rotate: -12 }"+ :initial="+ prefersReducedMotion+ ? false+ : { opacity: 0, scale: 0.7, rotate: -12 }+ ":animate="{ opacity: 1, scale: 1, rotate: 0 }"- :transition="{ delay: prefersReducedMotion ? 0 : 0.12, type: 'spring', stiffness: 260, damping: 20 }"+ :transition="{+ delay: prefersReducedMotion ? 0 : 0.12,+ type: 'spring',+ stiffness: 260,+ damping: 20,+ }">- <Icon name="tabler:lock" class="size-10" />+ <Icon+ name="tabler:lock"+ class="size-10"+ /></motion.div><motion.h1class="mb-5 text-center text-2xl font-semibold text-neutral-900 dark:text-white":initial="prefersReducedMotion ? false : { opacity: 0, y: 10 }":animate="{ opacity: 1, y: 0 }"- :transition="{ delay: prefersReducedMotion ? 0 : 0.2, duration: prefersReducedMotion ? 0 : 0.35 }"+ :transition="{+ delay: prefersReducedMotion ? 0 : 0.2,+ duration: prefersReducedMotion ? 0 : 0.35,+ }">{{ $t('album.passwordRequired') }}</motion.h1><motion.div:initial="prefersReducedMotion ? false : { opacity: 0, y: 12 }":animate="{ opacity: 1, y: 0 }"- :transition="{ delay: prefersReducedMotion ? 0 : 0.28, duration: prefersReducedMotion ? 0 : 0.35 }"+ :transition="{+ delay: prefersReducedMotion ? 0 : 0.28,+ duration: prefersReducedMotion ? 0 : 0.35,+ }">- <form class="flex flex-col gap-3" @submit.prevent="unlockAlbum">+ <form+ class="flex flex-col gap-3"+ @submit.prevent="unlockAlbum"+ ><motion.div- :animate="unlockErrorMessageKey && !prefersReducedMotion- ? { x: [0, -6, 6, -4, 4, 0] } : { x: 0 }"+ :animate="+ unlockErrorMessageKey && !prefersReducedMotion+ ? { x: [0, -6, 6, -4, 4, 0] }+ : { x: 0 }+ ":transition="{ duration: 0.32 }">- <UInput v-model="albumPassword" type="password" autocomplete="off"- :placeholder="$t('album.passwordPlaceholder')" autofocus class="w-full" />+ <UInput+ v-model="albumPassword"+ type="password"+ autocomplete="off"+ :placeholder="$t('album.passwordPlaceholder')"+ autofocus+ class="w-full"+ /></motion.div>- <p v-if="unlockErrorMessageKey" role="alert" class="text-sm text-error-500">+ <p+ v-if="unlockErrorMessageKey"+ role="alert"+ class="text-sm text-error-500"+ >{{ $t(unlockErrorMessageKey) }}</p>- <UButton type="submit" block :loading="isUnlocking" :disabled="!albumPassword">+ <UButton+ type="submit"+ block+ :loading="isUnlocking"+ :disabled="!albumPassword"+ >{{ $t('album.unlock') }}</UButton></form>@@ -305,12 +360,22 @@ useHead({:transition="{ duration: 0.4 }"><!-- title -->- <div>+ <div class="flex flex-wrap items-center justify-between gap-4"><h1class="text-3xl sm:text-4xl font-bold text-neutral-900 dark:text-white tracking-tight">{{ albumData.title }}</h1>+ <UButton+ v-if="user?.isAdmin"+ icon="tabler:cloud-upload"+ :to="{+ path: '/dashboard/photos',+ query: { uploadAlbumId: String(albumId) },+ }"+ >+ {{ $t('album.uploadToThisAlbum') }}+ </UButton></div><!-- metadata -->@@ -357,7 +422,13 @@ useHead({<!-- Created --><divclass="flex items-center gap-1"- :title="$t('album.createdTooltip', { date: $dayjs(albumData.createdAt).format('YYYY-MM-DD HH:mm:ss') })"+ :title="+ $t('album.createdTooltip', {+ date: $dayjs(albumData.createdAt).format(+ 'YYYY-MM-DD HH:mm:ss',+ ),+ })+ "><Iconname="tabler:clock-plus"diff --git a/app/pages/dashboard/albums.vue b/app/pages/dashboard/albums.vueindex 2706c05b..770c2bea 100644--- a/app/pages/dashboard/albums.vue+++ b/app/pages/dashboard/albums.vue@@ -5,7 +5,7 @@ import {ALBUM_PASSWORD_MAX_LENGTH,ALBUM_PASSWORD_MIN_LENGTH,isValidAlbumPasswordLength,-} from '~~/shared/utils/album-password'+} from '~~/shared/utils/album'definePageMeta({layout: 'dashboard',@@ -510,6 +510,9 @@ const submitButtonLabel = computed(() => {: $t('dashboard.albums.slideover.submitCreate')})+const albumUploadLabel = (album: AlbumItem) =>+ $t('dashboard.albums.actions.uploadToAlbum', { title: album.title })+const columns = computed<any[]>(() => [{id: 'coverPhoto',@@ -655,6 +658,26 @@ const columns = computed<any[]>(() => [class="flex gap-1"data-tour="album-actions">+ <UButton+ variant="ghost"+ color="primary"+ size="xs"+ icon="tabler:cloud-upload"+ :aria-label="+ albumUploadLabel(row.original as unknown as AlbumItem)+ "+ :title="+ albumUploadLabel(row.original as unknown as AlbumItem)+ "+ :to="{+ path: '/dashboard/photos',+ query: {+ uploadAlbumId: String(+ (row.original as unknown as AlbumItem).id,+ ),+ },+ }"+ /><UButtonvariant="ghost"color="neutral"diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vueindex d9c4517c..8a9986d3 100644--- a/app/pages/dashboard/photos.vue+++ b/app/pages/dashboard/photos.vue@@ -2,6 +2,10 @@import type { FormSubmitEvent, TableColumn } from '@nuxt/ui'import type { Album, Photo } from '~~/server/utils/db'import type { UploadingFile } from '~~/shared/types/uploading-file'+import {+ MAX_ALBUM_PHOTOS_PER_REQUEST,+ type AddPhotosToAlbumResult,+} from '~~/shared/utils/album'import { QueueWarningCode } from '~~/shared/utils/queue-warning'import {UploadQueueStatus,@@ -16,6 +20,8 @@ import ThumbImage from '~/components/ui/ThumbImage.vue'const UCheckbox = resolveComponent('UCheckbox')const Rating = resolveComponent('Rating')+const route = useRoute()+const router = useRouter()// 列名显示映射const columnNameMap = computed<Record<string, string>>(() => ({@@ -249,6 +255,10 @@ const uploadImage = async () => {const fileName = file.nameconst fileId = existingFileId || `${Date.now()}-${fileName}`+ const isVideoFile =+ file.type === 'video/quicktime' ||+ file.type === 'video/mp4' ||+ fileName.toLowerCase().endsWith('.mov')const uploadManager = useUpload({timeout: 60 * 1000, // 单个分片一分钟超时,避免请求长时间卡住@@ -292,20 +302,54 @@ const uploadImage = async (// 检查是否为跳过模式(重复文件)if (signedUrlResponse.skipped) {- uploadingFile.status = UploadQueueStatus.SkippeduploadingFile.progress = 100uploadingFile.canAbort = false- uploadingFile.error =- signedUrlResponse.message ||- $t('upload.duplicate.skip.message', { fileName })-- toast.add({- title: signedUrlResponse.title || $t('upload.duplicate.skip.title'),- description:+ if (albumId !== undefined && !isVideoFile) {+ try {+ const existingPhotoId = signedUrlResponse.existingPhoto?.id+ if (!existingPhotoId) throw new Error('Skipped photo has no ID')+ const result = await $fetch<AddPhotosToAlbumResult>(+ `/api/albums/${albumId}/photos`,+ {+ method: 'POST',+ body: { photoIds: [existingPhotoId] },+ },+ )+ const added = result.added > 0+ uploadingFile.status = UploadQueueStatus.Skipped+ uploadingFile.error = $t(+ added+ ? 'upload.duplicate.skip.addedToAlbum'+ : 'upload.duplicate.skip.alreadyInAlbum',+ )+ toast.add({+ title: added+ ? $t('dashboard.photos.addToAlbum.success')+ : $t('upload.duplicate.skip.title'),+ description: uploadingFile.error,+ color: added ? 'success' : 'neutral',+ })+ } catch (error) {+ console.error('Failed to add skipped photo to album:', error)+ uploadingFile.status = UploadQueueStatus.Error+ uploadingFile.error = $t('upload.duplicate.skip.albumAddFailed')+ toast.add({+ title: $t('dashboard.photos.addToAlbum.error'),+ description: uploadingFile.error,+ color: 'error',+ })+ }+ } else {+ uploadingFile.status = UploadQueueStatus.Skipped+ uploadingFile.error =signedUrlResponse.message ||- $t('upload.duplicate.skip.message', { fileName }),- color: 'warning',- })+ $t('upload.duplicate.skip.message', { fileName })+ toast.add({+ title: signedUrlResponse.title || $t('upload.duplicate.skip.title'),+ description: uploadingFile.error,+ color: 'warning',+ })+ }uploadingFiles.value = new Map(uploadingFiles.value)return@@ -362,19 +406,14 @@ const uploadImage = async (try {// 检查是否为MOV视频文件(通过MIME类型或文件扩展名)- const isMovFile =- file.type === 'video/quicktime' ||- file.type === 'video/mp4' ||- file.name.toLowerCase().endsWith('.mov')-const enqueueTask = (targetAlbumId?: number) =>$fetch('/api/queue/add-task', {method: 'POST',body: {payload: {- type: isMovFile ? 'live-photo-video' : 'photo',+ type: isVideoFile ? 'live-photo-video' : 'photo',storageKey: signedUrlResponse.fileKey,- ...(isMovFile+ ...(isVideoFile? {}: {eraseLocation:@@ -385,7 +424,7 @@ const uploadImage = async (: {}),}),},- priority: isMovFile ? 0 : 1, // Live Photo 视频优先级更低,确保图片优先处理+ priority: isVideoFile ? 0 : 1, // Live Photo 视频优先级更低,确保图片优先处理maxAttempts: 3,},})@@ -396,7 +435,7 @@ const uploadImage = async (resp = await enqueueTask(albumId)} catch (error: any) {const statusCode = error.statusCode ?? error.response?.status- if (isMovFile || albumId === undefined || statusCode !== 404) {+ if (isVideoFile || albumId === undefined || statusCode !== 404) {throw error}@@ -510,10 +549,28 @@ type UploadAlbumOption = Pick<Album, 'id' | 'title' | 'isHidden'> & {const uploadAlbums = ref<UploadAlbumOption[]>([])const selectedUploadAlbumId = ref(0)+const requestedUploadAlbumId = ref<number | null>(null)const isLoadingUploadAlbums = ref(false)const uploadAlbumsLoadFailed = ref(false)let uploadAlbumsRequestId = 0+const selectedUploadAlbumUnavailable = computed(+ () =>+ selectedUploadAlbumId.value !== 0 &&+ !isLoadingUploadAlbums.value &&+ !uploadAlbumsLoadFailed.value &&+ !uploadAlbums.value.some(+ (album) => album.id === selectedUploadAlbumId.value,+ ),+)+const canUseSelectedUploadAlbum = computed(+ () =>+ selectedUploadAlbumId.value === 0 ||+ (!isLoadingUploadAlbums.value &&+ !uploadAlbumsLoadFailed.value &&+ !selectedUploadAlbumUnavailable.value),+)+const uploadAlbumItems = computed(() => [{label: $t('dashboard.photos.slideover.album.none'),@@ -541,6 +598,7 @@ const uploadAlbumItems = computed(() => [value: album.id,})),])+const bulkAlbumItems = computed(() => uploadAlbumItems.value.slice(1))const loadUploadAlbums = async () => {const requestId = ++uploadAlbumsRequestId@@ -590,20 +648,34 @@ const clearSelectedFiles = () => {watch(isUploadSlideoverOpen, (open) => {if (!open) {- uploadAlbumsRequestId++- isLoadingUploadAlbums.value = falseclearSelectedFiles()uploadEraseLocationEnabled.value = systemUploadEraseLocationDefault.valueselectedUploadAlbumId.value = 0+ requestedUploadAlbumId.value = null}})-const openUploadSlideover = () => {+const openUploadSlideover = (albumId?: number) => {uploadEraseLocationEnabled.value = systemUploadEraseLocationDefault.value+ requestedUploadAlbumId.value = albumId ?? null+ selectedUploadAlbumId.value = albumId ?? 0isUploadSlideoverOpen.value = truevoid loadUploadAlbums()}+const openRequestedAlbumUpload = () => {+ const value = route.query.uploadAlbumId+ if (typeof value !== 'string') return+ const albumId = Number(value)+ if (/^[1-9]\d*$/.test(value) && Number.isSafeInteger(albumId)) {+ openUploadSlideover(albumId)+ }+ void router.replace({ query: { ...route.query, uploadAlbumId: undefined } })+}++onMounted(openRequestedAlbumUpload)+watch(() => route.query.uploadAlbumId, openRequestedAlbumUpload)+watch(isEditModalOpen, (open) => {if (!open) {editingPhoto.value = null@@ -628,6 +700,123 @@ const rowSelection = ref({})const table: any = useTemplateRef('table')const getPhotoRowId = (photo: Photo) => photo.idconst rowRangeSelection = useShiftRangeSelection()+const isAddToAlbumOpen = ref(false)+const selectedBulkPhotoIds = ref<string[]>([])+const selectedBulkAlbumId = ref<number | null>(null)+const isAddingToAlbum = ref(false)++const selectedBulkPhotoCountLabel = computed(() =>+ $t(+ 'plural.selectedPhoto',+ { count: selectedBulkPhotoIds.value.length },+ selectedBulkPhotoIds.value.length,+ ),+)++const formatAddToAlbumResult = (+ added: number,+ alreadyPresent: number,+ missing: number,+) => {+ const result = $t('dashboard.photos.addToAlbum.result', {+ added,+ alreadyPresent,+ })+ return missing > 0+ ? `${result} · ${$t('dashboard.photos.addToAlbum.missing', { count: missing })}`+ : result+}++const openAddToAlbum = () => {+ if (isAddingToAlbum.value) return++ const selectedRows =+ table.value?.tableApi?.getFilteredSelectedRowModel().rows || []+ selectedBulkPhotoIds.value = selectedRows.map(+ (row: { original: Photo }) => row.original.id,+ )+ if (selectedBulkPhotoIds.value.length === 0) return+ selectedBulkAlbumId.value = null+ isAddToAlbumOpen.value = true+ void loadUploadAlbums()+}++const addSelectedPhotosToAlbum = async () => {+ const albumId = selectedBulkAlbumId.value+ if (+ isAddingToAlbum.value ||+ albumId === null ||+ !uploadAlbums.value.some((album) => album.id === albumId)+ ) {+ return+ }++ isAddingToAlbum.value = true+ let added = 0+ let alreadyPresent = 0+ let missing = 0+ let completedRequests = 0+ try {+ const photoIds = [...selectedBulkPhotoIds.value]+ for (+ let index = 0;+ index < photoIds.length;+ index += MAX_ALBUM_PHOTOS_PER_REQUEST+ ) {+ const result = await $fetch<AddPhotosToAlbumResult>(+ `/api/albums/${albumId}/photos`,+ {+ method: 'POST',+ body: {+ photoIds: photoIds.slice(+ index,+ index + MAX_ALBUM_PHOTOS_PER_REQUEST,+ ),+ },+ },+ )+ added += result.added+ alreadyPresent += result.alreadyPresent+ missing += result.missing+ completedRequests+++ }+ const noChanges = added === 0 && missing === 0+ toast.add({+ title: $t(+ added > 0+ ? 'dashboard.photos.addToAlbum.success'+ : 'dashboard.photos.addToAlbum.noChanges',+ ),+ description: noChanges+ ? $t('dashboard.photos.addToAlbum.allAlreadyPresent')+ : formatAddToAlbumResult(added, alreadyPresent, missing),+ color: added > 0 ? 'success' : 'neutral',+ })+ rowSelection.value = {}+ isAddToAlbumOpen.value = false+ } catch (error) {+ console.error('Failed to add photos to album:', error)+ toast.add({+ title: $t('dashboard.photos.addToAlbum.error'),+ description:+ completedRequests > 0+ ? $t('dashboard.photos.addToAlbum.partialError', {+ processed: formatAddToAlbumResult(added, alreadyPresent, missing),+ })+ : undefined,+ color: 'error',+ })+ } finally {+ isAddingToAlbum.value = false+ }+}++watch(isAddToAlbumOpen, (open) => {+ if (!open) {+ selectedBulkPhotoIds.value = []+ selectedBulkAlbumId.value = null+ }+})watch(() => Object.keys(rowSelection.value).length === 0,@@ -1019,7 +1208,9 @@ const columns = computed<TableColumn<Photo>[]>(() => [)}- const location = [...new Set([locationLabel(row.original), country].filter(Boolean))].join(', ')+ const location = [+ ...new Set([locationLabel(row.original), country].filter(Boolean)),+ ].join(', ')return h('span',{@@ -1194,6 +1385,7 @@ const validateFile = (}const handleUpload = async () => {+ if (!canUseSelectedUploadAlbum.value) returnconst fileList = [...selectedFiles.value]const eraseLocation = uploadEraseLocationEnabled.valueconst albumId = selectedUploadAlbumId.value || undefined@@ -2165,7 +2357,7 @@ onUnmounted(() => {<UButtonicon="tabler:cloud-upload"data-tour="photo-upload"- @click="openUploadSlideover"+ @click="openUploadSlideover()"><span class="hidden sm:inline">{{$t('dashboard.photos.buttons.upload')@@ -2254,7 +2446,7 @@ onUnmounted(() => {value-key="value"label-key="label":loading="isLoadingUploadAlbums"- :disabled="isLoadingUploadAlbums || uploadAlbumsLoadFailed"+ :disabled="isLoadingUploadAlbums":aria-label="$t('dashboard.photos.slideover.album.label')"class="w-full"/>@@ -2269,13 +2461,26 @@ onUnmounted(() => {>{{ $t('dashboard.photos.slideover.album.empty') }}</p>+ <p+ v-if="selectedUploadAlbumUnavailable"+ role="alert"+ class="mt-2 text-sm text-error-600 dark:text-error-400"+ >+ {{+ $t(+ requestedUploadAlbumId === selectedUploadAlbumId+ ? 'dashboard.photos.slideover.album.requestedUnavailable'+ : 'dashboard.photos.slideover.album.unavailable',+ )+ }}+ </p><divv-if="uploadAlbumsLoadFailed"role="alert"class="mt-2 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"><span>{{- $t('dashboard.photos.slideover.album.loadFailed')+ $t('dashboard.photos.slideover.album.loadFailedUpload')}}</span><UButtonsize="xs"@@ -2344,7 +2549,7 @@ onUnmounted(() => {size="lg"class="w-full sm:w-auto"icon="tabler:upload"- :disabled="!hasSelectedFiles"+ :disabled="!hasSelectedFiles || !canUseSelectedUploadAlbum"@click="handleUpload">{{@@ -2383,335 +2588,360 @@ onUnmounted(() => {{{ $t('dashboard.photos.toolbar.title') }}</span><div class="flex items-center gap-1 sm:gap-2 sm:ml-1">- <UBadge- v-if="livePhotoStats.staticPhotos > 0"- variant="soft"- color="neutral"- size="sm"- >- <span class="hidden sm:inline"- >{{ livePhotoStats.staticPhotos }}- {{ $t('dashboard.photos.stats.photos') }}</span- >- <span class="sm:hidden"- >{{ livePhotoStats.staticPhotos }}P</span+ <UBadge+ v-if="livePhotoStats.staticPhotos > 0"+ variant="soft"+ color="neutral"+ size="sm">- </UBadge>- <UBadge- v-if="livePhotoStats.livePhotos > 0"- variant="soft"- color="warning"- size="sm"- >- <span class="hidden sm:inline"- >{{ livePhotoStats.livePhotos }}- {{ $t('dashboard.photos.stats.livePhotos') }}</span+ <span class="hidden sm:inline"+ >{{ livePhotoStats.staticPhotos }}+ {{ $t('dashboard.photos.stats.photos') }}</span+ >+ <span class="sm:hidden"+ >{{ livePhotoStats.staticPhotos }}P</span+ >+ </UBadge>+ <UBadge+ v-if="livePhotoStats.livePhotos > 0"+ variant="soft"+ color="warning"+ size="sm">- <span class="sm:hidden">{{ livePhotoStats.livePhotos }}LP</span>- </UBadge>+ <span class="hidden sm:inline"+ >{{ livePhotoStats.livePhotos }}+ {{ $t('dashboard.photos.stats.livePhotos') }}</span+ >+ <span class="sm:hidden"+ >{{ livePhotoStats.livePhotos }}LP</span+ >+ </UBadge>+ </div></div>- </div>- <div class="flex items-center gap-2">- <UPopover>- <UTooltip :text="$t('ui.action.filter.tooltip')">- <UChip- inset- size="sm"- color="info"- :show="totalSelectedFilters > 0"- >+ <div class="flex items-center gap-2">+ <UPopover>+ <UTooltip :text="$t('ui.action.filter.tooltip')">+ <UChip+ inset+ size="sm"+ color="info"+ :show="totalSelectedFilters > 0"+ >+ <UButton+ variant="soft"+ :color="hasActiveFilters ? 'info' : 'neutral'"+ class="bg-transparent rounded-full cursor-pointer relative"+ icon="tabler:filter"+ size="sm"+ />+ </UChip>+ </UTooltip>++ <template #content>+ <UCard variant="glassmorphism">+ <OverlayFilterPanel />+ </UCard>+ </template>+ </UPopover>+ <UPopover>+ <UTooltip :text="$t('ui.action.sort.tooltip')"><UButtonvariant="soft"- :color="hasActiveFilters ? 'info' : 'neutral'"- class="bg-transparent rounded-full cursor-pointer relative"- icon="tabler:filter"+ :color="+ currentSortOption?.key === 'dateTaken-desc'+ ? 'neutral'+ : 'info'+ "+ class="bg-transparent rounded-full cursor-pointer"+ :icon="currentSortIcon"size="sm"/>- </UChip>- </UTooltip>-- <template #content>- <UCard variant="glassmorphism">- <OverlayFilterPanel />- </UCard>- </template>- </UPopover>- <UPopover>- <UTooltip :text="$t('ui.action.sort.tooltip')">- <UButton- variant="soft"- :color="- currentSortOption?.key === 'dateTaken-desc'- ? 'neutral'- : 'info'- "- class="bg-transparent rounded-full cursor-pointer"- :icon="currentSortIcon"- size="sm"- />- </UTooltip>-- <template #content>- <OverlaySortPanel />- </template>- </UPopover>- <!-- 过滤器 -->- <USelectMenu- data-tour="photo-filter"- v-model="photoFilter"- class="w-full sm:w-48"- :items="[- {- label: $t('dashboard.photos.photoFilter.all'),- value: 'all',- icon: 'tabler:photo-scan',- },- {- label: $t('dashboard.photos.photoFilter.livephoto'),- value: 'livephoto',- icon: 'tabler:live-photo',- },- {- label: $t('dashboard.photos.photoFilter.static'),- value: 'static',- icon: 'tabler:photo',- },- ]"- value-key="value"- label-key="label"- size="sm"- >- </USelectMenu>-- <!-- 刷新按钮 -->- <UButton- variant="soft"- color="info"- size="sm"- icon="tabler:refresh"- :loading="reactionsLoading"- @click="- async () => {- await refresh()- if (filteredData.length > 0) {- await fetchReactions(filteredData.map((p: Photo) => p.id))- }- }- "- >- <span class="hidden sm:inline">{{- $t('dashboard.photos.toolbar.refresh')- }}</span>- </UButton>+ </UTooltip>++ <template #content>+ <OverlaySortPanel />+ </template>+ </UPopover>+ <!-- 过滤器 -->+ <USelectMenu+ data-tour="photo-filter"+ v-model="photoFilter"+ class="w-full sm:w-48"+ :items="[+ {+ label: $t('dashboard.photos.photoFilter.all'),+ value: 'all',+ icon: 'tabler:photo-scan',+ },+ {+ label: $t('dashboard.photos.photoFilter.livephoto'),+ value: 'livephoto',+ icon: 'tabler:live-photo',+ },+ {+ label: $t('dashboard.photos.photoFilter.static'),+ value: 'static',+ icon: 'tabler:photo',+ },+ ]"+ value-key="value"+ label-key="label"+ size="sm"+ >+ </USelectMenu>- <!-- 列可见性按钮 -->- <UDropdownMenu- :items="- table?.tableApi- ?.getAllColumns()- .filter((column: any) => column.getCanHide())- .map((column: any) => ({- label: columnNameMap[column.id] || column.id,- type: 'checkbox' as const,- checked: column.getIsVisible(),- disabled:- !column.getCanHide() ||- column.id === 'thumbnailUrl' ||- column.id === 'id' ||- column.id === 'actions',- onUpdateChecked(checked: boolean) {- table?.tableApi- ?.getColumn(column.id)- ?.toggleVisibility(!!checked)- },- onSelect(e: Event) {- e.preventDefault()- },- }))- "- :content="{ align: 'end' }"- >+ <!-- 刷新按钮 --><UButton- label=""- color="neutral"- variant="outline"+ variant="soft"+ color="info"size="sm"- icon="tabler:columns-3"- :title="- $t('dashboard.photos.table.columnVisibility.description')+ icon="tabler:refresh"+ :loading="reactionsLoading"+ @click="+ async () => {+ await refresh()+ if (filteredData.length > 0) {+ await fetchReactions(filteredData.map((p: Photo) => p.id))+ }+ }"><span class="hidden sm:inline">{{- $t('dashboard.photos.table.columnVisibility.button')+ $t('dashboard.photos.toolbar.refresh')}}</span></UButton>- </UDropdownMenu>- </div>- </div>- <!-- 照片列表 -->- <div class="relative flex-1 min-h-0 flex flex-col">- <UTable- ref="table"- v-model:row-selection="rowSelection"- v-model:column-visibility="columnVisibility"- :get-row-id="getPhotoRowId"- :column-pinning="{- right: ['actions'],- }"- :data="filteredData as Photo[]"- :columns="columns"- :loading="status === 'pending'"- sticky- class="h-full flex-1"- :ui="{- wrapper: 'relative scroll-smooth h-full overflow-auto',- base: 'min-w-full table-fixed',- divide:- 'divide-y divide-neutral-200/80 dark:divide-neutral-800/80',- thead:- 'bg-neutral-50/80 dark:bg-neutral-900/80 backdrop-blur-md sticky top-0 z-10 whitespace-nowrap',- tbody:- 'divide-y divide-neutral-200/80 dark:divide-neutral-800/80 bg-white dark:bg-neutral-900',- tr: {- base: 'hover:bg-neutral-50/50 dark:hover:bg-neutral-800/50 transition-colors',- selected: 'bg-primary-50/50 dark:bg-primary-900/20',- },- th: {- base: 'text-left rtl:text-right ',- padding: 'px-4 py-3.5',- color: 'text-neutral-500 dark:text-neutral-400',- font: 'font-medium text-sm',- },- td: {- padding: 'px-4 py-3',- color: 'text-neutral-700 dark:text-neutral-300 text-sm',- },- separator: 'bg-neutral-200/80 dark:bg-neutral-800/80',- }"- >- <template #actions-cell="{ row }">- <div class="flex justify-end">- <UDropdownMenu+ <!-- 列可见性按钮 -->+ <UDropdownMenu+ :items="+ table?.tableApi+ ?.getAllColumns()+ .filter((column: any) => column.getCanHide())+ .map((column: any) => ({+ label: columnNameMap[column.id] || column.id,+ type: 'checkbox' as const,+ checked: column.getIsVisible(),+ disabled:+ !column.getCanHide() ||+ column.id === 'thumbnailUrl' ||+ column.id === 'id' ||+ column.id === 'actions',+ onUpdateChecked(checked: boolean) {+ table?.tableApi+ ?.getColumn(column.id)+ ?.toggleVisibility(!!checked)+ },+ onSelect(e: Event) {+ e.preventDefault()+ },+ }))+ "+ :content="{ align: 'end' }"+ >+ <UButton+ label=""+ color="neutral"+ variant="outline"size="sm"- :content="{- align: 'end',- }"- :items="getRowActions(row.original)"+ icon="tabler:columns-3"+ :title="+ $t('dashboard.photos.table.columnVisibility.description')+ ">- <UButton- variant="outline"- color="neutral"+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.table.columnVisibility.button')+ }}</span>+ </UButton>+ </UDropdownMenu>+ </div>+ </div>++ <!-- 照片列表 -->+ <div class="relative flex-1 min-h-0 flex flex-col">+ <UTable+ ref="table"+ v-model:row-selection="rowSelection"+ v-model:column-visibility="columnVisibility"+ :get-row-id="getPhotoRowId"+ :column-pinning="{+ right: ['actions'],+ }"+ :data="filteredData as Photo[]"+ :columns="columns"+ :loading="status === 'pending'"+ sticky+ class="h-full flex-1"+ :ui="{+ wrapper: 'relative scroll-smooth h-full overflow-auto',+ base: 'min-w-full table-fixed',+ divide:+ 'divide-y divide-neutral-200/80 dark:divide-neutral-800/80',+ thead:+ 'bg-neutral-50/80 dark:bg-neutral-900/80 backdrop-blur-md sticky top-0 z-10 whitespace-nowrap',+ tbody:+ 'divide-y divide-neutral-200/80 dark:divide-neutral-800/80 bg-white dark:bg-neutral-900',+ tr: {+ base: 'hover:bg-neutral-50/50 dark:hover:bg-neutral-800/50 transition-colors',+ selected: 'bg-primary-50/50 dark:bg-primary-900/20',+ },+ th: {+ base: 'text-left rtl:text-right ',+ padding: 'px-4 py-3.5',+ color: 'text-neutral-500 dark:text-neutral-400',+ font: 'font-medium text-sm',+ },+ td: {+ padding: 'px-4 py-3',+ color: 'text-neutral-700 dark:text-neutral-300 text-sm',+ },+ separator: 'bg-neutral-200/80 dark:bg-neutral-800/80',+ }"+ >+ <template #actions-cell="{ row }">+ <div class="flex justify-end">+ <UDropdownMenusize="sm"- icon="tabler:dots-vertical"- />- </UDropdownMenu>- </div>- </template>- </UTable>-- <!-- 悬浮版批量操作菜单 -->- <transition- enter-active-class="transition-all duration-300 ease-out"- enter-from-class="translate-y-8 opacity-0 scale-95"- enter-to-class="translate-y-0 opacity-100 scale-100"- leave-active-class="transition-all duration-200 ease-in"- leave-from-class="translate-y-0 opacity-100 scale-100"- leave-to-class="translate-y-8 opacity-0 scale-95"- >- <div- v-if="selectedRowsCount > 0"- class="fixed bottom-8 left-1/2 -translate-x-1/2 z-60 w-max flex flex-col items-center gap-2"+ :content="{+ align: 'end',+ }"+ :items="getRowActions(row.original)"+ >+ <UButton+ variant="outline"+ color="neutral"+ size="sm"+ icon="tabler:dots-vertical"+ />+ </UDropdownMenu>+ </div>+ </template>+ </UTable>++ <!-- 悬浮版批量操作菜单 -->+ <transition+ enter-active-class="transition-all duration-300 ease-out"+ enter-from-class="translate-y-8 opacity-0 scale-95"+ enter-to-class="translate-y-0 opacity-100 scale-100"+ leave-active-class="transition-all duration-200 ease-in"+ leave-from-class="translate-y-0 opacity-100 scale-100"+ leave-to-class="translate-y-8 opacity-0 scale-95">- <p- class="hidden items-center gap-1.5 max-w-[calc(100vw-2rem)] px-3 py-1 rounded-full bg-white/80 dark:bg-neutral-900/80 backdrop-blur-xl border border-neutral-200/80 dark:border-neutral-800/80 text-xs text-neutral-500 dark:text-neutral-400 pointer-fine:flex"- >- <Icon- name="tabler:info-circle"- class="size-3.5 shrink-0"- />- {{ $t('ui.action.select.rangeTip') }}- </p>-<div- class="px-2 py-1.5 bg-white/90 dark:bg-neutral-900/90 backdrop-blur-xl shadow-xl rounded-full border border-neutral-200/80 dark:border-neutral-800/80 flex items-center gap-3 sm:gap-6 shadow-black/5 dark:shadow-black/20"+ v-if="selectedRowsCount > 0"+ class="fixed bottom-8 left-1/2 -translate-x-1/2 z-60 w-max flex flex-col items-center gap-2">+ <p+ class="hidden items-center gap-1.5 max-w-[calc(100vw-2rem)] px-3 py-1 rounded-full bg-white/80 dark:bg-neutral-900/80 backdrop-blur-xl border border-neutral-200/80 dark:border-neutral-800/80 text-xs text-neutral-500 dark:text-neutral-400 pointer-fine:flex"+ >+ <Icon+ name="tabler:info-circle"+ class="size-3.5 shrink-0"+ />+ {{ $t('ui.action.select.rangeTip') }}+ </p>+<div- class="pl-4 pr-1 border-r border-neutral-200 dark:border-neutral-800 min-w-max"+ class="max-w-[calc(100vw-1rem)] overflow-x-auto px-2 py-1.5 bg-white/90 dark:bg-neutral-900/90 backdrop-blur-xl shadow-xl rounded-full border border-neutral-200/80 dark:border-neutral-800/80 flex items-center gap-3 sm:gap-6 shadow-black/5 dark:shadow-black/20">- <p- class="text-sm font-medium tracking-wide text-neutral-700 dark:text-neutral-200"+ <div+ class="pl-4 pr-1 border-r border-neutral-200 dark:border-neutral-800 min-w-max">- {{- $t('dashboard.photos.selection.selected', {- count: selectedRowsCount,- total: totalRowsCount,- })- }}- </p>- </div>+ <p+ class="text-sm font-medium tracking-wide text-neutral-700 dark:text-neutral-200"+ >+ {{+ $t('dashboard.photos.selection.selected', {+ count: selectedRowsCount,+ total: totalRowsCount,+ })+ }}+ </p>+ </div>- <div class="flex items-center gap-1 sm:gap-1.5 pr-2">- <UButton- color="neutral"- variant="ghost"- size="sm"- class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"- icon="tabler:refresh"- @click="handleBatchReprocess"- >- <span class="hidden sm:inline">{{- $t('dashboard.photos.selection.batchReprocess')- }}</span>- </UButton>+ <div class="flex items-center gap-1 sm:gap-1.5 pr-2">+ <UButton+ color="primary"+ variant="ghost"+ size="sm"+ class="rounded-full"+ icon="tabler:album"+ :aria-label="$t('dashboard.photos.selection.addToAlbum')"+ @click="openAddToAlbum"+ >+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.selection.addToAlbum')+ }}</span>+ </UButton>+ <UButton+ color="neutral"+ variant="ghost"+ size="sm"+ class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"+ icon="tabler:refresh"+ :aria-label="+ $t('dashboard.photos.selection.batchReprocess')+ "+ @click="handleBatchReprocess"+ >+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.selection.batchReprocess')+ }}</span>+ </UButton>- <UButton- color="neutral"- variant="ghost"- size="sm"- class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"- icon="tabler:map-off"- @click="handleBatchEraseLocation"- >- <span class="hidden sm:inline">{{- $t('dashboard.photos.selection.batchEraseLocation')- }}</span>- </UButton>+ <UButton+ color="neutral"+ variant="ghost"+ size="sm"+ class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"+ icon="tabler:map-off"+ :aria-label="+ $t('dashboard.photos.selection.batchEraseLocation')+ "+ @click="handleBatchEraseLocation"+ >+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.selection.batchEraseLocation')+ }}</span>+ </UButton>- <UButton- color="neutral"- variant="ghost"- size="sm"- class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"- icon="tabler:download"- @click="handleBatchDownload"- >- <span class="hidden sm:inline">{{- $t('dashboard.photos.selection.batchDownload')- }}</span>- </UButton>+ <UButton+ color="neutral"+ variant="ghost"+ size="sm"+ class="rounded-full text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:text-white dark:hover:bg-neutral-800"+ icon="tabler:download"+ :aria-label="+ $t('dashboard.photos.selection.batchDownload')+ "+ @click="handleBatchDownload"+ >+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.selection.batchDownload')+ }}</span>+ </UButton>- <UButton- color="error"- variant="ghost"- size="sm"- class="rounded-full hover:bg-error-50 dark:hover:bg-error-500/20"- icon="tabler:trash"- @click="handleBatchDelete"- >- <span class="hidden sm:inline">{{- $t('dashboard.photos.selection.batchDelete')- }}</span>- </UButton>+ <UButton+ color="error"+ variant="ghost"+ size="sm"+ class="rounded-full hover:bg-error-50 dark:hover:bg-error-500/20"+ icon="tabler:trash"+ :aria-label="$t('dashboard.photos.selection.batchDelete')"+ @click="handleBatchDelete"+ >+ <span class="hidden sm:inline">{{+ $t('dashboard.photos.selection.batchDelete')+ }}</span>+ </UButton>+ </div></div></div>- </div>- </transition>+ </transition>+ </div></div>- </div>- <USlideover+ <USlideoverv-model:open="isEditModalOpen":title="$t('dashboard.photos.editModal.title')":description="$t('dashboard.photos.editModal.description')"@@ -2887,6 +3117,89 @@ onUnmounted(() => {</template></USlideover>+ <UModal+ v-model:open="isAddToAlbumOpen"+ :dismissible="!isAddingToAlbum"+ :close="!isAddingToAlbum"+ :title="$t('dashboard.photos.addToAlbum.title')"+ :description="+ $t('dashboard.photos.addToAlbum.description', {+ photos: selectedBulkPhotoCountLabel,+ })+ "+ >+ <template #body>+ <UFormField :label="$t('dashboard.photos.addToAlbum.albumLabel')">+ <USelectMenu+ v-model="selectedBulkAlbumId"+ :items="bulkAlbumItems"+ value-key="value"+ label-key="label"+ :loading="isLoadingUploadAlbums"+ :disabled="+ isLoadingUploadAlbums ||+ uploadAlbumsLoadFailed ||+ isAddingToAlbum+ "+ :aria-label="$t('dashboard.photos.addToAlbum.albumLabel')"+ :placeholder="$t('dashboard.photos.addToAlbum.albumLabel')"+ class="w-full"+ />+ </UFormField>+ <p+ v-if="+ !isLoadingUploadAlbums &&+ !uploadAlbumsLoadFailed &&+ uploadAlbums.length === 0+ "+ class="mt-3 text-sm text-neutral-500 dark:text-neutral-400"+ >+ {{ $t('dashboard.photos.slideover.album.empty') }}+ </p>+ <div+ v-if="uploadAlbumsLoadFailed"+ role="alert"+ class="mt-3 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"+ >+ <span>{{+ $t('dashboard.photos.slideover.album.loadFailed')+ }}</span>+ <UButton+ size="xs"+ variant="soft"+ @click="loadUploadAlbums"+ >+ {{ $t('dashboard.photos.slideover.album.retry') }}+ </UButton>+ </div>+ </template>+ <template #footer>+ <div class="flex w-full justify-end gap-2">+ <UButton+ variant="ghost"+ color="neutral"+ :disabled="isAddingToAlbum"+ @click="isAddToAlbumOpen = false"+ >+ {{ $t('dashboard.photos.addToAlbum.cancel') }}+ </UButton>+ <UButton+ icon="tabler:album"+ :loading="isAddingToAlbum"+ :disabled="+ selectedBulkAlbumId === null ||+ isLoadingUploadAlbums ||+ uploadAlbumsLoadFailed ||+ isAddingToAlbum+ "+ @click="addSelectedPhotosToAlbum"+ >+ {{ $t('dashboard.photos.addToAlbum.confirm') }}+ </UButton>+ </div>+ </template>+ </UModal>+<UModal v-model:open="isDeleteConfirmOpen"><template #body><div class="space-y-4">diff --git a/docs/guide/usage.md b/docs/guide/usage.mdindex 5f7c22cc..a63861c1 100644--- a/docs/guide/usage.md+++ b/docs/guide/usage.md@@ -4,8 +4,12 @@Sign in and open `/dashboard`. Select files or drag them onto the Photos page to upload a batch. After upload, background tasks extract EXIF, create thumbnails and identify locations. The task queue shows progress, errors and retry results.+Administrators can choose an existing album in the upload form to add successfully processed photos to it. From an album page or its row in Dashboard → Albums, use **Upload to this album** to open the form with that album selected.+If duplicate handling is set to **Skip** and the photo is already in the library, ChronoFrame adds the existing photo to the selected album without uploading the duplicate file.+- Sort and filter the photo table and choose which columns to show. ChronoFrame remembers column visibility and supports sorting by upload date.- Select photos to delete, download, reindex or add them to albums in batches. You can also use Shift + click range selection.+- For **Add to album**, select photos in Dashboard → Photos, choose an album, and confirm. Photos already in that album are skipped.- Edit photo metadata such as title, description and rating.- Motion Photos with embedded video are also supported. The WebGL viewer provides zoom, pan and tiled rendering for large images.diff --git a/docs/zh/guide/usage.md b/docs/zh/guide/usage.mdindex 5c28fc91..21a26386 100644--- a/docs/zh/guide/usage.md+++ b/docs/zh/guide/usage.md@@ -4,8 +4,12 @@登录后访问 `/dashboard`,在照片页选择文件或拖入文件,支持批量上传。上传完成后,后台继续提取 EXIF、生成缩略图并识别拍摄地点;可以在任务队列中查看进度、失败原因和重试结果。+管理员上传时可以选择已有相册,成功处理的照片会自动加入该相册。也可以在相册页面或后台相册列表中点击“上传到此相册”,打开已预选对应相册的上传表单。+如果重复文件处理方式设为“跳过”,且照片已存在于图库中,ChronoFrame 会将现有照片加入所选相册,而不会重新上传重复文件。+- 照片表格支持排序、筛选和自选显示列,并记住列的显示状态,也支持按上传日期排序。- 选中照片后可以批量删除、下载、重新索引或加入相册。支持 Shift + 单击连续选择。+- 使用“添加到相册”时,先在后台照片页选中照片,再选择目标相册并确认;已在该相册中的照片会被跳过。- 编辑照片可以修改标题、描述、评分等元数据。- 也支持带有嵌入视频的 Motion Photo。大图由 WebGL 查看器显示,支持平移、缩放和分块渲染。diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex 3c8dd0d3..cd3a5681 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -4,7 +4,8 @@"description": "Album passwords cannot protect public S3, OpenList or CDN photo URLs: anyone with a direct link can still access the file without the password. Use local storage for protected albums. Changing the password or default storage does not revoke existing links or cached copies. If photos were already public, disable public access at the storage/CDN, clear caches and change object URLs."},"plural": {- "photo": "no photos | one photo | {count} photos"+ "photo": "no photos | one photo | {count} photos",+ "selectedPhoto": "no selected photos | one selected photo | {count} selected photos"},"ui": {"locale": {@@ -195,7 +196,8 @@"dateRange": "Date Range","created": "Created"},- "createdTooltip": "Created: {date}"+ "createdTooltip": "Created: {date}",+ "uploadToThisAlbum": "Upload to this album"},"map": {"setupNotice": {@@ -530,7 +532,10 @@"skip": {"title": "Duplicate File Skipped","message": "Photo \"{fileName}\" already exists and has been automatically skipped",- "info": "Existing photo taken on {dateTaken}"+ "info": "Existing photo taken on {dateTaken}",+ "addedToAlbum": "Existing photo added to the selected album. The duplicate file was not uploaded.",+ "alreadyInAlbum": "Existing photo is already in the selected album. The duplicate file was not uploaded.",+ "albumAddFailed": "The duplicate file was not uploaded, and the existing photo could not be added to the selected album. Use Add to album in the photo library."},"warn": {"title": "Duplicate File Detected",@@ -671,7 +676,8 @@"batchReprocess": "Reprocess","batchEraseLocation": "Erase location info","batchDownload": "Download",- "batchDelete": "Batch Delete"+ "batchDelete": "Batch Delete",+ "addToAlbum": "Add to album"},"slideover": {"title": "Upload Photos",@@ -683,8 +689,11 @@"empty": "No albums available yet.","hidden": "Hidden","passwordProtected": "Password protected",- "loadFailed": "Could not load albums. You can retry or upload without an album.",- "retry": "Retry"+ "loadFailed": "Could not load albums. Try again.",+ "loadFailedUpload": "Could not load albums. Retry, or choose no album to upload without one.",+ "retry": "Retry",+ "unavailable": "The selected album is unavailable. Choose another album before uploading.",+ "requestedUnavailable": "This album no longer exists. Choose another album before uploading."},"options": {"eraseLocation": {@@ -886,7 +895,21 @@"goToQueue": "Queue"}},- "previewTitle": "Photo Preview"+ "previewTitle": "Photo Preview",+ "addToAlbum": {+ "title": "Add photos to album",+ "description": "Add {photos} to an existing album.",+ "albumLabel": "Album",+ "cancel": "Cancel",+ "confirm": "Add photos",+ "success": "Album updated",+ "noChanges": "No changes",+ "result": "{added} added · {alreadyPresent} already in album",+ "missing": "{count} unavailable",+ "allAlreadyPresent": "All selected photos are already in this album.",+ "error": "Could not add photos to the album",+ "partialError": "The request failed after {processed}. Retry safely; duplicates will be skipped."+ }},"albums": {"title": "Album Management",@@ -980,7 +1003,8 @@"photoCount": "{count} photos","actions": {"moveUp": "Move up",- "moveDown": "Move down"+ "moveDown": "Move down",+ "uploadToAlbum": "Upload to \"{title}\""}},"overview": {diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex dc2ca4b3..299ab283 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -4,7 +4,8 @@"description": "アルバムのパスワードでは、S3、OpenList、CDN の公開写真 URL を保護できません。直接リンクを持つ人は、パスワードなしでファイルにアクセスできます。保護するアルバムにはローカルストレージを使用してください。パスワードやデフォルトのストレージを変更しても、既存のリンクやキャッシュは無効になりません。すでに公開した写真は、ストレージ/CDN 側で公開アクセスを無効にし、キャッシュを削除してオブジェクト URL を変更する必要があります。"},"plural": {- "photo": "写真がありません | 写真 {count} 枚"+ "photo": "写真がありません | 写真 {count} 枚",+ "selectedPhoto": "選択した写真 {count} 枚"},"ui": {"locale": {@@ -195,7 +196,8 @@"dateRange": "日付範囲","created": "作成"},- "createdTooltip": "作成日:{date}"+ "createdTooltip": "作成日:{date}",+ "uploadToThisAlbum": "このアルバムにアップロード"},"map": {"setupNotice": {@@ -596,7 +598,8 @@"batchReprocess": "一括再処理","batchEraseLocation": "位置情報を抹消","batchDownload": "一括ダウンロード",- "batchDelete": "一括削除"+ "batchDelete": "一括削除",+ "addToAlbum": "アルバムに追加"},"slideover": {"title": "写真をアップロード",@@ -608,8 +611,11 @@"empty": "利用できるアルバムがまだありません。","hidden": "非表示","passwordProtected": "パスワード保護",- "loadFailed": "アルバムを読み込めませんでした。再試行するか、アルバムなしでアップロードできます。",- "retry": "再試行"+ "loadFailed": "アルバムを読み込めませんでした。再試行してください。",+ "loadFailedUpload": "アルバムを読み込めませんでした。再試行するか、アルバムなしでアップロードしてください。",+ "retry": "再試行",+ "unavailable": "選択したアルバムを利用できません。別のアルバムを選択してください。",+ "requestedUnavailable": "このアルバムは存在しません。別のアルバムを選択してください。"},"options": {"eraseLocation": {@@ -811,7 +817,21 @@"goToQueue": "キュー"}},- "previewTitle": "写真プレビュー"+ "previewTitle": "写真プレビュー",+ "addToAlbum": {+ "title": "写真をアルバムに追加",+ "description": "{photos}を既存のアルバムに追加します。",+ "albumLabel": "アルバム",+ "cancel": "キャンセル",+ "confirm": "写真を追加",+ "success": "アルバムを更新しました",+ "noChanges": "変更はありません",+ "result": "{added} 枚追加 · {alreadyPresent} 枚は追加済み",+ "missing": "{count} 枚は利用できません",+ "allAlreadyPresent": "選択した写真はすべてこのアルバムに追加されています。",+ "error": "写真をアルバムに追加できませんでした",+ "partialError": "{processed} を処理した後にリクエストが失敗しました。再試行しても重複は追加されません。"+ }},"albums": {"title": "アルバム管理",@@ -905,7 +925,8 @@"photoCount": "{count} 枚","actions": {"moveUp": "上へ移動",- "moveDown": "下へ移動"+ "moveDown": "下へ移動",+ "uploadToAlbum": "\"{title}\" にアップロード"}},"overview": {@@ -1698,7 +1719,10 @@"skip": {"title": "重複ファイルをスキップしました","message": "写真「{fileName}」は既に存在するため、自動的にスキップされました",- "info": "既存の写真の撮影日:{dateTaken}"+ "info": "既存の写真の撮影日:{dateTaken}",+ "addedToAlbum": "既存の写真を選択したアルバムに追加しました。重複ファイルはアップロードしていません。",+ "alreadyInAlbum": "既存の写真はすでに選択したアルバムにあります。重複ファイルはアップロードしていません。",+ "albumAddFailed": "重複ファイルはアップロードされず、既存の写真も選択したアルバムに追加できませんでした。写真ライブラリの「アルバムに追加」を使用してください。"},"warn": {"title": "重複ファイルを検出しました",diff --git a/i18n/locales/ru.json b/i18n/locales/ru.jsonindex 612936a0..06706c2c 100644--- a/i18n/locales/ru.json+++ b/i18n/locales/ru.json@@ -4,7 +4,8 @@"description": "Пароль альбома не защищает публичные ссылки на фотографии в S3, OpenList или CDN: любой, у кого есть прямая ссылка, может открыть файл без пароля. Для защищённых альбомов используйте локальное хранилище. Изменение пароля или хранилища по умолчанию не отзывает существующие ссылки и кэшированные копии. Если фотографии уже были публичными, отключите публичный доступ в хранилище/CDN, очистите кэш и измените адреса объектов."},"plural": {- "photo": "нет фото | одно фото | {count} фото"+ "photo": "нет фото | одно фото | {count} фото",+ "selectedPhoto": "нет выбранных фото | одно выбранное фото | {count} выбранных фото"},"ui": {"locale": {@@ -195,7 +196,8 @@"dateRange": "Диапазон дат","created": "Дата создания"},- "createdTooltip": "Создан: {date}"+ "createdTooltip": "Создан: {date}",+ "uploadToThisAlbum": "Загрузить в этот альбом"},"map": {"setupNotice": {@@ -530,7 +532,10 @@"skip": {"title": "Дубликат пропущен","message": "Фотография «{fileName}» уже существует и была автоматически пропущена",- "info": "Существующая фотография снята {dateTaken}"+ "info": "Существующая фотография снята {dateTaken}",+ "addedToAlbum": "Существующая фотография добавлена в выбранный альбом. Дубликат не загружен.",+ "alreadyInAlbum": "Существующая фотография уже находится в выбранном альбоме. Дубликат не загружен.",+ "albumAddFailed": "Дубликат не загружен, а существующую фотографию не удалось добавить в выбранный альбом. Используйте «Добавить в альбом» в библиотеке фотографий."},"warn": {"title": "Обнаружен дубликат",@@ -671,7 +676,8 @@"batchReprocess": "Обработать повторно","batchEraseLocation": "Удалить данные о местоположении","batchDownload": "Скачать",- "batchDelete": "Удалить выбранные"+ "batchDelete": "Удалить выбранные",+ "addToAlbum": "Добавить в альбом"},"slideover": {"title": "Загрузка фотографий",@@ -683,8 +689,11 @@"empty": "Пока нет доступных альбомов.","hidden": "Скрытый","passwordProtected": "Защищён паролем",- "loadFailed": "Не удалось загрузить альбомы. Повторите попытку или загрузите без альбома.",- "retry": "Повторить"+ "loadFailed": "Не удалось загрузить альбомы. Повторите попытку.",+ "loadFailedUpload": "Не удалось загрузить альбомы. Повторите попытку или выберите «Без альбома», чтобы загрузить без него.",+ "retry": "Повторить",+ "unavailable": "Выбранный альбом недоступен. Выберите другой альбом перед загрузкой.",+ "requestedUnavailable": "Этот альбом больше не существует. Выберите другой альбом перед загрузкой."},"options": {"eraseLocation": {@@ -886,7 +895,21 @@"goToQueue": "Очередь"}},- "previewTitle": "Предпросмотр фотографии"+ "previewTitle": "Предпросмотр фотографии",+ "addToAlbum": {+ "title": "Добавить фотографии в альбом",+ "description": "Добавить {photos} в существующий альбом.",+ "albumLabel": "Альбом",+ "cancel": "Отмена",+ "confirm": "Добавить фотографии",+ "success": "Альбом обновлён",+ "noChanges": "Без изменений",+ "result": "Добавлено: {added} · Уже в альбоме: {alreadyPresent}",+ "missing": "{count} недоступно",+ "allAlreadyPresent": "Все выбранные фотографии уже есть в этом альбоме.",+ "error": "Не удалось добавить фотографии в альбом",+ "partialError": "Запрос завершился ошибкой после: {processed}. Повторите попытку: дубликаты будут пропущены."+ }},"albums": {"title": "Управление альбомами",@@ -980,7 +1003,8 @@"photoCount": "Фотографий: {count}","actions": {"moveUp": "Переместить вверх",- "moveDown": "Переместить вниз"+ "moveDown": "Переместить вниз",+ "uploadToAlbum": "Загрузить в альбом \"{title}\""}},"overview": {diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex 4ebd9ee8..bdad9197 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -209,7 +209,8 @@"dateRange": "日期范围","created": "创建"},- "createdTooltip": "创建于:{date}"+ "createdTooltip": "创建于:{date}",+ "uploadToThisAlbum": "上传到此相册"},"minimap": {"loading": "加载小地图..."@@ -417,7 +418,8 @@"iso": "ISO"},"plural": {- "photo": "没有照片 | 一张照片 | {count} 张照片"+ "photo": "没有照片 | 一张照片 | {count} 张照片",+ "selectedPhoto": "{count} 张选中的照片"},"title": {"dashboard": "仪表板",@@ -530,7 +532,10 @@"skip": {"title": "跳过重复文件","message": "照片 \"{fileName}\" 已存在,已自动跳过上传",- "info": "现有照片拍摄于 {dateTaken}"+ "info": "现有照片拍摄于 {dateTaken}",+ "addedToAlbum": "已将现有照片添加到所选相册,重复文件未重新上传。",+ "alreadyInAlbum": "现有照片已在所选相册中,重复文件未重新上传。",+ "albumAddFailed": "重复文件未上传,现有照片也未能添加到所选相册。请在照片图库中使用“添加到相册”。"},"warn": {"title": "检测到重复文件",@@ -671,7 +676,8 @@"batchReprocess": "重新处理","batchEraseLocation": "抹除位置信息","batchDownload": "批量下载",- "batchDelete": "批量删除"+ "batchDelete": "批量删除",+ "addToAlbum": "添加到相册"},"slideover": {"title": "上传照片",@@ -683,8 +689,11 @@"empty": "暂无可用相簿。","hidden": "已隐藏","passwordProtected": "密码保护",- "loadFailed": "无法加载相簿。你可以重试,或不选择相簿直接上传。",- "retry": "重试"+ "loadFailed": "无法加载相册,请重试。",+ "loadFailedUpload": "无法加载相册,请重试,或选择“不选择相册”后直接上传。",+ "retry": "重试",+ "unavailable": "所选相册不可用,请选择其他相册后再上传。",+ "requestedUnavailable": "此相册已不存在,请选择其他相册后再上传。"},"options": {"eraseLocation": {@@ -886,7 +895,21 @@"goToQueue": "队列"}},- "previewTitle": "照片预览"+ "previewTitle": "照片预览",+ "addToAlbum": {+ "title": "将照片添加到相册",+ "description": "将{photos}添加到现有相册。",+ "albumLabel": "相册",+ "cancel": "取消",+ "confirm": "添加照片",+ "success": "相册已更新",+ "noChanges": "无更改",+ "result": "已添加 {added} 张 · {alreadyPresent} 张已在相册中",+ "missing": "{count} 张不可用",+ "allAlreadyPresent": "所选照片均已在相册中。",+ "error": "无法将照片添加到相册",+ "partialError": "请求在 {processed} 后失败。可以安全重试,重复照片会被跳过。"+ }},"albums": {"title": "相簿管理",@@ -980,7 +1003,8 @@"photoCount": "{count} 张","actions": {"moveUp": "上移",- "moveDown": "下移"+ "moveDown": "下移",+ "uploadToAlbum": "上传到\"{title}\""}},"overview": {diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex 22f9b5e3..56d0e9d1 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -209,7 +209,8 @@"dateRange": "日期範圍","created": "建立"},- "createdTooltip": "建立於:{date}"+ "createdTooltip": "建立於:{date}",+ "uploadToThisAlbum": "上傳至此相簿"},"minimap": {"loading": "載入小地圖..."@@ -417,7 +418,8 @@"iso": "ISO"},"plural": {- "photo": "沒有相片 | 一張相片 | {count} 張相片"+ "photo": "沒有相片 | 一張相片 | {count} 張相片",+ "selectedPhoto": "{count} 張選取的相片"},"title": {"dashboard": "控制台",@@ -596,7 +598,8 @@"batchReprocess": "批量重新處理","batchEraseLocation": "抹除位置資訊","batchDownload": "批量下載",- "batchDelete": "批量刪除"+ "batchDelete": "批量刪除",+ "addToAlbum": "加入相簿"},"slideover": {"title": "上傳相片",@@ -608,8 +611,11 @@"empty": "暫無可用相簿。","hidden": "已隱藏","passwordProtected": "密碼保護",- "loadFailed": "無法載入相簿。你可以重試,或不選相簿直接上傳。",- "retry": "重試"+ "loadFailed": "無法載入相簿,請重試。",+ "loadFailedUpload": "無法載入相簿,請重試,或選擇「不選擇相簿」後直接上傳。",+ "retry": "重試",+ "unavailable": "所選相簿無法使用,請選擇其他相簿後再上傳。",+ "requestedUnavailable": "此相簿已不存在,請選擇其他相簿後再上傳。"},"options": {"eraseLocation": {@@ -811,7 +817,21 @@"goToQueue": "佇列"}},- "previewTitle": "相片預覽"+ "previewTitle": "相片預覽",+ "addToAlbum": {+ "title": "將相片加入相簿",+ "description": "將{photos}加入現有相簿。",+ "albumLabel": "相簿",+ "cancel": "取消",+ "confirm": "加入相片",+ "success": "相簿已更新",+ "noChanges": "沒有變更",+ "result": "已加入 {added} 張 · {alreadyPresent} 張已在相簿中",+ "missing": "{count} 張無法使用",+ "allAlreadyPresent": "所選相片均已在相簿中。",+ "error": "無法將相片加入相簿",+ "partialError": "請求在 {processed} 後失敗。可以安全重試,重複相片會被略過。"+ }},"albums": {"title": "相簿管理",@@ -905,7 +925,8 @@"photoCount": "{count} 張","actions": {"moveUp": "上移",- "moveDown": "下移"+ "moveDown": "下移",+ "uploadToAlbum": "上傳至\"{title}\""}},"overview": {@@ -1689,7 +1710,10 @@"skip": {"title": "已跳過重複檔案","message": "相片「{fileName}」已存在,已自動跳過上傳",- "info": "現有相片拍攝於 {dateTaken}"+ "info": "現有相片拍攝於 {dateTaken}",+ "addedToAlbum": "已將現有相片加入所選相簿,重複檔案沒有重新上傳。",+ "alreadyInAlbum": "現有相片已在所選相簿中,重複檔案沒有重新上傳。",+ "albumAddFailed": "重複檔案沒有上傳,現有相片亦未能加入所選相簿。請在相片圖庫使用「加入相簿」。"},"warn": {"title": "偵測到重複檔案",diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex d370e359..510d7150 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -209,7 +209,8 @@"dateRange": "日期範圍","created": "建立"},- "createdTooltip": "建立於:{date}"+ "createdTooltip": "建立於:{date}",+ "uploadToThisAlbum": "上傳至此相簿"},"minimap": {"loading": "正在載入小地圖..."@@ -417,7 +418,8 @@"iso": "ISO"},"plural": {- "photo": "沒有相片 | 一張相片 | {count} 張相片"+ "photo": "沒有相片 | 一張相片 | {count} 張相片",+ "selectedPhoto": "{count} 張選取的照片"},"title": {"dashboard": "儀表板",@@ -596,7 +598,8 @@"batchReprocess": "批量重新處理","batchEraseLocation": "抹除位置資訊","batchDownload": "批量下載",- "batchDelete": "批量刪除"+ "batchDelete": "批量刪除",+ "addToAlbum": "加入相簿"},"slideover": {"title": "上傳照片",@@ -608,8 +611,11 @@"empty": "目前沒有可用相簿。","hidden": "已隱藏","passwordProtected": "密碼保護",- "loadFailed": "無法載入相簿。你可以重試,或不選相簿直接上傳。",- "retry": "重試"+ "loadFailed": "無法載入相簿,請重試。",+ "loadFailedUpload": "無法載入相簿,請重試,或選擇「不選擇相簿」後直接上傳。",+ "retry": "重試",+ "unavailable": "所選相簿無法使用,請選擇其他相簿後再上傳。",+ "requestedUnavailable": "此相簿已不存在,請選擇其他相簿後再上傳。"},"options": {"eraseLocation": {@@ -811,7 +817,21 @@"goToQueue": "佇列"}},- "previewTitle": "照片預覽"+ "previewTitle": "照片預覽",+ "addToAlbum": {+ "title": "將照片加入相簿",+ "description": "將{photos}加入現有相簿。",+ "albumLabel": "相簿",+ "cancel": "取消",+ "confirm": "加入照片",+ "success": "相簿已更新",+ "noChanges": "沒有變更",+ "result": "已加入 {added} 張 · {alreadyPresent} 張已在相簿中",+ "missing": "{count} 張無法使用",+ "allAlreadyPresent": "所選照片均已在相簿中。",+ "error": "無法將照片加入相簿",+ "partialError": "請求在 {processed} 後失敗。可以安全重試,重複照片會被略過。"+ }},"albums": {"title": "相簿管理",@@ -905,7 +925,8 @@"photoCount": "{count} 張","actions": {"moveUp": "上移",- "moveDown": "下移"+ "moveDown": "下移",+ "uploadToAlbum": "上傳至\"{title}\""}},"overview": {@@ -1689,7 +1710,10 @@"skip": {"title": "已跳過重複檔案","message": "照片「{fileName}」已存在,已自動跳過上傳",- "info": "現有照片拍攝於 {dateTaken}"+ "info": "現有照片拍攝於 {dateTaken}",+ "addedToAlbum": "已將現有照片加入所選相簿,重複檔案未重新上傳。",+ "alreadyInAlbum": "現有照片已在所選相簿中,重複檔案未重新上傳。",+ "albumAddFailed": "重複檔案未上傳,現有照片也無法加入所選相簿。請在照片圖庫中使用「加入相簿」。"},"warn": {"title": "偵測到重複檔案",diff --git a/server/api/albums/[albumId]/index.delete.ts b/server/api/albums/[albumId]/index.delete.tsindex 44a159b8..ab105a02 100644--- a/server/api/albums/[albumId]/index.delete.ts+++ b/server/api/albums/[albumId]/index.delete.ts@@ -1,7 +1,8 @@import { z } from 'zod'+import { requireAdminSession } from '../../../utils/require-admin.ts'export default eventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)const { albumId } = await getValidatedRouterParams(event,diff --git a/server/api/albums/[albumId]/index.put.ts b/server/api/albums/[albumId]/index.put.tsindex c4655093..26dd852a 100644--- a/server/api/albums/[albumId]/index.put.ts+++ b/server/api/albums/[albumId]/index.put.ts@@ -2,11 +2,13 @@ import { z } from 'zod'import {ALBUM_PASSWORD_MAX_LENGTH,ALBUM_PASSWORD_MIN_LENGTH,-} from '~~/shared/utils/album-password'+} from '~~/shared/utils/album'import { hashAlbumPassword } from '../../../utils/album-access'+import { appendAlbumPhotos } from '../../../utils/album-membership.ts'+import { requireAdminSession } from '../../../utils/require-admin.ts'export default eventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)const { albumId } = await getValidatedRouterParams(event,@@ -107,17 +109,7 @@ export default eventHandler(async (event) => {}if (photoIds.size > 0) {- let pos = 1000000- for (const photoId of photoIds) {- tx.insert(tables.albumPhotos)- .values({- albumId,- photoId,- position: (pos += 10),- })- .onConflictDoNothing()- .run()- }+ appendAlbumPhotos(tx, albumId, [...photoIds])}}diff --git a/server/api/albums/[albumId]/photos/[photoId].delete.ts b/server/api/albums/[albumId]/photos/[photoId].delete.tsindex 59336a2a..f1269d6b 100644--- a/server/api/albums/[albumId]/photos/[photoId].delete.ts+++ b/server/api/albums/[albumId]/photos/[photoId].delete.ts@@ -1,8 +1,9 @@import { z } from 'zod'import { and } from 'drizzle-orm'+import { requireAdminSession } from '../../../../utils/require-admin.ts'export default eventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)const { albumId } = await getValidatedRouterParams(event,diff --git a/server/api/albums/[albumId]/photos/index.post.ts b/server/api/albums/[albumId]/photos/index.post.tsnew file mode 100644index 00000000..e9789198--- /dev/null+++ b/server/api/albums/[albumId]/photos/index.post.ts@@ -0,0 +1,38 @@+import {+ createError,+ eventHandler,+ getValidatedRouterParams,+ readValidatedBody,+} from 'h3'+import { z } from 'zod'+import { MAX_ALBUM_PHOTOS_PER_REQUEST } from '../../../../../shared/utils/album'+import { addExistingPhotosToAlbum } from '../../../../utils/album-photos-add'+import { useDB } from '../../../../utils/db'+import { requireAdminSession } from '../../../../utils/require-admin.ts'++export default eventHandler(async (event) => {+ await requireAdminSession(event)++ const { albumId } = await getValidatedRouterParams(+ event,+ z.object({ albumId: z.coerce.number().int().positive() }).parse,+ )+ const { photoIds } = await readValidatedBody(+ event,+ z.object({+ photoIds: z+ .array(z.string().min(1))+ .min(1)+ .max(MAX_ALBUM_PHOTOS_PER_REQUEST),+ }).parse,+ )++ const result = addExistingPhotosToAlbum(useDB(), albumId, photoIds)+ if ('error' in result) {+ throw createError({+ statusCode: 404,+ statusMessage: 'Album not found',+ })+ }+ return result+})diff --git a/server/api/albums/[albumId]/unlock.post.ts b/server/api/albums/[albumId]/unlock.post.tsindex 4109f0e7..42a87289 100644--- a/server/api/albums/[albumId]/unlock.post.ts+++ b/server/api/albums/[albumId]/unlock.post.ts@@ -1,6 +1,6 @@import { eq } from 'drizzle-orm'import { z } from 'zod'-import { ALBUM_PASSWORD_MAX_LENGTH } from '~~/shared/utils/album-password'+import { ALBUM_PASSWORD_MAX_LENGTH } from '~~/shared/utils/album'import {grantAlbumAccess,verifyAlbumPassword,diff --git a/server/api/albums/index.post.ts b/server/api/albums/index.post.tsindex 1da5b206..0771a68c 100644--- a/server/api/albums/index.post.ts+++ b/server/api/albums/index.post.ts@@ -3,11 +3,13 @@ import z from 'zod'import {ALBUM_PASSWORD_MAX_LENGTH,ALBUM_PASSWORD_MIN_LENGTH,-} from '~~/shared/utils/album-password'+} from '~~/shared/utils/album'import { hashAlbumPassword } from '../../utils/album-access'+import { appendAlbumPhotos } from '../../utils/album-membership.ts'+import { requireAdminSession } from '../../utils/require-admin.ts'export default eventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)const body = await readValidatedBody(event,@@ -61,17 +63,7 @@ export default eventHandler(async (event) => {}if (photoIds.size > 0) {- let pos = 1000000- for (const photoId of photoIds) {- tx.insert(tables.albumPhotos)- .values({- albumId,- photoId,- position: (pos += 10),- })- .onConflictDoNothing()- .run()- }+ appendAlbumPhotos(tx, albumId, [...photoIds])}return {diff --git a/server/api/albums/reorder.put.ts b/server/api/albums/reorder.put.tsindex e9539b71..91281fe5 100644--- a/server/api/albums/reorder.put.ts+++ b/server/api/albums/reorder.put.ts@@ -1,7 +1,8 @@import z from 'zod'+import { requireAdminSession } from '../../utils/require-admin.ts'export default eventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)const { albumIds } = await readValidatedBody(event,diff --git a/server/api/albums/upload-options.get.ts b/server/api/albums/upload-options.get.tsindex 64a61817..4b12248e 100644--- a/server/api/albums/upload-options.get.ts+++ b/server/api/albums/upload-options.get.ts@@ -1,6 +1,7 @@import { listUploadAlbumOptions } from '../../utils/upload-album-options'+import { requireAdminSession } from '../../utils/require-admin.ts'export default defineEventHandler(async (event) => {- await requireUserSession(event)+ await requireAdminSession(event)return listUploadAlbumOptions(useDB())})diff --git a/server/api/queue/add-task.post.ts b/server/api/queue/add-task.post.tsindex 2bb6b6fb..2345320c 100644--- a/server/api/queue/add-task.post.ts+++ b/server/api/queue/add-task.post.ts@@ -1,6 +1,7 @@import { z } from 'zod'import {photoTaskAlbumExists,+ queuePayloadRequiresAdmin,queuePayloadSchema,} from '../../utils/queue-payload.ts'@@ -17,14 +18,14 @@ export default defineEventHandler(async (event) => {}).parse,)- if (!photoTaskAlbumExists(payload)) {- throw createError({ statusCode: 404, statusMessage: 'Album not found' })- }- if (payload.type === 'location-migration' && !session.user.isAdmin)+ if (queuePayloadRequiresAdmin(payload) && !session.user.isAdmin)throw createError({statusCode: 403,statusMessage: 'Admin privileges required',})+ if (!photoTaskAlbumExists(payload)) {+ throw createError({ statusCode: 404, statusMessage: 'Album not found' })+ }const workerPool = globalThis.__workerPooldiff --git a/server/api/queue/add-tasks.post.ts b/server/api/queue/add-tasks.post.tsindex a2f213dc..9dd433fc 100644--- a/server/api/queue/add-tasks.post.ts+++ b/server/api/queue/add-tasks.post.ts@@ -1,6 +1,7 @@import { z } from 'zod'import {createPhotoTaskAlbumChecker,+ queuePayloadRequiresAdmin,queuePayloadSchema,} from '../../utils/queue-payload.ts'@@ -28,7 +29,7 @@ export default defineEventHandler(async (event) => {)if (- tasks.some((task) => task.payload.type === 'location-migration') &&+ tasks.some((task) => queuePayloadRequiresAdmin(task.payload)) &&!session.user.isAdmin)throw createError({diff --git a/server/utils/album-membership.ts b/server/utils/album-membership.tsnew file mode 100644index 00000000..9067aade--- /dev/null+++ b/server/utils/album-membership.ts@@ -0,0 +1,80 @@+import { eq, max } from 'drizzle-orm'+import type { drizzle } from 'drizzle-orm/better-sqlite3'+import * as tables from '../database/schema.ts'++export const ALBUM_PHOTO_POSITION_START = 1_000_000+export const ALBUM_PHOTO_POSITION_GAP = 10+const INSERT_BATCH_SIZE = 200++type Database = ReturnType<typeof drizzle>+export type AlbumTransaction = Parameters<+ Parameters<Database['transaction']>[0]+>[0]++/**+ * Returns the position of the last photo in the album. New photos are+ * appended after it with `ALBUM_PHOTO_POSITION_GAP` spacing.+ */+export const lastAlbumPhotoPosition = (+ tx: AlbumTransaction,+ albumId: number,+): number => {+ const last = tx+ .select({ position: max(tables.albumPhotos.position) })+ .from(tables.albumPhotos)+ .where(eq(tables.albumPhotos.albumId, albumId))+ .get()++ return last?.position ?? ALBUM_PHOTO_POSITION_START+}++/**+ * Appends photos to the end of an album without changing existing+ * membership or order. Photos already in the album are skipped through the+ * unique album/photo index.+ *+ * Returns the number of membership rows actually inserted.+ */+export const appendAlbumPhotos = (+ tx: AlbumTransaction,+ albumId: number,+ photoIds: readonly string[],+): number => {+ const uniqueIds = [...new Set(photoIds)]+ if (uniqueIds.length === 0) return 0++ let position = lastAlbumPhotoPosition(tx, albumId)+ let added = 0++ for (let index = 0; index < uniqueIds.length; index += INSERT_BATCH_SIZE) {+ const batch = uniqueIds.slice(index, index + INSERT_BATCH_SIZE)+ const result = tx+ .insert(tables.albumPhotos)+ .values(+ batch.map((photoId, offset) => ({+ albumId,+ photoId,+ position: position + (offset + 1) * ALBUM_PHOTO_POSITION_GAP,+ })),+ )+ .onConflictDoNothing()+ .run()++ position += batch.length * ALBUM_PHOTO_POSITION_GAP+ added += result.changes+ }++ return added+}++/**+ * Album membership is part of the album's state, so adding photos updates+ * its `updatedAt` timestamp. Callers must invoke this only when membership+ * actually changed.+ */+export const touchAlbum = (tx: AlbumTransaction, albumId: number): void => {+ tx.update(tables.albums)+ .set({ updatedAt: new Date() })+ .where(eq(tables.albums.id, albumId))+ .run()+}diff --git a/server/utils/album-photos-add.ts b/server/utils/album-photos-add.tsnew file mode 100644index 00000000..5815129a--- /dev/null+++ b/server/utils/album-photos-add.ts@@ -0,0 +1,59 @@+import { and, eq, inArray } from 'drizzle-orm'+import type { drizzle } from 'drizzle-orm/better-sqlite3'+import type { AddPhotosToAlbumResult } from '../../shared/utils/album.ts'+import * as tables from '../database/schema.ts'+import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'++export const addExistingPhotosToAlbum = (+ db: ReturnType<typeof drizzle>,+ albumId: number,+ photoIds: string[],+): AddPhotosToAlbumResult | { error: 'album-not-found' } =>+ db.transaction((tx) => {+ const album = tx+ .select({ id: tables.albums.id })+ .from(tables.albums)+ .where(eq(tables.albums.id, albumId))+ .get()+ if (!album) return { error: 'album-not-found' }++ const uniqueIds = [...new Set(photoIds)]+ const foundPhotoIds = new Set<string>()+ const existingIds = new Set<string>()+ for (let index = 0; index < uniqueIds.length; index += 400) {+ const ids = uniqueIds.slice(index, index + 400)+ const foundPhotos = tx+ .select({ id: tables.photos.id })+ .from(tables.photos)+ .where(inArray(tables.photos.id, ids))+ .all()+ for (const { id } of foundPhotos) foundPhotoIds.add(id)++ const memberships = tx+ .select({ photoId: tables.albumPhotos.photoId })+ .from(tables.albumPhotos)+ .where(+ and(+ eq(tables.albumPhotos.albumId, albumId),+ inArray(tables.albumPhotos.photoId, ids),+ ),+ )+ .all()+ for (const { photoId } of memberships) existingIds.add(photoId)+ }++ const missingIds = uniqueIds.filter(+ (photoId) => !foundPhotoIds.has(photoId),+ )+ const appendableIds = uniqueIds.filter(+ (photoId) => foundPhotoIds.has(photoId) && !existingIds.has(photoId),+ )+ const added = appendAlbumPhotos(tx, albumId, appendableIds)+ if (added > 0) touchAlbum(tx, albumId)++ return {+ added,+ alreadyPresent: uniqueIds.length - added - missingIds.length,+ missing: missingIds.length,+ }+ })diff --git a/server/utils/photo-album.ts b/server/utils/photo-album.tsindex d129c818..83953197 100644--- a/server/utils/photo-album.ts+++ b/server/utils/photo-album.ts@@ -1,7 +1,8 @@-import { and, eq, max } from 'drizzle-orm'+import { and, eq } from 'drizzle-orm'import type { drizzle } from 'drizzle-orm/better-sqlite3'import * as tables from '../database/schema.ts'import { QueueWarningCode } from '../../shared/utils/queue-warning.ts'+import { appendAlbumPhotos, touchAlbum } from './album-membership.ts'export type AlbumAssignmentResult =| 'no-album'@@ -41,21 +42,10 @@ export const persistPhotoWithAlbum = (.get()if (existing) return 'already-added'- const last = tx- .select({ position: max(tables.albumPhotos.position) })- .from(tables.albumPhotos)- .where(eq(tables.albumPhotos.albumId, albumId))- .get()-- const insertResult = tx- .insert(tables.albumPhotos)- .values({- albumId,- photoId: photo.id,- position: (last?.position ?? 1000000) + 10,- })- .onConflictDoNothing()- .run()+ if (appendAlbumPhotos(tx, albumId, [photo.id]) === 0) {+ return 'already-added'+ }- return insertResult.changes > 0 ? 'added' : 'already-added'+ touchAlbum(tx, albumId)+ return 'added'})diff --git a/server/utils/queue-payload.ts b/server/utils/queue-payload.tsindex 1ba485be..9902dbbc 100644--- a/server/utils/queue-payload.ts+++ b/server/utils/queue-payload.ts@@ -29,6 +29,12 @@ export const queuePayloadSchema = z.discriminatedUnion('type', [}),])+export const queuePayloadRequiresAdmin = (+ payload: z.infer<typeof queuePayloadSchema>,+): boolean =>+ payload.type === 'location-migration' ||+ (payload.type === 'photo' && payload.albumId !== undefined)+export const photoTaskAlbumExists = (payload: z.infer<typeof queuePayloadSchema>,db?: ReturnType<typeof useDB>,@@ -44,9 +50,7 @@ export const photoTaskAlbumExists = (return Boolean(album)}-export const createPhotoTaskAlbumChecker = (- db?: ReturnType<typeof useDB>,-) => {+export const createPhotoTaskAlbumChecker = (db?: ReturnType<typeof useDB>) => {const cache = new Map<number, boolean>()return (payload: z.infer<typeof queuePayloadSchema>): boolean => {diff --git a/server/utils/require-admin.ts b/server/utils/require-admin.tsnew file mode 100644index 00000000..82f1d5e7--- /dev/null+++ b/server/utils/require-admin.ts@@ -0,0 +1,12 @@+import type { H3Event } from 'h3'++export const requireAdminSession = async (event: H3Event) => {+ const session = await requireUserSession(event)+ if (!session.user.isAdmin) {+ throw createError({+ statusCode: 403,+ statusMessage: 'Admin privileges required',+ })+ }+ return session+}diff --git a/shared/utils/album-password.ts b/shared/utils/album.tssimilarity index 64%rename from shared/utils/album-password.tsrename to shared/utils/album.tsindex d8245dae..9bb771f9 100644--- a/shared/utils/album-password.ts+++ b/shared/utils/album.ts@@ -1,5 +1,12 @@export const ALBUM_PASSWORD_MIN_LENGTH = 6export const ALBUM_PASSWORD_MAX_LENGTH = 128+export const MAX_ALBUM_PHOTOS_PER_REQUEST = 1000++export interface AddPhotosToAlbumResult {+ added: number+ alreadyPresent: number+ missing: number+}export function isValidAlbumPasswordLength(password: string): boolean {return (diff --git a/tests/album-admin-auth.test.ts b/tests/album-admin-auth.test.tsnew file mode 100644index 00000000..ad320b13--- /dev/null+++ b/tests/album-admin-auth.test.ts@@ -0,0 +1,54 @@+import assert from 'node:assert/strict'+import test from 'node:test'++test('album mutations reject non-admin sessions before reading input or accessing the database', async () => {+ let bodyReads = 0+ let dbAccesses = 0+ const globals = {+ eventHandler: (handler: unknown) => handler,+ requireUserSession: async (event: { role: 'guest' | 'user' | 'admin' }) => {+ if (event.role === 'guest') {+ throw Object.assign(new Error('Authentication required'), {+ statusCode: 401,+ })+ }+ return { user: { isAdmin: event.role === 'admin' ? 1 : 0 } }+ },+ createError: (options: { statusCode: number; statusMessage: string }) =>+ Object.assign(new Error(options.statusMessage), options),+ readValidatedBody: () => {+ bodyReads+++ return { albumIds: [] }+ },+ useDB: () => {+ dbAccesses+++ throw new Error('Unexpected database access')+ },+ }+ const previous = Object.getOwnPropertyDescriptors(globalThis)+ Object.assign(globalThis, globals)+ try {+ const { requireAdminSession } =+ await import('../server/utils/require-admin.ts')+ const { default: reorderAlbums } =+ await import('../server/api/albums/reorder.put.ts')++ await assert.rejects(requireAdminSession({ role: 'guest' } as never), {+ statusCode: 401,+ })+ await assert.rejects(reorderAlbums({ role: 'user' } as never), {+ statusCode: 403,+ })+ assert.equal(bodyReads, 0)+ assert.equal(dbAccesses, 0)+ assert.equal(+ (await requireAdminSession({ role: 'admin' } as never)).user.isAdmin,+ 1,+ )+ } finally {+ for (const key of Object.keys(globals)) {+ if (previous[key]) Object.defineProperty(globalThis, key, previous[key])+ else Reflect.deleteProperty(globalThis, key)+ }+ }+})diff --git a/tests/album-photos-add.test.ts b/tests/album-photos-add.test.tsnew file mode 100644index 00000000..0398a53c--- /dev/null+++ b/tests/album-photos-add.test.ts@@ -0,0 +1,181 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import Database from 'better-sqlite3'+import { eq } from 'drizzle-orm'+import { drizzle } from 'drizzle-orm/better-sqlite3'+import { migrate } from 'drizzle-orm/better-sqlite3/migrator'+import * as schema from '../server/database/schema.ts'+import { addExistingPhotosToAlbum } from '../server/utils/album-photos-add.ts'++const setup = () => {+ const sqlite = new Database(':memory:')+ const db = drizzle(sqlite, { schema })+ migrate(db, { migrationsFolder: './server/database/migrations' })+ return { sqlite, db }+}++test('bulk add appends missing photos without changing existing membership or cover', () => {+ const { sqlite, db } = setup()+ try {+ db.insert(schema.photos)+ .values([{ id: 'cover' }, { id: 'new-a' }, { id: 'new-b' }])+ .run()+ const originalUpdatedAt = new Date('2020-01-01T00:00:00Z')+ const album = db+ .insert(schema.albums)+ .values({+ title: 'Trip',+ coverPhotoId: 'cover',+ updatedAt: originalUpdatedAt,+ })+ .returning()+ .get()+ db.insert(schema.albumPhotos)+ .values({ albumId: album.id, photoId: 'cover', position: 25 })+ .run()++ assert.deepEqual(+ addExistingPhotosToAlbum(db, album.id, ['new-a', 'cover', 'new-b']),+ { added: 2, alreadyPresent: 1, missing: 0 },+ )+ assert.ok(+ db+ .select()+ .from(schema.albums)+ .where(eq(schema.albums.id, album.id))+ .get()!+ .updatedAt.getTime() > originalUpdatedAt.getTime(),+ )+ assert.deepEqual(+ db+ .select({+ photoId: schema.albumPhotos.photoId,+ position: schema.albumPhotos.position,+ })+ .from(schema.albumPhotos)+ .orderBy(schema.albumPhotos.position)+ .all(),+ [+ { photoId: 'cover', position: 25 },+ { photoId: 'new-a', position: 35 },+ { photoId: 'new-b', position: 45 },+ ],+ )+ assert.equal(db.select().from(schema.albums).get()!.coverPhotoId, 'cover')++ const sentinelUpdatedAt = new Date('2020-01-02T00:00:00Z')+ db.update(schema.albums)+ .set({ updatedAt: sentinelUpdatedAt })+ .where(eq(schema.albums.id, album.id))+ .run()++ assert.deepEqual(+ addExistingPhotosToAlbum(db, album.id, ['new-a', 'cover', 'new-b']),+ { added: 0, alreadyPresent: 3, missing: 0 },+ )+ assert.equal(+ db+ .select()+ .from(schema.albums)+ .where(eq(schema.albums.id, album.id))+ .get()!+ .updatedAt.getTime(),+ sentinelUpdatedAt.getTime(),+ )+ assert.deepEqual(+ addExistingPhotosToAlbum(db, album.id, ['new-a', 'new-a']),+ { added: 0, alreadyPresent: 1, missing: 0 },+ )+ assert.equal(db.select().from(schema.albumPhotos).all().length, 3)+ } finally {+ sqlite.close()+ }+})++test('bulk add rejects missing albums', () => {+ const { sqlite, db } = setup()+ try {+ db.insert(schema.photos).values({ id: 'exists' }).run()++ assert.deepEqual(addExistingPhotosToAlbum(db, 999, ['exists']), {+ error: 'album-not-found',+ })+ } finally {+ sqlite.close()+ }+})++test('bulk add skips missing photos and reports them', () => {+ const { sqlite, db } = setup()+ try {+ const album = db+ .insert(schema.albums)+ .values({ title: 'Trip' })+ .returning()+ .get()+ db.insert(schema.photos).values({ id: 'exists' }).run()++ assert.deepEqual(+ addExistingPhotosToAlbum(db, album.id, ['exists', 'missing']),+ { added: 1, alreadyPresent: 0, missing: 1 },+ )+ assert.deepEqual(addExistingPhotosToAlbum(db, album.id, ['missing']), {+ added: 0,+ alreadyPresent: 0,+ missing: 1,+ })+ assert.deepEqual(+ addExistingPhotosToAlbum(db, album.id, ['exists', 'missing']),+ { added: 0, alreadyPresent: 1, missing: 1 },+ )+ assert.deepEqual(+ db+ .select({ photoId: schema.albumPhotos.photoId })+ .from(schema.albumPhotos)+ .all(),+ [{ photoId: 'exists' }],+ )+ } finally {+ sqlite.close()+ }+})++test('bulk add handles selections larger than one SQLite query chunk', () => {+ const { sqlite, db } = setup()+ try {+ const album = db+ .insert(schema.albums)+ .values({ title: 'Trip' })+ .returning()+ .get()+ const photoIds = Array.from({ length: 405 }, (_, index) => `photo-${index}`)+ db.insert(schema.photos)+ .values(photoIds.map((id) => ({ id })))+ .run()+ db.insert(schema.albumPhotos)+ .values({ albumId: album.id, photoId: 'photo-100', position: 25 })+ .run()++ assert.deepEqual(addExistingPhotosToAlbum(db, album.id, photoIds), {+ added: 404,+ alreadyPresent: 1,+ missing: 0,+ })+ const memberships = db+ .select({+ photoId: schema.albumPhotos.photoId,+ position: schema.albumPhotos.position,+ })+ .from(schema.albumPhotos)+ .orderBy(schema.albumPhotos.position)+ .all()+ assert.deepEqual(memberships, [+ { photoId: 'photo-100', position: 25 },+ ...photoIds+ .filter((id) => id !== 'photo-100')+ .map((photoId, index) => ({ photoId, position: 35 + index * 10 })),+ ])+ } finally {+ sqlite.close()+ }+})diff --git a/tests/location-migration.test.ts b/tests/location-migration.test.tsindex 604b5857..9b772d41 100644--- a/tests/location-migration.test.ts+++ b/tests/location-migration.test.ts@@ -157,6 +157,27 @@ test('existing queue APIs accept migration tasks only for administrators', asyncbatch({ admin: false, body: { tasks: [{ payload }] } } as never),{ statusCode: 403 },)+ const albumPayload = {+ type: 'photo',+ storageKey: 'image.jpg',+ albumId: 7,+ }+ await assert.rejects(+ single({ admin: false, body: { payload: albumPayload } } as never),+ { statusCode: 403 },+ )+ await assert.rejects(+ batch({+ admin: false,+ body: {+ tasks: [+ { payload: { type: 'photo', storageKey: 'plain.jpg' } },+ { payload: albumPayload },+ ],+ },+ } as never),+ { statusCode: 403 },+ )assert.equal(submitted.length, 0)assert.equal((await single({ admin: true, body: { payload } } as never)).taskId,diff --git a/tests/upload-album-membership.test.ts b/tests/upload-album-membership.test.tsindex 84e0a694..59a5343f 100644--- a/tests/upload-album-membership.test.ts+++ b/tests/upload-album-membership.test.ts@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'import test from 'node:test'import { readFileSync } from 'node:fs'import Database from 'better-sqlite3'+import { eq } from 'drizzle-orm'import { drizzle } from 'drizzle-orm/better-sqlite3'import { migrate } from 'drizzle-orm/better-sqlite3/migrator'import * as schema from '../server/database/schema.ts'@@ -17,9 +18,10 @@ const setup = () => {test('successful photo processing appends once and preserves album order', () => {const { sqlite, db } = setup()try {+ const originalUpdatedAt = new Date('2020-01-01T00:00:00Z')const album = db.insert(schema.albums)- .values({ title: 'Trip' })+ .values({ title: 'Trip', updatedAt: originalUpdatedAt }).returning().get()db.insert(schema.photos).values({ id: 'existing' }).run()@@ -29,6 +31,15 @@ test('successful photo processing appends once and preserves album order', () =>assert.equal(persistPhotoWithAlbum(db, { id: 'first' }, album.id), 'added')assert.equal(persistPhotoWithAlbum(db, { id: 'second' }, album.id), 'added')+ assert.ok(+ db+ .select()+ .from(schema.albums)+ .where(eq(schema.albums.id, album.id))+ .get()!+ .updatedAt.getTime() > originalUpdatedAt.getTime(),+ )+const beforeRetry = db.select().from(schema.albumPhotos)@@ -42,10 +53,25 @@ test('successful photo processing appends once and preserves album order', () =>assert.ok(beforeRetry[1]!.position > beforeRetry[0]!.position)assert.ok(beforeRetry[2]!.position > beforeRetry[1]!.position)+ const sentinelUpdatedAt = new Date('2020-01-02T00:00:00Z')+ db.update(schema.albums)+ .set({ updatedAt: sentinelUpdatedAt })+ .where(eq(schema.albums.id, album.id))+ .run()+assert.equal(persistPhotoWithAlbum(db, { id: 'first', title: 'Updated' }, album.id),'already-added',)+ assert.equal(+ db+ .select()+ .from(schema.albums)+ .where(eq(schema.albums.id, album.id))+ .get()!+ .updatedAt.getTime(),+ sentinelUpdatedAt.getTime(),+ )const afterRetry = db.select().from(schema.albumPhotos)