From 2d349d1d737213529d0e1a13a345ad5d178a9c7b Mon Sep 17 00:00:00 2001 From: Chen Date: Sat, 6 Dec 2025 19:57:39 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E7=9A=84=E6=97=B6=E5=80=99=E5=90=8C=E6=97=B6?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E7=BC=A9=E7=95=A5=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/server.js | 7 +- backend/src/services/FileService.js | 25 ++++- backend/test-thumbnail-cleanup.js | 152 ++++++++++++++++++++++++++ frontend/src/components/Dashboard.jsx | 68 ++++-------- 4 files changed, 203 insertions(+), 49 deletions(-) create mode 100644 backend/test-thumbnail-cleanup.js diff --git a/backend/server.js b/backend/server.js index 3a18d39..ebcbf6d 100644 --- a/backend/server.js +++ b/backend/server.js @@ -125,8 +125,11 @@ server.listen(PORT, () => { for (const library of currentConfig.libraries) { try { const result = await fileService.cleanExpiredTempFiles(library.id); - if (result.cleaned > 0) { - console.log(`🧹 清理了 ${result.cleaned} 个过期临时文件`); + if (result.cleaned > 0 || result.thumbnailsCleaned > 0) { + const parts = []; + if (result.cleaned > 0) parts.push(`${result.cleaned} 个过期文件`); + if (result.thumbnailsCleaned > 0) parts.push(`${result.thumbnailsCleaned} 个缩略图`); + console.log(`🧹 已清理: ${parts.join('、')}`); } } catch (error) { // 忽略错误 diff --git a/backend/src/services/FileService.js b/backend/src/services/FileService.js index 49851c1..fc65e08 100644 --- a/backend/src/services/FileService.js +++ b/backend/src/services/FileService.js @@ -172,13 +172,14 @@ class FileService { const backupDir = path.join(libraryPath, TEMP_BACKUP_DIR); if (!fs.existsSync(backupDir)) { - return { cleaned: 0, failed: 0 }; + return { cleaned: 0, failed: 0, thumbnailsCleaned: 0 }; } const FIVE_MINUTES = 5 * 60 * 1000; // 5分钟 const now = Date.now(); let cleaned = 0; let failed = 0; + let thumbnailsCleaned = 0; // 统计清理的缩略图数量 // 递归扫描备份目录 const scanDir = async (dir) => { @@ -201,6 +202,26 @@ class FileService { // 超过5分钟,移入系统回收站 if (age > FIVE_MINUTES) { try { + // 1. 清理缩略图(在移入回收站前) + if (meta.imageRecords) { + const records = Array.isArray(meta.imageRecords) ? meta.imageRecords : [meta.imageRecords]; + for (const record of records) { + if (record.thumbnail_path) { + try { + const thumbnailFullPath = path.join(libraryPath, record.thumbnail_path); + if (fs.existsSync(thumbnailFullPath)) { + fs.unlinkSync(thumbnailFullPath); + thumbnailsCleaned++; + console.log(`🧹 已清理缩略图: ${record.thumbnail_path}`); + } + } catch (thumbError) { + console.warn(`清理缩略图失败 ${record.thumbnail_path}:`, thumbError.message); + } + } + } + } + + // 2. 移入系统回收站 // trash v8 是 ESM 模块,需要使用动态 import const { default: trash } = await import('trash'); await trash([fullPath]); @@ -297,7 +318,7 @@ class FileService { console.warn('[cleanExpiredTempFiles] 清理空文件夹时出错:', error.message); } - return { cleaned, failed }; + return { cleaned, failed, thumbnailsCleaned }; } /** diff --git a/backend/test-thumbnail-cleanup.js b/backend/test-thumbnail-cleanup.js new file mode 100644 index 0000000..65413c0 --- /dev/null +++ b/backend/test-thumbnail-cleanup.js @@ -0,0 +1,152 @@ +/** + * 测试缩略图清理功能 + * + * 测试流程: + * 1. 创建测试图片 + * 2. 扫描生成缩略图 + * 3. 删除图片(移到临时文件夹) + * 4. 模拟5分钟后的清理(修改删除时间) + * 5. 执行清理任务 + * 6. 验证缩略图是否被删除 + */ + +const fs = require('fs'); +const path = require('path'); +const config = require('./utils/config'); +const dbPool = require('./database/dbPool'); // 使用单例实例,不是类 + +async function testThumbnailCleanup() { + console.log('🧪 开始测试缩略图清理功能\n'); + + // 1. 加载配置 + const currentConfig = config.loadConfig(); + if (!currentConfig.libraries || currentConfig.libraries.length === 0) { + console.error('❌ 没有找到素材库,请先添加素材库'); + return; + } + + const library = currentConfig.libraries[0]; + console.log('📋 Library 对象:', JSON.stringify(library, null, 2)); + console.log(`📁 使用素材库: ${library.name} (${library.path})\n`); + + // 2. 确保素材库路径存在 + console.log(`🔍 检查路径: ${library.path}`); + if (!fs.existsSync(library.path)) { + console.error(`❌ 素材库路径不存在: ${library.path}`); + return; + } + + // 3. 获取数据库连接 + console.log('🔌 获取数据库连接...'); + const db = dbPool.acquire(library.path); + console.log('✅ 数据库连接成功'); + + // 4. 查找一个有缩略图的图片 + const stmt = db.db.prepare('SELECT * FROM images WHERE thumbnail_path IS NOT NULL LIMIT 1'); + const testImage = stmt.get(); + + if (!testImage) { + console.error('❌ 没有找到带缩略图的图片'); + dbPool.closeAll(); + return; + } + + console.log(`🖼️ 测试图片: ${testImage.filename}`); + console.log(`📸 缩略图路径: ${testImage.thumbnail_path}`); + + const thumbnailFullPath = path.join(library.path, testImage.thumbnail_path); + console.log(`📍 缩略图完整路径: ${thumbnailFullPath}`); + + // 5. 检查缩略图是否存在 + if (!fs.existsSync(thumbnailFullPath)) { + console.error('❌ 缩略图文件不存在'); + dbPool.closeAll(); + return; + } + console.log('✅ 缩略图文件存在\n'); + + // 6. 模拟删除(创建临时备份) + const backupDir = path.join(library.path, '.flypic/temp_backup'); + if (!fs.existsSync(backupDir)) { + fs.mkdirSync(backupDir, { recursive: true }); + } + + const backupPath = path.join(backupDir, testImage.path); + const backupParentDir = path.dirname(backupPath); + if (!fs.existsSync(backupParentDir)) { + fs.mkdirSync(backupParentDir, { recursive: true }); + } + + const originalPath = path.join(library.path, testImage.path); + + // 复制文件到备份目录(不删除原文件,避免影响实际数据) + console.log('📦 创建测试备份...'); + fs.copyFileSync(originalPath, backupPath); + + // 7. 创建 meta 文件(模拟删除时的记录) + const metaPath = backupPath + '.meta.json'; + const metaContent = { + originalPath: testImage.path, + deletedAt: Date.now() - (6 * 60 * 1000), // 模拟6分钟前删除(超过5分钟) + type: 'file', + imageRecords: { + path: testImage.path, + filename: testImage.filename, + folder: testImage.folder, + size: testImage.size, + width: testImage.width, + height: testImage.height, + format: testImage.format, + file_type: testImage.file_type, + created_at: testImage.created_at, + modified_at: testImage.modified_at, + file_hash: testImage.file_hash, + thumbnail_path: testImage.thumbnail_path, + thumbnail_size: testImage.thumbnail_size + } + }; + + fs.writeFileSync(metaPath, JSON.stringify(metaContent, null, 2)); + console.log('✅ 创建 meta 文件\n'); + + // 8. 执行清理(导入 FileService) + const FileService = require('./src/services/FileService'); + + // 创建 configManager 包装器(与 server.js 相同) + const configManager = { + load: () => config.loadConfig(), + save: (data) => config.saveConfig(data) + }; + + const fileService = new FileService(dbPool, configManager); + + console.log('🧹 执行清理任务...'); + const result = await fileService.cleanExpiredTempFiles(library.id); + + console.log('\n📊 清理结果:'); + console.log(` - 清理文件数: ${result.cleaned}`); + console.log(` - 清理缩略图数: ${result.thumbnailsCleaned}`); + console.log(` - 失败数: ${result.failed}`); + + // 9. 验证缩略图是否被删除 + console.log('\n🔍 验证结果:'); + if (!fs.existsSync(thumbnailFullPath)) { + console.log('✅ 缩略图已被成功清理!'); + } else { + console.log('❌ 缩略图仍然存在(清理失败)'); + } + + // 10. 清理测试数据(从系统回收站恢复文件) + console.log('\n🧹 清理测试数据...'); + // 注意:文件已被移入系统回收站,需要手动从回收站恢复 + console.log('⚠️ 测试文件已移入系统回收站,请手动从回收站恢复'); + + dbPool.closeAll(); + console.log('\n✅ 测试完成'); +} + +// 运行测试 +testThumbnailCleanup().catch(error => { + console.error('❌ 测试失败:', error); + process.exit(1); +}); diff --git a/frontend/src/components/Dashboard.jsx b/frontend/src/components/Dashboard.jsx index 7026fb2..f645b68 100644 --- a/frontend/src/components/Dashboard.jsx +++ b/frontend/src/components/Dashboard.jsx @@ -8,14 +8,9 @@ function Dashboard() { const { totalImageCount, totalSize, folders } = useImageStore(); const currentLibrary = getCurrentLibrary(); - - // Calculate stats const folderCount = folders.length; - - // Group folders by parent to find top-level folders const topLevelFolders = folders.filter(f => !f.parentPath || f.parentPath === '.' || f.parentPath === ''); - // Format bytes to human readable format const formatBytes = (bytes) => { if (bytes === 0) return '0 B'; const k = 1024; @@ -25,102 +20,85 @@ function Dashboard() { }; return ( -
+
-

+

{currentLibrary?.name || '素材库'}

{currentLibrary?.path && ( -

- {currentLibrary.path} -

+

{currentLibrary.path}

)}
- {/* Stats Cards */}
-
+
-
+
-
- {totalImageCount.toLocaleString()} -
-
总图片数
+
{totalImageCount.toLocaleString()}
+
图片总数
-
+
-
+
-
- {folderCount.toLocaleString()} -
-
文件夹
+
{folderCount.toLocaleString()}
+
文件夹数
-
+
-
+
-
- {formatBytes(totalSize)} -
-
素材库大小
+
{formatBytes(totalSize)}
+
总大小
- {/* Top Level Folders Preview */} {topLevelFolders.length > 0 && (
-

- 根目录文件夹 -

+

根目录文件夹

{topLevelFolders.map(folder => (
useImageStore.getState().setSelectedFolder(folder.path)} >
-
+
{folder.name}
-
- {folder.imageCount || 0} 张图片 -
+
{folder.imageCount || 0} 张图片
))}
)} - {/* Empty State */} {topLevelFolders.length === 0 && ( -
- -

- 暂无文件夹 -

-

+

+ +

暂无文件夹

+

您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。