优化 素材库新增处理优化,提速,其余bug处理

This commit is contained in:
Chen committed 2025-12-04 10:57:50 +08:00
1 parent ad774d8a22
commit 4bce6f5d72
67 files changed
+4861 -3111

No files matched your search

+19 -38
View File
@@ -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}`);
}
/**
+12 -27
View File
@@ -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
View File
@@ -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
View File
@@ -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 };
-22
View File
@@ -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,