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.

refactor: photo location display logic and improve code readability in photos.vue

Timothy Yin3dbbec0f5abe
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 33a134af..e918e1a4 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -14,5 +14,6 @@
"ui:\\s*{([^)]*)\\s*}",
"(?:'|\"|`)([^']*)(?:'|\"|`)"
]
- ]
+ ],
+ "eslint.useFlatConfig": true
}
\ No newline at end of file
diff --git a/app/components/masonry/HeaderItem.vue b/app/components/masonry/HeaderItem.vue
index 74945d59..fb0ce3ce 100644
--- a/app/components/masonry/HeaderItem.vue
+++ b/app/components/masonry/HeaderItem.vue
@@ -33,7 +33,7 @@ const handleOpenLogin = () => {
></div>
<div class="flex flex-col items-center py-6 gap-2">
<AuthState>
- <template #default="{ loggedIn, user, clear }">
+ <template #default="{ loggedIn, clear }">
<div class="flex flex-col items-center gap-2">
<div class="relative mx-auto">
<div
@@ -66,8 +66,8 @@ const handleOpenLogin = () => {
<p class="font-[Pacifico]">Mems rest within the lens.</p>
</div>
<div
- class="text-center mt-3"
v-if="loggedIn"
+ class="text-center mt-3"
>
<div class="flex items-center gap-2">
<UButton
diff --git a/app/components/masonry/PhotoItem.client.vue b/app/components/masonry/PhotoItem.client.vue
index 21a62ffa..c366df91 100644
--- a/app/components/masonry/PhotoItem.client.vue
+++ b/app/components/masonry/PhotoItem.client.vue
@@ -15,8 +15,6 @@ const emit = defineEmits<{
openViewer: [number]
}>()
-const toast = useToast()
-
// Constants
const ITEM_GAP = 4
@@ -66,11 +64,6 @@ const aspectRatio = computed(() => {
return 1.2
})
-const containerHeight = computed(() => {
- const currentWidth = containerWidth.value || 280
- return Math.round(currentWidth * aspectRatio.value)
-})
-
// Show info overlay only when not playing video or video has finished
const shouldShowInfoOverlay = computed(() => {
if (!props.photo.isLivePhoto) return true
@@ -88,7 +81,7 @@ const shouldShowInfoOverlay = computed(() => {
})
// Methods
-const handleImageLoad = (event: Event) => {
+const handleImageLoad = (_event: Event) => {
isLoading.value = false
}
@@ -465,12 +458,12 @@ onUnmounted(() => {
class="w-full relative"
:style="{ aspectRatio }"
>
- <!-- Thumbhash placeholder -->
+ <!-- ThumbHash placeholder -->
<div
v-if="isLoading && photo.thumbnailHash"
class="absolute inset-0 w-full h-full"
>
- <Thumbhash
+ <ThumbHash
:thumbhash="photo.thumbnailHash"
class="w-full h-full object-cover scale-110"
:alt="photo.title || 'Photo placeholder'"
@@ -485,8 +478,8 @@ onUnmounted(() => {
<!-- Main image with motion transition -->
<motion.img
- ref="mainImageRef"
v-show="!isLoading"
+ ref="mainImageRef"
:src="photo.thumbnailUrl || ''"
:alt="photo.title || photo.description || 'Photo'"
class="absolute inset-0 w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
diff --git a/app/components/masonry/Root.vue b/app/components/masonry/Root.vue
index 41702498..3d93c5ce 100644
--- a/app/components/masonry/Root.vue
+++ b/app/components/masonry/Root.vue
@@ -283,7 +283,7 @@ const handleOpenViewer = (index: number) => {
:key="photo.id || index"
:photo="photo"
:index="index"
- :hasAnimated
+ :has-animated
:first-screen-items="FIRST_SCREEN_ITEMS_COUNT"
@visibility-change="handleVisibilityChange"
@open-viewer="handleOpenViewer($event)"
diff --git a/app/components/photo/GalleryThumbnail.vue b/app/components/photo/GalleryThumbnail.vue
index 69a18ab5..d35925bb 100644
--- a/app/components/photo/GalleryThumbnail.vue
+++ b/app/components/photo/GalleryThumbnail.vue
@@ -118,7 +118,7 @@ onMounted(() => {
})
// 响应式监听
-watch(() => props.currentIndex, (newIndex, oldIndex) => {
+watch(() => props.currentIndex, (_newIndex, _oldIndex) => {
scrollToActiveThumbnail()
// 这里不需要再次 emit,因为索引变化是由外部传入的
// 只需要确保滚动位置正确即可
@@ -159,7 +159,7 @@ watch(isSmallScreen, scrollToActiveThumbnail)
}"
@click="onThumbnailClick(photo.index)"
>
- <Thumbhash
+ <ThumbHash
v-if="photo.thumbnailHash"
:thumbhash="photo.thumbnailHash"
class="absolute inset-0 w-full h-full"
diff --git a/app/components/photo/InfoPanel.vue b/app/components/photo/InfoPanel.vue
index f8177865..94c7c4e8 100644
--- a/app/components/photo/InfoPanel.vue
+++ b/app/components/photo/InfoPanel.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
-import { ref, computed } from 'vue'
-import { motion, AnimatePresence } from 'motion-v'
+import { computed } from 'vue'
+import { motion } from 'motion-v'
import type { NeededExif } from '../../../shared/types/photo'
import type { KVData } from './KVRenderer.vue'
import { formatCameraInfo, formatLensInfo } from '~/utils/camera'
@@ -55,25 +55,6 @@ const formatExposureTime = (
}
}
-// 格式化GPS坐标为标准的N/E格式
-const formatGPSCoordinates = (latitude: number, longitude: number): string => {
- const latDirection = latitude >= 0 ? 'N' : 'S'
- const lngDirection = longitude >= 0 ? 'E' : 'W'
-
- const latDegrees = Math.abs(latitude)
- const lngDegrees = Math.abs(longitude)
-
- const latDeg = Math.floor(latDegrees)
- const latMin = Math.floor((latDegrees - latDeg) * 60)
- const latSec = ((latDegrees - latDeg) * 60 - latMin) * 60
-
- const lngDeg = Math.floor(lngDegrees)
- const lngMin = Math.floor((lngDegrees - lngDeg) * 60)
- const lngSec = ((lngDegrees - lngDeg) * 60 - lngMin) * 60
-
- return `${latDeg}°${latMin}'${latSec.toFixed(2)}"${latDirection}, ${lngDeg}°${lngMin}'${lngSec.toFixed(2)}"${lngDirection}`
-}
-
// 格式化GPS坐标为两行显示
const formatGPSCoordinatesMultiLine = (
latitude: number,
@@ -461,11 +442,11 @@ const isMobile = useMediaQuery('(max-width: 768px)')
</h3>
<UButton
v-if="isMobile && onClose"
- @click="onClose"
icon="tabler:x"
variant="ghost"
color="neutral"
size="sm"
+ @click="onClose"
/>
</div>
diff --git a/app/components/photo/ProgressiveImage.vue b/app/components/photo/ProgressiveImage.vue
index 4c2053b5..5f9bc08c 100644
--- a/app/components/photo/ProgressiveImage.vue
+++ b/app/components/photo/ProgressiveImage.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { WebGLImageViewer } from '@chronoframe/webgl-image'
import type { LoadingIndicatorRef } from './LoadingIndicator.vue'
-import { ImageLoaderManager } from '~/libs/image-loader-manager'
+import type { ImageLoaderManager } from '~/libs/image-loader-manager'
interface Props {
src: string
@@ -28,9 +28,21 @@ const props = withDefaults(defineProps<Props>(), {
enablePan: true,
enableZoom: true,
isCurrentImage: true,
+ thumbnailSrc: '',
+ alt: 'Image',
+ width: undefined,
+ height: undefined,
+ className: '',
+ onProgress: undefined,
+ onError: undefined,
+ onZoomChange: undefined,
+ onBlobSrcChange: undefined,
+ onImageLoaded: undefined,
+ isLivePhoto: false,
+ livePhotoVideoUrl: '',
+ isHDR: false,
})
-const imageRef = ref<HTMLImageElement>()
const containerRef = ref<HTMLDivElement>()
// state
diff --git a/app/components/photo/Viewer.vue b/app/components/photo/Viewer.vue
index 671b199b..f2093cf9 100644
--- a/app/components/photo/Viewer.vue
+++ b/app/components/photo/Viewer.vue
@@ -400,7 +400,7 @@ const swiperModules = [Navigation, Keyboard, Virtual]
:transition="{ duration: 0.3 }"
class="fixed inset-0 z-40"
>
- <Thumbhash
+ <ThumbHash
:thumbhash="currentPhoto.thumbnailHash"
class="w-full h-full scale-110"
/>
@@ -411,11 +411,11 @@ const swiperModules = [Navigation, Keyboard, Virtual]
<AnimatePresence>
<motion.div
v-if="isOpen"
+ ref="containerRef"
:initial="{ opacity: 0 }"
:animate="{ opacity: 1 }"
:exit="{ opacity: 0 }"
:transition="{ duration: 0.3 }"
- ref="containerRef"
class="fixed inset-0 z-50 flex items-center justify-center"
:style="{ touchAction: isMobile ? 'manipulation' : 'none' }"
@click.self="emit('close')"
diff --git a/app/composables/useImageLoader.ts b/app/composables/useImageLoader.ts
index a625ef44..03b532c7 100644
--- a/app/composables/useImageLoader.ts
+++ b/app/composables/useImageLoader.ts
@@ -40,7 +40,7 @@ export const useImageLoader = (
updateBlobSrc?.(loadResult.blobSrc)
updateHighResLoaded?.(true)
onImageLoaded?.() // 通知图片加载完成
- } catch (err) {
+ } catch {
updateError?.(true)
loadingIndicatorRef?.updateLoadingState({
isVisible: true,
diff --git a/app/composables/useUpload.ts b/app/composables/useUpload.ts
index ed04f939..62518a28 100644
--- a/app/composables/useUpload.ts
+++ b/app/composables/useUpload.ts
@@ -214,7 +214,7 @@ export function useUpload(options: UseUploadOptions = {}) {
if (responseText) {
error += ` - ${responseText}`
}
- } catch (e) {
+ } catch {
// 忽略解析错误
}
diff --git a/app/layouts/dashboard.vue b/app/layouts/dashboard.vue
index 25d6354a..e2f4926f 100644
--- a/app/layouts/dashboard.vue
+++ b/app/layouts/dashboard.vue
@@ -51,38 +51,13 @@ const closeMobileMenu = () => {
</script>
<template>
- <header
- v-if="loggedIn"
- class="w-full px-4 border-b border-default"
- >
- <!-- 桌面端导航 -->
- <div class="hidden md:flex items-center gap-4">
- <div class="flex items-center gap-2">
- <Icon
- name="tabler:photo-circle"
- class="size-6 text-primary"
- />
- <NuxtLink
- to="/"
- class="text-lg font-medium text-nowrap"
- >
- TimoYin's mems
- </NuxtLink>
- </div>
- <UNavigationMenu
- variant="pill"
- :items="items"
- :ui="{
- viewportWrapper: 'max-w-5xl',
- }"
- class="w-full"
- />
- </div>
-
- <!-- 移动端导航 -->
- <div class="md:hidden">
- <!-- 移动端顶部栏 -->
- <div class="flex items-center justify-between py-3">
+ <div>
+ <header
+ v-if="loggedIn"
+ class="w-full px-4 border-b border-default"
+ >
+ <!-- 桌面端导航 -->
+ <div class="hidden md:flex items-center gap-4">
<div class="flex items-center gap-2">
<Icon
name="tabler:photo-circle"
@@ -90,91 +65,118 @@ const closeMobileMenu = () => {
/>
<NuxtLink
to="/"
- class="text-lg font-medium"
+ class="text-lg font-medium text-nowrap"
>
TimoYin's mems
</NuxtLink>
</div>
- <UButton
- variant="ghost"
- size="sm"
- :icon="isMobileMenuOpen ? 'tabler:x' : 'tabler:menu-2'"
- @click="toggleMobileMenu"
+ <UNavigationMenu
+ variant="pill"
+ :items="items"
+ :ui="{
+ viewportWrapper: 'max-w-5xl',
+ }"
+ class="w-full"
/>
</div>
- <!-- 移动端下拉菜单 -->
- <AnimatePresence>
- <motion.div
- v-if="isMobileMenuOpen"
- :initial="{ opacity: 0, y: -10, height: 0 }"
- :animate="{ opacity: 1, y: 0, height: 'auto' }"
- :exit="{ opacity: 0, y: -10, height: 0 }"
- :transition="{
- duration: 0.3,
- ease: 'easeOut',
- height: { duration: 0.2 }
- }"
- class="border-t border-default bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 overflow-hidden"
- >
- <nav class="py-2">
- <motion.div
- v-for="(item, index) in items"
- :key="index"
- :initial="{ opacity: 0, x: -20 }"
- :animate="{ opacity: 1, x: 0 }"
- :transition="{
- duration: 0.2,
- delay: index * 0.06,
- ease: 'easeOut'
- }"
- >
+ <!-- 移动端导航 -->
+ <div class="md:hidden">
+ <!-- 移动端顶部栏 -->
+ <div class="flex items-center justify-between py-3">
+ <div class="flex items-center gap-2">
+ <Icon
+ name="tabler:photo-circle"
+ class="size-6 text-primary"
+ />
<NuxtLink
- :to="item.to"
- :class="[
- 'flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors',
- isRouteActive(item.to as string)
- ? 'bg-primary/10 text-primary border-r-2 border-primary'
- : 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300'
- ]"
- @click="closeMobileMenu"
+ to="/"
+ class="text-lg font-medium"
+ >
+ TimoYin's mems
+ </NuxtLink>
+ </div>
+ <UButton
+ variant="ghost"
+ size="sm"
+ :icon="isMobileMenuOpen ? 'tabler:x' : 'tabler:menu-2'"
+ @click="toggleMobileMenu"
+ />
+ </div>
+
+ <!-- 移动端下拉菜单 -->
+ <AnimatePresence>
+ <motion.div
+ v-if="isMobileMenuOpen"
+ :initial="{ opacity: 0, y: -10, height: 0 }"
+ :animate="{ opacity: 1, y: 0, height: 'auto' }"
+ :exit="{ opacity: 0, y: -10, height: 0 }"
+ :transition="{
+ duration: 0.3,
+ ease: 'easeOut',
+ height: { duration: 0.2 }
+ }"
+ class="border-t border-default bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 overflow-hidden"
+ >
+ <nav class="py-2">
+ <motion.div
+ v-for="(item, index) in items"
+ :key="index"
+ :initial="{ opacity: 0, x: -20 }"
+ :animate="{ opacity: 1, x: 0 }"
+ :transition="{
+ duration: 0.2,
+ delay: index * 0.06,
+ ease: 'easeOut'
+ }"
>
- <Icon
- :name="item.icon!"
+ <NuxtLink
+ :to="item.to"
:class="[
- 'size-5',
+ 'flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors',
isRouteActive(item.to as string)
- ? 'text-primary'
- : 'text-gray-500'
+ ? 'bg-primary/10 text-primary border-r-2 border-primary'
+ : 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300'
]"
- />
- <span>{{ item.label }}</span>
- </NuxtLink>
- </motion.div>
- </nav>
- </motion.div>
- </AnimatePresence>
+ @click="closeMobileMenu"
+ >
+ <Icon
+ :name="item.icon!"
+ :class="[
+ 'size-5',
+ isRouteActive(item.to as string)
+ ? 'text-primary'
+ : 'text-gray-500'
+ ]"
+ />
+ <span>{{ item.label }}</span>
+ </NuxtLink>
+ </motion.div>
+ </nav>
+ </motion.div>
+ </AnimatePresence>
+ </div>
+ </header>
+ <main v-if="loggedIn && user?.isAdmin">
+ <NuxtPage />
+ </main>
+ <div
+ v-else
+ class="h-svh flex flex-col gap-4 items-center justify-center px-4"
+ >
+ <Icon
+ name="tabler:alert-triangle"
+ class="size-12 text-primary"
+ />
+ <p class="text-gray-500 text-center">
+ {{
+ !user?.isAdmin
+ ? 'Please login to view dashboard'
+ : 'Sorry, you do not have access to this page.'
+ }}
+ </p>
+ <UButton @click="handleLogin">Login with GitHub</UButton>
</div>
- </header>
- <main v-if="loggedIn && user?.isAdmin">
- <NuxtPage />
- </main>
- <div
- v-else
- class="h-svh flex flex-col gap-4 items-center justify-center px-4"
- >
- <Icon
- name="tabler:alert-triangle"
- class="size-12 text-primary"
- />
- <p class="text-gray-500 text-center">
- {{
- !user?.isAdmin
- ? 'Please login to view dashboard'
- : 'Sorry, you do not have access to this page.'
- }}
- </p>
- <UButton @click="handleLogin">Login with GitHub</UButton>
</div>
</template>
diff --git a/app/libs/image-loader-manager.ts b/app/libs/image-loader-manager.ts
index 1d673cac..0d02605b 100644
--- a/app/libs/image-loader-manager.ts
+++ b/app/libs/image-loader-manager.ts
@@ -55,7 +55,7 @@ export class ImageLoaderManager {
if (!fileType.mime.startsWith('image/')) return false
return true
- } catch (err) {
+ } catch {
return false
}
}
@@ -155,7 +155,7 @@ export class ImageLoaderManager {
}
const url = URL.createObjectURL(blob)
const result: ImageLoaderCacheResult = {
- blobSrc: originalUrl,
+ blobSrc: url,
originalSize: blob.size,
format: blob.type,
}
diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vue
index b533c445..6055cde9 100644
--- a/app/pages/dashboard/photos.vue
+++ b/app/pages/dashboard/photos.vue
@@ -316,14 +316,17 @@ const columns: TableColumn<Photo>[] = [
accessorKey: 'location',
header: '位置',
cell: ({ row }) => {
- if (!row.original.exif?.GPSLongitude && !row.original.exif?.GPSLatitude) {
- return h('span', { class: 'text-neutral-400 text-xs' }, '无 GPS 信息')
- }
- const location = `${row.original.city || ''}, ${row.original.country || ''}`.trim()
- return location
- ? h('span', { class: 'text-xs' }, location)
- : h('span', { class: 'text-neutral-400 text-xs' }, '未知')
- }
+ const { exif, city, country } = row.original
+
+ if (!exif?.GPSLongitude && !exif?.GPSLatitude) {
+ return h('span', { class: 'text-neutral-400 text-xs' }, '无 GPS 信息')
+ }
+
+ const location = [city, country].filter(Boolean).join(', ')
+ return h('span', {
+ class: location ? 'text-xs' : 'text-neutral-400 text-xs'
+ }, location || '未知')
+}
},
{
accessorKey: 'dateTaken',
@@ -1003,8 +1006,8 @@ onUnmounted(() => {
color="success"
size="sm"
icon="tabler:refresh"
- @click="handleBatchReindexExif"
class="flex-1 sm:flex-none"
+ @click="handleBatchReindexExif"
>
<span class="hidden sm:inline">重新索引 EXIF</span>
<span class="sm:hidden">索引</span>
@@ -1016,8 +1019,8 @@ onUnmounted(() => {
color="info"
size="sm"
icon="tabler:live-photo"
- @click="handleBatchDetectLivePhoto"
class="flex-1 sm:flex-none"
+ @click="handleBatchDetectLivePhoto"
>
<span class="hidden sm:inline">实况配对</span>
<span class="sm:hidden">配对</span>
@@ -1028,8 +1031,8 @@ onUnmounted(() => {
variant="soft"
size="sm"
icon="tabler:trash"
- @click="handleBatchDelete"
class="flex-1 sm:flex-none"
+ @click="handleBatchDelete"
>
<span class="hidden sm:inline">批量删除</span>
<span class="sm:hidden">删除</span>
diff --git a/app/pages/webgl/demo.vue b/app/pages/webgl/demo.vue
index db62f8e2..62869f7e 100644
--- a/app/pages/webgl/demo.vue
+++ b/app/pages/webgl/demo.vue
@@ -85,20 +85,20 @@ const handleLoadingStateChange = (
<div class="controls">
<button
- @click="zoomIn"
class="control-btn"
+ @click="zoomIn"
>
放大
</button>
<button
- @click="zoomOut"
class="control-btn"
+ @click="zoomOut"
>
缩小
</button>
<button
- @click="resetView"
class="control-btn"
+ @click="resetView"
>
重置
</button>
diff --git a/app/pages/webgl/features.vue b/app/pages/webgl/features.vue
index 210a0eb1..23771d09 100644
--- a/app/pages/webgl/features.vue
+++ b/app/pages/webgl/features.vue
@@ -193,32 +193,32 @@ const handleLoadingStateChange = (loading: boolean) => {
<div class="button-group">
<button
- @click="handleZoomIn"
class="btn"
+ @click="handleZoomIn"
>
放大 (无动画)
</button>
<button
- @click="handleZoomInAnimated"
class="btn"
+ @click="handleZoomInAnimated"
>
放大 (动画)
</button>
<button
- @click="handleZoomOut"
class="btn"
+ @click="handleZoomOut"
>
缩小 (无动画)
</button>
<button
- @click="handleZoomOutAnimated"
class="btn"
+ @click="handleZoomOutAnimated"
>
缩小 (动画)
</button>
<button
- @click="handleReset"
class="btn"
+ @click="handleReset"
>
重置
</button>
diff --git a/eslint.config.mjs b/eslint.config.mjs
index da068308..d9c4ef49 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -11,6 +11,7 @@ export default withNuxt({
'@stylistic/arrow-parens': 'off',
'@stylistic/operator-linebreak': 'off',
'@typescript-eslint/no-empty-object-type': 'off',
+ '@typescript-eslint/no-explicit-any': 'off',
},
plugins: {
prettier,
diff --git a/package.json b/package.json
index 922b7ba5..eea298bd 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,8 @@
"build:deps": "pnpm --filter @chronoframe/webgl-image build",
"dev": "pnpm dev:deps",
"dev:deps": "concurrently \"pnpm --filter @chronoframe/webgl-image dev\" \"wait-on packages/webgl-image/dist && nuxt dev\"",
+ "lint": "eslint .",
+ "lint:fix": "eslint . --fix",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
@@ -39,7 +41,6 @@
"db0": "^0.3.2",
"drizzle-orm": "^0.44.4",
"es-toolkit": "^1.39.10",
- "exifr": "^7.1.3",
"exiftool-vendored": "^30.3.0",
"file-type": "^21.0.0",
"heic-convert": "^2.1.0",
diff --git a/packages/webgl-image/src/components/WebGLImageViewer.vue b/packages/webgl-image/src/components/WebGLImageViewer.vue
index 770952bf..362a3aea 100644
--- a/packages/webgl-image/src/components/WebGLImageViewer.vue
+++ b/packages/webgl-image/src/components/WebGLImageViewer.vue
@@ -116,7 +116,7 @@ const initEngine = async (): Promise<void> => {
) => {
emit('loadingStateChange', isLoading, state, quality)
},
- onTransformChange: (transform) => {
+ onTransformChange: (_transform) => {
// 在任何变换变化时更新调试信息
if (config.value.debug) {
updateDebugInfo()
@@ -214,7 +214,7 @@ watch(
watch(
config,
- (newConfig) => {
+ (_newConfig) => {
if (engine.value) {
engine.value.destroy()
initEngine().catch(console.error)
diff --git a/packages/webgl-image/src/core/WebGLImageViewerEngine.ts b/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
index 5d1a51a5..16ccdff2 100644
--- a/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
+++ b/packages/webgl-image/src/core/WebGLImageViewerEngine.ts
@@ -2,7 +2,6 @@ import type {
EngineConfig,
Transform,
Animation,
- Bounds,
DebugInfo,
Point,
TouchState,
@@ -26,34 +25,6 @@ import {
} from './utils'
import { createProgram } from '../shaders'
-// 瓦片系统配置
-const TILE_SIZE = 512
-const MAX_TILES_PER_FRAME = 4
-const TILE_CACHE_SIZE = 32
-
-// 瓦片信息接口
-interface TileInfo {
- x: number
- y: number
- lodLevel: number
- texture: WebGLTexture | null
- lastUsed: number
- isLoading: boolean
- priority: number
-}
-
-// 瓦片键值
-type TileKey = string
-
-// 简化的 LOD 级别
-const SIMPLE_LOD_LEVELS = [
- { scale: 0.25 },
- { scale: 0.5 },
- { scale: 1 },
- { scale: 2 },
- { scale: 4 },
-] as const
-
export class WebGLImageViewerEngine {
private canvas: HTMLCanvasElement
private gl: WebGLRenderingContext
@@ -107,22 +78,11 @@ export class WebGLImageViewerEngine {
) => void
private onTransformChange?: (transform: Transform) => void
- // 瓦片系统和质量管理
- private currentLOD = 1 // 默认使用正常质量
- private lodTextures = new Map<number, WebGLTexture>()
- private tileCache = new Map<TileKey, TileInfo>()
- private loadingTiles = new Map<TileKey, { priority: number }>()
- private pendingTileRequests: Array<{ key: TileKey; priority: number }> = []
- private currentVisibleTiles = new Set<TileKey>()
- private lastViewportHash = ''
+ // 质量管理
private currentQuality: 'high' | 'medium' | 'low' | 'unknown' = 'unknown'
private isLoadingTexture = false
private currentLoadingState: LoadingState = LoadingState.IDLE
- // Worker 支持
- private worker: Worker | null = null
- private textureWorkerInitialized = false
-
constructor(canvas: HTMLCanvasElement, config: Partial<EngineConfig> = {}) {
this.canvas = canvas
this.config = { ...DEFAULT_CONFIG, ...config }
@@ -158,7 +118,6 @@ export class WebGLImageViewerEngine {
this.setupWebGL()
this.setupEventListeners()
this.setupResizeObserver()
- this.initWorker()
this.resize()
}
@@ -275,11 +234,6 @@ export class WebGLImageViewerEngine {
this.resizeObserver.observe(this.canvas)
}
- private initWorker(): void {
- // 简化的 Worker 初始化,暂时不使用 Worker
- this.textureWorkerInitialized = true
- }
-
private notifyLoadingStateChange(
isLoading: boolean,
state?: LoadingState,
@@ -292,52 +246,6 @@ export class WebGLImageViewerEngine {
this.onLoadingStateChange?.(isLoading, state, quality)
}
- private selectOptimalLOD(): number {
- if (!this.image) return 1
-
- const requiredScale = this.transform.scale * (window.devicePixelRatio || 1)
-
- // 寻找最佳的 LOD 级别
- for (const [i, lodLevel] of SIMPLE_LOD_LEVELS.entries()) {
- if (lodLevel.scale >= requiredScale) {
- return i
- }
- }
-
- // 如果没有找到,返回最高质量的 LOD
- return SIMPLE_LOD_LEVELS.length - 1
- }
-
- private createWebGLTexture(
- source: HTMLCanvasElement | HTMLImageElement | ImageBitmap,
- ): WebGLTexture | null {
- const { gl } = this
-
- const texture = gl.createTexture()
- if (!texture) return null
-
- gl.bindTexture(gl.TEXTURE_2D, texture)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
-
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source)
-
- return texture
- }
-
- private cleanupLODTextures(): void {
- for (const texture of this.lodTextures.values()) {
- this.gl.deleteTexture(texture)
- }
- this.lodTextures.clear()
- }
-
- private getTileKey(x: number, y: number, lodLevel: number): TileKey {
- return `${x}-${y}-${lodLevel}`
- }
-
public async loadImage(src: string): Promise<void> {
try {
this.notifyLoadingStateChange(true, LoadingState.IMAGE_LOADING)
@@ -487,23 +395,6 @@ export class WebGLImageViewerEngine {
}
}
- private getFitToScreenScale(): number {
- if (!this.image) return 1
-
- const canvasAspect = this.canvas.width / this.canvas.height
- const imageAspect = this.image.width / this.image.height
-
- let scale: number
- if (imageAspect > canvasAspect) {
- scale = this.canvas.width / this.image.width
- } else {
- scale = this.canvas.height / this.image.height
- }
-
- // 使用相对缩放约束
- return this.clampScale(scale)
- }
-
/**
* 获取基于相对缩放的绝对最小缩放值
*/
@@ -764,7 +655,7 @@ export class WebGLImageViewerEngine {
if (touches.length === 1 && touches[0]) {
// 单指操作
this.hasMoved = false // 重置移动标志
-
+
if (!this.config.panningDisabled) {
this.isDragging = true
this.lastMousePos = touches[0]
@@ -846,11 +737,16 @@ export class WebGLImageViewerEngine {
private handleTouchEnd(event: TouchEvent): void {
const now = Date.now()
-
+
// 只有在单指触摸且没有移动的情况下才处理双击
- if (event.touches.length === 0 && this.lastMousePos && !this.hasMoved && !this.config.doubleClickDisabled) {
+ if (
+ event.touches.length === 0 &&
+ this.lastMousePos &&
+ !this.hasMoved &&
+ !this.config.doubleClickDisabled
+ ) {
const currentTouchPosition = this.lastMousePos
-
+
// 检查是否为双击
if (
this.lastTouchTime > 0 &&
@@ -861,7 +757,7 @@ export class WebGLImageViewerEngine {
// 双击逻辑
const rect = this.canvas.getBoundingClientRect()
const dpr = window.devicePixelRatio || 1
-
+
// 转换为画布坐标系(考虑设备像素比)
const centerX = (currentTouchPosition.x - rect.left) * dpr
const centerY = (currentTouchPosition.y - rect.top) * dpr
@@ -871,7 +767,12 @@ export class WebGLImageViewerEngine {
if (isZoomedIn) {
this.resetView()
} else {
- this.zoomAtPoint(centerX, centerY, this.config.doubleClickStep, true)
+ this.zoomAtPoint(
+ centerX,
+ centerY,
+ this.config.doubleClickStep,
+ true,
+ )
}
} else {
this.zoomAtPoint(centerX, centerY, this.config.doubleClickStep, true)
@@ -900,7 +801,7 @@ export class WebGLImageViewerEngine {
private isNearPosition(pos1: Point, pos2: Point, threshold: number): boolean {
const distance = Math.sqrt(
- Math.pow(pos1.x - pos2.x, 2) + Math.pow(pos1.y - pos2.y, 2)
+ Math.pow(pos1.x - pos2.x, 2) + Math.pow(pos1.y - pos2.y, 2),
)
return distance <= threshold
}
@@ -965,7 +866,7 @@ export class WebGLImageViewerEngine {
// 计算目标变换(重置状态),但不直接应用到当前变换
const targetTransform = this.calculateCenterTransform()
-
+
// 使用动画过渡到目标状态
this.animateTo(targetTransform)
}
diff --git a/packages/webgl-image/src/core/utils.ts b/packages/webgl-image/src/core/utils.ts
index 34168a63..acb5fb67 100644
--- a/packages/webgl-image/src/core/utils.ts
+++ b/packages/webgl-image/src/core/utils.ts
@@ -84,7 +84,7 @@ export function debounce<T extends (...args: any[]) => any>(
return (...args: Parameters<T>) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(
- () => func.apply(null, args),
+ () => func(...args),
delay,
) as unknown as number
}
@@ -102,7 +102,7 @@ export function throttle<T extends (...args: any[]) => any>(
const now = Date.now()
if (now - lastCall >= delay) {
lastCall = now
- func.apply(null, args)
+ func(...args)
}
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e43e0a73..deec870b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -62,9 +62,6 @@ importers:
es-toolkit:
specifier: ^1.39.10
version: 1.39.10
- exifr:
- specifier: ^7.1.3
- version: 7.1.3
exiftool-vendored:
specifier: ^30.3.0
version: 30.3.0
@@ -4721,9 +4718,6 @@ packages:
resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==}
engines: {node: '>=16.17'}
- resolution: {integrity: sha512-g/aje2noHivrRSLbAUtBPWFbxKdKhgj/xr1vATDdUXPOFYJlQ62Ft0oy+72V6XLIpDJfHs6gXLbBLAolqOXYRw==}
-
resolution: {integrity: sha512-SjL+8N1dvLwJdxj5yviboAGfiPmyD6yssnmy9aqDDkJG/ffl/BKvw45ObjVnVD679PRPXs9x2uMTz4P4eHUlEw==}
os: [win32]
@@ -13025,8 +13019,6 @@ snapshots:
signal-exit: 4.1.0
strip-final-newline: 3.0.0
-
optional: true
diff --git a/server/api/auth/github.get.ts b/server/api/auth/github.get.ts
index 04303bac..7b60ffe2 100644
--- a/server/api/auth/github.get.ts
+++ b/server/api/auth/github.get.ts
@@ -41,7 +41,7 @@ export default defineOAuthGitHubEventHandler({
}
return sendRedirect(event, '/')
},
- onError(event) {
+ onError(_event) {
throw createError({
statusCode: 401,
statusMessage: 'Authentication failed',
diff --git a/server/api/health/processor.ts b/server/api/health/processor.ts
index f956aac9..5735979e 100644
--- a/server/api/health/processor.ts
+++ b/server/api/health/processor.ts
@@ -1,4 +1,4 @@
-export default eventHandler(async (event) => {
+export default eventHandler(async (_event) => {
// 简单的处理器状态检查
const status = {
mode: 'background-processing',
diff --git a/server/api/photos/[photoId].delete.ts b/server/api/photos/[photoId].delete.ts
index 85aa219c..ae0c85ca 100644
--- a/server/api/photos/[photoId].delete.ts
+++ b/server/api/photos/[photoId].delete.ts
@@ -32,7 +32,9 @@ export default eventHandler(async (event) => {
await storageProvider.delete(
photo.thumbnailUrl?.replace(storageProvider.getPublicUrl(''), '') || '',
)
- } catch (_) {}
+ } catch {
+ // ignore error
+ }
}
useDB().delete(tables.photos).where(eq(tables.photos.id, photoId)).run()
diff --git a/server/api/photos/index.put.ts b/server/api/photos/index.put.ts
index 4dbefb3f..0d4b4f92 100644
--- a/server/api/photos/index.put.ts
+++ b/server/api/photos/index.put.ts
@@ -1,4 +1,3 @@
-import sharp from 'sharp'
import { execPhotoPipelineAsync } from '~~/server/services/photo/pipeline-async'
import { useStorageProvider } from '~~/server/utils/useStorageProvider'
@@ -23,7 +22,7 @@ export default eventHandler(async (event) => {
)
// 立即返回响应,不等待处理完成
- const processingPromise = processPhotoInBackground(originalObject.key, originalObject)
+ processPhotoInBackground(originalObject.key, originalObject)
// 返回处理中的响应
return {
diff --git a/server/api/photos/livephoto-detect.post.ts b/server/api/photos/livephoto-detect.post.ts
index 69f927d6..f3b59326 100644
--- a/server/api/photos/livephoto-detect.post.ts
+++ b/server/api/photos/livephoto-detect.post.ts
@@ -2,10 +2,10 @@ import { batchTestLivePhotoDetection } from '~~/server/services/video/test-utils
export default eventHandler(async (event) => {
await requireUserSession(event)
-
+
const body = await readBody(event)
const { action, photoIds } = body
-
+
if (!action) {
throw createError({
statusCode: 400,
@@ -15,14 +15,15 @@ export default eventHandler(async (event) => {
try {
switch (action) {
- case 'batch-detect':
- // 批量检测现有照片的 LivePhoto 视频
+ case 'batch-detect': // 批量检测现有照片的 LivePhoto 视频
+ {
const results = await batchTestLivePhotoDetection(photoIds)
return {
message: 'Batch LivePhoto detection completed',
- results
+ results,
}
-
+ }
+
default:
throw createError({
statusCode: 400,
diff --git a/server/api/photos/livephoto-manage.post.ts b/server/api/photos/livephoto-manage.post.ts
index 2fa157f0..3ced8971 100644
--- a/server/api/photos/livephoto-manage.post.ts
+++ b/server/api/photos/livephoto-manage.post.ts
@@ -1,14 +1,17 @@
-import { processSpecificLivePhotoVideo, scanAndProcessExistingLivePhotos } from '~~/server/services/video/scanner'
+import {
+ processSpecificLivePhotoVideo,
+ scanAndProcessExistingLivePhotos,
+} from '~~/server/services/video/scanner'
import { eq } from 'drizzle-orm'
import { findLivePhotoVideoForImage } from '~~/server/services/video/livephoto'
import { getStorageManager } from '~~/server/plugins/storage'
export default eventHandler(async (event) => {
await requireUserSession(event)
-
+
const body = await readBody(event)
const { action, videoKey, photoId } = body
-
+
if (!action) {
throw createError({
statusCode: 400,
@@ -18,32 +21,34 @@ export default eventHandler(async (event) => {
try {
switch (action) {
- case 'scan':
- // 扫描现有文件
+ case 'scan': { // 扫描现有文件
const scanResults = await scanAndProcessExistingLivePhotos()
return {
message: 'Scan completed',
- results: scanResults
+ results: scanResults,
}
-
- case 'process':
- // 处理特定文件
+ }
+
+ case 'process': { // 处理特定文件
if (!videoKey) {
throw createError({
statusCode: 400,
statusMessage: 'videoKey is required for process action',
})
}
-
+
const success = await processSpecificLivePhotoVideo(videoKey)
return {
- message: success ? 'LivePhoto processed successfully' : 'Failed to process LivePhoto',
+ message: success
+ ? 'LivePhoto processed successfully'
+ : 'Failed to process LivePhoto',
success,
- videoKey
+ videoKey,
}
+ }
- case 'update-photo':
- // 为特定照片检查和更新 LivePhoto 状态
+ case 'update-photo': // 为特定照片检查和更新 LivePhoto 状态
+ {
if (!photoId) {
throw createError({
statusCode: 400,
@@ -66,16 +71,20 @@ export default eventHandler(async (event) => {
}
const photo = photos[0]
- const livePhotoVideo = await findLivePhotoVideoForImage(photo.storageKey!)
+ const livePhotoVideo = await findLivePhotoVideoForImage(
+ photo.storageKey!,
+ )
if (livePhotoVideo) {
const storageProvider = getStorageManager().getProvider()
-
+
await db
.update(tables.photos)
.set({
isLivePhoto: 1,
- livePhotoVideoUrl: storageProvider.getPublicUrl(livePhotoVideo.videoKey),
+ livePhotoVideoUrl: storageProvider.getPublicUrl(
+ livePhotoVideo.videoKey,
+ ),
livePhotoVideoKey: livePhotoVideo.videoKey,
})
.where(eq(tables.photos.id, photoId))
@@ -84,20 +93,22 @@ export default eventHandler(async (event) => {
message: 'Photo updated to LivePhoto successfully',
success: true,
photoId,
- videoKey: livePhotoVideo.videoKey
+ videoKey: livePhotoVideo.videoKey,
}
} else {
return {
message: 'No matching video found for this photo',
success: false,
- photoId
+ photoId,
}
}
-
+ }
+
default:
throw createError({
statusCode: 400,
- statusMessage: 'Invalid action. Use "scan", "process", or "update-photo"',
+ statusMessage:
+ 'Invalid action. Use "scan", "process", or "update-photo"',
})
}
} catch (error) {
diff --git a/server/api/photos/locations.get.ts b/server/api/photos/locations.get.ts
index dfb9a9ea..2a154587 100644
--- a/server/api/photos/locations.get.ts
+++ b/server/api/photos/locations.get.ts
@@ -6,7 +6,7 @@ export default eventHandler(async (event) => {
const query = getQuery(event)
const { country, city, hasLocation } = query
- let whereConditions = []
+ const whereConditions = []
// 如果指定了只显示有位置信息的照片
if (hasLocation === 'true') {
diff --git a/server/database/schema.ts b/server/database/schema.ts
index 40d4a32d..2f2ce432 100644
--- a/server/database/schema.ts
+++ b/server/database/schema.ts
@@ -1,5 +1,5 @@
import { sqliteTable, text, integer, real } from 'drizzle-orm/sqlite-core'
-import { NeededExif } from '~~/shared/types/photo'
+import type { NeededExif } from '~~/shared/types/photo'
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
diff --git a/server/plugins/storage.ts b/server/plugins/storage.ts
index 447b6fd1..abf5e809 100644
--- a/server/plugins/storage.ts
+++ b/server/plugins/storage.ts
@@ -1,8 +1,5 @@
-import {
- S3StorageProvider,
- StorageConfig,
- StorageManager,
-} from '../services/storage'
+import type { StorageConfig } from '../services/storage'
+import { StorageManager } from '../services/storage'
// 全局 storageManager 实例,可以在非请求上下文中使用
let globalStorageManager: StorageManager
@@ -31,13 +28,15 @@ export default nitroPlugin(async (nitroApp) => {
r2: {
provider: 'hub-r2',
prefix: 'photos/',
- cdnUrl: import.meta.dev ? 'http://localhost:3000/image/' : 'https://cdn-dev.lens.bh8.ga/',
+ cdnUrl: import.meta.dev
+ ? 'http://localhost:3000/image/'
+ : 'https://cdn-dev.lens.bh8.ga/',
maxKeys: 100,
},
}
const storageManager = new StorageManager(devConfigs.s3, logger.storage)
-
+
// 设置全局实例
globalStorageManager = storageManager
diff --git a/server/services/image/exif.ts b/server/services/image/exif.ts
index e854c9ee..c7853c12 100644
--- a/server/services/image/exif.ts
+++ b/server/services/image/exif.ts
@@ -1,11 +1,12 @@
import path from 'node:path'
import { mkdir, unlink, writeFile } from 'node:fs/promises'
-import sharp, { Metadata } from 'sharp'
+import type { Metadata } from 'sharp'
+import sharp from 'sharp'
import type { NeededExif, PhotoInfo } from '../../../shared/types/photo'
-import exifr from 'exifr'
-import { exiftool, ExifDateTime, Tags } from 'exiftool-vendored'
+import type { ExifDateTime, Tags } from 'exiftool-vendored'
+import { exiftool } from 'exiftool-vendored'
import { noop } from 'es-toolkit'
-import { Logger } from '~~/server/utils/logger'
+import type { Logger } from '~~/server/utils/logger'
const neededKeys: Array<keyof Tags | (string & {})> = [
'Title',
@@ -211,6 +212,7 @@ export const extractPhotoInfo = (
const viewsMatch = fileName.match(/(\d+)views?/i)
if (viewsMatch) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
views = Number.parseInt(viewsMatch[1])
}
diff --git a/server/services/image/processor.ts b/server/services/image/processor.ts
index 458ae36a..da0b75b4 100644
--- a/server/services/image/processor.ts
+++ b/server/services/image/processor.ts
@@ -32,7 +32,8 @@ const getMetadataWithSharp = async (
return null
}
- let { width, height, orientation } = metadata
+ const { orientation } = metadata
+ let { width, height } = metadata
if (orientation && [5, 6, 7, 8].includes(orientation)) {
;[width, height] = [height, width]
@@ -135,7 +136,9 @@ export const preprocessImageWithJpegUpload = async (
jpegKey = `${baseName}.jpeg`
// 上传 JPEG 版本到存储
- jpegStorageKey = (await storageProvider.create(jpegKey, processedBuffer, 'image/jpeg')).key
+ jpegStorageKey = (
+ await storageProvider.create(jpegKey, processedBuffer, 'image/jpeg')
+ ).key
logger.image.info(`Uploaded JPEG version to: ${jpegKey}`)
} catch (err) {
logger.image.error(`HEIC conversion failed: ${s3key}`, err)
diff --git a/server/services/photo/pipeline-async.ts b/server/services/photo/pipeline-async.ts
index 8f551c87..a5e9348c 100644
--- a/server/services/photo/pipeline-async.ts
+++ b/server/services/photo/pipeline-async.ts
@@ -1,16 +1,18 @@
import path from 'path'
import {
- preprocessImage,
preprocessImageWithJpegUpload,
processImageMetadataAndSharp,
} from '../image/processor'
import { generateThumbnailAndHash } from '../image/thumbnail'
-import { Photo } from '~~/server/utils/db'
+import type { Photo } from '~~/server/utils/db'
import { getStorageManager } from '~~/server/plugins/storage'
import { compressUint8Array } from '~~/shared/utils/u8array'
-import { StorageObject } from '../storage'
+import type { StorageObject } from '../storage'
import { extractExifData, extractPhotoInfo } from '../image/exif'
-import { extractLocationFromGPS, parseGPSCoordinates } from '../location/geocoding'
+import {
+ extractLocationFromGPS,
+ parseGPSCoordinates,
+} from '../location/geocoding'
import { findLivePhotoVideoForImage } from '../video/livephoto'
const generatePhotoId = (s3key: string) => {
@@ -87,23 +89,29 @@ async function processPhotoInternal(
return null
}
- const { sharpInst, imageBuffer, metadata } = processedData
+ const { imageBuffer, metadata } = processedData
- const { thumbnailBuffer, thumbnailHash } = await new Promise<any>((resolve, reject) => {
- setImmediate(async () => {
- try {
- const result = await generateThumbnailAndHash(imageBuffer)
- resolve(result)
- } catch (error) {
- reject(error)
- }
- })
- })
+ const { thumbnailBuffer, thumbnailHash } = await new Promise<any>(
+ (resolve, reject) => {
+ setImmediate(async () => {
+ try {
+ const result = await generateThumbnailAndHash(imageBuffer)
+ resolve(result)
+ } catch (error) {
+ reject(error)
+ }
+ })
+ },
+ )
const exifData = await new Promise<any>((resolve, reject) => {
setImmediate(async () => {
try {
- const result = await extractExifData(imageBuffer, imageBuffers.raw, log)
+ const result = await extractExifData(
+ imageBuffer,
+ imageBuffers.raw,
+ log,
+ )
resolve(result)
} catch (error) {
reject(error)
@@ -147,7 +155,9 @@ async function processPhotoInternal(
if (livePhotoVideo) {
livePhotoInfo = {
isLivePhoto: 1,
- livePhotoVideoUrl: storageProvider.getPublicUrl(livePhotoVideo.videoKey),
+ livePhotoVideoUrl: storageProvider.getPublicUrl(
+ livePhotoVideo.videoKey,
+ ),
livePhotoVideoKey: livePhotoVideo.videoKey,
}
log.info(`LivePhoto video found for ${s3key}: ${livePhotoVideo.videoKey}`)
@@ -159,7 +169,7 @@ async function processPhotoInternal(
const result = await storageProvider.create(
`thumbnails/${photoId}.webp`,
thumbnailBuffer,
- 'image/webp'
+ 'image/webp',
)
resolve(result)
} catch (error) {
@@ -181,8 +191,8 @@ async function processPhotoInternal(
fileSize: storageObject.size || null,
lastModified:
storageObject.lastModified?.toISOString() || new Date().toISOString(),
- originalUrl: imageBuffers.jpegKey
- ? storageProvider.getPublicUrl(imageBuffers.jpegKey) // 使用 JPEG 版本作为 originalUrl
+ originalUrl: imageBuffers.jpegKey
+ ? storageProvider.getPublicUrl(imageBuffers.jpegKey) // 使用 JPEG 版本作为 originalUrl
: storageProvider.getPublicUrl(s3key),
thumbnailUrl: storageProvider.getPublicUrl(thumbnailObject.key),
thumbnailHash: thumbnailHash ? compressUint8Array(thumbnailHash) : null,
@@ -201,7 +211,6 @@ async function processPhotoInternal(
log.info(`Async processing completed for ${s3key}`)
return result
-
} catch (err) {
log.error(`Photo pipeline failed for ${s3key}`, err)
return null
@@ -213,10 +222,11 @@ async function processPhotoInternal(
*/
export const execBatchPhotoPipelineAsync = async (
photos: Array<{ s3key: string; storageObject: StorageObject }>,
- maxConcurrent = 3
+ maxConcurrent = 3,
): Promise<Array<{ s3key: string; photo: Photo | null; error?: string }>> => {
- const results: Array<{ s3key: string; photo: Photo | null; error?: string }> = []
-
+ const results: Array<{ s3key: string; photo: Photo | null; error?: string }> =
+ []
+
// 分批处理以限制并发数
for (let i = 0; i < photos.length; i += maxConcurrent) {
const batch = photos.slice(i, i + maxConcurrent)
@@ -226,22 +236,24 @@ export const execBatchPhotoPipelineAsync = async (
return {
s3key,
photo,
- error: photo ? undefined : 'Processing failed'
+ error: photo ? undefined : 'Processing failed',
}
} catch (error) {
return {
s3key,
photo: null,
- error: error instanceof Error ? error.message : String(error)
+ error: error instanceof Error ? error.message : String(error),
}
}
})
const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)
-
- logger.image.info(`Processed async batch ${Math.floor(i / maxConcurrent) + 1} of ${Math.ceil(photos.length / maxConcurrent)}`)
+
+ logger.image.info(
+ `Processed async batch ${Math.floor(i / maxConcurrent) + 1} of ${Math.ceil(photos.length / maxConcurrent)}`,
+ )
}
-
+
return results
}
diff --git a/server/services/photo/pipeline.ts b/server/services/photo/pipeline.ts
index 799f67f8..49baa96b 100644
--- a/server/services/photo/pipeline.ts
+++ b/server/services/photo/pipeline.ts
@@ -1,14 +1,13 @@
import path from 'path'
import {
- preprocessImage,
preprocessImageWithJpegUpload,
processImageMetadataAndSharp,
} from '../image/processor'
import { generateThumbnailAndHash } from '../image/thumbnail'
-import { Photo } from '~~/server/utils/db'
+import type { Photo } from '~~/server/utils/db'
import { getStorageManager } from '~~/server/plugins/storage'
import { compressUint8Array } from '~~/shared/utils/u8array'
-import { StorageObject } from '../storage'
+import type { StorageObject } from '../storage'
import { extractExifData, extractPhotoInfo } from '../image/exif'
import { findLivePhotoVideoForImage } from '../video/livephoto'
@@ -35,7 +34,7 @@ export const execPhotoPipeline = async (
s3key,
)
if (!processedData) return null
- const { sharpInst, imageBuffer, metadata } = processedData
+ const { imageBuffer, metadata } = processedData
// 3. 生成缩略图和 BlurHash
const { thumbnailBuffer, thumbnailHash } =
@@ -50,11 +49,13 @@ export const execPhotoPipeline = async (
// 6. 检查是否有对应的 LivePhoto 视频文件
const livePhotoVideo = await findLivePhotoVideoForImage(s3key)
let livePhotoInfo = null
-
+
if (livePhotoVideo) {
livePhotoInfo = {
isLivePhoto: 1,
- livePhotoVideoUrl: storageProvider.getPublicUrl(livePhotoVideo.videoKey),
+ livePhotoVideoUrl: storageProvider.getPublicUrl(
+ livePhotoVideo.videoKey,
+ ),
livePhotoVideoKey: livePhotoVideo.videoKey,
}
log.info(`LivePhoto video found for ${s3key}: ${livePhotoVideo.videoKey}`)
@@ -64,7 +65,7 @@ export const execPhotoPipeline = async (
const thumbnailObject = await storageProvider.create(
`thumbnails/${photoId}.webp`,
thumbnailBuffer,
- 'image/webp'
+ 'image/webp',
)
return {
@@ -80,8 +81,8 @@ export const execPhotoPipeline = async (
fileSize: storageObject.size || null,
lastModified:
storageObject.lastModified?.toISOString() || new Date().toISOString(),
- originalUrl: imageBuffers.jpegKey
- ? storageProvider.getPublicUrl(imageBuffers.jpegKey) // 使用 JPEG 版本作为 originalUrl
+ originalUrl: imageBuffers.jpegKey
+ ? storageProvider.getPublicUrl(imageBuffers.jpegKey) // 使用 JPEG 版本作为 originalUrl
: storageProvider.getPublicUrl(s3key),
thumbnailUrl: storageProvider.getPublicUrl(thumbnailObject.key),
thumbnailHash: thumbnailHash ? compressUint8Array(thumbnailHash) : null,
diff --git a/server/services/storage/manager.ts b/server/services/storage/manager.ts
index 50e902c9..1bfb9ea6 100644
--- a/server/services/storage/manager.ts
+++ b/server/services/storage/manager.ts
@@ -1,7 +1,9 @@
-import { S3StorageProvider, StorageConfig, StorageProvider } from '.'
+import type { StorageConfig, StorageProvider } from '.';
+import { S3StorageProvider } from '.'
import type { Logger } from '../../utils/logger'
import { HubR2StorageProvider } from './providers/hub-r2'
+// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class StorageProviderFactory {
static createProvider(
config: StorageConfig,
diff --git a/server/services/storage/providers/github.ts b/server/services/storage/providers/github.ts
index 0ab610ac..1f81174c 100644
--- a/server/services/storage/providers/github.ts
+++ b/server/services/storage/providers/github.ts
@@ -1,4 +1,6 @@
-import { StorageObject, StorageProvider } from '../interfaces'
+// TODO: Implement GitHub storage provider and remove below line
+/* eslint-disable @typescript-eslint/no-unused-vars */
+import type { StorageObject, StorageProvider } from '../interfaces'
export class GitHubStorageProvider implements StorageProvider {
create(key: string, data: Buffer): Promise<StorageObject> {
diff --git a/server/services/storage/providers/hub-r2.ts b/server/services/storage/providers/hub-r2.ts
index 4de035e0..d69851e2 100644
--- a/server/services/storage/providers/hub-r2.ts
+++ b/server/services/storage/providers/hub-r2.ts
@@ -1,5 +1,5 @@
-import { BlobObject } from '@nuxthub/core'
-import {
+import type { BlobObject } from '@nuxthub/core'
+import type {
HubR2StorageConfig,
StorageObject,
StorageProvider,
@@ -15,7 +15,7 @@ const convertToStorageObject = (blob: BlobObject): StorageObject => {
}
export class HubR2StorageProvider implements StorageProvider {
- private config: HubR2StorageConfig
+ config: HubR2StorageConfig
private logger?: Logger['storage']
constructor(config: HubR2StorageConfig, logger?: Logger['storage']) {
@@ -26,7 +26,7 @@ export class HubR2StorageProvider implements StorageProvider {
async create(
key: string,
fileBuffer: Buffer,
- contentType?: string,
+ _contentType?: string,
): Promise<StorageObject> {
const file = new File([new Uint8Array(fileBuffer)], key)
diff --git a/server/services/storage/providers/s3.ts b/server/services/storage/providers/s3.ts
index 1d587b39..9cfb738b 100644
--- a/server/services/storage/providers/s3.ts
+++ b/server/services/storage/providers/s3.ts
@@ -1,14 +1,15 @@
-import {
+import type {
_Object,
+ S3ClientConfig} from '@aws-sdk/client-s3';
+import {
DeleteObjectCommand,
GetObjectCommand,
ListObjectsCommand,
PutObjectCommand,
- S3Client,
- S3ClientConfig,
+ S3Client
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
-import {
+import type {
S3StorageConfig,
StorageObject,
StorageProvider,
@@ -141,7 +142,7 @@ export class S3StorageProvider implements StorageProvider {
reject(err)
})
})
- } catch (_err) {
+ } catch {
return null
}
}
diff --git a/server/services/video/livephoto.ts b/server/services/video/livephoto.ts
index b621348e..8504b0a7 100644
--- a/server/services/video/livephoto.ts
+++ b/server/services/video/livephoto.ts
@@ -7,7 +7,7 @@ import { getStorageManager } from '~~/server/plugins/storage'
*/
export const processLivePhotoVideo = async (
videoKey: string,
- videoSize: number
+ _videoSize: number
): Promise<boolean> => {
const storageProvider = getStorageManager().getProvider()
const db = useDB()
@@ -110,7 +110,7 @@ export const findLivePhotoVideoForImage = async (
logger.chrono.warn(`Video file found but doesn't match LivePhoto criteria: ${videoKey} (size: ${videoSize})`)
}
}
- } catch (err) {
+ } catch {
// 文件不存在,继续检查下一个
continue
}
diff --git a/server/services/video/scanner.ts b/server/services/video/scanner.ts
index f7b57373..0feab056 100644
--- a/server/services/video/scanner.ts
+++ b/server/services/video/scanner.ts
@@ -9,25 +9,26 @@ export const scanAndProcessExistingLivePhotos = async (): Promise<{
matched: number
errors: string[]
}> => {
- const storageProvider = getStorageManager().getProvider()
const results = {
processed: 0,
matched: 0,
- errors: [] as string[]
+ errors: [] as string[],
}
-
+
try {
logger.chrono.info('Starting scan for existing LivePhoto videos...')
-
+
// 这里需要根据你的存储提供商实现列出所有文件的功能
// 如果你的存储提供商支持列出文件,可以使用类似的逻辑:
// const allFiles = await storageProvider.list()
-
+
// 由于大多数存储提供商不直接提供列出所有文件的功能,
// 这个函数可以作为管理工具,手动调用处理特定的 MOV 文件
-
- logger.chrono.info('Scan completed. Use processSpecificLivePhotoVideo for individual files.')
-
+
+ logger.chrono.info(
+ 'Scan completed. Use processSpecificLivePhotoVideo for individual files.',
+ )
+
return results
} catch (error) {
logger.chrono.error('Failed to scan existing LivePhotos:', error)
@@ -40,31 +41,35 @@ export const scanAndProcessExistingLivePhotos = async (): Promise<{
* 处理特定的 MOV 文件
*/
export const processSpecificLivePhotoVideo = async (
- videoKey: string
+ videoKey: string,
): Promise<boolean> => {
try {
const storageProvider = getStorageManager().getProvider()
-
+
// 获取文件信息
const fileBuffer = await storageProvider.get(videoKey)
if (!fileBuffer) {
logger.chrono.error(`Video file not found: ${videoKey}`)
return false
}
-
+
const fileName = videoKey.split('/').pop() || videoKey
-
+
// 检查是否为可能的 LivePhoto 视频
if (!isLivePhotoVideo(fileName, fileBuffer.length)) {
- logger.chrono.warn(`File does not appear to be a LivePhoto video: ${videoKey}`)
+ logger.chrono.warn(
+ `File does not appear to be a LivePhoto video: ${videoKey}`,
+ )
return false
}
-
+
// 处理 LivePhoto 视频
return await processLivePhotoVideo(videoKey, fileBuffer.length)
-
} catch (error) {
- logger.chrono.error(`Failed to process specific LivePhoto video ${videoKey}:`, error)
+ logger.chrono.error(
+ `Failed to process specific LivePhoto video ${videoKey}:`,
+ error,
+ )
return false
}
}
diff --git a/server/utils/db.ts b/server/utils/db.ts
index 75811bf3..f7151e49 100644
--- a/server/utils/db.ts
+++ b/server/utils/db.ts
@@ -1,9 +1,9 @@
// import { drizzle } from 'drizzle-orm/d1'
import { drizzle } from 'drizzle-orm/better-sqlite3'
import Database from 'better-sqlite3'
-export { sql, eq, and, or } from 'drizzle-orm'
import * as schema from '../database/schema'
+export { sql, eq, and, or } from 'drizzle-orm'
export const tables = schema
diff --git a/server/utils/useStorageProvider.ts b/server/utils/useStorageProvider.ts
index fed8ae4e..f4428f73 100644
--- a/server/utils/useStorageProvider.ts
+++ b/server/utils/useStorageProvider.ts
@@ -1,5 +1,5 @@
-import { H3Event, EventHandlerRequest } from 'h3'
-import { StorageProvider } from '../services/storage'
+import type { H3Event, EventHandlerRequest } from 'h3'
+import type { StorageProvider } from '../services/storage'
export const useStorageProvider = (event: H3Event<EventHandlerRequest>) => {
const storageProvider =