Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
refactor(pipeline-async): 使用新的安全照片ID生成函数,优化照片处理管道
Timothy Yin682079c0c472
diff --git a/eslint.config.mjs b/eslint.config.mjsindex d9c4ef49..9b451f6b 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -12,6 +12,7 @@ export default withNuxt({'@stylistic/operator-linebreak': 'off','@typescript-eslint/no-empty-object-type': 'off','@typescript-eslint/no-explicit-any': 'off',+ 'vue/multi-word-component-names': 'off',},plugins: {prettier,diff --git a/server/services/photo/pipeline-async.ts b/server/services/photo/pipeline-async.tsindex a5e9348c..05fb7366 100644--- a/server/services/photo/pipeline-async.ts+++ b/server/services/photo/pipeline-async.ts@@ -1,4 +1,3 @@-import path from 'path'import {preprocessImageWithJpegUpload,processImageMetadataAndSharp,@@ -14,10 +13,7 @@ import {parseGPSCoordinates,} from '../location/geocoding'import { findLivePhotoVideoForImage } from '../video/livephoto'--const generatePhotoId = (s3key: string) => {- return path.basename(s3key, path.extname(s3key)).replace(/ /g, '_')-}+import { generateSafePhotoId } from '~~/server/utils/file-utils'/*** 异步执行照片处理管道 - 不阻塞主线程@@ -48,12 +44,12 @@ async function processPhotoInternal(): Promise<Photo | null> {const log = logger.imageconst storageProvider = getStorageManager().getProvider()- const photoId = generatePhotoId(s3key)+ const photoId = generateSafePhotoId(s3key)try {log.info(`Starting async processing for ${s3key}`)- // 使用 Promise 包装每个步骤,确保异步执行+ // 步骤1: 预处理图片并上传JPEG版本const imageBuffers = await new Promise<any>((resolve, reject) => {setImmediate(async () => {try {@@ -70,6 +66,7 @@ async function processPhotoInternal(return null}+ // 步骤2: 处理图片元数据和Sharp处理const processedData = await new Promise<any>((resolve, reject) => {setImmediate(async () => {try {@@ -91,6 +88,7 @@ async function processPhotoInternal(const { imageBuffer, metadata } = processedData+ // 步骤3: 生成缩略图和哈希值const { thumbnailBuffer, thumbnailHash } = await new Promise<any>((resolve, reject) => {setImmediate(async () => {@@ -104,6 +102,19 @@ async function processPhotoInternal(},)+ // TODO 步骤4: 直方图和影调分析+ // const histogramData = await new Promise<any>((resolve, reject) => {+ // setImmediate(async () => {+ // try {+ // const result = await calculateHistogram(processedData.sharpInst)+ // resolve(result)+ // } catch (error) {+ // reject(error)+ // }+ // })+ // })++ // 步骤5: 提取EXIF数据const exifData = await new Promise<any>((resolve, reject) => {setImmediate(async () => {try {@@ -119,9 +130,10 @@ async function processPhotoInternal(})})+ // 步骤6: 提取照片基本信息const photoInfo = extractPhotoInfo(s3key, exifData)- // 处理地理位置信息+ // 步骤7: 处理地理位置信息let locationInfo = nullif (exifData) {const { latitude, longitude } = parseGPSCoordinates(exifData)@@ -139,7 +151,7 @@ async function processPhotoInternal(}}- // 检查是否有对应的 LivePhoto 视频文件+ // 步骤8: 配对 LivePhoto 视频文件let livePhotoInfo = nullconst livePhotoVideo = await new Promise<any>((resolve, reject) => {setImmediate(async () => {@@ -163,6 +175,7 @@ async function processPhotoInternal(log.info(`LivePhoto video found for ${s3key}: ${livePhotoVideo.videoKey}`)}+ // 步骤9: 上传缩略图到存储服务const thumbnailObject = await new Promise<any>((resolve, reject) => {setImmediate(async () => {try {@@ -178,6 +191,7 @@ async function processPhotoInternal(})})+ // 步骤10: 构建最终的Photo对象const result: Photo = {id: photoId,title: photoInfo.title,diff --git a/server/services/photo/pipeline.ts b/server/services/photo/pipeline.tsdeleted file mode 100644index 49baa96b..00000000--- a/server/services/photo/pipeline.ts+++ /dev/null@@ -1,105 +0,0 @@-import path from 'path'-import {- preprocessImageWithJpegUpload,- processImageMetadataAndSharp,-} from '../image/processor'-import { generateThumbnailAndHash } from '../image/thumbnail'-import type { Photo } from '~~/server/utils/db'-import { getStorageManager } from '~~/server/plugins/storage'-import { compressUint8Array } from '~~/shared/utils/u8array'-import type { StorageObject } from '../storage'-import { extractExifData, extractPhotoInfo } from '../image/exif'-import { findLivePhotoVideoForImage } from '../video/livephoto'--const generatePhotoId = (s3key: string) => {- return path.basename(s3key, path.extname(s3key))-}--export const execPhotoPipeline = async (- s3key: string,- storageObject: StorageObject,-): Promise<Photo | null> => {- const log = logger.image- const storageProvider = getStorageManager().getProvider()- const photoId = generatePhotoId(s3key)-- try {- // 1. 预处理图片,分离原始 Buffer 和 HEIC 转换- const imageBuffers = await preprocessImageWithJpegUpload(s3key)- if (!imageBuffers) return null-- // 2. 转换 BMP 格式,返回 Sharp 实例- const processedData = await processImageMetadataAndSharp(- imageBuffers.processed,- s3key,- )- if (!processedData) return null- const { imageBuffer, metadata } = processedData-- // 3. 生成缩略图和 BlurHash- const { thumbnailBuffer, thumbnailHash } =- await generateThumbnailAndHash(imageBuffer)-- // 4. EXIF- const exifData = await extractExifData(imageBuffer, imageBuffers.raw, log)-- // 5. 提取照片信息- const photoInfo = extractPhotoInfo(s3key, exifData)-- // 6. 检查是否有对应的 LivePhoto 视频文件- const livePhotoVideo = await findLivePhotoVideoForImage(s3key)- let livePhotoInfo = null-- if (livePhotoVideo) {- livePhotoInfo = {- isLivePhoto: 1,- livePhotoVideoUrl: storageProvider.getPublicUrl(- livePhotoVideo.videoKey,- ),- livePhotoVideoKey: livePhotoVideo.videoKey,- }- log.info(`LivePhoto video found for ${s3key}: ${livePhotoVideo.videoKey}`)- }-- // 7. 上传缩略图- const thumbnailObject = await storageProvider.create(- `thumbnails/${photoId}.webp`,- thumbnailBuffer,- 'image/webp',- )-- return {- id: photoId,- title: photoInfo.title,- description: photoInfo.description,- dateTaken: photoInfo.dateTaken,- tags: photoInfo.tags,- width: metadata.width,- height: metadata.height,- aspectRatio: metadata.width / metadata.height,- storageKey: s3key,- fileSize: storageObject.size || null,- lastModified:- storageObject.lastModified?.toISOString() || new Date().toISOString(),- originalUrl: imageBuffers.jpegKey- ? storageProvider.getPublicUrl(imageBuffers.jpegKey) // 使用 JPEG 版本作为 originalUrl- : storageProvider.getPublicUrl(s3key),- thumbnailUrl: storageProvider.getPublicUrl(thumbnailObject.key),- thumbnailHash: thumbnailHash ? compressUint8Array(thumbnailHash) : null,- exif: exifData,- // 地理位置信息- latitude: null,- longitude: null,- country: null,- city: null,- locationName: null,- // LivePhoto 相关字段- isLivePhoto: livePhotoInfo?.isLivePhoto || 0,- livePhotoVideoUrl: livePhotoInfo?.livePhotoVideoUrl || null,- livePhotoVideoKey: livePhotoInfo?.livePhotoVideoKey || null,- }- } catch (err) {- log.error(`Photo pipeline failed for ${s3key}`, err)- return null- }-}diff --git a/server/utils/file-utils.ts b/server/utils/file-utils.tsnew file mode 100644index 00000000..9699ca51--- /dev/null+++ b/server/utils/file-utils.ts@@ -0,0 +1,81 @@+import crypto from 'crypto'+import path from 'path'++/**+ * 清理文件名,移除或替换特殊字符+ * @param fileName 原始文件名+ * @param options 清理选项+ * @returns 清理后的文件名+ */+export const sanitizeFileName = (+ fileName: string,+ options: {+ maxLength?: number+ fallbackPrefix?: string+ minLength?: number+ } = {}+): string => {+ const {+ maxLength = 50,+ fallbackPrefix = 'file',+ minLength = 3+ } = options++ // 清理文件名:保留字母、数字、连字符、下划线、点号+ const cleanedName = fileName+ .replace(/[^\w\-_.]/g, '_') // 将非字母数字字符替换为下划线+ .replace(/_{2,}/g, '_') // 将多个连续下划线替换为单个下划线+ .replace(/^_+|_+$/g, '') // 移除开头和结尾的下划线++ // 如果清理后的名称太短或为空,使用后备方案+ if (cleanedName.length < minLength) {+ const hash = crypto.createHash('md5').update(fileName).digest('hex')+ return `${fallbackPrefix}_${hash.substring(0, 8)}`+ }++ // 如果清理后的名称太长,截断并添加哈希后缀以避免冲突+ if (cleanedName.length > maxLength) {+ const hash = crypto.createHash('md5').update(fileName).digest('hex')+ const truncateLength = maxLength - 9 // 为哈希和下划线预留空间+ return `${cleanedName.substring(0, truncateLength)}_${hash.substring(0, 8)}`+ }++ return cleanedName+}++/**+ * 生成安全的照片ID+ * @param s3key 存储键+ * @returns 安全的照片ID+ */+export const generateSafePhotoId = (s3key: string): string => {+ const baseName = path.basename(s3key, path.extname(s3key))+ return sanitizeFileName(baseName, {+ maxLength: 32,+ fallbackPrefix: 'photo',+ minLength: 3+ })+}++/**+ * 生成安全的文件键+ * @param s3key 原始存储键+ * @param newExtension 新的文件扩展名(包含点号,如 '.jpeg')+ * @returns 安全的文件键+ */+export const generateSafeFileKey = (s3key: string, newExtension: string): string => {+ const baseName = path.basename(s3key, path.extname(s3key))+ const dirName = path.dirname(s3key)+ const safeName = sanitizeFileName(baseName, {+ maxLength: 100,+ fallbackPrefix: 'file',+ minLength: 1+ })++ // 如果原路径有目录结构,保持目录结构+ if (dirName === '.' || dirName === '') {+ return `${safeName}${newExtension}`+ }++ return `${dirName}/${safeName}${newExtension}`+}