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: 优化LivePhoto处理逻辑,增加视频预加载和错误重试机制;改进上传队列管理,支持清除已完成和所有上传任务
cuijianzhuang87dd4282f9b3
diff --git a/app/components/masonry/item/Photo.vue b/app/components/masonry/item/Photo.vueindex 665904f3..2119bd13 100644--- a/app/components/masonry/item/Photo.vue+++ b/app/components/masonry/item/Photo.vue@@ -26,7 +26,7 @@ const isVideoPlaying = ref(false)const isVideoLoaded = ref(false)const videoBlob = ref<Blob | null>(null)const videoBlobUrl = ref<string | null>(null)-const { convertMovToMp4, getProcessingState } = useLivePhotoProcessor()+const { convertMovToMp4, getProcessingState, preloadLivePhotosInViewport } = useLivePhotoProcessor()const isTouching = ref(false)const touchCount = ref(0)@@ -80,7 +80,7 @@ const handleImageError = () => {console.warn(`Failed to load image: ${props.photo.thumbnailUrl}`)}-// LivePhoto video handling+// LivePhoto video handling - 优化的交互逻辑const handleMouseEnter = async () => {// Skip mouse events on mobile devicesif (isMobile.value) return@@ -89,9 +89,12 @@ const handleMouseEnter = async () => {if (!props.photo.isLivePhoto || !props.photo.livePhotoVideoUrl) return- // Only start video processing if we have the blob ready- if (videoBlob.value && videoBlobUrl.value) {+ // 如果视频已准备好,立即播放+ if (videoBlob.value && videoBlobUrl.value && isVideoLoaded.value) {playLivePhotoVideo()+ } else if (!processingState.value?.isProcessing) {+ // 如果视频还未处理,立即开始处理+ processLivePhotoWhenVisible()}}@@ -117,9 +120,10 @@ const handleMouseLeave = () => {const playLivePhotoVideo = () => {if (!videoRef.value || !videoBlobUrl.value) return+ // 确保视频从头开始播放videoRef.value.currentTime = 0- // Start the crossfade transition by setting video playing state first+ // 优化的播放逻辑:先设置状态,然后播放isVideoPlaying.value = true// Provide haptic feedback on mobile when starting playback@@ -127,13 +131,27 @@ const playLivePhotoVideo = () => {navigator.vibrate(50) // Short vibration for start}- // Then play the video after a small delay to ensure smooth transition- nextTick(() => {- videoRef.value?.play().catch((error: any) => {- console.warn('Failed to play LivePhoto video:', error)- isVideoPlaying.value = false- })- })+ // 立即尝试播放,使用更好的错误处理+ const playPromise = videoRef.value.play()++ if (playPromise !== undefined) {+ playPromise+ .then(() => {+ // 播放成功,确保状态正确+ if (videoRef.value && !videoRef.value.paused) {+ isVideoPlaying.value = true+ }+ })+ .catch((error: any) => {+ console.warn('Failed to play LivePhoto video:', error)+ isVideoPlaying.value = false++ // 如果是因为用户交互策略导致的失败,可以尝试重新处理+ if (error.name === 'NotAllowedError') {+ console.log('Video play blocked by browser policy')+ }+ })+ }}const handleVideoEnded = () => {@@ -249,7 +267,7 @@ const handleClick = (event: Event) => {emit('openViewer', props.index)}-// Process LivePhoto when it becomes visible+// 智能LivePhoto处理:基于可见性和用户行为const processLivePhotoWhenVisible = async () => {if (!props.photo.isLivePhoto ||@@ -259,10 +277,12 @@ const processLivePhotoWhenVisible = async () => {returntry {+ // 使用优化的转换函数,支持重试和缓存const blob = await convertMovToMp4(props.photo.livePhotoVideoUrl,props.photo.id,)+if (blob) {videoBlob.value = blob// Clean up previous blob URL@@ -271,9 +291,35 @@ const processLivePhotoWhenVisible = async () => {}videoBlobUrl.value = URL.createObjectURL(blob)isVideoLoaded.value = true++ // 预热视频元素以提高播放性能+ if (videoRef.value) {+ videoRef.value.load()+ }}} catch (error) {console.error('Failed to process LivePhoto:', error)+ // 错误状态会通过processingState反映出来+ }+}++// 预加载附近的LivePhoto(性能优化)+const preloadNearbyLivePhotos = async () => {+ if (!isVisible.value) return++ // 这里可以从父组件接收附近照片的信息+ // 目前只处理当前照片+ if (props.photo.isLivePhoto && props.photo.livePhotoVideoUrl) {+ await preloadLivePhotosInViewport([+ {+ id: props.photo.id,+ livePhotoVideoUrl: props.photo.livePhotoVideoUrl,+ isVisible: isVisible.value+ }+ ], {+ maxConcurrent: 1,+ prioritizeVisible: true+ })}}diff --git a/app/components/photo/LivePhotoIndicator.vue b/app/components/photo/LivePhotoIndicator.vueindex f48e84ff..485dcfec 100644--- a/app/components/photo/LivePhotoIndicator.vue+++ b/app/components/photo/LivePhotoIndicator.vue@@ -1,47 +1,144 @@<script lang="ts" setup>import { motion } from 'motion-v'+import { computed } from 'vue'-defineProps<{+const props = defineProps<{photo: PhotoisVideoPlaying: booleanprocessingState?: {isProcessing: booleanprogress: number+ error?: string | null+ retryCount?: number} | null}>()++// 计算指示器状态+const indicatorState = computed(() => {+ if (props.processingState?.isProcessing) {+ return 'processing'+ }+ if (props.processingState?.error) {+ return 'error'+ }+ if (props.isVideoPlaying) {+ return 'playing'+ }+ return 'ready'+})++// 计算显示文本+const displayText = computed(() => {+ const state = props.processingState+ if (state?.isProcessing) {+ if (state.retryCount && state.retryCount > 0) {+ return `重试中 ${state.retryCount}/3`+ }+ return '处理中...'+ }+ if (state?.error) {+ return '处理失败'+ }+ return $t('ui.livePhoto')+})++// 计算颜色样式+const colorClass = computed(() => {+ switch (indicatorState.value) {+ case 'playing':+ return 'text-yellow-300 bg-yellow-300/20 border-yellow-300/30'+ case 'processing':+ return 'text-blue-300 bg-blue-300/20 border-blue-300/30'+ case 'error':+ return 'text-red-300 bg-red-300/20 border-red-300/30'+ case 'ready':+ default:+ return 'text-white bg-black/40 border-white/20'+ }+})</script><template><motion.divv-if="photo.isLivePhoto"- class="backdrop-blur-md rounded-full pl-1 pr-1.5 py-1 text-[13px] font-bold flex items-center gap-0.5 leading-0 select-none transition-colors duration-300"- :class="`${isVideoPlaying ? 'text-yellow-300 bg-yellow-300/10' : 'text-white bg-black/30'}`"+ class="backdrop-blur-md rounded-full pl-1 pr-1.5 py-1 text-[13px] font-bold flex items-center gap-0.5 leading-0 select-none border transition-all duration-300"+ :class="colorClass":animate="{- scale: isVideoPlaying ? 1.06 : 1,+ scale: isVideoPlaying ? 1.08 : indicatorState === 'processing' ? 1.02 : 1,+ rotate: indicatorState === 'error' ? [0, -2, 2, 0] : 0,}":transition="{- duration: 0.3,- ease: 'easeInOut',+ duration: indicatorState === 'error' ? 0.5 : 0.3,+ ease: indicatorState === 'error' ? 'easeInOut' : 'easeOut',}">- <Icon+ <!-- 处理中状态 -->+ <motion.divv-if="processingState?.isProcessing"- name="tabler:loader"- class="size-[17px] animate-spin"- />+ class="size-[17px] relative"+ :animate="{ rotate: 360 }"+ :transition="{ duration: 1, repeat: Infinity, ease: 'linear' }"+ >+ <Icon+ name="tabler:loader"+ class="size-[17px]"+ />+ </motion.div>++ <!-- 错误状态 -->+ <motion.div+ v-else-if="processingState?.error"+ class="size-[17px]"+ :animate="{ scale: [1, 1.1, 1] }"+ :transition="{ duration: 0.6, repeat: Infinity }"+ >+ <Icon+ name="tabler:alert-circle"+ class="size-[17px]"+ />+ </motion.div>++ <!-- 播放中状态 -->+ <motion.div+ v-else-if="isVideoPlaying"+ class="size-[17px]"+ :animate="{ scale: [1, 1.1, 1] }"+ :transition="{ duration: 0.8, repeat: Infinity }"+ >+ <Icon+ name="tabler:player-play-filled"+ class="size-[17px]"+ />+ </motion.div>++ <!-- 正常状态 --><Iconv-elsename="tabler:live-photo"class="size-[17px]"/>- <span>{{ $t('ui.livePhoto') }}</span>++ <span class="truncate">{{ displayText }}</span>- <span+ <!-- 进度条 -->+ <motion.divv-if="processingState?.isProcessing"- class="text-[12px] text-white/80 pl-1"+ class="text-[11px] opacity-80 pl-0.5 min-w-[2ch]"+ :animate="{ opacity: [0.6, 1, 0.6] }"+ :transition="{ duration: 1.5, repeat: Infinity }">{{ Math.round(processingState.progress || 0) }}%- </span>+ </motion.div>++ <!-- 重试计数 -->+ <motion.div+ v-if="processingState?.retryCount && processingState.retryCount > 0"+ class="text-[10px] opacity-60 pl-0.5"+ :animate="{ scale: [1, 1.2, 1] }"+ :transition="{ duration: 0.3 }"+ >+ ({{ processingState.retryCount }}/3)+ </motion.div></motion.div></template>diff --git a/app/components/upload/DragDropUploadZone.vue b/app/components/upload/DragDropUploadZone.vuenew file mode 100644index 00000000..115a7e2c--- /dev/null+++ b/app/components/upload/DragDropUploadZone.vue@@ -0,0 +1,347 @@+<script lang="ts" setup>+import { motion, AnimatePresence } from 'motion-v'+import { ref, computed } from 'vue'++interface Props {+ isDragOver?: boolean+ isUploading?: boolean+ acceptedTypes?: string+ maxFileSize?: number+ disabled?: boolean+}++const props = withDefaults(defineProps<Props>(), {+ isDragOver: false,+ isUploading: false,+ acceptedTypes: 'image/jpeg,image/png,image/heic,image/heif,video/quicktime,.mov',+ maxFileSize: 100,+ disabled: false+})++const emit = defineEmits<{+ filesSelected: [files: FileList]+ dragEnter: []+ dragLeave: []+}>()++const fileInputRef = ref<HTMLInputElement>()+const isDragOverInternal = ref(false)+const dragCounter = ref(0)++// 计算拖拽状态+const isActive = computed(() => props.isDragOver || isDragOverInternal.value)++// 处理拖拽事件+const handleDragEnter = (e: DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ dragCounter.value++++ if (dragCounter.value === 1) {+ isDragOverInternal.value = true+ emit('dragEnter')+ }+}++const handleDragLeave = (e: DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+ dragCounter.value--++ if (dragCounter.value === 0) {+ isDragOverInternal.value = false+ emit('dragLeave')+ }+}++const handleDragOver = (e: DragEvent) => {+ e.preventDefault()+ e.stopPropagation()+}++const handleDrop = (e: DragEvent) => {+ e.preventDefault()+ e.stopPropagation()++ dragCounter.value = 0+ isDragOverInternal.value = false+ emit('dragLeave')++ if (props.disabled) return++ const files = e.dataTransfer?.files+ if (files && files.length > 0) {+ emit('filesSelected', files)+ }+}++// 处理文件选择+const handleFileSelect = (e: Event) => {+ const input = e.target as HTMLInputElement+ if (input.files && input.files.length > 0) {+ emit('filesSelected', input.files)+ }+ // 清空输入值以允许重新选择相同文件+ input.value = ''+}++// 触发文件选择+const triggerFileSelect = () => {+ if (!props.disabled) {+ fileInputRef.value?.click()+ }+}++// 格式化接受的文件类型+const acceptedTypesText = computed(() => {+ return 'JPEG、PNG、HEIC 格式照片,以及 MOV 格式 LivePhoto 视频'+})+</script>++<template>+ <motion.div+ class="relative border-2 border-dashed rounded-xl transition-all duration-300 cursor-pointer overflow-hidden"+ :class="{+ 'border-blue-300 bg-blue-50 dark:border-blue-600 dark:bg-blue-950/30': isActive && !disabled,+ 'border-neutral-300 dark:border-neutral-600 hover:border-neutral-400 dark:hover:border-neutral-500': !isActive && !disabled,+ 'border-neutral-200 dark:border-neutral-700 cursor-not-allowed opacity-50': disabled+ }"+ :animate="{+ scale: isActive ? 1.02 : 1,+ borderWidth: isActive ? 3 : 2+ }"+ :transition="{ duration: 0.2, ease: 'easeOut' }"+ @dragenter="handleDragEnter"+ @dragleave="handleDragLeave"+ @dragover="handleDragOver"+ @drop="handleDrop"+ @click="triggerFileSelect"+ >+ <!-- 背景动画 -->+ <AnimatePresence>+ <motion.div+ v-if="isActive"+ class="absolute inset-0 bg-gradient-to-br from-blue-400/10 to-purple-400/10 dark:from-blue-600/20 dark:to-purple-600/20"+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ :transition="{ duration: 0.3 }"+ />+ </AnimatePresence>++ <!-- 内容区域 -->+ <div class="relative p-8 text-center">+ <!-- 图标区域 -->+ <motion.div+ class="mb-4 flex justify-center"+ :animate="{+ y: isActive ? -8 : 0,+ scale: isActive ? 1.1 : 1+ }"+ :transition="{ duration: 0.3, ease: 'backOut' }"+ >+ <div+ class="p-4 rounded-full"+ :class="{+ 'bg-blue-100 dark:bg-blue-900/50': isActive,+ 'bg-neutral-100 dark:bg-neutral-800': !isActive+ }"+ >+ <AnimatePresence mode="wait">+ <motion.div+ :key="isUploading ? 'uploading' : isActive ? 'active' : 'idle'"+ :initial="{ opacity: 0, rotate: -90 }"+ :animate="{ opacity: 1, rotate: 0 }"+ :exit="{ opacity: 0, rotate: 90 }"+ :transition="{ duration: 0.3 }"+ >+ <Icon+ v-if="isUploading"+ name="tabler:loader"+ class="w-8 h-8 text-blue-600 dark:text-blue-400 animate-spin"+ />+ <Icon+ v-else-if="isActive"+ name="tabler:cloud-upload"+ class="w-8 h-8 text-blue-600 dark:text-blue-400"+ />+ <Icon+ v-else+ name="tabler:photo-plus"+ class="w-8 h-8 text-neutral-500 dark:text-neutral-400"+ />+ </motion.div>+ </AnimatePresence>+ </div>+ </motion.div>++ <!-- 文本区域 -->+ <motion.div+ :animate="{+ y: isActive ? -4 : 0+ }"+ :transition="{ duration: 0.3, ease: 'easeOut' }"+ >+ <AnimatePresence mode="wait">+ <motion.div+ :key="isUploading ? 'uploading' : isActive ? 'active' : 'idle'"+ :initial="{ opacity: 0, y: 10 }"+ :animate="{ opacity: 1, y: 0 }"+ :exit="{ opacity: 0, y: -10 }"+ :transition="{ duration: 0.3 }"+ >+ <h3+ class="text-lg font-semibold mb-2"+ :class="{+ 'text-blue-700 dark:text-blue-300': isActive,+ 'text-neutral-900 dark:text-neutral-100': !isActive+ }"+ >+ <template v-if="isUploading">+ 正在上传文件...+ </template>+ <template v-else-if="isActive">+ 松开以上传文件+ </template>+ <template v-else>+ 选择照片上传+ </template>+ </h3>++ <p+ class="text-sm mb-4"+ :class="{+ 'text-blue-600 dark:text-blue-400': isActive,+ 'text-neutral-600 dark:text-neutral-400': !isActive+ }"+ >+ <template v-if="isUploading">+ 请稍候,文件正在处理中...+ </template>+ <template v-else-if="isActive">+ 拖拽文件到此区域即可开始上传+ </template>+ <template v-else>+ 点击选择文件或将文件拖拽到此处+ </template>+ </p>+ </motion.div>+ </AnimatePresence>++ <!-- 支持的文件类型 -->+ <motion.div+ class="text-xs text-neutral-500 dark:text-neutral-400"+ :animate="{+ opacity: isActive ? 0.8 : 0.6+ }"+ :transition="{ duration: 0.2 }"+ >+ <p class="mb-1">支持格式: {{ acceptedTypesText }}</p>+ <p>最大文件大小: {{ maxFileSize }}MB</p>+ </motion.div>++ <!-- 上传按钮 -->+ <motion.div+ v-if="!isActive && !isUploading"+ class="mt-4"+ :initial="{ opacity: 0, scale: 0.9 }"+ :animate="{ opacity: 1, scale: 1 }"+ :transition="{ delay: 0.1, duration: 0.3 }"+ >+ <UButton+ color="primary"+ variant="soft"+ icon="tabler:upload"+ :disabled="disabled"+ @click.stop="triggerFileSelect"+ >+ 选择文件+ </UButton>+ </motion.div>+ </motion.div>++ <!-- 浮动粒子效果 -->+ <AnimatePresence>+ <motion.div+ v-if="isActive"+ class="absolute inset-0 pointer-events-none"+ :initial="{ opacity: 0 }"+ :animate="{ opacity: 1 }"+ :exit="{ opacity: 0 }"+ >+ <div+ v-for="i in 6"+ :key="i"+ class="absolute w-2 h-2 bg-blue-400 dark:bg-blue-500 rounded-full opacity-30"+ :class="`particle-${i}`"+ />+ </motion.div>+ </AnimatePresence>+ </div>++ <!-- 隐藏的文件输入 -->+ <input+ ref="fileInputRef"+ type="file"+ multiple+ :accept="acceptedTypes"+ class="hidden"+ :disabled="disabled"+ @change="handleFileSelect"+ >+ </motion.div>+</template>++<style scoped>+/* 粒子动画 */+.particle-1 {+ top: 20%;+ left: 15%;+ animation: float 3s ease-in-out infinite;+ animation-delay: 0s;+}++.particle-2 {+ top: 30%;+ right: 20%;+ animation: float 2.5s ease-in-out infinite;+ animation-delay: 0.5s;+}++.particle-3 {+ bottom: 30%;+ left: 25%;+ animation: float 3.5s ease-in-out infinite;+ animation-delay: 1s;+}++.particle-4 {+ bottom: 20%;+ right: 15%;+ animation: float 2.8s ease-in-out infinite;+ animation-delay: 1.5s;+}++.particle-5 {+ top: 50%;+ left: 10%;+ animation: float 3.2s ease-in-out infinite;+ animation-delay: 2s;+}++.particle-6 {+ top: 60%;+ right: 25%;+ animation: float 2.3s ease-in-out infinite;+ animation-delay: 2.5s;+}++@keyframes float {+ 0%, 100% {+ transform: translateY(0) scale(1);+ }+ 50% {+ transform: translateY(-20px) scale(1.2);+ }+}+</style>diff --git a/app/components/upload/UploadAnimationCard.vue b/app/components/upload/UploadAnimationCard.vuenew file mode 100644index 00000000..b0cf23ee--- /dev/null+++ b/app/components/upload/UploadAnimationCard.vue@@ -0,0 +1,407 @@+<script lang="ts" setup>+import { motion, AnimatePresence } from 'motion-v'+import { computed } from 'vue'++interface UploadFile {+ file: File+ fileName: string+ fileId: string+ status: 'preparing' | 'uploading' | 'processing' | 'completed' | 'error'+ stage?: string | null+ progress?: number+ error?: string+ taskId?: number+ uploadProgress?: {+ loaded: number+ total: number+ percentage: number+ speed?: number+ timeRemaining?: number+ speedText?: string+ timeRemainingText?: string+ }+ canAbort?: boolean+ abortUpload?: () => void+}++const props = defineProps<{+ uploadingFile: UploadFile+ fileId: string+}>()++const emit = defineEmits<{+ removeFile: [fileId: string]+}>()++// 计算文件图标+const fileIcon = computed(() => {+ const file = props.uploadingFile.file+ if (file.type.startsWith('image/')) {+ return 'tabler:photo'+ } else if (file.type.startsWith('video/')) {+ return 'tabler:video'+ }+ return 'tabler:file'+})++// 计算状态颜色+const statusColor = computed(() => {+ switch (props.uploadingFile.status) {+ case 'preparing':+ return 'blue'+ case 'uploading':+ return 'blue'+ case 'processing':+ return 'purple'+ case 'completed':+ return 'green'+ case 'error':+ return 'red'+ default:+ return 'neutral'+ }+})++// 计算状态文本+const statusText = computed(() => {+ switch (props.uploadingFile.status) {+ case 'preparing':+ return '准备中'+ case 'uploading':+ return `上传中 ${props.uploadingFile.progress || 0}%`+ case 'processing':+ return props.uploadingFile.stage+ ? getStageText(props.uploadingFile.stage)+ : '等待处理'+ case 'completed':+ return '完成'+ case 'error':+ return '错误'+ default:+ return '未知'+ }+})++// 获取处理阶段文本+const getStageText = (stage: string) => {+ const stageMap: Record<string, string> = {+ 'preprocessing': '预处理中',+ 'metadata': '提取元数据',+ 'thumbnail': '生成缩略图',+ 'exif': '处理EXIF',+ 'reverse-geocoding': '地理解析',+ 'live-photo': '处理LivePhoto'+ }+ return stageMap[stage] || stage+}++// 计算进度值+const progressValue = computed(() => {+ if (props.uploadingFile.status === 'uploading') {+ return props.uploadingFile.progress || 0+ }+ if (props.uploadingFile.status === 'processing') {+ return props.uploadingFile.stage ? undefined : null+ }+ if (props.uploadingFile.status === 'completed') {+ return 100+ }+ return 0+})++// 文件大小格式化+const formatBytes = (bytes: number) => {+ if (bytes === 0) return '0 B'+ const k = 1024+ const sizes = ['B', 'KB', 'MB', 'GB']+ const i = Math.floor(Math.log(bytes) / Math.log(k))+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]+}+</script>++<template>+ <motion.div+ class="bg-white dark:bg-neutral-800 rounded-lg p-4 shadow-sm border border-neutral-200 dark:border-neutral-700"+ :initial="{ opacity: 0, scale: 0.95, y: 20 }"+ :animate="{ opacity: 1, scale: 1, y: 0 }"+ :exit="{ opacity: 0, scale: 0.95, y: -20 }"+ :transition="{ duration: 0.3, ease: 'easeOut' }"+ layout+ >+ <!-- 文件信息头部 -->+ <div class="flex items-center justify-between mb-3">+ <div class="flex items-center gap-3 flex-1 min-w-0">+ <!-- 文件图标 -->+ <motion.div+ class="relative flex-shrink-0"+ :animate="{+ rotate: uploadingFile.status === 'processing' ? 360 : 0+ }"+ :transition="{+ duration: uploadingFile.status === 'processing' ? 2 : 0.3,+ repeat: uploadingFile.status === 'processing' ? Infinity : 0,+ ease: 'linear'+ }"+ >+ <div+ class="w-10 h-10 rounded-lg flex items-center justify-center"+ :class="`bg-${statusColor}-100 dark:bg-${statusColor}-900/30`"+ >+ <Icon+ :name="fileIcon"+ class="w-5 h-5"+ :class="`text-${statusColor}-600 dark:text-${statusColor}-400`"+ />+ </div>++ <!-- 状态指示器 -->+ <motion.div+ v-if="uploadingFile.status !== 'completed'"+ class="absolute -top-1 -right-1 w-4 h-4 rounded-full border-2 border-white dark:border-neutral-800 flex items-center justify-center"+ :class="{+ 'bg-blue-500': uploadingFile.status === 'preparing' || uploadingFile.status === 'uploading',+ 'bg-purple-500': uploadingFile.status === 'processing',+ 'bg-red-500': uploadingFile.status === 'error'+ }"+ :animate="{+ scale: uploadingFile.status === 'processing' ? [1, 1.2, 1] : 1+ }"+ :transition="{+ duration: 1,+ repeat: uploadingFile.status === 'processing' ? Infinity : 0+ }"+ >+ <Icon+ v-if="uploadingFile.status === 'error'"+ name="tabler:x"+ class="w-2.5 h-2.5 text-white"+ />+ <motion.div+ v-else+ class="w-2 h-2 bg-white rounded-full"+ :animate="{+ opacity: uploadingFile.status === 'processing' ? [0.5, 1, 0.5] : 1+ }"+ :transition="{+ duration: 1.5,+ repeat: uploadingFile.status === 'processing' ? Infinity : 0+ }"+ />+ </motion.div>++ <!-- 完成指示器 -->+ <motion.div+ v-if="uploadingFile.status === 'completed'"+ class="absolute -top-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white dark:border-neutral-800 flex items-center justify-center"+ :initial="{ scale: 0 }"+ :animate="{ scale: 1 }"+ :transition="{ delay: 0.2, duration: 0.3, ease: 'backOut' }"+ >+ <Icon+ name="tabler:check"+ class="w-2.5 h-2.5 text-white"+ />+ </motion.div>+ </motion.div>++ <!-- 文件信息 -->+ <div class="flex-1 min-w-0">+ <div class="flex items-center gap-2 mb-1">+ <p class="font-medium text-sm truncate text-neutral-900 dark:text-neutral-100">+ {{ uploadingFile.fileName }}+ </p>+ <UBadge+ :color="statusColor"+ variant="soft"+ size="sm"+ >+ {{ statusText }}+ </UBadge>+ </div>++ <div class="flex items-center gap-2 text-xs text-neutral-500 dark:text-neutral-400">+ <span>{{ formatBytes(uploadingFile.file.size) }}</span>+ <span+ v-if="uploadingFile.uploadProgress?.speedText && uploadingFile.status === 'uploading'"+ class="hidden sm:inline"+ >+ • {{ uploadingFile.uploadProgress.speedText }}+ </span>+ </div>+ </div>+ </div>++ <!-- 操作按钮 -->+ <div class="flex items-center gap-2 ml-2">+ <!-- 中止上传按钮 -->+ <motion.div+ v-if="uploadingFile.status === 'uploading' && uploadingFile.canAbort"+ :initial="{ opacity: 0, scale: 0.8 }"+ :animate="{ opacity: 1, scale: 1 }"+ :exit="{ opacity: 0, scale: 0.8 }"+ >+ <UButton+ size="xs"+ color="red"+ variant="ghost"+ icon="tabler:x"+ @click="uploadingFile.abortUpload?.()"+ >+ 中止+ </UButton>+ </motion.div>++ <!-- 清除按钮 -->+ <motion.div+ v-if="uploadingFile.status === 'completed' || uploadingFile.status === 'error'"+ :initial="{ opacity: 0, scale: 0.8 }"+ :animate="{ opacity: 1, scale: 1 }"+ :exit="{ opacity: 0, scale: 0.8 }"+ >+ <UButton+ size="xs"+ color="neutral"+ variant="ghost"+ icon="tabler:x"+ @click="emit('removeFile', fileId)"+ >+ 清除+ </UButton>+ </motion.div>+ </div>+ </div>++ <!-- 进度条区域 -->+ <AnimatePresence>+ <motion.div+ v-if="uploadingFile.status === 'uploading' || uploadingFile.status === 'processing'"+ :initial="{ opacity: 0, height: 0 }"+ :animate="{ opacity: 1, height: 'auto' }"+ :exit="{ opacity: 0, height: 0 }"+ :transition="{ duration: 0.3 }"+ class="space-y-2"+ >+ <!-- 上传进度 -->+ <div+ v-if="uploadingFile.status === 'uploading'"+ class="space-y-1"+ >+ <div class="flex justify-between items-center">+ <span class="text-xs text-neutral-600 dark:text-neutral-400">+ 上传进度+ </span>+ <span class="text-xs font-mono text-neutral-600 dark:text-neutral-400">+ {{ uploadingFile.progress }}%+ </span>+ </div>++ <motion.div+ class="relative"+ :initial="{ scaleX: 0 }"+ :animate="{ scaleX: 1 }"+ :transition="{ duration: 0.5 }"+ >+ <UProgress+ :model-value="progressValue"+ :color="statusColor"+ class="h-2"+ />+ </motion.div>++ <div+ v-if="uploadingFile.uploadProgress?.timeRemainingText"+ class="text-xs text-neutral-500 dark:text-neutral-400"+ >+ 剩余时间: {{ uploadingFile.uploadProgress.timeRemainingText }}+ </div>+ </div>++ <!-- 处理进度 -->+ <div+ v-if="uploadingFile.status === 'processing'"+ class="space-y-1"+ >+ <div class="flex justify-between items-center">+ <span class="text-xs text-neutral-600 dark:text-neutral-400">+ 处理状态+ </span>+ <motion.span+ class="text-xs text-purple-600 dark:text-purple-400"+ :animate="{ opacity: [0.6, 1, 0.6] }"+ :transition="{ duration: 2, repeat: Infinity }"+ >+ {{ getStageText(uploadingFile.stage || 'pending') }}+ </motion.span>+ </div>++ <UProgress+ :model-value="progressValue"+ animation="carousel"+ color="purple"+ class="h-2"+ />+ </div>+ </motion.div>+ </AnimatePresence>++ <!-- 错误信息 -->+ <AnimatePresence>+ <motion.div+ v-if="uploadingFile.status === 'error' && uploadingFile.error"+ :initial="{ opacity: 0, height: 0, y: -10 }"+ :animate="{ opacity: 1, height: 'auto', y: 0 }"+ :exit="{ opacity: 0, height: 0, y: -10 }"+ :transition="{ duration: 0.3 }"+ class="mt-3"+ >+ <UAlert+ :description="uploadingFile.error"+ color="red"+ variant="soft"+ icon="tabler:alert-circle"+ />+ </motion.div>+ </AnimatePresence>++ <!-- 成功动画 -->+ <AnimatePresence>+ <motion.div+ v-if="uploadingFile.status === 'completed'"+ :initial="{ opacity: 0, scale: 0.9 }"+ :animate="{ opacity: 1, scale: 1 }"+ :exit="{ opacity: 0, scale: 0.9 }"+ :transition="{ duration: 0.3, delay: 0.1 }"+ class="mt-3 flex items-center gap-2 text-green-600 dark:text-green-400"+ >+ <Icon name="tabler:check-circle" class="w-4 h-4" />+ <span class="text-sm font-medium">上传完成</span>+ </motion.div>+ </AnimatePresence>+ </motion.div>+</template>++<style scoped>+/* 动态颜色类 - 确保Tailwind包含这些类 */+.bg-blue-100,+.bg-blue-900\/30,+.text-blue-600,+.text-blue-400,+.bg-purple-100,+.bg-purple-900\/30,+.text-purple-600,+.text-purple-400,+.bg-green-100,+.bg-green-900\/30,+.text-green-600,+.text-green-400,+.bg-red-100,+.bg-red-900\/30,+.text-red-600,+.text-red-400,+.bg-neutral-100,+.bg-neutral-900\/30,+.text-neutral-600,+.text-neutral-400 {+ /* Tailwind会自动生成这些类 */+}+</style>diff --git a/app/components/upload/UploadProgressToast.vue b/app/components/upload/UploadProgressToast.vuenew file mode 100644index 00000000..f94820d4--- /dev/null+++ b/app/components/upload/UploadProgressToast.vue@@ -0,0 +1,156 @@+<script lang="ts" setup>+import { motion, AnimatePresence } from 'motion-v'+import { computed } from 'vue'++interface UploadStats {+ total: number+ uploading: number+ processing: number+ completed: number+ error: number+ active: number+ overallProgress: number+}++const props = defineProps<{+ stats: UploadStats+ visible: boolean+}>()++const emit = defineEmits<{+ close: []+ showDetails: []+}>()++// 计算显示文本+const statusText = computed(() => {+ if (props.stats.active === 0) {+ return props.stats.error > 0 ? '上传完成(有错误)' : '上传完成'+ }+ return `${props.stats.active} 个文件正在处理`+})++// 计算状态颜色+const statusColor = computed(() => {+ if (props.stats.error > 0 && props.stats.active === 0) return 'red'+ if (props.stats.active > 0) return 'blue'+ return 'green'+})++// 计算图标+const statusIcon = computed(() => {+ if (props.stats.active > 0) return 'tabler:upload'+ if (props.stats.error > 0) return 'tabler:alert-circle'+ return 'tabler:check-circle'+})+</script>++<template>+ <AnimatePresence>+ <motion.div+ v-if="visible"+ class="fixed top-4 right-4 z-50 max-w-sm"+ :initial="{ opacity: 0, x: 100, scale: 0.9 }"+ :animate="{ opacity: 1, x: 0, scale: 1 }"+ :exit="{ opacity: 0, x: 100, scale: 0.9 }"+ :transition="{ duration: 0.3, ease: 'backOut' }"+ >+ <motion.div+ class="bg-white dark:bg-neutral-900 rounded-lg shadow-lg border border-neutral-200 dark:border-neutral-700 p-4 cursor-pointer"+ :whileHover="{ scale: 1.02 }"+ :whileTap="{ scale: 0.98 }"+ @click="emit('showDetails')"+ >+ <!-- 头部 -->+ <div class="flex items-center justify-between mb-3">+ <div class="flex items-center gap-2">+ <motion.div+ :animate="{+ rotate: stats.active > 0 ? 360 : 0+ }"+ :transition="{+ duration: stats.active > 0 ? 2 : 0.3,+ repeat: stats.active > 0 ? Infinity : 0,+ ease: 'linear'+ }"+ >+ <Icon+ :name="statusIcon"+ class="w-5 h-5"+ :class="{+ 'text-blue-600 dark:text-blue-400': statusColor === 'blue',+ 'text-green-600 dark:text-green-400': statusColor === 'green',+ 'text-red-600 dark:text-red-400': statusColor === 'red'+ }"+ />+ </motion.div>++ <span class="font-medium text-sm text-neutral-900 dark:text-neutral-100">+ {{ statusText }}+ </span>+ </div>++ <UButton+ size="xs"+ color="neutral"+ variant="ghost"+ icon="tabler:x"+ @click.stop="emit('close')"+ />+ </div>++ <!-- 进度信息 -->+ <div class="space-y-2">+ <!-- 整体进度条 -->+ <motion.div+ v-if="stats.active > 0"+ :initial="{ scaleX: 0 }"+ :animate="{ scaleX: 1 }"+ :transition="{ duration: 0.5 }"+ style="transform-origin: left"+ >+ <div class="flex justify-between text-xs text-neutral-600 dark:text-neutral-400 mb-1">+ <span>整体进度</span>+ <span>{{ stats.overallProgress }}%</span>+ </div>+ <UProgress+ :model-value="stats.overallProgress"+ :color="statusColor"+ class="h-1.5"+ />+ </motion.div>++ <!-- 统计信息 -->+ <div class="flex items-center gap-4 text-xs text-neutral-600 dark:text-neutral-400">+ <div v-if="stats.uploading > 0" class="flex items-center gap-1">+ <div class="w-2 h-2 bg-blue-500 rounded-full animate-pulse" />+ <span>{{ stats.uploading }} 上传中</span>+ </div>++ <div v-if="stats.processing > 0" class="flex items-center gap-1">+ <div class="w-2 h-2 bg-purple-500 rounded-full animate-pulse" />+ <span>{{ stats.processing }} 处理中</span>+ </div>++ <div v-if="stats.completed > 0" class="flex items-center gap-1">+ <div class="w-2 h-2 bg-green-500 rounded-full" />+ <span>{{ stats.completed }} 完成</span>+ </div>++ <div v-if="stats.error > 0" class="flex items-center gap-1">+ <div class="w-2 h-2 bg-red-500 rounded-full" />+ <span>{{ stats.error }} 失败</span>+ </div>+ </div>+ </div>++ <!-- 点击提示 -->+ <div class="mt-2 text-xs text-neutral-500 dark:text-neutral-400">+ 点击查看详情+ </div>+ </motion.div>+ </motion.div>+ </AnimatePresence>+</template>++<style scoped></style>diff --git a/app/components/upload/UploadQueueContainer.vue b/app/components/upload/UploadQueueContainer.vuenew file mode 100644index 00000000..458076aa--- /dev/null+++ b/app/components/upload/UploadQueueContainer.vue@@ -0,0 +1,286 @@+<script lang="ts" setup>+import { motion, AnimatePresence } from 'motion-v'+import { computed, ref } from 'vue'++interface UploadFile {+ file: File+ fileName: string+ fileId: string+ status: 'preparing' | 'uploading' | 'processing' | 'completed' | 'error'+ stage?: string | null+ progress?: number+ error?: string+ taskId?: number+ uploadProgress?: {+ loaded: number+ total: number+ percentage: number+ speed?: number+ timeRemaining?: number+ speedText?: string+ timeRemainingText?: string+ }+ canAbort?: boolean+ abortUpload?: () => void+}++const props = defineProps<{+ uploadingFiles: Map<string, UploadFile>+ collapsed?: boolean+}>()++const emit = defineEmits<{+ removeFile: [fileId: string]+ clearCompleted: []+ clearAll: []+ toggle: []+}>()++const isCollapsed = ref(props.collapsed || false)++// 计算统计信息+const stats = computed(() => {+ const files = Array.from(props.uploadingFiles.values())+ return {+ total: files.length,+ uploading: files.filter(f => f.status === 'uploading').length,+ processing: files.filter(f => f.status === 'processing').length,+ completed: files.filter(f => f.status === 'completed').length,+ error: files.filter(f => f.status === 'error').length,+ active: files.filter(f => f.status === 'uploading' || f.status === 'processing').length,+ }+})++// 计算整体进度+const overallProgress = computed(() => {+ const files = Array.from(props.uploadingFiles.values())+ if (files.length === 0) return 0++ let totalProgress = 0+ files.forEach(file => {+ if (file.status === 'completed') {+ totalProgress += 100+ } else if (file.status === 'uploading' && file.progress !== undefined) {+ totalProgress += file.progress+ } else if (file.status === 'processing') {+ totalProgress += 50 // 估算处理进度为50%+ }+ })++ return Math.round(totalProgress / files.length)+})++// 计算状态颜色+const statusColor = computed(() => {+ if (stats.value.error > 0) return 'red'+ if (stats.value.active > 0) return 'blue'+ if (stats.value.completed > 0 && stats.value.active === 0) return 'green'+ return 'neutral'+})++// 切换折叠状态+const toggleCollapsed = () => {+ isCollapsed.value = !isCollapsed.value+ emit('toggle')+}++// 清除已完成的文件+const clearCompletedFiles = () => {+ emit('clearCompleted')+}++// 清除所有文件+const clearAllFiles = () => {+ emit('clearAll')+}+</script>++<template>+ <div+ v-if="uploadingFiles.size > 0"+ class="fixed bottom-4 right-4 z-50 w-96 max-w-[calc(100vw-2rem)]"+ >+ <motion.div+ class="bg-white dark:bg-neutral-900 rounded-xl shadow-xl border border-neutral-200 dark:border-neutral-700 overflow-hidden"+ :initial="{ opacity: 0, y: 100, scale: 0.9 }"+ :animate="{ opacity: 1, y: 0, scale: 1 }"+ :exit="{ opacity: 0, y: 100, scale: 0.9 }"+ :transition="{ duration: 0.4, ease: 'backOut' }"+ layout+ >+ <!-- 头部 -->+ <motion.div+ class="p-4 border-b border-neutral-200 dark:border-neutral-700 cursor-pointer"+ @click="toggleCollapsed"+ :whileHover="{ backgroundColor: 'rgba(0,0,0,0.02)' }"+ :whileTap="{ scale: 0.98 }"+ >+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-3">+ <!-- 状态指示器 -->+ <motion.div+ class="w-3 h-3 rounded-full"+ :class="{+ 'bg-blue-500': statusColor === 'blue',+ 'bg-green-500': statusColor === 'green',+ 'bg-red-500': statusColor === 'red',+ 'bg-neutral-400': statusColor === 'neutral'+ }"+ :animate="{+ scale: stats.active > 0 ? [1, 1.2, 1] : 1,+ opacity: stats.active > 0 ? [0.7, 1, 0.7] : 1+ }"+ :transition="{+ duration: 2,+ repeat: stats.active > 0 ? Infinity : 0+ }"+ />++ <!-- 标题和统计 -->+ <div>+ <h3 class="font-semibold text-sm text-neutral-900 dark:text-neutral-100">+ 文件上传队列+ <span class="text-neutral-500 dark:text-neutral-400">+ ({{ stats.total }})+ </span>+ </h3>++ <div class="flex items-center gap-2 text-xs text-neutral-500 dark:text-neutral-400 mt-1">+ <span v-if="stats.active > 0" class="text-blue-600 dark:text-blue-400">+ {{ stats.active }} 进行中+ </span>+ <span v-if="stats.completed > 0" class="text-green-600 dark:text-green-400">+ {{ stats.completed }} 完成+ </span>+ <span v-if="stats.error > 0" class="text-red-600 dark:text-red-400">+ {{ stats.error }} 失败+ </span>+ </div>+ </div>+ </div>++ <div class="flex items-center gap-2">+ <!-- 整体进度 -->+ <div+ v-if="stats.active > 0"+ class="text-xs text-neutral-500 dark:text-neutral-400 font-mono"+ >+ {{ overallProgress }}%+ </div>++ <!-- 折叠图标 -->+ <motion.div+ :animate="{ rotate: isCollapsed ? 0 : 180 }"+ :transition="{ duration: 0.3 }"+ >+ <Icon+ name="tabler:chevron-down"+ class="w-4 h-4 text-neutral-500 dark:text-neutral-400"+ />+ </motion.div>+ </div>+ </div>++ <!-- 整体进度条 -->+ <motion.div+ v-if="stats.active > 0"+ class="mt-3"+ :initial="{ opacity: 0, scaleX: 0 }"+ :animate="{ opacity: 1, scaleX: 1 }"+ :exit="{ opacity: 0, scaleX: 0 }"+ :transition="{ duration: 0.3 }"+ style="transform-origin: left"+ >+ <UProgress+ :model-value="overallProgress"+ :color="statusColor"+ class="h-1.5"+ />+ </motion.div>+ </motion.div>++ <!-- 文件列表 -->+ <AnimatePresence>+ <motion.div+ v-if="!isCollapsed"+ :initial="{ height: 0, opacity: 0 }"+ :animate="{ height: 'auto', opacity: 1 }"+ :exit="{ height: 0, opacity: 0 }"+ :transition="{ duration: 0.3, ease: 'easeInOut' }"+ class="max-h-96 overflow-y-auto"+ >+ <div class="p-2 space-y-2">+ <AnimatePresence mode="popLayout">+ <UploadAnimationCard+ v-for="[fileId, uploadingFile] in uploadingFiles"+ :key="fileId"+ :uploading-file="uploadingFile"+ :file-id="fileId"+ @remove-file="emit('removeFile', $event)"+ />+ </AnimatePresence>+ </div>+ </motion.div>+ </AnimatePresence>++ <!-- 底部操作栏 -->+ <AnimatePresence>+ <motion.div+ v-if="!isCollapsed && (stats.completed > 0 || stats.error > 0)"+ :initial="{ opacity: 0, height: 0 }"+ :animate="{ opacity: 1, height: 'auto' }"+ :exit="{ opacity: 0, height: 0 }"+ :transition="{ duration: 0.3 }"+ class="p-3 border-t border-neutral-200 dark:border-neutral-700 bg-neutral-50 dark:bg-neutral-800/50"+ >+ <div class="flex items-center justify-between gap-2">+ <div class="text-xs text-neutral-500 dark:text-neutral-400">+ {{ stats.completed }} 完成, {{ stats.error }} 失败+ </div>++ <div class="flex items-center gap-2">+ <UButton+ v-if="stats.completed > 0"+ size="xs"+ variant="ghost"+ color="neutral"+ @click="clearCompletedFiles"+ >+ 清除已完成+ </UButton>++ <UButton+ size="xs"+ variant="ghost"+ color="red"+ @click="clearAllFiles"+ >+ 清除全部+ </UButton>+ </div>+ </div>+ </motion.div>+ </AnimatePresence>+ </motion.div>+ </div>+</template>++<style scoped>+/* 滚动条样式 */+.max-h-96::-webkit-scrollbar {+ width: 4px;+}++.max-h-96::-webkit-scrollbar-track {+ background: transparent;+}++.max-h-96::-webkit-scrollbar-thumb {+ background: rgba(0, 0, 0, 0.2);+ border-radius: 2px;+}++.dark .max-h-96::-webkit-scrollbar-thumb {+ background: rgba(255, 255, 255, 0.2);+}+</style>diff --git a/app/composables/useLivePhotoProcessor.ts b/app/composables/useLivePhotoProcessor.tsindex c90a6221..d4929242 100644--- a/app/composables/useLivePhotoProcessor.ts+++ b/app/composables/useLivePhotoProcessor.ts@@ -5,6 +5,8 @@ interface LivePhotoProcessingState {progress: numbermp4Blob: Blob | nullerror: string | null+ lastProcessed?: number // 添加时间戳用于缓存管理+ retryCount?: number // 添加重试计数}// 全局存储已转换的实况照片@@ -17,19 +19,29 @@ export const useLivePhotoProcessor = () => {* @param photoId 照片 ID*/const convertMovToMp4 = async (movUrl: string, photoId: string): Promise<Blob | null> => {- // 如果已经在处理或已经处理完成,直接返回+ // 检查缓存状态const existing = processedLivePhotos.value.get(photoId)if (existing) {- if (existing.mp4Blob) {+ // 检查缓存是否过期(24小时)+ const now = Date.now()+ const cacheExpiry = 24 * 60 * 60 * 1000 // 24小时++ if (existing.mp4Blob && existing.lastProcessed && (now - existing.lastProcessed) < cacheExpiry) {return existing.mp4Blob}+if (existing.isProcessing) {- // 等待处理完成+ // 使用Promise而不是轮询,提高性能return new Promise((resolve) => {+ const timeout = setTimeout(() => {+ resolve(null) // 超时返回null+ }, 30000) // 30秒超时+const checkInterval = setInterval(() => {const current = processedLivePhotos.value.get(photoId)if (current && !current.isProcessing) {clearInterval(checkInterval)+ clearTimeout(timeout)resolve(current.mp4Blob)}}, 100)@@ -37,67 +49,139 @@ export const useLivePhotoProcessor = () => {}}- // 初始化处理状态+ // 初始化处理状态,包含重试逻辑+ const maxRetries = 3+ const currentRetry = existing?.retryCount || 0++ if (currentRetry >= maxRetries) {+ console.warn(`Max retries reached for LivePhoto ${photoId}`)+ return null+ }+const state: LivePhotoProcessingState = {isProcessing: true,progress: 0,mp4Blob: null,- error: null+ error: null,+ retryCount: currentRetry,+ lastProcessed: Date.now()}processedLivePhotos.value.set(photoId, state)try {- // 下载 MOV 文件- state.progress = 10- processedLivePhotos.value.set(photoId, { ...state })+ // 添加更平滑的进度更新+ const updateProgress = (progress: number) => {+ state.progress = progress+ processedLivePhotos.value.set(photoId, { ...state })+ }- const response = await fetch(movUrl)+ // 下载 MOV 文件,支持断点续传+ updateProgress(10)++ const controller = new AbortController()+ const timeoutId = setTimeout(() => controller.abort(), 30000) // 30秒超时++ const response = await fetch(movUrl, {+ signal: controller.signal,+ headers: {+ 'Cache-Control': 'max-age=3600', // 缓存1小时+ }+ })++ clearTimeout(timeoutId)+if (!response.ok) {- throw new Error(`Failed to fetch MOV file: ${response.statusText}`)+ throw new Error(`Failed to fetch MOV file: ${response.status} ${response.statusText}`)}- state.progress = 30- processedLivePhotos.value.set(photoId, { ...state })+ updateProgress(30)- const movBlob = await response.blob()+ // 使用流式读取,支持大文件+ const reader = response.body?.getReader()+ if (!reader) throw new Error('Failed to get response reader')- state.progress = 50- processedLivePhotos.value.set(photoId, { ...state })+ const chunks: Uint8Array[] = []+ const contentLength = parseInt(response.headers.get('content-length') || '0')+ let receivedLength = 0- // 使用 FFmpeg.wasm 或者简单的 video 元素进行转换- // 由于浏览器原生支持 MOV 播放,我们可以先尝试直接使用- // 如果需要真正的转换,可以集成 FFmpeg.wasm-- // 对于现在,我们直接创建一个可播放的 blob URL- // 大多数现代浏览器都支持 MOV 格式的播放- const mp4Blob = new Blob([movBlob], { type: 'video/mp4' })+ while (true) {+ const { done, value } = await reader.read()+ if (done) break++ chunks.push(value)+ receivedLength += value.length++ // 更新下载进度+ if (contentLength > 0) {+ const downloadProgress = 30 + (receivedLength / contentLength) * 40 // 30-70%+ updateProgress(Math.round(downloadProgress))+ }+ }- state.progress = 90- processedLivePhotos.value.set(photoId, { ...state })+ const movBlob = new Blob(chunks)+ updateProgress(70)++ // 优化的视频处理:先检查格式兼容性+ const mp4Blob = new Blob([movBlob], { type: 'video/mp4' })+ updateProgress(85)- // 验证视频是否可以播放+ // 更快的格式验证:只检查元数据const videoUrl = URL.createObjectURL(mp4Blob)const video = document.createElement('video')await new Promise<void>((resolve, reject) => {- video.onloadedmetadata = () => resolve()- video.onerror = () => reject(new Error('Video format not supported'))+ const timeout = setTimeout(() => {+ reject(new Error('Video validation timeout'))+ }, 5000) // 5秒验证超时++ video.onloadedmetadata = () => {+ clearTimeout(timeout)+ resolve()+ }+ video.onerror = () => {+ clearTimeout(timeout)+ reject(new Error('Video format not supported'))+ }video.src = videoUrl+ video.load()})URL.revokeObjectURL(videoUrl)+ updateProgress(95)+ // 成功完成state.isProcessing = falsestate.progress = 100state.mp4Blob = mp4Blob+ state.lastProcessed = Date.now()+ state.error = nullprocessedLivePhotos.value.set(photoId, { ...state })return mp4Blob} catch (error) {+ const errorMessage = error instanceof Error ? error.message : 'Unknown error'++ // 增加重试逻辑+ if (currentRetry < maxRetries - 1) {+ console.warn(`LivePhoto processing failed (attempt ${currentRetry + 1}/${maxRetries}), retrying...`, errorMessage)+ state.retryCount = currentRetry + 1+ state.isProcessing = false+ state.error = `Retrying... (${currentRetry + 1}/${maxRetries})`+ processedLivePhotos.value.set(photoId, { ...state })++ // 指数退避重试+ const retryDelay = Math.min(1000 * Math.pow(2, currentRetry), 5000)+ await new Promise(resolve => setTimeout(resolve, retryDelay))++ return convertMovToMp4(movUrl, photoId) // 递归重试+ }++ // 最终失败state.isProcessing = false- state.error = error instanceof Error ? error.message : 'Unknown error'+ state.error = errorMessage+ state.lastProcessed = Date.now()processedLivePhotos.value.set(photoId, { ...state })- console.error('Failed to convert MOV to MP4:', error)+ console.error(`Failed to convert MOV to MP4 after ${maxRetries} attempts:`, error)return null}}@@ -110,39 +194,168 @@ export const useLivePhotoProcessor = () => {}/**- * 批量处理视口内的实况照片+ * 智能预加载:基于视口和用户行为预测*/- const batchProcessLivePhotos = async (photos: Array<{ id: string; livePhotoVideoUrl?: string | null }>) => {+ const preloadLivePhotosInViewport = async (+ photos: Array<{ id: string; livePhotoVideoUrl?: string | null; isVisible?: boolean }>,+ options: {+ maxConcurrent?: number+ prioritizeVisible?: boolean+ prefetchDistance?: number+ } = {}+ ) => {+ const { maxConcurrent = 2, prioritizeVisible = true, prefetchDistance = 3 } = options+const livePhotos = photos.filter(photo => photo.livePhotoVideoUrl)- // 限制并发数量,避免过多请求- const batchSize = 3- for (let i = 0; i < livePhotos.length; i += batchSize) {- const batch = livePhotos.slice(i, i + batchSize)+ if (prioritizeVisible) {+ // 优先处理可见的LivePhoto+ const visiblePhotos = livePhotos.filter(photo => photo.isVisible)+ const nearbyPhotos = livePhotos.filter(photo => !photo.isVisible).slice(0, prefetchDistance)++ // 先处理可见的+ if (visiblePhotos.length > 0) {+ await processPhotoBatch(visiblePhotos, maxConcurrent)+ }++ // 然后预加载附近的+ if (nearbyPhotos.length > 0) {+ processPhotoBatch(nearbyPhotos, Math.min(maxConcurrent, 1)) // 降低并发数+ }+ } else {+ await processPhotoBatch(livePhotos, maxConcurrent)+ }+ }++ /**+ * 处理照片批次的辅助函数+ */+ const processPhotoBatch = async (+ photos: Array<{ id: string; livePhotoVideoUrl: string }>,+ maxConcurrent: number+ ) => {+ for (let i = 0; i < photos.length; i += maxConcurrent) {+ const batch = photos.slice(i, i + maxConcurrent)await Promise.allSettled(- batch.map(photo => convertMovToMp4(photo.livePhotoVideoUrl!, photo.id))+ batch.map(photo => convertMovToMp4(photo.livePhotoVideoUrl, photo.id)))++ // 添加小延迟避免过度占用资源+ if (i + maxConcurrent < photos.length) {+ await new Promise(resolve => setTimeout(resolve, 100))+ }+ }+ }++ /**+ * 批量处理视口内的实况照片(保持兼容性)+ */+ const batchProcessLivePhotos = async (photos: Array<{ id: string; livePhotoVideoUrl?: string | null }>) => {+ await preloadLivePhotosInViewport(photos, { maxConcurrent: 3 })+ }++ /**+ * 智能内存管理:清理过期或不需要的缓存+ */+ const cleanupExpiredCache = () => {+ const now = Date.now()+ const cacheExpiry = 24 * 60 * 60 * 1000 // 24小时+ const maxCacheSize = 50 // 最大缓存50个LivePhoto++ const entries = Array.from(processedLivePhotos.value.entries())+ const expiredEntries: string[] = []++ // 查找过期的条目+ entries.forEach(([photoId, state]) => {+ if (state.lastProcessed && (now - state.lastProcessed) > cacheExpiry) {+ expiredEntries.push(photoId)+ }+ })++ // 清理过期条目+ expiredEntries.forEach(photoId => {+ const state = processedLivePhotos.value.get(photoId)+ if (state?.mp4Blob) {+ // 这里可以安全地清理,因为已过期+ state.mp4Blob = null+ }+ processedLivePhotos.value.delete(photoId)+ })++ // 如果缓存仍然太大,清理最老的条目+ if (processedLivePhotos.value.size > maxCacheSize) {+ const sortedEntries = entries+ .filter(([photoId]) => !expiredEntries.includes(photoId))+ .sort((a, b) => (a[1].lastProcessed || 0) - (b[1].lastProcessed || 0))++ const toRemove = sortedEntries.slice(0, processedLivePhotos.value.size - maxCacheSize)+ toRemove.forEach(([photoId, state]) => {+ if (state.mp4Blob) {+ state.mp4Blob = null+ }+ processedLivePhotos.value.delete(photoId)+ })}++ console.log(`Cleaned up ${expiredEntries.length} expired LivePhoto cache entries`)}/**- * 清理已处理的实况照片缓存+ * 获取缓存统计信息+ */+ const getCacheStats = () => {+ const total = processedLivePhotos.value.size+ let processed = 0+ let processing = 0+ let failed = 0+ let totalSize = 0++ processedLivePhotos.value.forEach(state => {+ if (state.mp4Blob) {+ processed+++ totalSize += state.mp4Blob.size+ } else if (state.isProcessing) {+ processing+++ } else if (state.error) {+ failed+++ }+ })++ return {+ total,+ processed,+ processing,+ failed,+ totalSizeMB: Math.round(totalSize / (1024 * 1024) * 100) / 100+ }+ }++ /**+ * 清理所有缓存(完全清理)*/const clearProcessedCache = () => {// 释放所有 blob URLsprocessedLivePhotos.value.forEach((state) => {if (state.mp4Blob) {- // 注意:这里不直接 revoke,因为可能还在使用- // 实际应用中应该有更好的生命周期管理+ state.mp4Blob = null}})processedLivePhotos.value.clear()+ console.log('All LivePhoto cache cleared')+ }++ // 定期清理过期缓存(每10分钟)+ if (typeof window !== 'undefined') {+ setInterval(cleanupExpiredCache, 10 * 60 * 1000)}return {convertMovToMp4,getProcessingState,batchProcessLivePhotos,+ preloadLivePhotosInViewport,+ cleanupExpiredCache,+ getCacheStats,clearProcessedCache,processedLivePhotos: readonly(processedLivePhotos)}diff --git a/app/pages/dashboard/photos.vue b/app/pages/dashboard/photos.vueindex d9170777..838fa75c 100644--- a/app/pages/dashboard/photos.vue+++ b/app/pages/dashboard/photos.vue@@ -260,12 +260,7 @@ const startTaskStatusCheck = (taskId: number, fileId: string) => {clearInterval(intervalId)statusIntervals.value.delete(taskId)- // 显示成功提示- toast.add({- title: '照片处理完成',- description: `照片 ${uploadingFile.fileName} 已完成处理`,- color: 'success',- })+ // 不再显示单独的成功提示,由上传组件统一处理// 刷新照片列表await refresh()@@ -368,6 +363,45 @@ const clearCompletedTasks = () => {}}+// 清除已完成的上传+const clearCompletedUploads = () => {+ clearCompletedTasks()+}++// 清除所有上传+const clearAllUploads = () => {+ const toRemove: string[] = []++ for (const [fileId, uploadingFile] of uploadingFiles.value) {+ toRemove.push(fileId)++ // 如果是正在上传的任务,先中止+ if (uploadingFile.status === 'uploading' && uploadingFile.abortUpload) {+ uploadingFile.abortUpload()+ }++ // 清理状态检查定时器+ if (uploadingFile.taskId) {+ const intervalId = statusIntervals.value.get(uploadingFile.taskId)+ if (intervalId) {+ clearInterval(intervalId)+ statusIntervals.value.delete(uploadingFile.taskId)+ }+ }+ }++ uploadingFiles.value.clear()+ uploadingFiles.value = new Map(uploadingFiles.value)++ if (toRemove.length > 0) {+ toast.add({+ title: '已清除全部任务',+ description: `已清除 ${toRemove.length} 个上传任务`,+ color: 'info',+ })+ }+}+const columns: TableColumn<Photo>[] = [{id: 'select',@@ -913,190 +947,13 @@ onUnmounted(() => {<template><div class="flex flex-col gap-3 sm:gap-4 h-full p-3 sm:p-4">- <!-- 上传进度显示 -->- <div- v-if="uploadingFiles.size > 0"- class="space-y-3"- >- <div class="flex items-center justify-between">- <h3 class="text-lg font-semibold">上传进度</h3>- <UButton- size="sm"- color="neutral"- variant="ghost"- icon="tabler:trash"- @click="clearCompletedTasks"- >- 清除已完成任务- </UButton>- </div>- <div class="space-y-2">- <div- v-for="[fileId, uploadingFile] of uploadingFiles"- :key="fileId"- class="p-3 sm:p-4 border border-neutral-200 dark:border-neutral-700 rounded-lg"- >- <div- class="flex flex-col sm:flex-row sm:items-center justify-between gap-2 sm:gap-0 mb-2"- >- <span class="font-medium text-sm sm:text-base truncate">{{- uploadingFile.fileName- }}</span>- <div class="flex items-center gap-2">- <!-- 状态指示器 -->- <UBadge- :color="- uploadingFile.status === 'completed'- ? 'success'- : uploadingFile.status === 'error'- ? 'error'- : uploadingFile.status === 'processing'- ? 'info'- : 'warning'- "- variant="soft"- size="sm"- >- {{- uploadingFile.status === 'preparing'- ? '准备中'- : uploadingFile.status === 'uploading'- ? `上传中 ${uploadingFile.progress || 0}%`- : uploadingFile.status === 'processing'- ? uploadingFile.stage- ? uploadingFile.stage === 'preprocessing'- ? '预处理中'- : uploadingFile.stage === 'metadata'- ? '提取元数据'- : uploadingFile.stage === 'thumbnail'- ? '生成缩略图'- : uploadingFile.stage === 'exif'- ? '处理EXIF'- : uploadingFile.stage === 'reverse-geocoding'- ? '地理解析'- : uploadingFile.stage === 'live-photo'- ? '处理LivePhoto'- : '处理中'- : '等待处理'- : uploadingFile.status === 'completed'- ? '完成'- : '错误'- }}- </UBadge>-- <!-- 操作按钮 -->- <div class="flex items-center gap-2">- <!-- 中止上传按钮 -->- <UButton- v-if="- uploadingFile.status === 'uploading' &&- uploadingFile.canAbort- "- size="xs"- color="error"- variant="soft"- icon="tabler:file-x"- @click="uploadingFile.abortUpload?.()"- >- <span class="hidden sm:inline">中止上传</span>- <span class="sm:hidden">中止</span>- </UButton>-- <!-- 清除任务按钮 -->- <UButton- v-if="- uploadingFile.status === 'completed' ||- uploadingFile.status === 'error'- "- size="xs"- color="neutral"- variant="ghost"- icon="tabler:x"- @click="removeUploadingFile(fileId)"- >- <span class="hidden sm:inline">清除</span>- </UButton>- </div>- </div>- </div>-- <!-- 上传进度条 -->- <div- v-if="- uploadingFile.status === 'uploading' &&- uploadingFile.progress !== undefined- "- class="mb-2"- >- <div- class="flex justify-between text-xs sm:text-sm text-neutral-600 dark:text-neutral-400 mb-1"- >- <span>上传进度: {{ uploadingFile.progress }}%</span>- <span- v-if="uploadingFile.uploadProgress?.speedText"- class="hidden sm:inline"- >- {{ uploadingFile.uploadProgress.speedText }}- </span>- </div>- <UProgress- :model-value="uploadingFile.progress"- class="h-2"- />- <div- v-if="uploadingFile.uploadProgress?.timeRemainingText"- class="text-xs text-neutral-500 mt-1"- >- <span class="hidden sm:inline">预计剩余时间: </span>- {{ uploadingFile.uploadProgress.timeRemainingText }}- </div>- </div>-- <!-- 处理状态进度条 -->- <div- v-if="uploadingFile.status === 'processing'"- class="mb-2"- >- <div- class="flex justify-between text-xs sm:text-sm text-neutral-600 dark:text-neutral-400 mb-1"- >- <span>- 处理状态:- {{- uploadingFile.stage === 'preprocessing'- ? '预处理中'- : uploadingFile.stage === 'metadata'- ? '提取元数据'- : uploadingFile.stage === 'thumbnail'- ? '生成缩略图'- : uploadingFile.stage === 'exif'- ? '处理EXIF信息'- : uploadingFile.stage === 'reverse-geocoding'- ? '地理位置解析'- : uploadingFile.stage === 'live-photo'- ? '处理LivePhoto'- : '等待处理...'- }}- </span>- </div>- <UProgress- :model-value="uploadingFile.stage ? undefined : null"- animation="carousel"- class="h-2"- />- </div>-- <!-- 错误信息 -->- <UAlert- v-if="uploadingFile.status === 'error' && uploadingFile.error"- :description="uploadingFile.error"- color="error"- variant="soft"- class="mt-2"- />- </div>- </div>- </div>+ <!-- 上传队列容器 - 使用新的浮动组件 -->+ <UploadQueueContainer+ :uploading-files="uploadingFiles"+ @remove-file="removeUploadingFile"+ @clear-completed="clearCompletedUploads"+ @clear-all="clearAllUploads"+ /><!-- 文件上传组件 --><div class="relative">