v 1.0.0
This commit is contained in:
commit
9e346c7d5b
73 files changed
+19169
No files matched your search
@@ -0,0 +1,232 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
// 配置缓存
|
||||
let configCache = null;
|
||||
let configCacheTime = 0;
|
||||
const CONFIG_CACHE_TTL = 5000; // 5秒缓存
|
||||
|
||||
/**
|
||||
* Get config directory based on environment
|
||||
*/
|
||||
function getConfigDir() {
|
||||
// Check if running on fnOS
|
||||
if (process.env.TRIM_PKGVAR) {
|
||||
return process.env.TRIM_PKGVAR;
|
||||
}
|
||||
|
||||
// Windows
|
||||
if (process.platform === 'win32') {
|
||||
return path.join(process.env.APPDATA || os.homedir(), 'FlyPic');
|
||||
}
|
||||
|
||||
// Linux/Mac
|
||||
return path.join(os.homedir(), '.flypic');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config file path
|
||||
*/
|
||||
function getConfigPath() {
|
||||
const configDir = getConfigDir();
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
return path.join(configDir, 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configuration
|
||||
*/
|
||||
function loadConfig(forceReload = false) {
|
||||
// 检查缓存是否有效
|
||||
const now = Date.now();
|
||||
if (!forceReload && configCache && (now - configCacheTime) < CONFIG_CACHE_TTL) {
|
||||
return configCache;
|
||||
}
|
||||
|
||||
const configPath = getConfigPath();
|
||||
|
||||
if (!fs.existsSync(configPath)) {
|
||||
const defaultConfig = {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
// UI preferences
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16,
|
||||
leftPanelWidth: 256, // 左侧边栏宽度
|
||||
rightPanelWidth: 320 // 右侧边栏宽度
|
||||
}
|
||||
};
|
||||
saveConfig(defaultConfig);
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = fs.readFileSync(configPath, 'utf8');
|
||||
const config = JSON.parse(data);
|
||||
|
||||
// Ensure preferences exist (for backward compatibility)
|
||||
if (!config.preferences) {
|
||||
config.preferences = {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
};
|
||||
}
|
||||
|
||||
// 更新缓存
|
||||
configCache = config;
|
||||
configCacheTime = now;
|
||||
|
||||
return config;
|
||||
} catch (error) {
|
||||
console.error('Error loading config:', error);
|
||||
return {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save configuration
|
||||
*/
|
||||
function saveConfig(config) {
|
||||
const configPath = getConfigPath();
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
// 同步更新缓存
|
||||
configCache = config;
|
||||
configCacheTime = Date.now();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error saving config:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除配置缓存(用于强制重新加载)
|
||||
*/
|
||||
function clearConfigCache() {
|
||||
configCache = null;
|
||||
configCacheTime = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add library to config
|
||||
*/
|
||||
function addLibrary(name, libraryPath) {
|
||||
const config = loadConfig();
|
||||
const id = Date.now().toString();
|
||||
|
||||
config.libraries.push({
|
||||
id,
|
||||
name,
|
||||
path: libraryPath,
|
||||
lastScan: null,
|
||||
createdAt: Date.now()
|
||||
});
|
||||
|
||||
if (!config.currentLibraryId) {
|
||||
config.currentLibraryId = id;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove library from config
|
||||
*/
|
||||
function removeLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.libraries = config.libraries.filter(lib => lib.id !== libraryId);
|
||||
|
||||
if (config.currentLibraryId === libraryId) {
|
||||
config.currentLibraryId = config.libraries.length > 0 ? config.libraries[0].id : null;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update library
|
||||
*/
|
||||
function updateLibrary(libraryId, updates) {
|
||||
const config = loadConfig();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (library) {
|
||||
Object.assign(library, updates);
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get library by ID
|
||||
*/
|
||||
function getLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
return config.libraries.find(lib => lib.id === libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current library
|
||||
*/
|
||||
function setCurrentLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.currentLibraryId = libraryId;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update preferences
|
||||
*/
|
||||
function updatePreferences(preferences) {
|
||||
const config = loadConfig();
|
||||
config.preferences = { ...config.preferences, ...preferences };
|
||||
saveConfig(config);
|
||||
return config.preferences;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update theme
|
||||
*/
|
||||
function updateTheme(theme) {
|
||||
const config = loadConfig();
|
||||
config.theme = theme;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getConfigDir,
|
||||
getConfigPath,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
clearConfigCache,
|
||||
addLibrary,
|
||||
removeLibrary,
|
||||
updateLibrary,
|
||||
getLibrary,
|
||||
setCurrentLibrary,
|
||||
updatePreferences,
|
||||
updateTheme
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
const chokidar = require('chokidar');
|
||||
const path = require('path');
|
||||
const { getLibrary } = require('./config');
|
||||
const { syncLibrary, applyChangesFromEvents } = require('./scanner');
|
||||
const dbPool = require('../database/dbPool');
|
||||
|
||||
class FileWatcher {
|
||||
constructor() {
|
||||
this.watchers = new Map(); // libraryId -> watcher
|
||||
this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders }
|
||||
this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved }
|
||||
}
|
||||
|
||||
// 获取或创建变更缓冲区
|
||||
_getBuffer(libraryId) {
|
||||
if (!this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
}
|
||||
return this.changeBuffers.get(libraryId);
|
||||
}
|
||||
|
||||
// 缓冲区事件数量
|
||||
_bufferCount(buf) {
|
||||
return (
|
||||
buf.filesAdded.size +
|
||||
buf.filesChanged.size +
|
||||
buf.filesRemoved.size +
|
||||
buf.dirsAdded.size +
|
||||
buf.dirsRemoved.size
|
||||
);
|
||||
}
|
||||
|
||||
// 启动监控
|
||||
watch(libraryId, io) {
|
||||
// 如果已经在监控,先停止
|
||||
if (this.watchers.has(libraryId)) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
|
||||
const library = getLibrary(libraryId);
|
||||
if (!library) {
|
||||
console.error(`Library ${libraryId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查路径是否存在和可访问
|
||||
const fs = require('fs');
|
||||
try {
|
||||
fs.accessSync(library.path, fs.constants.R_OK);
|
||||
} catch (error) {
|
||||
const errorMsg = `Cannot access library path: ${library.path} - ${error.message}`;
|
||||
console.error(errorMsg);
|
||||
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
console.log(`Starting file watcher for library: ${library.name} (${library.path})`);
|
||||
|
||||
// 监控所有文件(使用通配符)
|
||||
const pattern = '**/*.*';
|
||||
|
||||
// 创建监控器(监控所有文件和文件夹)
|
||||
const watcher = chokidar.watch([pattern, '**/'], {
|
||||
cwd: library.path,
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/.flypic/**', // 忽略自己的缓存目录
|
||||
'**/.*' // 忽略隐藏文件
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true, // 忽略初始扫描
|
||||
usePolling: false, // 不使用轮询,减少 CPU 占用
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1000, // 文件稳定 1 秒后触发,确保复制完成
|
||||
pollInterval: 200
|
||||
}
|
||||
});
|
||||
|
||||
// 防抖处理:多个文件变化合并为一次同步(自适应时长)
|
||||
const debouncedSync = (forceRebuildFolders = false) => {
|
||||
const buf = this._getBuffer(libraryId);
|
||||
const changeCount = this._bufferCount(buf);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const oldTimer = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(oldTimer.timer);
|
||||
// 聚合 forceRebuildFolders 标记
|
||||
forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders;
|
||||
}
|
||||
|
||||
// 自适应防抖时间:更快响应
|
||||
let debounceMs = 2000;
|
||||
if (changeCount <= 1) debounceMs = 800; // 单文件 0.8 秒
|
||||
else if (changeCount <= 5) debounceMs = 1000; // 少量 1 秒
|
||||
else if (changeCount <= 20) debounceMs = 1500;
|
||||
else if (changeCount <= 100) debounceMs = 2000;
|
||||
else debounceMs = 3000; // 大批量 3 秒
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
const snapshot = this._getBuffer(libraryId);
|
||||
// 清空缓冲区(开始新一轮累计)
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
|
||||
// 从连接池获取数据库连接
|
||||
const db = dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const total = this._bufferCount(snapshot);
|
||||
let results;
|
||||
|
||||
// 始终使用基于事件的快速同步(不再调用 syncLibrary)
|
||||
results = await applyChangesFromEvents(library.path, db, {
|
||||
filesAdded: Array.from(snapshot.filesAdded),
|
||||
filesChanged: Array.from(snapshot.filesChanged),
|
||||
filesRemoved: Array.from(snapshot.filesRemoved),
|
||||
dirsAdded: Array.from(snapshot.dirsAdded),
|
||||
dirsRemoved: Array.from(snapshot.dirsRemoved)
|
||||
});
|
||||
|
||||
// 通过 Socket.IO 通知前端
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
console.log(`Sync complete for ${library.name}:`, results);
|
||||
} catch (error) {
|
||||
console.error(`Sync error for ${library.name}:`, error);
|
||||
io.emit('scanError', { libraryId, error: error.message });
|
||||
} finally {
|
||||
// 释放数据库连接(不关闭,复用)
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}, debounceMs);
|
||||
|
||||
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
|
||||
};
|
||||
|
||||
// 监听文件和文件夹变化(写入缓冲,统一合并处理)
|
||||
watcher
|
||||
.on('add', (filePath) => {
|
||||
this._getBuffer(libraryId).filesAdded.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('unlink', (filePath) => {
|
||||
this._getBuffer(libraryId).filesRemoved.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('change', (filePath) => {
|
||||
this._getBuffer(libraryId).filesChanged.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('addDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsAdded.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('unlinkDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsRemoved.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('error', (error) => {
|
||||
console.error(`Watcher error for ${library.name}:`, error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
console.log(`File watcher ready for: ${library.name}`);
|
||||
});
|
||||
|
||||
this.watchers.set(libraryId, watcher);
|
||||
}
|
||||
|
||||
// 停止监控
|
||||
unwatch(libraryId) {
|
||||
const watcher = this.watchers.get(libraryId);
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
this.watchers.delete(libraryId);
|
||||
console.log(`Stopped file watcher for library: ${libraryId}`);
|
||||
}
|
||||
|
||||
// 清除防抖定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const timerObj = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(timerObj.timer);
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}
|
||||
|
||||
// 清空缓冲区
|
||||
if (this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.delete(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 停止所有监控
|
||||
unwatchAll() {
|
||||
for (const libraryId of this.watchers.keys()) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取监控状态
|
||||
isWatching(libraryId) {
|
||||
return this.watchers.has(libraryId);
|
||||
}
|
||||
|
||||
// 获取所有正在监控的库
|
||||
getWatchedLibraries() {
|
||||
return Array.from(this.watchers.keys());
|
||||
}
|
||||
}
|
||||
|
||||
// 单例模式
|
||||
const fileWatcher = new FileWatcher();
|
||||
|
||||
module.exports = fileWatcher;
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* 扫描状态管理器
|
||||
* 支持扫描的停止、继续和持久化
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
class ScanManager {
|
||||
constructor() {
|
||||
// 每个素材库的扫描状态(内存)
|
||||
this.scanStates = new Map();
|
||||
// 素材库路径映射(用于持久化)
|
||||
this.libraryPaths = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册素材库路径(用于持久化)
|
||||
*/
|
||||
registerLibraryPath(libraryId, libraryPath) {
|
||||
this.libraryPaths.set(libraryId, libraryPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取状态文件路径
|
||||
*/
|
||||
getStateFilePath(libraryId) {
|
||||
const libraryPath = this.libraryPaths.get(libraryId);
|
||||
if (!libraryPath) return null;
|
||||
return path.join(libraryPath, '.flypic', 'scan-state.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存状态到文件(轻量:只保存关键信息)
|
||||
*/
|
||||
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);
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const saveData = {
|
||||
status: state.status,
|
||||
progress: state.progress,
|
||||
pendingCount: state.pendingFiles?.length || 0,
|
||||
// 只保存文件相对路径,不保存完整路径列表(太大)
|
||||
savedAt: Date.now()
|
||||
};
|
||||
fs.writeFileSync(stateFile, JSON.stringify(saveData, null, 2));
|
||||
} catch (e) {
|
||||
console.error('Failed to save scan state:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载状态
|
||||
*/
|
||||
loadState(libraryId) {
|
||||
const stateFile = this.getStateFilePath(libraryId);
|
||||
if (!stateFile || !fs.existsSync(stateFile)) return null;
|
||||
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
|
||||
// 状态超过 24 小时视为过期
|
||||
if (Date.now() - data.savedAt > 24 * 60 * 60 * 1000) {
|
||||
fs.unlinkSync(stateFile);
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态(优先内存,其次文件)
|
||||
*/
|
||||
getState(libraryId) {
|
||||
// 先检查内存中的状态
|
||||
const memState = this.scanStates.get(libraryId);
|
||||
if (memState) return memState;
|
||||
|
||||
// 尝试从文件加载(应用重启后的恢复)
|
||||
const fileState = this.loadState(libraryId);
|
||||
if (fileState && fileState.status === 'paused') {
|
||||
// 重建内存状态(不含 pendingFiles,需要重新扫描确定)
|
||||
const restored = {
|
||||
status: 'paused',
|
||||
progress: fileState.progress,
|
||||
pendingFiles: [], // 无法恢复完整列表,需要继续扫描时重新计算
|
||||
processedCount: fileState.progress?.current || 0,
|
||||
abortController: { aborted: true },
|
||||
needsRescan: true // 标记需要重新扫描
|
||||
};
|
||||
this.scanStates.set(libraryId, restored);
|
||||
return restored;
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'idle',
|
||||
progress: null,
|
||||
pendingFiles: [],
|
||||
processedCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始扫描
|
||||
*/
|
||||
startScan(libraryId, totalFiles) {
|
||||
this.scanStates.set(libraryId, {
|
||||
status: 'scanning',
|
||||
progress: { current: 0, total: totalFiles, percent: 0 },
|
||||
pendingFiles: [],
|
||||
processedCount: 0,
|
||||
abortController: { aborted: false }
|
||||
});
|
||||
return this.scanStates.get(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新进度
|
||||
*/
|
||||
updateProgress(libraryId, current, total) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.progress = {
|
||||
current,
|
||||
total,
|
||||
percent: Math.round((current / total) * 100)
|
||||
};
|
||||
state.processedCount = current;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
*/
|
||||
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.saveState(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否正在扫描
|
||||
*/
|
||||
isScanning(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.status === 'scanning';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否已暂停
|
||||
*/
|
||||
isPaused(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.status === 'paused';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除素材库状态(删除素材库时调用)
|
||||
*/
|
||||
clearState(libraryId) {
|
||||
this.scanStates.delete(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有空闲状态(内存清理)
|
||||
*/
|
||||
cleanupIdleStates() {
|
||||
for (const [libraryId, state] of this.scanStates.entries()) {
|
||||
if (state.status === 'idle') {
|
||||
this.scanStates.delete(libraryId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 单例
|
||||
const scanManager = new ScanManager();
|
||||
|
||||
module.exports = scanManager;
|
||||
@@ -0,0 +1,723 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { glob } = require('glob');
|
||||
const {
|
||||
isImageFile,
|
||||
getFileType,
|
||||
calculateFileHash,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails
|
||||
} = require('./thumbnail');
|
||||
const scanManager = require('./scanManager');
|
||||
|
||||
/**
|
||||
* Get all image files in a directory
|
||||
*/
|
||||
async function getAllImageFiles(libraryPath) {
|
||||
// 支持所有文件格式(使用通配符 *.*)
|
||||
const pattern = path.join(libraryPath, '**', '*.*').replace(/\\/g, '/');
|
||||
const files = await glob(pattern, {
|
||||
nodir: true,
|
||||
nocase: true, // 大小写不敏感(Windows/macOS)
|
||||
ignore: ['**/.flypic/**', '**/node_modules/**']
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a folder and its parents exist in DB
|
||||
*/
|
||||
function ensureFolderChain(db, folderPath) {
|
||||
if (!folderPath || folderPath === '.' || folderPath === '') return;
|
||||
let current = folderPath.replace(/\\/g, '/');
|
||||
const visited = new Set();
|
||||
while (current && current !== '.' && !visited.has(current)) {
|
||||
visited.add(current);
|
||||
const parent = path.posix.dirname(current);
|
||||
const name = current.split('/').pop();
|
||||
const existing = db.getFolderByPath(current);
|
||||
if (!existing) {
|
||||
db.insertFolder({
|
||||
path: current,
|
||||
parent_path: parent === '.' ? '' : (parent === current ? '' : parent),
|
||||
name,
|
||||
image_count: 0
|
||||
});
|
||||
}
|
||||
if (parent === current) break;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply changes from file system events quickly without full rescan
|
||||
* events = {
|
||||
* filesAdded: [relPath],
|
||||
* filesChanged: [relPath],
|
||||
* filesRemoved: [relPath],
|
||||
* dirsAdded: [relDir],
|
||||
* dirsRemoved: [relDir]
|
||||
* }
|
||||
*/
|
||||
async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
try {
|
||||
// Normalize helper: 统一使用正斜杠,与数据库记录格式一致
|
||||
const norm = (p) => path.normalize(p).replace(/\\/g, '/');
|
||||
|
||||
const affectedFolders = new Set();
|
||||
const results = { added: 0, modified: 0, deleted: 0, foldersAdded: 0, foldersRemoved: 0 };
|
||||
|
||||
// Handle directory additions (ensure chain exists)
|
||||
for (const dir of (events.dirsAdded || [])) {
|
||||
const d = norm(dir);
|
||||
ensureFolderChain(db, d);
|
||||
results.foldersAdded++;
|
||||
// update parents too
|
||||
let cur = d;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file additions
|
||||
for (const file of (events.filesAdded || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const folder = path.dirname(rel);
|
||||
ensureFolderChain(db, folder);
|
||||
await processImage(full, libraryPath, db);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.added++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing added file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file changes
|
||||
for (const file of (events.filesChanged || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await processImage(full, libraryPath, db);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
results.modified++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing changed file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file removals
|
||||
for (const file of (events.filesRemoved || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
db.deleteImage(rel);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.deleted++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle directory removals (bulk delete)
|
||||
for (const dir of (events.dirsRemoved || [])) {
|
||||
try {
|
||||
const d = norm(dir);
|
||||
// delete images and folders under this dir
|
||||
db.deleteImagesByFolderPrefix(d);
|
||||
db.deleteFoldersByPrefix(d);
|
||||
const parent = path.dirname(d);
|
||||
if (parent && parent !== '.') affectedFolders.add(parent);
|
||||
results.foldersRemoved++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting directory ${dir}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Update counts for all affected folders
|
||||
affectedFolders.forEach((folderPath) => {
|
||||
if (folderPath && folderPath !== '.') {
|
||||
try {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
} catch (error) {
|
||||
console.error(`Error updating folder count ${folderPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error in applyChangesFromEvents:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get folder structure
|
||||
*/
|
||||
async function getFolderStructure(libraryPath) {
|
||||
const folders = [];
|
||||
|
||||
function scanDir(dirPath, parentPath = '') {
|
||||
const items = fs.readdirSync(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const item of items) {
|
||||
if (item.isDirectory() && !item.name.startsWith('.')) {
|
||||
const fullPath = path.join(dirPath, item.name);
|
||||
const relativePath = path.relative(libraryPath, fullPath);
|
||||
const relativePathUnix = relativePath.replace(/\\/g, '/');
|
||||
const parentUnix = (parentPath || '').replace(/\\/g, '/');
|
||||
|
||||
folders.push({
|
||||
path: relativePathUnix,
|
||||
parent_path: parentUnix,
|
||||
name: item.name,
|
||||
image_count: 0
|
||||
});
|
||||
|
||||
scanDir(fullPath, relativePathUnix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scanDir(libraryPath);
|
||||
return folders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single image file
|
||||
*/
|
||||
/**
|
||||
* Process a single image file
|
||||
* @param {boolean} dryRun - If true, return data instead of inserting into DB (for batch write)
|
||||
*/
|
||||
async function processImage(imagePath, libraryPath, db, dryRun = false) {
|
||||
try {
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
const filename = path.basename(imagePath);
|
||||
const folderRaw = path.dirname(relativePath);
|
||||
const folder = folderRaw === '.' ? '' : folderRaw.replace(/\\/g, '/');
|
||||
|
||||
// Check if image already exists in database
|
||||
const existing = db.getImageByPath(relativePath.replace(/\\/g, '/'));
|
||||
const currentHash = calculateFileHash(imagePath);
|
||||
|
||||
// For unchanged files, check whether thumbnails need upgrade/regeneration
|
||||
let needRegenThumbs = false;
|
||||
if (existing) {
|
||||
const flypicDir = path.join(libraryPath, '.flypic');
|
||||
const filenameOnly = (existing.thumbnail_path || '').replace(/\\/g, '/').split('/').pop();
|
||||
if (filenameOnly) {
|
||||
// Calculate sharded path
|
||||
const hash = filenameOnly.replace(/\.[^/.]+$/, ""); // remove extension
|
||||
const shard1 = hash.slice(0, 2);
|
||||
// New structure: .flypic/thumbnails/ab/hash.webp
|
||||
const expectedPath = path.join(flypicDir, 'thumbnails', shard1, filenameOnly);
|
||||
|
||||
// 需要重建的情况:新结构文件不存在
|
||||
if (!fs.existsSync(expectedPath)) {
|
||||
needRegenThumbs = true;
|
||||
}
|
||||
} else {
|
||||
needRegenThumbs = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip only if unchanged and thumbnails are up-to-date
|
||||
if (existing && existing.file_hash === currentHash && !needRegenThumbs) {
|
||||
return { status: 'skipped', path: relativePath };
|
||||
}
|
||||
|
||||
// Get image metadata
|
||||
const metadata = await getImageMetadata(imagePath);
|
||||
if (!metadata) {
|
||||
return { status: 'error', path: relativePath, error: 'Failed to read metadata' };
|
||||
}
|
||||
|
||||
// Generate thumbnails (also for unchanged files when thumbnails missing/outdated)
|
||||
const thumbnails = await generateImageThumbnails(imagePath, libraryPath);
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
// 使用缩略图的实际尺寸(对于视频/PSD,这是提取后的真实尺寸)
|
||||
const actualWidth = thumbnails.width || metadata.width;
|
||||
const actualHeight = thumbnails.height || metadata.height;
|
||||
|
||||
const imageData = {
|
||||
path: relativePath.replace(/\\/g, '/'),
|
||||
filename: filename,
|
||||
folder: folder,
|
||||
size: metadata.size,
|
||||
width: actualWidth,
|
||||
height: actualHeight,
|
||||
format: metadata.format,
|
||||
file_type: fileType,
|
||||
created_at: Math.floor(metadata.created_at),
|
||||
modified_at: Math.floor(metadata.modified_at),
|
||||
file_hash: currentHash,
|
||||
thumbnail_path: thumbnails.thumbnail_path,
|
||||
thumbnail_size: thumbnails.thumbnail_size
|
||||
};
|
||||
|
||||
if (dryRun) {
|
||||
return { status: 'processed', path: relativePath, data: imageData };
|
||||
}
|
||||
|
||||
// Insert/update in database
|
||||
db.insertImage(imageData);
|
||||
|
||||
return { status: 'processed', path: relativePath };
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', imagePath, error);
|
||||
return { status: 'error', path: imagePath, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan library and update database
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @param {object} db - 数据库实例
|
||||
* @param {function} onProgress - 进度回调
|
||||
* @param {string} libraryId - 素材库ID(用于停止控制)
|
||||
* @param {Array} resumeFiles - 继续扫描时的待处理文件列表
|
||||
*/
|
||||
/**
|
||||
* Scan library and update database
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @param {object} db - 数据库实例
|
||||
* @param {function} onProgress - 进度回调
|
||||
* @param {string} libraryId - 素材库ID(用于停止控制)
|
||||
* @param {Array} resumeFiles - 继续扫描时的待处理文件列表
|
||||
*/
|
||||
async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resumeFiles = null) {
|
||||
try {
|
||||
let files;
|
||||
|
||||
// 动态导入 p-limit
|
||||
const pLimit = (await import('p-limit')).default;
|
||||
|
||||
// 根据 CPU 核心数动态调整并发数
|
||||
const os = require('os');
|
||||
const cpuCount = os.cpus().length;
|
||||
// 默认并发数:核心数 - 1,最小 4,最大 16
|
||||
const concurrency = Math.max(4, Math.min(16, cpuCount - 1));
|
||||
const limit = pLimit(concurrency);
|
||||
|
||||
console.log(`🚀 Starting scan with concurrency: ${concurrency} (CPU cores: ${cpuCount})`);
|
||||
|
||||
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);
|
||||
// 使用事务批量插入文件夹
|
||||
const insertFolders = db.db.transaction((folders) => {
|
||||
for (const folder of folders) db.insertFolder(folder);
|
||||
});
|
||||
insertFolders(folders);
|
||||
}
|
||||
|
||||
const total = files.length;
|
||||
|
||||
// 初始化扫描状态
|
||||
if (libraryId) {
|
||||
scanManager.startScan(libraryId, total);
|
||||
}
|
||||
|
||||
const results = {
|
||||
processed: 0,
|
||||
skipped: 0,
|
||||
errors: 0,
|
||||
stopped: false
|
||||
};
|
||||
|
||||
const startTime = Date.now();
|
||||
let processedCount = 0;
|
||||
|
||||
// 批量写入缓冲区
|
||||
let writeBuffer = [];
|
||||
const WRITE_BATCH_SIZE = 100; // 每 100 条写入一次数据库
|
||||
|
||||
// 批量写入函数(事务)
|
||||
const batchWrite = db.db.transaction((items) => {
|
||||
for (const item of items) {
|
||||
if (item.status === 'processed' && item.data) {
|
||||
db.insertImage(item.data);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 处理单个文件的包装函数
|
||||
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;
|
||||
} catch (error) {
|
||||
return { status: 'error', path: file, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// 创建所有任务
|
||||
const tasks = files.map(file => limit(async () => {
|
||||
// 如果已经停止,直接返回
|
||||
if (results.stopped) return;
|
||||
|
||||
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') {
|
||||
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 (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,
|
||||
canStop: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 性能日志
|
||||
if (processedCount > 0 && processedCount % 1000 === 0) {
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
const speed = processedCount / elapsed;
|
||||
console.log(`⚡ Performance: ${speed.toFixed(1)} images/sec, ${processedCount}/${total} completed`);
|
||||
}
|
||||
}));
|
||||
|
||||
// 等待所有任务完成
|
||||
await Promise.all(tasks);
|
||||
|
||||
// 写入剩余的缓冲区数据
|
||||
if (writeBuffer.length > 0) {
|
||||
batchWrite(writeBuffer);
|
||||
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`);
|
||||
|
||||
// Update folder image counts
|
||||
db.updateAllFolderCounts();
|
||||
|
||||
// 标记扫描完成
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
|
||||
console.log('Scan complete:', results);
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error scanning library:', error);
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync library (incremental scan)
|
||||
*/
|
||||
async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgress = null) {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Get all current files (统一使用正斜杠)
|
||||
const currentFiles = await getAllImageFiles(libraryPath);
|
||||
const currentPaths = new Set(
|
||||
currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/'))
|
||||
);
|
||||
|
||||
// Get database files (已经是正斜杠格式)
|
||||
const dbImages = db.getAllImages();
|
||||
const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/')));
|
||||
|
||||
// Find new, modified, and deleted files
|
||||
const toAdd = [...currentPaths].filter(p => !dbPaths.has(p));
|
||||
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`);
|
||||
|
||||
// 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题
|
||||
if (toDelete.length > 0 && dbImages.length > 0) {
|
||||
const deleteRatio = toDelete.length / dbImages.length;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:要删除 ${toDelete.length}/${dbImages.length} (${(deleteRatio * 100).toFixed(1)}%) 的文件,这可能是路径匹配问题,跳过删除操作`);
|
||||
console.log('示例 currentPath:', [...currentPaths].slice(0, 3));
|
||||
console.log('示例 dbPath:', [...dbPaths].slice(0, 3));
|
||||
// 清空 toDelete,不执行删除
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
|
||||
const total = toAdd.length + toDelete.length;
|
||||
let processed = 0;
|
||||
|
||||
// Process new files in batches
|
||||
const batchSize = 100;
|
||||
for (let i = 0; i < toAdd.length; i += batchSize) {
|
||||
const batch = toAdd.slice(i, i + batchSize);
|
||||
await Promise.all(
|
||||
batch.map(relativePath => {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
return processImage(fullPath, libraryPath, db);
|
||||
})
|
||||
);
|
||||
|
||||
processed += batch.length;
|
||||
|
||||
// 报告进度
|
||||
if (onProgress && total > 0) {
|
||||
onProgress({
|
||||
total,
|
||||
current: processed,
|
||||
percent: Math.round((processed / total) * 100),
|
||||
currentFile: batch[batch.length - 1]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check modified files in batches (只检查hash,不重新处理)
|
||||
const modifiedCount = toCheck.filter(relativePath => {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
const existing = db.getImageByPath(relativePath);
|
||||
const currentHash = calculateFileHash(fullPath);
|
||||
return existing.file_hash !== currentHash;
|
||||
}).length;
|
||||
|
||||
console.log(`Found ${modifiedCount} modified files (skipped, hash unchanged)`);
|
||||
|
||||
// Delete removed files
|
||||
for (const relativePath of toDelete) {
|
||||
db.deleteImage(relativePath);
|
||||
// TODO: Clean up thumbnail files
|
||||
}
|
||||
|
||||
// Rebuild folder structure if there are changes or forced
|
||||
if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) {
|
||||
console.log('Rebuilding folder structure...');
|
||||
|
||||
// Get current folder structure from file system
|
||||
const currentFolders = await getFolderStructure(libraryPath);
|
||||
|
||||
// Get existing folders from database
|
||||
const dbFolders = db.getAllFolders();
|
||||
const dbFolderPaths = new Set(dbFolders.map(f => f.path));
|
||||
|
||||
// Find new and deleted folders
|
||||
const currentFolderPaths = new Set(currentFolders.map(f => f.path));
|
||||
const foldersToAdd = currentFolders.filter(f => !dbFolderPaths.has(f.path));
|
||||
const foldersToDelete = dbFolders.filter(f => !currentFolderPaths.has(f.path));
|
||||
|
||||
// Add new folders
|
||||
foldersToAdd.forEach(folder => {
|
||||
db.insertFolder(folder);
|
||||
});
|
||||
|
||||
// Delete removed folders
|
||||
foldersToDelete.forEach(folder => {
|
||||
db.deleteFolder(folder.path);
|
||||
});
|
||||
|
||||
console.log(`Folders: +${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)
|
||||
[...toAdd, ...toDelete].forEach(relativePath => {
|
||||
let folderPath = path.dirname(relativePath);
|
||||
|
||||
// Add current folder and all parent folders
|
||||
while (folderPath && folderPath !== '.') {
|
||||
affectedFolders.add(folderPath);
|
||||
const parent = path.dirname(folderPath);
|
||||
if (parent === folderPath) break; // Reached root
|
||||
folderPath = parent;
|
||||
}
|
||||
});
|
||||
|
||||
// Update counts for all affected folders
|
||||
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`);
|
||||
|
||||
return {
|
||||
added: toAdd.length,
|
||||
modified: modifiedCount,
|
||||
deleted: toDelete.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error syncing library:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick sync - 只检查新增/删除,不检查修改(用于启动时快速检测)
|
||||
*/
|
||||
async function quickSync(libraryPath, db) {
|
||||
const startTime = Date.now();
|
||||
|
||||
// 获取当前文件(统一使用正斜杠)
|
||||
const currentFiles = await getAllImageFiles(libraryPath);
|
||||
const currentPaths = new Set(
|
||||
currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/'))
|
||||
);
|
||||
|
||||
// 获取数据库文件
|
||||
const dbImages = db.getAllImages();
|
||||
const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/')));
|
||||
|
||||
// 只检查新增和删除(不检查修改)
|
||||
const toAdd = [...currentPaths].filter(p => !dbPaths.has(p));
|
||||
let toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
// 安全检查
|
||||
if (toDelete.length > 0 && dbImages.length > 0) {
|
||||
const deleteRatio = toDelete.length / dbImages.length;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:跳过删除 ${toDelete.length} 个文件`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
|
||||
// 处理新增文件
|
||||
for (const relativePath of toAdd) {
|
||||
try {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
// 确保文件夹链存在
|
||||
const folder = path.dirname(relativePath).replace(/\\/g, '/');
|
||||
if (folder && folder !== '.') {
|
||||
ensureFolderChain(db, folder);
|
||||
}
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (err) {
|
||||
console.error(`Error adding ${relativePath}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 删除已移除的文件
|
||||
for (const relativePath of toDelete) {
|
||||
db.deleteImage(relativePath);
|
||||
}
|
||||
|
||||
// 如果有变化,更新所有文件夹的图片数量
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
console.log(`Quick sync: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
}
|
||||
|
||||
return { added: toAdd.length, deleted: toDelete.length };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getAllImageFiles,
|
||||
getFolderStructure,
|
||||
processImage,
|
||||
scanLibrary,
|
||||
syncLibrary,
|
||||
quickSync,
|
||||
applyChangesFromEvents
|
||||
};
|
||||
@@ -0,0 +1,642 @@
|
||||
const sharp = require('sharp');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 支持的文件格式(确定可以生成缩略图的)
|
||||
const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg'];
|
||||
|
||||
// 文件类型分类(用于显示和占位图)
|
||||
const FILE_CATEGORIES = {
|
||||
// 图片类
|
||||
image: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg', 'ico', 'raw', 'cr2', 'nef', 'dng'],
|
||||
|
||||
// 视频类
|
||||
video: ['mp4', 'webm', 'mov', 'avi', 'mkv', 'flv', 'm4v', 'wmv', 'mpg', 'mpeg', '3gp', 'ts', 'vob', 'ogv'],
|
||||
|
||||
// 音频类
|
||||
audio: ['mp3', 'wav', 'flac', 'aac', 'm4a', 'ogg', 'wma', 'ape', 'alac', 'opus', 'aiff'],
|
||||
|
||||
// 文档类
|
||||
document: [
|
||||
'pdf', 'txt', 'md', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
|
||||
'rtf', 'odt', 'ods', 'odp', 'csv', 'pages', 'numbers', 'key'
|
||||
],
|
||||
|
||||
// 设计类
|
||||
design: ['psd', 'ai', 'sketch', 'xd', 'fig', 'figma', 'indd', 'eps', 'cdr', 'dwg']
|
||||
};
|
||||
|
||||
// 为了兼容旧代码
|
||||
const SUPPORTED_FORMATS = {
|
||||
image: IMAGE_FORMATS,
|
||||
video: FILE_CATEGORIES.video,
|
||||
document: FILE_CATEGORIES.document,
|
||||
special: FILE_CATEGORIES.design
|
||||
};
|
||||
|
||||
// 所有支持的格式(扁平化,兼容所有文件)
|
||||
const ALL_FORMATS = [
|
||||
...FILE_CATEGORIES.image,
|
||||
...FILE_CATEGORIES.video,
|
||||
...FILE_CATEGORIES.audio,
|
||||
...FILE_CATEGORIES.document,
|
||||
...FILE_CATEGORIES.design
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取文件类型分类
|
||||
*/
|
||||
function getFileType(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
|
||||
// 检查所有分类
|
||||
if (FILE_CATEGORIES.image.includes(ext)) return 'image';
|
||||
if (FILE_CATEGORIES.video.includes(ext)) return 'video';
|
||||
if (FILE_CATEGORIES.audio.includes(ext)) return 'audio';
|
||||
if (FILE_CATEGORIES.document.includes(ext)) return 'document';
|
||||
if (FILE_CATEGORIES.design.includes(ext)) return 'design';
|
||||
|
||||
// 未知类型也兼容,归类为 other
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否可以用 Sharp 生成缩略图
|
||||
*/
|
||||
function canGenerateThumbnail(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
return IMAGE_FORMATS.includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is supported
|
||||
*/
|
||||
function isImageFile(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
return ALL_FORMATS.includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate file hash for change detection
|
||||
*/
|
||||
function calculateFileHash(filePath) {
|
||||
const fileBuffer = fs.readFileSync(filePath);
|
||||
const hashSum = crypto.createHash('md5');
|
||||
hashSum.update(fileBuffer);
|
||||
return hashSum.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thumbnail configuration based on original image size
|
||||
* 分阶段策略:根据原图大小使用不同的缩略图尺寸和质量
|
||||
*
|
||||
* 策略说明:
|
||||
* - 小图(<1MP):保持原尺寸或轻微缩小,高质量
|
||||
* - 中图(1-4MP):缩略图 200px 高,高质量
|
||||
* - 大图(4-12MP):缩略图 250px 高,中高质量
|
||||
* - 超大图(>12MP):缩略图 300px 高,中等质量
|
||||
*/
|
||||
function getThumbnailConfig(originalWidth, originalHeight, targetHeight = 200) {
|
||||
const originalPixels = originalWidth * originalHeight;
|
||||
const aspectRatio = originalWidth / originalHeight;
|
||||
|
||||
let finalHeight, finalQuality, targetSize;
|
||||
|
||||
// 分阶段策略 - 提高质量,扩大文件大小
|
||||
if (originalPixels < 1000000) {
|
||||
// 小图 <1MP(如 1000x1000):保持较小尺寸,极高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 95;
|
||||
targetSize = { min: 80 * 1024, max: 240 * 1024 }; // 80-240KB
|
||||
}
|
||||
else if (originalPixels < 4000000) {
|
||||
// 中图 1-4MP(如 2000x2000):标准尺寸,极高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 93;
|
||||
targetSize = { min: 120 * 1024, max: 300 * 1024 }; // 120-300KB
|
||||
}
|
||||
else if (originalPixels < 12000000) {
|
||||
// 大图 4-12MP(如 4000x3000):增大尺寸,高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 91;
|
||||
targetSize = { min: 160 * 1024, max: 400 * 1024 }; // 160-400KB
|
||||
}
|
||||
else {
|
||||
// 超大图 >12MP(如 6000x4000):更大尺寸,高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 89;
|
||||
targetSize = { min: 200 * 1024, max: 500 * 1024 }; // 200-500KB
|
||||
}
|
||||
|
||||
const finalWidth = Math.round(aspectRatio * finalHeight);
|
||||
|
||||
// 计算原图大小(MP)
|
||||
const megaPixels = (originalPixels / 1000000).toFixed(1);
|
||||
|
||||
return {
|
||||
width: finalWidth,
|
||||
height: finalHeight,
|
||||
quality: finalQuality,
|
||||
targetSize: targetSize,
|
||||
format: 'webp',
|
||||
originalPixels: originalPixels,
|
||||
megaPixels: megaPixels
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for an image with high quality settings
|
||||
*
|
||||
* 核心优化点:
|
||||
* 1. 禁用 smartSubsample,保持色彩锐度(关键!)
|
||||
* 2. 使用更强的 unsharp mask 锐化
|
||||
* 3. 固定高质量 Q96,不动态调整
|
||||
* 4. 不修改色彩(饱和度/亮度),保持原图风格
|
||||
*/
|
||||
async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
|
||||
try {
|
||||
// 先读取文件到 Buffer,避免 Sharp 锁定文件句柄
|
||||
const inputBuffer = fs.readFileSync(inputPath);
|
||||
|
||||
// Get image metadata from buffer
|
||||
const metadata = await sharp(inputBuffer).metadata();
|
||||
const config = getThumbnailConfig(metadata.width, metadata.height, targetHeight);
|
||||
const hasAlpha = Boolean(metadata.hasAlpha);
|
||||
|
||||
// 计算缩小比例,用于调整锐化强度
|
||||
const downscaleRatio = metadata.height ? (metadata.height / config.height) : 1;
|
||||
|
||||
// 锐化参数:根据缩小比例动态调整
|
||||
// sharpen(sigma, flat, jagged) - sigma: 高斯模糊半径, flat: 平坦区域锐化, jagged: 边缘锐化
|
||||
let sharpSigma, sharpFlat, sharpJagged;
|
||||
if (downscaleRatio >= 4) {
|
||||
// 大幅缩小(如 4000px → 300px):强锐化
|
||||
sharpSigma = 1.2;
|
||||
sharpFlat = 1.0;
|
||||
sharpJagged = 2.0;
|
||||
} else if (downscaleRatio >= 2) {
|
||||
// 中等缩小:中等锐化
|
||||
sharpSigma = 1.0;
|
||||
sharpFlat = 0.8;
|
||||
sharpJagged = 1.5;
|
||||
} else {
|
||||
// 轻微缩小或不缩小:轻度锐化
|
||||
sharpSigma = 0.8;
|
||||
sharpFlat = 0.5;
|
||||
sharpJagged = 1.0;
|
||||
}
|
||||
|
||||
// 固定高质量 92(平衡清晰度和体积)
|
||||
const quality = 92;
|
||||
|
||||
// 生成缩略图(使用 buffer,不锁定原文件)
|
||||
await sharp(inputBuffer)
|
||||
.rotate() // 按EXIF旋转
|
||||
.resize(config.width, config.height, {
|
||||
fit: 'cover',
|
||||
position: 'center',
|
||||
kernel: 'lanczos3', // 最高质量缩放算法
|
||||
withoutEnlargement: true,
|
||||
fastShrinkOnLoad: false // 禁用快速缩小,保持质量
|
||||
})
|
||||
// 锐化:使用完整的 unsharp mask 参数(不修改色彩)
|
||||
.sharpen({
|
||||
sigma: sharpSigma, // 高斯模糊半径
|
||||
m1: sharpFlat, // 平坦区域锐化强度
|
||||
m2: sharpJagged, // 边缘/锯齿区域锐化强度
|
||||
x1: 2, // 平坦区域阈值
|
||||
y2: 10, // 边缘区域阈值上限
|
||||
y3: 20 // 最大锐化限制
|
||||
})
|
||||
.webp({
|
||||
quality: quality,
|
||||
effort: 4, // 降低 effort,减少编码损失
|
||||
smartSubsample: false, // 关键!禁用色度子采样,保持边缘清晰
|
||||
nearLossless: false, // 禁用近无损(会增加体积但不增加清晰度)
|
||||
preset: 'photo',
|
||||
alphaQuality: hasAlpha ? 100 : undefined
|
||||
})
|
||||
.toFile(outputPath);
|
||||
|
||||
// 获取文件大小
|
||||
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,
|
||||
size: finalSize,
|
||||
quality: quality,
|
||||
originalPixels: config.originalPixels,
|
||||
path: outputPath
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error generating thumbnail:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file metadata (支持所有文件类型)
|
||||
* 优化:优先使用流式读取,避免加载整个文件到内存
|
||||
*/
|
||||
async function getImageMetadata(imagePath) {
|
||||
try {
|
||||
const stats = fs.statSync(imagePath);
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
// 对于图片文件,尝试获取详细元数据
|
||||
if (fileType === 'image') {
|
||||
try {
|
||||
// 优化:直接传入路径,让 sharp 使用流式读取,仅读取头部元数据
|
||||
// 只有在失败时才回退到 Buffer 读取
|
||||
const metadata = await sharp(imagePath).metadata();
|
||||
return {
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
format: metadata.format,
|
||||
size: stats.size,
|
||||
created_at: stats.birthtimeMs,
|
||||
modified_at: stats.mtimeMs
|
||||
};
|
||||
} catch (sharpError) {
|
||||
// Sharp 无法处理某些图片格式(如 SVG)或路径问题,回退到基础信息
|
||||
// console.warn(`Sharp cannot process ${imagePath}, using basic metadata`);
|
||||
}
|
||||
}
|
||||
|
||||
// 对于非图片文件或 Sharp 失败的情况,返回基础信息
|
||||
const ext = path.extname(imagePath).toLowerCase().slice(1);
|
||||
return {
|
||||
width: 640, // 占位图尺寸
|
||||
height: 480,
|
||||
format: ext,
|
||||
size: stats.size,
|
||||
created_at: stats.birthtimeMs,
|
||||
modified_at: stats.mtimeMs
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error getting file metadata:', imagePath, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for a file (image/video/document)
|
||||
* 使用 480px 高度(与 Billfish 一致)
|
||||
*/
|
||||
async function generateImageThumbnails(imagePath, libraryPath) {
|
||||
const flypicDir = path.join(libraryPath, '.flypic');
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
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
|
||||
const out480 = path.join(flypicDir, 'thumbnails', shard1, `${hash}.webp`);
|
||||
fs.mkdirSync(path.dirname(out480), { recursive: true });
|
||||
|
||||
let thumbnailResult;
|
||||
|
||||
// 根据文件类型生成不同的缩略图
|
||||
const ext = path.extname(imagePath).slice(1).toUpperCase();
|
||||
|
||||
if (fileType === 'image' && canGenerateThumbnail(imagePath)) {
|
||||
// 图片:使用 Sharp 生成真实缩略图
|
||||
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`);
|
||||
|
||||
return {
|
||||
thumbnail_path: path.relative(flypicDir, out480),
|
||||
thumbnail_size: thumbnailResult.size,
|
||||
width: thumbnailResult.width,
|
||||
height: thumbnailResult.height,
|
||||
file_type: fileType
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 PSD 文件提取嵌入的缩略图
|
||||
*/
|
||||
async function extractPSDThumbnail(psdPath, outputPath) {
|
||||
try {
|
||||
const buffer = fs.readFileSync(psdPath);
|
||||
|
||||
// PSD 文件格式:
|
||||
// 前 4 字节: "8BPS" (签名)
|
||||
// 偏移 26: Image Resources Section
|
||||
// 查找 Resource ID 1036 (缩略图资源)
|
||||
|
||||
if (buffer.toString('utf8', 0, 4) !== '8BPS') {
|
||||
throw new Error('Not a valid PSD file');
|
||||
}
|
||||
|
||||
// 读取 Image Resources Section 长度
|
||||
const colorModeLength = buffer.readUInt32BE(26);
|
||||
const imageResourcesOffset = 26 + 4 + colorModeLength;
|
||||
const imageResourcesLength = buffer.readUInt32BE(imageResourcesOffset);
|
||||
|
||||
let offset = imageResourcesOffset + 4;
|
||||
const endOffset = offset + imageResourcesLength;
|
||||
|
||||
// 查找缩略图资源 (ID 1033 或 1036)
|
||||
while (offset < endOffset) {
|
||||
const signature = buffer.toString('utf8', offset, offset + 4);
|
||||
if (signature !== '8BIM') break;
|
||||
|
||||
const resourceId = buffer.readUInt16BE(offset + 4);
|
||||
const nameLength = buffer.readUInt8(offset + 6);
|
||||
const namePadding = nameLength % 2 === 0 ? nameLength + 2 : nameLength + 1;
|
||||
const dataSize = buffer.readUInt32BE(offset + 6 + namePadding);
|
||||
const dataPadding = dataSize % 2 === 0 ? dataSize : dataSize + 1;
|
||||
|
||||
// 1033 = 缩略图 (旧格式), 1036 = 缩略图 (新格式)
|
||||
if (resourceId === 1033 || resourceId === 1036) {
|
||||
const dataOffset = offset + 6 + namePadding + 4;
|
||||
|
||||
// 跳过前 28 字节的头部信息
|
||||
const jpegOffset = dataOffset + 28;
|
||||
const jpegData = buffer.slice(jpegOffset, jpegOffset + dataSize - 28);
|
||||
|
||||
// 先获取原始缩略图尺寸
|
||||
const metadata = await sharp(jpegData).metadata();
|
||||
console.log(` 📐 PSD embedded thumbnail: ${metadata.width}x${metadata.height}`);
|
||||
|
||||
// 使用高质量缩放,保持宽高比
|
||||
const aspectRatio = metadata.width / metadata.height;
|
||||
const targetHeight = 480;
|
||||
const targetWidth = Math.round(targetHeight * aspectRatio);
|
||||
|
||||
// 根据原始尺寸调整处理策略
|
||||
let resizeOptions, sharpenOptions, webpQuality;
|
||||
|
||||
if (metadata.width >= 1000 || metadata.height >= 1000) {
|
||||
// 高分辨率缩略图(≥1000px):正常缩放
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: true
|
||||
};
|
||||
sharpenOptions = { sigma: 0.8, m1: 0.5, m2: 1.0 };
|
||||
webpQuality = 95;
|
||||
} else if (metadata.width >= 500 || metadata.height >= 500) {
|
||||
// 中等分辨率(500-1000px):轻微放大 + 强锐化
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: false // 允许放大
|
||||
};
|
||||
sharpenOptions = { sigma: 1.2, m1: 1.0, m2: 2.0 }; // 强锐化
|
||||
webpQuality = 96;
|
||||
} else {
|
||||
// 低分辨率(<500px):放大 + 超强锐化
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: false
|
||||
};
|
||||
sharpenOptions = { sigma: 1.5, m1: 1.2, m2: 2.5 }; // 超强锐化
|
||||
webpQuality = 98; // 最高质量
|
||||
}
|
||||
|
||||
await sharp(jpegData)
|
||||
.resize(targetWidth, targetHeight, resizeOptions)
|
||||
.sharpen(sharpenOptions)
|
||||
.webp({
|
||||
quality: webpQuality,
|
||||
effort: 4,
|
||||
smartSubsample: false
|
||||
})
|
||||
.toFile(outputPath);
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
console.log(` ✅ PSD thumbnail extracted: ${(stats.size / 1024).toFixed(1)}KB`);
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
offset += 6 + namePadding + 4 + dataPadding;
|
||||
}
|
||||
|
||||
throw new Error('No thumbnail found in PSD');
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract PSD thumbnail: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从视频提取封面(使用 ffmpeg 或系统工具)
|
||||
* 注意:这需要系统安装 ffmpeg,如果没有则回退到占位图
|
||||
*/
|
||||
async function extractVideoThumbnail(videoPath, outputPath) {
|
||||
try {
|
||||
const { exec } = require('child_process');
|
||||
const util = require('util');
|
||||
const execPromise = util.promisify(exec);
|
||||
|
||||
// 检查是否有 ffmpeg
|
||||
try {
|
||||
await execPromise('ffmpeg -version', { timeout: 2000 });
|
||||
} catch (e) {
|
||||
console.warn(' ⚠️ ffmpeg not found, skipping video thumbnail extraction');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 使用 ffmpeg 提取第 2 秒的帧(避免黑屏)
|
||||
const tempJpg = outputPath.replace('.webp', '_temp.jpg');
|
||||
const ffmpegCmd = `ffmpeg -i "${videoPath}" -ss 00:00:02 -vframes 1 -q:v 2 "${tempJpg}" -y`;
|
||||
|
||||
await execPromise(ffmpegCmd, { timeout: 10000 });
|
||||
|
||||
// 如果生成了 JPG,转换为 WebP
|
||||
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;
|
||||
const targetHeight = 480;
|
||||
const targetWidth = Math.round(targetHeight * aspectRatio);
|
||||
|
||||
await sharp(tempJpg)
|
||||
.resize(targetWidth, targetHeight, {
|
||||
fit: 'cover',
|
||||
position: 'center',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: true
|
||||
})
|
||||
.webp({ quality: 92, smartSubsample: false })
|
||||
.toFile(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,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.warn(` ⚠️ Failed to extract video thumbnail: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成占位缩略图(用于视频/文档等)
|
||||
*/
|
||||
async function generatePlaceholderThumbnail(outputPath, type, label) {
|
||||
// 使用 Sharp 生成简单的占位图
|
||||
const width = 640;
|
||||
const height = 480;
|
||||
|
||||
// 不同类型的背景色和图标
|
||||
const typeConfig = {
|
||||
image: {
|
||||
color: { r: 99, g: 102, b: 241 }, // 靛蓝色
|
||||
icon: '🖼️',
|
||||
text: '图片'
|
||||
},
|
||||
video: {
|
||||
color: { r: 59, g: 130, b: 246 }, // 蓝色
|
||||
icon: '🎬',
|
||||
text: '视频'
|
||||
},
|
||||
audio: {
|
||||
color: { r: 236, g: 72, b: 153 }, // 粉色
|
||||
icon: '🎵',
|
||||
text: '音频'
|
||||
},
|
||||
document: {
|
||||
color: { r: 16, g: 185, b: 129 }, // 绿色
|
||||
icon: '📄',
|
||||
text: '文档'
|
||||
},
|
||||
design: {
|
||||
color: { r: 168, g: 85, b: 247 }, // 紫色
|
||||
icon: '🎨',
|
||||
text: '设计'
|
||||
},
|
||||
other: {
|
||||
color: { r: 107, g: 114, b: 128 }, // 灰色
|
||||
icon: '📁',
|
||||
text: '其他'
|
||||
}
|
||||
};
|
||||
|
||||
const config = typeConfig[type] || typeConfig.other;
|
||||
|
||||
const color = config.color;
|
||||
|
||||
// 创建渐变背景 + 图标 + 文件扩展名
|
||||
const svg = `
|
||||
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:rgb(${color.r},${color.g},${color.b});stop-opacity:0.15" />
|
||||
<stop offset="100%" style="stop-color:rgb(${color.r},${color.g},${color.b});stop-opacity:0.05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="${width}" height="${height}" fill="url(#grad)"/>
|
||||
<text x="50%" y="35%" font-family="Arial, sans-serif" font-size="100" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.35">
|
||||
${config.icon}
|
||||
</text>
|
||||
<text x="50%" y="55%" font-family="Arial, sans-serif" font-size="48" font-weight="700" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.7">
|
||||
.${label.toLowerCase()}
|
||||
</text>
|
||||
<text x="50%" y="68%" font-family="Arial, sans-serif" font-size="24" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.5">
|
||||
${config.text}文件
|
||||
</text>
|
||||
<text x="50%" y="78%" font-family="Arial, sans-serif" font-size="18" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.4">
|
||||
双击在默认应用中打开
|
||||
</text>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
await sharp(Buffer.from(svg))
|
||||
.resize(640, 480)
|
||||
.webp({ quality: 85 })
|
||||
.toFile(outputPath);
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
return {
|
||||
width: 640,
|
||||
height: 480,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件类型对应的图标(Unicode)
|
||||
*/
|
||||
function getIconForType(type) {
|
||||
const icons = {
|
||||
video: '🎬',
|
||||
document: '📄',
|
||||
special: '🎨'
|
||||
};
|
||||
return icons[type] || '📁';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isImageFile,
|
||||
getFileType,
|
||||
calculateFileHash,
|
||||
getThumbnailConfig,
|
||||
generateThumbnail,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails,
|
||||
SUPPORTED_FORMATS,
|
||||
ALL_FORMATS
|
||||
};
|
||||
Reference in new issue
Block a user