优化 素材库新增处理优化,提速,其余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

+6 -5
View File
@@ -1,6 +1,6 @@
# FlyPic 飞图
专为飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用。
主要飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用。
## ✨ 核心特性
@@ -8,18 +8,19 @@
- 🛡️ **非侵入式** - 只在素材库目录创建 .flypic 文件夹存储索引和缩略图,不修改任何原始文件
- 🔄 **实时同步** - 基于 Worker Thread 的文件监控,自动检测新增、删除、修改
- 🌐 **远程访问** - 支持 FN Connect 远程访问,随时随地浏览管理图片素材库
- 🎨 **现代界面** - Google Photos 风格瀑布流布局,支持亮色/暗色主题,响应式设计
- 🎨 **现代界面** - 固定行高瀑布流布局,支持亮色/暗色主题,响应式设计
- 🔍 **智能搜索** - 多关键词组合搜索,高级筛选(格式/大小/方向)
- 📱 **移动适配** - 响应式设计,手机上也能流畅使用
- 🆓 **开源免费** - 100% 开源,MIT 协议
- 其他平台
## 🛠️ 技术栈
**前端**:React 18 + Vite 5 + TailwindCSS + Zustand + react-window + react-photo-view + Lucide Icons
**前端**:React 18 + Vite 5 + TailwindCSS + Zustand + react-window + react-photo-view
**后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO + chokidar
**后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO
**架构**:三层架构(Config → Model → Service → Route)+ 模块化前端(Store → API → Components)
**架构**:三层架构(Config → Model → Service → Route)+ 模块化前端(Store → Hooks → API)
## 🚀 快速开始
+27 -10
View File
@@ -19,19 +19,23 @@ class LibraryDatabase {
this.db = new Database(this.dbPath);
// 超激进内存优化配置
// 使用 DELETE 模式而非 WAL(WAL 可能导致内存泄漏)
this.db.pragma('journal_mode = DELETE'); // 使用 DELETE 模式(更低内存)
// 优化数据库性能
this.db.pragma('journal_mode = WAL'); // 启用 WAL 模式,支持并发读写
this.db.pragma('synchronous = NORMAL'); // 平衡性能和安全性
this.db.pragma('cache_size = -4096'); // 4MB 缓存(超激进:从8MB降至4MB)
this.db.pragma('temp_store = FILE'); // 临时表存储在磁盘
this.db.pragma('mmap_size = 0'); // 禁用内存映射
this.db.pragma('page_size = 4096'); // 4KB 页面大小(减少内存占用)
console.log('[LibraryDatabase] Ultra-aggressive memory optimization applied:');
console.log(' cache_size: 4MB, temp_store: FILE, mmap_size: 0, page_size: 4KB');
this.db.pragma('cache_size = -64000'); // 64MB 缓存
this.db.pragma('temp_store = MEMORY'); // 临时表存储在内存
this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射
this.initTables();
// 启动 WAL 定期 checkpoint(每 5 分钟)
this.walCheckpointInterval = setInterval(() => {
try {
this.db.pragma('wal_checkpoint(PASSIVE)');
} catch (e) {
console.warn('[DB] WAL checkpoint warning:', e.message);
}
}, 300000); // 5 分钟
}
initTables() {
@@ -400,6 +404,19 @@ class LibraryDatabase {
}
close() {
// 清理 WAL checkpoint 定时器
if (this.walCheckpointInterval) {
clearInterval(this.walCheckpointInterval);
this.walCheckpointInterval = null;
}
// 执行最后一次 checkpoint
try {
this.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn('[DB] Final WAL checkpoint warning:', e.message);
}
this.db.close();
}
}
+33 -44
View File
@@ -6,9 +6,14 @@ const LibraryDatabase = require('./db');
*/
class DatabasePool {
constructor() {
// 单例模式:确保只有一个实例,避免多个定时器
if (DatabasePool.instance) {
return DatabasePool.instance;
}
DatabasePool.instance = this;
this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount }
this.maxConnections = 1; // 最大连接数:1
this.maxIdleTime = 60000; // 60秒未使用则关闭(保持连接复用,减少创建/关闭)
this.maxIdleTime = 60000; // 60秒未使用则关闭
this.cleanupInterval = null;
// 启动定期清理
@@ -23,16 +28,6 @@ class DatabasePool {
let conn = this.connections.get(libraryPath);
if (!conn) {
// 强制执行最大连接数限制:如果已有连接,先关闭所有空闲连接
if (this.connections.size >= this.maxConnections) {
for (const [path, existingConn] of this.connections.entries()) {
if (existingConn.refCount === 0) {
console.log(`[DBPool] Max connections reached, closing idle: ${path}`);
this.close(path);
}
}
}
// 创建新连接
const db = new LibraryDatabase(libraryPath);
conn = {
@@ -41,7 +36,6 @@ class DatabasePool {
refCount: 0
};
this.connections.set(libraryPath, conn);
console.log(`[DBPool] Created new connection for: ${libraryPath} (total: ${this.connections.size}/${this.maxConnections})`);
}
// 更新使用时间和引用计数
@@ -72,17 +66,19 @@ class DatabasePool {
// 强制设置引用计数为0
conn.refCount = 0;
// 关闭数据库连接
// 执行 checkpoint 确保 WAL 写入主数据库
if (conn.db && conn.db.db) {
// 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint
// 直接关闭连接即可
conn.db.close();
try {
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
}
}
conn.db.close();
this.connections.delete(libraryPath);
console.log(`[DBPool] Closed connection for: ${libraryPath}`);
} catch (error) {
console.error(`[DBPool] Error closing connection:`, error);
console.error(`❌ 关闭数据库连接失败:`, error.message);
// 即使出错也删除引用
this.connections.delete(libraryPath);
}
@@ -93,27 +89,28 @@ class DatabasePool {
* 关闭所有连接
*/
closeAll() {
console.log(`[DBPool] Closing all connections (${this.connections.size} total)`);
for (const [path, conn] of this.connections.entries()) {
try {
// 强制设置引用计数为0
conn.refCount = 0;
// 注意:db.js 使用 DELETE 模式而非 WAL,无需 checkpoint
// 直接关闭连接即可
conn.db.close();
console.log(`[DBPool] Closed connection for: ${path}`);
} catch (error) {
console.error(`[DBPool] Error closing connection for ${path}:`, error);
}
}
this.connections.clear();
// 先清理定时器,避免在关闭过程中触发清理
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
for (const [path, conn] of this.connections.entries()) {
try {
// 执行 checkpoint 确保 WAL 写入主数据库
if (conn.db && conn.db.db) {
try {
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
}
}
conn.db.close();
} catch (error) {
console.error(`❌ 关闭数据库连接失败:`, error.message);
}
}
this.connections.clear();
}
/**
@@ -121,7 +118,6 @@ class DatabasePool {
* 与 closeAll() 相同,但提供明确的语义
*/
forceCloseAll() {
console.log('[DBPool] Force closing all connections (emergency cleanup)');
this.closeAll();
}
@@ -144,14 +140,11 @@ class DatabasePool {
toClose.forEach(path => this.close(path));
if (toClose.length > 0) {
console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`);
// 关闭连接后立即强制 GC
if (global.gc) {
for (let i = 0; i < 3; i++) {
global.gc();
}
console.log(`[DBPool] Forced GC after closing connections`);
}
}
}, 10000); // 每10秒检查一次(更频繁)
@@ -191,10 +184,6 @@ class DatabasePool {
}
toClose.forEach(path => this.close(path));
if (toClose.length > 0) {
console.log(`[DBPool] Cleared ${toClose.length} idle connections`);
}
}
}
+2 -2
View File
@@ -4,8 +4,8 @@
"description": "FlyPic backend server",
"main": "server.js",
"scripts": {
"dev": "cross-env PORT=15002 nodemon server.js",
"start": "node server.js"
"dev": "cross-env PORT=15002 nodemon --expose-gc server.js",
"start": "node --expose-gc server.js"
},
"dependencies": {
"better-sqlite3": "^9.2.2",
+90 -25
View File
@@ -35,13 +35,13 @@ if (!FRONTEND_DIST) {
for (const p of possiblePaths) {
if (fs.existsSync(p)) {
FRONTEND_DIST = p;
console.log('✅ Found frontend at:', p);
console.log('✅ 前端目录:', p);
break;
}
}
if (!FRONTEND_DIST) {
console.log('⚠️ Frontend not found, API-only mode');
console.log('⚠️ 未找到前端,API模式');
}
}
@@ -89,15 +89,18 @@ server.on('request', app);
// Socket.IO 连接处理
io.on('connection', (socket) => {
console.log('✅ Socket.IO client connected:', socket.id);
console.log('✅ 客户端连接:', socket.id);
socket.on('disconnect', () => {
console.log('❌ Socket.IO client disconnected:', socket.id);
console.log('❌ 客户端断开:', socket.id);
});
});
// 启动内存监控
const memoryMonitor = new MemoryMonitor();
// 启动内存监控(开发模式:每30秒输出RSS)
const memoryMonitor = new MemoryMonitor({
devMode: true,
devLogInterval: 30000 // 30秒
});
memoryMonitor.start();
// 启动清理管理器
@@ -106,36 +109,95 @@ cleanupManager.startRoutineCleanup();
// 启动服务器
server.listen(PORT, () => {
console.log('\n🚀 FlyPic Server (New Architecture) Started');
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.log(`📡 Server running on http://localhost:${PORT}`);
console.log(`🔌 Socket.IO ready`);
console.log(`📁 Frontend: ${FRONTEND_DIST || 'Not found (API-only mode)'}`);
console.log(`🏗️ Architecture: Config → Model → Service → Route`);
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
// 为当前素材库启动文件监控
console.log('\n🚀 FlyPic 服务器已启动');
console.log(`📡 端口: ${PORT}`);
console.log(`🔌 Socket.IO 就绪`);
if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`);
console.log('');
try {
const currentConfig = config.loadConfig();
// 恢复所有素材库的扫描状态
if (currentConfig.libraries && currentConfig.libraries.length > 0) {
scanManager.restoreAllStates(currentConfig.libraries);
// 检查是否有未完成的扫描,自动继续
const activeStates = scanManager.getAllActiveStates();
if (Object.keys(activeStates).length > 0) {
console.log(`📊 发现 ${Object.keys(activeStates).length} 个活跃扫描`);
}
for (const [libraryId, state] of Object.entries(activeStates)) {
const lib = currentConfig.libraries.find(l => l.id === libraryId);
if (lib && state.status === 'scanning') {
console.log(`🔄 恢复扫描: ${lib.name} (${state.progress?.percent || 0}%)`);
// 立即恢复扫描状态(让前端能检测到)
scanManager.scanStates.set(libraryId, {
status: 'scanning',
progress: state.progress || { current: 0, total: 0, percent: 0 },
startTime: state.startTime || Date.now()
});
// 立即向所有连接的客户端推送扫描状态
io.emit('scanProgress', {
libraryId,
...state.progress,
resuming: true
});
// 延迟启动实际扫描,等服务完全准备好
setTimeout(() => {
const db = dbPool.acquire(lib.path);
// 继续扫描(从中断处继续)
scanner.scanLibrary(
lib.path,
db,
(progress) => {
io.emit('scanProgress', { libraryId, ...progress });
},
libraryId
).then(() => {
scanManager.completeScan(libraryId);
io.emit('scanComplete', { libraryId });
dbPool.release(lib.path);
console.log(`✅ 扫描完成: ${lib.name}`);
}).catch((err) => {
console.error(`❌ 扫描失败: ${lib.name}`, err.message);
scanManager.completeScan(libraryId);
dbPool.release(lib.path);
});
}, 2000);
}
}
}
// 为当前素材库启动文件监控
if (currentConfig.currentLibraryId) {
const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId);
if (currentLib) {
lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io);
console.log(`📂 File watcher started for: ${currentLib.name}`);
}
}
} catch (e) {
console.warn('⚠️ Failed to start file watcher:', e.message);
console.warn('⚠️ 初始化失败:', e.message);
}
});
// 标记是否正在关闭
let isShuttingDown = false;
// 优雅关闭
const shutdown = async () => {
console.log('\n🛑 Shutting down gracefully...');
if (isShuttingDown) return;
isShuttingDown = true;
console.log('\n🛑 正在关闭服务器...');
// 停止接受新连接
server.close(() => {
console.log('✅ HTTP server closed');
console.log('✅ HTTP 服务器已关闭');
});
// 停止监控
@@ -145,27 +207,30 @@ const shutdown = async () => {
// 停止所有文件监控
lightweightWatcher.stopAll();
// 等待扫描任务完成当前批次(最多等2秒)
await new Promise(resolve => setTimeout(resolve, 2000));
// 关闭所有数据库连接
dbPool.closeAll();
// 等待资源释放
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('✅ Shutdown complete');
console.log('✅ 关闭完成');
process.exit(0);
};
// 导出关闭状态供其他模块检查
module.exports.isShuttingDown = () => isShuttingDown;
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
// 错误处理
process.on('uncaughtException', (error) => {
console.error('💥 Uncaught Exception:', error);
console.error('💥 未捕获异常:', error.message);
shutdown();
});
process.on('unhandledRejection', (reason, promise) => {
console.error('💥 Unhandled Rejection at:', promise, 'reason:', reason);
console.error('💥 未处理的Promise拒绝:', reason);
shutdown();
});
+3 -23
View File
@@ -103,52 +103,32 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.get('/thumbnail/:libraryId/:filename', (req, res) => {
const { libraryId, filename } = req.params;
console.log(`[Thumbnail] ========== NEW REQUEST ==========`);
console.log(`[Thumbnail] LibraryId: ${libraryId}, Filename: ${filename}`);
try {
const config = require('../../utils/config').loadConfig();
console.log(`[Thumbnail] All libraries:`, config.libraries.map(l => ({ id: l.id, type: typeof l.id })));
// 尝试两种方式查找:数字和字符串
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
if (!library) {
library = config.libraries.find(lib => lib.id == libraryId); // 使用 == 宽松比较
library = config.libraries.find(lib => lib.id == libraryId);
}
if (!library) {
console.log(`[Thumbnail] Library not found: ${libraryId} (type: ${typeof libraryId})`);
return res.status(404).send('Library not found');
}
console.log(`[Thumbnail] Library path: ${library.path}`);
// 使用分片结构:取文件名前2个字符作为分片目录
const hash = filename.replace(/\.[^/.]+$/, ''); // 移除扩展名
const hash = filename.replace(/\.[^/.]+$/, '');
const shard = hash.slice(0, 2);
const flypicPath = getFlypicPath(library.path);
const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename);
console.log(`[Thumbnail] Hash: ${hash}, Shard: ${shard}`);
console.log(`[Thumbnail] Full path: ${thumbnailPath}`);
console.log(`[Thumbnail] File exists: ${fs.existsSync(thumbnailPath)}`);
if (!fs.existsSync(thumbnailPath)) {
// 列出分片目录的内容
const shardDir = path.join(flypicPath, 'thumbnails', shard);
if (fs.existsSync(shardDir)) {
const files = fs.readdirSync(shardDir);
console.log(`[Thumbnail] Files in shard dir (${shard}):`, files.slice(0, 5));
} else {
console.log(`[Thumbnail] Shard directory does not exist: ${shardDir}`);
}
return res.status(404).send('Thumbnail not found');
}
console.log(`[Thumbnail] ✅ Serving file`);
res.sendFile(thumbnailPath);
} catch (error) {
console.error('[Thumbnail] Error:', error);
console.error('❌ 缩略图错误:', error.message);
res.status(500).send('Error serving thumbnail');
}
});
+9 -28
View File
@@ -46,34 +46,6 @@ router.post('/sync',
})
);
/**
* 停止扫描
* POST /api/scan/stop
* Body: { libraryId }
*/
router.post('/stop',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId } = req.body;
const result = scanService.stopScan(libraryId);
res.json({ success: true, data: result });
})
);
/**
* 继续扫描
* POST /api/scan/resume
* Body: { libraryId }
*/
router.post('/resume',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId } = req.body;
const result = scanService.resumeScan(libraryId);
res.json({ success: true, data: result });
})
);
/**
* 获取扫描状态
* GET /api/scan/status/:libraryId
@@ -84,6 +56,15 @@ router.get('/status/:libraryId', asyncHandler(async (req, res) => {
res.json({ success: true, data: result });
}));
/**
* 获取所有活跃的扫描状态
* GET /api/scan/active-states
*/
router.get('/active-states', asyncHandler(async (req, res) => {
const result = scanService.getAllActiveStates();
res.json({ success: true, data: result });
}));
/**
* 修复文件夹路径
* POST /api/scan/fix-folders
+42 -5
View File
@@ -39,23 +39,60 @@ class LibraryService {
throw new ValidationError('Name and path are required');
}
if (!fs.existsSync(libraryPath)) {
// 规范化路径
const normalizedPath = path.normalize(libraryPath);
console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`);
if (!fs.existsSync(normalizedPath)) {
console.log(`[LibraryService] Path does not exist: ${normalizedPath}`);
throw new ValidationError('Path does not exist', 'path');
}
// 检查文件夹访问权限
try {
// 尝试读取目录
fs.readdirSync(normalizedPath);
// 尝试在目录中创建测试文件(检查写权限)
const testFile = path.join(normalizedPath, '.flypic-test');
try {
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
} catch (writeError) {
console.log(`[LibraryService] No write permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
} catch (readError) {
if (readError.code === 'EACCES' || readError.code === 'EPERM') {
console.log(`[LibraryService] No access permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
// 如果不是权限错误,继续抛出
if (readError.name !== 'ValidationError') {
throw readError;
}
throw readError;
}
// 检查路径是否已存在
const config = this.configManager.load();
const existingLib = config.libraries.find(lib => lib.path === libraryPath);
const existingLib = config.libraries.find(lib => lib.path === normalizedPath);
if (existingLib) {
throw new ValidationError('Library path already exists', 'path');
}
// 创建素材库
const id = this.configManager.addLibrary(name, libraryPath);
const id = this.configManager.addLibrary(name, normalizedPath);
// 检查是否有现有索引
const flypicDir = getFlypicPath(libraryPath);
const dbPath = getDatabasePath(libraryPath);
const flypicDir = getFlypicPath(normalizedPath);
const dbPath = getDatabasePath(normalizedPath);
const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath);
return {
+25 -114
View File
@@ -1,6 +1,6 @@
/**
* 扫描服务层
* 封装扫描相关的业务逻辑
* 扫描服务层(简化版)
* 无暂停功能,只负责扫描和进度推送
*/
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
@@ -22,35 +22,21 @@ class ScanService {
const db = this.dbPool.acquire(library.path);
try {
// 检查是否已在扫描
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
// 开始扫描
if (wait) {
// 同步模式:等待扫描完成
await this.scanner.scanLibrary(
library.path,
db,
(progress) => this._emitProgress(libraryId, progress)
);
return {
success: true,
message: 'Scan completed',
(progress) => this._emitProgress(libraryId, progress),
libraryId
};
);
return { success: true, message: 'Scan completed', libraryId };
} else {
// 异步模式:后台扫描
this._startAsyncScan(libraryId, library.path, db);
return {
success: true,
message: 'Scan started',
libraryId,
async: true
};
return { success: true, message: 'Scan started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
@@ -66,35 +52,21 @@ class ScanService {
const db = this.dbPool.acquire(library.path);
try {
// 检查是否已在扫描
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
// 开始增量同步
if (wait) {
// 同步模式
await this.scanner.incrementalSync(
await this.scanner.syncLibrary(
library.path,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
);
return {
success: true,
message: 'Sync completed',
libraryId
};
return { success: true, message: 'Sync completed', libraryId };
} else {
// 异步模式
this._startAsyncSync(libraryId, library.path, db);
return {
success: true,
message: 'Sync started',
libraryId,
async: true
};
return { success: true, message: 'Sync started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
@@ -102,44 +74,6 @@ class ScanService {
}
}
/**
* 停止扫描
*/
stopScan(libraryId) {
const library = this._getLibrary(libraryId);
if (!this.scanManager.isScanning(libraryId)) {
throw new ValidationError('No scan in progress', 'libraryId');
}
this.scanManager.pauseScan(libraryId);
return {
success: true,
message: 'Scan stopped',
libraryId
};
}
/**
* 继续扫描
*/
resumeScan(libraryId) {
const library = this._getLibrary(libraryId);
if (!this.scanManager.isPaused(libraryId)) {
throw new ValidationError('No paused scan found', 'libraryId');
}
this.scanManager.resumeScan(libraryId);
return {
success: true,
message: 'Scan resumed',
libraryId
};
}
/**
* 获取扫描状态
*/
@@ -149,13 +83,19 @@ class ScanService {
return {
libraryId,
isScanning: this.scanManager.isScanning(libraryId),
isPaused: this.scanManager.isPaused(libraryId),
status: state?.status || 'idle',
progress: state?.progress || null,
startTime: state?.startTime || null
};
}
/**
* 获取所有活跃状态
*/
getAllActiveStates() {
return this.scanManager.getAllActiveStates();
}
/**
* 修复文件夹路径
*/
@@ -165,12 +105,7 @@ class ScanService {
try {
await this.scanner.fixFolderPaths(library.path, db);
return {
success: true,
message: 'Folders fixed',
libraryId
};
return { success: true, message: 'Folders fixed', libraryId };
} finally {
this.dbPool.release(library.path);
}
@@ -178,13 +113,13 @@ class ScanService {
/**
* 启动异步扫描
* @private
*/
_startAsyncScan(libraryId, libraryPath, db) {
this.scanner.scanLibrary(
libraryPath,
db,
(progress) => this._emitProgress(libraryId, progress)
(progress) => this._emitProgress(libraryId, progress),
libraryId
).then(() => {
this._emitComplete(libraryId);
this.dbPool.release(libraryPath);
@@ -196,12 +131,12 @@ class ScanService {
/**
* 启动异步同步
* @private
*/
_startAsyncSync(libraryId, libraryPath, db) {
this.scanner.incrementalSync(
this.scanner.syncLibrary(
libraryPath,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
).then(() => {
this._emitComplete(libraryId);
@@ -212,54 +147,30 @@ class ScanService {
});
}
/**
* 发送进度更新
* @private
*/
_emitProgress(libraryId, progress) {
if (this.io) {
this.io.emit('scanProgress', {
libraryId,
...progress
});
this.io.emit('scanProgress', { libraryId, ...progress });
}
}
/**
* 发送完成事件
* @private
*/
_emitComplete(libraryId) {
if (this.io) {
this.io.emit('scanComplete', { libraryId });
}
}
/**
* 发送错误事件
* @private
*/
_emitError(libraryId, error) {
if (this.io) {
this.io.emit('scanError', {
libraryId,
error: error.message
});
this.io.emit('scanError', { libraryId, error: error.message });
}
}
/**
* 获取素材库对象
* @private
*/
_getLibrary(libraryId) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === libraryId);
if (!library) {
throw new NotFoundError('Library', libraryId);
}
return library;
}
}
+19 -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,
+31 -7
View File
@@ -13,11 +13,9 @@ class LibraryDatabase {
fs.mkdirSync(this.flypicDir, { recursive: true });
}
// Create thumbnails directory (480px 与 Billfish 一致)
// Create thumbnails directory (使用分片结构: .flypic/thumbnails/ab/hash.webp)
const thumbDir = path.join(this.flypicDir, 'thumbnails');
const thumbDir480 = path.join(thumbDir, '480');
if (!fs.existsSync(thumbDir)) fs.mkdirSync(thumbDir, { recursive: true });
if (!fs.existsSync(thumbDir480)) fs.mkdirSync(thumbDir480, { recursive: true });
this.db = new Database(this.dbPath);
@@ -29,6 +27,15 @@ class LibraryDatabase {
this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射
this.initTables();
// 启动 WAL 定期 checkpoint(每 5 分钟)
this.walCheckpointInterval = setInterval(() => {
try {
this.db.pragma('wal_checkpoint(PASSIVE)');
} catch (e) {
console.warn('[DB] WAL checkpoint warning:', e.message);
}
}, 300000); // 5 分钟
}
initTables() {
@@ -165,8 +172,11 @@ class LibraryDatabase {
}
getAllImages() {
const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC');
return stmt.all();
// ⚠️ 警告:此方法会加载所有图片到内存,仅用于调试!
// 生产环境请使用 searchImages() 或流式查询
console.warn('[DB] WARNING: getAllImages() loads all data into memory. Use searchImages() instead!');
const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC LIMIT 1000');
return stmt.all(); // 限制最多 1000 条
}
searchImages(keywords, filters = {}, pagination = null) {
@@ -220,8 +230,9 @@ class LibraryDatabase {
if (pagination && typeof pagination.offset === 'number' && typeof pagination.limit === 'number') {
const timings = {};
// 先获取数据(快速)
const query = `SELECT * ${baseQuery} ORDER BY created_at DESC LIMIT ? OFFSET ?`;
// 只选择必要字段,减少内存占用
const essentialFields = 'id, path, filename, size, format, width, height, thumbnail_path, folder';
const query = `SELECT ${essentialFields} ${baseQuery} ORDER BY created_at DESC LIMIT ? OFFSET ?`;
const paginatedParams = [...params, pagination.limit, pagination.offset];
let queryStart = Date.now();
@@ -393,6 +404,19 @@ class LibraryDatabase {
}
close() {
// 清理 WAL checkpoint 定时器
if (this.walCheckpointInterval) {
clearInterval(this.walCheckpointInterval);
this.walCheckpointInterval = null;
}
// 执行最后一次 checkpoint
try {
this.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn('[DB] Final WAL checkpoint warning:', e.message);
}
this.db.close();
}
}
+66 -30
View File
@@ -6,6 +6,12 @@ const LibraryDatabase = require('./db');
*/
class DatabasePool {
constructor() {
// 单例模式:确保只有一个实例,避免多个定时器
if (DatabasePool.instance) {
return DatabasePool.instance;
}
DatabasePool.instance = this;
this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount }
this.maxIdleTime = 60000; // 60秒未使用则关闭
this.cleanupInterval = null;
@@ -16,20 +22,12 @@ class DatabasePool {
/**
* 获取数据库连接(复用或创建)
* 优化:同时只保持一个活跃连接
* 优化:严格限制最大1个活跃连接
*/
acquire(libraryPath) {
let conn = this.connections.get(libraryPath);
if (!conn) {
// 如果已有其他连接且引用计数为0,先关闭它们
for (const [path, existingConn] of this.connections.entries()) {
if (existingConn.refCount === 0) {
console.log(`[DBPool] Auto-closing idle connection: ${path}`);
this.close(path);
}
}
// 创建新连接
const db = new LibraryDatabase(libraryPath);
conn = {
@@ -38,7 +36,6 @@ class DatabasePool {
refCount: 0
};
this.connections.set(libraryPath, conn);
console.log(`[DBPool] Created new connection for: ${libraryPath}`);
}
// 更新使用时间和引用计数
@@ -69,23 +66,19 @@ class DatabasePool {
// 强制设置引用计数为0
conn.refCount = 0;
// 关闭数据库连接
// 执行 checkpoint 确保 WAL 写入主数据库
if (conn.db && conn.db.db) {
// 执行 checkpoint 确保 WAL 写入主数据库
try {
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
}
// 关闭连接
conn.db.close();
}
conn.db.close();
this.connections.delete(libraryPath);
console.log(`[DBPool] Closed connection for: ${libraryPath}`);
} catch (error) {
console.error(`[DBPool] Error closing connection:`, error);
console.error(`❌ 关闭数据库连接失败:`, error.message);
// 即使出错也删除引用
this.connections.delete(libraryPath);
}
@@ -96,26 +89,43 @@ class DatabasePool {
* 关闭所有连接
*/
closeAll() {
for (const [path, conn] of this.connections.entries()) {
try {
conn.db.close();
console.log(`[DBPool] Closed connection for: ${path}`);
} catch (error) {
console.error(`[DBPool] Error closing connection:`, error);
}
}
this.connections.clear();
// 先清理定时器,避免在关闭过程中触发清理
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
for (const [path, conn] of this.connections.entries()) {
try {
// 执行 checkpoint 确保 WAL 写入主数据库
if (conn.db && conn.db.db) {
try {
conn.db.db.pragma('wal_checkpoint(TRUNCATE)');
} catch (e) {
console.warn(`[DBPool] WAL checkpoint warning:`, e.message);
}
}
conn.db.close();
} catch (error) {
console.error(`❌ 关闭数据库连接失败:`, error.message);
}
}
this.connections.clear();
}
/**
* 强制关闭所有连接(用于紧急清理)
* 与 closeAll() 相同,但提供明确的语义
*/
forceCloseAll() {
this.closeAll();
}
/**
* 启动定期清理空闲连接
*/
startCleanup() {
// 更频繁的检查(每10秒)
this.cleanupInterval = setInterval(() => {
const now = Date.now();
const toClose = [];
@@ -130,9 +140,14 @@ class DatabasePool {
toClose.forEach(path => this.close(path));
if (toClose.length > 0) {
console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`);
// 关闭连接后立即强制 GC
if (global.gc) {
for (let i = 0; i < 3; i++) {
global.gc();
}
}
}
}, 30000); // 每30秒检查一次
}, 10000); // 每10秒检查一次(更频繁)
}
/**
@@ -147,7 +162,28 @@ class DatabasePool {
idleTime: Date.now() - conn.lastUsed
});
}
return status;
return {
connections: status,
totalConnections: this.connections.size,
maxConnections: this.maxConnections,
maxIdleTime: this.maxIdleTime
};
}
/**
* 实现 clear() 方法以支持 CleanupManager 注册
*/
clear() {
// 清理空闲连接
const toClose = [];
for (const [path, conn] of this.connections.entries()) {
if (conn.refCount === 0) {
toClose.push(path);
}
}
toClose.forEach(path => this.close(path));
}
}
+162 -87
View File
@@ -580,23 +580,23 @@
}
},
"node_modules/body-parser": {
"version": "1.20.3",
"resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.3.tgz",
"integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==",
"version": "1.20.4",
"resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.4.tgz",
"integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"on-finished": "2.4.1",
"qs": "6.13.0",
"raw-body": "2.5.2",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.14.0",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "1.0.0"
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
@@ -786,18 +786,18 @@
}
},
"node_modules/cookie": {
"version": "0.7.1",
"resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.1.tgz",
"integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==",
"version": "0.7.2",
"resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.6.tgz",
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
"version": "1.0.7",
"resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"node_modules/cors": {
@@ -993,15 +993,6 @@
"node": ">=10.0.0"
}
},
"node_modules/engine.io/node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/engine.io/node_modules/debug": {
"version": "4.3.7",
"resolved": "https://registry.npmmirror.com/debug/-/debug-4.3.7.tgz",
@@ -1080,39 +1071,39 @@
}
},
"node_modules/express": {
"version": "4.21.2",
"resolved": "https://registry.npmmirror.com/express/-/express-4.21.2.tgz",
"integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==",
"version": "4.22.1",
"resolved": "https://registry.npmmirror.com/express/-/express-4.22.1.tgz",
"integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "1.20.3",
"content-disposition": "0.5.4",
"body-parser": "~1.20.3",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "0.7.1",
"cookie-signature": "1.0.6",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "1.3.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "2.4.1",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.12",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "6.13.0",
"qs": "~6.14.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "0.19.0",
"serve-static": "1.16.2",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
@@ -1144,17 +1135,17 @@
}
},
"node_modules/finalhandler": {
"version": "1.3.1",
"resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.1.tgz",
"integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==",
"version": "1.3.2",
"resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "2.4.1",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "2.0.1",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
@@ -1346,19 +1337,23 @@
}
},
"node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
@@ -1917,12 +1912,12 @@
}
},
"node_modules/qs": {
"version": "6.13.0",
"resolved": "https://registry.npmmirror.com/qs/-/qs-6.13.0.tgz",
"integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==",
"version": "6.14.0",
"resolved": "https://registry.npmmirror.com/qs/-/qs-6.14.0.tgz",
"integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==",
"license": "BSD-3-Clause",
"dependencies": {
"side-channel": "^1.0.6"
"side-channel": "^1.1.0"
},
"engines": {
"node": ">=0.6"
@@ -1941,15 +1936,15 @@
}
},
"node_modules/raw-body": {
"version": "2.5.2",
"resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.2.tgz",
"integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==",
"version": "2.5.3",
"resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"http-errors": "2.0.0",
"iconv-lite": "0.4.24",
"unpipe": "1.0.0"
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
@@ -2035,6 +2030,98 @@
}
},
"node_modules/send": {
"version": "0.19.1",
"resolved": "https://registry.npmmirror.com/send/-/send-0.19.1.tgz",
"integrity": "sha512-p4rRk4f23ynFEfcD9LA0xRYngj+IyGiEYyqqOak8kaN0TvNmuxC2dcVeBn62GpCeR2CpWqyHCNScTP91QbAVFg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "0.5.2",
"http-errors": "2.0.0",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "2.4.1",
"range-parser": "~1.2.1",
"statuses": "2.0.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/send/node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/serve-static": {
"version": "1.16.2",
"resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.2.tgz",
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.19.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/serve-static/node_modules/http-errors": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz",
"integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",
"license": "MIT",
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/serve-static/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static/node_modules/send": {
"version": "0.19.0",
"resolved": "https://registry.npmmirror.com/send/-/send-0.19.0.tgz",
"integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==",
@@ -2058,7 +2145,7 @@
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/encodeurl": {
"node_modules/serve-static/node_modules/send/node_modules/encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-1.0.2.tgz",
"integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==",
@@ -2067,25 +2154,13 @@
"node": ">= 0.8"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.2",
"resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.2.tgz",
"integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==",
"node_modules/serve-static/node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "0.19.0"
},
"engines": {
"node": ">= 0.8.0"
"node": ">= 0.8"
}
},
"node_modules/setprototypeof": {
@@ -2416,9 +2491,9 @@
"license": "MIT"
},
"node_modules/statuses": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
+2 -2
View File
@@ -4,8 +4,8 @@
"description": "FlyPic backend server",
"main": "server.js",
"scripts": {
"dev": "cross-env PORT=15002 nodemon server.js",
"start": "node server.js"
"dev": "cross-env PORT=15002 nodemon --expose-gc server.js",
"start": "node --expose-gc server.js"
},
"dependencies": {
"better-sqlite3": "^9.2.2",
@@ -1,224 +0,0 @@
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var Es=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function su(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var gf={exports:{}},$o={},yf={exports:{}},Se={};/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ms=Symbol.for("react.element"),Sm=Symbol.for("react.portal"),bm=Symbol.for("react.fragment"),Em=Symbol.for("react.strict_mode"),Cm=Symbol.for("react.profiler"),Nm=Symbol.for("react.provider"),Rm=Symbol.for("react.context"),Tm=Symbol.for("react.forward_ref"),Om=Symbol.for("react.suspense"),Im=Symbol.for("react.memo"),Am=Symbol.for("react.lazy"),fc=Symbol.iterator;function jm(e){return e===null||typeof e!="object"?null:(e=fc&&e[fc]||e["@@iterator"],typeof e=="function"?e:null)}var vf={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},wf=Object.assign,xf={};function vi(e,t,n){this.props=e,this.context=t,this.refs=xf,this.updater=n||vf}vi.prototype.isReactComponent={};vi.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};vi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _f(){}_f.prototype=vi.prototype;function ou(e,t,n){this.props=e,this.context=t,this.refs=xf,this.updater=n||vf}var au=ou.prototype=new _f;au.constructor=ou;wf(au,vi.prototype);au.isPureReactComponent=!0;var hc=Array.isArray,kf=Object.prototype.hasOwnProperty,lu={current:null},Sf={key:!0,ref:!0,__self:!0,__source:!0};function bf(e,t,n){var r,i={},s=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)kf.call(t,r)&&!Sf.hasOwnProperty(r)&&(i[r]=t[r]);var a=arguments.length-2;if(a===1)i.children=n;else if(1<a){for(var l=Array(a),d=0;d<a;d++)l[d]=arguments[d+2];i.children=l}if(e&&e.defaultProps)for(r in a=e.defaultProps,a)i[r]===void 0&&(i[r]=a[r]);return{$$typeof:ms,type:e,key:s,ref:o,props:i,_owner:lu.current}}function zm(e,t){return{$$typeof:ms,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function uu(e){return typeof e=="object"&&e!==null&&e.$$typeof===ms}function Lm(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var pc=/\/+/g;function ha(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Lm(""+e.key):t.toString(36)}function Ys(e,t,n,r,i){var s=typeof e;(s==="undefined"||s==="boolean")&&(e=null);var o=!1;if(e===null)o=!0;else switch(s){case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case ms:case Sm:o=!0}}if(o)return o=e,i=i(o),e=r===""?"."+ha(o,0):r,hc(i)?(n="",e!=null&&(n=e.replace(pc,"$&/")+"/"),Ys(i,t,n,"",function(d){return d})):i!=null&&(uu(i)&&(i=zm(i,n+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(pc,"$&/")+"/")+e)),t.push(i)),1;if(o=0,r=r===""?".":r+":",hc(e))for(var a=0;a<e.length;a++){s=e[a];var l=r+ha(s,a);o+=Ys(s,t,n,l,i)}else if(l=jm(e),typeof l=="function")for(e=l.call(e),a=0;!(s=e.next()).done;)s=s.value,l=r+ha(s,a++),o+=Ys(s,t,n,l,i);else if(s==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return o}function Cs(e,t,n){if(e==null)return e;var r=[],i=0;return Ys(e,r,"","",function(s){return t.call(n,s,i++)}),r}function Pm(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ft={current:null},Zs={transition:null},Fm={ReactCurrentDispatcher:ft,ReactCurrentBatchConfig:Zs,ReactCurrentOwner:lu};function Ef(){throw Error("act(...) is not supported in production builds of React.")}Se.Children={map:Cs,forEach:function(e,t,n){Cs(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return Cs(e,function(){t++}),t},toArray:function(e){return Cs(e,function(t){return t})||[]},only:function(e){if(!uu(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};Se.Component=vi;Se.Fragment=bm;Se.Profiler=Cm;Se.PureComponent=ou;Se.StrictMode=Em;Se.Suspense=Om;Se.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Fm;Se.act=Ef;Se.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=wf({},e.props),i=e.key,s=e.ref,o=e._owner;if(t!=null){if(t.ref!==void 0&&(s=t.ref,o=lu.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(l in t)kf.call(t,l)&&!Sf.hasOwnProperty(l)&&(r[l]=t[l]===void 0&&a!==void 0?a[l]:t[l])}var l=arguments.length-2;if(l===1)r.children=n;else if(1<l){a=Array(l);for(var d=0;d<l;d++)a[d]=arguments[d+2];r.children=a}return{$$typeof:ms,type:e.type,key:i,ref:s,props:r,_owner:o}};Se.createContext=function(e){return e={$$typeof:Rm,_currentValue:e,_currentValue2:e,_threadCountLine truncated
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Dm=Z,Mm=Symbol.for("react.element"),Bm=Symbol.for("react.fragment"),Um=Object.prototype.hasOwnProperty,$m=Dm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Wm={key:!0,ref:!0,__self:!0,__source:!0};function Cf(e,t,n){var r,i={},s=null,o=null;n!==void 0&&(s=""+n),t.key!==void 0&&(s=""+t.key),t.ref!==void 0&&(o=t.ref);for(r in t)Um.call(t,r)&&!Wm.hasOwnProperty(r)&&(i[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)i[r]===void 0&&(i[r]=t[r]);return{$$typeof:Mm,type:e,key:s,ref:o,props:i,_owner:$m.current}}$o.Fragment=Bm;$o.jsx=Cf;$o.jsxs=Cf;gf.exports=$o;var S=gf.exports,Za={},Nf={exports:{}},Nt={},Rf={exports:{}},Tf={};/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/(function(e){function t(H,U){var ee=H.length;H.push(U);e:for(;0<ee;){var z=ee-1>>>1,F=H[z];if(0<i(F,U))H[z]=U,H[ee]=F,ee=z;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var U=H[0],ee=H.pop();if(ee!==U){H[0]=ee;e:for(var z=0,F=H.length,A=F>>>1;z<A;){var B=2*(z+1)-1,D=H[B],le=B+1,de=H[le];if(0>i(D,ee))le<F&&0>i(de,D)?(H[z]=de,H[le]=ee,z=le):(H[z]=D,H[B]=ee,z=B);else if(le<F&&0>i(de,ee))H[z]=de,H[le]=ee,z=le;else break e}}return U}function i(H,U){var ee=H.sortIndex-U.sortIndex;return ee!==0?ee:H.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],d=[],p=1,y=null,x=3,g=!1,m=!1,u=!1,v=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,h=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(H){for(var U=n(d);U!==null;){if(U.callback===null)r(d);else if(U.startTime<=H)r(d),U.sortIndex=U.expirationTime,t(l,U);else break;U=n(d)}}function k(H){if(u=!1,w(H),!m)if(n(l)!==null)m=!0,ce(b);else{var U=n(d);U!==null&&Q(k,U.startTime-H)}}function b(H,U){m=!1,u&&(u=!1,c(P),P=-1),g=!0;var ee=x;try{for(w(U),y=n(l);y!==null&&(!(y.expirationTime>U)||H&&!J());){var z=y.callback;if(typeof z=="function"){y.callback=null,x=y.priorityLevel;var F=z(y.expirationTime<=U);U=e.unstable_now(),typeof F=="function"?y.callback=F:y===n(l)&&r(l),w(U)}else r(l);y=n(l)}if(y!==null)var A=!0;else{var B=n(d);B!==null&&Q(k,B.startTime-U),A=!1}return A}finally{y=null,x=ee,g=!1}}var N=!1,T=null,P=-1,O=5,M=-1;function J(){return!(e.unstable_now()-M<O)}function R(){if(T!==null){var H=e.unstable_now();M=H;var U=!0;try{U=T(!0,H)}finally{U?W():(N=!1,T=null)}}else N=!1}var W;if(typeof h=="function")W=function(){h(R)};else if(typeof MessageChannel<"u"){var _=new MessageChannel,V=_.port2;_.port1.onmessage=R,W=function(){V.postMessage(null)}}else W=function(){v(R,0)};function ce(H){T=H,N||(N=!0,W())}function Q(H,U){P=v(function(){H(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_continueExecution=function(){m||g||(m=!0,ce(b))},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):O=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return x},e.unstable_getFirstCallbackNode=function(){return n(l)},e.unstable_next=function(H){switch(x){case 1:case 2:case 3:var U=3;break;default:U=x}var ee=x;x=U;try{return H()}finally{x=ee}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(H,U){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var ee=x;x=H;try{return U()}finally{x=ee}},e.unstable_scheduleCallback=function(H,U,ee){var z=e.unstable_now();switch(typeof ee=="object"&&ee!==null?(ee=ee.delay,ee=typeof ee=="number"&&0<ee?z+ee:z):ee=z,H){case 1:var F=-1;break;case 2:F=250;break;case 5:F=1073741823;break;case 4:F=1e4;break;default:F=5e3}return F=ee+F,H={id:p++,callback:U,priorityLevel:H,startTime:ee,expirationTime:F,sortIndex:-1},ee>z?(H.sortIndex=ee,t(d,H),n(l)===null&&H===n(d)&&(u?(c(P),P=-1):u=!0,Q(k,ee-z))):(H.sortIndex=F,t(l,H),m||g||(m=!0,ce(b))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var U=x;return function(){var ee=x;x=U;try{return H.apply(this,arguments)}finally{x=ee}}}})(Tf);Rf.exports=Tf;var Hm=Rf.exports;/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Vm=Z,Ct=Hm;function ae(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Of=new Set,Qi={};function Ir(e,t){ui(e,t),ui(e+"Capture",t)}function ui(e,t){for(Qi[e]=t,e=0;e<t.length;e++)Of.add(t[e])}var In=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Qa=Object.prototype.hasOwnProperty,qm=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,mc={},gc={};function Km(e){return Qa.call(gc,e)?!0:Qa.call(mc,e)?!1:qm.test(e)?gc[e]=!0:(mc[e]=!0,!1)}function Xm(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ym(e,t,n,r){if(t===null||typeof t>"u"||Xm(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ht(e,t,n,r,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var et={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){et[e]=new ht(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];et[t]=new ht(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){et[e]=new ht(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){et[e]=new ht(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){et[e]=new ht(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){et[e]=new ht(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){et[e]=new ht(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){et[e]=new ht(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){et[e]=new ht(e,5,!1,e.toLowerCase(),null,!1,!1)});var cu=/[\-:]([a-z])/g;function du(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(cu,du);et[t]=new ht(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){et[e]=new ht(e,1,!1,e.toLowerCase(),null,!1,!1)});et.xlinkHref=new ht("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){et[e]=new ht(e,1,!1,e.toLowerCase(),null,!0,!0)});function fu(e,t,n,r){var i=et.hasOwnProperty(t)?et[t]:null;(i!==null?i.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!== Line truncated
`+pa+e}var ma=!1;function ga(e,t){if(!e||ma)return"";ma=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(d){var r=d}Reflect.construct(e,[],t)}else{try{t.call()}catch(d){r=d}e.call(t.prototype)}else{try{throw Error()}catch(d){r=d}e()}}catch(d){if(d&&r&&typeof d.stack=="string"){for(var i=d.stack.split(`
`),s=r.stack.split(`
`),o=i.length-1,a=s.length-1;1<=o&&0<=a&&i[o]!==s[a];)a--;for(;1<=o&&0<=a;o--,a--)if(i[o]!==s[a]){if(o!==1||a!==1)do if(o--,a--,0>a||i[o]!==s[a]){var l=`
`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{ma=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Pi(e):""}function Zm(e){switch(e.tag){case 5:return Pi(e.type);case 16:return Pi("Lazy");case 13:return Pi("Suspense");case 19:return Pi("SuspenseList");case 0:case 2:case 15:return e=ga(e.type,!1),e;case 11:return e=ga(e.type.render,!1),e;case 1:return e=ga(e.type,!0),e;default:return""}}function tl(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Hr:return"Fragment";case Wr:return"Portal";case Ga:return"Profiler";case hu:return"StrictMode";case Ja:return"Suspense";case el:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Af:return(e.displayName||"Context")+".Consumer";case If:return(e._context.displayName||"Context")+".Provider";case pu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case mu:return t=e.displayName||null,t!==null?t:tl(e.type)||"Memo";case Wn:t=e._payload,e=e._init;try{return tl(e(t))}catch{}}return null}function Qm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return tl(t);case 8:return t===hu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function or(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function zf(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Gm(e){var t=zf(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){r=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Rs(e){e._valueTracker||(e._valueTracker=Gm(e))}function Lf(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=zf(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function mo(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function nl(e,t){var n=t.checked;return Ue({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function vc(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=or(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Pf(e,t){t=t.checked,t!=null&&fu(e,"checked",t,!1)}function rl(e,t){Pf(e,t);var n=or(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?il(e,t.type,n):t.hasOwnProperty("defaultValue")&&il(e,t.type,or(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function wc(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function il(e,t,n){(t!=="number"||mo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Fi=Array.isArray;function ni(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t["$"+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty("$"+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=""+or(n),t=null,i=0;i<e.length;i++){if(e[i].value===n){e[i].selected=!0,r&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function sl(e,t){if(t.dan Line truncated
`).replace(lg,"")}function Ps(e,t,n){if(t=$c(t),$c(e)!==t&&n)throw Error(ae(425))}function So(){}var vl=null,wl=null;function xl(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var _l=typeof setTimeout=="function"?setTimeout:void 0,ug=typeof clearTimeout=="function"?clearTimeout:void 0,Wc=typeof Promise=="function"?Promise:void 0,cg=typeof queueMicrotask=="function"?queueMicrotask:typeof Wc<"u"?function(e){return Wc.resolve(null).then(e).catch(dg)}:_l;function dg(e){setTimeout(function(){throw e})}function Ta(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&i.nodeType===8)if(n=i.data,n==="/$"){if(r===0){e.removeChild(i),ns(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=i}while(n);ns(t)}function Jn(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function Hc(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var xi=Math.random().toString(36).slice(2),un="__reactFiber$"+xi,as="__reactProps$"+xi,An="__reactContainer$"+xi,kl="__reactEvents$"+xi,fg="__reactListeners$"+xi,hg="__reactHandles$"+xi;function vr(e){var t=e[un];if(t)return t;for(var n=e.parentNode;n;){if(t=n[An]||n[un]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Hc(e);e!==null;){if(n=e[un])return n;e=Hc(e)}return t}e=n,n=e.parentNode}return null}function vs(e){return e=e[un]||e[An],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Xr(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(ae(33))}function Ko(e){return e[as]||null}var Sl=[],Yr=-1;function ur(e){return{current:e}}function Le(e){0>Yr||(e.current=Sl[Yr],Sl[Yr]=null,Yr--)}function Oe(e,t){Yr++,Sl[Yr]=e.current,e.current=t}var ar={},ot=ur(ar),gt=ur(!1),Er=ar;function ci(e,t){var n=e.type.contextTypes;if(!n)return ar;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function yt(e){return e=e.childContextTypes,e!=null}function bo(){Le(gt),Le(ot)}function Vc(e,t,n){if(ot.current!==ar)throw Error(ae(168));Oe(ot,t),Oe(gt,n)}function bh(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(ae(108,Qm(e)||"Unknown",i));return Ue({},n,r)}function Eo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ar,Er=ot.current,Oe(ot,e),Oe(gt,gt.current),!0}function qc(e,t,n){var r=e.stateNode;if(!r)throw Error(ae(169));n?(e=bh(e,t,Er),r.__reactInternalMemoizedMergedChildContext=e,Le(gt),Le(ot),Oe(ot,e)):Le(gt),Oe(gt,n)}var Cn=null,Xo=!1,Oa=!1;function Eh(e){Cn===null?Cn=[e]:Cn.push(e)}function pg(e){Xo=!0,Eh(e)}function cr(){if(!Oa&&Cn!==null){Oa=!0;var e=0,t=Re;try{var n=Cn;for(Re=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Cn=null,Xo=!1}catch(i){throw Cn!==null&&(Cn=Cn.slice(e+1)),Zf(yu,cr),i}finally{Re=t,Oa=!1}}return null}var Zr=[],Qr=0,Co=null,No=0,zt=[],Lt=0,Cr=null,Rn=1,Tn="";function mr(e,t){Zr[Qr++]=No,Zr[Qr++]=Co,Co=e,No=t}function Ch(e,t,n){zt[Lt++]=Rn,zt[Lt++]=Tn,zt[Lt++]=Cr,Cr=e;var r=Rn;e=Tn;var i=32-Yt(r)-1;r&=~(1<<i),n+=1;var s=32-Yt(t)+i;if(30<s){var o=i-i%5;s=(r&(1<<o)-1).toString(32),r>>=o,i-=o,Rn=1<<32-Yt(t)+i|n<<i|r,Tn=s+e}else Rn=1<<s|n<<i|r,Tn=e}function Cu(e){e.return!==null&&(mr(e,1),Ch(e,1,0))}function Nu(e){for(;e===Co;)Co=Zr[--Qr],Zr[Qr]=null,No=Zr[--Qr],Zr[Qr]=null;for(;e===Cr;)Cr=zt[--Lt],zt[Lt]=null,Tn=zt[--Lt],zt[Lt]=null,Rn=zt[--Lt],zt[Lt]=null}var Et=null,bt=null,Fe=!1,Xt=null;function Nh(e,t){var n=Dt(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Kc(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,Et=e,bt=Jn(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,Et=e,bt=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=Cr!==null?{id:Rn,overflow:Tn}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=Dt(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,Et=e,bt=null,!0):!1;default:return!1}}function bl(e){return(e.mode&1)!==0&&(e.flags&128)===0}function El(e){if(Fe){var t=bt;if(t){var n=t;if(!Kc(e,t)){if(bl(e))throw Error(ae(418));t=Jn(n.nextSibling);var r=Et;t&&Kc(e,t)?Nh(r,n):(e.flags=e.flags&-4097|2,Fe=!1,Et=e)}}else{if(bl(e))throw Error(ae(418));e.flags=e.flags&-4097|2,Fe=!1,Et=e}}}function Xc(e){ Line truncated
Error generating stack: `+s.message+`
`+s.stack}return{value:e,source:t,stack:i,digest:null}}function La(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Tl(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var Sg=typeof WeakMap=="function"?WeakMap:Map;function ep(e,t,n){n=On(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Lo||(Lo=!0,Ml=r),Tl(e,t)},n}function tp(e,t,n){n=On(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){Tl(e,t)}}var s=e.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(n.callback=function(){Tl(e,t),typeof r!="function"&&(tr===null?tr=new Set([this]):tr.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),n}function nd(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Sg;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=Fg.bind(null,e,t,n),t.then(e,e))}function rd(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function id(e,t,n,r,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=On(-1,1),t.tag=2,er(n,t,1))),n.lanes|=1),e)}var bg=Ln.ReactCurrentOwner,mt=!1;function ct(e,t,n,r){t.child=e===null?Oh(t,null,n,r):fi(t,e.child,n,r)}function sd(e,t,n,r,i){n=n.render;var s=t.ref;return oi(t,i),r=Du(e,t,n,r,s,i),n=Mu(),e!==null&&!mt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,zn(e,t,i)):(Fe&&n&&Cu(t),t.flags|=1,ct(e,t,r,i),t.child)}function od(e,t,n,r,i){if(e===null){var s=n.type;return typeof s=="function"&&!Yu(s)&&s.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=s,np(e,t,s,r,i)):(e=oo(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(s=e.child,!(e.lanes&i)){var o=s.memoizedProps;if(n=n.compare,n=n!==null?n:is,n(o,r)&&e.ref===t.ref)return zn(e,t,i)}return t.flags|=1,e=rr(s,r),e.ref=t.ref,e.return=t,t.child=e}function np(e,t,n,r,i){if(e!==null){var s=e.memoizedProps;if(is(s,r)&&e.ref===t.ref)if(mt=!1,t.pendingProps=r=s,(e.lanes&i)!==0)e.flags&131072&&(mt=!0);else return t.lanes=e.lanes,zn(e,t,i)}return Ol(e,t,n,r,i)}function rp(e,t,n){var r=t.pendingProps,i=r.children,s=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Oe(ei,St),St|=n;else{if(!(n&1073741824))return e=s!==null?s.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Oe(ei,St),St|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=s!==null?s.baseLanes:n,Oe(ei,St),St|=r}else s!==null?(r=s.baseLanes|n,t.memoizedState=null):r=n,Oe(ei,St),St|=r;return ct(e,t,i,n),t.child}function ip(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Ol(e,t,n,r,i){var s=yt(n)?Er:ot.current;return s=ci(t,s),oi(t,i),n=Du(e,t,n,r,s,i),r=Mu(),e!==null&&!mt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,zn(e,t,i)):(Fe&&r&&Cu(t),t.flags|=1,ct(e,t,n,i),t.child)}function ad(e,t,n,r,i){if(yt(n)){var s=!0;Eo(t)}else s=!1;if(oi(t,i),t.stateNode===null)ro(e,t),Jh(t,n,r),Rl(t,n,r,i),r=!0;else if(e===null){var o=t.stateNode,a=t.memoizedProps;o.props=a;var l=o.context,d=n.contextType;typeof d=="object"&&d!==null?d=Bt(d):(d=yt(n)?Er:ot.current,d=ci(t,d));var p=n.getDerivedStateFromProps,y=typeof p=="function"||typeof o.getSnapshotBeforeUpdate=="function";y||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==r||l!==d)&&td(t,o,r,d),Hn=!1;var x=t.memoizedState;o.state=x,Oo(t,r,o,i),l=t.memoizedState,a!==r||x!==l||gt.current||Hn?(typeof p=="function"&&(Nl(t,n,p,r),l=t.memoizedState),(a=Hn||ed(t,n,a,r,x,l,d))?(y||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),o.props=r,o.state=l,o.context=d,r=a):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,Ah(e,t),a=t.memoizedProps,d=t.type===t.elementType?a:Vt(t.type,a),o.props=d,y=t.pendingProps,x=o.context,l=n.contextType,typeof l=="object"&&l!==null?l=Bt(l):(l=yt(n)?Er:ot.current,l=ci(t,l));var g=n.getDerivedStateFromProps;(p=typeof g=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==y||x!==l)&&td(t,o,r,l),Hn=!1,x=t.memoizedState,o.state=x,Oo(t,r,o,i);var m=t.memoizedS Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var gi=Z;function Wy(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Hy=typeof Object.is=="function"?Object.is:Wy,Vy=gi.useState,qy=gi.useEffect,Ky=gi.useLayoutEffect,Xy=gi.useDebugValue;function Yy(e,t){var n=t(),r=Vy({inst:{value:n,getSnapshot:t}}),i=r[0].inst,s=r[1];return Ky(function(){i.value=n,i.getSnapshot=t,$a(i)&&s({inst:i})},[e,n,t]),qy(function(){return $a(i)&&s({inst:i}),e(function(){$a(i)&&s({inst:i})})},[e]),Xy(n),n}function $a(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Hy(e,n)}catch{return!0}}function Zy(e,t){return t()}var Qy=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Zy:Yy;Vp.useSyncExternalStore=gi.useSyncExternalStore!==void 0?gi.useSyncExternalStore:Qy;Hp.exports=Vp;var Gy=Hp.exports;/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var oa=Z,Jy=Gy;function ev(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var tv=typeof Object.is=="function"?Object.is:ev,nv=Jy.useSyncExternalStore,rv=oa.useRef,iv=oa.useEffect,sv=oa.useMemo,ov=oa.useDebugValue;Wp.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var s=rv(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=sv(function(){function l(g){if(!d){if(d=!0,p=g,g=r(g),i!==void 0&&o.hasValue){var m=o.value;if(i(m,g))return y=m}return y=g}if(m=y,tv(p,g))return m;var u=r(g);return i!==void 0&&i(m,u)?(p=g,m):(p=g,y=u)}var d=!1,p,y,x=n===void 0?null:n;return[function(){return l(t())},x===null?void 0:function(){return l(x())}]},[t,n,r,i]);var a=nv(e,s[0],s[1]);return iv(function(){o.hasValue=!0,o.value=a},[a]),ov(a),a};$p.exports=Wp;var av=$p.exports;const lv=su(av),qp={},{useDebugValue:uv}=ke,{useSyncExternalStoreWithSelector:cv}=lv;let Nd=!1;const dv=e=>e;function fv(e,t=dv,n){(qp?"production":void 0)!=="production"&&n&&!Nd&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Nd=!0);const r=cv(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return uv(r),r}const Rd=e=>{(qp?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?$y(e):e,n=(r,i)=>fv(t,r,i);return Object.assign(n,t),n},hv=e=>e?Rd(e):Rd,me=hv((e,t)=>({theme:"light",setTheme:n=>e({theme:n}),toggleTheme:()=>e(n=>({theme:n.theme==="light"?"dark":"light"})),libraries:[],currentLibraryId:null,setLibraries:n=>e({libraries:n}),setCurrentLibrary:n=>e({currentLibraryId:n}),addLibrary:n=>e(r=>({libraries:[...r.libraries,n]})),removeLibrary:n=>e(r=>({libraries:r.libraries.filter(i=>i.id!==n),currentLibraryId:r.currentLibraryId===n?null:r.currentLibraryId})),images:[],filteredImages:[],totalImageCount:0,setImages:n=>e({images:n,filteredImages:n}),setFilteredImages:n=>e({filteredImages:n}),setTotalImageCount:n=>e({totalImageCount:n}),imageLoadingState:{isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1},setImageLoadingState:n=>e(r=>({imageLoadingState:{...r.imageLoadingState,...n}})),appendImages:n=>e(r=>({images:[...r.images,...n],filteredImages:[...r.filteredImages,...n]})),folders:[],selectedFolder:null,setFolders:n=>e({folders:n}),setSelectedFolder:n=>e({selectedFolder:n}),searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null},setSearchKeywords:n=>e({searchKeywords:n}),setFilters:n=>e(r=>({filters:{...r.filters,...n}})),resetFilters:()=>e({searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null}}),selectedImage:null,setSelectedImage:n=>e({selectedImage:n}),selectedImages:[],setSelectedImages:n=>e({selectedImages:n}),toggleImageSelection:n=>e(r=>r.selectedImages.some(s=>s.path===n.path)?{selectedImages:r.selectedImages.filter(s=>s.path!==n.path)}:{selectedImages:[...r.selectedImages,n]}),clearSelection:()=>e({selectedImages:[],selectedImage:null}),scanProgress:null,scanStartTime:null,setScanProgress:n=>e(r=>n&&!r.scanStartTime&&n.current>0?{scanProgress:n,scanStartTime:Date.now()}:n?{scanProgress:n}:{scanProgress:null,scanStartTime:null}),isResizingPanels:!1,setIsResizingPanels:n=>e({isResizingPanels:n}),resizingSide:null,setResizingSide:n=>e({resizingSide:n}),thumbnailHeight:200,setThumbnailHeight:n=>e({thumbnailHeight:n}),mobileView:"main",setMobileView:n=>e({mobileView:n}),getCurrentLibrary:()=>{const n=t();return n.libraries.find(r=>r.id===n.currentLibraryId)}}));function Kp(e,t){return function(){return e.apply(t,arguments)}}const{toString:pv}=Object.prototype,{getPrototypeOf:sc}=Object,{iterator:aa,toStringTag:Xp}=Symbol,la=(e=>t=>{const n=pv.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Gt=e=>(e=e.toLowerCase(),t=>la(t)===e),ua=e=>t=>typeof t===e,{isArray:ki}=Array,yi=ua("undefined");function xs(e){return e!==null&&!yi(e)&&e.constructor!==null&&!yi(e.constructor)&&wt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Yp=Gt("ArrayBuffer");function mv(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Yp(e.buffer),t}const gv=ua("string"),wt=ua("function"),Zp=ua("number"),_s=e=>e!==null&&typeof e=="object",yv=e=>e===!0||e===!1,fo=e=>{if(la(e)!=="object")return!1;const t=sc(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Xp in e)&&!(aa in e)},vv=e=>{if(!_s(e)||xs(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},wv=Gt("Date"),xv=Gt("File"),_v=Gt("Blob"),kv=Gt("FileList"),Sv=e=>_s(e)&&wt(e.pipe),bv=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||wt(e.append)&&((t=Line truncated
`).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&m1[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},jd=Symbol("internals");function Li(e){return e&&String(e).trim().toLowerCase()}function ho(e){return e===!1||e==null?e:K.isArray(e)?e.map(ho):String(e)}function y1(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const v1=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Wa(e,t,n,r,i){if(K.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!K.isString(t)){if(K.isString(r))return t.indexOf(r)!==-1;if(K.isRegExp(r))return r.test(t)}}function w1(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function x1(e,t){const n=K.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(i,s,o){return this[r].call(this,t,i,s,o)},configurable:!0})})}let xt=class{constructor(t){t&&this.set(t)}set(t,n,r){const i=this;function s(a,l,d){const p=Li(l);if(!p)throw new Error("header name must be a non-empty string");const y=K.findKey(i,p);(!y||i[y]===void 0||d===!0||d===void 0&&i[y]!==!1)&&(i[y||l]=ho(a))}const o=(a,l)=>K.forEach(a,(d,p)=>s(d,p,l));if(K.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(K.isString(t)&&(t=t.trim())&&!v1(t))o(g1(t),n);else if(K.isObject(t)&&K.isIterable(t)){let a={},l,d;for(const p of t){if(!K.isArray(p))throw TypeError("Object iterator must return a key-value pair");a[d=p[0]]=(l=a[d])?K.isArray(l)?[...l,p[1]]:[l,p[1]]:p[1]}o(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Li(t),t){const r=K.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return y1(i);if(K.isFunction(n))return n.call(this,i,r);if(K.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Li(t),t){const r=K.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Wa(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=Li(o),o){const a=K.findKey(r,o);a&&(!n||Wa(r,r[a],a,n))&&(delete r[a],i=!0)}}return K.isArray(t)?t.forEach(s):s(t),i}clear(t){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const s=n[r];(!t||Wa(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return K.forEach(this,(i,s)=>{const o=K.findKey(r,s);if(o){n[o]=ho(i),delete n[s];return}const a=t?w1(s):String(s).trim();a!==s&&delete n[s],n[a]=ho(i),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return K.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&K.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[jd]=this[jd]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=Li(o);r[a]||(x1(i,o),r[a]=!0)}return K.isArray(t)?t.forEach(s):s(t),this}};xt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);K.reduceDescriptors(xt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});K.freezeMethods(xt);function Ha(e,t){const n=this||Ss,r=t||n,i=xt.from(r.headers);let s=r.data;return K.forEach(e,function(a){s=a.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function lm(e){return!!(e&&e.__CANCEL__)}function Si(e,t,n){we.call(this,e??"canceled",we.ERR_CANCELED,t,n),this.name="CanceledError"}K.inherits(Si,we,{__CANCEL__:!0});function um(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new we("Request failed with status code "+n.status,[we.ERR_BAD_REQUEST,we.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function _1(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function k1(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,s=0,o;return t=t!==void 0?t:1e3,function(l){const d=Date.now(),p=r[s];o||(o=d),n[i]=l,r[i]=d;let y=s,x=0;for(;y!==i;)x+=n[y++],y=y%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),d-o<t)return;const g=p&&d-p;return g?Math.round(x*1e3/g):void 0}}function S1(e,t){let n=0,r=1e3/t,i,s;const o=(d,p=Date.now())=>{n=p,i=null,s&&(clearTimeout(s),s=null),e(...d)};return[(...d)=>{const p=Date.now(),y=p-n;y>=r?o(d,p):(i=d,s||(s=setTimeout(()=>{s=null,o(i)},r-y)))},()=>i&&o(i)]}const Mo=(e,t,n=3)=>{let r=0;const i=k1(50,250);return S1(s=>{const o=s.loaded,a=s.lengthComputable?s.total:void 0,l=o-r,d=i(l),p=o<=a;r=o;const y={loaded:o,total:a,progress:a?o/a:void 0,bytes:l,rate:d||void 0,estimated:d&&a&&p?(a-o)/d:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(y)},n)},zd=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ld=e=>(...t)=>K.asap(()=>e(...t)),b1=st.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,st.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(st.origin),st.navigator&&/(msie|trident)/i.test(st.navigator.userAgent)):()=>!0,E1=st.hasStandardBrowserEnv?{write(e,t,n,r,i,s,o){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];K.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),K.isString(r)&&a.push(`path=${r}`),K.isString(i)&&a.push(`domain=${i}`),s===!0&&a.push("secure"),K.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function C1(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function N1(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function cm(e,t,n){let r=!C1(t);return e&&(r||n==!1)?N1(e,t):t}const Pd=e=>e instanceof xt?{...e}:e;function Or(e,t){t=t||{};const n={};function r(d,p,y,x){return K.isPlainObject(d)&&K.isPlainObject(p)?K.merge.call({caseless:x},d,p):K.isPlainObject(p)?K.merge({},p):K.isArray(p)?p.slice():p}function i(d,p,y,x){if(K.isUndefined(p)){if(!K.isUndefined(d))return r(void 0,d,y,x)}else return r(d,p,y,x)}function s(d,p){if(!K.isUndefined(p))return r(void 0,p)}function o(d,p){if(K.isUndefined(p)){if(!K.isUndefined(d))return r(void 0,d)}else return r(void 0,p)}function a(d,p,y){if(y in t)return r(d,p);if(y in e)return r(void 0,d)}const l={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(d,p,y)=>i(Pd(d),Pd(p),y,!0)};return K.forEach(Object.keys({...e,...t}),function(p){const y=l[p]||i,x=y(e[p],t[p],p);K.isUndefined(x)&&y!==a||(n[p]=x)}),n}const dm=e=>{const t=Or({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=t;if(t.headers=o=xt.from(o),t.url=sm(cm(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),K.isFormData(n)){if(st.hasStandardBrowserEnv||st.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(K.isFunction(n.getHeaders)){const l=n.getHeaders(),d=["content-type","content-length"];Object.entries(l).forEach(([p,y])=>{d.inclu Line truncated
`+o.map($d).join(`
`):" "+$d(o[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const hm={getAdapter:D1,adapters:lc};function Va(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Si(null,e)}function Wd(e){return Va(e),e.headers=xt.from(e.headers),e.data=Ha.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hm.getAdapter(e.adapter||Ss.adapter,e)(e).then(function(r){return Va(e),r.data=Ha.call(e,e.transformResponse,r),r.headers=xt.from(r.headers),r},function(r){return lm(r)||(Va(e),r&&r.response&&(r.response.data=Ha.call(e,e.transformResponse,r.response),r.response.headers=xt.from(r.response.headers))),Promise.reject(r)})}const pm="1.13.2",da={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{da[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Hd={};da.transitional=function(t,n,r){function i(s,o){return"[Axios v"+pm+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,a)=>{if(t===!1)throw new we(i(o," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!Hd[o]&&(Hd[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,o,a):!0}};da.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function M1(e,t,n){if(typeof e!="object")throw new we("options must be an object",we.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const a=e[s],l=a===void 0||o(a,s,e);if(l!==!0)throw new we("option "+s+" must be "+l,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+s,we.ERR_BAD_OPTION)}}const po={assertOptions:M1,validators:da},an=po.validators;let br=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ad,response:new Ad}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Or(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&po.assertOptions(r,{silentJSONParsing:an.transitional(an.boolean),forcedJSONParsing:an.transitional(an.boolean),clarifyTimeoutError:an.transitional(an.boolean)},!1),i!=null&&(K.isFunction(i)?n.paramsSerializer={serialize:i}:po.assertOptions(i,{encode:an.function,serialize:an.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),po.assertOptions(n,{baseUrl:an.spelling("baseURL"),withXsrfToken:an.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&K.merge(s.common,s[n.method]);s&&K.forEach(["delete","get","head","post","put","patch","common"],m=>{delete s[m]}),n.headers=xt.concat(o,s);const a=[];let l=!0;this.interceptors.request.forEach(function(u){typeof u.runWhen=="function"&&u.runWhen(n)===!1||(l=l&&u.synchronous,a.unshift(u.fulfilled,u.rejected))});const d=[];this.interceptors.response.forEach(function(u){d.push(u.fulfilled,u.rejected)});let p,y=0,x;if(!l){const m=[Wd.bind(this),void 0];for(m.unshift(...a),m.push(...d),x=m.length,p=Promise.resolve(n);y<x;)p=p.then(m[y++],m[y++]);return p}x=a.length;let g=n;for(;y<x;){const m=a[y++],u=a[y++];try{g=m(g)}catch(v){u.call(this,v);break}}try{p=Wd.call(this,g)}catch(m){return Promise.reject(m)}for(y=0,x=d.length;y<x;)p=p.then(d[y++],d[y++]);return p}getUri(t){t=Or(this.defaults,t);const n=cm(t.baseURL,t.url,t.allowAbsoluteUrls);return sm(n,t.params,t.paramsSerializer)}};K.forEach(["delete","get","head","options"],function(t){br.prototype[t]=function(n,r){return this.request(Or(r||{},{method:t,url:n,data:(r||{}).data}))}});K.forEach(["post","put","patch"],function(t){function n(r){return function(s,o,a){return this.request(Or(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}br.prototype[t]=n(),br.prototype[t+"Form"]=n(!0)});let B1=class mm{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(a=>{r.subscribe(a),s=a}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},t(function(s,o,a){r.reason||(r.reason=new Si(s,o,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new mm(function(i){t=i}),cancel:t}}};function U1(e){return function(n){return e.apply(null,n)}}function $1(e){return K.isObject(e)&&e.isAxiosError===!0}const Gl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Gl).forEach(([e,t])=>{Gl[t]=e});function gm(e){const t=new br(e),n=Kp(br.prototype.request,t);return K.extend(n,br.prototype,t,{allOwnKeys:!0}),K.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return gm(Or(e,i))},n}const xe=gm(Ss);xe.Axios=br;xe.CanceledError=Si;xe.CancelToken=B1;xe.isCancel=lm;xe.VERSION=pm;xe.toFormData=ca;xe.AxiosError=we;xe.Cancel=xe.CanceledError;xe.all=function(t){return Promise.all(t)};xe.spread=U1;xe.isAxiosError=$1;xe.mergeConfig=Or;xe.AxiosH Line truncated
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/var W1={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const H1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Ie=(e,t)=>{const n=Z.forwardRef(({color:r="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:o,className:a="",children:l,...d},p)=>Z.createElement("svg",{ref:p,...W1,width:i,height:i,stroke:r,strokeWidth:o?Number(s)*24/Number(i):s,className:["lucide",`lucide-${H1(e)}`,a].join(" "),...d},[...t.map(([y,x])=>Z.createElement(y,x)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const V1=Ie("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const q1=Ie("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const qd=Ie("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const K1=Ie("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const X1=Ie("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Y1=Ie("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Z1=Ie("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Q1=Ie("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const G1=Ie("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const J1=Ie("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ew=Ie("File",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Kd=Ie("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const tw=Ie("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Zi=Ie("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const nw=Ie("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Xd=Ie("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const rw=Ie("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const iw=Ie("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",key:"1xcu5"}],["circle",{cx:"17.5",cy:"10.5",r:".5",key:"736e4u"}],["circle",{cx:"8.5",cy:"7.5",r:".5",key:"clrty"}],["circle",{cx:"6.5",cy:"12.5",r:".5",key:"1s4xz9"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const sw=Ie("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ym=Ie("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Yd=Ie("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Bo=Ie("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Zd=Ie("Sliders",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Qd=Ie("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ow=Ie("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const vm=Ie("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ps={LIBRARY:"library",FOLDER:"folder",IMAGES:"images"};let Gd=0;const aw=()=>(Gd+=1,`req_${Date.now()}_${Gd}`);class lw{constructor(){this.activeRequests=new Map,this.requestContexts=new Map}createRequest(t){const n=aw(),r=new AbortController,i={id:n,type:t,createdAt:Date.now(),abortController:r,signal:r.signal,status:"pending",isActive:!0,cancel:()=>{if(i.isActive){i.isActive=!1,i.status="cancelled",r.abort(),this.requestContexts.delete(n);const s=this.activeRequests.get(t);s&&s.delete(n)}}};return this.requestContexts.set(n,i),this.activeRequests.has(t)||this.activeRequests.set(t,new Map),this.activeRequests.get(t).set(n,i),i}cancelAll(t){const n=this.activeRequests.get(t);if(n){for(const r of n.values())r.cancel();n.clear()}}cancelAllRequests(){for(const t of Object.values(ps))this.cancelAll(t)}isValid(t){const n=this.requestContexts.get(t);return n?n.isActive:!1}complete(t){const n=this.requestContexts.get(t);if(n&&n.isActive){n.status="completed",n.isActive=!1,this.requestContexts.delete(t);const r=this.activeRequests.get(n.type);r&&r.delete(t)}}error(t){const n=this.requestContexts.get(t);if(n&&n.isActive){n.status="error",n.isActive=!1,this.requestContexts.delete(t);const r=this.activeRequests.get(n.type);r&&r.delete(t)}}getActiveCount(t){const n=this.activeRequests.get(t);return n?n.size:0}hasActiveRequests(t){return this.getActiveCount(t)>0}}const Ft=new lw;function Jl(){Ft.cancelAll(ps.IMAGES)}function uw(e){e&&setTimeout(()=>{},300)}const cw=async e=>{try{return(await sr.getStatus(e)).data}catch{return null}};function Jd(){const{libraries:e,currentLibraryId:t,folders:n,selectedFolder:r,totalImageCount:i,setCurrentLibrary:s,setSelectedFolder:o,addLibrary:a,removeLibrary:l}=me(),[d,p]=Z.useState(!1),[y,x]=Z.useState(""),[g,m]=Z.useState(""),[u,v]=Z.useState(""),[c,h]=Z.useState(""),[w,k]=Z.useState(new Set),[b,N]=Z.useState(!1),[T,P]=Z.useState(!1),O=Z.useRef(null),M=A=>{h(A),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{v(A)},300)};Z.useEffect(()=>()=>{O.current&&clearTimeout(O.current)},[]);const J=async()=>{if(!y.trim()){alert("请输入素材库名称");return}if(!g.trim()){alert("请输入文件夹路径");return}N(!0);try{console.log("📝 添加素材库...");const A=await Nn.add(y.trim(),g.trim()),B=A.data.id,D=A.data.hasExistingIndex;if(a({id:B,name:y.trim(),path:g.trim()}),x(""),m(""),p(!1),N(!1),console.log("🔄 切换到新素材库..."),await Nn.setCurrent(B),s(B),o(null),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setSelectedImage(null),me.getState().setTotalImageCount(0),me.getState().setScanProgress({libraryId:B,current:0,total:0,percent:0,status:"preparing"}),D){console.log("检测到已有索引,先加载现有数据...");try{const[le,de]=await Promise.all([Me.getFolders(B),Me.getCount(B)]);me.getState().setFolders(le.data.folders),me.getState().setTotalImageCount(de.data.count),console.log("✅ 已加载现有数据")}catch(le){console.warn("⚠️ 加载现有数据失败:",le)}}console.log("🔍 开始异步扫描..."),D?(console.log("执行增量同步,检测变化..."),sr.sync(B,!1)):(console.log("首次添加,执行全量扫描..."),sr.fullScan(B,!1)),console.log("✅ 扫描已启动,请等待进度显示...")}catch(A){console.error("❌ Error adding library:",A),alert("添加素材库失败: "+A.message),me.getState().setScanProgress(null),N(!1)}},R=async A=>{if(A!==t){P(!0);try{Jl(),Ft.cancelAllRequests(),me.getState().setScanProgress(null),me.getState().setSelectedImage(null),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1}),o(null),await Nn.setCurrent(A);const[B,D]=await Promise.all([Me.getFolders(A),Me.getCount(A)]);me.getState().setFolders(B.data.folders),me.getState().setTotalImageCount(D.data.count),s(A),cw(A).then(le=>{var de,ue;le&&le.status==="paused"&&(le.needsRescan?(me.getState().setScanProgress({...le.progress,libraryId:A,canStop:!0,isPaused:!0,pendingCount:((de=le.progress)==null?void 0:de.total)-((ue=le.progress)==null?void 0:ue.current)||0,needsRescan:!0}),console.log("⏸️ 发现中断的扫描,需要继续完成")):le.pendingCount>0&&(me.getState().setScanProgress({...le.progress,libraryId:A,canStop:!0,isPaused:!0,pendingCount:le.pendingCount}),console.log(`⏸️ 发现暂停的扫描,待处理: ${le.pendingCount} 张`)))}).catch(()=>{})}catch(B){console.error("Error setting current library:",B),alert("切换素材库失败: "+B.message),me.getState().setImageLoadingState({isLoading:!1})}finally{P(!1)}}},W=async()=>{if(!t)return;const A=e.find(D=>D.id===t);if(!(!A||!confirm(`确定要删除素材库"${A.name}"吗?
路径: ${A.path}
⚠️ 注意:
• 将删除索引数据并释放数据库连接
• 不会删除原始图片文件
• .flypic 文件夹将保留,您可以手动删除`)))try{await Nn.delete(t),l(t),me.getState().setImages([]),me.getState().setFolders([]),me.getState().setSelectedImage(null),me.getState().setSelectedFolder(null);const D=e.filter(le=>le.id!==t);if(D.length>0){const le=D[0];await Nn.setCurrent(le.id),s(le.id)}console.log(`✅ 素材库已删除: ${A.name}`),console.log(`数据库连接已释放,可手动删除: ${A.path}\\.flypic`)}catch(D){console.error("Error deleting library:",D),alert("删除素材库失败: "+D.message)}},_=A=>{const B=new Set(w);B.has(A)?B.delete(A):B.add(A),k(B)},V=A=>{const B=[],D=le=>{le.forEach(de=>{de.children&&de.children.length>0&&(B.push(de.path),D(de.children))})};return D(A),B},ce=()=>{const A=V(U.length>0?U:n);k(new Set(A))},Q=()=>{k(new Set)},H=()=>{const A=V(U.length>0?U:n);return A.length>0&&A.every(B=>w.has(B))},U=Z.useMemo(()=>{if(!u)return n;const A=u.trim().toLowerCase().split(/\s+/).filter(de=>de.length>0);if(A.length===0)return n;const B=[],D=de=>de.reduce((ue,se)=>{const X=se.name.toLowerCase(),re=se.path.toLowerCase(),q=A.every(I=>X.includes(I)),ne=A.every(I=>re.includes(I));let f=[];return se.children&&se.children.length>0&&(f=D(se.children)),(q||ne||f.length>0)&&(ue.push({...se,children:f}),f.length>0&&B.push(se.path)),ue},[]),le=D(n);return B.length>0&&setTimeout(()=>{k(de=>{const ue=new Set(de);return B.forEach(se=>ue.add(se)),ue})},0),le},[n,u]),ee=(A,B)=>{A.stopPropagation(),_(B)},z=A=>{const B=A.children&&A.children.length>0;r!==A.path?(Jl(),o(A.path)):B&&_(A.path)},F=(A,B=0)=>A.map(D=>{const le=w.has(D.path),de=D.children&&D.children.length>0,ue=r===D.path;return S.jsxs("div",{children:[S.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${ue?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,style:{paddingLeft:`${B*16+12}px`},onClick:()=>z(D),children:[de?S.jsx("div",{className:"flex items-center justify-center w-5 h-5 mr-1 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 rounded",onClick:se=>ee(se,D.path),children:le?S.jsx(qd,{className:"w-4 h-4 text-gray-500"}):S.jsx(K1,{className:"w-4 h-4 text-gray-500"})}):S.jsx("div",{className:"w-5 mr-1"}),S.jsx(Zi,{className:"w-4 h-4 mr-2 text-gray-500 flex-shrink-0"}),S.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate flex-1",children:D.name}),S.jsx("span",{className:"text-xs text-gray-400 ml-2 flex-shrink-0",children:D.image_count})]}),de&&le&&F(D.children,B+1)]},D.path)});return S.jsxs("div",{className:"w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col",children:[S.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[S.jsx("div",{className:"flex items-center justify-between mb-3",children:S.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"素材库"})}),S.jsxs("div",{className:"flex gap-2",children:[S.jsxs("div",{className:"relative flex-1",children:[S.jsxs("select",{value:t||"",onChange:A=>{const B=A.target.value;B==="__add__"?p(!0):B&&R(B)},disabled:T,className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{paddingRight:"2rem"},children:[e.length===0&&S.jsx("option",{value:"",children:"暂无素材库"}),e.map(A=>S.jsx("option",{value:A.id,children:A.name},A.id)),S.jsx("option",{value:"__add__",style:{borderTop:"1px solid #ccc"},children:"+ 添加新素材库"})]}),S.jsx(qd,{className:"absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none"})]}),t&&e.length>0&&S.jsx("button",{onClick:W,className:"px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors",title:"删除当前素材库",children:S.jsx(ow,{className:"w-4 h-4"})})]}),d&&S.jsxs("div",{className:"mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700",children:[S.jsxs("div",{className:"flex items-center justify-between mb-2",children:[S.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"添加素材库"}),S.jsx("button",{onClick:()=>p(!1),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600",children:S.jsx(vm,{className:"w-4 h-4 text-gray-500"})})]}),S.jsxs("div",{className:"space-y-2",children:[S.jsx("input",{type:"text",placeholder:"素材库名称",value:y,onChange:A=>x(A.target.value),onKeyDown:A=>A.key==="Enter"&&J(),autoFocus:!0,className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),S.jsx("input",{type:"text",placeholder:"文件夹路径(例如:C:\\Users\\Pictures)",value:g,onChange:A=>m(A.target.value),onKeyDown:A=>A.key==="Enter"&&J(),className:"w-full px-2 py Line truncated
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
JSZip uses the library pako released under the MIT license :
https://github.com/nodeca/pako/blob/main/LICENSE
*/(function(e,t){(function(n){e.exports=n()})(function(){return function n(r,i,s){function o(d,p){if(!i[d]){if(!r[d]){var y=typeof Xs=="function"&&Xs;if(!p&&y)return y(d,!0);if(a)return a(d,!0);var x=new Error("Cannot find module '"+d+"'");throw x.code="MODULE_NOT_FOUND",x}var g=i[d]={exports:{}};r[d][0].call(g.exports,function(m){var u=r[d][1][m];return o(u||m)},g,g.exports,n,r,i,s)}return i[d].exports}for(var a=typeof Xs=="function"&&Xs,l=0;l<s.length;l++)o(s[l]);return o}({1:[function(n,r,i){var s=n("./utils"),o=n("./support"),a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(l){for(var d,p,y,x,g,m,u,v=[],c=0,h=l.length,w=h,k=s.getTypeOf(l)!=="string";c<l.length;)w=h-c,y=k?(d=l[c++],p=c<h?l[c++]:0,c<h?l[c++]:0):(d=l.charCodeAt(c++),p=c<h?l.charCodeAt(c++):0,c<h?l.charCodeAt(c++):0),x=d>>2,g=(3&d)<<4|p>>4,m=1<w?(15&p)<<2|y>>6:64,u=2<w?63&y:64,v.push(a.charAt(x)+a.charAt(g)+a.charAt(m)+a.charAt(u));return v.join("")},i.decode=function(l){var d,p,y,x,g,m,u=0,v=0,c="data:";if(l.substr(0,c.length)===c)throw new Error("Invalid base64 input, it looks like a data url.");var h,w=3*(l=l.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(l.charAt(l.length-1)===a.charAt(64)&&w--,l.charAt(l.length-2)===a.charAt(64)&&w--,w%1!=0)throw new Error("Invalid base64 input, bad content length.");for(h=o.uint8array?new Uint8Array(0|w):new Array(0|w);u<l.length;)d=a.indexOf(l.charAt(u++))<<2|(x=a.indexOf(l.charAt(u++)))>>4,p=(15&x)<<4|(g=a.indexOf(l.charAt(u++)))>>2,y=(3&g)<<6|(m=a.indexOf(l.charAt(u++))),h[v++]=d,g!==64&&(h[v++]=p),m!==64&&(h[v++]=y);return h}},{"./support":30,"./utils":32}],2:[function(n,r,i){var s=n("./external"),o=n("./stream/DataWorker"),a=n("./stream/Crc32Probe"),l=n("./stream/DataLengthProbe");function d(p,y,x,g,m){this.compressedSize=p,this.uncompressedSize=y,this.crc32=x,this.compression=g,this.compressedContent=m}d.prototype={getContentWorker:function(){var p=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),y=this;return p.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),p},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(p,y,x){return p.pipe(new a).pipe(new l("uncompressedSize")).pipe(y.compressWorker(x)).pipe(new l("compressedSize")).withStreamInfo("compression",y)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,i){var s=n("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,i){var s=n("./utils"),o=function(){for(var a,l=[],d=0;d<256;d++){a=d;for(var p=0;p<8;p++)a=1&a?3988292384^a>>>1:a>>>1;l[d]=a}return l}();r.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(d,p,y,x){var g=o,m=x+y;d^=-1;for(var u=x;u<m;u++)d=d>>>8^g[255&(d^p[u])];return-1^d}(0|l,a,a.length,0):function(d,p,y,x){var g=o,m=x+y;d^=-1;for(var u=x;u<m;u++)d=d>>>8^g[255&(d^p.charCodeAt(u))];return-1^d}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(n,r,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(n,r,i){var s=null;s=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:s}},{lie:37}],7:[function(n,r,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=n("pako"),a=n("./utils"),l=n("./stream/GenericWorker"),d=s?"uint8array":"array";function p(y,x){l.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=x,this.meta={}}i.magic="\b\0",a.inherits(p,l),p.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(d,y.data),!1)},p.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},p.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},p.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(x){y.push({data:x,meta:y.meta})}},i.compressWorker=function(y){return new p("Deflate",y)},i.uncompressWorker=function(){return new p("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(g,m){var u,v="";for(u=0;u<m;u++)v+=String.fromCharCode(255&g),g>>>=8;return v}function o(g,m,u,v,c,h){var w,k,b=g.file,N=g.compression,T=h!==d.Line truncated
\0`,B+=s(z,2),B+=N.magic,B+=s(w,2),B+=s(k,2),B+=s(ee.crc32,4),B+=s(ee.compressedSize,4),B+=s(ee.uncompressedSize,4),B+=s(P.length,2),B+=s(V.length,2),{fileRecord:y.LOCAL_FILE_HEADER+B+P+V,dirRecord:y.CENTRAL_FILE_HEADER+s(A,2)+B+s(J.length,2)+"\0\0\0\0"+s(F,4)+s(v,4)+P+V+J}}var a=n("../utils"),l=n("../stream/GenericWorker"),d=n("../utf8"),p=n("../crc32"),y=n("../signature");function x(g,m,u,v){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=m,this.zipPlatform=u,this.encodeFileName=v,this.streamFiles=g,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(x,l),x.prototype.push=function(g){var m=g.meta.percent||0,u=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(g):(this.bytesWritten+=g.data.length,l.prototype.push.call(this,{data:g.data,meta:{currentFile:this.currentFile,percent:u?(m+100*(u-v-1))/u:100}}))},x.prototype.openedSource=function(g){this.currentSourceOffset=this.bytesWritten,this.currentFile=g.file.name;var m=this.streamFiles&&!g.file.dir;if(m){var u=o(g,m,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},x.prototype.closedSource=function(g){this.accumulate=!1;var m=this.streamFiles&&!g.file.dir,u=o(g,m,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),m)this.push({data:function(v){return y.DATA_DESCRIPTOR+s(v.crc32,4)+s(v.compressedSize,4)+s(v.uncompressedSize,4)}(g),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},x.prototype.flush=function(){for(var g=this.bytesWritten,m=0;m<this.dirRecords.length;m++)this.push({data:this.dirRecords[m],meta:{percent:100}});var u=this.bytesWritten-g,v=function(c,h,w,k,b){var N=a.transformTo("string",b(k));return y.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(c,2)+s(c,2)+s(h,4)+s(w,4)+s(N.length,2)+N}(this.dirRecords.length,u,g,this.zipComment,this.encodeFileName);this.push({data:v,meta:{percent:100}})},x.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},x.prototype.registerPrevious=function(g){this._sources.push(g);var m=this;return g.on("data",function(u){m.processChunk(u)}),g.on("end",function(){m.closedSource(m.previous.streamInfo),m._sources.length?m.prepareNextSource():m.end()}),g.on("error",function(u){m.error(u)}),this},x.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},x.prototype.error=function(g){var m=this._sources;if(!l.prototype.error.call(this,g))return!1;for(var u=0;u<m.length;u++)try{m[u].error(g)}catch{}return!0},x.prototype.lock=function(){l.prototype.lock.call(this);for(var g=this._sources,m=0;m<g.length;m++)g[m].lock()},r.exports=x},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(n,r,i){var s=n("../compressions"),o=n("./ZipFileWorker");i.generateWorker=function(a,l,d){var p=new o(l.streamFiles,d,l.platform,l.encodeFileName),y=0;try{a.forEach(function(x,g){y++;var m=function(h,w){var k=h||w,b=s[k];if(!b)throw new Error(k+" is not a valid compression method !");return b}(g.options.compression,l.compression),u=g.options.compressionOptions||l.compressionOptions||{},v=g.dir,c=g.date;g._compressWorker(m,u).withStreamInfo("file",{name:x,dir:v,date:c,comment:g.comment||"",unixPermissions:g.unixPermissions,dosPermissions:g.dosPermissions}).pipe(p)}),p.entriesCount=y}catch(x){p.error(x)}return p}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(n,r,i){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var o=new s;for(var a in this)typeof this[a]!="function"&&(o[a]=this[a]);return o}}(s.prototype=n("./object")).loadAsync=n("./load"),s.support=n("./support"),s.defaults=n("./defaults"),s.version="3.10.1",s.loadAsync=function(o,a){return new s().loadAsync(o,a)},s.external=n("./external"),r.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(n,r,i){var s=n("./utils"),o=n("./external"),a=n("./utf8"),l=n("./zipEntries"),d=n("./stream/Crc32Probe"),p=n("./nodejsUtils");function y(x){return new o.Promise(function(g,m){var u=x.decompressed.getContentWorker().pipe(new d);u.on("error",function(v){m(v)}).on("end",function(){u.streamInfo.crc32!==x.decompressed.crc32?m(new Error("Corrupted zip : CRC32 mismatch")):g()}).resume()})}r.exports=function(x,g){var m=thi Line truncated
(当前浏览器环境限制,无法直接复制图片)`)):alert(`复制失败,请手动复制图片链接:
`+A)}catch(A){console.error("复制图片失败:",A),alert("复制图片失败,请重试")}},Q=async A=>new Promise(async B=>{try{const D=document.createElement("div");D.setAttribute("contenteditable","true"),D.style.position="fixed",D.style.left="-9999px",D.style.top="-9999px",D.style.opacity="0",document.body.appendChild(D);for(const{url:se,filename:X}of A)try{const q=await(await fetch(se)).blob(),ne=new Image;ne.crossOrigin="anonymous",await new Promise((E,j)=>{ne.onload=E,ne.onerror=j,ne.src=URL.createObjectURL(q)});const f=document.createElement("canvas");f.width=ne.width,f.height=ne.height,f.getContext("2d").drawImage(ne,0,0),URL.revokeObjectURL(ne.src);const L=f.toDataURL("image/png"),C=document.createElement("img");C.src=L,C.alt=X,C.style.display="block",C.style.marginBottom="10px",D.appendChild(C)}catch(re){console.error(`加载图片失败: ${X}`,re)}await new Promise(se=>setTimeout(se,100));const le=document.createRange();le.selectNodeContents(D);const de=window.getSelection();de.removeAllRanges(),de.addRange(le);let ue=!1;try{ue=document.execCommand("copy")}catch(se){console.error("execCommand copy 失败:",se)}de.removeAllRanges(),document.body.removeChild(D),B(ue)}catch(D){console.error("批量复制图片失败:",D),B(!1)}}),H=async()=>{try{const A=P?t:[e];if(A.length===1){await ce();return}const B=A.map(ue=>({url:Me.getOriginalUrl(n,ue.path),filename:ue.filename})),D=A.map(ue=>ue.filename).join(`
`);if(R())try{const se=(await Promise.all(A.map(async X=>{const re=Me.getOriginalUrl(n,X.path),ne=await(await fetch(re)).blob();return new Promise(f=>{const I=new FileReader;I.onloadend=()=>{f({dataUrl:I.result,filename:X.filename})},I.readAsDataURL(ne)})}))).map(({dataUrl:X,filename:re})=>`<img src="${X}" alt="${re}" style="display:block; margin:10px 0;">`).join(`
`);await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([se],{type:"text/html"}),"text/plain":new Blob([D],{type:"text/plain"})})]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(ue){console.warn("Clipboard API 失败,尝试备用方案:",ue)}if(console.log("尝试 contenteditable 批量复制方案..."),await Q(B)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("批量图片复制失败,降级为复制文件名"),V(D)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制 ${A.length} 个文件名到剪贴板
(当前环境限制,建议使用"导出"功能)`)):alert('复制失败,请使用"导出"功能下载图片')}catch(A){console.error("复制图片失败:",A),alert("复制图片失败,请重试")}},U=async()=>{c(!0);try{const A=P?t:[e];if(A.length===1){const B=Me.getOriginalUrl(n,A[0].path),D=document.createElement("a");D.href=B,D.download=A[0].filename,D.target="_blank",document.body.appendChild(D),D.click(),document.body.removeChild(D)}else{const B=new hf,D=B.folder("images");w(0);for(let ue=0;ue<A.length;ue++){const se=A[ue],X=Me.getOriginalUrl(n,se.path);try{const q=await(await fetch(X)).blob();D.file(se.filename,q);const ne=Math.round((ue+1)/A.length*90);w(ne),console.log(`已添加: ${se.filename} (${ue+1}/${A.length})`)}catch(re){console.error(`下载失败: ${se.filename}`,re)}}w(95),console.log("正在生成 ZIP 文件...");const le=await B.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});w(100);const de=document.createElement("a");de.href=URL.createObjectURL(le),de.download=`FlyPic_导出_${A.length}张_${Date.now()}.zip`,document.body.appendChild(de),de.click(),document.body.removeChild(de),URL.revokeObjectURL(de.href),console.log("导出完成!")}}catch(A){console.error("导出失败:",A),alert("导出失败,请重试")}finally{c(!1)}},ee=async()=>{if(!r){alert("请先选择一个文件夹");return}b(!0),T(0);try{const A=i.filter(se=>se.folder&&se.folder.startsWith(r));if(A.length===0){alert("当前文件夹没有图片");return}const B=new hf,D=r.split("/").pop()||"images",le=B.folder(D);for(let se=0;se<A.length;se++){const X=A[se],re=Me.getOriginalUrl(n,X.path);try{const ne=await(await fetch(re)).blob(),f=X.folder.replace(r,"").replace(/^\//,""),I=f?`${f}/${X.filename}`:X.filename;le.file(I,ne);const L=Math.round((se+1)/A.length*90);T(L),console.log(`已添加: ${I} (${se+1}/${A.length})`)}catch(q){console.error(`下载失败: ${X.filename}`,q)}}T(95),console.log("正在生成 ZIP 文件...");const de=await B.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});T(100);const ue=document.createElement("a");ue.href=URL.createObjectURL(de),ue.download=`${D}_${A.length}张_${Date.now()}.zip`,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue),URL.revokeObjectURL(ue.href),console.log("文件夹导出完成!")}catch(A){console.error("导出文件夹失败:",A),alert("导出文件夹失败,请重试")}finally{b(!1)}},z=A=>A<1024?A+" B":A<1024*1024?(A/1024).toFixed(2)+" KB":(A/(1024*1024)).toFixed(2)+" MB",F=A=>new Date(A).toLocaleString("zh-CN");return S.jsxs("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full",children:[l&&S.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex items-center",children:S.jsxs("button",{onClick:()=>s("main"),className:"flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500",children:[S.jsx(V1,{className:"w-5 h-5"}),S.jsx("span",{className:"text-sm font-medium",children:"返回"})]})}),S.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:S.jsxs("div",{className:"w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative",children:[S.jsx("img",{src:p,alt:O.filename,decoding:"async",className:`w-full h-full object-contain transition-opacity duration-300 ${x?"opacity-75":"opacity-100"}`}),x&&S.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded",children:"加载原图中..."})]})}),S.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 min-h-0",children:S.jsxs("div",{children:[S.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"基本信息"}),S.jsxs("div",{className:"space-y-2 text-sm",children:[S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"文件名:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100 break-all",children:e.filename})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"尺寸:"}),S.jsxs("p",{className:"text-gray-900 dark:text-gray-100",children:[e.width," × ",e.height]})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"大小:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:z(e.size)})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"格式:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100 uppercase",children:e.format})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"创建时间:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:F(e.created_at)})]}),S.jsxs("div",{children:[S.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"修改时间:"}),S.jsx("p",{className:"text-gray-900 dark:text-gray-100", Line truncated
@@ -0,0 +1 @@
.PhotoView-Portal{direction:ltr;height:100%;left:0;overflow:hidden;position:fixed;top:0;touch-action:none;width:100%;z-index:2000}@keyframes PhotoView__rotate{0%{transform:rotate(0)}to{transform:rotate(1turn)}}@keyframes PhotoView__delayIn{0%,50%{opacity:0}to{opacity:1}}.PhotoView__Spinner{animation:PhotoView__delayIn .4s linear both}.PhotoView__Spinner svg{animation:PhotoView__rotate .6s linear infinite}.PhotoView__Photo{cursor:grab;max-width:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.PhotoView__Photo:active{cursor:grabbing}.PhotoView__icon{display:inline-block;left:0;position:absolute;top:0;transform:translate(-50%,-50%)}.PhotoView__PhotoBox,.PhotoView__PhotoWrap{bottom:0;direction:ltr;left:0;position:absolute;right:0;top:0;touch-action:none;width:100%}.PhotoView__PhotoWrap{overflow:hidden;z-index:10}.PhotoView__PhotoBox{transform-origin:left top}@keyframes PhotoView__fade{0%{opacity:0}to{opacity:1}}.PhotoView-Slider__clean .PhotoView-Slider__ArrowLeft,.PhotoView-Slider__clean .PhotoView-Slider__ArrowRight,.PhotoView-Slider__clean .PhotoView-Slider__BannerWrap,.PhotoView-Slider__clean .PhotoView-Slider__Overlay,.PhotoView-Slider__willClose .PhotoView-Slider__BannerWrap:hover{opacity:0}.PhotoView-Slider__Backdrop{background:#000;height:100%;left:0;position:absolute;top:0;transition-property:background-color;width:100%;z-index:-1}.PhotoView-Slider__fadeIn{animation:PhotoView__fade linear both;opacity:0}.PhotoView-Slider__fadeOut{animation:PhotoView__fade linear reverse both;opacity:0}.PhotoView-Slider__BannerWrap{align-items:center;background-color:#00000080;color:#fff;display:flex;height:44px;justify-content:space-between;left:0;position:absolute;top:0;transition:opacity .2s ease-out;width:100%;z-index:20}.PhotoView-Slider__BannerWrap:hover{opacity:1}.PhotoView-Slider__Counter{font-size:14px;opacity:.75;padding:0 10px}.PhotoView-Slider__BannerRight{align-items:center;display:flex;height:100%}.PhotoView-Slider__toolbarIcon{fill:#fff;box-sizing:border-box;cursor:pointer;opacity:.75;padding:10px;transition:opacity .2s linear}.PhotoView-Slider__toolbarIcon:hover{opacity:1}.PhotoView-Slider__ArrowLeft,.PhotoView-Slider__ArrowRight{align-items:center;bottom:0;cursor:pointer;display:flex;height:100px;justify-content:center;margin:auto;opacity:.75;position:absolute;top:0;transition:opacity .2s linear;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:70px;z-index:20}.PhotoView-Slider__ArrowLeft:hover,.PhotoView-Slider__ArrowRight:hover{opacity:1}.PhotoView-Slider__ArrowLeft svg,.PhotoView-Slider__ArrowRight svg{fill:#fff;background:#0000004d;box-sizing:content-box;height:24px;padding:10px;width:24px}.PhotoView-Slider__ArrowLeft{left:0}.PhotoView-Slider__ArrowRight{right:0}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-painLine truncated
@@ -0,0 +1,226 @@
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function r(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(i){if(i.ep)return;i.ep=!0;const s=r(i);fetch(i.href,s)}})();var us=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Il(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _d={exports:{}},_o={},kd={exports:{}},we={};/**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ns=Symbol.for("react.element"),sp=Symbol.for("react.portal"),op=Symbol.for("react.fragment"),ap=Symbol.for("react.strict_mode"),lp=Symbol.for("react.profiler"),up=Symbol.for("react.provider"),cp=Symbol.for("react.context"),dp=Symbol.for("react.forward_ref"),fp=Symbol.for("react.suspense"),hp=Symbol.for("react.memo"),pp=Symbol.for("react.lazy"),Ou=Symbol.iterator;function mp(e){return e===null||typeof e!="object"?null:(e=Ou&&e[Ou]||e["@@iterator"],typeof e=="function"?e:null)}var Sd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},bd=Object.assign,Cd={};function ui(e,t,r){this.props=e,this.context=t,this.refs=Cd,this.updater=r||Sd}ui.prototype.isReactComponent={};ui.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ui.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Ed(){}Ed.prototype=ui.prototype;function jl(e,t,r){this.props=e,this.context=t,this.refs=Cd,this.updater=r||Sd}var Ll=jl.prototype=new Ed;Ll.constructor=jl;bd(Ll,ui.prototype);Ll.isPureReactComponent=!0;var Au=Array.isArray,Nd=Object.prototype.hasOwnProperty,Ol={current:null},Rd={key:!0,ref:!0,__self:!0,__source:!0};function Td(e,t,r){var n,i={},s=null,o=null;if(t!=null)for(n in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(s=""+t.key),t)Nd.call(t,n)&&!Rd.hasOwnProperty(n)&&(i[n]=t[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1<a){for(var l=Array(a),h=0;h<a;h++)l[h]=arguments[h+2];i.children=l}if(e&&e.defaultProps)for(n in a=e.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:ns,type:e,key:s,ref:o,props:i,_owner:Ol.current}}function gp(e,t){return{$$typeof:ns,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Al(e){return typeof e=="object"&&e!==null&&e.$$typeof===ns}function yp(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Pu=/\/+/g;function Wo(e,t){return typeof e=="object"&&e!==null&&e.key!=null?yp(""+e.key):t.toString(36)}function Ls(e,t,r,n,i){var s=typeof e;(s==="undefined"||s==="boolean")&&(e=null);var o=!1;if(e===null)o=!0;else switch(s){case"string":case"number":o=!0;break;case"object":switch(e.$$typeof){case ns:case sp:o=!0}}if(o)return o=e,i=i(o),e=n===""?"."+Wo(o,0):n,Au(i)?(r="",e!=null&&(r=e.replace(Pu,"$&/")+"/"),Ls(i,t,r,"",function(h){return h})):i!=null&&(Al(i)&&(i=gp(i,r+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(Pu,"$&/")+"/")+e)),t.push(i)),1;if(o=0,n=n===""?".":n+":",Au(e))for(var a=0;a<e.length;a++){s=e[a];var l=n+Wo(s,a);o+=Ls(s,t,r,l,i)}else if(l=mp(e),typeof l=="function")for(e=l.call(e),a=0;!(s=e.next()).done;)s=s.value,l=n+Wo(s,a++),o+=Ls(s,t,r,l,i);else if(s==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return o}function cs(e,t,r){if(e==null)return e;var n=[],i=0;return Ls(e,n,"","",function(s){return t.call(r,s,i++)}),n}function vp(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var lt={current:null},Os={transition:null},wp={ReactCurrentDispatcher:lt,ReactCurrentBatchConfig:Os,ReactCurrentOwner:Ol};function zd(){throw Error("act(...) is not supported in production builds of React.")}we.Children={map:cs,forEach:function(e,t,r){cs(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return cs(e,function(){t++}),t},toArray:function(e){return cs(e,function(t){return t})||[]},only:function(e){if(!Al(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};we.Component=ui;we.Fragment=op;we.Profiler=lp;we.PureComponent=jl;we.StrictMode=ap;we.Suspense=fp;we.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=wp;we.act=zd;we.cloneElement=function(e,t,r){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var n=bd({},e.props),i=e.key,s=e.ref,o=e._owner;if(t!=null){if(t.ref!==void 0&&(s=t.ref,o=Ol.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(l in t)Nd.call(t,l)&&!Rd.hasOwnProperty(l)&&(n[l]=t[l]===void 0&&a!==void 0?a[l]:t[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){a=Array(l);for(var h=0;h<l;h++)a[h]=arguments[h+2];n.children=a}return{$$typeof:ns,type:e.type,key:i,ref:s,props:n,_owner:o}};we.createContext=function(e){return e={$$typeof:cp,_currentValue:e,_currentValue2:e,_threadCountLine truncated
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var xp=G,_p=Symbol.for("react.element"),kp=Symbol.for("react.fragment"),Sp=Object.prototype.hasOwnProperty,bp=xp.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Cp={key:!0,ref:!0,__self:!0,__source:!0};function Id(e,t,r){var n,i={},s=null,o=null;r!==void 0&&(s=""+r),t.key!==void 0&&(s=""+t.key),t.ref!==void 0&&(o=t.ref);for(n in t)Sp.call(t,n)&&!Cp.hasOwnProperty(n)&&(i[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps,t)i[n]===void 0&&(i[n]=t[n]);return{$$typeof:_p,type:e,key:s,ref:o,props:i,_owner:bp.current}}_o.Fragment=kp;_o.jsx=Id;_o.jsxs=Id;_d.exports=_o;var k=_d.exports,ba={},jd={exports:{}},kt={},Ld={exports:{}},Od={};/**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/(function(e){function t(Y,$){var J=Y.length;Y.push($);e:for(;0<J;){var M=J-1>>>1,A=Y[M];if(0<i(A,$))Y[M]=$,Y[J]=A,J=M;else break e}}function r(Y){return Y.length===0?null:Y[0]}function n(Y){if(Y.length===0)return null;var $=Y[0],J=Y.pop();if(J!==$){Y[0]=J;e:for(var M=0,A=Y.length,le=A>>>1;M<le;){var B=2*(M+1)-1,N=Y[B],V=B+1,j=Y[V];if(0>i(N,J))V<A&&0>i(j,N)?(Y[M]=j,Y[V]=J,M=V):(Y[M]=N,Y[B]=J,M=B);else if(V<A&&0>i(j,J))Y[M]=j,Y[V]=J,M=V;else break e}}return $}function i(Y,$){var J=Y.sortIndex-$.sortIndex;return J!==0?J:Y.id-$.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],h=[],w=1,y=null,v=3,p=!1,x=!1,u=!1,_=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(Y){for(var $=r(h);$!==null;){if($.callback===null)n(h);else if($.startTime<=Y)n(h),$.sortIndex=$.expirationTime,t(l,$);else break;$=r(h)}}function S(Y){if(u=!1,g(Y),!x)if(r(l)!==null)x=!0,oe(b);else{var $=r(h);$!==null&&Q(S,$.startTime-Y)}}function b(Y,$){x=!1,u&&(u=!1,c(O),O=-1),p=!0;var J=v;try{for(g($),y=r(l);y!==null&&(!(y.expirationTime>$)||Y&&!re());){var M=y.callback;if(typeof M=="function"){y.callback=null,v=y.priorityLevel;var A=M(y.expirationTime<=$);$=e.unstable_now(),typeof A=="function"?y.callback=A:y===r(l)&&n(l),g($)}else n(l);y=r(l)}if(y!==null)var le=!0;else{var B=r(h);B!==null&&Q(S,B.startTime-$),le=!1}return le}finally{y=null,v=J,p=!1}}var R=!1,z=null,O=-1,I=5,P=-1;function re(){return!(e.unstable_now()-P<I)}function T(){if(z!==null){var Y=e.unstable_now();P=Y;var $=!0;try{$=z(!0,Y)}finally{$?H():(R=!1,z=null)}}else R=!1}var H;if(typeof d=="function")H=function(){d(T)};else if(typeof MessageChannel<"u"){var m=new MessageChannel,K=m.port2;m.port1.onmessage=T,H=function(){K.postMessage(null)}}else H=function(){_(T,0)};function oe(Y){z=Y,R||(R=!0,H())}function Q(Y,$){O=_(function(){Y(e.unstable_now())},$)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(Y){Y.callback=null},e.unstable_continueExecution=function(){x||p||(x=!0,oe(b))},e.unstable_forceFrameRate=function(Y){0>Y||125<Y?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<Y?Math.floor(1e3/Y):5},e.unstable_getCurrentPriorityLevel=function(){return v},e.unstable_getFirstCallbackNode=function(){return r(l)},e.unstable_next=function(Y){switch(v){case 1:case 2:case 3:var $=3;break;default:$=v}var J=v;v=$;try{return Y()}finally{v=J}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(Y,$){switch(Y){case 1:case 2:case 3:case 4:case 5:break;default:Y=3}var J=v;v=Y;try{return $()}finally{v=J}},e.unstable_scheduleCallback=function(Y,$,J){var M=e.unstable_now();switch(typeof J=="object"&&J!==null?(J=J.delay,J=typeof J=="number"&&0<J?M+J:M):J=M,Y){case 1:var A=-1;break;case 2:A=250;break;case 5:A=1073741823;break;case 4:A=1e4;break;default:A=5e3}return A=J+A,Y={id:w++,callback:$,priorityLevel:Y,startTime:J,expirationTime:A,sortIndex:-1},J>M?(Y.sortIndex=J,t(h,Y),r(l)===null&&Y===r(h)&&(u?(c(O),O=-1):u=!0,Q(S,J-M))):(Y.sortIndex=A,t(l,Y),x||p||(x=!0,oe(b))),Y},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(Y){var $=v;return function(){var J=v;v=$;try{return Y.apply(this,arguments)}finally{v=J}}}})(Od);Ld.exports=Od;var Ep=Ld.exports;/**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Np=G,_t=Ep;function se(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Ad=new Set,Fi={};function kn(e,t){ei(e,t),ei(e+"Capture",t)}function ei(e,t){for(Fi[e]=t,e=0;e<t.length;e++)Ad.add(t[e])}var br=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ca=Object.prototype.hasOwnProperty,Rp=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Mu={},Du={};function Tp(e){return Ca.call(Du,e)?!0:Ca.call(Mu,e)?!1:Rp.test(e)?Du[e]=!0:(Mu[e]=!0,!1)}function zp(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ip(e,t,r,n){if(t===null||typeof t>"u"||zp(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ut(e,t,r,n,i,s,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=o}var Xe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Xe[e]=new ut(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Xe[t]=new ut(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Xe[e]=new ut(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Xe[e]=new ut(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Xe[e]=new ut(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Xe[e]=new ut(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Xe[e]=new ut(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Xe[e]=new ut(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Xe[e]=new ut(e,5,!1,e.toLowerCase(),null,!1,!1)});var Pl=/[\-:]([a-z])/g;function Ml(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Pl,Ml);Xe[t]=new ut(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Xe[e]=new ut(e,1,!1,e.toLowerCase(),null,!1,!1)});Xe.xlinkHref=new ut("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Xe[e]=new ut(e,1,!1,e.toLowerCase(),null,!0,!0)});function Dl(e,t,r,n){var i=Xe.hasOwnProperty(t)?Xe[t]:null;(i!==null?i.type!==0:n||!(2<t.length)||t[0]!=="o"&&t[0]!== Line truncated
`+Vo+e}var Ho=!1;function qo(e,t){if(!e||Ho)return"";Ho=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(h){var n=h}Reflect.construct(e,[],t)}else{try{t.call()}catch(h){n=h}e.call(t.prototype)}else{try{throw Error()}catch(h){n=h}e()}}catch(h){if(h&&n&&typeof h.stack=="string"){for(var i=h.stack.split(`
`),s=n.stack.split(`
`),o=i.length-1,a=s.length-1;1<=o&&0<=a&&i[o]!==s[a];)a--;for(;1<=o&&0<=a;o--,a--)if(i[o]!==s[a]){if(o!==1||a!==1)do if(o--,a--,0>a||i[o]!==s[a]){var l=`
`+i[o].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{Ho=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?bi(e):""}function jp(e){switch(e.tag){case 5:return bi(e.type);case 16:return bi("Lazy");case 13:return bi("Suspense");case 19:return bi("SuspenseList");case 0:case 2:case 15:return e=qo(e.type,!1),e;case 11:return e=qo(e.type.render,!1),e;case 1:return e=qo(e.type,!0),e;default:return""}}function Ta(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case An:return"Fragment";case On:return"Portal";case Ea:return"Profiler";case Fl:return"StrictMode";case Na:return"Suspense";case Ra:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Md:return(e.displayName||"Context")+".Consumer";case Pd:return(e._context.displayName||"Context")+".Provider";case Bl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ul:return t=e.displayName||null,t!==null?t:Ta(e.type)||"Memo";case Pr:t=e._payload,e=e._init;try{return Ta(e(t))}catch{}}return null}function Lp(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ta(t);case 8:return t===Fl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Gr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Fd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Op(e){var t=Fd(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,s=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(o){n=""+o,s.call(this,o)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(o){n=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function fs(e){e._valueTracker||(e._valueTracker=Op(e))}function Bd(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=Fd(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function Zs(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function za(e,t){var r=t.checked;return Me({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function Bu(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=Gr(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ud(e,t){t=t.checked,t!=null&&Dl(e,"checked",t,!1)}function Ia(e,t){Ud(e,t);var r=Gr(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?ja(e,t.type,r):t.hasOwnProperty("defaultValue")&&ja(e,t.type,Gr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Uu(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function ja(e,t,r){(t!=="number"||Zs(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Ci=Array.isArray;function Kn(e,t,r,n){if(e=e.options,t){t={};for(var i=0;i<r.length;i++)t["$"+r[i]]=!0;for(r=0;r<e.length;r++)i=t.hasOwnProperty("$"+e[r].value),e[r].selected!==i&&(e[r].selected=i),i&&n&&(e[r].defaultSelected=!0)}else{for(r=""+Gr(r),t=null,i=0;i<e.length;i++){if(e[i].value===r){e[i].selected=!0,n&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function La(e,t){if(t.dan Line truncated
`).replace(Vm,"")}function xs(e,t,r){if(t=cc(t),cc(e)!==t&&r)throw Error(se(425))}function no(){}var qa=null,Ka=null;function Ya(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Za=typeof setTimeout=="function"?setTimeout:void 0,Hm=typeof clearTimeout=="function"?clearTimeout:void 0,dc=typeof Promise=="function"?Promise:void 0,qm=typeof queueMicrotask=="function"?queueMicrotask:typeof dc<"u"?function(e){return dc.resolve(null).then(e).catch(Km)}:Za;function Km(e){setTimeout(function(){throw e})}function sa(e,t){var r=t,n=0;do{var i=r.nextSibling;if(e.removeChild(r),i&&i.nodeType===8)if(r=i.data,r==="/$"){if(n===0){e.removeChild(i),Vi(t);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=i}while(r);Vi(t)}function qr(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function fc(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var di=Math.random().toString(36).slice(2),tr="__reactFiber$"+di,Zi="__reactProps$"+di,Cr="__reactContainer$"+di,Xa="__reactEvents$"+di,Ym="__reactListeners$"+di,Zm="__reactHandles$"+di;function fn(e){var t=e[tr];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Cr]||r[tr]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=fc(e);e!==null;){if(r=e[tr])return r;e=fc(e)}return t}e=r,r=e.parentNode}return null}function os(e){return e=e[tr]||e[Cr],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Fn(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(se(33))}function Eo(e){return e[Zi]||null}var Qa=[],Bn=-1;function tn(e){return{current:e}}function je(e){0>Bn||(e.current=Qa[Bn],Qa[Bn]=null,Bn--)}function Ne(e,t){Bn++,Qa[Bn]=e.current,e.current=t}var Jr={},rt=tn(Jr),ft=tn(!1),yn=Jr;function ti(e,t){var r=e.type.contextTypes;if(!r)return Jr;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in r)i[s]=t[s];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function ht(e){return e=e.childContextTypes,e!=null}function io(){je(ft),je(rt)}function hc(e,t,r){if(rt.current!==Jr)throw Error(se(168));Ne(rt,t),Ne(ft,r)}function zf(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in t))throw Error(se(108,Lp(e)||"Unknown",i));return Me({},r,n)}function so(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Jr,yn=rt.current,Ne(rt,e),Ne(ft,ft.current),!0}function pc(e,t,r){var n=e.stateNode;if(!n)throw Error(se(169));r?(e=zf(e,t,yn),n.__reactInternalMemoizedMergedChildContext=e,je(ft),je(rt),Ne(rt,e)):je(ft),Ne(ft,r)}var wr=null,No=!1,oa=!1;function If(e){wr===null?wr=[e]:wr.push(e)}function Xm(e){No=!0,If(e)}function rn(){if(!oa&&wr!==null){oa=!0;var e=0,t=Ce;try{var r=wr;for(Ce=1;e<r.length;e++){var n=r[e];do n=n(!0);while(n!==null)}wr=null,No=!1}catch(i){throw wr!==null&&(wr=wr.slice(e+1)),tf(Wl,rn),i}finally{Ce=t,oa=!1}}return null}var Un=[],$n=0,oo=null,ao=0,Tt=[],zt=0,vn=null,_r=1,kr="";function ln(e,t){Un[$n++]=ao,Un[$n++]=oo,oo=e,ao=t}function jf(e,t,r){Tt[zt++]=_r,Tt[zt++]=kr,Tt[zt++]=vn,vn=e;var n=_r;e=kr;var i=32-Vt(n)-1;n&=~(1<<i),r+=1;var s=32-Vt(t)+i;if(30<s){var o=i-i%5;s=(n&(1<<o)-1).toString(32),n>>=o,i-=o,_r=1<<32-Vt(t)+i|r<<i|n,kr=s+e}else _r=1<<s|r<<i|n,kr=e}function Gl(e){e.return!==null&&(ln(e,1),jf(e,1,0))}function Jl(e){for(;e===oo;)oo=Un[--$n],Un[$n]=null,ao=Un[--$n],Un[$n]=null;for(;e===vn;)vn=Tt[--zt],Tt[zt]=null,kr=Tt[--zt],Tt[zt]=null,_r=Tt[--zt],Tt[zt]=null}var xt=null,wt=null,Oe=!1,Wt=null;function Lf(e,t){var r=Lt(5,null,null,0);r.elementType="DELETED",r.stateNode=t,r.return=e,t=e.deletions,t===null?(e.deletions=[r],e.flags|=16):t.push(r)}function mc(e,t){switch(e.tag){case 5:var r=e.type;return t=t.nodeType!==1||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,xt=e,wt=qr(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,xt=e,wt=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(r=vn!==null?{id:_r,overflow:kr}:null,e.memoizedState={dehydrated:t,treeContext:r,retryLane:1073741824},r=Lt(18,null,null,0),r.stateNode=t,r.return=e,e.child=r,xt=e,wt=null,!0):!1;default:return!1}}function Ga(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Ja(e){if(Oe){var t=wt;if(t){var r=t;if(!mc(e,t)){if(Ga(e))throw Error(se(418));t=qr(r.nextSibling);var n=xt;t&&mc(e,t)?Lf(n,r):(e.flags=e.flags&-4097|2,Oe=!1,xt=e)}}else{if(Ga(e))throw Error(se(418));e.flags=e.flags&-4097|2,Oe=!1,xt=e}}}function gc(e){ Line truncated
Error generating stack: `+s.message+`
`+s.stack}return{value:e,source:t,stack:i,digest:null}}function da(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function nl(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var s0=typeof WeakMap=="function"?WeakMap:Map;function oh(e,t,r){r=Sr(-1,r),r.tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){go||(go=!0,hl=n),nl(e,t)},r}function ah(e,t,r){r=Sr(-1,r),r.tag=3;var n=e.type.getDerivedStateFromError;if(typeof n=="function"){var i=t.value;r.payload=function(){return n(i)},r.callback=function(){nl(e,t)}}var s=e.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(r.callback=function(){nl(e,t),typeof n!="function"&&(Yr===null?Yr=new Set([this]):Yr.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),r}function bc(e,t,r){var n=e.pingCache;if(n===null){n=e.pingCache=new s0;var i=new Set;n.set(t,i)}else i=n.get(t),i===void 0&&(i=new Set,n.set(t,i));i.has(r)||(i.add(r),e=w0.bind(null,e,t,r),t.then(e,e))}function Cc(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ec(e,t,r,n,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=Sr(-1,1),t.tag=2,Kr(r,t,1))),r.lanes|=1),e)}var o0=Rr.ReactCurrentOwner,dt=!1;function ot(e,t,r,n){t.child=e===null?Pf(t,null,r,n):ni(t,e.child,r,n)}function Nc(e,t,r,n,i){r=r.render;var s=t.ref;return Qn(t,i),n=cu(e,t,r,n,s,i),r=du(),e!==null&&!dt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Nr(e,t,i)):(Oe&&r&&Gl(t),t.flags|=1,ot(e,t,n,i),t.child)}function Rc(e,t,r,n,i){if(e===null){var s=r.type;return typeof s=="function"&&!_u(s)&&s.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=s,lh(e,t,s,n,i)):(e=Vs(r.type,null,n,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(s=e.child,!(e.lanes&i)){var o=s.memoizedProps;if(r=r.compare,r=r!==null?r:qi,r(o,n)&&e.ref===t.ref)return Nr(e,t,i)}return t.flags|=1,e=Xr(s,n),e.ref=t.ref,e.return=t,t.child=e}function lh(e,t,r,n,i){if(e!==null){var s=e.memoizedProps;if(qi(s,n)&&e.ref===t.ref)if(dt=!1,t.pendingProps=n=s,(e.lanes&i)!==0)e.flags&131072&&(dt=!0);else return t.lanes=e.lanes,Nr(e,t,i)}return il(e,t,r,n,i)}function uh(e,t,r){var n=t.pendingProps,i=n.children,s=e!==null?e.memoizedState:null;if(n.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},Ne(Hn,vt),vt|=r;else{if(!(r&1073741824))return e=s!==null?s.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,Ne(Hn,vt),vt|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=s!==null?s.baseLanes:r,Ne(Hn,vt),vt|=n}else s!==null?(n=s.baseLanes|r,t.memoizedState=null):n=r,Ne(Hn,vt),vt|=n;return ot(e,t,i,r),t.child}function ch(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function il(e,t,r,n,i){var s=ht(r)?yn:rt.current;return s=ti(t,s),Qn(t,i),r=cu(e,t,r,n,s,i),n=du(),e!==null&&!dt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,Nr(e,t,i)):(Oe&&n&&Gl(t),t.flags|=1,ot(e,t,r,i),t.child)}function Tc(e,t,r,n,i){if(ht(r)){var s=!0;so(t)}else s=!1;if(Qn(t,i),t.stateNode===null)Us(e,t),sh(t,r,n),rl(t,r,n,i),n=!0;else if(e===null){var o=t.stateNode,a=t.memoizedProps;o.props=a;var l=o.context,h=r.contextType;typeof h=="object"&&h!==null?h=At(h):(h=ht(r)?yn:rt.current,h=ti(t,h));var w=r.getDerivedStateFromProps,y=typeof w=="function"||typeof o.getSnapshotBeforeUpdate=="function";y||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==n||l!==h)&&Sc(t,o,n,h),Mr=!1;var v=t.memoizedState;o.state=v,co(t,n,o,i),l=t.memoizedState,a!==n||v!==l||ft.current||Mr?(typeof w=="function"&&(tl(t,r,w,n),l=t.memoizedState),(a=Mr||kc(t,r,a,n,v,l,h))?(y||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount=="function"&&(t.flags|=4194308)):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=l),o.props=n,o.state=l,o.context=h,n=a):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),n=!1)}else{o=t.stateNode,Df(e,t),a=t.memoizedProps,h=t.type===t.elementType?a:Bt(t.type,a),o.props=h,y=t.pendingProps,v=o.context,l=r.contextType,typeof l=="object"&&l!==null?l=At(l):(l=ht(r)?yn:rt.current,l=ti(t,l));var p=r.getDerivedStateFromProps;(w=typeof p=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==y||v!==l)&&Sc(t,o,n,l),Mr=!1,v=t.memoizedState,o.state=v,co(t,n,o,i);var x=t.memoizedS Line truncated
* @license React
* use-sync-external-store-shim.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ai=G;function Cg(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Eg=typeof Object.is=="function"?Object.is:Cg,Ng=ai.useState,Rg=ai.useEffect,Tg=ai.useLayoutEffect,zg=ai.useDebugValue;function Ig(e,t){var r=t(),n=Ng({inst:{value:r,getSnapshot:t}}),i=n[0].inst,s=n[1];return Tg(function(){i.value=r,i.getSnapshot=t,va(i)&&s({inst:i})},[e,r,t]),Rg(function(){return va(i)&&s({inst:i}),e(function(){va(i)&&s({inst:i})})},[e]),zg(r),r}function va(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!Eg(e,r)}catch{return!0}}function jg(e,t){return t()}var Lg=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?jg:Ig;Qh.useSyncExternalStore=ai.useSyncExternalStore!==void 0?ai.useSyncExternalStore:Lg;Xh.exports=Qh;var Og=Xh.exports;/**
* @license React
* use-sync-external-store-shim/with-selector.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Fo=G,Ag=Og;function Pg(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Mg=typeof Object.is=="function"?Object.is:Pg,Dg=Ag.useSyncExternalStore,Fg=Fo.useRef,Bg=Fo.useEffect,Ug=Fo.useMemo,$g=Fo.useDebugValue;Zh.useSyncExternalStoreWithSelector=function(e,t,r,n,i){var s=Fg(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=Ug(function(){function l(p){if(!h){if(h=!0,w=p,p=n(p),i!==void 0&&o.hasValue){var x=o.value;if(i(x,p))return y=x}return y=p}if(x=y,Mg(w,p))return x;var u=n(p);return i!==void 0&&i(x,u)?(w=p,x):(w=p,y=u)}var h=!1,w,y,v=r===void 0?null:r;return[function(){return l(t())},v===null?void 0:function(){return l(v())}]},[t,r,n,i]);var a=Dg(e,s[0],s[1]);return Bg(function(){o.hasValue=!0,o.value=a},[a]),$g(a),a};Yh.exports=Zh;var Wg=Yh.exports;const Vg=Il(Wg),Gh={},{useDebugValue:Hg}=ye,{useSyncExternalStoreWithSelector:qg}=Vg;let Zc=!1;const Kg=e=>e;function Yg(e,t=Kg,r){(Gh?"production":void 0)!=="production"&&r&&!Zc&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Zc=!0);const n=qg(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return Hg(n),n}const Xc=e=>{(Gh?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?bg(e):e,r=(n,i)=>Yg(t,n,i);return Object.assign(r,t),r},Bo=e=>e?Xc(e):Xc,yt=Bo(e=>({theme:"light",mobileView:"main",thumbnailHeight:200,isResizingPanels:!1,resizingSide:null,setTheme:t=>e({theme:t}),toggleTheme:()=>e(t=>({theme:t.theme==="light"?"dark":"light"})),setMobileView:t=>e({mobileView:t}),setThumbnailHeight:t=>e({thumbnailHeight:t}),setIsResizingPanels:t=>e({isResizingPanels:t}),setResizingSide:t=>e({resizingSide:t})})),rr=Bo((e,t)=>({libraries:[],currentLibraryId:null,setLibraries:r=>e({libraries:r}),setCurrentLibrary:r=>e({currentLibraryId:r}),addLibrary:r=>e(n=>({libraries:[...n.libraries,r]})),removeLibrary:r=>e(n=>({libraries:n.libraries.filter(i=>i.id!==r),currentLibraryId:n.currentLibraryId===r?null:n.currentLibraryId})),updateLibrary:(r,n)=>e(i=>({libraries:i.libraries.map(s=>s.id===r?{...s,...n}:s)})),getCurrentLibrary:()=>{const{libraries:r,currentLibraryId:n}=t();return r.find(i=>i.id===n)}})),_e=Bo((e,t)=>({images:[],selectedImage:null,selectedImages:[],totalImageCount:0,folders:[],selectedFolder:null,searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null},imageLoadingState:{isLoading:!1,loadedCount:0,totalCount:0,hasMore:!1},setImages:r=>e({images:r}),appendImages:r=>e(n=>({images:[...n.images,...r]})),clearImages:()=>e({images:[]}),setSelectedImage:r=>e({selectedImage:r}),setSelectedImages:r=>e({selectedImages:r}),toggleImageSelection:r=>e(n=>({selectedImages:n.selectedImages.some(s=>s.path===r.path)?n.selectedImages.filter(s=>s.path!==r.path):[...n.selectedImages,r]})),clearSelection:()=>e({selectedImages:[],selectedImage:null}),setFolders:r=>e({folders:r}),setSelectedFolder:r=>e({selectedFolder:r}),setSearchKeywords:r=>e({searchKeywords:r}),setFilters:r=>e(n=>({filters:{...n.filters,...r}})),resetFilters:()=>e({searchKeywords:"",filters:{formats:[],minSize:null,maxSize:null,startDate:null,endDate:null}}),setTotalImageCount:r=>e({totalImageCount:r}),setImageLoadingState:r=>e(n=>({imageLoadingState:{...n.imageLoadingState,...r}}))})),cn=Bo((e,t)=>({scanProgress:null,scanStartTime:null,setScanProgress:r=>e(n=>r&&!n.scanStartTime&&r.current>0?{scanProgress:r,scanStartTime:Date.now()}:r?{scanProgress:r}:{scanProgress:null,scanStartTime:null}),clearScanProgress:()=>e({scanProgress:null,scanStartTime:null}),getEstimatedTimeLeft:()=>{const{scanProgress:r,scanStartTime:n}=t();if(!r||!n||r.current===0)return null;const i=Date.now()-n,s=r.current/i,o=r.total-r.current;return Math.ceil(o/s/1e3)},isScanning:()=>{const{scanProgress:r}=t();return r&&r.status!=="preparing"}})),Zg="/api";class wa extends Error{constructor(t,r,n){super(t),this.name="APIError",this.status=r,this.data=n}}async function Uo(e,t={}){var n;const r={headers:{"Content-Type":"application/json",...t.headers},...t};try{const i=await fetch(`${Zg}${e}`,r),s=await i.json();if(!i.ok)throw new wa(((n=s.error)==null?void 0:n.message)||s.error||"Request failed",i.status,s);return s.data!==void 0?s.data:s}catch(i){throw i instanceof wa?i:new wa(i.message||"Network error",0,null)}}function Xg(e,t={}){return Uo(e,{method:"GET",...t})}function Qg(e,t,r={}){return Uo(e,{method:"POST",body:JSON.stringify(t),...r})}function Gg(e,t,r={}){return Uo(e,{method:"PUT",body:JSON.stringify(t),...r})}function Jg(e,t={}){return Uo(e,{method:"DELETE",...t})}const Qe={get:Xg,post:Qg,put:Gg,delete:Jg};async function ey(){return Qe.get("/library")}async function ty(e,t){return Line truncated
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/var Sy={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const by=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Re=(e,t)=>{const r=G.forwardRef(({color:n="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:o,className:a="",children:l,...h},w)=>G.createElement("svg",{ref:w,...Sy,width:i,height:i,stroke:n,strokeWidth:o?Number(s)*24/Number(i):s,className:["lucide",`lucide-${by(e)}`,a].join(" "),...h},[...t.map(([y,v])=>G.createElement(y,v)),...Array.isArray(l)?l:[l]]));return r.displayName=`${e}`,r};/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Cy=Re("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ey=Re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Qc=Re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ny=Re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ry=Re("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ty=Re("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const zy=Re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Iy=Re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const jy=Re("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ly=Re("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Oy=Re("File",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Gc=Re("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Ay=Re("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Di=Re("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Py=Re("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const My=Re("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Jc=Re("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Dy=Re("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Fy=Re("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",key:"1xcu5"}],["circle",{cx:"17.5",cy:"10.5",r:".5",key:"736e4u"}],["circle",{cx:"8.5",cy:"7.5",r:".5",key:"clrty"}],["circle",{cx:"6.5",cy:"12.5",r:".5",key:"1s4xz9"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const By=Re("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ed=Re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const bl=Re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const td=Re("Sliders",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const rd=Re("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const Uy=Re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
* @license lucide-react v0.300.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const ep=Re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),rs={LIBRARY:"library",FOLDER:"folder",IMAGES:"images"};let nd=0;const $y=()=>(nd+=1,`req_${Date.now()}_${nd}`);class Wy{constructor(){this.activeRequests=new Map,this.requestContexts=new Map}createRequest(t){const r=$y(),n=new AbortController,i={id:r,type:t,createdAt:Date.now(),abortController:n,signal:n.signal,status:"pending",isActive:!0,cancel:()=>{if(i.isActive){i.isActive=!1,i.status="cancelled",n.abort(),this.requestContexts.delete(r);const s=this.activeRequests.get(t);s&&s.delete(r)}}};return this.requestContexts.set(r,i),this.activeRequests.has(t)||this.activeRequests.set(t,new Map),this.activeRequests.get(t).set(r,i),i}cancelAll(t){const r=this.activeRequests.get(t);if(r){for(const n of r.values())n.cancel();r.clear()}}cancelAllRequests(){for(const t of Object.values(rs))this.cancelAll(t)}isValid(t){const r=this.requestContexts.get(t);return r?r.isActive:!1}complete(t){const r=this.requestContexts.get(t);if(r&&r.isActive){r.status="completed",r.isActive=!1,this.requestContexts.delete(t);const n=this.activeRequests.get(r.type);n&&n.delete(t)}}error(t){const r=this.requestContexts.get(t);if(r&&r.isActive){r.status="error",r.isActive=!1,this.requestContexts.delete(t);const n=this.activeRequests.get(r.type);n&&n.delete(t)}}getActiveCount(t){const r=this.activeRequests.get(t);return r?r.size:0}hasActiveRequests(t){return this.getActiveCount(t)>0}}const jt=new Wy;function Cl(){jt.cancelAll(rs.IMAGES)}function Vy(e){e&&setTimeout(()=>{},300)}const Hy=async e=>{try{const t=await li.getStatus(e);return t.data||t}catch{return null}};function id(){const{libraries:e,currentLibraryId:t,setCurrentLibrary:r,addLibrary:n,removeLibrary:i}=rr(),{folders:s,selectedFolder:o,totalImageCount:a,setSelectedFolder:l}=_e(),{isScanning:h}=cn(),[w,y]=G.useState(!1),[v,p]=G.useState(""),[x,u]=G.useState(""),[_,c]=G.useState(""),[d,g]=G.useState(""),[S,b]=G.useState(new Set),[R,z]=G.useState(!1),[O,I]=G.useState(!1),P=G.useRef(null),re=B=>{g(B),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{c(B)},300)};G.useEffect(()=>()=>{P.current&&clearTimeout(P.current)},[]);const T=async()=>{var B,N;if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}if(!v.trim()){alert("请输入素材库名称");return}if(!x.trim()){alert("请输入文件夹路径");return}z(!0);try{console.log("📝 添加素材库...");const V=await xr.add(v.trim(),x.trim()),j=V.id,W=V.hasExistingIndex;if(n({id:j,name:v.trim(),path:x.trim()}),p(""),u(""),y(!1),z(!1),console.log("🔄 切换到新素材库..."),await xr.setCurrent(j),r(j),l(null),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setSelectedImage(null),_e.getState().setTotalImageCount(0),cn.getState().setScanProgress({libraryId:j,current:0,total:0,percent:0,status:"preparing"}),W){console.log("检测到已有索引,先加载现有数据...");try{const[q,X]=await Promise.all([Le.getFolders(j),Le.getCount(j)]);_e.getState().setFolders(q.folders),_e.getState().setTotalImageCount(X.count),console.log("✅ 已加载现有数据")}catch(q){console.warn("⚠️ 加载现有数据失败:",q)}}console.log("🔍 开始异步扫描..."),W?(console.log("执行增量同步,检测变化..."),li.sync(j,!1)):(console.log("首次添加,执行全量扫描..."),li.fullScan(j,!1)),console.log("✅ 扫描已启动,请等待进度显示...")}catch(V){console.error("❌ Error adding library:",V);let j=V.message||"未知错误";(N=(B=V.response)==null?void 0:B.data)!=null&&N.message&&(j=V.response.data.message),j.includes("无法访问")||j.includes("权限")||j.includes("数据共享")?alert(`⚠️ 文件夹权限不足
`+j+`
操作步骤:
1. 应用中心找到 FlyPic 应用
2. 点击 应用设置
3. 将该文件夹添加到 FlyPic 应用的读写权限`):alert("添加素材库失败: "+j),cn.getState().setScanProgress(null),z(!1)}},H=async B=>{if(B!==t){if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}I(!0);try{Cl(),jt.cancelAllRequests(),cn.getState().setScanProgress(null),_e.getState().setSelectedImage(null),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setImageLoadingState({isLoading:!1,loadedCount:0,totalCount:0}),l(null),await xr.setCurrent(B);const[N,V]=await Promise.all([Le.getFolders(B),Le.getCount(B)]);_e.getState().setFolders(N.folders),_e.getState().setTotalImageCount(V.count),r(B),Hy(B).then(j=>{j&&j.status==="scanning"&&cn.getState().setScanProgress(j.progress)}).catch(()=>{})}catch(N){console.error("Error setting current library:",N),alert("切换素材库失败: "+N.message),_e.getState().setImageLoadingState({isLoading:!1})}finally{I(!1)}}},m=async()=>{if(!t)return;if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}const B=e.find(V=>V.id===t);if(!(!B||!confirm(`确定要删除素材库"${B.name}"吗?
路径: ${B.path}
⚠️ 注意:
• 将删除索引数据并释放数据库连接
• 不会删除原始图片文件
• .flypic 文件夹将保留,您可以手动删除`)))try{await xr.remove(t),i(t),_e.getState().setImages([]),_e.getState().setFolders([]),_e.getState().setSelectedImage(null),_e.getState().setSelectedFolder(null);const V=e.filter(j=>j.id!==t);if(V.length>0){const j=V[0];await xr.setCurrent(j.id),r(j.id)}console.log(`✅ 素材库已删除: ${B.name}`),console.log(`数据库连接已释放,可手动删除: ${B.path}\\.flypic`)}catch(V){console.error("Error deleting library:",V),alert("删除素材库失败: "+V.message)}},K=B=>{const N=new Set(S);N.has(B)?N.delete(B):N.add(B),b(N)},oe=B=>{const N=[],V=j=>{j.forEach(W=>{W.children&&W.children.length>0&&(N.push(W.path),V(W.children))})};return V(B),N},Q=()=>{const B=oe(J.length>0?J:s);b(new Set(B))},Y=()=>{b(new Set)},$=()=>{const B=oe(J.length>0?J:s);return B.length>0&&B.every(N=>S.has(N))},J=G.useMemo(()=>{if(!_)return s;const B=_.trim().toLowerCase().split(/\s+/).filter(W=>W.length>0);if(B.length===0)return s;const N=[],V=W=>W.reduce((q,X)=>{const ne=X.name.toLowerCase(),ce=X.path.toLowerCase(),de=B.every(D=>ne.includes(D)),f=B.every(D=>ce.includes(D));let F=[];return X.children&&X.children.length>0&&(F=V(X.children)),(de||f||F.length>0)&&(q.push({...X,children:F}),F.length>0&&N.push(X.path)),q},[]),j=V(s);return N.length>0&&setTimeout(()=>{b(W=>{const q=new Set(W);return N.forEach(X=>q.add(X)),q})},0),j},[s,_]),M=(B,N)=>{B.stopPropagation(),K(N)},A=B=>{const N=B.children&&B.children.length>0;o!==B.path?(Cl(),l(B.path)):N&&K(B.path)},le=(B,N=0)=>B.map(V=>{const j=S.has(V.path),W=V.children&&V.children.length>0,q=o===V.path;return k.jsxs("div",{children:[k.jsxs("div",{className:`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${q?"bg-blue-50 dark:bg-blue-900":"hover:bg-gray-100 dark:hover:bg-gray-700"}`,style:{paddingLeft:`${N*16+12}px`},onClick:()=>A(V),children:[W?k.jsx("div",{className:"flex items-center justify-center w-5 h-5 mr-1 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 rounded",onClick:X=>M(X,V.path),children:j?k.jsx(Qc,{className:"w-4 h-4 text-gray-500"}):k.jsx(Ny,{className:"w-4 h-4 text-gray-500"})}):k.jsx("div",{className:"w-5 mr-1"}),k.jsx(Di,{className:"w-4 h-4 mr-2 text-gray-500 flex-shrink-0"}),k.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate flex-1",children:V.name}),k.jsx("span",{className:"text-xs text-gray-400 ml-2 flex-shrink-0",children:V.imageCount})]}),W&&j&&le(V.children,N+1)]},V.path)});return k.jsxs("div",{className:"w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col",children:[k.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[k.jsx("div",{className:"flex items-center justify-between mb-3",children:k.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"素材库"})}),k.jsxs("div",{className:"flex gap-2",children:[k.jsxs("div",{className:"relative flex-1",children:[k.jsxs("select",{value:t||"",onChange:B=>{const N=B.target.value;if(N==="__add__"){if(h()){alert("扫描进行中,请稍后再试或暂停扫描");return}y(!0)}else N&&H(N)},disabled:O||h(),className:"w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{paddingRight:"2rem"},children:[e.length===0&&k.jsx("option",{value:"",children:"暂无素材库"}),e.map(B=>k.jsx("option",{value:B.id,children:B.name},B.id)),k.jsx("option",{value:"__add__",style:{borderTop:"1px solid #ccc"},children:"+ 添加新素材库"})]}),k.jsx(Qc,{className:"absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none"})]}),t&&e.length>0&&k.jsx("button",{onClick:m,disabled:h(),className:"px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:h()?"扫描进行中,无法删除":"删除当前素材库",children:k.jsx(Uy,{className:"w-4 h-4"})})]}),w&&k.jsxs("div",{className:"mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700",children:[k.jsxs("div",{className:"flex items-center justify-between mb-2",children:[k.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"添加素材库"}),k.jsx("button",{onClick:()=>y(!1),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600",children:k.jsx(ep,{className:"w-4 h-4 text-gray-500"})})]}),k.jsxs("div",{className:"space-y-2",children:[k.jsx("input",{type:"text",placeholder:"素材库名称",value:v,onChange:B=>p(B.target.value),onKeyDown:B=>B.key==="Enter"&&T(),autoFocus:!0,className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"}),k.jsx("input",{type:"text",placeholder:"文件 Line truncated
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
JSZip uses the library pako released under the MIT license :
https://github.com/nodeca/pako/blob/main/LICENSE
*/(function(e,t){(function(r){e.exports=r()})(function(){return function r(n,i,s){function o(h,w){if(!i[h]){if(!n[h]){var y=typeof js=="function"&&js;if(!w&&y)return y(h,!0);if(a)return a(h,!0);var v=new Error("Cannot find module '"+h+"'");throw v.code="MODULE_NOT_FOUND",v}var p=i[h]={exports:{}};n[h][0].call(p.exports,function(x){var u=n[h][1][x];return o(u||x)},p,p.exports,r,n,i,s)}return i[h].exports}for(var a=typeof js=="function"&&js,l=0;l<s.length;l++)o(s[l]);return o}({1:[function(r,n,i){var s=r("./utils"),o=r("./support"),a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(l){for(var h,w,y,v,p,x,u,_=[],c=0,d=l.length,g=d,S=s.getTypeOf(l)!=="string";c<l.length;)g=d-c,y=S?(h=l[c++],w=c<d?l[c++]:0,c<d?l[c++]:0):(h=l.charCodeAt(c++),w=c<d?l.charCodeAt(c++):0,c<d?l.charCodeAt(c++):0),v=h>>2,p=(3&h)<<4|w>>4,x=1<g?(15&w)<<2|y>>6:64,u=2<g?63&y:64,_.push(a.charAt(v)+a.charAt(p)+a.charAt(x)+a.charAt(u));return _.join("")},i.decode=function(l){var h,w,y,v,p,x,u=0,_=0,c="data:";if(l.substr(0,c.length)===c)throw new Error("Invalid base64 input, it looks like a data url.");var d,g=3*(l=l.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(l.charAt(l.length-1)===a.charAt(64)&&g--,l.charAt(l.length-2)===a.charAt(64)&&g--,g%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=o.uint8array?new Uint8Array(0|g):new Array(0|g);u<l.length;)h=a.indexOf(l.charAt(u++))<<2|(v=a.indexOf(l.charAt(u++)))>>4,w=(15&v)<<4|(p=a.indexOf(l.charAt(u++)))>>2,y=(3&p)<<6|(x=a.indexOf(l.charAt(u++))),d[_++]=h,p!==64&&(d[_++]=w),x!==64&&(d[_++]=y);return d}},{"./support":30,"./utils":32}],2:[function(r,n,i){var s=r("./external"),o=r("./stream/DataWorker"),a=r("./stream/Crc32Probe"),l=r("./stream/DataLengthProbe");function h(w,y,v,p,x){this.compressedSize=w,this.uncompressedSize=y,this.crc32=v,this.compression=p,this.compressedContent=x}h.prototype={getContentWorker:function(){var w=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),y=this;return w.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),w},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},h.createWorkerFrom=function(w,y,v){return w.pipe(new a).pipe(new l("uncompressedSize")).pipe(y.compressWorker(v)).pipe(new l("compressedSize")).withStreamInfo("compression",y)},n.exports=h},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,n,i){var s=r("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,n,i){var s=r("./utils"),o=function(){for(var a,l=[],h=0;h<256;h++){a=h;for(var w=0;w<8;w++)a=1&a?3988292384^a>>>1:a>>>1;l[h]=a}return l}();n.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(h,w,y,v){var p=o,x=v+y;h^=-1;for(var u=v;u<x;u++)h=h>>>8^p[255&(h^w[u])];return-1^h}(0|l,a,a.length,0):function(h,w,y,v){var p=o,x=v+y;h^=-1;for(var u=v;u<x;u++)h=h>>>8^p[255&(h^w.charCodeAt(u))];return-1^h}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(r,n,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(r,n,i){var s=null;s=typeof Promise<"u"?Promise:r("lie"),n.exports={Promise:s}},{lie:37}],7:[function(r,n,i){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=r("pako"),a=r("./utils"),l=r("./stream/GenericWorker"),h=s?"uint8array":"array";function w(y,v){l.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=v,this.meta={}}i.magic="\b\0",a.inherits(w,l),w.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(h,y.data),!1)},w.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},w.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},w.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(v){y.push({data:v,meta:y.meta})}},i.compressWorker=function(y){return new w("Deflate",y)},i.uncompressWorker=function(){return new w("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,n,i){function s(p,x){var u,_="";for(u=0;u<x;u++)_+=String.fromCharCode(255&p),p>>>=8;return _}function o(p,x,u,_,c,d){var g,S,b=p.file,R=p.compression,z=d!==h.Line truncated
\0`,B+=s(M,2),B+=R.magic,B+=s(g,2),B+=s(S,2),B+=s(J.crc32,4),B+=s(J.compressedSize,4),B+=s(J.uncompressedSize,4),B+=s(O.length,2),B+=s(K.length,2),{fileRecord:y.LOCAL_FILE_HEADER+B+O+K,dirRecord:y.CENTRAL_FILE_HEADER+s(le,2)+B+s(re.length,2)+"\0\0\0\0"+s(A,4)+s(_,4)+O+K+re}}var a=r("../utils"),l=r("../stream/GenericWorker"),h=r("../utf8"),w=r("../crc32"),y=r("../signature");function v(p,x,u,_){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=u,this.encodeFileName=_,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(v,l),v.prototype.push=function(p){var x=p.meta.percent||0,u=this.entriesCount,_=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,l.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:u?(x+100*(u-_-1))/u:100}}))},v.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var x=this.streamFiles&&!p.file.dir;if(x){var u=o(p,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:u.fileRecord,meta:{percent:0}})}else this.accumulate=!0},v.prototype.closedSource=function(p){this.accumulate=!1;var x=this.streamFiles&&!p.file.dir,u=o(p,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(u.dirRecord),x)this.push({data:function(_){return y.DATA_DESCRIPTOR+s(_.crc32,4)+s(_.compressedSize,4)+s(_.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:u.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},v.prototype.flush=function(){for(var p=this.bytesWritten,x=0;x<this.dirRecords.length;x++)this.push({data:this.dirRecords[x],meta:{percent:100}});var u=this.bytesWritten-p,_=function(c,d,g,S,b){var R=a.transformTo("string",b(S));return y.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(c,2)+s(c,2)+s(d,4)+s(g,4)+s(R.length,2)+R}(this.dirRecords.length,u,p,this.zipComment,this.encodeFileName);this.push({data:_,meta:{percent:100}})},v.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},v.prototype.registerPrevious=function(p){this._sources.push(p);var x=this;return p.on("data",function(u){x.processChunk(u)}),p.on("end",function(){x.closedSource(x.previous.streamInfo),x._sources.length?x.prepareNextSource():x.end()}),p.on("error",function(u){x.error(u)}),this},v.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},v.prototype.error=function(p){var x=this._sources;if(!l.prototype.error.call(this,p))return!1;for(var u=0;u<x.length;u++)try{x[u].error(p)}catch{}return!0},v.prototype.lock=function(){l.prototype.lock.call(this);for(var p=this._sources,x=0;x<p.length;x++)p[x].lock()},n.exports=v},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(r,n,i){var s=r("../compressions"),o=r("./ZipFileWorker");i.generateWorker=function(a,l,h){var w=new o(l.streamFiles,h,l.platform,l.encodeFileName),y=0;try{a.forEach(function(v,p){y++;var x=function(d,g){var S=d||g,b=s[S];if(!b)throw new Error(S+" is not a valid compression method !");return b}(p.options.compression,l.compression),u=p.options.compressionOptions||l.compressionOptions||{},_=p.dir,c=p.date;p._compressWorker(x,u).withStreamInfo("file",{name:v,dir:_,date:c,comment:p.comment||"",unixPermissions:p.unixPermissions,dosPermissions:p.dosPermissions}).pipe(w)}),w.entriesCount=y}catch(v){w.error(v)}return w}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(r,n,i){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var o=new s;for(var a in this)typeof this[a]!="function"&&(o[a]=this[a]);return o}}(s.prototype=r("./object")).loadAsync=r("./load"),s.support=r("./support"),s.defaults=r("./defaults"),s.version="3.10.1",s.loadAsync=function(o,a){return new s().loadAsync(o,a)},s.external=r("./external"),n.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(r,n,i){var s=r("./utils"),o=r("./external"),a=r("./utf8"),l=r("./zipEntries"),h=r("./stream/Crc32Probe"),w=r("./nodejsUtils");function y(v){return new o.Promise(function(p,x){var u=v.decompressed.getContentWorker().pipe(new h);u.on("error",function(_){x(_)}).on("end",function(){u.streamInfo.crc32!==v.decompressed.crc32?x(new Error("Corrupted zip : CRC32 mismatch")):p()}).resume()})}n.exports=function(v,p){var x=thi Line truncated
(当前浏览器环境限制,无法直接复制图片)`)):alert(`复制失败,请手动复制图片链接:
`+N)}catch(N){console.error("复制图片失败:",N),alert("复制图片失败,请重试")}},Y=async N=>new Promise(async V=>{try{const j=document.createElement("div");j.setAttribute("contenteditable","true"),j.style.position="fixed",j.style.left="-9999px",j.style.top="-9999px",j.style.opacity="0",document.body.appendChild(j);for(const{url:ne,filename:ce}of N)try{const f=await(await fetch(ne)).blob(),F=new Image;F.crossOrigin="anonymous",await new Promise((Z,ee)=>{F.onload=Z,F.onerror=ee,F.src=URL.createObjectURL(f)});const D=document.createElement("canvas");D.width=F.width,D.height=F.height,D.getContext("2d").drawImage(F,0,0),URL.revokeObjectURL(F.src);const C=D.toDataURL("image/png"),L=document.createElement("img");L.src=C,L.alt=ce,L.style.display="block",L.style.marginBottom="10px",j.appendChild(L)}catch(de){console.error(`加载图片失败: ${ce}`,de)}await new Promise(ne=>setTimeout(ne,100));const W=document.createRange();W.selectNodeContents(j);const q=window.getSelection();q.removeAllRanges(),q.addRange(W);let X=!1;try{X=document.execCommand("copy")}catch(ne){console.error("execCommand copy 失败:",ne)}q.removeAllRanges(),document.body.removeChild(j),V(X)}catch(j){console.error("批量复制图片失败:",j),V(!1)}}),$=()=>r.length>0?t&&!r.some(N=>N.id===t.id)?[t,...r]:r:t?[t]:[],J=async()=>{try{const N=$();if(N.length===1){await Q();return}const V=N.map(X=>({url:Le.getOriginalUrl(e,X.path),filename:X.filename})),j=N.map(X=>X.filename).join(`
`);if(H())try{const ne=(await Promise.all(N.map(async ce=>{const de=Le.getOriginalUrl(e,ce.path),F=await(await fetch(de)).blob();return new Promise(D=>{const E=new FileReader;E.onloadend=()=>{D({dataUrl:E.result,filename:ce.filename})},E.readAsDataURL(F)})}))).map(({dataUrl:ce,filename:de})=>`<img src="${ce}" alt="${de}" style="display:block; margin:10px 0;">`).join(`
`);await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([ne],{type:"text/html"}),"text/plain":new Blob([j],{type:"text/plain"})})]),u(!0),setTimeout(()=>u(!1),2e3);return}catch(X){console.warn("Clipboard API 失败,尝试备用方案:",X)}if(console.log("尝试 contenteditable 批量复制方案..."),await Y(V)){u(!0),setTimeout(()=>u(!1),2e3);return}console.warn("批量图片复制失败,降级为复制文件名"),oe(j)?(u(!0),setTimeout(()=>u(!1),2e3),alert(`已复制 ${N.length} 个文件名到剪贴板
(当前环境限制,建议使用"导出"功能)`)):alert('复制失败,请使用"导出"功能下载图片')}catch(N){console.error("复制图片失败:",N),alert("复制图片失败,请重试")}},M=async()=>{c(!0);try{const N=$();if(N.length===1){const V=Le.getOriginalUrl(e,N[0].path),j=document.createElement("a");j.href=V,j.download=N[0].filename,j.target="_blank",document.body.appendChild(j),j.click(),document.body.removeChild(j)}else{const V=new vd,j=V.folder("images");g(0);for(let X=0;X<N.length;X++){const ne=N[X],ce=Le.getOriginalUrl(e,ne.path);try{const f=await(await fetch(ce)).blob();j.file(ne.filename,f);const F=Math.round((X+1)/N.length*90);g(F),console.log(`已添加: ${ne.filename} (${X+1}/${N.length})`)}catch(de){console.error(`下载失败: ${ne.filename}`,de)}}g(95),console.log("正在生成 ZIP 文件...");const W=await V.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});g(100);const q=document.createElement("a");q.href=URL.createObjectURL(W),q.download=`FlyPic_导出_${N.length}张_${Date.now()}.zip`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(q.href),console.log("导出完成!")}}catch(N){console.error("导出失败:",N),alert("导出失败,请重试")}finally{c(!1)}},A=async()=>{if(!n){alert("请先选择一个文件夹");return}b(!0),z(0);try{const N=i.filter(ne=>ne.folder&&ne.folder.startsWith(n));if(N.length===0){alert("当前文件夹没有图片");return}const V=new vd,j=n.split("/").pop()||"images",W=V.folder(j);for(let ne=0;ne<N.length;ne++){const ce=N[ne],de=Le.getOriginalUrl(e,ce.path);try{const F=await(await fetch(de)).blob(),D=ce.folder.replace(n,"").replace(/^\//,""),E=D?`${D}/${ce.filename}`:ce.filename;W.file(E,F);const C=Math.round((ne+1)/N.length*90);z(C),console.log(`已添加: ${E} (${ne+1}/${N.length})`)}catch(f){console.error(`下载失败: ${ce.filename}`,f)}}z(95),console.log("正在生成 ZIP 文件...");const q=await V.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});z(100);const X=document.createElement("a");X.href=URL.createObjectURL(q),X.download=`${j}_${N.length}张_${Date.now()}.zip`,document.body.appendChild(X),X.click(),document.body.removeChild(X),URL.revokeObjectURL(X.href),console.log("文件夹导出完成!")}catch(N){console.error("导出文件夹失败:",N),alert("导出文件夹失败,请重试")}finally{b(!1)}},le=N=>N<1024?N+" B":N<1024*1024?(N/1024).toFixed(2)+" KB":(N/(1024*1024)).toFixed(2)+" MB",B=N=>new Date(N).toLocaleString("zh-CN");return k.jsxs("div",{className:"w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full",children:[l&&k.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex items-center",children:k.jsxs("button",{onClick:()=>s("main"),className:"flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500",children:[k.jsx(Cy,{className:"w-5 h-5"}),k.jsx("span",{className:"text-sm font-medium",children:"返回"})]})}),k.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:k.jsxs("div",{className:"w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative",children:[k.jsx("img",{src:w,alt:P.filename,decoding:"async",className:`w-full h-full object-contain transition-opacity duration-300 ${v?"opacity-75":"opacity-100"}`}),v&&k.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded",children:"加载原图中..."})]})}),k.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 min-h-0",children:k.jsxs("div",{children:[k.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"基本信息"}),k.jsxs("div",{className:"space-y-2 text-sm",children:[k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"文件名:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100 break-all",children:t.filename})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"尺寸:"}),k.jsxs("p",{className:"text-gray-900 dark:text-gray-100",children:[t.width," × ",t.height]})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"大小:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:le(t.size)})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"格式:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100 uppercase",children:t.format})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"创建时间:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:B(t.created_at)})]}),k.jsxs("div",{children:[k.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"修改时间:"}),k.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:B(t.modified_at) Line truncated
@@ -1 +0,0 @@
.PhotoView-Portal{direction:ltr;height:100%;left:0;overflow:hidden;position:fixed;top:0;touch-action:none;width:100%;z-index:2000}@keyframes PhotoView__rotate{0%{transform:rotate(0)}to{transform:rotate(1turn)}}@keyframes PhotoView__delayIn{0%,50%{opacity:0}to{opacity:1}}.PhotoView__Spinner{animation:PhotoView__delayIn .4s linear both}.PhotoView__Spinner svg{animation:PhotoView__rotate .6s linear infinite}.PhotoView__Photo{cursor:grab;max-width:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.PhotoView__Photo:active{cursor:grabbing}.PhotoView__icon{display:inline-block;left:0;position:absolute;top:0;transform:translate(-50%,-50%)}.PhotoView__PhotoBox,.PhotoView__PhotoWrap{bottom:0;direction:ltr;left:0;position:absolute;right:0;top:0;touch-action:none;width:100%}.PhotoView__PhotoWrap{overflow:hidden;z-index:10}.PhotoView__PhotoBox{transform-origin:left top}@keyframes PhotoView__fade{0%{opacity:0}to{opacity:1}}.PhotoView-Slider__clean .PhotoView-Slider__ArrowLeft,.PhotoView-Slider__clean .PhotoView-Slider__ArrowRight,.PhotoView-Slider__clean .PhotoView-Slider__BannerWrap,.PhotoView-Slider__clean .PhotoView-Slider__Overlay,.PhotoView-Slider__willClose .PhotoView-Slider__BannerWrap:hover{opacity:0}.PhotoView-Slider__Backdrop{background:#000;height:100%;left:0;position:absolute;top:0;transition-property:background-color;width:100%;z-index:-1}.PhotoView-Slider__fadeIn{animation:PhotoView__fade linear both;opacity:0}.PhotoView-Slider__fadeOut{animation:PhotoView__fade linear reverse both;opacity:0}.PhotoView-Slider__BannerWrap{align-items:center;background-color:#00000080;color:#fff;display:flex;height:44px;justify-content:space-between;left:0;position:absolute;top:0;transition:opacity .2s ease-out;width:100%;z-index:20}.PhotoView-Slider__BannerWrap:hover{opacity:1}.PhotoView-Slider__Counter{font-size:14px;opacity:.75;padding:0 10px}.PhotoView-Slider__BannerRight{align-items:center;display:flex;height:100%}.PhotoView-Slider__toolbarIcon{fill:#fff;box-sizing:border-box;cursor:pointer;opacity:.75;padding:10px;transition:opacity .2s linear}.PhotoView-Slider__toolbarIcon:hover{opacity:1}.PhotoView-Slider__ArrowLeft,.PhotoView-Slider__ArrowRight{align-items:center;bottom:0;cursor:pointer;display:flex;height:100px;justify-content:center;margin:auto;opacity:.75;position:absolute;top:0;transition:opacity .2s linear;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:70px;z-index:20}.PhotoView-Slider__ArrowLeft:hover,.PhotoView-Slider__ArrowRight:hover{opacity:1}.PhotoView-Slider__ArrowLeft svg,.PhotoView-Slider__ArrowRight svg{fill:#fff;background:#0000004d;box-sizing:content-box;height:24px;padding:10px;width:24px}.PhotoView-Slider__ArrowLeft{left:0}.PhotoView-Slider__ArrowRight{right:0}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-painLine truncated
@@ -1 +0,0 @@
(function(){"use strict";let c={containerWidth:0,targetHeight:0,imageCount:0,rows:[],pendingRow:[],pendingRowWidthSum:0};function W(n,o,l,i,s){const a=(n.length-1)*16;let e=(o-a)/l;i&&n.length<3&&(e=Math.min(e,1.2));const t=s*e;return n.map(u=>({...u,calculatedWidth:u.originalWidth*e,calculatedHeight:t}))}function A(n,o,l){if(!n.length||!o)return{rows:[],pendingRow:[],pendingRowWidthSum:0};const i=[];let s=[],a=0;for(let h=0;h<n.length;h++){const e=n[h],t=e.width/e.height,u=l*t;s.push({...e,originalWidth:u,aspectRatio:t}),a+=u;const r=(s.length-1)*16,g=a+r,p=h===n.length-1;let d=!1;if(p)d=!0;else if(g>=o*.95)d=!0;else{const w=n[h+1];if(w){const R=w.width/w.height,G=l*R;a+G+s.length*16>o*1.2&&(d=!0)}}if(d){const w=W(s,o,a,p,l);i.push(w),s=[],a=0}}return{rows:i,pendingRow:s,pendingRowWidthSum:a}}function x(n,o,l,i,s,a){if(!n.length){if(s.length>0){const r=W(s,o,a,!0,l);return{rows:[...i,r],pendingRow:[],pendingRowWidthSum:0}}return{rows:i,pendingRow:[],pendingRowWidthSum:0}}const h=[...i];let e=[...s],t=a;const u=i.reduce((r,g)=>r+g.length,0)+s.length+n.length;for(let r=0;r<n.length;r++){const g=n[r],p=g.width/g.height,d=l*p;e.push({...g,originalWidth:d,aspectRatio:p}),t+=d;const w=(e.length-1)*16,R=t+w,S=i.reduce((f,C)=>f+C.length,0)+h.length-i.length+e.length>=u;let m=!1;if(S)m=!0;else if(R>=o*.95)m=!0;else{const f=n[r+1];if(f){const C=f.width/f.height,I=l*C;t+I+e.length*16>o*1.2&&(m=!0)}}if(m){const f=W(e,o,t,S,l);h.push(f),e=[],t=0}}return{rows:h,pendingRow:e,pendingRowWidthSum:t}}function P(){c={containerWidth:0,targetHeight:0,imageCount:0,rows:[],pendingRow:[],pendingRowWidthSum:0}}self.onmessage=function(n){const{images:o,containerWidth:l,targetHeight:i,requestId:s,incremental:a,reset:h}=n.data;if(h){P(),self.postMessage({requestId:s,reset:!0});return}const e=performance.now();let t;const u=a&&c.containerWidth===l&&c.targetHeight===i&&o.length>c.imageCount;if(u){const g=o.slice(c.imageCount),p=c.rows.slice(0,-1),d=c.rows[c.rows.length-1]||[];t=x(g,l,i,p,c.pendingRow.length>0?c.pendingRow:d,c.pendingRowWidthSum>0?c.pendingRowWidthSum:d.reduce((w,R)=>w+R.originalWidth,0))}else t=A(o,l,i);c={containerWidth:l,targetHeight:i,imageCount:o.length,rows:t.rows,pendingRow:t.pendingRow,pendingRowWidthSum:t.pendingRowWidthSum};const r=performance.now()-e;self.postMessage({rows:t.rows,requestId:s,duration:r,imageCount:o.length,rowCount:t.rows.length,incremental:u})}})();
+2 -2
View File
@@ -5,8 +5,8 @@
<link rel="icon" type="image/png" href="/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>FlyPic 飞图 - 图片素材库管理</title>
<script type="module" crossorigin src="/assets/index-CGwCzICz.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-lXh_CTLb.css">
<script type="module" crossorigin src="/assets/index-DWWYNoqs.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CcwAM3eE.css">
</head>
<body>
<div id="root"></div>␍
-297
View File
@@ -1,297 +0,0 @@
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');
const dbPool = require('../database/dbPool');
const { generateThumbnail } = require('../utils/thumbnail');
const { getLibrary } = require('../utils/config');
// Get images with search and filters (supports pagination)
router.get('/', (req, res) => {
try {
const { libraryId, keywords, folder, formats, minSize, maxSize, startDate, endDate, offset, limit } = req.query;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
// 使用连接池获取数据库连接
const db = dbPool.acquire(library.path);
try {
const filters = {};
if (folder) filters.folder = folder;
if (formats) filters.formats = formats.split(',');
if (minSize) filters.minSize = parseInt(minSize);
if (maxSize) filters.maxSize = parseInt(maxSize);
if (startDate) filters.startDate = parseInt(startDate);
if (endDate) filters.endDate = parseInt(endDate);
// 分页参数(可选)
let pagination = null;
if (offset !== undefined && limit !== undefined) {
pagination = {
offset: parseInt(offset, 10),
limit: parseInt(limit, 10)
};
}
const result = db.searchImages(keywords || '', filters, pagination);
// 如果使用分页,返回分页格式;否则保持向后兼容
if (pagination) {
res.json({
images: result.images,
total: result.total,
offset: result.offset,
limit: result.limit,
hasMore: result.hasMore
});
} else {
res.json({ images: result });
}
} finally {
// 释放连接
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get cache metadata (database modification time, counts)
router.get('/cache-meta', (req, res) => {
try {
const { libraryId } = req.query;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const db = dbPool.acquire(library.path);
try {
const meta = db.getCacheMeta();
res.json(meta);
} finally {
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get total image count
router.get('/count', (req, res) => {
try {
const { libraryId } = req.query;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const db = dbPool.acquire(library.path);
try {
const row = db.db.prepare('SELECT COUNT(*) as count FROM images').get();
res.json({ count: row.count });
} finally {
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get folders
router.get('/folders', (req, res) => {
try {
const { libraryId } = req.query;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const db = dbPool.acquire(library.path);
try {
const folders = db.getFolderTree();
res.json({ folders });
} finally {
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Serve thumbnail
router.get('/thumbnail/:libraryId/:size/:filename', async (req, res) => {
try {
const { libraryId, size, filename } = req.params;
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
// New structure: .flypic/thumbnails/ab/hash.webp
const thumbBase = path.join(library.path, '.flypic', 'thumbnails');
const hash = filename.replace(/\.[^/.]+$/, ""); // remove extension if present
const shard1 = hash.slice(0, 2);
const targetPath = path.join(thumbBase, shard1, filename);
if (!fs.existsSync(targetPath)) {
// 按需生成:尝试通过文件名在数据库中定位原图并生成
try {
const db = dbPool.acquire(library.path);
try {
const row = db.db.prepare('SELECT path, thumbnail_path FROM images WHERE thumbnail_path LIKE ?').get(`%/${filename}`);
if (row && row.path) {
const originalFull = path.join(library.path, row.path);
// 确保目标目录存在
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
// 生成指定尺寸 (default 480)
await generateThumbnail(originalFull, targetPath, parseInt(size, 10) || 480);
}
} finally {
dbPool.release(library.path);
}
} catch (e) {
// 忽略生成失败
}
}
if (!fs.existsSync(targetPath)) {
return res.status(404).json({ error: 'Thumbnail not found' });
}
// 设置缓存头,减少重复请求(缩略图内容不变)
res.set({
'Cache-Control': 'public, max-age=31536000, immutable',
'Vary': 'Accept-Encoding'
});
res.sendFile(targetPath);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Serve original image
router.get('/original/:libraryId/*', (req, res) => {
try {
const { libraryId } = req.params;
const imagePath = req.params[0];
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const fullPath = path.join(library.path, imagePath);
if (!fs.existsSync(fullPath)) {
return res.status(404).json({ error: 'Image not found' });
}
res.sendFile(fullPath);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Open file in system default application
router.post('/:libraryId/open-file', (req, res) => {
try {
const { libraryId } = req.params;
const { path: filePath } = req.body;
if (!filePath) {
return res.status(400).json({ error: 'Path is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const fullPath = path.join(library.path, filePath);
if (!fs.existsSync(fullPath)) {
return res.status(404).json({ error: 'File not found' });
}
// 使用系统默认应用打开文件
const command = process.platform === 'win32'
? `start "" "${fullPath}"`
: process.platform === 'darwin'
? `open "${fullPath}"`
: `xdg-open "${fullPath}"`;
exec(command, (error) => {
if (error) {
console.error('打开文件失败:', error);
return res.status(500).json({ error: '打开文件失败' });
}
res.json({ success: true });
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Open folder in file explorer
router.post('/:libraryId/open-folder', (req, res) => {
try {
const { path: imagePath } = req.body;
if (!imagePath) {
return res.status(400).json({ error: 'Path is required' });
}
// 获取文件所在文件夹
const folderPath = path.dirname(imagePath);
// Windows: 使用 explorer
// Linux: 使用 xdg-open
// macOS: 使用 open
const command = process.platform === 'win32'
? `explorer "${folderPath}"`
: process.platform === 'darwin'
? `open "${folderPath}"`
: `xdg-open "${folderPath}"`;
exec(command, (error) => {
if (error) {
console.error('打开文件夹失败:', error);
return res.status(500).json({ error: '打开文件夹失败' });
}
res.json({ success: true });
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
-238
View File
@@ -1,238 +0,0 @@
const express = require('express');
const router = express.Router();
const fs = require('fs');
const {
loadConfig,
addLibrary,
removeLibrary,
updateLibrary,
setCurrentLibrary,
updatePreferences,
updateTheme
} = require('../utils/config');
// Get all libraries and config
router.get('/', (req, res) => {
try {
const config = loadConfig();
res.json({
libraries: config.libraries,
currentLibraryId: config.currentLibraryId,
theme: config.theme,
preferences: config.preferences
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Add new library
router.post('/', (req, res) => {
try {
const { name, path } = req.body;
if (!name || !path) {
return res.status(400).json({ error: 'Name and path are required' });
}
if (!fs.existsSync(path)) {
return res.status(400).json({ error: 'Path does not exist' });
}
const id = addLibrary(name, path);
// Check if .flypic directory exists
const flypicDir = require('path').join(path, '.flypic');
const hasExistingIndex = fs.existsSync(flypicDir);
res.json({
id,
message: 'Library added successfully',
hasExistingIndex
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Update preferences (must be before /:id route)
router.put('/preferences', (req, res) => {
try {
const preferences = updatePreferences(req.body);
res.json({ preferences });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Update theme (must be before /:id route)
router.put('/theme', (req, res) => {
try {
const { theme } = req.body;
updateTheme(theme);
res.json({ theme });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Update library
router.put('/:id', (req, res) => {
try {
const { id } = req.params;
const updates = req.body;
const success = updateLibrary(id, updates);
if (success) {
res.json({ message: 'Library updated successfully' });
} else {
res.status(404).json({ error: 'Library not found' });
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Delete library
router.delete('/:id', async (req, res) => {
try {
const { id } = req.params;
// 获取素材库信息
const config = loadConfig();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const dbPool = require('../database/dbPool');
const fileWatcher = require('../utils/fileWatcher');
const scanManager = require('../utils/scanManager');
// 1. 停止扫描并清理状态
scanManager.clearState(id);
// 2. 停止文件监控
fileWatcher.unwatch(id);
// 3. 关闭数据库连接
dbPool.close(library.path);
// 等待一下,确保连接完全关闭
await new Promise(resolve => setTimeout(resolve, 300));
// 删除索引
removeLibrary(id);
res.json({
message: 'Library removed successfully',
path: library.path
});
} catch (error) {
console.error('Error in delete library:', error);
res.status(500).json({ error: error.message });
}
});
// Set current library
router.post('/:id/set-current', async (req, res) => {
try {
const { id } = req.params;
const config = loadConfig();
const dbPool = require('../database/dbPool');
const scanManager = require('../utils/scanManager');
// 获取旧的当前素材库
const oldLibraryId = config.currentLibraryId;
if (oldLibraryId && oldLibraryId !== id) {
const oldLibrary = config.libraries.find(lib => lib.id === oldLibraryId);
if (oldLibrary) {
// 1. 停止扫描(如果正在进行),但保留暂停状态以便恢复
if (scanManager.isScanning(oldLibraryId)) {
const state = scanManager.getState(oldLibraryId);
if (state.abortController) {
state.abortController.aborted = true;
}
}
// 2. 关闭数据库连接
dbPool.close(oldLibrary.path);
}
}
// 设置新的当前素材库
setCurrentLibrary(id);
const newLibrary = config.libraries.find(lib => lib.id === id);
// 预热新数据库连接(避免第一个查询时才创建连接)
if (newLibrary) {
const db = dbPool.acquire(newLibrary.path);
// 执行一个简单查询来预热缓存
try {
db.db.prepare('SELECT 1').get();
} catch (e) {
// 忽略预热错误
}
dbPool.release(newLibrary.path);
}
res.json({ message: 'Current library set successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Close database connection for a library
router.post('/:id/close-db', (req, res) => {
try {
const { id } = req.params;
const config = loadConfig();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const dbPool = require('../database/dbPool');
dbPool.close(library.path);
res.json({ message: 'Database connection closed successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Release all resources for a library (database + file watcher)
router.post('/:id/release', (req, res) => {
try {
const { id } = req.params;
const config = loadConfig();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
// 1. 关闭数据库连接
const dbPool = require('../database/dbPool');
dbPool.close(library.path);
// 2. 停止文件监控
const fileWatcher = req.app.get('fileWatcher');
if (fileWatcher && fileWatcher.isWatching(id)) {
fileWatcher.unwatch(id);
}
res.json({
message: 'All resources released successfully',
library: library.name
});
} catch (error) {
console.error('[Release] Error:', error);
res.status(500).json({ error: error.message });
}
});
module.exports = router;
-283
View File
@@ -1,283 +0,0 @@
const express = require('express');
const router = express.Router();
const LibraryDatabase = require('../database/db');
const { getLibrary, updateLibrary } = require('../utils/config');
const { scanLibrary, syncLibrary } = require('../utils/scanner');
const scanManager = require('../utils/scanManager');
// Start full scan
router.post('/full', async (req, res) => {
try {
const { libraryId, wait } = req.body;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const io = req.app.get('io');
const dbPool = require('../database/dbPool');
const db = dbPool.acquire(library.path);
// 如果需要等待扫描完成
if (wait) {
try {
const results = await scanLibrary(library.path, db, (progress) => {
io.emit('scanProgress', {
libraryId,
...progress
});
});
dbPool.release(library.path);
updateLibrary(libraryId, { lastScan: Date.now() });
io.emit('scanComplete', { libraryId, results });
res.json({ message: 'Scan completed', results });
} catch (error) {
dbPool.release(library.path);
io.emit('scanError', { libraryId, error: error.message });
throw error;
}
} else {
// Start scan in background
console.log(`🔍 Starting background scan for library: ${libraryId}`);
res.json({ message: 'Scan started' });
scanLibrary(library.path, db, (progress) => {
console.log(`📊 Progress: ${progress.current}/${progress.total} (${progress.percent}%)`);
io.emit('scanProgress', {
libraryId,
...progress
});
}, libraryId).then(results => {
console.log(`✅ Scan complete for library: ${libraryId}`, results);
dbPool.release(library.path);
if (!results.stopped) {
updateLibrary(libraryId, { lastScan: Date.now() });
io.emit('scanComplete', { libraryId, results });
} else {
io.emit('scanPaused', { libraryId, results });
}
}).catch(error => {
console.error(`❌ Scan error for library: ${libraryId}`, error);
dbPool.release(library.path);
io.emit('scanError', { libraryId, error: error.message });
});
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start incremental sync
router.post('/sync', async (req, res) => {
try {
const { libraryId, wait } = req.body;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const io = req.app.get('io');
const dbPool = require('../database/dbPool');
const db = dbPool.acquire(library.path);
// 如果需要等待同步完成
if (wait) {
try {
const results = await syncLibrary(library.path, db);
dbPool.release(library.path);
updateLibrary(libraryId, { lastScan: Date.now() });
io.emit('scanComplete', { libraryId, results });
res.json({ message: 'Sync completed', results });
} catch (error) {
dbPool.release(library.path);
io.emit('scanError', { libraryId, error: error.message });
throw error;
}
} else {
// Start sync in background
console.log(`🔄 Starting background sync for library: ${libraryId}`);
res.json({ message: 'Sync started' });
syncLibrary(library.path, db, false, (progress) => {
console.log(`📊 Sync progress: ${progress.current}/${progress.total} (${progress.percent}%)`);
io.emit('scanProgress', {
libraryId,
...progress
});
}).then(results => {
console.log(`✅ Sync complete for library: ${libraryId}`, results);
dbPool.release(library.path);
updateLibrary(libraryId, { lastScan: Date.now() });
io.emit('scanComplete', { libraryId, results });
}).catch(error => {
console.error(`❌ Sync error for library: ${libraryId}`, error);
dbPool.release(library.path);
io.emit('scanError', { libraryId, error: error.message });
});
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Fix folder paths in database (one-time migration)
router.post('/fix-folders', async (req, res) => {
try {
const { libraryId } = req.body;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const db = dbPool.acquire(library.path);
try {
const path = require('path');
const images = db.getAllImages();
let fixed = 0;
for (const img of images) {
const expectedFolderRaw = path.dirname(img.path || '');
const expectedFolder = expectedFolderRaw === '.' ? '' : expectedFolderRaw.replace(/\\/g, '/');
const currentFolder = (img.folder || '').replace(/\\/g, '/');
if (expectedFolder !== currentFolder) {
db.updateImageFolder(img.path, expectedFolder);
fixed++;
}
}
console.log(`✅ Fixed ${fixed} folder paths`);
res.json({ message: `Fixed ${fixed} folder paths`, fixed });
} finally {
dbPool.release(library.path);
}
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 停止扫描
router.post('/stop', async (req, res) => {
try {
const { libraryId } = req.body;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
if (!scanManager.isScanning(libraryId)) {
return res.status(400).json({ error: 'No scan in progress' });
}
// 设置停止标志(实际停止在下一个批次检查时)
const state = scanManager.getState(libraryId);
state.abortController.aborted = true;
console.log(`⏸️ Stop requested for library: ${libraryId}`);
res.json({ message: 'Stop requested', libraryId });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 继续扫描
router.post('/resume', async (req, res) => {
try {
const { libraryId } = req.body;
if (!libraryId) {
return res.status(400).json({ error: 'Library ID is required' });
}
if (!scanManager.isPaused(libraryId)) {
return res.status(400).json({ error: 'Scan is not paused' });
}
const library = getLibrary(libraryId);
if (!library) {
return res.status(404).json({ error: 'Library not found' });
}
const pendingFiles = scanManager.resumeScan(libraryId);
if (pendingFiles.length === 0) {
return res.status(400).json({ error: 'No pending files to resume' });
}
const io = req.app.get('io');
const dbPool = require('../database/dbPool');
const db = dbPool.acquire(library.path);
console.log(`▶️ Resuming scan for library: ${libraryId}, ${pendingFiles.length} files`);
res.json({ message: 'Scan resumed', pendingFiles: pendingFiles.length });
// 继续扫描
scanLibrary(library.path, db, (progress) => {
io.emit('scanProgress', {
libraryId,
...progress
});
}, libraryId, pendingFiles).then(results => {
dbPool.release(library.path);
if (!results.stopped) {
updateLibrary(libraryId, { lastScan: Date.now() });
io.emit('scanComplete', { libraryId, results });
} else {
io.emit('scanPaused', { libraryId, results });
}
}).catch(error => {
dbPool.release(library.path);
io.emit('scanError', { libraryId, error: error.message });
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// 获取扫描状态
router.get('/status/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
// 注册素材库路径(用于持久化恢复)
const library = getLibrary(libraryId);
if (library) {
scanManager.registerLibraryPath(libraryId, library.path);
}
const state = scanManager.getState(libraryId);
res.json({
libraryId,
status: state.status,
progress: state.progress,
pendingCount: state.pendingFiles?.length || 0,
needsRescan: state.needsRescan || false // 标记是否需要重新扫描
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
-81
View File
@@ -1,81 +0,0 @@
const express = require('express');
const router = express.Router();
// Start watching a library
router.post('/start/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const fileWatcher = req.app.get('fileWatcher');
const io = req.app.get('io');
// 立即返回响应,让文件监控在后台启动
res.json({
message: 'File watching starting',
libraryId,
isWatching: true
});
// 异步启动监控(不阻塞响应)
setImmediate(() => {
try {
fileWatcher.watch(libraryId, io);
} catch (watchError) {
console.error(`Failed to start file watching for ${libraryId}:`, watchError.message);
}
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Stop watching a library
router.post('/stop/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const fileWatcher = req.app.get('fileWatcher');
fileWatcher.unwatch(libraryId);
res.json({
message: 'File watching stopped',
libraryId,
isWatching: false
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get watch status
router.get('/status/:libraryId', (req, res) => {
try {
const { libraryId } = req.params;
const fileWatcher = req.app.get('fileWatcher');
const isWatching = fileWatcher.isWatching(libraryId);
res.json({
libraryId,
isWatching
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get all watched libraries
router.get('/list', (req, res) => {
try {
const fileWatcher = req.app.get('fileWatcher');
const watchedLibraries = fileWatcher.getWatchedLibraries();
res.json({
watchedLibraries,
count: watchedLibraries.length
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
module.exports = router;
+198 -151
View File
@@ -1,191 +1,238 @@
const express = require('express');
const cors = require('cors');
const path = require('path');
/**
* FlyPic 服务器入口(新架构)
* 使用重构后的 Service 层和 Model 层
*/
const http = require('http');
const { Server } = require('socket.io');
const fileWatcher = require('./utils/fileWatcher');
const path = require('path');
const fs = require('fs');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: process.env.FRONTEND_DIST ? false : ['http://localhost:5173', 'http://localhost:3000'],
methods: ['GET', 'POST']
}
});
// 导入新架构的应用
const { createApp } = require('./src/app');
// 导入现有的依赖(保持兼容)
const config = require('./utils/config');
const dbPool = require('./database/dbPool');
const scanner = require('./utils/scanner');
const scanManager = require('./utils/scanManager');
const lightweightWatcher = require('./utils/lightweightWatcher');
const MemoryMonitor = require('./utils/memoryMonitor');
const CleanupManager = require('./utils/cleanupManager');
const PORT = process.env.PORT || 15002;
// Auto-detect frontend dist path
// 自动检测前端构建目录
let FRONTEND_DIST = process.env.FRONTEND_DIST;
if (!FRONTEND_DIST) {
// Try common locations
const possiblePaths = [
path.join(__dirname, 'public'), // 飞牛 fnOS 打包后的位置
path.join(__dirname, '../frontend/dist'), // 开发环境
path.join(__dirname, 'public'),
path.join(__dirname, '../frontend/dist'),
path.join(__dirname, '../public'),
path.join(__dirname, '../../frontend/dist')
];
for (const p of possiblePaths) {
if (require('fs').existsSync(p)) {
if (fs.existsSync(p)) {
FRONTEND_DIST = p;
console.log('✅ Found frontend at:', p);
console.log('✅ 前端目录:', p);
break;
}
}
if (!FRONTEND_DIST) {
console.log('⚠️ Frontend not found, tried:', possiblePaths);
console.log('⚠️ 未找到前端,API模式');
}
}
// Middleware
app.use(cors());
app.use(express.json());
// API Routes
const libraryRouter = require('./routes/library');
const imageRouter = require('./routes/image');
const scanRouter = require('./routes/scan');
const watchRouter = require('./routes/watch');
app.use('/api/library', libraryRouter);
app.use('/api/image', imageRouter);
app.use('/api/scan', scanRouter);
app.use('/api/watch', watchRouter);
// Serve static files (production)
// 设置环境变量
if (FRONTEND_DIST) {
console.log('📁 Serving frontend from:', FRONTEND_DIST);
app.use(express.static(FRONTEND_DIST));
app.get('*', (req, res) => {
if (!req.path.startsWith('/api')) {
res.sendFile(path.join(FRONTEND_DIST, 'index.html'));
}
});
process.env.FRONTEND_DIST = FRONTEND_DIST;
}
// Socket.IO for real-time updates
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
});
});
// Make io accessible to routes
app.set('io', io);
// Make fileWatcher accessible to routes
app.set('fileWatcher', fileWatcher);
server.listen(PORT, () => {
console.log(`🚀 FlyPic server running on http://localhost:${PORT}`);
// 只为当前选中的素材库启动文件监控和快速同步
const { loadConfig } = require('./utils/config');
const config = loadConfig();
const currentLibraryId = config.currentLibraryId;
const currentLibrary = config.libraries.find(lib => lib.id === currentLibraryId);
if (currentLibrary) {
console.log(`📡 启动当前素材库监控: ${currentLibrary.name}`);
// 启动文件监控
try {
fileWatcher.watch(currentLibrary.id, io);
console.log(` ✅ 文件监控已启动`);
} catch (err) {
console.log(` ❌ 文件监控失败: ${err.message}`);
}
// 快速同步检测离线变化
console.log('🔄 检测离线期间的文件变化...');
const { quickSync } = require('./utils/scanner');
const dbPool = require('./database/dbPool');
(async () => {
try {
const db = dbPool.acquire(currentLibrary.path);
const results = await quickSync(currentLibrary.path, db);
dbPool.release(currentLibrary.path);
const changes = results.added + results.deleted;
if (changes > 0) {
console.log(` 📊 ${currentLibrary.name}: +${results.added} -${results.deleted}`);
io.emit('scanComplete', { libraryId: currentLibrary.id, results });
} else {
console.log(` ✅ ${currentLibrary.name}: 无变化`);
}
} catch (err) {
console.log(` ❌ ${currentLibrary.name}: ${err.message}`);
}
console.log('✅ 启动检查完成');
})();
} else {
console.log('📭 未选中素材库,等待用户操作...');
// 创建 Socket.IO 服务器
const server = http.createServer();
const io = new Server(server, {
cors: {
origin: FRONTEND_DIST ? false : ['http://localhost:5173', 'http://localhost:3000'],
methods: ['GET', 'POST']
}
});
// Graceful shutdown - 优雅关闭,释放所有资源
const gracefulShutdown = (signal) => {
console.log(`\n🛑 Received ${signal}, shutting down gracefully...`);
try {
// 1. 停止所有文件监控
console.log('📡 Stopping file watchers...');
fileWatcher.unwatchAll();
// 2. 关闭所有数据库连接
console.log('💾 Closing database connections...');
const dbPool = require('./database/dbPool');
dbPool.closeAll();
// 3. 关闭 HTTP 服务器
console.log('🌐 Closing HTTP server...');
server.close(() => {
console.log('✅ All resources released, goodbye!');
process.exit(0);
});
// 如果10秒内没有正常关闭,强制退出
setTimeout(() => {
console.error('⚠️ Forced shutdown after timeout');
process.exit(1);
}, 10000);
} catch (error) {
console.error('❌ Error during shutdown:', error);
process.exit(1);
}
// 准备依赖注入
// 包装 config 函数为对象接口
const configManager = {
load: () => config.loadConfig(),
save: (data) => config.saveConfig(data),
addLibrary: (name, path) => config.addLibrary(name, path),
removeLibrary: (id) => config.removeLibrary(id),
updateLibrary: (id, updates) => config.updateLibrary(id, updates),
setCurrentLibrary: (id) => config.setCurrentLibrary(id),
updatePreferences: (prefs) => config.updatePreferences(prefs),
updateTheme: (theme) => config.updateTheme(theme)
};
// 监听各种退出信号
process.on('SIGINT', () => gracefulShutdown('SIGINT')); // Ctrl+C
process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); // kill
process.on('SIGHUP', () => gracefulShutdown('SIGHUP')); // 终端关闭
const dependencies = {
configManager,
dbPool,
scanner,
scanManager,
lightweightWatcher,
io
};
// Windows 特殊处理(Ctrl+C)
if (process.platform === 'win32') {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
// 创建 Express 应用(使用新架构)
const app = createApp(dependencies);
// 将 Express 应用挂载到 HTTP 服务器
server.on('request', app);
// Socket.IO 连接处理
io.on('connection', (socket) => {
console.log('✅ 客户端连接:', socket.id);
socket.on('disconnect', () => {
console.log('❌ 客户端断开:', socket.id);
});
});
// 启动内存监控(开发模式:每30秒输出RSS)
const memoryMonitor = new MemoryMonitor({
devMode: true,
devLogInterval: 30000 // 30秒
});
memoryMonitor.start();
// 启动清理管理器
const cleanupManager = new CleanupManager({ dbPool });
cleanupManager.startRoutineCleanup();
// 启动服务器
server.listen(PORT, () => {
console.log('\n🚀 FlyPic 服务器已启动');
console.log(`📡 端口: ${PORT}`);
console.log(`🔌 Socket.IO 就绪`);
if (FRONTEND_DIST) console.log(`📁 前端: ${FRONTEND_DIST}`);
console.log('');
try {
const currentConfig = config.loadConfig();
// 恢复所有素材库的扫描状态
if (currentConfig.libraries && currentConfig.libraries.length > 0) {
scanManager.restoreAllStates(currentConfig.libraries);
// 检查是否有未完成的扫描,自动继续
const activeStates = scanManager.getAllActiveStates();
if (Object.keys(activeStates).length > 0) {
console.log(`📊 发现 ${Object.keys(activeStates).length} 个活跃扫描`);
}
for (const [libraryId, state] of Object.entries(activeStates)) {
const lib = currentConfig.libraries.find(l => l.id === libraryId);
if (lib && state.status === 'scanning') {
console.log(`🔄 恢复扫描: ${lib.name} (${state.progress?.percent || 0}%)`);
// 立即恢复扫描状态(让前端能检测到)
scanManager.scanStates.set(libraryId, {
status: 'scanning',
progress: state.progress || { current: 0, total: 0, percent: 0 },
startTime: state.startTime || Date.now()
});
// 立即向所有连接的客户端推送扫描状态
io.emit('scanProgress', {
libraryId,
...state.progress,
resuming: true
});
// 延迟启动实际扫描,等服务完全准备好
setTimeout(() => {
const db = dbPool.acquire(lib.path);
// 继续扫描(从中断处继续)
scanner.scanLibrary(
lib.path,
db,
(progress) => {
io.emit('scanProgress', { libraryId, ...progress });
},
libraryId
).then(() => {
scanManager.completeScan(libraryId);
io.emit('scanComplete', { libraryId });
dbPool.release(lib.path);
console.log(`✅ 扫描完成: ${lib.name}`);
}).catch((err) => {
console.error(`❌ 扫描失败: ${lib.name}`, err.message);
scanManager.completeScan(libraryId);
dbPool.release(lib.path);
});
}, 2000);
}
}
}
// 为当前素材库启动文件监控
if (currentConfig.currentLibraryId) {
const currentLib = currentConfig.libraries.find(lib => lib.id === currentConfig.currentLibraryId);
if (currentLib) {
lightweightWatcher.watch(currentLib.id, currentLib.path, currentLib.name, io);
}
}
} catch (e) {
console.warn('⚠️ 初始化失败:', e.message);
}
});
// 标记是否正在关闭
let isShuttingDown = false;
// 优雅关闭
const shutdown = async () => {
if (isShuttingDown) return;
isShuttingDown = true;
console.log('\n🛑 正在关闭服务器...');
// 停止接受新连接
server.close(() => {
console.log('✅ HTTP 服务器已关闭');
});
rl.on('SIGINT', () => {
process.emit('SIGINT');
});
}
// 停止监控
memoryMonitor.stop();
cleanupManager.stopRoutineCleanup();
// 捕获未处理的异常
// 停止所有文件监控
lightweightWatcher.stopAll();
// 等待扫描任务完成当前批次(最多等2秒)
await new Promise(resolve => setTimeout(resolve, 2000));
// 关闭所有数据库连接
dbPool.closeAll();
console.log('✅ 关闭完成');
process.exit(0);
};
// 导出关闭状态供其他模块检查
module.exports.isShuttingDown = () => isShuttingDown;
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
// 错误处理
process.on('uncaughtException', (error) => {
console.error('❌ Uncaught Exception:', error);
gracefulShutdown('uncaughtException');
console.error('💥 未捕获异常:', error.message);
shutdown();
});
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
gracefulShutdown('unhandledRejection');
console.error('💥 未处理的Promise拒绝:', reason);
shutdown();
});
// 导出供测试使用
module.exports = { app, server, io };
+95
View File
@@ -0,0 +1,95 @@
/**
* Express 应用配置
* 使用新的架构:Config → Model → Service → Route
*/
const express = require('express');
const cors = require('cors');
const path = require('path');
const { errorHandler } = require('./middleware/errorHandler');
// 导入服务
const LibraryService = require('./services/LibraryService');
const ImageService = require('./services/ImageService');
const ScanService = require('./services/ScanService');
/**
* 创建 Express 应用
*/
function createApp(dependencies) {
const {
configManager,
dbPool,
scanner,
scanManager,
lightweightWatcher,
io
} = dependencies;
const app = express();
// 中间件
app.use(cors());
app.use(express.json());
// 初始化服务
const libraryService = new LibraryService(
configManager,
dbPool,
scanManager,
lightweightWatcher,
io
);
const imageService = new ImageService(
configManager,
dbPool
);
const scanService = new ScanService(
configManager,
dbPool,
scanner,
scanManager,
io
);
// 将服务注入到 app 中,供路由使用
app.set('libraryService', libraryService);
app.set('imageService', imageService);
app.set('scanService', scanService);
// API 路由
const libraryRouter = require('./routes/library');
const imageRouter = require('./routes/image');
const scanRouter = require('./routes/scan');
app.use('/api/library', libraryRouter);
app.use('/api/image', imageRouter);
app.use('/api/scan', scanRouter);
// 健康检查
app.get('/api/health', (req, res) => {
res.json({
success: true,
status: 'ok',
timestamp: Date.now()
});
});
// 静态文件服务(前端)
const FRONTEND_DIST = process.env.FRONTEND_DIST;
if (FRONTEND_DIST) {
app.use(express.static(FRONTEND_DIST));
app.get('*', (req, res) => {
res.sendFile(path.join(FRONTEND_DIST, 'index.html'));
});
}
// 错误处理中间件(必须放在最后)
app.use(errorHandler);
return app;
}
module.exports = { createApp };
+62
View File
@@ -0,0 +1,62 @@
/**
* 应用常量配置
*/
module.exports = {
// 支持的图片格式
SUPPORTED_FORMATS: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff'],
// 缩略图配置
THUMBNAIL: {
SIZES: {
SMALL: 200,
MEDIUM: 480,
LARGE: 800
},
QUALITY: 80,
FORMAT: 'webp',
SHARD_LENGTH: 2 // 分片目录长度
},
// 分页配置
PAGINATION: {
DEFAULT_SIZE: 100,
MAX_SIZE: 500
},
// 扫描配置
SCAN: {
BATCH_SIZE: 50,
CONCURRENT_LIMIT: 10,
PROGRESS_UPDATE_INTERVAL: 100
},
// 内存配置
MEMORY: {
WARNING_THRESHOLD_MB: 200,
DANGER_THRESHOLD_MB: 300,
CACHE_SIZE_KB: 4096,
CLEANUP_INTERVAL_MS: 60000,
DB_IDLE_TIMEOUT_MS: 300000
},
// 数据库配置
DATABASE: {
PRAGMA: {
journal_mode: 'DELETE',
synchronous: 'NORMAL',
cache_size: -4096,
temp_store: 'FILE',
page_size: 4096,
mmap_size: 0
}
},
// 路径配置
PATHS: {
FLYPIC_DIR: '.flypic',
THUMBNAILS_DIR: 'thumbnails',
DATABASE_FILE: 'metadata.db',
CONFIG_FILE: 'config.json'
}
};
+42
View File
@@ -0,0 +1,42 @@
/**
* 配置管理入口
*/
const constants = require('./constants');
const path = require('path');
/**
* 获取 FlyPic 目录路径
*/
function getFlypicPath(libraryPath) {
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR);
}
/**
* 获取缩略图目录路径
*/
function getThumbnailsPath(libraryPath) {
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.THUMBNAILS_DIR);
}
/**
* 获取数据库文件路径
*/
function getDatabasePath(libraryPath) {
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.DATABASE_FILE);
}
/**
* 获取配置文件路径
*/
function getConfigPath(libraryPath) {
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.CONFIG_FILE);
}
module.exports = {
constants,
getFlypicPath,
getThumbnailsPath,
getDatabasePath,
getConfigPath
};
@@ -0,0 +1,97 @@
/**
* 统一错误处理中间件
*/
/**
* 应用错误类
*/
class AppError extends Error {
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') {
super(message);
this.statusCode = statusCode;
this.code = code;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* 验证错误
*/
class ValidationError extends AppError {
constructor(message, field = null) {
super(message, 400, 'VALIDATION_ERROR');
this.field = field;
}
}
/**
* 资源未找到错误
*/
class NotFoundError extends AppError {
constructor(resource, id = null) {
super(
`${resource} not found${id ? `: ${id}` : ''}`,
404,
'NOT_FOUND'
);
this.resource = resource;
this.id = id;
}
}
/**
* 冲突错误
*/
class ConflictError extends AppError {
constructor(message) {
super(message, 409, 'CONFLICT');
}
}
/**
* 错误处理中间件
*/
const errorHandler = (err, req, res, next) => {
// 操作性错误(预期的错误)
if (err.isOperational) {
return res.status(err.statusCode).json({
success: false,
error: {
code: err.code,
message: err.message,
...(err.field && { field: err.field })
}
});
}
// 编程错误(未预期的错误)
console.error('💥 Unexpected Error:', err);
res.status(500).json({
success: false,
error: {
code: 'INTERNAL_ERROR',
message: process.env.NODE_ENV === 'development'
? err.message
: 'Internal server error',
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
}
});
};
/**
* 异步路由处理器包装
*/
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
module.exports = {
AppError,
ValidationError,
NotFoundError,
ConflictError,
errorHandler,
asyncHandler
};
@@ -0,0 +1,67 @@
/**
* 请求参数验证中间件
*/
const { ValidationError } = require('./errorHandler');
/**
* 验证必需参数
*/
function validateRequired(fields) {
return (req, res, next) => {
const source = req.method === 'GET' ? req.query : req.body;
for (const field of fields) {
if (!source[field]) {
return next(new ValidationError(`${field} is required`, field));
}
}
next();
};
}
/**
* 验证素材库 ID
*/
function validateLibraryId(req, res, next) {
const libraryId = req.params.id || req.query.libraryId || req.body.libraryId;
if (!libraryId) {
return next(new ValidationError('Library ID is required', 'libraryId'));
}
req.libraryId = libraryId;
next();
}
/**
* 验证分页参数
*/
function validatePagination(req, res, next) {
const { offset, limit } = req.query;
if (offset !== undefined) {
const offsetNum = parseInt(offset, 10);
if (isNaN(offsetNum) || offsetNum < 0) {
return next(new ValidationError('Invalid offset', 'offset'));
}
req.pagination = { offset: offsetNum };
}
if (limit !== undefined) {
const limitNum = parseInt(limit, 10);
if (isNaN(limitNum) || limitNum < 1 || limitNum > 500) {
return next(new ValidationError('Invalid limit (1-500)', 'limit'));
}
req.pagination = { ...req.pagination, limit: limitNum };
}
next();
}
module.exports = {
validateRequired,
validateLibraryId,
validatePagination
};
+44
View File
@@ -0,0 +1,44 @@
/**
* 基础数据模型
* 提供通用的数据库操作方法
*/
class BaseModel {
constructor(db) {
this.db = db;
}
/**
* 执行查询并返回单条记录
*/
findOne(query, params = []) {
const stmt = this.db.prepare(query);
return stmt.get(...params);
}
/**
* 执行查询并返回多条记录
*/
findMany(query, params = []) {
const stmt = this.db.prepare(query);
return stmt.all(...params);
}
/**
* 执行插入/更新/删除操作
*/
execute(query, params = []) {
const stmt = this.db.prepare(query);
return stmt.run(...params);
}
/**
* 执行事务
*/
transaction(fn) {
const transaction = this.db.transaction(fn);
return transaction();
}
}
module.exports = BaseModel;
+115
View File
@@ -0,0 +1,115 @@
/**
* 文件夹数据模型
*/
const BaseModel = require('./BaseModel');
const { mapFolderForFrontend } = require('../utils/fieldMapper');
class FolderModel extends BaseModel {
/**
* 根据路径查找文件夹
*/
findByPath(path) {
const query = 'SELECT * FROM folders WHERE path = ?';
const folder = this.findOne(query, [path]);
return folder ? mapFolderForFrontend(folder) : null;
}
/**
* 获取所有文件夹
*/
findAll() {
const query = 'SELECT * FROM folders ORDER BY path';
return this.findMany(query).map(mapFolderForFrontend);
}
/**
* 获取文件夹树
*/
getTree() {
const folders = this.findAll();
return this._buildTree(folders);
}
/**
* 插入文件夹
*/
insert(data) {
const query = `
INSERT OR REPLACE INTO folders
(path, parent_path, name, image_count, last_scan)
VALUES (?, ?, ?, ?, ?)
`;
return this.execute(query, [
data.path,
data.parentPath || '',
data.name,
data.imageCount || 0,
data.lastScan || Date.now()
]);
}
/**
* 更新文件夹图片数量
*/
updateImageCount(path) {
const query = `
UPDATE folders
SET image_count = (
SELECT COUNT(*) FROM images
WHERE folder = ? OR folder LIKE ?
)
WHERE path = ?
`;
return this.execute(query, [path, `${path}/%`, path]);
}
/**
* 删除文件夹
*/
deleteByPath(path) {
const query = 'DELETE FROM folders WHERE path = ?';
return this.execute(query, [path]);
}
/**
* 按前缀批量删除
*/
deleteByPrefix(prefix) {
const query = 'DELETE FROM folders WHERE path = ? OR path LIKE ?';
return this.execute(query, [prefix, `${prefix}/%`]);
}
/**
* 构建文件夹树
*/
_buildTree(folders) {
const folderMap = new Map();
const rootFolders = [];
// 第一遍:创建映射
folders.forEach(folder => {
folderMap.set(folder.path, { ...folder, children: [] });
});
// 第二遍:构建树结构
folders.forEach(folder => {
const node = folderMap.get(folder.path);
if (!folder.parentPath || folder.parentPath === '') {
rootFolders.push(node);
} else {
const parent = folderMap.get(folder.parentPath);
if (parent) {
parent.children.push(node);
} else {
rootFolders.push(node);
}
}
});
return rootFolders;
}
}
module.exports = FolderModel;
+222
View File
@@ -0,0 +1,222 @@
/**
* 图片数据模型
*/
const BaseModel = require('./BaseModel');
const { mapImageForFrontend } = require('../utils/fieldMapper');
class ImageModel extends BaseModel {
/**
* 根据 ID 查找图片
*/
findById(id) {
const query = 'SELECT * FROM images WHERE id = ?';
const image = this.findOne(query, [id]);
return image ? mapImageForFrontend(image) : null;
}
/**
* 根据路径查找图片
*/
findByPath(path) {
const query = 'SELECT * FROM images WHERE path = ?';
const image = this.findOne(query, [path]);
return image ? mapImageForFrontend(image) : null;
}
/**
* 搜索图片(支持分页)
*/
search(filters = {}, pagination = null) {
const { query, params } = this._buildSearchQuery(filters, pagination);
// 获取总数(不包含分页参数)
const { query: countQueryBase, params: countParams } = this._buildSearchQuery(filters, null);
const countQuery = countQueryBase
.replace('SELECT *', 'SELECT COUNT(*) as total')
.split('ORDER BY')[0];
const { total } = this.findOne(countQuery, countParams);
// 获取数据
const images = this.findMany(query, params).map(mapImageForFrontend);
// 统一返回对象格式
if (pagination) {
return {
images,
total,
offset: pagination.offset,
limit: pagination.limit,
hasMore: pagination.offset + images.length < total
};
}
// 无分页时也返回对象格式
return {
images,
total
};
}
/**
* 插入图片
*/
insert(data) {
const query = `
INSERT OR REPLACE INTO images
(path, filename, folder, size, width, height, format, file_type,
created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`;
return this.execute(query, [
data.path,
data.filename,
data.folder,
data.size,
data.width,
data.height,
data.format,
data.fileType || 'image',
data.createdAt,
data.modifiedAt,
data.fileHash,
data.thumbnailPath,
data.thumbnailSize,
Date.now()
]);
}
/**
* 批量插入图片
*/
insertBatch(images) {
const query = `
INSERT OR REPLACE INTO images
(path, filename, folder, size, width, height, format, file_type,
created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`;
return this.transaction(() => {
const stmt = this.db.prepare(query);
for (const data of images) {
stmt.run(
data.path, data.filename, data.folder, data.size,
data.width, data.height, data.format, data.fileType || 'image',
data.createdAt, data.modifiedAt, data.fileHash,
data.thumbnailPath, data.thumbnailSize, Date.now()
);
}
});
}
/**
* 更新图片
*/
update(path, data) {
const fields = [];
const params = [];
Object.entries(data).forEach(([key, value]) => {
fields.push(`${key} = ?`);
params.push(value);
});
params.push(path);
const query = `UPDATE images SET ${fields.join(', ')} WHERE path = ?`;
return this.execute(query, params);
}
/**
* 删除图片
*/
deleteByPath(path) {
const query = 'DELETE FROM images WHERE path = ?';
return this.execute(query, [path]);
}
/**
* 按文件夹前缀批量删除
*/
deleteByFolderPrefix(folderPrefix) {
const query = 'DELETE FROM images WHERE folder = ? OR folder LIKE ?';
return this.execute(query, [folderPrefix, `${folderPrefix}/%`]);
}
/**
* 获取图片总数
*/
count(filters = {}) {
const { query, params } = this._buildSearchQuery(filters);
const countQuery = query
.replace('SELECT *', 'SELECT COUNT(*) as count')
.split('ORDER BY')[0];
const { count } = this.findOne(countQuery, params);
return count;
}
/**
* 构建搜索查询
*/
_buildSearchQuery(filters = {}, pagination = null) {
let query = 'SELECT * FROM images WHERE 1=1';
const params = [];
// 关键词搜索(AND 逻辑)
if (filters.keywords) {
const terms = filters.keywords.trim().split(/\s+/);
terms.forEach(term => {
query += ' AND filename LIKE ?';
params.push(`%${term}%`);
});
}
// 文件夹过滤(包含子文件夹)
if (filters.folder) {
query += ' AND (folder = ? OR folder LIKE ?)';
params.push(filters.folder, `${filters.folder}/%`);
}
// 格式过滤
if (filters.formats && filters.formats.length > 0) {
const placeholders = filters.formats.map(() => '?').join(',');
query += ` AND format IN (${placeholders})`;
params.push(...filters.formats);
}
// 大小过滤
if (filters.minSize) {
query += ' AND size >= ?';
params.push(filters.minSize);
}
if (filters.maxSize) {
query += ' AND size <= ?';
params.push(filters.maxSize);
}
// 日期过滤
if (filters.startDate) {
query += ' AND created_at >= ?';
params.push(filters.startDate);
}
if (filters.endDate) {
query += ' AND created_at <= ?';
params.push(filters.endDate);
}
// 排序
query += ' ORDER BY created_at DESC';
// 分页
if (pagination) {
query += ' LIMIT ? OFFSET ?';
params.push(pagination.limit, pagination.offset);
}
return { query, params };
}
}
module.exports = ImageModel;
+170
View File
@@ -0,0 +1,170 @@
/**
* 图片路由(新架构)
* 薄层路由,业务逻辑在 Service 层
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const { asyncHandler } = require('../middleware/errorHandler');
const { validatePagination } = require('../middleware/validator');
const { getFlypicPath } = require('../config');
// 服务实例(从 app 中获取)
let imageService;
router.use((req, res, next) => {
if (!imageService) {
imageService = req.app.get('imageService');
}
next();
});
/**
* 搜索图片
* GET /api/image?libraryId=xxx&keywords=xxx&folder=xxx&offset=0&limit=100
*/
router.get('/',
validatePagination,
asyncHandler(async (req, res) => {
const { libraryId, keywords, folder, formats, offset, limit } = req.query;
const filters = {};
if (keywords) filters.keywords = keywords;
if (folder) filters.folder = folder;
if (formats) filters.formats = formats.split(',');
const pagination = (offset !== undefined && limit !== undefined)
? { offset: parseInt(offset), limit: parseInt(limit) }
: null;
const result = await imageService.searchImages(libraryId, filters, pagination);
res.json({ success: true, data: result });
})
);
/**
* 获取图片总数
* GET /api/image/count?libraryId=xxx
*/
router.get('/count', asyncHandler(async (req, res) => {
const { libraryId } = req.query;
const count = await imageService.getImageCount(libraryId);
res.json({ success: true, data: { count } });
}));
/**
* 获取图片统计
* GET /api/image/stats?libraryId=xxx
*/
router.get('/stats', asyncHandler(async (req, res) => {
const { libraryId } = req.query;
const stats = await imageService.getImageStats(libraryId);
res.json({ success: true, data: stats });
}));
/**
* 获取文件夹列表
* GET /api/image/folders?libraryId=xxx
*/
router.get('/folders', asyncHandler(async (req, res) => {
const { libraryId } = req.query;
const folders = await imageService.getFolders(libraryId);
res.json({ success: true, data: { folders } });
}));
/**
* 获取缓存元数据
* GET /api/image/cache-meta?libraryId=xxx
*/
router.get('/cache-meta', asyncHandler(async (req, res) => {
const { libraryId } = req.query;
const meta = await imageService.getCacheMeta(libraryId);
res.json({ success: true, data: meta });
}));
/**
* 获取图片详情
* GET /api/image/:id?libraryId=xxx
*/
router.get('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const { libraryId } = req.query;
const image = await imageService.getImageById(libraryId, id);
res.json({ success: true, data: image });
}));
/**
* 获取缩略图
* GET /api/image/thumbnail/:libraryId/:filename
* 使用分片结构:.flypic/thumbnails/ab/hash.webp
*/
router.get('/thumbnail/:libraryId/:filename', (req, res) => {
const { libraryId, filename } = req.params;
try {
const config = require('../../utils/config').loadConfig();
// 尝试两种方式查找:数字和字符串
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
if (!library) {
library = config.libraries.find(lib => lib.id == libraryId);
}
if (!library) {
return res.status(404).send('Library not found');
}
// 使用分片结构:取文件名前2个字符作为分片目录
const hash = filename.replace(/\.[^/.]+$/, '');
const shard = hash.slice(0, 2);
const flypicPath = getFlypicPath(library.path);
const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename);
if (!fs.existsSync(thumbnailPath)) {
return res.status(404).send('Thumbnail not found');
}
res.sendFile(thumbnailPath);
} catch (error) {
console.error('❌ 缩略图错误:', error.message);
res.status(500).send('Error serving thumbnail');
}
});
/**
* 获取原图
* GET /api/image/original/:libraryId/:path
*/
router.get('/original/:libraryId/*', (req, res) => {
const { libraryId } = req.params;
const imagePath = req.params[0]; // 获取通配符匹配的路径
try {
const config = require('../../utils/config').loadConfig();
// 尝试两种方式查找:数字和字符串
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
if (!library) {
library = config.libraries.find(lib => lib.id == libraryId);
}
if (!library) {
return res.status(404).send('Library not found');
}
const fullPath = path.join(library.path, imagePath);
if (!fs.existsSync(fullPath)) {
return res.status(404).send('Image not found');
}
res.sendFile(fullPath);
} catch (error) {
console.error('Error serving original image:', error);
res.status(500).send('Error serving image');
}
});
module.exports = router;
+109
View File
@@ -0,0 +1,109 @@
/**
* 素材库路由(新架构)
* 薄层路由,业务逻辑在 Service 层
*/
const express = require('express');
const router = express.Router();
const { asyncHandler } = require('../middleware/errorHandler');
const { validateRequired } = require('../middleware/validator');
// 服务实例(从 app 中获取)
let libraryService;
router.use((req, res, next) => {
if (!libraryService) {
libraryService = req.app.get('libraryService');
}
next();
});
/**
* 获取所有素材库
* GET /api/library
*/
router.get('/', asyncHandler(async (req, res) => {
const data = libraryService.getAllLibraries();
res.json({ success: true, data });
}));
/**
* 创建素材库
* POST /api/library
* Body: { name, path }
*/
router.post('/',
validateRequired(['name', 'path']),
asyncHandler(async (req, res) => {
const { name, path } = req.body;
const result = await libraryService.createLibrary(name, path);
res.json({ success: true, data: result });
})
);
/**
* 更新素材库
* PUT /api/library/:id
* Body: { name?, path? }
*/
router.put('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const result = await libraryService.updateLibrary(id, req.body);
res.json({ success: true, data: result });
}));
/**
* 删除素材库
* DELETE /api/library/:id
*/
router.delete('/:id', asyncHandler(async (req, res) => {
const { id } = req.params;
const result = await libraryService.deleteLibrary(id);
res.json({ success: true, data: result });
}));
/**
* 设置当前素材库
* POST /api/library/:id/set-current
*/
router.post('/:id/set-current', asyncHandler(async (req, res) => {
const { id } = req.params;
const result = await libraryService.setCurrentLibrary(id);
res.json({ success: true, data: result });
}));
/**
* 更新偏好设置
* PUT /api/library/preferences
* Body: { preferences }
*/
router.put('/preferences', asyncHandler(async (req, res) => {
const result = libraryService.updatePreferences(req.body);
res.json({ success: true, data: result });
}));
/**
* 更新主题
* PUT /api/library/theme
* Body: { theme }
*/
router.put('/theme',
validateRequired(['theme']),
asyncHandler(async (req, res) => {
const { theme } = req.body;
const result = libraryService.updateTheme(theme);
res.json({ success: true, data: result });
})
);
/**
* 获取素材库统计
* GET /api/library/:id/stats
*/
router.get('/:id/stats', asyncHandler(async (req, res) => {
const { id } = req.params;
const result = await libraryService.getLibraryStats(id);
res.json({ success: true, data: result });
}));
module.exports = router;
+82
View File
@@ -0,0 +1,82 @@
/**
* 扫描路由(新架构)
* 薄层路由,业务逻辑在 Service 层
*/
const express = require('express');
const router = express.Router();
const { asyncHandler } = require('../middleware/errorHandler');
const { validateRequired } = require('../middleware/validator');
// 服务实例(从 app 中获取)
let scanService;
router.use((req, res, next) => {
if (!scanService) {
scanService = req.app.get('scanService');
}
next();
});
/**
* 全量扫描
* POST /api/scan/full
* Body: { libraryId, wait? }
*/
router.post('/full',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId, wait = false } = req.body;
const result = await scanService.fullScan(libraryId, wait);
res.json({ success: true, data: result });
})
);
/**
* 增量同步
* POST /api/scan/sync
* Body: { libraryId, wait? }
*/
router.post('/sync',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId, wait = false } = req.body;
const result = await scanService.incrementalSync(libraryId, wait);
res.json({ success: true, data: result });
})
);
/**
* 获取扫描状态
* GET /api/scan/status/:libraryId
*/
router.get('/status/:libraryId', asyncHandler(async (req, res) => {
const { libraryId } = req.params;
const result = scanService.getScanStatus(libraryId);
res.json({ success: true, data: result });
}));
/**
* 获取所有活跃的扫描状态
* GET /api/scan/active-states
*/
router.get('/active-states', asyncHandler(async (req, res) => {
const result = scanService.getAllActiveStates();
res.json({ success: true, data: result });
}));
/**
* 修复文件夹路径
* POST /api/scan/fix-folders
* Body: { libraryId }
*/
router.post('/fix-folders',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId } = req.body;
const result = await scanService.fixFolders(libraryId);
res.json({ success: true, data: result });
})
);
module.exports = router;
@@ -0,0 +1,181 @@
/**
* 图片服务层
* 封装图片相关的业务逻辑
*/
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
const ImageModel = require('../models/ImageModel');
const FolderModel = require('../models/FolderModel');
class ImageService {
constructor(configManager, dbPool) {
this.configManager = configManager;
this.dbPool = dbPool;
}
/**
* 搜索图片
*/
async searchImages(libraryId, filters = {}, pagination = null) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const imageModel = new ImageModel(db.db);
return imageModel.search(filters, pagination);
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取图片详情
*/
async getImageById(libraryId, imageId) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const imageModel = new ImageModel(db.db);
const image = imageModel.findById(imageId);
if (!image) {
throw new NotFoundError('Image', imageId);
}
return image;
} finally {
this.dbPool.release(library.path);
}
}
/**
* 根据路径获取图片
*/
async getImageByPath(libraryId, imagePath) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const imageModel = new ImageModel(db.db);
const image = imageModel.findByPath(imagePath);
if (!image) {
throw new NotFoundError('Image', imagePath);
}
return image;
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取图片总数
*/
async getImageCount(libraryId, filters = {}) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const imageModel = new ImageModel(db.db);
return imageModel.count(filters);
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取图片统计信息
*/
async getImageStats(libraryId) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const stats = db.db.prepare(`
SELECT
COUNT(*) as total,
SUM(size) as totalSize,
AVG(size) as avgSize,
MAX(size) as maxSize,
MIN(size) as minSize,
COUNT(DISTINCT format) as formatCount,
COUNT(DISTINCT folder) as folderCount
FROM images
`).get();
const formatStats = db.db.prepare(`
SELECT format, COUNT(*) as count
FROM images
GROUP BY format
ORDER BY count DESC
`).all();
return {
...stats,
formats: formatStats
};
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取文件夹列表
*/
async getFolders(libraryId) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const folderModel = new FolderModel(db.db);
return folderModel.getTree();
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取缓存元数据
*/
async getCacheMeta(libraryId) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
const result = db.db.prepare(`
SELECT
COUNT(*) as totalImages,
COUNT(DISTINCT folder) as totalFolders,
MAX(indexed_at) as lastIndexed
FROM images
`).get();
return {
libraryId,
...result,
dbPath: library.path
};
} finally {
this.dbPool.release(library.path);
}
}
/**
* 获取素材库对象
* @private
*/
_getLibrary(libraryId) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === libraryId);
if (!library) {
throw new NotFoundError('Library', libraryId);
}
return library;
}
}
module.exports = ImageService;
@@ -0,0 +1,275 @@
/**
* 素材库服务层
* 封装素材库相关的业务逻辑
*/
const fs = require('fs');
const path = require('path');
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
const { getFlypicPath, getDatabasePath } = require('../config');
class LibraryService {
constructor(configManager, dbPool, scanManager, lightweightWatcher, io) {
this.configManager = configManager;
this.dbPool = dbPool;
this.scanManager = scanManager;
this.lightweightWatcher = lightweightWatcher;
this.io = io;
}
/**
* 获取所有素材库
*/
getAllLibraries() {
const config = this.configManager.load();
return {
libraries: config.libraries || [],
currentLibraryId: config.currentLibraryId,
theme: config.theme || 'light',
preferences: config.preferences || {}
};
}
/**
* 创建新素材库
*/
async createLibrary(name, libraryPath) {
// 验证参数
if (!name || !libraryPath) {
throw new ValidationError('Name and path are required');
}
// 规范化路径
const normalizedPath = path.normalize(libraryPath);
console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`);
if (!fs.existsSync(normalizedPath)) {
console.log(`[LibraryService] Path does not exist: ${normalizedPath}`);
throw new ValidationError('Path does not exist', 'path');
}
// 检查文件夹访问权限
try {
// 尝试读取目录
fs.readdirSync(normalizedPath);
// 尝试在目录中创建测试文件(检查写权限)
const testFile = path.join(normalizedPath, '.flypic-test');
try {
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
} catch (writeError) {
console.log(`[LibraryService] No write permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
} catch (readError) {
if (readError.code === 'EACCES' || readError.code === 'EPERM') {
console.log(`[LibraryService] No access permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
// 如果不是权限错误,继续抛出
if (readError.name !== 'ValidationError') {
throw readError;
}
throw readError;
}
// 检查路径是否已存在
const config = this.configManager.load();
const existingLib = config.libraries.find(lib => lib.path === normalizedPath);
if (existingLib) {
throw new ValidationError('Library path already exists', 'path');
}
// 创建素材库
const id = this.configManager.addLibrary(name, normalizedPath);
// 检查是否有现有索引
const flypicDir = getFlypicPath(normalizedPath);
const dbPath = getDatabasePath(normalizedPath);
const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath);
return {
id,
hasExistingIndex,
message: hasExistingIndex
? 'Library created with existing index'
: 'Library created, please scan to build index'
};
}
/**
* 更新素材库
*/
updateLibrary(id, updates) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
throw new NotFoundError('Library', id);
}
// 验证更新的路径是否存在
if (updates.path && !fs.existsSync(updates.path)) {
throw new ValidationError('Path does not exist', 'path');
}
const success = this.configManager.updateLibrary(id, updates);
return { success };
}
/**
* 删除素材库
*/
async deleteLibrary(id) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
throw new NotFoundError('Library', id);
}
// 清理资源
await this._cleanupLibraryResources(id, library.path);
// 删除配置
this.configManager.removeLibrary(id);
return {
success: true,
path: library.path,
message: 'Library deleted successfully'
};
}
/**
* 设置当前素材库
*/
async setCurrentLibrary(id) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === id);
if (!library) {
throw new NotFoundError('Library', id);
}
// 切换前清理旧素材库资源
if (config.currentLibraryId && config.currentLibraryId !== id) {
const oldLibrary = config.libraries.find(lib => lib.id === config.currentLibraryId);
if (oldLibrary) {
await this._cleanupLibraryResources(config.currentLibraryId, oldLibrary.path, false);
}
}
// 设置新素材库
this.configManager.setCurrentLibrary(id);
// 预热数据库连接
try {
const db = this.dbPool.acquire(library.path);
db.db.prepare('SELECT 1').get();
this.dbPool.release(library.path);
} catch (e) {
// 忽略预热错误
}
// 启动文件监控
if (this.lightweightWatcher && this.io) {
try {
this.lightweightWatcher.watch(id, library.path, library.name, this.io);
} catch (e) {
console.warn('Failed to start file watcher:', e.message);
}
}
return {
success: true,
libraryId: id,
message: 'Current library set successfully'
};
}
/**
* 更新偏好设置
*/
updatePreferences(preferences) {
this.configManager.updatePreferences(preferences);
return { success: true };
}
/**
* 更新主题
*/
updateTheme(theme) {
if (!['light', 'dark'].includes(theme)) {
throw new ValidationError('Invalid theme, must be light or dark', 'theme');
}
this.configManager.updateTheme(theme);
return { success: true, theme };
}
/**
* 清理素材库资源
* @private
*/
async _cleanupLibraryResources(libraryId, libraryPath, deleteConfig = true) {
// 停止扫描
if (this.scanManager) {
this.scanManager.clearState(libraryId);
}
// 停止文件监控
if (this.lightweightWatcher) {
this.lightweightWatcher.unwatch(libraryId);
}
// 关闭数据库连接
if (this.dbPool) {
this.dbPool.close(libraryPath);
}
// 等待资源释放
await new Promise(resolve => setTimeout(resolve, 300));
}
/**
* 获取素材库统计信息
*/
async getLibraryStats(libraryId) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === libraryId);
if (!library) {
throw new NotFoundError('Library', libraryId);
}
const db = this.dbPool.acquire(library.path);
try {
const imageCount = db.db.prepare('SELECT COUNT(*) as count FROM images').get().count;
const folderCount = db.db.prepare('SELECT COUNT(*) as count FROM folders').get().count;
const sizeResult = db.db.prepare('SELECT SUM(size) as totalSize FROM images').get();
const totalSize = sizeResult.totalSize || 0;
return {
libraryId,
imageCount,
folderCount,
totalSize,
path: library.path,
name: library.name
};
} finally {
this.dbPool.release(library.path);
}
}
}
module.exports = LibraryService;
@@ -0,0 +1,178 @@
/**
* 扫描服务层(简化版)
* 无暂停功能,只负责扫描和进度推送
*/
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
class ScanService {
constructor(configManager, dbPool, scanner, scanManager, io) {
this.configManager = configManager;
this.dbPool = dbPool;
this.scanner = scanner;
this.scanManager = scanManager;
this.io = io;
}
/**
* 全量扫描
*/
async fullScan(libraryId, wait = false) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
if (wait) {
await this.scanner.scanLibrary(
library.path,
db,
(progress) => this._emitProgress(libraryId, progress),
libraryId
);
return { success: true, message: 'Scan completed', libraryId };
} else {
this._startAsyncScan(libraryId, library.path, db);
return { success: true, message: 'Scan started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
throw error;
}
}
/**
* 增量同步
*/
async incrementalSync(libraryId, wait = false) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
if (wait) {
await this.scanner.syncLibrary(
library.path,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
);
return { success: true, message: 'Sync completed', libraryId };
} else {
this._startAsyncSync(libraryId, library.path, db);
return { success: true, message: 'Sync started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
throw error;
}
}
/**
* 获取扫描状态
*/
getScanStatus(libraryId) {
const library = this._getLibrary(libraryId);
const state = this.scanManager.getState(libraryId);
return {
libraryId,
status: state?.status || 'idle',
progress: state?.progress || null,
startTime: state?.startTime || null
};
}
/**
* 获取所有活跃状态
*/
getAllActiveStates() {
return this.scanManager.getAllActiveStates();
}
/**
* 修复文件夹路径
*/
async fixFolders(libraryId) {
const library = this._getLibrary(libraryId);
const db = this.dbPool.acquire(library.path);
try {
await this.scanner.fixFolderPaths(library.path, db);
return { success: true, message: 'Folders fixed', libraryId };
} finally {
this.dbPool.release(library.path);
}
}
/**
* 启动异步扫描
*/
_startAsyncScan(libraryId, libraryPath, db) {
this.scanner.scanLibrary(
libraryPath,
db,
(progress) => this._emitProgress(libraryId, progress),
libraryId
).then(() => {
this._emitComplete(libraryId);
this.dbPool.release(libraryPath);
}).catch((error) => {
this._emitError(libraryId, error);
this.dbPool.release(libraryPath);
});
}
/**
* 启动异步同步
*/
_startAsyncSync(libraryId, libraryPath, db) {
this.scanner.syncLibrary(
libraryPath,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
).then(() => {
this._emitComplete(libraryId);
this.dbPool.release(libraryPath);
}).catch((error) => {
this._emitError(libraryId, error);
this.dbPool.release(libraryPath);
});
}
_emitProgress(libraryId, progress) {
if (this.io) {
this.io.emit('scanProgress', { libraryId, ...progress });
}
}
_emitComplete(libraryId) {
if (this.io) {
this.io.emit('scanComplete', { libraryId });
}
}
_emitError(libraryId, error) {
if (this.io) {
this.io.emit('scanError', { libraryId, error: error.message });
}
}
_getLibrary(libraryId) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === libraryId);
if (!library) {
throw new NotFoundError('Library', libraryId);
}
return library;
}
}
module.exports = ScanService;
@@ -0,0 +1,71 @@
/**
* 数据库字段映射工具
* 将 snake_case 转换为 camelCase
*/
// 数据库字段到前端字段的映射
const DB_TO_FRONTEND_MAP = {
// Image fields
file_type: 'fileType',
created_at: 'createdAt',
modified_at: 'modifiedAt',
file_hash: 'fileHash',
thumbnail_path: 'thumbnailPath',
thumbnail_size: 'thumbnailSize',
indexed_at: 'indexedAt',
// Folder fields
parent_path: 'parentPath',
image_count: 'imageCount',
last_scan: 'lastScan'
};
/**
* 映射单个对象的字段
*/
function mapFields(obj, mapping) {
if (!obj) return null;
const result = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = mapping[key] || key;
result[newKey] = value;
}
return result;
}
/**
* 映射图片对象
*/
function mapImageForFrontend(image) {
return mapFields(image, DB_TO_FRONTEND_MAP);
}
/**
* 映射文件夹对象
*/
function mapFolderForFrontend(folder) {
return mapFields(folder, DB_TO_FRONTEND_MAP);
}
/**
* 批量映射图片数组
*/
function mapImagesForFrontend(images) {
return images.map(mapImageForFrontend);
}
/**
* 批量映射文件夹数组
*/
function mapFoldersForFrontend(folders) {
return folders.map(mapFolderForFrontend);
}
module.exports = {
mapImageForFrontend,
mapFolderForFrontend,
mapImagesForFrontend,
mapFoldersForFrontend,
mapFields
};
+31
View File
@@ -0,0 +1,31 @@
/**
* 简单的日志工具
*/
const LOG_LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3
};
const currentLevel = process.env.LOG_LEVEL
? LOG_LEVELS[process.env.LOG_LEVEL.toUpperCase()]
: LOG_LEVELS.INFO;
function log(level, message, ...args) {
if (LOG_LEVELS[level] >= currentLevel) {
const timestamp = new Date().toISOString();
const prefix = `[${timestamp}] [${level}]`;
console.log(prefix, message, ...args);
}
}
const logger = {
debug: (message, ...args) => log('DEBUG', message, ...args),
info: (message, ...args) => log('INFO', message, ...args),
warn: (message, ...args) => log('WARN', message, ...args),
error: (message, ...args) => log('ERROR', message, ...args)
};
module.exports = logger;
+233
View File
@@ -0,0 +1,233 @@
/**
* Cleanup Manager
* Executes routine and emergency memory cleanup procedures
*/
class CleanupManager {
constructor(options = {}) {
this.routineInterval = options.routineInterval || 5000; // 5 seconds
this.dbPool = options.dbPool;
this.caches = new Map(); // name -> cache object with clear() method
this.routineIntervalId = null;
this.isRunning = false;
this.cleanupCount = 0;
this.lastCleanupTime = 0;
}
/**
* Start routine cleanup
*/
startRoutineCleanup() {
if (this.isRunning) return;
console.log('🧹 清理管理器已启动');
this.isRunning = true;
this.routineIntervalId = setInterval(() => {
this.executeRoutineCleanup();
}, this.routineInterval);
}
/**
* Stop routine cleanup
*/
stopRoutineCleanup() {
if (!this.isRunning) return;
console.log('🧹 清理管理器已停止');
if (this.routineIntervalId) {
clearInterval(this.routineIntervalId);
this.routineIntervalId = null;
}
this.isRunning = false;
}
/**
* Execute routine cleanup
* - Clear registered caches
* - Trigger garbage collection (if available)
*/
executeRoutineCleanup() {
const memoryBefore = this.getMemoryStats();
const rssBefore = memoryBefore.rss / 1024 / 1024;
try {
// Clear all registered caches
const cachesCleared = this.clearAllCaches();
// 强制多次 GC(更激进)
if (global.gc) {
// 执行 5 次 GC 确保内存真正释放
for (let i = 0; i < 5; i++) {
global.gc();
}
}
const memoryAfter = this.getMemoryStats();
const rssAfter = memoryAfter.rss / 1024 / 1024;
const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed;
const rssReclaimed = rssBefore - rssAfter;
this.cleanupCount++;
this.lastCleanupTime = Date.now();
// 只在内存回收显著时输出日志
if (Math.abs(rssReclaimed) > 10) {
console.log(`🧹 内存清理: ${rssBefore.toFixed(0)}MB → ${rssAfter.toFixed(0)}MB`);
}
return {
memoryBefore,
memoryAfter,
memoryReclaimed,
cachesCleared,
connectionsCleared: 0
};
} catch (error) {
console.error('❌ 清理失败:', error.message);
return null;
}
}
/**
* Execute emergency cleanup
* - Force close all database connections
* - Clear all caches
* - Force garbage collection multiple times (3+)
*/
executeEmergencyCleanup() {
console.log('🚨 执行紧急内存清理...');
const memoryBefore = this.getMemoryStats();
try {
// 1. Force close all database connections
let connectionsCleared = 0;
if (this.dbPool) {
try {
this.dbPool.closeAll();
connectionsCleared = 1;
console.log(' ✓ 数据库连接已关闭');
} catch (error) {
console.error(' ✗ 关闭连接失败:', error.message);
}
}
// 2. Clear all registered caches
const cachesCleared = this.clearAllCaches();
console.log(` ✓ 已清理 ${cachesCleared} 个缓存`);
// 3. Force garbage collection multiple times (minimum 3)
this.forceGarbageCollection(3);
const memoryAfter = this.getMemoryStats();
const memoryReclaimed = memoryBefore.heapUsed - memoryAfter.heapUsed;
console.log(`✅ 紧急清理完成: 回收 ${(memoryReclaimed / 1024 / 1024).toFixed(0)}MB`);
return {
memoryBefore,
memoryAfter,
memoryReclaimed,
cachesCleared,
connectionsCleared
};
} catch (error) {
console.error('❌ 紧急清理失败:', error.message);
return null;
}
}
/**
* Force garbage collection multiple times
* @param {number} iterations - Number of GC iterations (minimum 3)
*/
forceGarbageCollection(iterations = 3) {
if (!global.gc) return;
const actualIterations = Math.max(3, iterations);
for (let i = 0; i < actualIterations; i++) {
try {
global.gc();
} catch (error) {
console.error(` ✗ GC失败 (${i + 1}/${actualIterations}):`, error.message);
}
}
}
/**
* Clear all registered caches
* @returns {number} Number of caches cleared
*/
clearAllCaches() {
let cleared = 0;
for (const [name, cache] of this.caches.entries()) {
try {
if (cache && typeof cache.clear === 'function') {
cache.clear();
cleared++;
}
} catch (error) {
console.error(`❌ 清理缓存失败 "${name}":`, error.message);
}
}
return cleared;
}
/**
* Register a cache for cleanup
* @param {string} name - Cache name
* @param {Object} cache - Cache object with clear() method
*/
registerCache(name, cache) {
if (!cache || typeof cache.clear !== 'function') {
console.warn(`⚠️ 缓存 "${name}" 无clear()方法`);
return;
}
this.caches.set(name, cache);
}
/**
* Unregister a cache
* @param {string} name - Cache name
*/
unregisterCache(name) {
this.caches.delete(name);
}
/**
* Get current memory statistics
*/
getMemoryStats() {
const usage = process.memoryUsage();
return {
heapUsed: usage.heapUsed,
heapTotal: usage.heapTotal,
rss: usage.rss,
external: usage.external,
arrayBuffers: usage.arrayBuffers,
timestamp: Date.now()
};
}
/**
* Get cleanup manager status
*/
getStatus() {
return {
isRunning: this.isRunning,
routineInterval: this.routineInterval,
cleanupCount: this.cleanupCount,
lastCleanupTime: this.lastCleanupTime,
registeredCaches: Array.from(this.caches.keys())
};
}
}
module.exports = CleanupManager;
-242
View File
@@ -1,242 +0,0 @@
const { Worker } = require('worker_threads');
const path = require('path');
const { getLibrary } = require('./config');
const { applyChangesFromEvents } = require('./scanner');
const dbPool = require('../database/dbPool');
class FileWatcher {
constructor() {
this.workers = new Map(); // libraryId -> Worker
this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders }
this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved }
this.ioRef = null; // Socket.IO 引用
}
// 获取或创建变更缓冲区
_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
);
}
// 启动监控(使用 Worker Thread,不阻塞主线程)
watch(libraryId, io) {
// 保存 io 引用
this.ioRef = io;
// 如果已经在监控,先停止
if (this.workers.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);
throw new Error(errorMsg);
}
console.log(`[FileWatcher] Starting worker for: ${library.name} (${library.path})`);
// 创建 Worker Thread
const workerPath = path.join(__dirname, 'fileWatcherWorker.js');
const worker = new Worker(workerPath, {
workerData: {
libraryPath: library.path,
libraryName: library.name
}
});
// 处理 Worker 消息
worker.on('message', (msg) => {
this._handleWorkerMessage(libraryId, library, msg);
});
worker.on('error', (error) => {
console.error(`[FileWatcher] Worker error for ${library.name}:`, error);
});
worker.on('exit', (code) => {
if (code !== 0) {
console.error(`[FileWatcher] Worker exited with code ${code} for ${library.name}`);
}
this.workers.delete(libraryId);
});
this.workers.set(libraryId, worker);
}
// 处理 Worker 发来的消息
_handleWorkerMessage(libraryId, library, msg) {
switch (msg.type) {
case 'add':
this._getBuffer(libraryId).filesAdded.add(msg.path);
this._debouncedSync(libraryId, library);
break;
case 'unlink':
this._getBuffer(libraryId).filesRemoved.add(msg.path);
this._debouncedSync(libraryId, library);
break;
case 'change':
this._getBuffer(libraryId).filesChanged.add(msg.path);
this._debouncedSync(libraryId, library);
break;
case 'addDir':
this._getBuffer(libraryId).dirsAdded.add(msg.path);
this._debouncedSync(libraryId, library, true);
break;
case 'unlinkDir':
this._getBuffer(libraryId).dirsRemoved.add(msg.path);
this._debouncedSync(libraryId, library, true);
break;
case 'ready':
console.log(`[FileWatcher] Ready for: ${library.name}`);
break;
case 'error':
console.error(`[FileWatcher] Error for ${library.name}:`, msg.message);
break;
case 'closed':
console.log(`[FileWatcher] Closed for: ${library.name}`);
break;
}
}
// 防抖同步
_debouncedSync(libraryId, library, 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 || oldTimer.forceRebuildFolders;
}
// 自适应防抖时间
let debounceMs = 2000;
if (changeCount <= 1) debounceMs = 800;
else if (changeCount <= 5) debounceMs = 1000;
else if (changeCount <= 20) debounceMs = 1500;
else if (changeCount <= 100) debounceMs = 2000;
else debounceMs = 3000;
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 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)
});
if (this.ioRef) {
this.ioRef.emit('scanComplete', { libraryId, results });
}
console.log(`[FileWatcher] Sync complete for ${library.name}:`, results);
} catch (error) {
console.error(`[FileWatcher] Sync error for ${library.name}:`, error);
if (this.ioRef) {
this.ioRef.emit('scanError', { libraryId, error: error.message });
}
} finally {
dbPool.release(library.path);
}
this.debounceTimers.delete(libraryId);
}, debounceMs);
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
}
// 停止监控
unwatch(libraryId) {
const worker = this.workers.get(libraryId);
if (worker) {
// 发送关闭命令给 Worker
worker.postMessage({ type: 'close' });
// 给 Worker 一些时间优雅关闭,然后强制终止
setTimeout(() => {
if (this.workers.has(libraryId)) {
worker.terminate();
this.workers.delete(libraryId);
}
}, 1000);
console.log(`[FileWatcher] Stopping worker for: ${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.workers.keys()) {
this.unwatch(libraryId);
}
}
// 获取监控状态
isWatching(libraryId) {
return this.workers.has(libraryId);
}
// 获取所有正在监控的库
getWatchedLibraries() {
return Array.from(this.workers.keys());
}
}
// 单例模式
const fileWatcher = new FileWatcher();
module.exports = fileWatcher;
@@ -1,64 +0,0 @@
/**
* File Watcher Worker - 在独立线程中运行 chokidar
* 避免文件监控初始化阻塞主线程的事件循环
*/
const { parentPort, workerData } = require('worker_threads');
const chokidar = require('chokidar');
const { libraryPath, libraryName } = workerData;
console.log(`[Worker] Starting chokidar for: ${libraryName}`);
// 创建监控器
const watcher = chokidar.watch(['**/*.*', '**/'], {
cwd: libraryPath,
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/.flypic/**',
'**/.*'
],
persistent: true,
ignoreInitial: true,
usePolling: false,
awaitWriteFinish: {
stabilityThreshold: 1000,
pollInterval: 200
}
});
// 监听事件并发送到主线程
watcher
.on('add', (filePath) => {
parentPort.postMessage({ type: 'add', path: filePath });
})
.on('unlink', (filePath) => {
parentPort.postMessage({ type: 'unlink', path: filePath });
})
.on('change', (filePath) => {
parentPort.postMessage({ type: 'change', path: filePath });
})
.on('addDir', (dirPath) => {
parentPort.postMessage({ type: 'addDir', path: dirPath });
})
.on('unlinkDir', (dirPath) => {
parentPort.postMessage({ type: 'unlinkDir', path: dirPath });
})
.on('error', (error) => {
parentPort.postMessage({ type: 'error', message: error.message });
})
.on('ready', () => {
console.log(`[Worker] File watcher ready for: ${libraryName}`);
parentPort.postMessage({ type: 'ready' });
});
// 监听主线程的关闭命令
parentPort.on('message', (msg) => {
if (msg.type === 'close') {
console.log(`[Worker] Closing watcher for: ${libraryName}`);
watcher.close().then(() => {
parentPort.postMessage({ type: 'closed' });
process.exit(0);
});
}
});
@@ -0,0 +1,402 @@
/**
* 轻量级文件监控器
* 使用智能轮询代替 chokidar,内存占用 < 50MB
*
* 策略:
* 1. 每 5-10 秒检查一次文件夹的修改时间戳
* 2. 只扫描时间戳变化的文件夹
* 3. 不缓存任何文件元数据
* 4. 使用增量对比,只处理变化的文件
*/
const fs = require('fs').promises;
const path = require('path');
const { applyChangesFromEvents } = require('./scanner');
const dbPool = require('../database/dbPool');
class LightweightWatcher {
constructor() {
this.watchers = new Map(); // libraryId -> { interval, folderTimestamps, libraryPath }
this.ioRef = null;
this.pollInterval = 5000; // 5 秒轮询一次
}
/**
* 启动轻量级监控
*/
async watch(libraryId, libraryPath, libraryName, io) {
this.ioRef = io;
// 如果已经在监控,先停止
if (this.watchers.has(libraryId)) {
this.unwatch(libraryId);
}
console.log(`[LightweightWatcher] Starting for: ${libraryName}`);
console.log(` Strategy: Folder timestamp polling (${this.pollInterval}ms interval)`);
console.log(` Memory: < 50MB (vs chokidar ~800MB)`);
// 🔍 检测离线期间的变化
console.log(`[LightweightWatcher] Checking offline changes...`);
try {
await this._checkOfflineChanges(libraryId, libraryPath, libraryName);
} catch (error) {
console.error(`[LightweightWatcher] Failed to check offline changes:`, error.message);
}
// 初始化文件夹时间戳缓存
const folderTimestamps = new Map();
try {
await this._initializeFolderTimestamps(libraryPath, folderTimestamps);
console.log(` Initialized ${folderTimestamps.size} folders`);
} catch (error) {
console.error(`[LightweightWatcher] Failed to initialize:`, error.message);
return;
}
// 启动轮询
const interval = setInterval(async () => {
try {
await this._checkForChanges(libraryId, libraryPath, libraryName, folderTimestamps);
} catch (error) {
console.error(`[LightweightWatcher] Error checking changes:`, error.message);
}
}, this.pollInterval);
this.watchers.set(libraryId, {
interval,
folderTimestamps,
libraryPath,
libraryName
});
console.log(`[LightweightWatcher] Started for: ${libraryName}`);
}
/**
* 初始化文件夹时间戳(只扫描文件夹,不扫描文件)
*/
async _initializeFolderTimestamps(libraryPath, folderTimestamps) {
const folders = await this._getAllFolders(libraryPath);
for (const folder of folders) {
try {
const stats = await fs.stat(folder);
folderTimestamps.set(folder, stats.mtimeMs);
} catch (error) {
// 忽略无法访问的文件夹
}
}
}
/**
* 递归获取所有文件夹(不包含文件)
*/
async _getAllFolders(dir, folders = []) {
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
// 跳过隐藏文件夹和特殊文件夹
if (entry.name.startsWith('.') ||
entry.name === 'node_modules' ||
entry.name === '.flypic') {
continue;
}
if (entry.isDirectory()) {
const fullPath = path.join(dir, entry.name);
folders.push(fullPath);
// 递归获取子文件夹
await this._getAllFolders(fullPath, folders);
}
}
} catch (error) {
// 忽略无法访问的文件夹
}
return folders;
}
/**
* 检查文件夹变化(核心逻辑)
*/
async _checkForChanges(libraryId, libraryPath, libraryName, folderTimestamps) {
const changedFolders = [];
const deletedFolders = [];
// 1. 检查现有文件夹的时间戳
for (const [folder, oldTimestamp] of folderTimestamps.entries()) {
try {
const stats = await fs.stat(folder);
const newTimestamp = stats.mtimeMs;
if (newTimestamp !== oldTimestamp) {
changedFolders.push(folder);
folderTimestamps.set(folder, newTimestamp);
}
} catch (error) {
// 文件夹被删除
console.log(`[LightweightWatcher] Folder deleted: ${folder}`);
deletedFolders.push(folder);
folderTimestamps.delete(folder);
}
}
// 2. 检查新增的文件夹
const currentFolders = await this._getAllFolders(libraryPath);
for (const folder of currentFolders) {
if (!folderTimestamps.has(folder)) {
console.log(`[LightweightWatcher] New folder detected: ${folder}`);
changedFolders.push(folder);
try {
const stats = await fs.stat(folder);
folderTimestamps.set(folder, stats.mtimeMs);
} catch (error) {
// 忽略
}
}
}
// 3. 如果有变化,扫描这些文件夹
if (changedFolders.length > 0) {
console.log(`[LightweightWatcher] Detected changes in ${changedFolders.length} folders`);
await this._processChangedFolders(libraryId, libraryPath, libraryName, changedFolders);
}
// 4. 处理删除的文件夹
if (deletedFolders.length > 0) {
console.log(`[LightweightWatcher] Processing ${deletedFolders.length} deleted folders`);
await this._processDeletedFolders(libraryId, libraryPath, deletedFolders);
}
}
/**
* 处理变化的文件夹(只扫描这些文件夹)
*/
async _processChangedFolders(libraryId, libraryPath, libraryName, changedFolders) {
const db = dbPool.acquire(libraryPath); // 这是 LibraryDatabase 实例
try {
// 获取数据库中这些文件夹的文件列表
const dbFiles = new Set();
for (const folder of changedFolders) {
const relativePath = path.relative(libraryPath, folder).replace(/\\/g, '/');
// 使用正确的 SQL 模式匹配
const pattern = relativePath ? `${relativePath}/%` : '%';
const stmt = db.db.prepare('SELECT path FROM images WHERE folder = ? OR folder LIKE ?');
const rows = stmt.all(relativePath, pattern);
rows.forEach(row => dbFiles.add(row.path));
}
// 扫描文件系统中这些文件夹的文件
const fsFiles = new Set();
for (const folder of changedFolders) {
await this._scanFolder(folder, libraryPath, fsFiles);
}
// 对比找出变化
const filesAdded = [];
const filesRemoved = [];
for (const file of fsFiles) {
if (!dbFiles.has(file)) {
filesAdded.push(file);
}
}
for (const file of dbFiles) {
if (!fsFiles.has(file)) {
filesRemoved.push(file);
}
}
// 应用变化
if (filesAdded.length > 0 || filesRemoved.length > 0) {
console.log(`[LightweightWatcher] Changes: +${filesAdded.length} -${filesRemoved.length}`);
// 打印详细信息用于调试
if (filesAdded.length > 0) {
console.log(`[LightweightWatcher] Files added:`, filesAdded.slice(0, 5));
}
if (filesRemoved.length > 0) {
console.log(`[LightweightWatcher] Files removed:`, filesRemoved.slice(0, 5));
}
const results = await applyChangesFromEvents(libraryPath, db, {
filesAdded,
filesChanged: [],
filesRemoved,
dirsAdded: [],
dirsRemoved: []
});
if (this.ioRef) {
console.log(`[LightweightWatcher] Emitting scanComplete event for library ${libraryId}`);
this.ioRef.emit('scanComplete', { libraryId, results });
} else {
console.warn(`[LightweightWatcher] No Socket.IO reference, cannot emit scanComplete`);
}
}
} catch (error) {
console.error(`[LightweightWatcher] Error processing changes:`, error);
if (this.ioRef) {
this.ioRef.emit('scanError', { libraryId, error: error.message });
}
} finally {
dbPool.release(libraryPath);
}
}
/**
* 扫描单个文件夹的所有支持的文件
*/
async _scanFolder(folder, libraryPath, fsFiles) {
try {
const entries = await fs.readdir(folder, { withFileTypes: true });
// 支持所有文件类型(与 scanner.js 保持一致)
const supportedExtensions = [
// 图片
'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.tiff', '.tif', '.avif', '.heif', '.heic',
// 视频
'.mp4', '.webm', '.mov', '.avi', '.mkv', '.flv', '.m4v', '.wmv', '.mpg', '.mpeg',
// 音频
'.mp3', '.wav', '.flac', '.aac', '.m4a', '.ogg',
// 文档
'.pdf', '.txt', '.md', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
// 设计
'.psd', '.ai', '.sketch', '.xd', '.fig'
];
for (const entry of entries) {
if (entry.isFile()) {
const ext = path.extname(entry.name).toLowerCase();
if (supportedExtensions.includes(ext)) {
const fullPath = path.join(folder, entry.name);
const relativePath = path.relative(libraryPath, fullPath).replace(/\\/g, '/');
fsFiles.add(relativePath);
}
}
}
} catch (error) {
// 忽略无法访问的文件夹
console.warn(`[LightweightWatcher] Cannot access folder: ${folder}`, error.message);
}
}
/**
* 处理删除的文件夹
*/
async _processDeletedFolders(libraryId, libraryPath, deletedFolders) {
const db = dbPool.acquire(libraryPath);
try {
const filesRemoved = [];
// 获取这些文件夹中的所有文件
for (const folder of deletedFolders) {
const relativePath = path.relative(libraryPath, folder);
const stmt = db.db.prepare('SELECT path FROM images WHERE path LIKE ?');
const rows = stmt.all(`${relativePath}%`);
rows.forEach(row => filesRemoved.push(row.path));
}
if (filesRemoved.length > 0) {
console.log(`[LightweightWatcher] Removing ${filesRemoved.length} files from deleted folders`);
const results = await applyChangesFromEvents(libraryPath, db, {
filesAdded: [],
filesChanged: [],
filesRemoved,
dirsAdded: [],
dirsRemoved: deletedFolders.map(f => path.relative(libraryPath, f))
});
if (this.ioRef) {
this.ioRef.emit('scanComplete', { libraryId, results });
}
}
} catch (error) {
console.error(`[LightweightWatcher] Error processing deleted folders:`, error);
} finally {
dbPool.release(libraryPath);
}
}
/**
* 停止监控
*/
unwatch(libraryId) {
const watcher = this.watchers.get(libraryId);
if (watcher) {
clearInterval(watcher.interval);
this.watchers.delete(libraryId);
console.log(`[LightweightWatcher] Stopped for: ${watcher.libraryName}`);
}
}
/**
* 检测离线期间的变化
* 使用 quickSync 快速检测新增和删除的文件
*/
async _checkOfflineChanges(libraryId, libraryPath, libraryName) {
const db = dbPool.acquire(libraryPath);
try {
const { quickSync } = require('./scanner');
// 使用 quickSync 快速检测变化(只检查新增/删除,不检查修改)
const results = await quickSync(libraryPath, db);
const changes = results.added + results.deleted;
if (changes > 0) {
console.log(`[LightweightWatcher] Offline changes: +${results.added} -${results.deleted}`);
// 发送完成事件
if (this.ioRef) {
this.ioRef.emit('scanComplete', { libraryId, results });
}
} else {
console.log(`[LightweightWatcher] No offline changes`);
}
} catch (error) {
console.error(`[LightweightWatcher] Error checking offline changes:`, error);
} finally {
dbPool.release(libraryPath);
}
}
/**
* 停止所有监控
*/
stopAll() {
for (const libraryId of this.watchers.keys()) {
this.unwatch(libraryId);
}
}
// 别名,保持兼容性
unwatchAll() {
this.stopAll();
}
/**
* 获取监控状态
*/
isWatching(libraryId) {
return this.watchers.has(libraryId);
}
/**
* 获取所有正在监控的库
*/
getWatchedLibraries() {
return Array.from(this.watchers.keys());
}
}
// 单例模式
const lightweightWatcher = new LightweightWatcher();
module.exports = lightweightWatcher;
@@ -0,0 +1,176 @@
/**
* Memory Diagnostics Tool
* 诊断内存泄漏和高内存使用
*/
const v8 = require('v8');
const fs = require('fs');
const path = require('path');
/**
* 生成堆快照
*/
function takeHeapSnapshot(filename) {
const snapshotPath = path.join(__dirname, '..', 'logs', filename);
// 确保目录存在
const dir = path.dirname(snapshotPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const snapshot = v8.writeHeapSnapshot(snapshotPath);
console.log(`[MemoryDiagnostics] Heap snapshot saved: ${snapshot}`);
return snapshot;
}
/**
* 获取堆统计信息
*/
function getHeapStatistics() {
const stats = v8.getHeapStatistics();
return {
totalHeapSize: (stats.total_heap_size / 1024 / 1024).toFixed(2) + ' MB',
totalHeapSizeExecutable: (stats.total_heap_size_executable / 1024 / 1024).toFixed(2) + ' MB',
totalPhysicalSize: (stats.total_physical_size / 1024 / 1024).toFixed(2) + ' MB',
totalAvailableSize: (stats.total_available_size / 1024 / 1024).toFixed(2) + ' MB',
usedHeapSize: (stats.used_heap_size / 1024 / 1024).toFixed(2) + ' MB',
heapSizeLimit: (stats.heap_size_limit / 1024 / 1024).toFixed(2) + ' MB',
mallocedMemory: (stats.malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
peakMallocedMemory: (stats.peak_malloced_memory / 1024 / 1024).toFixed(2) + ' MB',
doesZapGarbage: stats.does_zap_garbage
};
}
/**
* 打印堆统计信息
*/
function logHeapStatistics() {
const stats = getHeapStatistics();
console.log('\n[MemoryDiagnostics] Heap Statistics:');
Object.entries(stats).forEach(([key, value]) => {
console.log(` ${key}: ${value}`);
});
}
/**
* 强制垃圾回收并报告
*/
function forceGCAndReport() {
if (!global.gc) {
console.warn('[MemoryDiagnostics] GC not available. Run with --expose-gc');
return null;
}
const before = process.memoryUsage();
const beforeRSS = before.rss / 1024 / 1024;
const beforeHeap = before.heapUsed / 1024 / 1024;
console.log(`[MemoryDiagnostics] Before GC: RSS=${beforeRSS.toFixed(0)}MB, Heap=${beforeHeap.toFixed(0)}MB`);
// 执行多次 GC
for (let i = 0; i < 5; i++) {
global.gc();
}
const after = process.memoryUsage();
const afterRSS = after.rss / 1024 / 1024;
const afterHeap = after.heapUsed / 1024 / 1024;
const rssReclaimed = beforeRSS - afterRSS;
const heapReclaimed = beforeHeap - afterHeap;
console.log(`[MemoryDiagnostics] After GC: RSS=${afterRSS.toFixed(0)}MB, Heap=${afterHeap.toFixed(0)}MB`);
console.log(`[MemoryDiagnostics] Reclaimed: RSS=${rssReclaimed.toFixed(0)}MB, Heap=${heapReclaimed.toFixed(0)}MB`);
return {
before: { rss: beforeRSS, heap: beforeHeap },
after: { rss: afterRSS, heap: afterHeap },
reclaimed: { rss: rssReclaimed, heap: heapReclaimed }
};
}
/**
* 检测可能的内存泄漏
*/
function detectMemoryLeak() {
const usage = process.memoryUsage();
const rss = usage.rss / 1024 / 1024;
const heap = usage.heapUsed / 1024 / 1024;
const external = usage.external / 1024 / 1024;
const issues = [];
// RSS 过高
if (rss > 500) {
issues.push({
type: 'HIGH_RSS',
severity: 'critical',
message: `RSS is very high: ${rss.toFixed(0)}MB`,
suggestion: 'Check for native memory leaks, large buffers, or file handles'
});
}
// Heap 过高
if (heap > 200) {
issues.push({
type: 'HIGH_HEAP',
severity: 'warning',
message: `Heap usage is high: ${heap.toFixed(0)}MB`,
suggestion: 'Check for object retention, closures, or large data structures'
});
}
// External 过高
if (external > 100) {
issues.push({
type: 'HIGH_EXTERNAL',
severity: 'warning',
message: `External memory is high: ${external.toFixed(0)}MB`,
suggestion: 'Check for Buffer allocations, native addons, or C++ objects'
});
}
// RSS 远大于 Heap(可能是 native 内存泄漏)
if (rss > heap * 3) {
issues.push({
type: 'RSS_HEAP_MISMATCH',
severity: 'critical',
message: `RSS (${rss.toFixed(0)}MB) is much larger than Heap (${heap.toFixed(0)}MB)`,
suggestion: 'Likely native memory leak. Check SQLite, Sharp, or other native modules'
});
}
return issues;
}
/**
* 打印内存泄漏诊断
*/
function diagnoseMemoryLeak() {
console.log('\n[MemoryDiagnostics] Running memory leak detection...\n');
const issues = detectMemoryLeak();
if (issues.length === 0) {
console.log('✅ No obvious memory issues detected');
} else {
console.log(`⚠️ Found ${issues.length} potential issues:\n`);
issues.forEach((issue, index) => {
console.log(`${index + 1}. [${issue.severity.toUpperCase()}] ${issue.type}`);
console.log(` ${issue.message}`);
console.log(` 💡 ${issue.suggestion}\n`);
});
}
return issues;
}
module.exports = {
takeHeapSnapshot,
getHeapStatistics,
logHeapStatistics,
forceGCAndReport,
detectMemoryLeak,
diagnoseMemoryLeak
};
+195
View File
@@ -0,0 +1,195 @@
/**
* Memory Monitor
* Continuously monitors memory usage and triggers cleanup when thresholds are exceeded
*/
class MemoryMonitor {
constructor(options = {}) {
this.warningThreshold = options.warningThreshold || 150 * 1024 * 1024; // 150MB
this.dangerThreshold = options.dangerThreshold || 300 * 1024 * 1024; // 300MB
this.checkInterval = options.checkInterval || 2000; // 2 seconds
this.cleanupManager = options.cleanupManager;
this.devMode = options.devMode || process.env.NODE_ENV === 'development';
this.devLogInterval = options.devLogInterval || 30000; // 30 seconds
this.intervalId = null;
this.devLogIntervalId = null;
this.isRunning = false;
this.lastWarningTime = 0;
this.lastDangerTime = 0;
this.warningCooldown = 10000; // 10 seconds between warnings
}
/**
* Start monitoring memory usage
*/
start() {
if (this.isRunning) return;
console.log('📊 内存监控已启动');
this.isRunning = true;
// Start periodic memory checks
this.intervalId = setInterval(() => {
this.checkMemory();
}, this.checkInterval);
// Start development mode logging
if (this.devMode) {
this.devLogIntervalId = setInterval(() => {
const stats = this.getMemoryStats();
this.logMemoryStats(stats, 'DEV');
}, this.devLogInterval);
}
// Initial check
this.checkMemory();
}
/**
* Stop monitoring
*/
stop() {
if (!this.isRunning) return;
console.log('📊 内存监控已停止');
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
if (this.devLogIntervalId) {
clearInterval(this.devLogIntervalId);
this.devLogIntervalId = null;
}
this.isRunning = false;
}
/**
* Get current memory statistics
* @returns {Object} Memory statistics
*/
getMemoryStats() {
const usage = process.memoryUsage();
return {
heapUsed: usage.heapUsed,
heapTotal: usage.heapTotal,
rss: usage.rss,
external: usage.external,
arrayBuffers: usage.arrayBuffers,
timestamp: Date.now()
};
}
/**
* Check memory and trigger actions if thresholds exceeded
*/
checkMemory() {
const stats = this.getMemoryStats();
const heapUsedMB = stats.heapUsed / 1024 / 1024;
// Check danger threshold first
if (stats.heapUsed > this.dangerThreshold) {
this.handleDanger(stats);
}
// Check warning threshold
else if (stats.heapUsed > this.warningThreshold) {
this.handleWarning(stats);
}
return stats;
}
/**
* Handle warning threshold exceeded
*/
handleWarning(stats) {
const now = Date.now();
// Cooldown to avoid spam
if (now - this.lastWarningTime < this.warningCooldown) {
return;
}
this.lastWarningTime = now;
console.warn('⚠️ 内存使用偏高');
this.logMemoryStats(stats, 'WARNING');
}
/**
* Handle danger threshold exceeded
*/
handleDanger(stats) {
const now = Date.now();
// Cooldown to avoid spam (shorter for danger)
if (now - this.lastDangerTime < 5000) {
return;
}
this.lastDangerTime = now;
console.error('🚨 内存使用危险!');
this.logMemoryStats(stats, 'DANGER');
// Trigger emergency cleanup if cleanup manager is available
if (this.cleanupManager) {
console.log('🚨 触发紧急清理...');
try {
this.cleanupManager.executeEmergencyCleanup();
// 等待一下再检查
setTimeout(() => {
const afterStats = this.getMemoryStats();
const afterRSS = afterStats.rss / 1024 / 1024;
// 如果 RSS 仍然很高,强制更多 GC
if (afterRSS > 500) {
if (global.gc) {
for (let i = 0; i < 10; i++) {
global.gc();
}
}
}
}, 1000);
} catch (error) {
console.error('❌ 紧急清理失败:', error.message);
}
}
}
/**
* Log memory statistics with detailed breakdown
*/
logMemoryStats(stats, level = 'INFO') {
const heapUsedMB = (stats.heapUsed / 1024 / 1024).toFixed(2);
const heapTotalMB = (stats.heapTotal / 1024 / 1024).toFixed(2);
const rssMB = (stats.rss / 1024 / 1024).toFixed(2);
const externalMB = (stats.external / 1024 / 1024).toFixed(2);
const arrayBuffersMB = (stats.arrayBuffers / 1024 / 1024).toFixed(2);
console.log(`📊 内存状态 [${level}]:`);
console.log(` Heap: ${heapUsedMB}/${heapTotalMB} MB`);
console.log(` RSS: ${rssMB} MB`);
console.log(` External: ${externalMB} MB`);
}
/**
* Get monitoring status
*/
getStatus() {
return {
isRunning: this.isRunning,
warningThreshold: this.warningThreshold,
dangerThreshold: this.dangerThreshold,
checkInterval: this.checkInterval,
currentMemory: this.isRunning ? this.getMemoryStats() : null
};
}
}
module.exports = MemoryMonitor;
+63
View File
@@ -0,0 +1,63 @@
/**
* Memory Statistics Utility
* 显示详细的内存使用统计
*/
function formatBytes(bytes) {
return (bytes / 1024 / 1024).toFixed(2) + ' MB';
}
function getMemoryStats() {
const usage = process.memoryUsage();
return {
heapUsed: usage.heapUsed,
heapTotal: usage.heapTotal,
rss: usage.rss,
external: usage.external,
arrayBuffers: usage.arrayBuffers,
heapUsedMB: formatBytes(usage.heapUsed),
heapTotalMB: formatBytes(usage.heapTotal),
rssMB: formatBytes(usage.rss),
externalMB: formatBytes(usage.external),
arrayBuffersMB: formatBytes(usage.arrayBuffers)
};
}
function logMemoryStats(label = 'Memory') {
const stats = getMemoryStats();
console.log(`\n[${label}] Memory Statistics:`);
console.log(` RSS (总内存): ${stats.rssMB}`);
console.log(` Heap Used (堆使用): ${stats.heapUsedMB}`);
console.log(` Heap Total (堆总量):${stats.heapTotalMB}`);
console.log(` External (外部): ${stats.externalMB}`);
console.log(` Array Buffers: ${stats.arrayBuffersMB}`);
}
function getMemoryPressure() {
const usage = process.memoryUsage();
const heapUsedMB = usage.heapUsed / 1024 / 1024;
const rssMB = usage.rss / 1024 / 1024;
let pressure = 'low';
if (heapUsedMB > 200 || rssMB > 500) {
pressure = 'critical';
} else if (heapUsedMB > 100 || rssMB > 300) {
pressure = 'high';
} else if (heapUsedMB > 50 || rssMB > 150) {
pressure = 'medium';
}
return {
level: pressure,
heapUsedMB,
rssMB
};
}
module.exports = {
getMemoryStats,
logMemoryStats,
getMemoryPressure,
formatBytes
};
@@ -0,0 +1,148 @@
/**
* 缩略图迁移工具
* 将旧结构的缩略图迁移到新的分片结构
*
* 旧结构:.flypic/thumbnails/hash.webp
* 新结构:.flypic/thumbnails/ab/hash.webp (分片存储)
*/
const fs = require('fs');
const path = require('path');
/**
* 迁移单个素材库的缩略图
* @param {string} libraryPath - 素材库路径
* @returns {Object} 迁移结果统计
*/
async function migrateThumbnails(libraryPath) {
const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
// 检查目录是否存在
if (!fs.existsSync(thumbnailsDir)) {
return { migrated: 0, skipped: 0, errors: 0, message: 'Thumbnails directory not found' };
}
const stats = {
migrated: 0,
skipped: 0,
errors: 0
};
try {
const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
for (const entry of entries) {
// 跳过已经是目录的(已经是新结构)
if (entry.isDirectory()) {
continue;
}
// 只处理 .webp 文件
if (!entry.name.endsWith('.webp')) {
continue;
}
try {
const oldPath = path.join(thumbnailsDir, entry.name);
// 提取 hash(去掉扩展名)
const hash = entry.name.replace('.webp', '');
// 计算分片目录(使用前2个字符)
const shard = hash.slice(0, 2);
const shardDir = path.join(thumbnailsDir, shard);
const newPath = path.join(shardDir, entry.name);
// 如果新路径已存在,跳过
if (fs.existsSync(newPath)) {
stats.skipped++;
continue;
}
// 创建分片目录
if (!fs.existsSync(shardDir)) {
fs.mkdirSync(shardDir, { recursive: true });
}
// 移动文件
fs.renameSync(oldPath, newPath);
stats.migrated++;
console.log(`[Migrate] Moved: ${entry.name} -> ${shard}/${entry.name}`);
} catch (error) {
console.error(`[Migrate] Error migrating ${entry.name}:`, error.message);
stats.errors++;
}
}
console.log(`[Migrate] Complete for ${libraryPath}:`, stats);
return stats;
} catch (error) {
console.error(`[Migrate] Error reading thumbnails directory:`, error);
return { ...stats, message: error.message };
}
}
/**
* 检查是否需要迁移
* @param {string} libraryPath - 素材库路径
* @returns {boolean} 是否需要迁移
*/
function needsMigration(libraryPath) {
const thumbnailsDir = path.join(libraryPath, '.flypic', 'thumbnails');
if (!fs.existsSync(thumbnailsDir)) {
return false;
}
try {
const entries = fs.readdirSync(thumbnailsDir, { withFileTypes: true });
// 检查是否有直接在 thumbnails 目录下的 .webp 文件
for (const entry of entries) {
if (entry.isFile() && entry.name.endsWith('.webp')) {
return true;
}
}
return false;
} catch (error) {
console.error(`[Migrate] Error checking migration need:`, error);
return false;
}
}
/**
* 批量迁移多个素材库
* @param {Array} libraries - 素材库列表
* @returns {Object} 总体迁移统计
*/
async function migrateAllLibraries(libraries) {
const totalStats = {
migrated: 0,
skipped: 0,
errors: 0,
librariesProcessed: 0
};
for (const library of libraries) {
if (needsMigration(library.path)) {
console.log(`[Migrate] Processing library: ${library.name}`);
const stats = await migrateThumbnails(library.path);
totalStats.migrated += stats.migrated;
totalStats.skipped += stats.skipped;
totalStats.errors += stats.errors;
totalStats.librariesProcessed++;
}
}
console.log(`[Migrate] Total stats:`, totalStats);
return totalStats;
}
module.exports = {
migrateThumbnails,
needsMigration,
migrateAllLibraries
};
+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;
+114 -109
View File
@@ -35,6 +35,13 @@ function ensureFolderChain(db, folderPath) {
visited.add(current);
const parent = path.posix.dirname(current);
const name = current.split('/').pop();
// 安全检查:确保 db 对象有 getFolderByPath 方法
if (typeof db.getFolderByPath !== 'function') {
console.error('❌ db.getFolderByPath 不是函数');
return;
}
const existing = db.getFolderByPath(current);
if (!existing) {
db.insertFolder({
@@ -108,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);
}
}
@@ -129,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);
}
}
@@ -150,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);
}
}
@@ -165,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);
}
}
@@ -175,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;
}
}
@@ -302,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 };
}
}
@@ -333,20 +340,15 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume
// 根据 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);
@@ -361,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 = {
@@ -376,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) => {
@@ -389,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;
@@ -402,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) {
@@ -474,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();
@@ -492,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);
}
@@ -517,25 +516,26 @@ async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgr
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, '/')));
// Get database files (只获取路径,不加载完整数据)
const dbPaths = new Set();
const stmt = db.db.prepare('SELECT path FROM images');
for (const row of stmt.iterate()) {
dbPaths.add((row.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`);
console.log(`🔄 同步: +${toAdd.length} 检查${toCheck.length} -${toDelete.length}`);
// 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题
if (toDelete.length > 0 && dbImages.length > 0) {
const deleteRatio = toDelete.length / dbImages.length;
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}/${dbImages.length} (${(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 = [];
}
}
@@ -575,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) {
@@ -585,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);
@@ -609,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)
@@ -632,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,
@@ -645,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;
}
}
@@ -662,19 +663,23 @@ async function quickSync(libraryPath, db) {
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 dbPaths = new Set();
const stmt = db.db.prepare('SELECT path FROM images');
for (const row of stmt.iterate()) {
dbPaths.add((row.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;
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} 个文件`);
console.warn(`⚠️ 跳过删除 ${toDelete.length} 个文件`);
toDelete = [];
}
}
@@ -690,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);
}
}
@@ -706,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 };
+30 -36
View File
@@ -3,6 +3,16 @@ const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
// 配置 Sharp 内存限制(防止内存泄漏)
sharp.cache({
memory: 50, // 最大缓存 50MB(默认 50MB)
files: 0, // 禁用文件缓存
items: 20 // 最多缓存 20 个操作
});
// 设置并发限制
sharp.concurrency(1); // 一次只处理 1 张图片
// 支持的文件格式(确定可以生成缩略图的)
const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg'];
@@ -81,10 +91,15 @@ function isImageFile(filename) {
* Calculate file hash for change detection
*/
function calculateFileHash(filePath) {
const fileBuffer = fs.readFileSync(filePath);
let fileBuffer = fs.readFileSync(filePath);
const hashSum = crypto.createHash('md5');
hashSum.update(fileBuffer);
return hashSum.digest('hex');
const hash = hashSum.digest('hex');
// 显式释放 Buffer
fileBuffer = null;
return hash;
}
/**
@@ -157,7 +172,7 @@ function getThumbnailConfig(originalWidth, originalHeight, targetHeight = 200) {
async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
try {
// 先读取文件到 Buffer,避免 Sharp 锁定文件句柄
const inputBuffer = fs.readFileSync(inputPath);
let inputBuffer = fs.readFileSync(inputPath);
// Get image metadata from buffer
const metadata = await sharp(inputBuffer).metadata();
@@ -219,17 +234,18 @@ async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
})
.toFile(outputPath);
// 显式释放 Buffer 内存
inputBuffer = null;
// 强制 GC(如果可用)
if (global.gc && Math.random() < 0.1) { // 10% 概率执行 GC
global.gc();
}
// 获取文件大小
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,
@@ -291,7 +307,7 @@ async function getImageMetadata(imagePath) {
/**
* Generate thumbnail for a file (image/video/document)
* 使用 480px 高度
* 使用 480px 高度(与 Billfish 一致)
*/
async function generateImageThumbnails(imagePath, libraryPath) {
const flypicDir = path.join(libraryPath, '.flypic');
@@ -299,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
@@ -317,36 +331,32 @@ 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, '/');
return {
thumbnail_path: path.relative(flypicDir, out480),
thumbnail_path: thumbnailPath,
thumbnail_size: thumbnailResult.size,
width: thumbnailResult.width,
height: thumbnailResult.height,
@@ -399,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;
@@ -449,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,
@@ -496,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;
@@ -516,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,
@@ -617,18 +623,6 @@ async function generatePlaceholderThumbnail(outputPath, type, label) {
};
}
/**
* 获取文件类型对应的图标(Unicode)
*/
function getIconForType(type) {
const icons = {
video: '🎬',
document: '📄',
special: '🎨'
};
return icons[type] || '📁';
}
module.exports = {
isImageFile,
getFileType,
+44 -52
View File
@@ -57,7 +57,6 @@ function App() {
? 'http://localhost:15002' // 开发模式:后端端口
: window.location.origin; // 生产模式:同源
console.log('🔌 Connecting to Socket.IO:', socketUrl);
const socket = io(socketUrl, {
transports: ['websocket', 'polling'], // 优先使用 websocket
reconnection: true,
@@ -66,19 +65,34 @@ function App() {
});
socket.on('connect', () => {
console.log('✅ Socket.IO connected:', socket.id);
});
socket.on('disconnect', () => {
console.log('❌ Socket.IO disconnected');
// 连接后检查扫描状态
const checkScanStatus = (retries = 5, delay = 1000) => {
const currentLibId = useLibraryStore.getState().currentLibraryId;
if (!currentLibId) return;
scanAPI.getStatus(currentLibId).then(res => {
const scanStatus = res.data || res;
if (scanStatus && scanStatus.status === 'scanning' && scanStatus.progress) {
setScanProgress(scanStatus.progress);
} else if (retries > 0) {
setTimeout(() => checkScanStatus(retries - 1, delay), delay);
}
}).catch((err) => {
if (retries > 0) {
setTimeout(() => checkScanStatus(retries - 1, delay), delay);
}
});
};
checkScanStatus(5, 1000);
});
socket.on('connect_error', (error) => {
console.error('❌ Socket.IO connection error:', error);
console.error('❌ 连接错误:', error.message);
});
socket.on('scanProgress', (progress) => {
// 只显示当前素材库的进度
const currentLibId = useLibraryStore.getState().currentLibraryId;
if (progress.libraryId === currentLibId) {
setScanProgress(progress);
@@ -86,14 +100,9 @@ function App() {
});
socket.on('scanComplete', ({ libraryId, results }) => {
console.log('📊 Scan complete:', { libraryId, results });
// Only reload if this is the current library
const currentLibId = useLibraryStore.getState().currentLibraryId;
console.log('🔍 Current library:', currentLibId, 'Scan library:', libraryId, 'Match:', libraryId === currentLibId);
if (libraryId === currentLibId) {
console.log('🔄 Reloading folders and images...');
// 获取当前的筛选条件
const imageState = useImageStore.getState();
@@ -119,33 +128,22 @@ function App() {
]).then(([foldersRes, imagesRes, countRes]) => {
useImageStore.getState().setFolders(foldersRes.folders);
useImageStore.getState().setImages(imagesRes.images);
// 更新图片总数
useImageStore.getState().setTotalImageCount(countRes.count);
console.log(`✅ Data reloaded, total: ${countRes.count}`);
}).catch(err => {
console.error('❌ Error reloading data:', err);
console.error('❌ 加载数据失败:', err.message);
}).finally(() => {
// 最后清除进度
setScanProgress(null);
console.log('✅ Scan progress cleared');
});
} else {
console.log('⚠️ Library mismatch, skipping reload');
// 不是当前素材库,直接清除进度
setScanProgress(null);
}
});
socket.on('scanError', ({ libraryId, error }) => {
setScanProgress(null);
console.error('Scan error:', error);
console.error('❌ 扫描错误:', error);
});
socket.on('scanPaused', ({ libraryId, results }) => {
console.log('⏸️ Scan paused:', { libraryId, results });
// 保持进度显示,但标记为可以继续
});
// Socket 监听已就绪后,再加载库并可能触发同步
loadLibraries();
@@ -160,18 +158,19 @@ function App() {
const loadLibraries = async () => {
try {
const response = await libraryAPI.getAll();
const { libraries, currentLibraryId: libId, theme: configTheme, preferences } = response;
const data = response.data || response;
// 立即更新基础状态
setLibraries(libraries);
setCurrentLibrary(libId);
setLibraries(data.libraries || []);
setCurrentLibrary(data.currentLibraryId);
const libId = data.currentLibraryId;
// 加载主题和偏好设置
if (configTheme) {
useUIStore.getState().setTheme(configTheme);
if (data.theme) {
useUIStore.getState().setTheme(data.theme);
}
if (preferences) {
const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = preferences;
if (data.preferences) {
const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = data.preferences;
if (thumbnailHeight) useUIStore.getState().setThumbnailHeight(thumbnailHeight);
if (leftPanelWidth) setLeftWidth(leftPanelWidth);
if (rightPanelWidth) setRightWidth(rightPanelWidth);
@@ -191,27 +190,20 @@ function App() {
const countRes = await imageAPI.getCount(libId);
useImageStore.getState().setTotalImageCount(countRes.count);
} catch (e) {
console.error('Failed to get image count:', e);
console.error('❌ 获取图片总数失败:', e.message);
}
console.log('📂 数据加载完成,文件监控器将自动检测变化');
// 后台检查扫描状态(不阻塞主流程)
// 后台检查当前素材库的扫描状态
scanAPI.getStatus(libId).then(scanStatus => {
const { status, progress, pendingCount } = scanStatus;
if (status === 'scanning' || status === 'paused') {
console.log(`🔄 恢复扫描状态: ${status}, 进度: ${progress?.percent || 0}%`);
setScanProgress({
...progress,
canStop: true,
isPaused: status === 'paused',
pendingCount: pendingCount
});
const { status, progress } = scanStatus;
if (status === 'scanning') {
setScanProgress(progress);
}
}).catch(() => { }); // 忽略状态检查错误
}).catch(() => { });
}
} catch (error) {
console.error('Error loading libraries:', error);
console.error('❌ 加载素材库失败:', error.message);
}
};
@@ -228,7 +220,7 @@ function App() {
const response = await imageAPI.search(libraryId, params);
useImageStore.getState().setImages(response.images);
} catch (error) {
console.error('Error loading images:', error);
console.error('❌ 加载图片失败:', error.message);
}
};
@@ -237,7 +229,7 @@ function App() {
const response = await imageAPI.getFolders(libraryId);
useImageStore.getState().setFolders(response.folders);
} catch (error) {
console.error('Error loading folders:', error);
console.error('❌ 加载文件夹失败:', error.message);
}
};
@@ -249,7 +241,7 @@ function App() {
rightPanelWidth: right
});
} catch (error) {
console.error('Error saving panel widths:', error);
console.error('❌ 保存面板宽度失败:', error.message);
}
};
+1 -27
View File
@@ -1,47 +1,21 @@
/**
* 扫描 API
* 扫描 API(简化版)
*/
import { api } from '../client';
/**
* 全量扫描
*/
export async function fullScan(libraryId, wait = false) {
return api.post('/scan/full', { libraryId, wait });
}
/**
* 增量同步
*/
export async function sync(libraryId, wait = false) {
return api.post('/scan/sync', { libraryId, wait });
}
/**
* 停止扫描
*/
export async function stop(libraryId) {
return api.post('/scan/stop', { libraryId });
}
/**
* 继续扫描
*/
export async function resume(libraryId) {
return api.post('/scan/resume', { libraryId });
}
/**
* 获取扫描状态
*/
export async function getStatus(libraryId) {
return api.get(`/scan/status/${libraryId}`);
}
/**
* 修复文件夹路径
*/
export async function fixFolders(libraryId) {
return api.post('/scan/fix-folders', { libraryId });
}
+11 -74
View File
@@ -1,10 +1,9 @@
import { useEffect, useRef, useState, useCallback } from 'react';
import { Pause, Play } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
import { useScanStore } from '../stores/useScanStore';
import { imageAPI, scanAPI } from '../api';
import { imageAPI } from '../api';
import { onUserActionStart, onUserActionEnd } from '../services/imageLoadService';
import requestManager, { RequestType } from '../services/requestManager';
import imageCache from '../utils/imageCache';
@@ -21,9 +20,6 @@ function MainContent() {
const currentRequestContextRef = useRef(null);
// 文件夹切换防抖
const debounceTimerRef = useRef(null);
// 扫描控制
const [scanPaused, setScanPaused] = useState(false);
const [isStoppingOrResuming, setIsStoppingOrResuming] = useState(false);
// 计算预估剩余时间
const getEstimatedTime = () => {
@@ -116,8 +112,6 @@ function MainContent() {
hasMore: hasMore || false,
});
console.log(`[MainContent] Loaded page: +${images.length}, total: ${(isInitialLoad ? images.length : imageLoadingState.loadedCount + images.length)}/${total}`);
// 如果还有更多数据,恢复空闲加载
if (hasMore) {
onUserActionEnd(hasMore);
@@ -187,83 +181,26 @@ function MainContent() {
};
}, [cancelCurrentRequest]);
// 停止扫描
const handleStopScan = async () => {
if (!currentLibraryId || isStoppingOrResuming) return;
setIsStoppingOrResuming(true);
try {
await scanAPI.stop(currentLibraryId);
setScanPaused(true);
} catch (error) {
console.error('Error stopping scan:', error);
} finally {
setIsStoppingOrResuming(false);
}
};
// 继续扫描
const handleResumeScan = async () => {
if (!currentLibraryId || isStoppingOrResuming) return;
setIsStoppingOrResuming(true);
try {
if (scanProgress?.needsRescan) {
await scanAPI.sync(currentLibraryId);
} else {
await scanAPI.resume(currentLibraryId);
}
setScanPaused(false);
} catch (error) {
console.error('Error resuming scan:', error);
} finally {
setIsStoppingOrResuming(false);
}
};
// 同步扫描暂停状态
useEffect(() => {
if (!scanProgress) {
setScanPaused(false);
} else if (scanProgress.isPaused) {
setScanPaused(true);
} else if (scanProgress.percent === 100) {
setScanPaused(false);
}
}, [scanProgress]);
return (
<div className="flex flex-col h-full bg-gray-50 dark:bg-gray-900">
{/* Scan Progress */}
{/* Scan Progress - 简化版,无暂停按钮 */}
{scanProgress && (
<div className={`p-4 border-b ${scanPaused
? 'bg-yellow-50 dark:bg-yellow-900 border-yellow-200 dark:border-yellow-700'
: 'bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700'
}`}>
<div className="p-4 border-b bg-blue-50 dark:bg-blue-900 border-blue-200 dark:border-blue-700">
<div className="flex items-center justify-between mb-2">
<div className={`text-sm font-medium ${scanPaused ? 'text-yellow-700 dark:text-yellow-300' : 'text-blue-700 dark:text-blue-300'}`}>
{scanPaused ? '扫描已暂停' : scanProgress?.status === 'preparing' ? '正在准备扫描...' : '正在扫描素材库,期间建议勿操作,否则会影响扫描速度'}
</div>
<div className="flex items-center gap-2">
<span className={`text-sm ${scanPaused ? 'text-yellow-600' : 'text-blue-600'}`}>
{scanProgress?.percent || 0}%
</span>
{(scanProgress?.canStop || scanPaused) && (
<button
onClick={scanPaused ? handleResumeScan : handleStopScan}
disabled={isStoppingOrResuming}
className={`p-1.5 rounded-md ${scanPaused ? 'bg-green-500 hover:bg-green-600' : 'bg-yellow-500 hover:bg-yellow-600'} text-white`}
>
{scanPaused ? <Play className="w-4 h-4" /> : <Pause className="w-4 h-4" />}
</button>
)}
<div className="text-sm font-medium text-blue-700 dark:text-blue-300">
{scanProgress?.status === 'preparing' ? '正在准备扫描...' : '正在扫描素材库...'}
</div>
<span className="text-sm text-blue-600 dark:text-blue-400">
{scanProgress?.percent || 0}%
</span>
</div>
<div className={`w-full rounded-full h-2 mb-2 ${scanPaused ? 'bg-yellow-200' : 'bg-blue-200'}`}>
<div className="w-full rounded-full h-2 mb-2 bg-blue-200 dark:bg-blue-800">
<div
className={`h-2 rounded-full transition-all ${scanPaused ? 'bg-yellow-500' : 'bg-blue-500'}`}
className="h-2 rounded-full transition-all bg-blue-500"
style={{ width: `${scanProgress?.percent || 0}%` }}
/>
</div>
<div className={`text-xs ${scanPaused ? 'text-yellow-600' : 'text-blue-600'}`}>
<div className="text-xs text-blue-600 dark:text-blue-400">
已处理 {scanProgress?.current || 0} / {scanProgress?.total || 0} 张图片
{getEstimatedTime() && ` · ${getEstimatedTime()}`}
</div>
+58 -31
View File
@@ -7,11 +7,11 @@ import { libraryAPI, scanAPI, imageAPI } from '../api';
import requestManager from '../services/requestManager';
import { onUserActionStart } from '../services/imageLoadService';
// 检查素材库是否有暂停的扫描
const checkPausedScan = async (libraryId) => {
// 检查素材库扫描状态
const checkScanStatus = async (libraryId) => {
try {
const response = await scanAPI.getStatus(libraryId);
return response.data;
return response.data || response;
} catch (error) {
return null;
}
@@ -20,6 +20,7 @@ const checkPausedScan = async (libraryId) => {
function Sidebar() {
const { libraries, currentLibraryId, setCurrentLibrary, addLibrary, removeLibrary } = useLibraryStore();
const { folders, selectedFolder, totalImageCount, setSelectedFolder } = useImageStore();
const { isScanning } = useScanStore();
const [showAddLibrary, setShowAddLibrary] = useState(false);
const [newLibraryName, setNewLibraryName] = useState('');
@@ -54,6 +55,12 @@ function Sidebar() {
}, []);
const handleAddLibrary = async () => {
// 扫描期间禁止添加素材库
if (isScanning()) {
alert('扫描进行中,请稍后再试或暂停扫描');
return;
}
if (!newLibraryName.trim()) {
alert('请输入素材库名称');
return;
@@ -137,7 +144,29 @@ function Sidebar() {
console.log('✅ 扫描已启动,请等待进度显示...');
} catch (error) {
console.error('❌ Error adding library:', error);
alert('添加素材库失败: ' + error.message);
// 提取错误信息
let errorMessage = error.message || '未知错误';
// 如果是后端返回的错误响应
if (error.response?.data?.message) {
errorMessage = error.response.data.message;
}
// 特殊处理权限错误
if (errorMessage.includes('无法访问') || errorMessage.includes('权限') || errorMessage.includes('数据共享')) {
alert(
'⚠️ 文件夹权限不足\n\n' +
errorMessage + '\n\n' +
'操作步骤:\n' +
'1. 应用中心找到 FlyPic 应用\n' +
'2. 点击 应用设置\n' +
'3. 将该文件夹添加到 FlyPic 应用的读写权限'
);
} else {
alert('添加素材库失败: ' + errorMessage);
}
useScanStore.getState().setScanProgress(null);
setIsAdding(false);
}
@@ -145,6 +174,12 @@ function Sidebar() {
const handleLibraryClick = async (libraryId) => {
if (libraryId === currentLibraryId) return;
// 扫描期间禁止切换素材库
if (isScanning()) {
alert('扫描进行中,请稍后再试或暂停扫描');
return;
}
setIsSwitching(true);
try {
@@ -178,31 +213,12 @@ function Sidebar() {
useImageStore.getState().setTotalImageCount(countRes.count);
setCurrentLibrary(libraryId); // 最后才更新 currentLibraryId
// 7. 后台检查新素材库是否有暂停的扫描(不阻塞主流程)
checkPausedScan(libraryId).then(scanStatus => {
if (scanStatus && scanStatus.status === 'paused') {
if (scanStatus.needsRescan) {
useScanStore.getState().setScanProgress({
...scanStatus.progress,
libraryId,
canStop: true,
isPaused: true,
pendingCount: scanStatus.progress?.total - scanStatus.progress?.current || 0,
needsRescan: true
});
console.log(`⏸️ 发现中断的扫描,需要继续完成`);
} else if (scanStatus.pendingCount > 0) {
useScanStore.getState().setScanProgress({
...scanStatus.progress,
libraryId,
canStop: true,
isPaused: true,
pendingCount: scanStatus.pendingCount
});
console.log(`⏸️ 发现暂停的扫描,待处理: ${scanStatus.pendingCount} 张`);
}
// 7. 检查新素材库是否正在扫描
checkScanStatus(libraryId).then(scanStatus => {
if (scanStatus && scanStatus.status === 'scanning') {
useScanStore.getState().setScanProgress(scanStatus.progress);
}
}).catch(() => { }); // 忽略状态检查错误
}).catch(() => { });
} catch (error) {
console.error('Error setting current library:', error);
alert('切换素材库失败: ' + error.message);
@@ -215,6 +231,12 @@ function Sidebar() {
const handleDeleteLibrary = async () => {
if (!currentLibraryId) return;
// 扫描期间禁止删除素材库
if (isScanning()) {
alert('扫描进行中,请稍后再试或暂停扫描');
return;
}
const currentLib = libraries.find(lib => lib.id === currentLibraryId);
if (!currentLib) return;
@@ -453,12 +475,16 @@ function Sidebar() {
onChange={(e) => {
const value = e.target.value;
if (value === '__add__') {
if (isScanning()) {
alert('扫描进行中,请稍后再试或暂停扫描');
return;
}
setShowAddLibrary(true);
} else if (value) {
handleLibraryClick(value);
}
}}
disabled={isSwitching}
disabled={isSwitching || isScanning()}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
style={{ paddingRight: '2rem' }}
>
@@ -480,8 +506,9 @@ function Sidebar() {
{currentLibraryId && libraries.length > 0 && (
<button
onClick={handleDeleteLibrary}
className="px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors"
title="删除当前素材库"
disabled={isScanning()}
className="px-3 py-2 border border-red-300 dark:border-red-600 rounded-lg hover:bg-red-50 dark:hover:bg-red-900 text-red-600 dark:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title={isScanning() ? "扫描进行中,无法删除" : "删除当前素材库"}
>
<Trash2 className="w-4 h-4" />
</button>
+8 -15
View File
@@ -1,45 +1,38 @@
/**
* 扫描状态管理
* 扫描状态管理(简化版)
*/
import { create } from 'zustand';
export const useScanStore = create((set, get) => ({
// 扫描进度
scanProgress: null,
scanStartTime: null,
// 设置扫描进度
setScanProgress: (progress) => set((state) => {
// 第一次收到进度时记录开始时间
if (progress && !state.scanStartTime && progress.current > 0) {
return { scanProgress: progress, scanStartTime: Date.now() };
}
// 扫描结束时清空开始时间
if (!progress) {
return { scanProgress: null, scanStartTime: null };
}
return { scanProgress: progress };
}),
// 清除扫描进度
clearScanProgress: () => set({ scanProgress: null, scanStartTime: null }),
// 获取预估剩余时间
getEstimatedTimeLeft: () => {
const { scanProgress, scanStartTime } = get();
if (!scanProgress || !scanStartTime || scanProgress.current === 0) {
return null;
}
const elapsed = Date.now() - scanStartTime;
const rate = scanProgress.current / elapsed; // 图片/毫秒
const rate = scanProgress.current / elapsed;
const remaining = scanProgress.total - scanProgress.current;
const estimatedMs = remaining / rate;
return Math.ceil(estimatedMs / 1000); // 返回秒数
return Math.ceil((remaining / rate) / 1000);
},
isScanning: () => {
const { scanProgress } = get();
return scanProgress && scanProgress.status !== 'preparing';
}
}));
+1 -4
View File
@@ -109,8 +109,6 @@ class ImageCache {
this.cache.clear();
this.accessOrder = [];
console.log('[ImageCache] Cache cleared');
}
/**
@@ -124,7 +122,6 @@ class ImageCache {
// First item in access order is least recently used
const lruImageId = this.accessOrder[0];
console.log(`[ImageCache] Evicting LRU: ${lruImageId}`);
this.remove(lruImageId);
this.stats.evictionCount++;
}
@@ -195,7 +192,7 @@ class ImageCache {
*/
logStats() {
const stats = this.getStats();
console.log('[ImageCache] Statistics:', stats);
// 仅在需要时输出统计信息
}
}
-172
View File
@@ -1,172 +0,0 @@
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, '..');
const backendDir = path.join(root, 'backend');
const frontendDir = path.join(root, 'frontend');
const packDir = path.join(root, 'flypic');
const packServerDir = path.join(packDir, 'app', 'server');
function run(cmd, options = {}) {
console.log(`> ${cmd}`);
execSync(cmd, { stdio: 'inherit', cwd: root, ...options });
}
console.log('=== 使用 Docker 构建 FlyPic 飞牛应用包 ===\n');
// 1. 构建前端
console.log('1. 构建前端...');
run(`cd ${frontendDir} && npm run build`);
// 2. 清理并创建服务器目录
console.log('\n2. 准备服务器目录...');
if (fs.existsSync(packServerDir)) {
fs.rmSync(packServerDir, { recursive: true });
}
fs.mkdirSync(packServerDir, { recursive: true });
// 3. 复制后端文件
console.log('\n3. 复制后端文件...');
const backendFiles = ['server.js', 'package.json', 'package-lock.json'];
backendFiles.forEach(file => {
const src = path.join(backendDir, file);
const dest = path.join(packServerDir, file);
if (fs.existsSync(src)) {
fs.copyFileSync(src, dest);
console.log(` 复制: ${file}`);
}
});
const backendDirs = ['routes', 'database', 'utils'];
backendDirs.forEach(dir => {
const src = path.join(backendDir, dir);
const dest = path.join(packServerDir, dir);
if (fs.existsSync(src)) {
fs.cpSync(src, dest, { recursive: true });
console.log(` 复制目录: ${dir}/`);
}
});
// 4. 复制前端构建产物
console.log('\n4. 复制前端构建产物...');
const frontendDist = path.join(frontendDir, 'dist');
const serverPublic = path.join(packServerDir, 'public');
if (fs.existsSync(frontendDist)) {
fs.cpSync(frontendDist, serverPublic, { recursive: true });
console.log(' 复制: frontend/dist -> app/server/public');
}
// 5. 使用 Docker 安装 Linux 版本的依赖(完整编译)
console.log('\n5. 使用 Docker 安装 Linux 依赖(完整编译原生模块)...');
console.log(' 这将确保上传到飞牛后可以直接使用,无需额外操作\n');
// 转换 Windows 路径为 WSL 路径(Docker Desktop for Windows 需要)
const convertToWSLPath = (winPath) => {
// C:\Users\... -> /c/Users/...
return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (match, drive) => `/${drive.toLowerCase()}`);
};
const wslPackServerDir = convertToWSLPath(packServerDir);
// 完整安装方案:安装构建工具 + 完整编译所有原生模块
const dockerCmd = `docker run --rm -v "${wslPackServerDir}:/app" -w /app node:22-slim bash -c "apt-get update -qq && apt-get install -y -qq build-essential python3 && npm config set registry https://registry.npmmirror.com && npm install --production && du -sh node_modules/"`;
console.log(' 开始构建...');
console.log(` Docker 挂载路径: ${wslPackServerDir}`);
console.log(' 提示:首次构建需要下载并编译,可能需要 5-10 分钟\n');
try {
run(dockerCmd);
console.log('\n ✅ Linux 依赖完整编译成功!');
console.log(' ✅ node_modules 已安装(约 57 MB)');
console.log(' ✅ 包含 Sharp 和 better-sqlite3 的 Linux 版本');
console.log(' ✅ 上传到飞牛后可直接使用,无需额外操作');
console.log('\n 注意:如果看到权限错误,可以忽略,这是 Windows + Docker 的正常现象');
} catch (error) {
console.error('\n ❌ Docker 编译失败');
console.error(' 错误信息:', error.message);
console.log('\n 可能的原因:');
console.log(' 1. Docker 未运行或未正确安装');
console.log(' 2. 网络连接问题(无法下载依赖)');
console.log(' 3. 磁盘空间不足');
console.log('\n 解决方案:');
console.log(' 1. 确保 Docker Desktop 正在运行');
console.log(' 2. 在 Docker Desktop 设置中启用文件共享');
console.log(' 3. 检查网络连接');
console.log(' 4. 或使用方法二:在飞牛 fnOS 上手动安装依赖');
process.exit(1);
}
// 6. 创建UI配置
console.log('\n6. 创建UI配置...');
const uiConfigDir = path.join(packDir, 'app', 'ui');
if (!fs.existsSync(uiConfigDir)) {
fs.mkdirSync(uiConfigDir, { recursive: true });
}
const uiConfig = {
".url": {
"flypic.Application": {
"title": "FlyPic",
"icon": "images/icon-{0}.png",
"type": "url",
"protocol": "http",
"port": "15002",
"allUsers": true,
"control": {
"portPerm": "editable"
}
}
}
};
fs.writeFileSync(
path.join(uiConfigDir, 'config'),
JSON.stringify(uiConfig, null, 2)
);
console.log(' 创建: app/ui/config');
// 7. 创建其他必要的脚本
console.log('\n7. 创建生命周期脚本...');
const scripts = [
'uninstall_init', 'uninstall_callback',
'upgrade_init', 'upgrade_callback',
'config_init', 'config_callback'
];
scripts.forEach(script => {
const scriptPath = path.join(packDir, 'cmd', script);
if (!fs.existsSync(scriptPath)) {
fs.writeFileSync(scriptPath, '#!/bin/bash\nexit 0\n');
console.log(` 创建: cmd/${script}`);
}
});
// 8. 确保所有脚本使用 LF 换行符
console.log('\n8. 修复脚本换行符...');
const cmdDir = path.join(packDir, 'cmd');
if (fs.existsSync(cmdDir)) {
const allScripts = fs.readdirSync(cmdDir);
allScripts.forEach(script => {
const scriptPath = path.join(cmdDir, script);
if (fs.statSync(scriptPath).isFile()) {
let content = fs.readFileSync(scriptPath, 'utf8');
content = content.replace(/\r\n/g, '\n');
fs.writeFileSync(scriptPath, content, { encoding: 'utf8' });
console.log(` 修复: cmd/${script}`);
}
});
}
console.log('\n=== 构建完成 ===');
console.log(`\n打包目录: ${packDir}`);
console.log('\n✅ 已包含完整编译的 Linux 版本 node_modules');
console.log('✅ 包含 Sharp (图片处理) 和 better-sqlite3 (数据库) 的原生模块');
console.log('✅ 上传到飞牛后可直接使用,无需任何额外操作');
console.log('\n下一步:');
console.log('1. 上传 flypic 文件夹到飞牛 fnOS');
console.log('2. 在飞牛 fnOS 上使用 fnpack build 打包');
console.log(' cd flypic && fnpack build');
console.log('3. 安装生成的 .fpk 文件即可使用');
-136
View File
@@ -1,136 +0,0 @@
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, '..');
const backendDir = path.join(root, 'backend');
const frontendDir = path.join(root, 'frontend');
const packDir = path.join(root, 'flypic');
const packServerDir = path.join(packDir, 'app', 'server');
function run(cmd) {
console.log(`> ${cmd}`);
execSync(cmd, { stdio: 'inherit', cwd: root });
}
console.log('=== 构建 FlyPic 飞牛应用包 ===\n');
// 1. 构建前端
console.log('1. 构建前端...');
run(`cd ${frontendDir} && npm run build`);
// 2. 清理并创建服务器目录
console.log('\n2. 准备服务器目录...');
if (fs.existsSync(packServerDir)) {
fs.rmSync(packServerDir, { recursive: true });
}
fs.mkdirSync(packServerDir, { recursive: true });
// 3. 复制后端文件
console.log('\n3. 复制后端文件...');
const backendFiles = ['server.js', 'package.json', 'package-lock.json'];
backendFiles.forEach(file => {
const src = path.join(backendDir, file);
const dest = path.join(packServerDir, file);
if (fs.existsSync(src)) {
fs.copyFileSync(src, dest);
console.log(` 复制: ${file}`);
}
});
// 复制后端目录
const backendDirs = ['routes', 'database', 'utils'];
backendDirs.forEach(dir => {
const src = path.join(backendDir, dir);
const dest = path.join(packServerDir, dir);
if (fs.existsSync(src)) {
fs.cpSync(src, dest, { recursive: true });
console.log(` 复制目录: ${dir}/`);
}
});
// 4. 复制前端构建产物
console.log('\n4. 复制前端构建产物...');
const frontendDist = path.join(frontendDir, 'dist');
const serverPublic = path.join(packServerDir, 'public');
if (fs.existsSync(frontendDist)) {
fs.cpSync(frontendDist, serverPublic, { recursive: true });
console.log(' 复制: frontend/dist -> app/server/public');
}
// 5. 跳过依赖安装(在目标系统上安装)
console.log('\n5. 跳过依赖安装(将在飞牛 fnOS 上安装)...');
// 6. 创建UI配置
console.log('\n6. 创建UI配置...');
const uiConfigDir = path.join(packDir, 'app', 'ui');
if (!fs.existsSync(uiConfigDir)) {
fs.mkdirSync(uiConfigDir, { recursive: true });
}
const uiConfig = {
".url": {
"flypic.Application": {
"title": "FlyPic",
"icon": "images/icon-{0}.png",
"type": "url",
"protocol": "http",
"port": "15002",
"allUsers": true,
"control": {
"portPerm": "editable"
}
}
}
};
fs.writeFileSync(
path.join(uiConfigDir, 'config'),
JSON.stringify(uiConfig, null, 2)
);
console.log(' 创建: app/ui/config');
// 7. 创建其他必要的脚本
console.log('\n7. 创建生命周期脚本...');
const scripts = [
'uninstall_init', 'uninstall_callback',
'upgrade_init', 'upgrade_callback',
'config_init', 'config_callback'
];
scripts.forEach(script => {
const scriptPath = path.join(packDir, 'cmd', script);
if (!fs.existsSync(scriptPath)) {
fs.writeFileSync(scriptPath, '#!/bin/bash\nexit 0\n');
console.log(` 创建: cmd/${script}`);
}
});
// 8. 确保所有脚本使用 LF 换行符
console.log('\n8. 修复脚本换行符...');
const cmdDir = path.join(packDir, 'cmd');
if (fs.existsSync(cmdDir)) {
const allScripts = fs.readdirSync(cmdDir);
allScripts.forEach(script => {
const scriptPath = path.join(cmdDir, script);
if (fs.statSync(scriptPath).isFile()) {
let content = fs.readFileSync(scriptPath, 'utf8');
// 将 CRLF 转换为 LF
content = content.replace(/\r\n/g, '\n');
fs.writeFileSync(scriptPath, content, { encoding: 'utf8' });
console.log(` 修复: cmd/${script}`);
}
});
}
console.log('\n=== 构建完成 ===');
console.log(`\n打包目录: ${packDir}`);
console.log('\n下一步:');
console.log('1. 准备图标文件 (64x64 和 256x256)');
console.log(' - flypic/app/ui/images/icon_64.png');
console.log(' - flypic/app/ui/images/icon_256.png');
console.log(' - flypic/ICON.PNG (256x256)');
console.log(' - flypic/ICON_256.PNG (256x256)');
console.log('2. 添加 LICENSE 文件');
console.log('3. 在飞牛 fnOS 上使用 fnpack build 打包');
console.log(' cd flypic && fnpack build');
+188
View File
@@ -0,0 +1,188 @@
/**
* FlyPic 飞牛应用构建脚本
*
* 使用 Docker (node:22-slim, Debian) 构建 Linux glibc 版本依赖
* 确保与飞牛 fnOS (Debian 系) 兼容
*
* 用法: node scripts/build.js
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
// 路径配置
const root = path.join(__dirname, '..');
const backendDir = path.join(root, 'backend');
const frontendDir = path.join(root, 'frontend');
const packDir = path.join(root, 'flypic');
const packServerDir = path.join(packDir, 'app', 'server');
// 执行命令
function run(cmd, options = {}) {
console.log(`> ${cmd}`);
execSync(cmd, { stdio: 'inherit', shell: true, ...options });
}
// 转换 Windows 路径为 Docker 挂载路径
function toDockerPath(winPath) {
// C:\Users\... -> /c/Users/...
return winPath.replace(/\\/g, '/').replace(/^([A-Z]):/, (_, drive) => `/${drive.toLowerCase()}`);
}
console.log('╔════════════════════════════════════════════════════════════╗');
console.log('║ FlyPic 飞牛应用构建脚本 (Docker + Debian) ║');
console.log('╚════════════════════════════════════════════════════════════╝\n');
// ============================================================
// 1. 构建前端
// ============================================================
console.log('📦 [1/6] 构建前端...');
run('npm run build', { cwd: frontendDir });
console.log(' ✅ 前端构建完成\n');
// ============================================================
// 2. 清理并准备服务器目录
// ============================================================
console.log('🧹 [2/6] 准备服务器目录...');
if (fs.existsSync(packServerDir)) {
fs.rmSync(packServerDir, { recursive: true });
}
fs.mkdirSync(packServerDir, { recursive: true });
console.log(' ✅ 目录已清理\n');
// ============================================================
// 3. 复制后端文件
// ============================================================
console.log('📋 [3/6] 复制后端文件...');
// 复制单文件
const backendFiles = ['server.js', 'package.json'];
backendFiles.forEach(file => {
const src = path.join(backendDir, file);
const dest = path.join(packServerDir, file);
if (fs.existsSync(src)) {
fs.copyFileSync(src, dest);
console.log(` 复制: ${file}`);
}
});
// 复制目录
const backendDirs = ['src', 'database', 'utils'];
backendDirs.forEach(dir => {
const src = path.join(backendDir, dir);
const dest = path.join(packServerDir, dir);
if (fs.existsSync(src)) {
fs.cpSync(src, dest, { recursive: true });
console.log(` 复制目录: ${dir}/`);
}
});
console.log(' ✅ 后端文件复制完成\n');
// ============================================================
// 4. 复制前端构建产物
// ============================================================
console.log('🎨 [4/6] 复制前端构建产物...');
const frontendDist = path.join(frontendDir, 'dist');
const serverPublic = path.join(packServerDir, 'public');
if (fs.existsSync(frontendDist)) {
fs.cpSync(frontendDist, serverPublic, { recursive: true });
console.log(' 复制: frontend/dist -> app/server/public');
}
console.log(' ✅ 前端产物复制完成\n');
// ============================================================
// 5. 使用 Docker 安装 Linux 依赖
// ============================================================
console.log('🐳 [5/6] 使用 Docker 安装 Linux 依赖...');
console.log(' 镜像: node:22-slim (Debian, glibc)');
console.log(' 目标: 飞牛 fnOS (Debian 系)');
console.log(' ⏳ 首次构建需要编译原生模块,约需 1-3 分钟...\n');
const dockerPath = toDockerPath(packServerDir);
// 使用 node:22-slim (Debian) 确保 glibc 兼容性
const dockerCmd = [
'docker run --rm',
`-v "${dockerPath}:/app"`,
'-w /app',
'node:22-slim',
'sh -c "' + [
// 安装编译工具
'apt-get update',
'apt-get install -y python3 make g++ --no-install-recommends',
// 配置 npm 镜像
'npm config set registry https://registry.npmmirror.com',
// 清理旧依赖并安装
'rm -rf node_modules package-lock.json',
'npm install --production',
// 显示结果
'echo ""',
'echo "=== 依赖安装完成 ==="',
'du -sh node_modules/'
].join(' && ') + '"'
].join(' ');
try {
run(dockerCmd, { cwd: root });
console.log('\n ✅ Linux 依赖安装成功');
console.log(' ✅ 包含 sharp-linux-x64 (glibc 版本)');
console.log(' ✅ 包含 better-sqlite3 (Linux 编译版本)\n');
} catch (error) {
console.error('\n ❌ Docker 构建失败');
console.error(' 错误:', error.message);
console.log('\n 请检查:');
console.log(' 1. Docker Desktop 是否正在运行');
console.log(' 2. 是否有 node:22-slim 镜像 (docker pull node:22-slim)');
console.log(' 3. 网络连接是否正常');
process.exit(1);
}
// ============================================================
// 6. 修复脚本换行符 (Windows -> Unix)
// ============================================================
console.log('🔧 [6/6] 修复脚本换行符...');
const cmdDir = path.join(packDir, 'cmd');
if (fs.existsSync(cmdDir)) {
const scripts = fs.readdirSync(cmdDir);
scripts.forEach(script => {
const scriptPath = path.join(cmdDir, script);
if (fs.statSync(scriptPath).isFile()) {
let content = fs.readFileSync(scriptPath, 'utf8');
content = content.replace(/\r\n/g, '\n');
fs.writeFileSync(scriptPath, content, { encoding: 'utf8' });
console.log(` 修复: cmd/${script}`);
}
});
}
console.log(' ✅ 换行符修复完成\n');
// ============================================================
// 完成
// ============================================================
console.log('╔════════════════════════════════════════════════════════════╗');
console.log('║ 🎉 构建完成! ║');
console.log('╚════════════════════════════════════════════════════════════╝\n');
console.log(`📁 打包目录: ${packDir}\n`);
console.log('📦 包含内容:');
console.log(' • app/server/ 后端代码 + 前端构建产物');
console.log(' • app/server/node_modules/ Linux glibc 依赖 (~57MB)');
console.log(' • app/ui/ UI 配置');
console.log(' • cmd/ 生命周期脚本');
console.log(' • config/ 资源配置');
console.log(' • wizard/ 安装向导');
console.log(' • manifest 应用清单');
console.log(' • ICON*.PNG 应用图标\n');
console.log('📋 下一步:');
console.log(' 1. 上传 flypic 文件夹到飞牛 NAS');
console.log(' 例如: /vol1/1000/flypic');
console.log('');
console.log(' 2. SSH 登录飞牛,打包应用:');
console.log(' cd /vol1/1000/flypic');
console.log(' fnpack build');
console.log('');
console.log(' 3. 安装生成的 .fpk 文件');
console.log(' 在应用中心 -> 手动安装 -> 选择 flypic_x.x.x_all.fpk');
-55
View File
@@ -1,55 +0,0 @@
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const os = require('os');
const packServerDir = path.resolve(__dirname, '../flypic/app/server');
console.log('=== 在 Docker 中测试 FlyPic ===\n');
// 创建临时启动脚本
const startScript = `#!/bin/bash
set -e
export PORT=5002
export FRONTEND_DIST=/app/public
mkdir -p /tmp/flypic_data
echo "Environment variables set"
echo "PORT=$PORT"
echo "FRONTEND_DIST=$FRONTEND_DIST"
echo "Current directory: $(pwd)"
echo "Files in /app:"
ls -la /app
echo ""
echo "Files in /app/public:"
ls -la /app/public || echo "public directory not found"
echo ""
echo "Starting server..."
node server.js
`;
// 写入临时脚本文件
const tmpScript = path.join(os.tmpdir(), 'flypic-start.sh');
fs.writeFileSync(tmpScript, startScript);
const dockerCmd = `docker run --rm -it -v "${packServerDir}:/app" -v "${tmpScript}:/start.sh" -w /app -p 5002:5002 node:22-slim bash /start.sh`;
console.log('提示:');
console.log('- 服务将在 http://localhost:5002 运行');
console.log('- 按 Ctrl+C 停止服务');
console.log('- 这是测试 Linux 版本依赖是否正常');
console.log('\n正在启动...\n');
try {
execSync(dockerCmd, { stdio: 'inherit' });
} catch (error) {
if (error.signal === 'SIGINT') {
console.log('\n服务已停止');
} else {
console.log('\n启动失败,错误信息见上方');
}
} finally {
// 清理临时文件
if (fs.existsSync(tmpScript)) {
fs.unlinkSync(tmpScript);
}
}
+96 -45
View File
@@ -9,35 +9,28 @@
- Docker Desktop(用于编译 Linux 版本依赖)
### 飞牛 NAS
- fnOS 系统
- fnpack 命令行工具(通过 `npm install -g fnpack` 安装)
- fnOS 0.9.27+
- fnpack 命令行工具(系统预装或通过 `npm install -g fnpack` 安装)
## 一、构建应用
### 方法一:使用 Docker 构建(推荐)
### 使用 Docker 构建(推荐)
此方法会自动编译 Linux 版本的原生模块(Sharp、better-sqlite3),上传到飞牛后可直接使用。
此方法使用 `node:22-slim` (Debian) 镜像编译原生模块,确保与飞牛 fnOS (Debian 系) 的 glibc 兼容。
```bash
# 确保 Docker Desktop 正在运行
node scripts/build-fpk-docker.js
node scripts/build.js
```
构建完成后,`flypic` 目录将包含:
- `app/server/` - 后端代码和前端构建产物
- `app/server/node_modules/` - Linux 版本的依赖(约 50MB)
- `app/ui/` - 应用 UI 配置
- `cmd/` - 生命周期脚本
- `wizard/` - 安装向导配置
- `manifest` - 应用清单
构建过程:
1. 构建前端 (Vite)
2. 复制后端代码到 `flypic/app/server/`
3. 复制前端产物到 `flypic/app/server/public/`
4. 使用 Docker 安装 Linux glibc 版本依赖
5. 修复脚本换行符 (CRLF → LF)
### 方法二:仅构建代码(需在飞牛上安装依赖)
```bash
node scripts/build-fpk.js
```
此方法不包含 node_modules,需要在飞牛 NAS 上手动安装依赖。
构建完成后,`flypic` 目录即可上传到飞牛。
## 二、上传到飞牛 NAS
@@ -60,7 +53,7 @@ cd /vol1/1000/flypic
fnpack build
```
成功后会生成 `flypic_x.x.x_all.fpk` 文件。
成功后会生成 `flypic_0.1.0_all.fpk` 文件。
## 四、安装应用
@@ -72,7 +65,7 @@ fnpack build
### 方法二:命令行安装
```bash
fnpack install flypic_x.x.x_all.fpk
appcenter-cli install-fpk flypic_0.1.0_all.fpk
```
## 五、配置应用
@@ -89,51 +82,102 @@ fnpack install flypic_x.x.x_all.fpk
```
flypic/
├── ICON.PNG # 应用图标 64x64
├── ICON_256.PNG # 应用图标 256x256
├── manifest # 应用清单
├── app/
│ ├── server/ # 应用服务器
│ │ ├── server.js # 主入口
│ │ ├── package.json
│ │ ├── node_modules/ # 依赖(Docker 构建时包含)
│ │ ├── public/ # 前端静态文件
│ │ ├── routes/ # API 路由
│ │ ├── database/ # 数据库模块
│ │ └── utils/ # 工具函数
│ ├── server/ # 应用服务器
│ │ ├── server.js # 主入口
│ │ ├── package.json # 依赖配置
│ │ ├── node_modules/ # Linux glibc 依赖 (~57MB)
│ │ │ ├── @img/sharp-linux-x64/ # Sharp 原生模块
│ │ │ ├── better-sqlite3/ # SQLite 原生模块
│ │ │ └── ...
│ │ ├── public/ # 前端静态文件 (Vite 构建产物)
│ │ ├── src/ # 后端源码
│ │ │ ├── routes/ # API 路由
│ │ │ ├── services/ # 业务逻辑
│ │ │ ├── models/ # 数据模型
│ │ │ └── config/ # 配置
│ │ ├── database/ # 数据库模块
│ │ └── utils/ # 工具函数
│ └── ui/
│ ├── config # UI 配置
│ └── images/ # 应用图标
│ └── config # UI 入口配置
├── cmd/
│ ├── main # 启动脚本
│ ├── install_init # 安装前脚本
│ ├── install_callback # 安装后脚本
│ └── ... # 其他生命周期脚本
├── wizard/
│ └── install # 安装向导配置
│ ├── main # 启动/停止脚本
│ ├── install_init # 安装前脚本
│ ├── install_callback # 安装后脚本
│ ├── uninstall_init # 卸载前脚本
│ ├── uninstall_callback # 卸载后脚本
│ ├── upgrade_init # 升级前脚本
│ ├── upgrade_callback # 升级后脚本
│ ├── config_init # 配置前脚本
│ └── config_callback # 配置后脚本
├── config/
│ └── resource # 资源配置
├── manifest # 应用清单
├── ICON.PNG # 应用图标 256x256
└── ICON_256.PNG # 应用图标 256x256
│ ├── privilege # 权限配置
│ └── resource # 资源配置 (数据共享目录)
└── wizard/
└── install # 安装向导配置
```
## 关键配置文件
### manifest (应用清单)
```
appname=flypic
version=0.1.0
desc=飞图 - 专为飞牛 fnOS 设计的轻量、快速、稳定的图像素材检索浏览应用
arch=x86_64
display_name=FlyPic
maintainer=ZangXincz
source=thirdparty
service_port=15002
install_dep_apps=nodejs_v22
```
### config/resource (资源配置)
```json
{
"data-share": [
{
"name": "FlyPic数据",
"path": "data",
"mode": "rw",
"desc": "FlyPic 应用数据存储目录"
}
]
}
```
## 常见问题
### Q: 应用启动失败,显示"异常退出"
A: 检查以下几点:
1. 确保使用 Docker 构建方法,包含 Linux 版本的 node_modules
2. 检查应用日志,查看具体错误信息
1. 确保使用 `node scripts/build.js` 构建,包含 Linux glibc 版本的 node_modules
2. 检查应用日志:`/var/apps/flypic/var/info.log`
3. 确保端口 15002 未被占用
4. 确保依赖应用 nodejs_v22 已安装
### Q: Sharp 或 SQLite 报错
A: 原生模块需要正确的 Linux 版本:
- 必须使用 Docker (node:22-slim, Debian) 构建
- 不能使用 Alpine 镜像(musl libc 不兼容)
- 不能直接在 Windows/Mac 上 npm install
### Q: 无法访问素材库文件夹
A: 在飞牛应用设置中配置授权目录,添加素材库路径的访问权限。
### Q: 如何更新应用?
A:
1. 重新构建:`node scripts/build-fpk-docker.js`
1. 重新构建:`node scripts/build.js`
2. 上传到飞牛并打包:`fnpack build`
3. 在应用中心选择「更新」或重新安装
### Q: 如何查看应用日志?
A: 在飞牛系统日志中查看,或 SSH 登录后查看应用日志文件。
A: SSH 登录后查看:
```bash
cat /var/apps/flypic/var/info.log
```
## 开发调试
@@ -152,3 +196,10 @@ npm run dev
```
访问 http://localhost:5173 进行开发调试。
## 技术栈
- **后端**: Node.js + Express + Sharp + better-sqlite3 + Socket.IO
- **前端**: React + Vite + TailwindCSS + Zustand
- **运行时**: nodejs_v22 (飞牛应用依赖)
- **端口**: 15002