优化 素材库新增处理优化,提速,其余bug处理
This commit is contained in:
1 parent
ad774d8a22
commit
4bce6f5d72
67 files changed
+4861
-3111
No files matched your search
+27
-10
@@ -19,19 +19,23 @@ class LibraryDatabase {
|
||||
|
||||
this.db = new Database(this.dbPath);
|
||||
|
||||
// 超激进内存优化配置
|
||||
// 使用 DELETE 模式而非 WAL(WAL 可能导致内存泄漏)
|
||||
this.db.pragma('journal_mode = DELETE'); // 使用 DELETE 模式(更低内存)
|
||||
// 优化数据库性能
|
||||
this.db.pragma('journal_mode = WAL'); // 启用 WAL 模式,支持并发读写
|
||||
this.db.pragma('synchronous = NORMAL'); // 平衡性能和安全性
|
||||
this.db.pragma('cache_size = -4096'); // 4MB 缓存(超激进:从8MB降至4MB)
|
||||
this.db.pragma('temp_store = FILE'); // 临时表存储在磁盘
|
||||
this.db.pragma('mmap_size = 0'); // 禁用内存映射
|
||||
this.db.pragma('page_size = 4096'); // 4KB 页面大小(减少内存占用)
|
||||
|
||||
console.log('[LibraryDatabase] Ultra-aggressive memory optimization applied:');
|
||||
console.log(' cache_size: 4MB, temp_store: FILE, mmap_size: 0, page_size: 4KB');
|
||||
this.db.pragma('cache_size = -64000'); // 64MB 缓存
|
||||
this.db.pragma('temp_store = MEMORY'); // 临时表存储在内存
|
||||
this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射
|
||||
|
||||
this.initTables();
|
||||
|
||||
// 启动 WAL 定期 checkpoint(每 5 分钟)
|
||||
this.walCheckpointInterval = setInterval(() => {
|
||||
try {
|
||||
this.db.pragma('wal_checkpoint(PASSIVE)');
|
||||
} catch (e) {
|
||||
console.warn('[DB] WAL checkpoint warning:', e.message);
|
||||
}
|
||||
}, 300000); // 5 分钟
|
||||
}
|
||||
|
||||
initTables() {
|
||||
@@ -400,6 +404,19 @@ class LibraryDatabase {
|
||||
}
|
||||
|
||||
close() {
|
||||
// 清理 WAL checkpoint 定时器
|
||||
if (this.walCheckpointInterval) {
|
||||
clearInterval(this.walCheckpointInterval);
|
||||
this.walCheckpointInterval = null;
|
||||
}
|
||||
|
||||
// 执行最后一次 checkpoint
|
||||
try {
|
||||
this.db.pragma('wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {
|
||||
console.warn('[DB] Final WAL checkpoint warning:', e.message);
|
||||
}
|
||||
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
+33
-44
@@ -6,9 +6,14 @@ const LibraryDatabase = require('./db');
|
||||
*/
|
||||
class DatabasePool {
|
||||
constructor() {
|
||||
// 单例模式:确保只有一个实例,避免多个定时器
|
||||
if (DatabasePool.instance) {
|
||||
return DatabasePool.instance;
|
||||
}
|
||||
DatabasePool.instance = this;
|
||||
|
||||
this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount }
|
||||
this.maxConnections = 1; // 最大连接数:1
|
||||
this.maxIdleTime = 60000; // 60秒未使用则关闭(保持连接复用,减少创建/关闭)
|
||||
this.maxIdleTime = 60000; // 60秒未使用则关闭
|
||||
this.cleanupInterval = null;
|
||||
|
||||
// 启动定期清理
|
||||
@@ -23,16 +28,6 @@ class DatabasePool {
|
||||
let conn = this.connections.get(libraryPath);
|
||||
|
||||
if (!conn) {
|
||||
// 强制执行最大连接数限制:如果已有连接,先关闭所有空闲连接
|
||||
if (this.connections.size >= this.maxConnections) {
|
||||
for (const [path, existingConn] of this.connections.entries()) {
|
||||
if (existingConn.refCount === 0) {
|
||||
console.log(`[DBPool] Max connections reached, closing idle: ${path}`);
|
||||
this.close(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新连接
|
||||
const db = new LibraryDatabase(libraryPath);
|
||||
conn = {
|
||||
@@ -41,7 +36,6 @@ class DatabasePool {
|
||||
refCount: 0
|
||||
};
|
||||
this.connections.set(libraryPath, conn);
|
||||
console.log(`[DBPool] Created new connection for: ${libraryPath} (total: ${this.connections.size}/${this.maxConnections})`);
|
||||
}
|
||||
|
||||
// 更新使用时间和引用计数
|
||||
@@ -72,17 +66,19 @@ class DatabasePool {
|
||||
// 强制设置引用计数为0
|
||||
conn.refCount = 0;
|
||||
|
||||
// 关闭数据库连接
|
||||
// 执行 checkpoint 确保 WAL 写入主数据库
|
||||
if (conn.db && conn.db.db) {
|
||||
// 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint
|
||||
// 直接关闭连接即可
|
||||
conn.db.close();
|
||||
try {
|
||||
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {
|
||||
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
|
||||
}
|
||||
}
|
||||
conn.db.close();
|
||||
|
||||
this.connections.delete(libraryPath);
|
||||
console.log(`[DBPool] Closed connection for: ${libraryPath}`);
|
||||
} catch (error) {
|
||||
console.error(`[DBPool] Error closing connection:`, error);
|
||||
console.error(`❌ 关闭数据库连接失败:`, error.message);
|
||||
// 即使出错也删除引用
|
||||
this.connections.delete(libraryPath);
|
||||
}
|
||||
@@ -93,27 +89,28 @@ class DatabasePool {
|
||||
* 关闭所有连接
|
||||
*/
|
||||
closeAll() {
|
||||
console.log(`[DBPool] Closing all connections (${this.connections.size} total)`);
|
||||
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
try {
|
||||
// 强制设置引用计数为0
|
||||
conn.refCount = 0;
|
||||
|
||||
// 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint
|
||||
// 直接关闭连接即可
|
||||
conn.db.close();
|
||||
console.log(`[DBPool] Closed connection for: ${path}`);
|
||||
} catch (error) {
|
||||
console.error(`[DBPool] Error closing connection for ${path}:`, error);
|
||||
}
|
||||
}
|
||||
this.connections.clear();
|
||||
|
||||
// 先清理定时器,避免在关闭过程中触发清理
|
||||
if (this.cleanupInterval) {
|
||||
clearInterval(this.cleanupInterval);
|
||||
this.cleanupInterval = null;
|
||||
}
|
||||
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
try {
|
||||
// 执行 checkpoint 确保 WAL 写入主数据库
|
||||
if (conn.db && conn.db.db) {
|
||||
try {
|
||||
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {
|
||||
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
|
||||
}
|
||||
}
|
||||
conn.db.close();
|
||||
} catch (error) {
|
||||
console.error(`❌ 关闭数据库连接失败:`, error.message);
|
||||
}
|
||||
}
|
||||
this.connections.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,7 +118,6 @@ class DatabasePool {
|
||||
* 与 closeAll() 相同,但提供明确的语义
|
||||
*/
|
||||
forceCloseAll() {
|
||||
console.log('[DBPool] Force closing all connections (emergency cleanup)');
|
||||
this.closeAll();
|
||||
}
|
||||
|
||||
@@ -144,14 +140,11 @@ class DatabasePool {
|
||||
toClose.forEach(path => this.close(path));
|
||||
|
||||
if (toClose.length > 0) {
|
||||
console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`);
|
||||
|
||||
// 关闭连接后立即强制 GC
|
||||
if (global.gc) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
global.gc();
|
||||
}
|
||||
console.log(`[DBPool] Forced GC after closing connections`);
|
||||
}
|
||||
}
|
||||
}, 10000); // 每10秒检查一次(更频繁)
|
||||
@@ -191,10 +184,6 @@ class DatabasePool {
|
||||
}
|
||||
|
||||
toClose.forEach(path => this.close(path));
|
||||
|
||||
if (toClose.length > 0) {
|
||||
console.log(`[DBPool] Cleared ${toClose.length} idle connections`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
"description": "FlyPic backend server",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"dev": "cross-env PORT=15002 nodemon server.js",
|
||||
"start": "node server.js"
|
||||
"dev": "cross-env PORT=15002 nodemon --expose-gc server.js",
|
||||
"start": "node --expose-gc server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^9.2.2",
|
||||
|
||||
+90
-25
@@ -35,13 +35,13 @@ if (!FRONTEND_DIST) {
|
||||
for (const p of possiblePaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
FRONTEND_DIST = p;
|
||||
console.log('✅ Found frontend at:', p);
|
||||
console.log('✅ 前端目录:', p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!FRONTEND_DIST) {
|
||||
console.log('⚠️ Frontend not found, API-only mode');
|
||||
console.log('⚠️ 未找到前端,API模式');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,15 +89,18 @@ server.on('request', app);
|
||||
|
||||
// Socket.IO 连接处理
|
||||
io.on('connection', (socket) => {
|
||||
console.log('✅ Socket.IO client connected:', socket.id);
|
||||
console.log('✅ 客户端连接:', socket.id);
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('❌ Socket.IO client disconnected:', socket.id);
|
||||
console.log('❌ 客户端断开:', socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
// 启动内存监控
|
||||
const memoryMonitor = new MemoryMonitor();
|
||||
// 启动内存监控(开发模式:每30秒输出RSS)
|
||||
const memoryMonitor = new MemoryMonitor({
|
||||
devMode: true,
|
||||
devLogInterval: 30000 // 30秒
|
||||
});
|
||||
memoryMonitor.start();
|
||||
|
||||
// 启动清理管理器
|
||||
@@ -106,36 +109,95 @@ cleanupManager.startRoutineCleanup();
|
||||
|
||||
// 启动服务器
|
||||
server.listen(PORT, () => {
|
||||
console.log('\n🚀 FlyPic Server (New Architecture) Started');
|
||||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
||||
console.log(`📡 Server running on http://localhost:${PORT}`);
|
||||
console.log(`🔌 Socket.IO ready`);
|
||||
console.log(`📁 Frontend: ${FRONTEND_DIST || 'Not found (API-only mode)'}`);
|
||||
console.log(`🏗️ Architecture: Config → Model → Service → Route`);
|
||||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
||||
|
||||
// 为当前素材库启动文件监控
|
||||
console.log('\n🚀 FlyPic 服务器已启动');
|
||||
console.log(`📡 端口: ${PORT}`);
|
||||
console.log(`🔌 Socket.IO 就绪`);
|
||||
if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`);
|
||||
console.log('');
|
||||
|
||||
try {
|
||||
const currentConfig = config.loadConfig();
|
||||
|
||||
// 恢复所有素材库的扫描状态
|
||||
if (currentConfig.libraries && currentConfig.libraries.length > 0) {
|
||||
scanManager.restoreAllStates(currentConfig.libraries);
|
||||
|
||||
// 检查是否有未完成的扫描,自动继续
|
||||
const activeStates = scanManager.getAllActiveStates();
|
||||
if (Object.keys(activeStates).length > 0) {
|
||||
console.log(`📊 发现 ${Object.keys(activeStates).length} 个活跃扫描`);
|
||||
}
|
||||
|
||||
for (const [libraryId, state] of Object.entries(activeStates)) {
|
||||
const lib = currentConfig.libraries.find(l => l.id === libraryId);
|
||||
if (lib && state.status === 'scanning') {
|
||||
console.log(`🔄 恢复扫描: ${lib.name} (${state.progress?.percent || 0}%)`);
|
||||
|
||||
// 立即恢复扫描状态(让前端能检测到)
|
||||
scanManager.scanStates.set(libraryId, {
|
||||
status: 'scanning',
|
||||
progress: state.progress || { current: 0, total: 0, percent: 0 },
|
||||
startTime: state.startTime || Date.now()
|
||||
});
|
||||
|
||||
// 立即向所有连接的客户端推送扫描状态
|
||||
io.emit('scanProgress', {
|
||||
libraryId,
|
||||
...state.progress,
|
||||
resuming: true
|
||||
});
|
||||
|
||||
// 延迟启动实际扫描,等服务完全准备好
|
||||
setTimeout(() => {
|
||||
const db = dbPool.acquire(lib.path);
|
||||
// 继续扫描(从中断处继续)
|
||||
scanner.scanLibrary(
|
||||
lib.path,
|
||||
db,
|
||||
(progress) => {
|
||||
io.emit('scanProgress', { libraryId, ...progress });
|
||||
},
|
||||
libraryId
|
||||
).then(() => {
|
||||
scanManager.completeScan(libraryId);
|
||||
io.emit('scanComplete', { libraryId });
|
||||
dbPool.release(lib.path);
|
||||
console.log(`✅ 扫描完成: ${lib.name}`);
|
||||
}).catch((err) => {
|
||||
console.error(`❌ 扫描失败: ${lib.name}`, err.message);
|
||||
scanManager.completeScan(libraryId);
|
||||
dbPool.release(lib.path);
|
||||
});
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 为当前素材库启动文件监控
|
||||
if (currentConfig.currentLibraryId) {
|
||||
const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId);
|
||||
if (currentLib) {
|
||||
lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io);
|
||||
console.log(`📂 File watcher started for: ${currentLib.name}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('⚠️ Failed to start file watcher:', e.message);
|
||||
console.warn('⚠️ 初始化失败:', e.message);
|
||||
}
|
||||
});
|
||||
|
||||
// 标记是否正在关闭
|
||||
let isShuttingDown = false;
|
||||
|
||||
// 优雅关闭
|
||||
const shutdown = async () => {
|
||||
console.log('\n🛑 Shutting down gracefully...');
|
||||
if (isShuttingDown) return;
|
||||
isShuttingDown = true;
|
||||
|
||||
console.log('\n🛑 正在关闭服务器...');
|
||||
|
||||
// 停止接受新连接
|
||||
server.close(() => {
|
||||
console.log('✅ HTTP server closed');
|
||||
console.log('✅ HTTP 服务器已关闭');
|
||||
});
|
||||
|
||||
// 停止监控
|
||||
@@ -145,27 +207,30 @@ const shutdown = async () => {
|
||||
// 停止所有文件监控
|
||||
lightweightWatcher.stopAll();
|
||||
|
||||
// 等待扫描任务完成当前批次(最多等2秒)
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
// 关闭所有数据库连接
|
||||
dbPool.closeAll();
|
||||
|
||||
// 等待资源释放
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
console.log('✅ Shutdown complete');
|
||||
console.log('✅ 关闭完成');
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
// 导出关闭状态供其他模块检查
|
||||
module.exports.isShuttingDown = () => isShuttingDown;
|
||||
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
|
||||
// 错误处理
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('💥 Uncaught Exception:', error);
|
||||
console.error('💥 未捕获异常:', error.message);
|
||||
shutdown();
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('💥 Unhandled Rejection at:', promise, 'reason:', reason);
|
||||
console.error('💥 未处理的Promise拒绝:', reason);
|
||||
shutdown();
|
||||
});
|
||||
|
||||
|
||||
@@ -103,52 +103,32 @@ router.get('/:id', asyncHandler(async (req, res) => {
|
||||
router.get('/thumbnail/:libraryId/:filename', (req, res) => {
|
||||
const { libraryId, filename } = req.params;
|
||||
|
||||
console.log(`[Thumbnail] ========== NEW REQUEST ==========`);
|
||||
console.log(`[Thumbnail] LibraryId: ${libraryId}, Filename: ${filename}`);
|
||||
|
||||
try {
|
||||
const config = require('../../utils/config').loadConfig();
|
||||
console.log(`[Thumbnail] All libraries:`, config.libraries.map(l => ({ id: l.id, type: typeof l.id })));
|
||||
|
||||
// 尝试两种方式查找:数字和字符串
|
||||
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
|
||||
if (!library) {
|
||||
library = config.libraries.find(lib => lib.id == libraryId); // 使用 == 宽松比较
|
||||
library = config.libraries.find(lib => lib.id == libraryId);
|
||||
}
|
||||
|
||||
if (!library) {
|
||||
console.log(`[Thumbnail] Library not found: ${libraryId} (type: ${typeof libraryId})`);
|
||||
return res.status(404).send('Library not found');
|
||||
}
|
||||
|
||||
console.log(`[Thumbnail] Library path: ${library.path}`);
|
||||
|
||||
// 使用分片结构:取文件名前2个字符作为分片目录
|
||||
const hash = filename.replace(/\.[^/.]+$/, ''); // 移除扩展名
|
||||
const hash = filename.replace(/\.[^/.]+$/, '');
|
||||
const shard = hash.slice(0, 2);
|
||||
const flypicPath = getFlypicPath(library.path);
|
||||
const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename);
|
||||
|
||||
console.log(`[Thumbnail] Hash: ${hash}, Shard: ${shard}`);
|
||||
console.log(`[Thumbnail] Full path: ${thumbnailPath}`);
|
||||
console.log(`[Thumbnail] File exists: ${fs.existsSync(thumbnailPath)}`);
|
||||
|
||||
if (!fs.existsSync(thumbnailPath)) {
|
||||
// 列出分片目录的内容
|
||||
const shardDir = path.join(flypicPath, 'thumbnails', shard);
|
||||
if (fs.existsSync(shardDir)) {
|
||||
const files = fs.readdirSync(shardDir);
|
||||
console.log(`[Thumbnail] Files in shard dir (${shard}):`, files.slice(0, 5));
|
||||
} else {
|
||||
console.log(`[Thumbnail] Shard directory does not exist: ${shardDir}`);
|
||||
}
|
||||
return res.status(404).send('Thumbnail not found');
|
||||
}
|
||||
|
||||
console.log(`[Thumbnail] ✅ Serving file`);
|
||||
res.sendFile(thumbnailPath);
|
||||
} catch (error) {
|
||||
console.error('[Thumbnail] Error:', error);
|
||||
console.error('❌ 缩略图错误:', error.message);
|
||||
res.status(500).send('Error serving thumbnail');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -46,34 +46,6 @@ router.post('/sync',
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
* POST /api/scan/stop
|
||||
* Body: { libraryId }
|
||||
*/
|
||||
router.post('/stop',
|
||||
validateRequired(['libraryId']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.body;
|
||||
const result = scanService.stopScan(libraryId);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 继续扫描
|
||||
* POST /api/scan/resume
|
||||
* Body: { libraryId }
|
||||
*/
|
||||
router.post('/resume',
|
||||
validateRequired(['libraryId']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.body;
|
||||
const result = scanService.resumeScan(libraryId);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取扫描状态
|
||||
* GET /api/scan/status/:libraryId
|
||||
@@ -84,6 +56,15 @@ router.get('/status/:libraryId', asyncHandler(async (req, res) => {
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取所有活跃的扫描状态
|
||||
* GET /api/scan/active-states
|
||||
*/
|
||||
router.get('/active-states', asyncHandler(async (req, res) => {
|
||||
const result = scanService.getAllActiveStates();
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 修复文件夹路径
|
||||
* POST /api/scan/fix-folders
|
||||
|
||||
@@ -39,23 +39,60 @@ class LibraryService {
|
||||
throw new ValidationError('Name and path are required');
|
||||
}
|
||||
|
||||
if (!fs.existsSync(libraryPath)) {
|
||||
// 规范化路径
|
||||
const normalizedPath = path.normalize(libraryPath);
|
||||
console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`);
|
||||
|
||||
if (!fs.existsSync(normalizedPath)) {
|
||||
console.log(`[LibraryService] Path does not exist: ${normalizedPath}`);
|
||||
throw new ValidationError('Path does not exist', 'path');
|
||||
}
|
||||
|
||||
// 检查文件夹访问权限
|
||||
try {
|
||||
// 尝试读取目录
|
||||
fs.readdirSync(normalizedPath);
|
||||
|
||||
// 尝试在目录中创建测试文件(检查写权限)
|
||||
const testFile = path.join(normalizedPath, '.flypic-test');
|
||||
try {
|
||||
fs.writeFileSync(testFile, 'test');
|
||||
fs.unlinkSync(testFile);
|
||||
} catch (writeError) {
|
||||
console.log(`[LibraryService] No write permission: ${normalizedPath}`);
|
||||
throw new ValidationError(
|
||||
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
|
||||
'permission'
|
||||
);
|
||||
}
|
||||
} catch (readError) {
|
||||
if (readError.code === 'EACCES' || readError.code === 'EPERM') {
|
||||
console.log(`[LibraryService] No access permission: ${normalizedPath}`);
|
||||
throw new ValidationError(
|
||||
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
|
||||
'permission'
|
||||
);
|
||||
}
|
||||
// 如果不是权限错误,继续抛出
|
||||
if (readError.name !== 'ValidationError') {
|
||||
throw readError;
|
||||
}
|
||||
throw readError;
|
||||
}
|
||||
|
||||
// 检查路径是否已存在
|
||||
const config = this.configManager.load();
|
||||
const existingLib = config.libraries.find(lib => lib.path === libraryPath);
|
||||
const existingLib = config.libraries.find(lib => lib.path === normalizedPath);
|
||||
if (existingLib) {
|
||||
throw new ValidationError('Library path already exists', 'path');
|
||||
}
|
||||
|
||||
// 创建素材库
|
||||
const id = this.configManager.addLibrary(name, libraryPath);
|
||||
const id = this.configManager.addLibrary(name, normalizedPath);
|
||||
|
||||
// 检查是否有现有索引
|
||||
const flypicDir = getFlypicPath(libraryPath);
|
||||
const dbPath = getDatabasePath(libraryPath);
|
||||
const flypicDir = getFlypicPath(normalizedPath);
|
||||
const dbPath = getDatabasePath(normalizedPath);
|
||||
const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* 扫描服务层
|
||||
* 封装扫描相关的业务逻辑
|
||||
* 扫描服务层(简化版)
|
||||
* 无暂停功能,只负责扫描和进度推送
|
||||
*/
|
||||
|
||||
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
|
||||
@@ -22,35 +22,21 @@ class ScanService {
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
// 检查是否已在扫描
|
||||
if (this.scanManager.isScanning(libraryId)) {
|
||||
throw new ValidationError('Scan already in progress', 'libraryId');
|
||||
}
|
||||
|
||||
// 开始扫描
|
||||
if (wait) {
|
||||
// 同步模式:等待扫描完成
|
||||
await this.scanner.scanLibrary(
|
||||
library.path,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan completed',
|
||||
(progress) => this._emitProgress(libraryId, progress),
|
||||
libraryId
|
||||
};
|
||||
);
|
||||
return { success: true, message: 'Scan completed', libraryId };
|
||||
} else {
|
||||
// 异步模式:后台扫描
|
||||
this._startAsyncScan(libraryId, library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan started',
|
||||
libraryId,
|
||||
async: true
|
||||
};
|
||||
return { success: true, message: 'Scan started', libraryId, async: true };
|
||||
}
|
||||
} catch (error) {
|
||||
this.dbPool.release(library.path);
|
||||
@@ -66,35 +52,21 @@ class ScanService {
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
// 检查是否已在扫描
|
||||
if (this.scanManager.isScanning(libraryId)) {
|
||||
throw new ValidationError('Scan already in progress', 'libraryId');
|
||||
}
|
||||
|
||||
// 开始增量同步
|
||||
if (wait) {
|
||||
// 同步模式
|
||||
await this.scanner.incrementalSync(
|
||||
await this.scanner.syncLibrary(
|
||||
library.path,
|
||||
db,
|
||||
false,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Sync completed',
|
||||
libraryId
|
||||
};
|
||||
return { success: true, message: 'Sync completed', libraryId };
|
||||
} else {
|
||||
// 异步模式
|
||||
this._startAsyncSync(libraryId, library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Sync started',
|
||||
libraryId,
|
||||
async: true
|
||||
};
|
||||
return { success: true, message: 'Sync started', libraryId, async: true };
|
||||
}
|
||||
} catch (error) {
|
||||
this.dbPool.release(library.path);
|
||||
@@ -102,44 +74,6 @@ class ScanService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
*/
|
||||
stopScan(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
|
||||
if (!this.scanManager.isScanning(libraryId)) {
|
||||
throw new ValidationError('No scan in progress', 'libraryId');
|
||||
}
|
||||
|
||||
this.scanManager.pauseScan(libraryId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan stopped',
|
||||
libraryId
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 继续扫描
|
||||
*/
|
||||
resumeScan(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
|
||||
if (!this.scanManager.isPaused(libraryId)) {
|
||||
throw new ValidationError('No paused scan found', 'libraryId');
|
||||
}
|
||||
|
||||
this.scanManager.resumeScan(libraryId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan resumed',
|
||||
libraryId
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态
|
||||
*/
|
||||
@@ -149,13 +83,19 @@ class ScanService {
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
isScanning: this.scanManager.isScanning(libraryId),
|
||||
isPaused: this.scanManager.isPaused(libraryId),
|
||||
status: state?.status || 'idle',
|
||||
progress: state?.progress || null,
|
||||
startTime: state?.startTime || null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有活跃状态
|
||||
*/
|
||||
getAllActiveStates() {
|
||||
return this.scanManager.getAllActiveStates();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复文件夹路径
|
||||
*/
|
||||
@@ -165,12 +105,7 @@ class ScanService {
|
||||
|
||||
try {
|
||||
await this.scanner.fixFolderPaths(library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Folders fixed',
|
||||
libraryId
|
||||
};
|
||||
return { success: true, message: 'Folders fixed', libraryId };
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
@@ -178,13 +113,13 @@ class ScanService {
|
||||
|
||||
/**
|
||||
* 启动异步扫描
|
||||
* @private
|
||||
*/
|
||||
_startAsyncScan(libraryId, libraryPath, db) {
|
||||
this.scanner.scanLibrary(
|
||||
libraryPath,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
(progress) => this._emitProgress(libraryId, progress),
|
||||
libraryId
|
||||
).then(() => {
|
||||
this._emitComplete(libraryId);
|
||||
this.dbPool.release(libraryPath);
|
||||
@@ -196,12 +131,12 @@ class ScanService {
|
||||
|
||||
/**
|
||||
* 启动异步同步
|
||||
* @private
|
||||
*/
|
||||
_startAsyncSync(libraryId, libraryPath, db) {
|
||||
this.scanner.incrementalSync(
|
||||
this.scanner.syncLibrary(
|
||||
libraryPath,
|
||||
db,
|
||||
false,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
).then(() => {
|
||||
this._emitComplete(libraryId);
|
||||
@@ -212,54 +147,30 @@ class ScanService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送进度更新
|
||||
* @private
|
||||
*/
|
||||
_emitProgress(libraryId, progress) {
|
||||
if (this.io) {
|
||||
this.io.emit('scanProgress', {
|
||||
libraryId,
|
||||
...progress
|
||||
});
|
||||
this.io.emit('scanProgress', { libraryId, ...progress });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送完成事件
|
||||
* @private
|
||||
*/
|
||||
_emitComplete(libraryId) {
|
||||
if (this.io) {
|
||||
this.io.emit('scanComplete', { libraryId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送错误事件
|
||||
* @private
|
||||
*/
|
||||
_emitError(libraryId, error) {
|
||||
if (this.io) {
|
||||
this.io.emit('scanError', {
|
||||
libraryId,
|
||||
error: error.message
|
||||
});
|
||||
this.io.emit('scanError', { libraryId, error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取素材库对象
|
||||
* @private
|
||||
*/
|
||||
_getLibrary(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', libraryId);
|
||||
}
|
||||
|
||||
return library;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,14 +19,9 @@ class CleanupManager {
|
||||
* Start routine cleanup
|
||||
*/
|
||||
startRoutineCleanup() {
|
||||
if (this.isRunning) {
|
||||
console.log('[CleanupManager] Routine cleanup already running');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[CleanupManager] Starting routine cleanup');
|
||||
console.log(` Interval: ${this.routineInterval}ms`);
|
||||
if (this.isRunning) return;
|
||||
|
||||
console.log('🧹 清理管理器已启动');
|
||||
this.isRunning = true;
|
||||
|
||||
this.routineIntervalId = setInterval(() => {
|
||||
@@ -38,11 +33,9 @@ class CleanupManager {
|
||||
* Stop routine cleanup
|
||||
*/
|
||||
stopRoutineCleanup() {
|
||||
if (!this.isRunning) {
|
||||
return;
|
||||
}
|
||||
if (!this.isRunning) return;
|
||||
|
||||
console.log('[CleanupManager] Stopping routine cleanup');
|
||||
console.log('🧹 清理管理器已停止');
|
||||
|
||||
if (this.routineIntervalId) {
|
||||
clearInterval(this.routineIntervalId);
|
||||
@@ -81,11 +74,10 @@ class CleanupManager {
|
||||
this.cleanupCount++;
|
||||
this.lastCleanupTime = Date.now();
|
||||
|
||||
// 总是显示日志(帮助诊断)
|
||||
console.log('[CleanupManager] Routine cleanup completed');
|
||||
console.log(` Caches cleared: ${cachesCleared}`);
|
||||
console.log(` Heap reclaimed: ${(memoryReclaimed / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(` RSS: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB (${rssReclaimed > 0 ? '-' : '+'}${Math.abs(rssReclaimed).toFixed(0)}MB)`);
|
||||
// 只在内存回收显著时输出日志
|
||||
if (Math.abs(rssReclaimed) > 10) {
|
||||
console.log(`🧹 内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`);
|
||||
}
|
||||
|
||||
return {
|
||||
memoryBefore,
|
||||
@@ -95,7 +87,7 @@ class CleanupManager {
|
||||
connectionsCleared: 0
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[CleanupManager] Routine cleanup error:', error);
|
||||
console.error('❌ 清理失败:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -107,7 +99,7 @@ class CleanupManager {
|
||||
* - Force garbage collection multiple times (3+)
|
||||
*/
|
||||
executeEmergencyCleanup() {
|
||||
console.log('[CleanupManager] 🚨 Executing EMERGENCY cleanup...');
|
||||
console.log('🚨 执行紧急内存清理...');
|
||||
|
||||
const memoryBefore = this.getMemoryStats();
|
||||
|
||||
@@ -118,15 +110,15 @@ class CleanupManager {
|
||||
try {
|
||||
this.dbPool.closeAll();
|
||||
connectionsCleared = 1;
|
||||
console.log('[CleanupManager] ✓ Database connections closed');
|
||||
console.log(' ✓ 数据库连接已关闭');
|
||||
} catch (error) {
|
||||
console.error('[CleanupManager] ✗ Failed to close connections:', error.message);
|
||||
console.error(' ✗ 关闭连接失败:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Clear all registered caches
|
||||
const cachesCleared = this.clearAllCaches();
|
||||
console.log(`[CleanupManager] ✓ ${cachesCleared} caches cleared`);
|
||||
console.log(` ✓ 已清理 ${cachesCleared} 个缓存`);
|
||||
|
||||
// 3. Force garbage collection multiple times (minimum 3)
|
||||
this.forceGarbageCollection(3);
|
||||
@@ -134,10 +126,7 @@ class CleanupManager {
|
||||
const memoryAfter = this.getMemoryStats();
|
||||
const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed;
|
||||
|
||||
console.log('[CleanupManager] Emergency cleanup completed');
|
||||
console.log(` Memory before: ${(memoryBefore.heapUsed / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(` Memory after: ${(memoryAfter.heapUsed / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(` Memory reclaimed: ${(memoryReclaimed / 1024 / 1024).toFixed(2)} MB`);
|
||||
console.log(`✅ 紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`);
|
||||
|
||||
return {
|
||||
memoryBefore,
|
||||
@@ -147,7 +136,7 @@ class CleanupManager {
|
||||
connectionsCleared
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[CleanupManager] Emergency cleanup error:', error);
|
||||
console.error('❌ 紧急清理失败:', error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -157,23 +146,16 @@ class CleanupManager {
|
||||
* @param {number} iterations - Number of GC iterations (minimum 3)
|
||||
*/
|
||||
forceGarbageCollection(iterations = 3) {
|
||||
if (!global.gc) {
|
||||
console.warn('[CleanupManager] Garbage collection not available (run with --expose-gc)');
|
||||
return;
|
||||
}
|
||||
if (!global.gc) return;
|
||||
|
||||
const actualIterations = Math.max(3, iterations);
|
||||
console.log(`[CleanupManager] Running GC ${actualIterations} times...`);
|
||||
|
||||
for (let i = 0; i < actualIterations; i++) {
|
||||
try {
|
||||
global.gc();
|
||||
} catch (error) {
|
||||
console.error(`[CleanupManager] GC iteration ${i + 1} failed:`, error.message);
|
||||
console.error(` ✗ GC失败 (${i + 1}/${actualIterations}):`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[CleanupManager] ✓ Garbage collection completed');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,7 +172,7 @@ class CleanupManager {
|
||||
cleared++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[CleanupManager] Failed to clear cache "${name}":`, error.message);
|
||||
console.error(`❌ 清理缓存失败 "${name}":`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,12 +186,11 @@ class CleanupManager {
|
||||
*/
|
||||
registerCache(name, cache) {
|
||||
if (!cache || typeof cache.clear !== 'function') {
|
||||
console.warn(`[CleanupManager] Cache "${name}" does not have a clear() method`);
|
||||
console.warn(`⚠️ 缓存 "${name}" 无clear()方法`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.caches.set(name, cache);
|
||||
console.log(`[CleanupManager] Registered cache: ${name}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -24,15 +24,9 @@ class MemoryMonitor {
|
||||
* Start monitoring memory usage
|
||||
*/
|
||||
start() {
|
||||
if (this.isRunning) {
|
||||
console.log('[MemoryMonitor] Already running');
|
||||
return;
|
||||
}
|
||||
if (this.isRunning) return;
|
||||
|
||||
console.log('[MemoryMonitor] Starting memory monitoring');
|
||||
console.log(` Warning threshold: ${(this.warningThreshold / 1024 / 1024).toFixed(0)}MB`);
|
||||
console.log(` Danger threshold: ${(this.dangerThreshold / 1024 / 1024).toFixed(0)}MB`);
|
||||
console.log(` Check interval: ${this.checkInterval}ms`);
|
||||
console.log('📊 内存监控已启动');
|
||||
|
||||
this.isRunning = true;
|
||||
|
||||
@@ -43,7 +37,6 @@ class MemoryMonitor {
|
||||
|
||||
// Start development mode logging
|
||||
if (this.devMode) {
|
||||
console.log('[MemoryMonitor] Development mode: logging every 30 seconds');
|
||||
this.devLogIntervalId = setInterval(() => {
|
||||
const stats = this.getMemoryStats();
|
||||
this.logMemoryStats(stats, 'DEV');
|
||||
@@ -58,11 +51,9 @@ class MemoryMonitor {
|
||||
* Stop monitoring
|
||||
*/
|
||||
stop() {
|
||||
if (!this.isRunning) {
|
||||
return;
|
||||
}
|
||||
if (!this.isRunning) return;
|
||||
|
||||
console.log('[MemoryMonitor] Stopping memory monitoring');
|
||||
console.log('📊 内存监控已停止');
|
||||
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
@@ -125,7 +116,7 @@ class MemoryMonitor {
|
||||
|
||||
this.lastWarningTime = now;
|
||||
|
||||
console.warn('[MemoryMonitor] ⚠️ WARNING: Memory usage high');
|
||||
console.warn('⚠️ 内存使用偏高');
|
||||
this.logMemoryStats(stats, 'WARNING');
|
||||
}
|
||||
|
||||
@@ -142,12 +133,12 @@ class MemoryMonitor {
|
||||
|
||||
this.lastDangerTime = now;
|
||||
|
||||
console.error('[MemoryMonitor] 🚨 DANGER: Memory usage critical!');
|
||||
console.error('🚨 内存使用危险!');
|
||||
this.logMemoryStats(stats, 'DANGER');
|
||||
|
||||
// Trigger emergency cleanup if cleanup manager is available
|
||||
if (this.cleanupManager) {
|
||||
console.log('[MemoryMonitor] Triggering emergency cleanup...');
|
||||
console.log('🚨 触发紧急清理...');
|
||||
try {
|
||||
this.cleanupManager.executeEmergencyCleanup();
|
||||
|
||||
@@ -155,11 +146,9 @@ class MemoryMonitor {
|
||||
setTimeout(() => {
|
||||
const afterStats = this.getMemoryStats();
|
||||
const afterRSS = afterStats.rss / 1024 / 1024;
|
||||
console.log(`[MemoryMonitor] After emergency cleanup: RSS = ${afterRSS.toFixed(0)}MB`);
|
||||
|
||||
// 如果 RSS 仍然很高,强制更多 GC
|
||||
if (afterRSS > 500) {
|
||||
console.log('[MemoryMonitor] RSS still high, forcing additional GC...');
|
||||
if (global.gc) {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
global.gc();
|
||||
@@ -168,10 +157,8 @@ class MemoryMonitor {
|
||||
}
|
||||
}, 1000);
|
||||
} catch (error) {
|
||||
console.error('[MemoryMonitor] Emergency cleanup failed:', error);
|
||||
console.error('❌ 紧急清理失败:', error.message);
|
||||
}
|
||||
} else {
|
||||
console.warn('[MemoryMonitor] No cleanup manager available');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,12 +172,10 @@ class MemoryMonitor {
|
||||
const externalMB = (stats.external / 1024 / 1024).toFixed(2);
|
||||
const arrayBuffersMB = (stats.arrayBuffers / 1024 / 1024).toFixed(2);
|
||||
|
||||
console.log(`[MemoryMonitor] ${level} - Memory Statistics:`);
|
||||
console.log(` Heap Used: ${heapUsedMB} MB`);
|
||||
console.log(` Heap Total: ${heapTotalMB} MB`);
|
||||
console.log(` RSS: ${rssMB} MB`);
|
||||
console.log(` External: ${externalMB} MB`);
|
||||
console.log(` Array Buffers: ${arrayBuffersMB} MB`);
|
||||
console.log(`📊 内存状态 [${level}]:`);
|
||||
console.log(` Heap: ${heapUsedMB}/${heapTotalMB} MB`);
|
||||
console.log(` RSS: ${rssMB} MB`);
|
||||
console.log(` External: ${externalMB} MB`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+101
-100
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* 扫描状态管理器
|
||||
* 支持扫描的停止、继续和持久化
|
||||
* 扫描状态管理器(简化版)
|
||||
* 只负责进度持久化,无暂停功能
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
@@ -8,17 +8,17 @@ const path = require('path');
|
||||
|
||||
class ScanManager {
|
||||
constructor() {
|
||||
// 每个素材库的扫描状态(内存)
|
||||
this.scanStates = new Map();
|
||||
// 素材库路径映射(用于持久化)
|
||||
this.libraryPaths = new Map();
|
||||
this.saveTimers = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册素材库路径(用于持久化)
|
||||
* 注册素材库路径
|
||||
*/
|
||||
registerLibraryPath(libraryId, libraryPath) {
|
||||
this.libraryPaths.set(libraryId, libraryPath);
|
||||
this._restoreStateFromFile(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -31,15 +31,15 @@ class ScanManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存状态到文件(轻量:只保存关键信息)
|
||||
* 保存状态到文件
|
||||
*/
|
||||
saveState(libraryId) {
|
||||
const stateFile = this.getStateFilePath(libraryId);
|
||||
if (!stateFile) return;
|
||||
|
||||
const state = this.scanStates.get(libraryId);
|
||||
|
||||
if (!state || state.status === 'idle') {
|
||||
// 删除状态文件
|
||||
try {
|
||||
if (fs.existsSync(stateFile)) {
|
||||
fs.unlinkSync(stateFile);
|
||||
@@ -49,19 +49,38 @@ class ScanManager {
|
||||
}
|
||||
|
||||
try {
|
||||
const dir = path.dirname(stateFile);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
const saveData = {
|
||||
status: state.status,
|
||||
progress: state.progress,
|
||||
pendingCount: state.pendingFiles?.length || 0,
|
||||
// 只保存文件相对路径,不保存完整路径列表(太大)
|
||||
startTime: state.startTime,
|
||||
savedAt: Date.now()
|
||||
};
|
||||
|
||||
fs.writeFileSync(stateFile, JSON.stringify(saveData, null, 2));
|
||||
} catch (e) {
|
||||
console.error('Failed to save scan state:', e.message);
|
||||
console.error('❌ 保存扫描状态失败:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时保存(每5秒)
|
||||
*/
|
||||
_scheduleSave(libraryId) {
|
||||
if (this.saveTimers.has(libraryId)) {
|
||||
clearTimeout(this.saveTimers.get(libraryId));
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
this.saveState(libraryId);
|
||||
this.saveTimers.delete(libraryId);
|
||||
}, 5000);
|
||||
this.saveTimers.set(libraryId, timer);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载状态
|
||||
*/
|
||||
@@ -71,7 +90,7 @@ class ScanManager {
|
||||
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
|
||||
// 状态超过 24 小时视为过期
|
||||
// 24小时过期
|
||||
if (Date.now() - data.savedAt > 24 * 60 * 60 * 1000) {
|
||||
fs.unlinkSync(stateFile);
|
||||
return null;
|
||||
@@ -83,48 +102,67 @@ class ScanManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态(优先内存,其次文件)
|
||||
* 从文件恢复状态
|
||||
*/
|
||||
_restoreStateFromFile(libraryId) {
|
||||
if (this.scanStates.has(libraryId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fileState = this.loadState(libraryId);
|
||||
|
||||
if (fileState && fileState.status === 'scanning') {
|
||||
this.scanStates.set(libraryId, {
|
||||
status: fileState.status,
|
||||
progress: fileState.progress,
|
||||
startTime: fileState.startTime
|
||||
});
|
||||
console.log(`🔄 恢复扫描状态: ${fileState.progress?.percent || 0}%`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态
|
||||
*/
|
||||
getState(libraryId) {
|
||||
// 先检查内存中的状态
|
||||
const memState = this.scanStates.get(libraryId);
|
||||
if (memState) return memState;
|
||||
|
||||
// 尝试从文件加载(应用重启后的恢复)
|
||||
const fileState = this.loadState(libraryId);
|
||||
if (fileState && fileState.status === 'paused') {
|
||||
// 重建内存状态(不含 pendingFiles,需要重新扫描确定)
|
||||
if (fileState && fileState.status === 'scanning') {
|
||||
const restored = {
|
||||
status: 'paused',
|
||||
status: 'scanning',
|
||||
progress: fileState.progress,
|
||||
pendingFiles: [], // 无法恢复完整列表,需要继续扫描时重新计算
|
||||
processedCount: fileState.progress?.current || 0,
|
||||
abortController: { aborted: true },
|
||||
needsRescan: true // 标记需要重新扫描
|
||||
startTime: fileState.startTime
|
||||
};
|
||||
this.scanStates.set(libraryId, restored);
|
||||
return restored;
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'idle',
|
||||
progress: null,
|
||||
pendingFiles: [],
|
||||
processedCount: 0
|
||||
};
|
||||
return { status: 'idle', progress: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始扫描
|
||||
*/
|
||||
startScan(libraryId, totalFiles) {
|
||||
startScan(libraryId, totalFiles, libraryPath) {
|
||||
// 确保路径已注册
|
||||
if (libraryPath && !this.libraryPaths.has(libraryId)) {
|
||||
this.libraryPaths.set(libraryId, libraryPath);
|
||||
}
|
||||
|
||||
if (this.saveTimers.has(libraryId)) {
|
||||
clearTimeout(this.saveTimers.get(libraryId));
|
||||
this.saveTimers.delete(libraryId);
|
||||
}
|
||||
|
||||
this.scanStates.set(libraryId, {
|
||||
status: 'scanning',
|
||||
progress: { current: 0, total: totalFiles, percent: 0 },
|
||||
pendingFiles: [],
|
||||
processedCount: 0,
|
||||
abortController: { aborted: false }
|
||||
startTime: Date.now()
|
||||
});
|
||||
|
||||
this.saveState(libraryId);
|
||||
return this.scanStates.get(libraryId);
|
||||
}
|
||||
|
||||
@@ -139,68 +177,15 @@ class ScanManager {
|
||||
total,
|
||||
percent: Math.round((current / total) * 100)
|
||||
};
|
||||
state.processedCount = current;
|
||||
this._scheduleSave(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
*/
|
||||
stopScan(libraryId, pendingFiles = []) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.status = 'paused';
|
||||
state.pendingFiles = pendingFiles;
|
||||
state.abortController.aborted = true;
|
||||
// 持久化状态
|
||||
this.saveState(libraryId);
|
||||
console.log(`⏸️ Scan paused for ${libraryId}, ${pendingFiles.length} files pending`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否应该停止
|
||||
*/
|
||||
shouldStop(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.abortController?.aborted || false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取待处理文件
|
||||
*/
|
||||
getPendingFiles(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.pendingFiles || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复扫描
|
||||
*/
|
||||
resumeScan(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state && state.status === 'paused') {
|
||||
const pendingFiles = [...state.pendingFiles]; // 复制一份
|
||||
state.status = 'scanning';
|
||||
state.abortController = { aborted: false };
|
||||
state.pendingFiles = []; // 清空待处理列表
|
||||
console.log(`▶️ Scan resumed for ${libraryId}, ${pendingFiles.length} files to process`);
|
||||
return pendingFiles;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成扫描
|
||||
*/
|
||||
completeScan(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.status = 'idle';
|
||||
state.pendingFiles = [];
|
||||
state.progress = null;
|
||||
}
|
||||
// 清除持久化状态
|
||||
this.scanStates.delete(libraryId);
|
||||
this.saveState(libraryId);
|
||||
}
|
||||
|
||||
@@ -212,34 +197,50 @@ class ScanManager {
|
||||
return state?.status === 'scanning';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否已暂停
|
||||
*/
|
||||
isPaused(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.status === 'paused';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除素材库状态(删除素材库时调用)
|
||||
*/
|
||||
clearState(libraryId) {
|
||||
this.scanStates.delete(libraryId);
|
||||
this.libraryPaths.delete(libraryId);
|
||||
// 删除状态文件
|
||||
const stateFile = this.getStateFilePath(libraryId);
|
||||
if (stateFile) {
|
||||
try {
|
||||
const fs = require('fs');
|
||||
if (fs.existsSync(stateFile)) {
|
||||
fs.unlinkSync(stateFile);
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有空闲状态(内存清理)
|
||||
* 获取所有活跃状态
|
||||
*/
|
||||
cleanupIdleStates() {
|
||||
getAllActiveStates() {
|
||||
const activeStates = {};
|
||||
for (const [libraryId, state] of this.scanStates.entries()) {
|
||||
if (state.status === 'idle') {
|
||||
this.scanStates.delete(libraryId);
|
||||
if (state.status === 'scanning') {
|
||||
activeStates[libraryId] = {
|
||||
status: state.status,
|
||||
progress: state.progress,
|
||||
startTime: state.startTime
|
||||
};
|
||||
}
|
||||
}
|
||||
return activeStates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复所有素材库状态
|
||||
*/
|
||||
restoreAllStates(libraries) {
|
||||
for (const lib of libraries) {
|
||||
this.registerLibraryPath(lib.id, lib.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 单例
|
||||
const scanManager = new ScanManager();
|
||||
|
||||
module.exports = scanManager;
|
||||
+94
-102
@@ -38,8 +38,7 @@ function ensureFolderChain(db, folderPath) {
|
||||
|
||||
// 安全检查:确保 db 对象有 getFolderByPath 方法
|
||||
if (typeof db.getFolderByPath !== 'function') {
|
||||
console.error('[ensureFolderChain] Error: db.getFolderByPath is not a function');
|
||||
console.error('[ensureFolderChain] db object keys:', Object.keys(db));
|
||||
console.error('❌ db.getFolderByPath 不是函数');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -116,7 +115,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
}
|
||||
results.added++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing added file ${file}:`, error.message);
|
||||
console.error(`❌ 处理新增文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +136,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
affectedFolders.add(folder);
|
||||
results.modified++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing changed file ${file}:`, error.message);
|
||||
console.error(`❌ 处理修改文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +157,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
}
|
||||
results.deleted++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting file ${file}:`, error.message);
|
||||
console.error(`❌ 删除文件失败 ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +172,7 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
if (parent && parent !== '.') affectedFolders.add(parent);
|
||||
results.foldersRemoved++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting directory ${dir}:`, error.message);
|
||||
console.error(`❌ 删除目录失败 ${dir}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,14 +182,14 @@ async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
try {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
} catch (error) {
|
||||
console.error(`Error updating folder count ${folderPath}:`, error.message);
|
||||
console.error(`❌ 更新文件夹计数失败 ${folderPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error in applyChangesFromEvents:', error);
|
||||
console.error('❌ 应用变化失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -310,7 +309,7 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) {
|
||||
|
||||
return { status: 'processed', path: relativePath };
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', imagePath, error);
|
||||
console.error('❌ 处理图片失败:', path.basename(imagePath), error.message);
|
||||
return { status: 'error', path: imagePath, error: error.message };
|
||||
}
|
||||
}
|
||||
@@ -338,20 +337,18 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
// 动态导入 p-limit
|
||||
const pLimit = (await import('p-limit')).default;
|
||||
|
||||
// 超激进内存控制:限制并发数为 2(防止 Sharp 内存泄漏)
|
||||
const concurrency = 2; // 固定为 2,避免 Sharp 并发导致内存泄漏
|
||||
// 根据 CPU 核心数动态调整并发数
|
||||
const os = require('os');
|
||||
const cpuCount = os.cpus().length;
|
||||
const concurrency = Math.max(4, Math.min(16, cpuCount - 1));
|
||||
const limit = pLimit(concurrency);
|
||||
|
||||
console.log(`🚀 Starting scan with concurrency: ${concurrency} (memory-optimized)`);
|
||||
|
||||
if (resumeFiles && resumeFiles.length > 0) {
|
||||
// 继续扫描:使用待处理文件列表
|
||||
files = resumeFiles;
|
||||
console.log(`▶️ Resuming scan with ${files.length} pending files`);
|
||||
} else {
|
||||
// 新扫描:获取所有文件
|
||||
files = await getAllImageFiles(libraryPath);
|
||||
console.log(`Found ${files.length} images in library`);
|
||||
|
||||
// Get folder structure
|
||||
const folders = await getFolderStructure(libraryPath);
|
||||
@@ -366,7 +363,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
|
||||
// 初始化扫描状态
|
||||
if (libraryId) {
|
||||
scanManager.startScan(libraryId, total);
|
||||
scanManager.startScan(libraryId, total, libraryPath);
|
||||
}
|
||||
|
||||
const results = {
|
||||
@@ -381,7 +378,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
|
||||
// 批量写入缓冲区
|
||||
let writeBuffer = [];
|
||||
const WRITE_BATCH_SIZE = 100; // 每 100 条写入一次数据库
|
||||
const WRITE_BATCH_SIZE = 50; // 每 50 条写入一次数据库(降低内存峰值)
|
||||
const STREAM_BATCH_SIZE = 200; // 每批处理 200 个文件(流式处理)
|
||||
|
||||
// 批量写入函数(事务)
|
||||
const batchWrite = db.db.transaction((items) => {
|
||||
@@ -394,11 +392,6 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
|
||||
// 处理单个文件的包装函数
|
||||
const processFile = async (file) => {
|
||||
// 检查是否需要停止
|
||||
if (libraryId && scanManager.shouldStop(libraryId)) {
|
||||
return { status: 'stopped', file };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await processImage(file, libraryPath, db, true); // true = dryRun (不直接写入DB)
|
||||
return result;
|
||||
@@ -407,71 +400,82 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
}
|
||||
};
|
||||
|
||||
// 创建所有任务
|
||||
const tasks = files.map(file => limit(async () => {
|
||||
// 如果已经停止,直接返回
|
||||
if (results.stopped) return;
|
||||
// 流式处理:分批处理文件,避免一次性创建大量 Promise
|
||||
for (let batchStart = 0; batchStart < total; batchStart += STREAM_BATCH_SIZE) {
|
||||
const batchEnd = Math.min(batchStart + STREAM_BATCH_SIZE, total);
|
||||
const batchFiles = files.slice(batchStart, batchEnd);
|
||||
|
||||
const result = await processFile(file);
|
||||
// 处理当前批次
|
||||
const batchTasks = batchFiles.map(file => limit(async () => {
|
||||
const result = await processFile(file);
|
||||
|
||||
if (result.status === 'stopped') {
|
||||
results.stopped = true;
|
||||
return;
|
||||
}
|
||||
// 更新统计
|
||||
if (result.status === 'processed') results.processed++;
|
||||
else if (result.status === 'skipped') results.skipped++;
|
||||
else if (result.status === 'error') results.errors++;
|
||||
|
||||
// 更新统计
|
||||
if (result.status === 'processed') results.processed++;
|
||||
else if (result.status === 'skipped') results.skipped++;
|
||||
else if (result.status === 'error') results.errors++;
|
||||
// 添加到写入缓冲区
|
||||
if (result.status === 'processed') {
|
||||
writeBuffer.push(result);
|
||||
|
||||
// 添加到写入缓冲区
|
||||
if (result.status === 'processed') {
|
||||
writeBuffer.push(result);
|
||||
|
||||
// 缓冲区满,执行批量写入
|
||||
if (writeBuffer.length >= WRITE_BATCH_SIZE) {
|
||||
batchWrite(writeBuffer);
|
||||
writeBuffer = [];
|
||||
}
|
||||
}
|
||||
|
||||
processedCount++;
|
||||
|
||||
// 报告进度 (每完成 10 个文件报告一次,避免过于频繁)
|
||||
if (processedCount % 10 === 0 || processedCount === total) {
|
||||
const current = processedCount;
|
||||
|
||||
if (libraryId) {
|
||||
scanManager.updateProgress(libraryId, current, total);
|
||||
// 缓冲区满,执行批量写入
|
||||
if (writeBuffer.length >= WRITE_BATCH_SIZE) {
|
||||
batchWrite(writeBuffer);
|
||||
writeBuffer = []; // 清空缓冲区,释放内存
|
||||
}
|
||||
}
|
||||
|
||||
if (onProgress) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
const avgTimePerImage = elapsed / current;
|
||||
const remaining = total - current;
|
||||
const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000);
|
||||
processedCount++;
|
||||
|
||||
onProgress({
|
||||
total,
|
||||
current,
|
||||
percent: Math.round((current / total) * 100),
|
||||
currentFile: file,
|
||||
estimatedTimeLeft,
|
||||
canStop: true
|
||||
});
|
||||
// 报告进度 (每完成 10 个文件报告一次)
|
||||
if (processedCount % 10 === 0 || processedCount === total) {
|
||||
const current = processedCount;
|
||||
|
||||
if (libraryId) {
|
||||
scanManager.updateProgress(libraryId, current, total);
|
||||
}
|
||||
|
||||
if (onProgress) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
const avgTimePerImage = elapsed / current;
|
||||
const remaining = total - current;
|
||||
const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000);
|
||||
|
||||
onProgress({
|
||||
total,
|
||||
current,
|
||||
percent: Math.round((current / total) * 100),
|
||||
currentFile: file,
|
||||
estimatedTimeLeft
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}));
|
||||
|
||||
// 等待当前批次完成
|
||||
await Promise.all(batchTasks);
|
||||
|
||||
// 批次完成后,写入剩余缓冲区并释放内存
|
||||
if (writeBuffer.length > 0) {
|
||||
batchWrite(writeBuffer);
|
||||
writeBuffer = [];
|
||||
}
|
||||
|
||||
// 性能日志
|
||||
if (processedCount > 0 && processedCount % 1000 === 0) {
|
||||
// 每1000个文件输出一次进度(减少日志)
|
||||
if (processedCount % 1000 === 0) {
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
const speed = processedCount / elapsed;
|
||||
console.log(`⚡ Performance: ${speed.toFixed(1)} images/sec, ${processedCount}/${total} completed`);
|
||||
const percent = ((processedCount / total) * 100).toFixed(1);
|
||||
console.log(`⚡ ${processedCount}/${total} (${percent}%) | ${speed.toFixed(1)} 张/秒`);
|
||||
}
|
||||
}));
|
||||
|
||||
// 等待所有任务完成
|
||||
await Promise.all(tasks);
|
||||
|
||||
// 每 1000 个文件触发一次 GC
|
||||
if (processedCount > 0 && processedCount % 1000 === 0 && global.gc) {
|
||||
global.gc();
|
||||
}
|
||||
}
|
||||
|
||||
// 写入剩余的缓冲区数据
|
||||
if (writeBuffer.length > 0) {
|
||||
@@ -479,16 +483,8 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
writeBuffer = [];
|
||||
}
|
||||
|
||||
// 处理停止情况
|
||||
if (results.stopped) {
|
||||
const pendingFiles = files.slice(processedCount);
|
||||
scanManager.stopScan(libraryId, pendingFiles);
|
||||
console.log(`⏸️ Scan stopped at ${processedCount}/${total}, ${pendingFiles.length} files pending`);
|
||||
return results;
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000;
|
||||
console.log(`✅ Scan completed in ${totalTime.toFixed(1)}s, speed: ${(total / totalTime).toFixed(1)} images/sec`);
|
||||
console.log(`✅ 扫描完成: ${total} 个文件 (${totalTime.toFixed(1)}秒, ${(total / totalTime).toFixed(1)} 张/秒)`);
|
||||
|
||||
// Update folder image counts
|
||||
db.updateAllFolderCounts();
|
||||
@@ -497,11 +493,9 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
|
||||
console.log('Scan complete:', results);
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error scanning library:', error);
|
||||
console.error('❌ 扫描失败:', error.message);
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
@@ -534,17 +528,14 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
const toCheck = [...currentPaths].filter(p => dbPaths.has(p));
|
||||
let toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
console.log(`Sync: ${toAdd.length} new, ${toCheck.length} to check, ${toDelete.length} deleted`);
|
||||
console.log(`🔄 同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`);
|
||||
|
||||
// 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题
|
||||
const dbImageCount = dbPaths.size;
|
||||
if (toDelete.length > 0 && dbImageCount > 0) {
|
||||
const deleteRatio = toDelete.length / dbImageCount;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:要删除 ${toDelete.length}/${dbImageCount} (${(deleteRatio * 100).toFixed(1)}%) 的文件,这可能是路径匹配问题,跳过删除操作`);
|
||||
console.log('示例 currentPath:', [...currentPaths].slice(0, 3));
|
||||
console.log('示例 dbPath:', [...dbPaths].slice(0, 3));
|
||||
// 清空 toDelete,不执行删除
|
||||
console.warn(`⚠️ 安全检查: 跳过删除 ${toDelete.length}/${dbImageCount} 个文件 (${(deleteRatio * 100).toFixed(1)}%)`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
@@ -584,7 +575,9 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
return existing.file_hash !== currentHash;
|
||||
}).length;
|
||||
|
||||
console.log(`Found ${modifiedCount} modified files (skipped, hash unchanged)`);
|
||||
if (modifiedCount > 0) {
|
||||
console.log(`📝 发现 ${modifiedCount} 个修改文件`);
|
||||
}
|
||||
|
||||
// Delete removed files
|
||||
for (const relativePath of toDelete) {
|
||||
@@ -594,7 +587,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
|
||||
// Rebuild folder structure if there are changes or forced
|
||||
if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) {
|
||||
console.log('Rebuilding folder structure...');
|
||||
console.log('📂 重建文件夹结构...');
|
||||
|
||||
// Get current folder structure from file system
|
||||
const currentFolders = await getFolderStructure(libraryPath);
|
||||
@@ -618,10 +611,11 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
db.deleteFolder(folder.path);
|
||||
});
|
||||
|
||||
console.log(`Folders: +${foldersToAdd.length}, -${foldersToDelete.length}`);
|
||||
if (foldersToAdd.length > 0 || foldersToDelete.length > 0) {
|
||||
console.log(`📂 文件夹变化: +${foldersToAdd.length} -${foldersToDelete.length}`);
|
||||
}
|
||||
|
||||
// Update folder image counts
|
||||
console.log('Updating folder image counts...');
|
||||
const affectedFolders = new Set();
|
||||
|
||||
// Collect all affected folders (including parent folders)
|
||||
@@ -641,12 +635,10 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
affectedFolders.forEach(folderPath => {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
});
|
||||
|
||||
console.log(`Updated ${affectedFolders.size} folder counts`);
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000;
|
||||
console.log(`✅ Sync completed in ${totalTime.toFixed(1)}s`);
|
||||
console.log(`✅ 同步完成 (${totalTime.toFixed(1)}秒)`);
|
||||
|
||||
return {
|
||||
added: toAdd.length,
|
||||
@@ -654,7 +646,7 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
|
||||
deleted: toDelete.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error syncing library:', error);
|
||||
console.error('❌ 同步失败:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -687,7 +679,7 @@ async function quickSync(libraryPath, db) {
|
||||
if (toDelete.length > 0 && dbImageCount > 0) {
|
||||
const deleteRatio = toDelete.length / dbImageCount;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:跳过删除 ${toDelete.length} 个文件`);
|
||||
console.warn(`⚠️ 跳过删除 ${toDelete.length} 个文件`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
@@ -703,7 +695,7 @@ async function quickSync(libraryPath, db) {
|
||||
}
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (err) {
|
||||
console.error(`Error adding ${relativePath}:`, err.message);
|
||||
console.error(`❌ 添加失败 ${relativePath}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -719,7 +711,7 @@ async function quickSync(libraryPath, db) {
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
console.log(`Quick sync: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
console.log(`⚡ 快速同步: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
}
|
||||
|
||||
return { added: toAdd.length, deleted: toDelete.length };
|
||||
|
||||
@@ -13,8 +13,6 @@ sharp.cache({
|
||||
// 设置并发限制
|
||||
sharp.concurrency(1); // 一次只处理 1 张图片
|
||||
|
||||
console.log('[Sharp] Memory-optimized configuration applied: cache=50MB, concurrency=1');
|
||||
|
||||
// 支持的文件格式(确定可以生成缩略图的)
|
||||
const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg'];
|
||||
|
||||
@@ -248,13 +246,6 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
|
||||
const stats = fs.statSync(outputPath);
|
||||
const finalSize = stats.size;
|
||||
|
||||
// 可选:输出详细信息(每100张输出一次,避免日志过多)
|
||||
const shouldLog = Math.random() < 0.01; // 1% 概率输出
|
||||
if (shouldLog) {
|
||||
const sizeKB = (finalSize / 1024).toFixed(1);
|
||||
console.log(`📸 Thumbnail: ${config.megaPixels}MP → ${config.width}x${config.height} (${sizeKB}KB, Q${quality}, ratio ${downscaleRatio.toFixed(1)}x)`);
|
||||
}
|
||||
|
||||
return {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
@@ -324,8 +315,6 @@ async function generateImageThumbnails(imagePath, libraryPath) {
|
||||
const hash = crypto.createHash('md5').update(relativePath).digest('hex');
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
console.log(`📝 Processing file: ${path.basename(imagePath)}, type: ${fileType}`);
|
||||
|
||||
// Sharding: use first 2 chars of hash for subdirectories (e.g. /ab/)
|
||||
const shard1 = hash.slice(0, 2);
|
||||
// 1-level sharding: .flypic/thumbnails/ab/hash.webp
|
||||
@@ -342,34 +331,27 @@ async function generateImageThumbnails(imagePath, libraryPath) {
|
||||
thumbnailResult = await generateThumbnail(imagePath, out480, 480);
|
||||
} else if (fileType === 'video') {
|
||||
// 视频:尝试提取封面
|
||||
console.log(`🎬 Extracting video thumbnail for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await extractVideoThumbnail(imagePath, out480);
|
||||
|
||||
// 如果提取失败,生成占位图
|
||||
if (!thumbnailResult) {
|
||||
console.log(`🎬 Generating video placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, 'video', ext);
|
||||
}
|
||||
} else if (fileType === 'design') {
|
||||
// 设计文件:尝试提取嵌入缩略图(仅 PSD)
|
||||
if (ext.toLowerCase() === 'psd') {
|
||||
console.log(`🎨 Extracting PSD thumbnail for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await extractPSDThumbnail(imagePath, out480);
|
||||
}
|
||||
|
||||
// 如果提取失败或不是 PSD,生成占位图
|
||||
if (!thumbnailResult) {
|
||||
console.log(`🎨 Generating design placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, 'design', ext);
|
||||
}
|
||||
} else {
|
||||
// 其他类型(音频/文档/未知):生成占位图
|
||||
console.log(`📦 Generating ${fileType} placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, fileType, ext);
|
||||
}
|
||||
|
||||
console.log(`✅ Thumbnail generated: ${path.basename(out480)}, ${thumbnailResult.width}x${thumbnailResult.height}, ${(thumbnailResult.size / 1024).toFixed(1)}KB`);
|
||||
|
||||
// 返回相对于 libraryPath 的路径(包含 .flypic 前缀)
|
||||
const thumbnailPath = path.relative(libraryPath, out480).replace(/\\/g, '/');
|
||||
|
||||
@@ -427,7 +409,6 @@ async function extractPSDThumbnail(psdPath, outputPath) {
|
||||
|
||||
// 先获取原始缩略图尺寸
|
||||
const metadata = await sharp(jpegData).metadata();
|
||||
console.log(` 📐 PSD embedded thumbnail: ${metadata.width}x${metadata.height}`);
|
||||
|
||||
// 使用高质量缩放,保持宽高比
|
||||
const aspectRatio = metadata.width / metadata.height;
|
||||
@@ -477,7 +458,6 @@ async function extractPSDThumbnail(psdPath, outputPath) {
|
||||
.toFile(outputPath);
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
console.log(` ✅ PSD thumbnail extracted: ${(stats.size / 1024).toFixed(1)}KB`);
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
@@ -524,7 +504,6 @@ async function extractVideoThumbnail(videoPath, outputPath) {
|
||||
if (fs.existsSync(tempJpg)) {
|
||||
// 先获取实际尺寸
|
||||
const metadata = await sharp(tempJpg).metadata();
|
||||
console.log(` 📐 Video frame: ${metadata.width}x${metadata.height}`);
|
||||
|
||||
// 保持宽高比缩放到 480 高度
|
||||
const aspectRatio = metadata.width / metadata.height;
|
||||
@@ -544,7 +523,6 @@ async function extractVideoThumbnail(videoPath, outputPath) {
|
||||
fs.unlinkSync(tempJpg); // 删除临时 JPG
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
console.log(` ✅ Video thumbnail extracted: ${targetWidth}x${targetHeight}, ${(stats.size / 1024).toFixed(1)}KB`);
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
|
||||
Reference in new issue
Block a user