优化 删除文件的时候同时删除缩略图

This commit is contained in:
Chen committed 2025-12-06 19:57:39 +08:00
1 parent 3787b15814
commit 2d349d1d73
4 files changed
+203 -49

No files matched your search

+5 -2
View File
@@ -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) {
// 忽略错误
+23 -2
View File
@@ -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 };
}
/**
+152
View File
@@ -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);
});
+23 -45
View File
@@ -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 (
<div className="flex-1 h-full overflow-y-auto bg-gray-50 dark:bg-gray-900 p-8">
<div className="flex-1 h-full overflow-y-auto bg-primary p-8">
<div className="max-w-4xl mx-auto">
<div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
<h1 className="text-3xl font-bold text-primary mb-2">
{currentLibrary?.name || '素材库'}
</h1>
{currentLibrary?.path && (
<p className="text-sm text-gray-500 dark:text-gray-400">
{currentLibrary.path}
</p>
<p className="text-sm text-tertiary">{currentLibrary.path}</p>
)}
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
<div className="flex items-center gap-4">
<div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400">
<div className="p-3 bg-blue-100 rounded-lg text-accent">
<ImageIcon className="w-6 h-6" />
</div>
<div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{totalImageCount.toLocaleString()}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">总图片数</div>
<div className="text-2xl font-bold text-primary">{totalImageCount.toLocaleString()}</div>
<div className="text-sm text-tertiary">图片总数</div>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
<div className="flex items-center gap-4">
<div className="p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-indigo-600 dark:text-indigo-400">
<div className="p-3 bg-indigo-100 rounded-lg text-indigo-600">
<Folder className="w-6 h-6" />
</div>
<div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{folderCount.toLocaleString()}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">文件夹</div>
<div className="text-2xl font-bold text-primary">{folderCount.toLocaleString()}</div>
<div className="text-sm text-tertiary">文件夹数</div>
</div>
</div>
</div>
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
<div className="flex items-center gap-4">
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg text-purple-600 dark:text-purple-400">
<div className="p-3 bg-purple-100 rounded-lg text-purple-600">
<HardDrive className="w-6 h-6" />
</div>
<div>
<div className="text-2xl font-bold text-gray-900 dark:text-white">
{formatBytes(totalSize)}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">素材库大小</div>
<div className="text-2xl font-bold text-primary">{formatBytes(totalSize)}</div>
<div className="text-sm text-tertiary">总大小</div>
</div>
</div>
</div>
</div>
{/* Top Level Folders Preview */}
{topLevelFolders.length > 0 && (
<div>
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
根目录文件夹
</h2>
<h2 className="text-xl font-semibold text-primary mb-4">根目录文件夹</h2>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{topLevelFolders.map(folder => (
<div
key={folder.path}
className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer group"
className="bg-secondary rounded-lg p-4 shadow-sm border hover:shadow-md transition-shadow cursor-pointer group"
onClick={() => useImageStore.getState().setSelectedFolder(folder.path)}
>
<div className="flex items-center gap-3 mb-2">
<Folder className="w-8 h-8 text-yellow-500 group-hover:text-yellow-400 transition-colors" />
<div className="flex-1 min-w-0">
<div className="font-medium text-gray-900 dark:text-white truncate" title={folder.name}>
<div className="font-medium text-primary truncate" title={folder.name}>
{folder.name}
</div>
</div>
</div>
<div className="text-xs text-gray-500 dark:text-gray-400">
{folder.imageCount || 0} 张图片
</div>
<div className="text-xs text-tertiary">{folder.imageCount || 0} 张图片</div>
</div>
))}
</div>
</div>
)}
{/* Empty State */}
{topLevelFolders.length === 0 && (
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-dashed border-gray-300 dark:border-gray-700">
<Folder className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
暂无文件夹
</h3>
<p className="text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
<div className="text-center py-12 bg-secondary rounded-xl border border-dashed">
<Folder className="w-12 h-12 text-secondary mx-auto mb-4" />
<h3 className="text-lg font-medium text-primary mb-2">暂无文件夹</h3>
<p className="text-tertiary max-w-sm mx-auto">
您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。
</p>
</div>