v 1.0.0
This commit is contained in:
commit
9e346c7d5b
73 files changed
+19169
No files matched your search
+55
@@ -0,0 +1,55 @@
|
||||
# 依赖目录
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# 构建输出
|
||||
dist/
|
||||
build/
|
||||
out/
|
||||
*.log
|
||||
|
||||
# 环境变量文件
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# IDE 和编辑器
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
|
||||
# 操作系统文件
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# 临时文件
|
||||
*.tmp
|
||||
*.temp
|
||||
.cache/
|
||||
.temp/
|
||||
|
||||
# 测试覆盖率
|
||||
coverage/
|
||||
*.coverage
|
||||
.nyc_output/
|
||||
|
||||
# 知识库文件夹 - 不同步到 GitHub
|
||||
Knowledge base/
|
||||
飞牛打包部署指南.md
|
||||
|
||||
# 构建输出
|
||||
dist/
|
||||
|
||||
# 测试数据
|
||||
test-library/
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 ZangXincz
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,109 @@
|
||||
# FlyPic
|
||||
|
||||
一个轻量、快速、稳定的图片检索浏览应用,专为飞牛 fnOS 设计。
|
||||
|
||||
## 核心特性
|
||||
|
||||
- 🚀 **高性能**: 支持 10万-100万 级别图片浏览
|
||||
- 🎨 **Eagle 风格瀑布流**: 固定高度,宽度自适应,视觉整齐
|
||||
- 🔍 **智能搜索**: 多关键词组合搜索,快速定位
|
||||
|
||||
## 🛠️ 技术栈
|
||||
|
||||
- **前端**:React + Vite + TailwindCSS + react-photo-view + zustand
|
||||
- **后端**:Node.js + Express + Sharp + better-sqlite3 + Socket.IO
|
||||
- **部署**:飞牛 fnOS
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 开发环境
|
||||
|
||||
```bash
|
||||
# 安装依赖
|
||||
npm install
|
||||
|
||||
# 启动前端开发服务器(推荐)
|
||||
npm run dev:frontend
|
||||
# 访问 http://localhost:5173
|
||||
|
||||
# 启动后端开发服务器
|
||||
npm run dev:backend
|
||||
# API 运行在 http://localhost:5002
|
||||
```
|
||||
|
||||
### 构建部署
|
||||
|
||||
```bash
|
||||
# 方法一:使用 Docker 构建(推荐)
|
||||
# 包含 Linux 版本的依赖,上传后直接可用
|
||||
npm run build:fpk:docker
|
||||
|
||||
# 方法二:普通构建
|
||||
# 需要在飞牛上手动安装依赖
|
||||
npm run build:fpk
|
||||
|
||||
# 本地测试 Linux 版本
|
||||
npm run test:docker
|
||||
```
|
||||
|
||||
## 📦 部署到飞牛 fnOS
|
||||
|
||||
详细步骤请查看:**[飞牛打包部署指南](./飞牛打包部署指南.md)**
|
||||
|
||||
### 快速部署
|
||||
|
||||
1. **构建**:`npm run build:fpk:docker`
|
||||
2. **上传**:将 `flypic/` 目录上传到飞牛
|
||||
3. **打包**:`fnpack build`
|
||||
4. **安装**:`appcenter-cli install-fpk flypic.fpk`
|
||||
5. **访问**:`http://你的飞牛IP:5002`
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
FlyPic/
|
||||
├── frontend/ # React 前端
|
||||
├── backend/ # Node.js 后端
|
||||
├── flypic/ # 飞牛打包目录(构建生成)
|
||||
├── scripts/ # 构建脚本
|
||||
│ ├── build-fpk.js # 普通构建
|
||||
│ ├── build-fpk-docker.js # Docker 构建
|
||||
│ └── test-in-docker.js # Docker 测试
|
||||
├── dev.bat # Windows 开发启动脚本
|
||||
├── start.bat # Windows 生产启动脚本
|
||||
└── 飞牛打包部署指南.md # 完整部署文档
|
||||
```
|
||||
|
||||
## 🎯 支持的图片格式
|
||||
|
||||
jpg, jpeg, png, webp, gif, bmp, tiff
|
||||
|
||||
## 📝 开发说明
|
||||
|
||||
### 数据存储
|
||||
|
||||
```
|
||||
素材库目录/
|
||||
├── 用户图片文件...
|
||||
└── .flypic/
|
||||
├── thumbnails/200/ # WebP 缩略图
|
||||
├── metadata.db # SQLite 数据库
|
||||
└── config.json # 配置文件
|
||||
```
|
||||
|
||||
### 端口配置
|
||||
|
||||
- 前端开发:5173
|
||||
- 后端服务:5002
|
||||
|
||||
## 🐛 故障排查
|
||||
|
||||
常见问题请查看 [飞牛打包部署指南 - 故障排查](./飞牛打包部署指南.md#故障排查)
|
||||
|
||||
## 📄 License
|
||||
|
||||
MIT License - 详见 [LICENSE](./LICENSE) 文件
|
||||
|
||||
---
|
||||
|
||||
**最后更新**:2025-11-29
|
||||
@@ -0,0 +1,281 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
class LibraryDatabase {
|
||||
constructor(libraryPath) {
|
||||
this.libraryPath = libraryPath;
|
||||
this.flypicDir = path.join(libraryPath, '.flypic');
|
||||
this.dbPath = path.join(this.flypicDir, 'metadata.db');
|
||||
|
||||
// Ensure .flypic directory exists
|
||||
if (!fs.existsSync(this.flypicDir)) {
|
||||
fs.mkdirSync(this.flypicDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Create thumbnails directory (480px 与 Billfish 一致)
|
||||
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);
|
||||
|
||||
// 优化数据库性能
|
||||
this.db.pragma('journal_mode = WAL'); // 启用 WAL 模式,支持并发读写
|
||||
this.db.pragma('synchronous = NORMAL'); // 平衡性能和安全性
|
||||
this.db.pragma('cache_size = -64000'); // 64MB 缓存
|
||||
this.db.pragma('temp_store = MEMORY'); // 临时表存储在内存
|
||||
this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射
|
||||
|
||||
this.initTables();
|
||||
}
|
||||
|
||||
initTables() {
|
||||
// Images table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
path TEXT UNIQUE NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
size INTEGER,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
format TEXT,
|
||||
file_type TEXT DEFAULT 'image',
|
||||
created_at INTEGER,
|
||||
modified_at INTEGER,
|
||||
file_hash TEXT,
|
||||
thumbnail_path TEXT,
|
||||
thumbnail_size INTEGER,
|
||||
indexed_at INTEGER
|
||||
)
|
||||
`);
|
||||
|
||||
// 添加 file_type 列(如果不存在)
|
||||
try {
|
||||
this.db.exec(`ALTER TABLE images ADD COLUMN file_type TEXT DEFAULT 'image'`);
|
||||
} catch (e) {
|
||||
// 列已存在,忽略错误
|
||||
}
|
||||
|
||||
// Folders table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS folders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
path TEXT UNIQUE NOT NULL,
|
||||
parent_path TEXT,
|
||||
name TEXT NOT NULL,
|
||||
image_count INTEGER DEFAULT 0,
|
||||
last_scan INTEGER
|
||||
)
|
||||
`);
|
||||
|
||||
// Create indexes
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_filename ON images(filename);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder ON images(folder);
|
||||
CREATE INDEX IF NOT EXISTS idx_created_at ON images(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_file_hash ON images(file_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_path ON folders(path);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_parent ON folders(parent_path);
|
||||
-- 复合索引:优化文件夹+时间排序查询
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_created ON images(folder, created_at DESC);
|
||||
`);
|
||||
}
|
||||
|
||||
// Image operations
|
||||
insertImage(imageData) {
|
||||
const stmt = this.db.prepare(`
|
||||
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 stmt.run(
|
||||
imageData.path,
|
||||
imageData.filename,
|
||||
imageData.folder,
|
||||
imageData.size,
|
||||
imageData.width,
|
||||
imageData.height,
|
||||
imageData.format,
|
||||
imageData.file_type || 'image',
|
||||
imageData.created_at,
|
||||
imageData.modified_at,
|
||||
imageData.file_hash,
|
||||
imageData.thumbnail_path,
|
||||
imageData.thumbnail_size,
|
||||
Date.now()
|
||||
);
|
||||
}
|
||||
|
||||
getImageByPath(imagePath) {
|
||||
const stmt = this.db.prepare('SELECT * FROM images WHERE path = ?');
|
||||
return stmt.get(imagePath);
|
||||
}
|
||||
|
||||
getAllImages() {
|
||||
const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
searchImages(keywords, filters = {}) {
|
||||
let query = 'SELECT * FROM images WHERE 1=1';
|
||||
const params = [];
|
||||
|
||||
// Keyword search (AND logic)
|
||||
if (keywords && keywords.trim()) {
|
||||
const terms = keywords.trim().split(/\s+/);
|
||||
terms.forEach(term => {
|
||||
query += ' AND filename LIKE ?';
|
||||
params.push(`%${term}%`);
|
||||
});
|
||||
}
|
||||
|
||||
// Folder filter
|
||||
if (filters.folder) {
|
||||
query += ' AND folder LIKE ?';
|
||||
params.push(`${filters.folder}%`);
|
||||
}
|
||||
|
||||
// Format filter
|
||||
if (filters.formats && filters.formats.length > 0) {
|
||||
const placeholders = filters.formats.map(() => '?').join(',');
|
||||
query += ` AND format IN (${placeholders})`;
|
||||
params.push(...filters.formats);
|
||||
}
|
||||
|
||||
// Size filter (in KB)
|
||||
if (filters.minSize) {
|
||||
query += ' AND size >= ?';
|
||||
params.push(filters.minSize * 1024);
|
||||
}
|
||||
if (filters.maxSize) {
|
||||
query += ' AND size <= ?';
|
||||
params.push(filters.maxSize * 1024);
|
||||
}
|
||||
|
||||
// Date filter
|
||||
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';
|
||||
|
||||
const stmt = this.db.prepare(query);
|
||||
return stmt.all(...params);
|
||||
}
|
||||
|
||||
deleteImage(imagePath) {
|
||||
const stmt = this.db.prepare('DELETE FROM images WHERE path = ?');
|
||||
return stmt.run(imagePath);
|
||||
}
|
||||
|
||||
// Update folder field for a specific image (by path)
|
||||
updateImageFolder(imagePath, folderPath) {
|
||||
const stmt = this.db.prepare('UPDATE images SET folder = ? WHERE path = ?');
|
||||
return stmt.run(folderPath, imagePath);
|
||||
}
|
||||
|
||||
// Folder operations
|
||||
insertFolder(folderData) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO folders (path, parent_path, name, image_count, last_scan)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
return stmt.run(
|
||||
folderData.path,
|
||||
folderData.parent_path,
|
||||
folderData.name,
|
||||
folderData.image_count || 0,
|
||||
Date.now()
|
||||
);
|
||||
}
|
||||
|
||||
getAllFolders() {
|
||||
const stmt = this.db.prepare('SELECT * FROM folders ORDER BY path');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
getFolderByPath(folderPath) {
|
||||
const stmt = this.db.prepare('SELECT * FROM folders WHERE path = ?');
|
||||
return stmt.get(folderPath);
|
||||
}
|
||||
|
||||
deleteFolder(folderPath) {
|
||||
const stmt = this.db.prepare('DELETE FROM folders WHERE path = ?');
|
||||
return stmt.run(folderPath);
|
||||
}
|
||||
|
||||
deleteImagesByFolderPrefix(folderPath) {
|
||||
// 使用 folderPath/% 确保只匹配真正的子文件夹,避免误删同名前缀文件夹
|
||||
const stmt = this.db.prepare('DELETE FROM images WHERE folder = ? OR folder LIKE ?');
|
||||
return stmt.run(folderPath, `${folderPath}/%`);
|
||||
}
|
||||
|
||||
deleteFoldersByPrefix(folderPath) {
|
||||
// 使用 folderPath/% 确保只匹配真正的子文件夹
|
||||
const stmt = this.db.prepare('DELETE FROM folders WHERE path = ? OR path LIKE ?');
|
||||
return stmt.run(folderPath, `${folderPath}/%`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文件夹的文件数量(包含所有子文件夹中的图片)
|
||||
*/
|
||||
updateFolderImageCount(folderPath) {
|
||||
// 统计该文件夹及其所有子文件夹中的图片总数
|
||||
// folder = ? 匹配直接子文件,folder LIKE ?/% 匹配所有子文件夹
|
||||
const countStmt = this.db.prepare(
|
||||
'SELECT COUNT(*) as count FROM images WHERE folder = ? OR folder LIKE ?'
|
||||
);
|
||||
const result = countStmt.get(folderPath, `${folderPath}/%`);
|
||||
|
||||
// 更新文件夹记录
|
||||
const updateStmt = this.db.prepare('UPDATE folders SET image_count = ? WHERE path = ?');
|
||||
return updateStmt.run(result.count, folderPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新所有文件夹的文件数量
|
||||
*/
|
||||
updateAllFolderCounts() {
|
||||
const folders = this.getAllFolders();
|
||||
for (const folder of folders) {
|
||||
this.updateFolderImageCount(folder.path);
|
||||
}
|
||||
}
|
||||
|
||||
getFolderTree() {
|
||||
const folders = this.getAllFolders();
|
||||
const tree = [];
|
||||
const map = {};
|
||||
|
||||
// Build folder map
|
||||
folders.forEach(folder => {
|
||||
map[folder.path] = { ...folder, children: [] };
|
||||
});
|
||||
|
||||
// Build tree structure
|
||||
folders.forEach(folder => {
|
||||
if (folder.parent_path && map[folder.parent_path]) {
|
||||
map[folder.parent_path].children.push(map[folder.path]);
|
||||
} else {
|
||||
tree.push(map[folder.path]);
|
||||
}
|
||||
});
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
close() {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LibraryDatabase;
|
||||
@@ -0,0 +1,157 @@
|
||||
const LibraryDatabase = require('./db');
|
||||
|
||||
/**
|
||||
* 数据库连接池管理器
|
||||
* 复用数据库连接,避免频繁创建/关闭
|
||||
*/
|
||||
class DatabasePool {
|
||||
constructor() {
|
||||
this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount }
|
||||
this.maxIdleTime = 60000; // 60秒未使用则关闭
|
||||
this.cleanupInterval = null;
|
||||
|
||||
// 启动定期清理
|
||||
this.startCleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库连接(复用或创建)
|
||||
* 优化:同时只保持一个活跃连接
|
||||
*/
|
||||
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 = {
|
||||
db,
|
||||
lastUsed: Date.now(),
|
||||
refCount: 0
|
||||
};
|
||||
this.connections.set(libraryPath, conn);
|
||||
console.log(`[DBPool] Created new connection for: ${libraryPath}`);
|
||||
}
|
||||
|
||||
// 更新使用时间和引用计数
|
||||
conn.lastUsed = Date.now();
|
||||
conn.refCount++;
|
||||
|
||||
return conn.db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放数据库连接(减少引用计数)
|
||||
*/
|
||||
release(libraryPath) {
|
||||
const conn = this.connections.get(libraryPath);
|
||||
if (conn) {
|
||||
conn.refCount = Math.max(0, conn.refCount - 1);
|
||||
conn.lastUsed = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制关闭指定连接
|
||||
*/
|
||||
close(libraryPath) {
|
||||
const conn = this.connections.get(libraryPath);
|
||||
if (conn) {
|
||||
try {
|
||||
// 强制设置引用计数为0
|
||||
conn.refCount = 0;
|
||||
|
||||
// 关闭数据库连接
|
||||
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();
|
||||
}
|
||||
|
||||
this.connections.delete(libraryPath);
|
||||
console.log(`[DBPool] Closed connection for: ${libraryPath}`);
|
||||
} catch (error) {
|
||||
console.error(`[DBPool] Error closing connection:`, error);
|
||||
// 即使出错也删除引用
|
||||
this.connections.delete(libraryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭所有连接
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定期清理空闲连接
|
||||
*/
|
||||
startCleanup() {
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
const now = Date.now();
|
||||
const toClose = [];
|
||||
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
// 如果连接空闲超过阈值且没有引用,则关闭
|
||||
if (conn.refCount === 0 && now - conn.lastUsed > this.maxIdleTime) {
|
||||
toClose.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
toClose.forEach(path => this.close(path));
|
||||
|
||||
if (toClose.length > 0) {
|
||||
console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`);
|
||||
}
|
||||
}, 30000); // 每30秒检查一次
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取连接池状态
|
||||
*/
|
||||
getStatus() {
|
||||
const status = [];
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
status.push({
|
||||
path,
|
||||
refCount: conn.refCount,
|
||||
idleTime: Date.now() - conn.lastUsed
|
||||
});
|
||||
}
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
// 单例模式
|
||||
const dbPool = new DatabasePool();
|
||||
|
||||
module.exports = dbPool;
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "flypic-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "FlyPic backend server",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"dev": "nodemon server.js",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^9.2.2",
|
||||
"chokidar": "^3.6.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto": "^1.0.1",
|
||||
"express": "^4.18.2",
|
||||
"glob": "^10.3.10",
|
||||
"p-limit": "^7.2.0",
|
||||
"sharp": "^0.33.0",
|
||||
"socket.io": "^4.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
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
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const { libraryId, keywords, folder, formats, minSize, maxSize, startDate, endDate } = 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);
|
||||
|
||||
const images = db.searchImages(keywords || '', filters);
|
||||
|
||||
res.json({ images });
|
||||
} 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;
|
||||
@@ -0,0 +1,242 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
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');
|
||||
|
||||
console.log(`[Delete] Cleaning up library: ${library.name}`);
|
||||
|
||||
// 1. 停止扫描并清理状态
|
||||
scanManager.clearState(id);
|
||||
|
||||
// 2. 停止文件监控
|
||||
fileWatcher.unwatch(id);
|
||||
|
||||
// 3. 关闭数据库连接
|
||||
dbPool.close(library.path);
|
||||
|
||||
// 等待一下,确保连接完全关闭
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
// 删除索引
|
||||
removeLibrary(id);
|
||||
|
||||
console.log(`✅ Library removed: ${library.name}`);
|
||||
|
||||
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 fileWatcher = require('../utils/fileWatcher');
|
||||
const scanManager = require('../utils/scanManager');
|
||||
|
||||
// 获取旧的当前素材库
|
||||
const oldLibraryId = config.currentLibraryId;
|
||||
if (oldLibraryId && oldLibraryId !== id) {
|
||||
const oldLibrary = config.libraries.find(lib => lib.id === oldLibraryId);
|
||||
if (oldLibrary) {
|
||||
console.log(`[Switch] Cleaning up old library: ${oldLibrary.name}`);
|
||||
|
||||
// 1. 停止扫描(如果正在进行),但保留暂停状态以便恢复
|
||||
if (scanManager.isScanning(oldLibraryId)) {
|
||||
const state = scanManager.getState(oldLibraryId);
|
||||
if (state.abortController) {
|
||||
state.abortController.aborted = true;
|
||||
}
|
||||
// 不调用 completeScan,让扫描自己暂停并保留待处理文件
|
||||
console.log(` ⏸️ Pausing scan (will preserve state)`);
|
||||
}
|
||||
|
||||
// 3. 关闭数据库连接
|
||||
dbPool.close(oldLibrary.path);
|
||||
console.log(` ⏹️ Closed database`);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新的当前素材库
|
||||
setCurrentLibrary(id);
|
||||
|
||||
const newLibrary = config.libraries.find(lib => lib.id === id);
|
||||
console.log(`[Switch] Switched to library: ${newLibrary?.name}`);
|
||||
|
||||
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' });
|
||||
}
|
||||
|
||||
console.log(`[Release] Releasing resources for library: ${library.name}`);
|
||||
|
||||
// 1. 关闭数据库连接
|
||||
const dbPool = require('../database/dbPool');
|
||||
dbPool.close(library.path);
|
||||
console.log(`[Release] Database connection closed`);
|
||||
|
||||
// 2. 停止文件监控
|
||||
const fileWatcher = req.app.get('fileWatcher');
|
||||
if (fileWatcher && fileWatcher.isWatching(id)) {
|
||||
fileWatcher.unwatch(id);
|
||||
console.log(`[Release] File watcher stopped`);
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -0,0 +1,283 @@
|
||||
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;
|
||||
@@ -0,0 +1,84 @@
|
||||
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');
|
||||
|
||||
// 尝试启动监控,如果失败则返回详细错误
|
||||
try {
|
||||
fileWatcher.watch(libraryId, io);
|
||||
res.json({
|
||||
message: 'File watching started',
|
||||
libraryId,
|
||||
isWatching: true
|
||||
});
|
||||
} catch (watchError) {
|
||||
// 监控启动失败,但不应该导致整个请求失败
|
||||
console.error(`Failed to start file watching for ${libraryId}:`, watchError.message);
|
||||
res.status(200).json({
|
||||
message: 'File watching could not be started',
|
||||
libraryId,
|
||||
isWatching: false,
|
||||
error: 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;
|
||||
@@ -0,0 +1,192 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
const { Server } = require('socket.io');
|
||||
const fileWatcher = require('./utils/fileWatcher');
|
||||
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server, {
|
||||
cors: {
|
||||
origin: process.env.FRONTEND_DIST ? false : 'http://localhost:5173',
|
||||
methods: ['GET', 'POST']
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// 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')
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (require('fs').existsSync(p)) {
|
||||
FRONTEND_DIST = p;
|
||||
console.log('✅ Found frontend at:', p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!FRONTEND_DIST) {
|
||||
console.log('⚠️ Frontend not found, tried:', possiblePaths);
|
||||
}
|
||||
}
|
||||
|
||||
// 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'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 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('📭 未选中素材库,等待用户操作...');
|
||||
}
|
||||
});
|
||||
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
|
||||
// 监听各种退出信号
|
||||
process.on('SIGINT', () => gracefulShutdown('SIGINT')); // Ctrl+C
|
||||
process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); // kill
|
||||
process.on('SIGHUP', () => gracefulShutdown('SIGHUP')); // 终端关闭
|
||||
|
||||
// Windows 特殊处理(Ctrl+C)
|
||||
if (process.platform === 'win32') {
|
||||
const readline = require('readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
rl.on('SIGINT', () => {
|
||||
process.emit('SIGINT');
|
||||
});
|
||||
}
|
||||
|
||||
// 捕获未处理的异常
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('❌ Uncaught Exception:', error);
|
||||
gracefulShutdown('uncaughtException');
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
|
||||
gracefulShutdown('unhandledRejection');
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
// 配置缓存
|
||||
let configCache = null;
|
||||
let configCacheTime = 0;
|
||||
const CONFIG_CACHE_TTL = 5000; // 5秒缓存
|
||||
|
||||
/**
|
||||
* Get config directory based on environment
|
||||
*/
|
||||
function getConfigDir() {
|
||||
// Check if running on fnOS
|
||||
if (process.env.TRIM_PKGVAR) {
|
||||
return process.env.TRIM_PKGVAR;
|
||||
}
|
||||
|
||||
// Windows
|
||||
if (process.platform === 'win32') {
|
||||
return path.join(process.env.APPDATA || os.homedir(), 'FlyPic');
|
||||
}
|
||||
|
||||
// Linux/Mac
|
||||
return path.join(os.homedir(), '.flypic');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config file path
|
||||
*/
|
||||
function getConfigPath() {
|
||||
const configDir = getConfigDir();
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
return path.join(configDir, 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configuration
|
||||
*/
|
||||
function loadConfig(forceReload = false) {
|
||||
// 检查缓存是否有效
|
||||
const now = Date.now();
|
||||
if (!forceReload && configCache && (now - configCacheTime) < CONFIG_CACHE_TTL) {
|
||||
return configCache;
|
||||
}
|
||||
|
||||
const configPath = getConfigPath();
|
||||
|
||||
if (!fs.existsSync(configPath)) {
|
||||
const defaultConfig = {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
// UI preferences
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16,
|
||||
leftPanelWidth: 256, // 左侧边栏宽度
|
||||
rightPanelWidth: 320 // 右侧边栏宽度
|
||||
}
|
||||
};
|
||||
saveConfig(defaultConfig);
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = fs.readFileSync(configPath, 'utf8');
|
||||
const config = JSON.parse(data);
|
||||
|
||||
// Ensure preferences exist (for backward compatibility)
|
||||
if (!config.preferences) {
|
||||
config.preferences = {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
};
|
||||
}
|
||||
|
||||
// 更新缓存
|
||||
configCache = config;
|
||||
configCacheTime = now;
|
||||
|
||||
return config;
|
||||
} catch (error) {
|
||||
console.error('Error loading config:', error);
|
||||
return {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save configuration
|
||||
*/
|
||||
function saveConfig(config) {
|
||||
const configPath = getConfigPath();
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
// 同步更新缓存
|
||||
configCache = config;
|
||||
configCacheTime = Date.now();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error saving config:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除配置缓存(用于强制重新加载)
|
||||
*/
|
||||
function clearConfigCache() {
|
||||
configCache = null;
|
||||
configCacheTime = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add library to config
|
||||
*/
|
||||
function addLibrary(name, libraryPath) {
|
||||
const config = loadConfig();
|
||||
const id = Date.now().toString();
|
||||
|
||||
config.libraries.push({
|
||||
id,
|
||||
name,
|
||||
path: libraryPath,
|
||||
lastScan: null,
|
||||
createdAt: Date.now()
|
||||
});
|
||||
|
||||
if (!config.currentLibraryId) {
|
||||
config.currentLibraryId = id;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove library from config
|
||||
*/
|
||||
function removeLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.libraries = config.libraries.filter(lib => lib.id !== libraryId);
|
||||
|
||||
if (config.currentLibraryId === libraryId) {
|
||||
config.currentLibraryId = config.libraries.length > 0 ? config.libraries[0].id : null;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update library
|
||||
*/
|
||||
function updateLibrary(libraryId, updates) {
|
||||
const config = loadConfig();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (library) {
|
||||
Object.assign(library, updates);
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get library by ID
|
||||
*/
|
||||
function getLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
return config.libraries.find(lib => lib.id === libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current library
|
||||
*/
|
||||
function setCurrentLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.currentLibraryId = libraryId;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update preferences
|
||||
*/
|
||||
function updatePreferences(preferences) {
|
||||
const config = loadConfig();
|
||||
config.preferences = { ...config.preferences, ...preferences };
|
||||
saveConfig(config);
|
||||
return config.preferences;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update theme
|
||||
*/
|
||||
function updateTheme(theme) {
|
||||
const config = loadConfig();
|
||||
config.theme = theme;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getConfigDir,
|
||||
getConfigPath,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
clearConfigCache,
|
||||
addLibrary,
|
||||
removeLibrary,
|
||||
updateLibrary,
|
||||
getLibrary,
|
||||
setCurrentLibrary,
|
||||
updatePreferences,
|
||||
updateTheme
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
const chokidar = require('chokidar');
|
||||
const path = require('path');
|
||||
const { getLibrary } = require('./config');
|
||||
const { syncLibrary, applyChangesFromEvents } = require('./scanner');
|
||||
const dbPool = require('../database/dbPool');
|
||||
|
||||
class FileWatcher {
|
||||
constructor() {
|
||||
this.watchers = new Map(); // libraryId -> watcher
|
||||
this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders }
|
||||
this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved }
|
||||
}
|
||||
|
||||
// 获取或创建变更缓冲区
|
||||
_getBuffer(libraryId) {
|
||||
if (!this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
}
|
||||
return this.changeBuffers.get(libraryId);
|
||||
}
|
||||
|
||||
// 缓冲区事件数量
|
||||
_bufferCount(buf) {
|
||||
return (
|
||||
buf.filesAdded.size +
|
||||
buf.filesChanged.size +
|
||||
buf.filesRemoved.size +
|
||||
buf.dirsAdded.size +
|
||||
buf.dirsRemoved.size
|
||||
);
|
||||
}
|
||||
|
||||
// 启动监控
|
||||
watch(libraryId, io) {
|
||||
// 如果已经在监控,先停止
|
||||
if (this.watchers.has(libraryId)) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
|
||||
const library = getLibrary(libraryId);
|
||||
if (!library) {
|
||||
console.error(`Library ${libraryId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查路径是否存在和可访问
|
||||
const fs = require('fs');
|
||||
try {
|
||||
fs.accessSync(library.path, fs.constants.R_OK);
|
||||
} catch (error) {
|
||||
const errorMsg = `Cannot access library path: ${library.path} - ${error.message}`;
|
||||
console.error(errorMsg);
|
||||
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
console.log(`Starting file watcher for library: ${library.name} (${library.path})`);
|
||||
|
||||
// 监控所有文件(使用通配符)
|
||||
const pattern = '**/*.*';
|
||||
|
||||
// 创建监控器(监控所有文件和文件夹)
|
||||
const watcher = chokidar.watch([pattern, '**/'], {
|
||||
cwd: library.path,
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/.flypic/**', // 忽略自己的缓存目录
|
||||
'**/.*' // 忽略隐藏文件
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true, // 忽略初始扫描
|
||||
usePolling: false, // 不使用轮询,减少 CPU 占用
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1000, // 文件稳定 1 秒后触发,确保复制完成
|
||||
pollInterval: 200
|
||||
}
|
||||
});
|
||||
|
||||
// 防抖处理:多个文件变化合并为一次同步(自适应时长)
|
||||
const debouncedSync = (forceRebuildFolders = false) => {
|
||||
const buf = this._getBuffer(libraryId);
|
||||
const changeCount = this._bufferCount(buf);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const oldTimer = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(oldTimer.timer);
|
||||
// 聚合 forceRebuildFolders 标记
|
||||
forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders;
|
||||
}
|
||||
|
||||
// 自适应防抖时间:更快响应
|
||||
let debounceMs = 2000;
|
||||
if (changeCount <= 1) debounceMs = 800; // 单文件 0.8 秒
|
||||
else if (changeCount <= 5) debounceMs = 1000; // 少量 1 秒
|
||||
else if (changeCount <= 20) debounceMs = 1500;
|
||||
else if (changeCount <= 100) debounceMs = 2000;
|
||||
else debounceMs = 3000; // 大批量 3 秒
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
const snapshot = this._getBuffer(libraryId);
|
||||
// 清空缓冲区(开始新一轮累计)
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
|
||||
// 从连接池获取数据库连接
|
||||
const db = dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const total = this._bufferCount(snapshot);
|
||||
let results;
|
||||
|
||||
// 始终使用基于事件的快速同步(不再调用 syncLibrary)
|
||||
results = await applyChangesFromEvents(library.path, db, {
|
||||
filesAdded: Array.from(snapshot.filesAdded),
|
||||
filesChanged: Array.from(snapshot.filesChanged),
|
||||
filesRemoved: Array.from(snapshot.filesRemoved),
|
||||
dirsAdded: Array.from(snapshot.dirsAdded),
|
||||
dirsRemoved: Array.from(snapshot.dirsRemoved)
|
||||
});
|
||||
|
||||
// 通过 Socket.IO 通知前端
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
console.log(`Sync complete for ${library.name}:`, results);
|
||||
} catch (error) {
|
||||
console.error(`Sync error for ${library.name}:`, error);
|
||||
io.emit('scanError', { libraryId, error: error.message });
|
||||
} finally {
|
||||
// 释放数据库连接(不关闭,复用)
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}, debounceMs);
|
||||
|
||||
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
|
||||
};
|
||||
|
||||
// 监听文件和文件夹变化(写入缓冲,统一合并处理)
|
||||
watcher
|
||||
.on('add', (filePath) => {
|
||||
this._getBuffer(libraryId).filesAdded.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('unlink', (filePath) => {
|
||||
this._getBuffer(libraryId).filesRemoved.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('change', (filePath) => {
|
||||
this._getBuffer(libraryId).filesChanged.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('addDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsAdded.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('unlinkDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsRemoved.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('error', (error) => {
|
||||
console.error(`Watcher error for ${library.name}:`, error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
console.log(`File watcher ready for: ${library.name}`);
|
||||
});
|
||||
|
||||
this.watchers.set(libraryId, watcher);
|
||||
}
|
||||
|
||||
// 停止监控
|
||||
unwatch(libraryId) {
|
||||
const watcher = this.watchers.get(libraryId);
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
this.watchers.delete(libraryId);
|
||||
console.log(`Stopped file watcher for library: ${libraryId}`);
|
||||
}
|
||||
|
||||
// 清除防抖定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const timerObj = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(timerObj.timer);
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}
|
||||
|
||||
// 清空缓冲区
|
||||
if (this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.delete(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 停止所有监控
|
||||
unwatchAll() {
|
||||
for (const libraryId of this.watchers.keys()) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取监控状态
|
||||
isWatching(libraryId) {
|
||||
return this.watchers.has(libraryId);
|
||||
}
|
||||
|
||||
// 获取所有正在监控的库
|
||||
getWatchedLibraries() {
|
||||
return Array.from(this.watchers.keys());
|
||||
}
|
||||
}
|
||||
|
||||
// 单例模式
|
||||
const fileWatcher = new FileWatcher();
|
||||
|
||||
module.exports = fileWatcher;
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* 扫描状态管理器
|
||||
* 支持扫描的停止、继续和持久化
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
class ScanManager {
|
||||
constructor() {
|
||||
// 每个素材库的扫描状态(内存)
|
||||
this.scanStates = new Map();
|
||||
// 素材库路径映射(用于持久化)
|
||||
this.libraryPaths = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册素材库路径(用于持久化)
|
||||
*/
|
||||
registerLibraryPath(libraryId, libraryPath) {
|
||||
this.libraryPaths.set(libraryId, libraryPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取状态文件路径
|
||||
*/
|
||||
getStateFilePath(libraryId) {
|
||||
const libraryPath = this.libraryPaths.get(libraryId);
|
||||
if (!libraryPath) return null;
|
||||
return path.join(libraryPath, '.flypic', 'scan-state.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存状态到文件(轻量:只保存关键信息)
|
||||
*/
|
||||
saveState(libraryId) {
|
||||
const stateFile = this.getStateFilePath(libraryId);
|
||||
if (!stateFile) return;
|
||||
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (!state || state.status === 'idle') {
|
||||
// 删除状态文件
|
||||
try {
|
||||
if (fs.existsSync(stateFile)) {
|
||||
fs.unlinkSync(stateFile);
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const saveData = {
|
||||
status: state.status,
|
||||
progress: state.progress,
|
||||
pendingCount: state.pendingFiles?.length || 0,
|
||||
// 只保存文件相对路径,不保存完整路径列表(太大)
|
||||
savedAt: Date.now()
|
||||
};
|
||||
fs.writeFileSync(stateFile, JSON.stringify(saveData, null, 2));
|
||||
} catch (e) {
|
||||
console.error('Failed to save scan state:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载状态
|
||||
*/
|
||||
loadState(libraryId) {
|
||||
const stateFile = this.getStateFilePath(libraryId);
|
||||
if (!stateFile || !fs.existsSync(stateFile)) return null;
|
||||
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(stateFile, 'utf8'));
|
||||
// 状态超过 24 小时视为过期
|
||||
if (Date.now() - data.savedAt > 24 * 60 * 60 * 1000) {
|
||||
fs.unlinkSync(stateFile);
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态(优先内存,其次文件)
|
||||
*/
|
||||
getState(libraryId) {
|
||||
// 先检查内存中的状态
|
||||
const memState = this.scanStates.get(libraryId);
|
||||
if (memState) return memState;
|
||||
|
||||
// 尝试从文件加载(应用重启后的恢复)
|
||||
const fileState = this.loadState(libraryId);
|
||||
if (fileState && fileState.status === 'paused') {
|
||||
// 重建内存状态(不含 pendingFiles,需要重新扫描确定)
|
||||
const restored = {
|
||||
status: 'paused',
|
||||
progress: fileState.progress,
|
||||
pendingFiles: [], // 无法恢复完整列表,需要继续扫描时重新计算
|
||||
processedCount: fileState.progress?.current || 0,
|
||||
abortController: { aborted: true },
|
||||
needsRescan: true // 标记需要重新扫描
|
||||
};
|
||||
this.scanStates.set(libraryId, restored);
|
||||
return restored;
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'idle',
|
||||
progress: null,
|
||||
pendingFiles: [],
|
||||
processedCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始扫描
|
||||
*/
|
||||
startScan(libraryId, totalFiles) {
|
||||
this.scanStates.set(libraryId, {
|
||||
status: 'scanning',
|
||||
progress: { current: 0, total: totalFiles, percent: 0 },
|
||||
pendingFiles: [],
|
||||
processedCount: 0,
|
||||
abortController: { aborted: false }
|
||||
});
|
||||
return this.scanStates.get(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新进度
|
||||
*/
|
||||
updateProgress(libraryId, current, total) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.progress = {
|
||||
current,
|
||||
total,
|
||||
percent: Math.round((current / total) * 100)
|
||||
};
|
||||
state.processedCount = current;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
*/
|
||||
stopScan(libraryId, pendingFiles = []) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.status = 'paused';
|
||||
state.pendingFiles = pendingFiles;
|
||||
state.abortController.aborted = true;
|
||||
// 持久化状态
|
||||
this.saveState(libraryId);
|
||||
console.log(`⏸️ Scan paused for ${libraryId}, ${pendingFiles.length} files pending`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否应该停止
|
||||
*/
|
||||
shouldStop(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.abortController?.aborted || false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取待处理文件
|
||||
*/
|
||||
getPendingFiles(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.pendingFiles || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复扫描
|
||||
*/
|
||||
resumeScan(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state && state.status === 'paused') {
|
||||
const pendingFiles = [...state.pendingFiles]; // 复制一份
|
||||
state.status = 'scanning';
|
||||
state.abortController = { aborted: false };
|
||||
state.pendingFiles = []; // 清空待处理列表
|
||||
console.log(`▶️ Scan resumed for ${libraryId}, ${pendingFiles.length} files to process`);
|
||||
return pendingFiles;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成扫描
|
||||
*/
|
||||
completeScan(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
if (state) {
|
||||
state.status = 'idle';
|
||||
state.pendingFiles = [];
|
||||
state.progress = null;
|
||||
}
|
||||
// 清除持久化状态
|
||||
this.saveState(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否正在扫描
|
||||
*/
|
||||
isScanning(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.status === 'scanning';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否已暂停
|
||||
*/
|
||||
isPaused(libraryId) {
|
||||
const state = this.scanStates.get(libraryId);
|
||||
return state?.status === 'paused';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除素材库状态(删除素材库时调用)
|
||||
*/
|
||||
clearState(libraryId) {
|
||||
this.scanStates.delete(libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有空闲状态(内存清理)
|
||||
*/
|
||||
cleanupIdleStates() {
|
||||
for (const [libraryId, state] of this.scanStates.entries()) {
|
||||
if (state.status === 'idle') {
|
||||
this.scanStates.delete(libraryId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 单例
|
||||
const scanManager = new ScanManager();
|
||||
|
||||
module.exports = scanManager;
|
||||
@@ -0,0 +1,723 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { glob } = require('glob');
|
||||
const {
|
||||
isImageFile,
|
||||
getFileType,
|
||||
calculateFileHash,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails
|
||||
} = require('./thumbnail');
|
||||
const scanManager = require('./scanManager');
|
||||
|
||||
/**
|
||||
* Get all image files in a directory
|
||||
*/
|
||||
async function getAllImageFiles(libraryPath) {
|
||||
// 支持所有文件格式(使用通配符 *.*)
|
||||
const pattern = path.join(libraryPath, '**', '*.*').replace(/\\/g, '/');
|
||||
const files = await glob(pattern, {
|
||||
nodir: true,
|
||||
nocase: true, // 大小写不敏感(Windows/macOS)
|
||||
ignore: ['**/.flypic/**', '**/node_modules/**']
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a folder and its parents exist in DB
|
||||
*/
|
||||
function ensureFolderChain(db, folderPath) {
|
||||
if (!folderPath || folderPath === '.' || folderPath === '') return;
|
||||
let current = folderPath.replace(/\\/g, '/');
|
||||
const visited = new Set();
|
||||
while (current && current !== '.' && !visited.has(current)) {
|
||||
visited.add(current);
|
||||
const parent = path.posix.dirname(current);
|
||||
const name = current.split('/').pop();
|
||||
const existing = db.getFolderByPath(current);
|
||||
if (!existing) {
|
||||
db.insertFolder({
|
||||
path: current,
|
||||
parent_path: parent === '.' ? '' : (parent === current ? '' : parent),
|
||||
name,
|
||||
image_count: 0
|
||||
});
|
||||
}
|
||||
if (parent === current) break;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply changes from file system events quickly without full rescan
|
||||
* events = {
|
||||
* filesAdded: [relPath],
|
||||
* filesChanged: [relPath],
|
||||
* filesRemoved: [relPath],
|
||||
* dirsAdded: [relDir],
|
||||
* dirsRemoved: [relDir]
|
||||
* }
|
||||
*/
|
||||
async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
try {
|
||||
// Normalize helper: 统一使用正斜杠,与数据库记录格式一致
|
||||
const norm = (p) => path.normalize(p).replace(/\\/g, '/');
|
||||
|
||||
const affectedFolders = new Set();
|
||||
const results = { added: 0, modified: 0, deleted: 0, foldersAdded: 0, foldersRemoved: 0 };
|
||||
|
||||
// Handle directory additions (ensure chain exists)
|
||||
for (const dir of (events.dirsAdded || [])) {
|
||||
const d = norm(dir);
|
||||
ensureFolderChain(db, d);
|
||||
results.foldersAdded++;
|
||||
// update parents too
|
||||
let cur = d;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file additions
|
||||
for (const file of (events.filesAdded || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const folder = path.dirname(rel);
|
||||
ensureFolderChain(db, folder);
|
||||
await processImage(full, libraryPath, db);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.added++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing added file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file changes
|
||||
for (const file of (events.filesChanged || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await processImage(full, libraryPath, db);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
results.modified++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing changed file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file removals
|
||||
for (const file of (events.filesRemoved || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
db.deleteImage(rel);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.deleted++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle directory removals (bulk delete)
|
||||
for (const dir of (events.dirsRemoved || [])) {
|
||||
try {
|
||||
const d = norm(dir);
|
||||
// delete images and folders under this dir
|
||||
db.deleteImagesByFolderPrefix(d);
|
||||
db.deleteFoldersByPrefix(d);
|
||||
const parent = path.dirname(d);
|
||||
if (parent && parent !== '.') affectedFolders.add(parent);
|
||||
results.foldersRemoved++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting directory ${dir}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Update counts for all affected folders
|
||||
affectedFolders.forEach((folderPath) => {
|
||||
if (folderPath && folderPath !== '.') {
|
||||
try {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
} catch (error) {
|
||||
console.error(`Error updating folder count ${folderPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error in applyChangesFromEvents:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get folder structure
|
||||
*/
|
||||
async function getFolderStructure(libraryPath) {
|
||||
const folders = [];
|
||||
|
||||
function scanDir(dirPath, parentPath = '') {
|
||||
const items = fs.readdirSync(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const item of items) {
|
||||
if (item.isDirectory() && !item.name.startsWith('.')) {
|
||||
const fullPath = path.join(dirPath, item.name);
|
||||
const relativePath = path.relative(libraryPath, fullPath);
|
||||
const relativePathUnix = relativePath.replace(/\\/g, '/');
|
||||
const parentUnix = (parentPath || '').replace(/\\/g, '/');
|
||||
|
||||
folders.push({
|
||||
path: relativePathUnix,
|
||||
parent_path: parentUnix,
|
||||
name: item.name,
|
||||
image_count: 0
|
||||
});
|
||||
|
||||
scanDir(fullPath, relativePathUnix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scanDir(libraryPath);
|
||||
return folders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single image file
|
||||
*/
|
||||
/**
|
||||
* Process a single image file
|
||||
* @param {boolean} dryRun - If true, return data instead of inserting into DB (for batch write)
|
||||
*/
|
||||
async function processImage(imagePath, libraryPath, db, dryRun = false) {
|
||||
try {
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
const filename = path.basename(imagePath);
|
||||
const folderRaw = path.dirname(relativePath);
|
||||
const folder = folderRaw === '.' ? '' : folderRaw.replace(/\\/g, '/');
|
||||
|
||||
// Check if image already exists in database
|
||||
const existing = db.getImageByPath(relativePath.replace(/\\/g, '/'));
|
||||
const currentHash = calculateFileHash(imagePath);
|
||||
|
||||
// For unchanged files, check whether thumbnails need upgrade/regeneration
|
||||
let needRegenThumbs = false;
|
||||
if (existing) {
|
||||
const flypicDir = path.join(libraryPath, '.flypic');
|
||||
const filenameOnly = (existing.thumbnail_path || '').replace(/\\/g, '/').split('/').pop();
|
||||
if (filenameOnly) {
|
||||
// Calculate sharded path
|
||||
const hash = filenameOnly.replace(/\.[^/.]+$/, ""); // remove extension
|
||||
const shard1 = hash.slice(0, 2);
|
||||
// New structure: .flypic/thumbnails/ab/hash.webp
|
||||
const expectedPath = path.join(flypicDir, 'thumbnails', shard1, filenameOnly);
|
||||
|
||||
// 需要重建的情况:新结构文件不存在
|
||||
if (!fs.existsSync(expectedPath)) {
|
||||
needRegenThumbs = true;
|
||||
}
|
||||
} else {
|
||||
needRegenThumbs = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip only if unchanged and thumbnails are up-to-date
|
||||
if (existing && existing.file_hash === currentHash && !needRegenThumbs) {
|
||||
return { status: 'skipped', path: relativePath };
|
||||
}
|
||||
|
||||
// Get image metadata
|
||||
const metadata = await getImageMetadata(imagePath);
|
||||
if (!metadata) {
|
||||
return { status: 'error', path: relativePath, error: 'Failed to read metadata' };
|
||||
}
|
||||
|
||||
// Generate thumbnails (also for unchanged files when thumbnails missing/outdated)
|
||||
const thumbnails = await generateImageThumbnails(imagePath, libraryPath);
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
// 使用缩略图的实际尺寸(对于视频/PSD,这是提取后的真实尺寸)
|
||||
const actualWidth = thumbnails.width || metadata.width;
|
||||
const actualHeight = thumbnails.height || metadata.height;
|
||||
|
||||
const imageData = {
|
||||
path: relativePath.replace(/\\/g, '/'),
|
||||
filename: filename,
|
||||
folder: folder,
|
||||
size: metadata.size,
|
||||
width: actualWidth,
|
||||
height: actualHeight,
|
||||
format: metadata.format,
|
||||
file_type: fileType,
|
||||
created_at: Math.floor(metadata.created_at),
|
||||
modified_at: Math.floor(metadata.modified_at),
|
||||
file_hash: currentHash,
|
||||
thumbnail_path: thumbnails.thumbnail_path,
|
||||
thumbnail_size: thumbnails.thumbnail_size
|
||||
};
|
||||
|
||||
if (dryRun) {
|
||||
return { status: 'processed', path: relativePath, data: imageData };
|
||||
}
|
||||
|
||||
// Insert/update in database
|
||||
db.insertImage(imageData);
|
||||
|
||||
return { status: 'processed', path: relativePath };
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', imagePath, error);
|
||||
return { status: 'error', path: imagePath, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan library and update database
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @param {object} db - 数据库实例
|
||||
* @param {function} onProgress - 进度回调
|
||||
* @param {string} libraryId - 素材库ID(用于停止控制)
|
||||
* @param {Array} resumeFiles - 继续扫描时的待处理文件列表
|
||||
*/
|
||||
/**
|
||||
* Scan library and update database
|
||||
* @param {string} libraryPath - 素材库路径
|
||||
* @param {object} db - 数据库实例
|
||||
* @param {function} onProgress - 进度回调
|
||||
* @param {string} libraryId - 素材库ID(用于停止控制)
|
||||
* @param {Array} resumeFiles - 继续扫描时的待处理文件列表
|
||||
*/
|
||||
async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resumeFiles = null) {
|
||||
try {
|
||||
let files;
|
||||
|
||||
// 动态导入 p-limit
|
||||
const pLimit = (await import('p-limit')).default;
|
||||
|
||||
// 根据 CPU 核心数动态调整并发数
|
||||
const os = require('os');
|
||||
const cpuCount = os.cpus().length;
|
||||
// 默认并发数:核心数 - 1,最小 4,最大 16
|
||||
const concurrency = Math.max(4, Math.min(16, cpuCount - 1));
|
||||
const limit = pLimit(concurrency);
|
||||
|
||||
console.log(`🚀 Starting scan with concurrency: ${concurrency} (CPU cores: ${cpuCount})`);
|
||||
|
||||
if (resumeFiles && resumeFiles.length > 0) {
|
||||
// 继续扫描:使用待处理文件列表
|
||||
files = resumeFiles;
|
||||
console.log(`▶️ Resuming scan with ${files.length} pending files`);
|
||||
} else {
|
||||
// 新扫描:获取所有文件
|
||||
files = await getAllImageFiles(libraryPath);
|
||||
console.log(`Found ${files.length} images in library`);
|
||||
|
||||
// Get folder structure
|
||||
const folders = await getFolderStructure(libraryPath);
|
||||
// 使用事务批量插入文件夹
|
||||
const insertFolders = db.db.transaction((folders) => {
|
||||
for (const folder of folders) db.insertFolder(folder);
|
||||
});
|
||||
insertFolders(folders);
|
||||
}
|
||||
|
||||
const total = files.length;
|
||||
|
||||
// 初始化扫描状态
|
||||
if (libraryId) {
|
||||
scanManager.startScan(libraryId, total);
|
||||
}
|
||||
|
||||
const results = {
|
||||
processed: 0,
|
||||
skipped: 0,
|
||||
errors: 0,
|
||||
stopped: false
|
||||
};
|
||||
|
||||
const startTime = Date.now();
|
||||
let processedCount = 0;
|
||||
|
||||
// 批量写入缓冲区
|
||||
let writeBuffer = [];
|
||||
const WRITE_BATCH_SIZE = 100; // 每 100 条写入一次数据库
|
||||
|
||||
// 批量写入函数(事务)
|
||||
const batchWrite = db.db.transaction((items) => {
|
||||
for (const item of items) {
|
||||
if (item.status === 'processed' && item.data) {
|
||||
db.insertImage(item.data);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 处理单个文件的包装函数
|
||||
const processFile = async (file) => {
|
||||
// 检查是否需要停止
|
||||
if (libraryId && scanManager.shouldStop(libraryId)) {
|
||||
return { status: 'stopped', file };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await processImage(file, libraryPath, db, true); // true = dryRun (不直接写入DB)
|
||||
return result;
|
||||
} catch (error) {
|
||||
return { status: 'error', path: file, error: error.message };
|
||||
}
|
||||
};
|
||||
|
||||
// 创建所有任务
|
||||
const tasks = files.map(file => limit(async () => {
|
||||
// 如果已经停止,直接返回
|
||||
if (results.stopped) return;
|
||||
|
||||
const result = await processFile(file);
|
||||
|
||||
if (result.status === 'stopped') {
|
||||
results.stopped = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新统计
|
||||
if (result.status === 'processed') results.processed++;
|
||||
else if (result.status === 'skipped') results.skipped++;
|
||||
else if (result.status === 'error') results.errors++;
|
||||
|
||||
// 添加到写入缓冲区
|
||||
if (result.status === 'processed') {
|
||||
writeBuffer.push(result);
|
||||
|
||||
// 缓冲区满,执行批量写入
|
||||
if (writeBuffer.length >= WRITE_BATCH_SIZE) {
|
||||
batchWrite(writeBuffer);
|
||||
writeBuffer = [];
|
||||
}
|
||||
}
|
||||
|
||||
processedCount++;
|
||||
|
||||
// 报告进度 (每完成 10 个文件报告一次,避免过于频繁)
|
||||
if (processedCount % 10 === 0 || processedCount === total) {
|
||||
const current = processedCount;
|
||||
|
||||
if (libraryId) {
|
||||
scanManager.updateProgress(libraryId, current, total);
|
||||
}
|
||||
|
||||
if (onProgress) {
|
||||
const elapsed = Date.now() - startTime;
|
||||
const avgTimePerImage = elapsed / current;
|
||||
const remaining = total - current;
|
||||
const estimatedTimeLeft = Math.round((remaining * avgTimePerImage) / 1000);
|
||||
|
||||
onProgress({
|
||||
total,
|
||||
current,
|
||||
percent: Math.round((current / total) * 100),
|
||||
currentFile: file,
|
||||
estimatedTimeLeft,
|
||||
canStop: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 性能日志
|
||||
if (processedCount > 0 && processedCount % 1000 === 0) {
|
||||
const elapsed = (Date.now() - startTime) / 1000;
|
||||
const speed = processedCount / elapsed;
|
||||
console.log(`⚡ Performance: ${speed.toFixed(1)} images/sec, ${processedCount}/${total} completed`);
|
||||
}
|
||||
}));
|
||||
|
||||
// 等待所有任务完成
|
||||
await Promise.all(tasks);
|
||||
|
||||
// 写入剩余的缓冲区数据
|
||||
if (writeBuffer.length > 0) {
|
||||
batchWrite(writeBuffer);
|
||||
writeBuffer = [];
|
||||
}
|
||||
|
||||
// 处理停止情况
|
||||
if (results.stopped) {
|
||||
const pendingFiles = files.slice(processedCount);
|
||||
scanManager.stopScan(libraryId, pendingFiles);
|
||||
console.log(`⏸️ Scan stopped at ${processedCount}/${total}, ${pendingFiles.length} files pending`);
|
||||
return results;
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000;
|
||||
console.log(`✅ Scan completed in ${totalTime.toFixed(1)}s, speed: ${(total / totalTime).toFixed(1)} images/sec`);
|
||||
|
||||
// Update folder image counts
|
||||
db.updateAllFolderCounts();
|
||||
|
||||
// 标记扫描完成
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
|
||||
console.log('Scan complete:', results);
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error scanning library:', error);
|
||||
if (libraryId) {
|
||||
scanManager.completeScan(libraryId);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync library (incremental scan)
|
||||
*/
|
||||
async function syncLibrary(libraryPath, db, forceRebuildFolders = false, onProgress = null) {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Get all current files (统一使用正斜杠)
|
||||
const currentFiles = await getAllImageFiles(libraryPath);
|
||||
const currentPaths = new Set(
|
||||
currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/'))
|
||||
);
|
||||
|
||||
// Get database files (已经是正斜杠格式)
|
||||
const dbImages = db.getAllImages();
|
||||
const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/')));
|
||||
|
||||
// Find new, modified, and deleted files
|
||||
const toAdd = [...currentPaths].filter(p => !dbPaths.has(p));
|
||||
const toCheck = [...currentPaths].filter(p => dbPaths.has(p));
|
||||
let toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
console.log(`Sync: ${toAdd.length} new, ${toCheck.length} to check, ${toDelete.length} deleted`);
|
||||
|
||||
// 安全检查:如果要删除的文件数量超过数据库中文件的50%,可能是路径匹配问题
|
||||
if (toDelete.length > 0 && dbImages.length > 0) {
|
||||
const deleteRatio = toDelete.length / dbImages.length;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:要删除 ${toDelete.length}/${dbImages.length} (${(deleteRatio * 100).toFixed(1)}%) 的文件,这可能是路径匹配问题,跳过删除操作`);
|
||||
console.log('示例 currentPath:', [...currentPaths].slice(0, 3));
|
||||
console.log('示例 dbPath:', [...dbPaths].slice(0, 3));
|
||||
// 清空 toDelete,不执行删除
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
|
||||
const total = toAdd.length + toDelete.length;
|
||||
let processed = 0;
|
||||
|
||||
// Process new files in batches
|
||||
const batchSize = 100;
|
||||
for (let i = 0; i < toAdd.length; i += batchSize) {
|
||||
const batch = toAdd.slice(i, i + batchSize);
|
||||
await Promise.all(
|
||||
batch.map(relativePath => {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
return processImage(fullPath, libraryPath, db);
|
||||
})
|
||||
);
|
||||
|
||||
processed += batch.length;
|
||||
|
||||
// 报告进度
|
||||
if (onProgress && total > 0) {
|
||||
onProgress({
|
||||
total,
|
||||
current: processed,
|
||||
percent: Math.round((processed / total) * 100),
|
||||
currentFile: batch[batch.length - 1]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check modified files in batches (只检查hash,不重新处理)
|
||||
const modifiedCount = toCheck.filter(relativePath => {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
const existing = db.getImageByPath(relativePath);
|
||||
const currentHash = calculateFileHash(fullPath);
|
||||
return existing.file_hash !== currentHash;
|
||||
}).length;
|
||||
|
||||
console.log(`Found ${modifiedCount} modified files (skipped, hash unchanged)`);
|
||||
|
||||
// Delete removed files
|
||||
for (const relativePath of toDelete) {
|
||||
db.deleteImage(relativePath);
|
||||
// TODO: Clean up thumbnail files
|
||||
}
|
||||
|
||||
// Rebuild folder structure if there are changes or forced
|
||||
if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) {
|
||||
console.log('Rebuilding folder structure...');
|
||||
|
||||
// Get current folder structure from file system
|
||||
const currentFolders = await getFolderStructure(libraryPath);
|
||||
|
||||
// Get existing folders from database
|
||||
const dbFolders = db.getAllFolders();
|
||||
const dbFolderPaths = new Set(dbFolders.map(f => f.path));
|
||||
|
||||
// Find new and deleted folders
|
||||
const currentFolderPaths = new Set(currentFolders.map(f => f.path));
|
||||
const foldersToAdd = currentFolders.filter(f => !dbFolderPaths.has(f.path));
|
||||
const foldersToDelete = dbFolders.filter(f => !currentFolderPaths.has(f.path));
|
||||
|
||||
// Add new folders
|
||||
foldersToAdd.forEach(folder => {
|
||||
db.insertFolder(folder);
|
||||
});
|
||||
|
||||
// Delete removed folders
|
||||
foldersToDelete.forEach(folder => {
|
||||
db.deleteFolder(folder.path);
|
||||
});
|
||||
|
||||
console.log(`Folders: +${foldersToAdd.length}, -${foldersToDelete.length}`);
|
||||
|
||||
// Update folder image counts
|
||||
console.log('Updating folder image counts...');
|
||||
const affectedFolders = new Set();
|
||||
|
||||
// Collect all affected folders (including parent folders)
|
||||
[...toAdd, ...toDelete].forEach(relativePath => {
|
||||
let folderPath = path.dirname(relativePath);
|
||||
|
||||
// Add current folder and all parent folders
|
||||
while (folderPath && folderPath !== '.') {
|
||||
affectedFolders.add(folderPath);
|
||||
const parent = path.dirname(folderPath);
|
||||
if (parent === folderPath) break; // Reached root
|
||||
folderPath = parent;
|
||||
}
|
||||
});
|
||||
|
||||
// Update counts for all affected folders
|
||||
affectedFolders.forEach(folderPath => {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
});
|
||||
|
||||
console.log(`Updated ${affectedFolders.size} folder counts`);
|
||||
}
|
||||
|
||||
const totalTime = (Date.now() - startTime) / 1000;
|
||||
console.log(`✅ Sync completed in ${totalTime.toFixed(1)}s`);
|
||||
|
||||
return {
|
||||
added: toAdd.length,
|
||||
modified: modifiedCount,
|
||||
deleted: toDelete.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error syncing library:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick sync - 只检查新增/删除,不检查修改(用于启动时快速检测)
|
||||
*/
|
||||
async function quickSync(libraryPath, db) {
|
||||
const startTime = Date.now();
|
||||
|
||||
// 获取当前文件(统一使用正斜杠)
|
||||
const currentFiles = await getAllImageFiles(libraryPath);
|
||||
const currentPaths = new Set(
|
||||
currentFiles.map(file => path.relative(libraryPath, file).replace(/\\/g, '/'))
|
||||
);
|
||||
|
||||
// 获取数据库文件
|
||||
const dbImages = db.getAllImages();
|
||||
const dbPaths = new Set(dbImages.map(img => (img.path || '').replace(/\\/g, '/')));
|
||||
|
||||
// 只检查新增和删除(不检查修改)
|
||||
const toAdd = [...currentPaths].filter(p => !dbPaths.has(p));
|
||||
let toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
// 安全检查
|
||||
if (toDelete.length > 0 && dbImages.length > 0) {
|
||||
const deleteRatio = toDelete.length / dbImages.length;
|
||||
if (deleteRatio > 0.5 && toDelete.length > 10) {
|
||||
console.warn(`⚠️ 安全检查:跳过删除 ${toDelete.length} 个文件`);
|
||||
toDelete = [];
|
||||
}
|
||||
}
|
||||
|
||||
// 处理新增文件
|
||||
for (const relativePath of toAdd) {
|
||||
try {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
// 确保文件夹链存在
|
||||
const folder = path.dirname(relativePath).replace(/\\/g, '/');
|
||||
if (folder && folder !== '.') {
|
||||
ensureFolderChain(db, folder);
|
||||
}
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
} catch (err) {
|
||||
console.error(`Error adding ${relativePath}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 删除已移除的文件
|
||||
for (const relativePath of toDelete) {
|
||||
db.deleteImage(relativePath);
|
||||
}
|
||||
|
||||
// 如果有变化,更新所有文件夹的图片数量
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
db.updateAllFolderCounts();
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - startTime;
|
||||
if (toAdd.length > 0 || toDelete.length > 0) {
|
||||
console.log(`Quick sync: +${toAdd.length} -${toDelete.length} (${elapsed}ms)`);
|
||||
}
|
||||
|
||||
return { added: toAdd.length, deleted: toDelete.length };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getAllImageFiles,
|
||||
getFolderStructure,
|
||||
processImage,
|
||||
scanLibrary,
|
||||
syncLibrary,
|
||||
quickSync,
|
||||
applyChangesFromEvents
|
||||
};
|
||||
@@ -0,0 +1,642 @@
|
||||
const sharp = require('sharp');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 支持的文件格式(确定可以生成缩略图的)
|
||||
const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg'];
|
||||
|
||||
// 文件类型分类(用于显示和占位图)
|
||||
const FILE_CATEGORIES = {
|
||||
// 图片类
|
||||
image: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif', 'avif', 'heif', 'heic', 'svg', 'ico', 'raw', 'cr2', 'nef', 'dng'],
|
||||
|
||||
// 视频类
|
||||
video: ['mp4', 'webm', 'mov', 'avi', 'mkv', 'flv', 'm4v', 'wmv', 'mpg', 'mpeg', '3gp', 'ts', 'vob', 'ogv'],
|
||||
|
||||
// 音频类
|
||||
audio: ['mp3', 'wav', 'flac', 'aac', 'm4a', 'ogg', 'wma', 'ape', 'alac', 'opus', 'aiff'],
|
||||
|
||||
// 文档类
|
||||
document: [
|
||||
'pdf', 'txt', 'md', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
|
||||
'rtf', 'odt', 'ods', 'odp', 'csv', 'pages', 'numbers', 'key'
|
||||
],
|
||||
|
||||
// 设计类
|
||||
design: ['psd', 'ai', 'sketch', 'xd', 'fig', 'figma', 'indd', 'eps', 'cdr', 'dwg']
|
||||
};
|
||||
|
||||
// 为了兼容旧代码
|
||||
const SUPPORTED_FORMATS = {
|
||||
image: IMAGE_FORMATS,
|
||||
video: FILE_CATEGORIES.video,
|
||||
document: FILE_CATEGORIES.document,
|
||||
special: FILE_CATEGORIES.design
|
||||
};
|
||||
|
||||
// 所有支持的格式(扁平化,兼容所有文件)
|
||||
const ALL_FORMATS = [
|
||||
...FILE_CATEGORIES.image,
|
||||
...FILE_CATEGORIES.video,
|
||||
...FILE_CATEGORIES.audio,
|
||||
...FILE_CATEGORIES.document,
|
||||
...FILE_CATEGORIES.design
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取文件类型分类
|
||||
*/
|
||||
function getFileType(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
|
||||
// 检查所有分类
|
||||
if (FILE_CATEGORIES.image.includes(ext)) return 'image';
|
||||
if (FILE_CATEGORIES.video.includes(ext)) return 'video';
|
||||
if (FILE_CATEGORIES.audio.includes(ext)) return 'audio';
|
||||
if (FILE_CATEGORIES.document.includes(ext)) return 'document';
|
||||
if (FILE_CATEGORIES.design.includes(ext)) return 'design';
|
||||
|
||||
// 未知类型也兼容,归类为 other
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否可以用 Sharp 生成缩略图
|
||||
*/
|
||||
function canGenerateThumbnail(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
return IMAGE_FORMATS.includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is supported
|
||||
*/
|
||||
function isImageFile(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
return ALL_FORMATS.includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate file hash for change detection
|
||||
*/
|
||||
function calculateFileHash(filePath) {
|
||||
const fileBuffer = fs.readFileSync(filePath);
|
||||
const hashSum = crypto.createHash('md5');
|
||||
hashSum.update(fileBuffer);
|
||||
return hashSum.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thumbnail configuration based on original image size
|
||||
* 分阶段策略:根据原图大小使用不同的缩略图尺寸和质量
|
||||
*
|
||||
* 策略说明:
|
||||
* - 小图(<1MP):保持原尺寸或轻微缩小,高质量
|
||||
* - 中图(1-4MP):缩略图 200px 高,高质量
|
||||
* - 大图(4-12MP):缩略图 250px 高,中高质量
|
||||
* - 超大图(>12MP):缩略图 300px 高,中等质量
|
||||
*/
|
||||
function getThumbnailConfig(originalWidth, originalHeight, targetHeight = 200) {
|
||||
const originalPixels = originalWidth * originalHeight;
|
||||
const aspectRatio = originalWidth / originalHeight;
|
||||
|
||||
let finalHeight, finalQuality, targetSize;
|
||||
|
||||
// 分阶段策略 - 提高质量,扩大文件大小
|
||||
if (originalPixels < 1000000) {
|
||||
// 小图 <1MP(如 1000x1000):保持较小尺寸,极高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 95;
|
||||
targetSize = { min: 80 * 1024, max: 240 * 1024 }; // 80-240KB
|
||||
}
|
||||
else if (originalPixels < 4000000) {
|
||||
// 中图 1-4MP(如 2000x2000):标准尺寸,极高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 93;
|
||||
targetSize = { min: 120 * 1024, max: 300 * 1024 }; // 120-300KB
|
||||
}
|
||||
else if (originalPixels < 12000000) {
|
||||
// 大图 4-12MP(如 4000x3000):增大尺寸,高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 91;
|
||||
targetSize = { min: 160 * 1024, max: 400 * 1024 }; // 160-400KB
|
||||
}
|
||||
else {
|
||||
// 超大图 >12MP(如 6000x4000):更大尺寸,高质量
|
||||
finalHeight = Math.min(targetHeight, originalHeight);
|
||||
finalQuality = 89;
|
||||
targetSize = { min: 200 * 1024, max: 500 * 1024 }; // 200-500KB
|
||||
}
|
||||
|
||||
const finalWidth = Math.round(aspectRatio * finalHeight);
|
||||
|
||||
// 计算原图大小(MP)
|
||||
const megaPixels = (originalPixels / 1000000).toFixed(1);
|
||||
|
||||
return {
|
||||
width: finalWidth,
|
||||
height: finalHeight,
|
||||
quality: finalQuality,
|
||||
targetSize: targetSize,
|
||||
format: 'webp',
|
||||
originalPixels: originalPixels,
|
||||
megaPixels: megaPixels
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for an image with high quality settings
|
||||
*
|
||||
* 核心优化点:
|
||||
* 1. 禁用 smartSubsample,保持色彩锐度(关键!)
|
||||
* 2. 使用更强的 unsharp mask 锐化
|
||||
* 3. 固定高质量 Q96,不动态调整
|
||||
* 4. 不修改色彩(饱和度/亮度),保持原图风格
|
||||
*/
|
||||
async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
|
||||
try {
|
||||
// 先读取文件到 Buffer,避免 Sharp 锁定文件句柄
|
||||
const inputBuffer = fs.readFileSync(inputPath);
|
||||
|
||||
// Get image metadata from buffer
|
||||
const metadata = await sharp(inputBuffer).metadata();
|
||||
const config = getThumbnailConfig(metadata.width, metadata.height, targetHeight);
|
||||
const hasAlpha = Boolean(metadata.hasAlpha);
|
||||
|
||||
// 计算缩小比例,用于调整锐化强度
|
||||
const downscaleRatio = metadata.height ? (metadata.height / config.height) : 1;
|
||||
|
||||
// 锐化参数:根据缩小比例动态调整
|
||||
// sharpen(sigma, flat, jagged) - sigma: 高斯模糊半径, flat: 平坦区域锐化, jagged: 边缘锐化
|
||||
let sharpSigma, sharpFlat, sharpJagged;
|
||||
if (downscaleRatio >= 4) {
|
||||
// 大幅缩小(如 4000px → 300px):强锐化
|
||||
sharpSigma = 1.2;
|
||||
sharpFlat = 1.0;
|
||||
sharpJagged = 2.0;
|
||||
} else if (downscaleRatio >= 2) {
|
||||
// 中等缩小:中等锐化
|
||||
sharpSigma = 1.0;
|
||||
sharpFlat = 0.8;
|
||||
sharpJagged = 1.5;
|
||||
} else {
|
||||
// 轻微缩小或不缩小:轻度锐化
|
||||
sharpSigma = 0.8;
|
||||
sharpFlat = 0.5;
|
||||
sharpJagged = 1.0;
|
||||
}
|
||||
|
||||
// 固定高质量 92(平衡清晰度和体积)
|
||||
const quality = 92;
|
||||
|
||||
// 生成缩略图(使用 buffer,不锁定原文件)
|
||||
await sharp(inputBuffer)
|
||||
.rotate() // 按EXIF旋转
|
||||
.resize(config.width, config.height, {
|
||||
fit: 'cover',
|
||||
position: 'center',
|
||||
kernel: 'lanczos3', // 最高质量缩放算法
|
||||
withoutEnlargement: true,
|
||||
fastShrinkOnLoad: false // 禁用快速缩小,保持质量
|
||||
})
|
||||
// 锐化:使用完整的 unsharp mask 参数(不修改色彩)
|
||||
.sharpen({
|
||||
sigma: sharpSigma, // 高斯模糊半径
|
||||
m1: sharpFlat, // 平坦区域锐化强度
|
||||
m2: sharpJagged, // 边缘/锯齿区域锐化强度
|
||||
x1: 2, // 平坦区域阈值
|
||||
y2: 10, // 边缘区域阈值上限
|
||||
y3: 20 // 最大锐化限制
|
||||
})
|
||||
.webp({
|
||||
quality: quality,
|
||||
effort: 4, // 降低 effort,减少编码损失
|
||||
smartSubsample: false, // 关键!禁用色度子采样,保持边缘清晰
|
||||
nearLossless: false, // 禁用近无损(会增加体积但不增加清晰度)
|
||||
preset: 'photo',
|
||||
alphaQuality: hasAlpha ? 100 : undefined
|
||||
})
|
||||
.toFile(outputPath);
|
||||
|
||||
// 获取文件大小
|
||||
const stats = fs.statSync(outputPath);
|
||||
const finalSize = stats.size;
|
||||
|
||||
// 可选:输出详细信息(每100张输出一次,避免日志过多)
|
||||
const shouldLog = Math.random() < 0.01; // 1% 概率输出
|
||||
if (shouldLog) {
|
||||
const sizeKB = (finalSize / 1024).toFixed(1);
|
||||
console.log(`📸 Thumbnail: ${config.megaPixels}MP → ${config.width}x${config.height} (${sizeKB}KB, Q${quality}, ratio ${downscaleRatio.toFixed(1)}x)`);
|
||||
}
|
||||
|
||||
return {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
size: finalSize,
|
||||
quality: quality,
|
||||
originalPixels: config.originalPixels,
|
||||
path: outputPath
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error generating thumbnail:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file metadata (支持所有文件类型)
|
||||
* 优化:优先使用流式读取,避免加载整个文件到内存
|
||||
*/
|
||||
async function getImageMetadata(imagePath) {
|
||||
try {
|
||||
const stats = fs.statSync(imagePath);
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
// 对于图片文件,尝试获取详细元数据
|
||||
if (fileType === 'image') {
|
||||
try {
|
||||
// 优化:直接传入路径,让 sharp 使用流式读取,仅读取头部元数据
|
||||
// 只有在失败时才回退到 Buffer 读取
|
||||
const metadata = await sharp(imagePath).metadata();
|
||||
return {
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
format: metadata.format,
|
||||
size: stats.size,
|
||||
created_at: stats.birthtimeMs,
|
||||
modified_at: stats.mtimeMs
|
||||
};
|
||||
} catch (sharpError) {
|
||||
// Sharp 无法处理某些图片格式(如 SVG)或路径问题,回退到基础信息
|
||||
// console.warn(`Sharp cannot process ${imagePath}, using basic metadata`);
|
||||
}
|
||||
}
|
||||
|
||||
// 对于非图片文件或 Sharp 失败的情况,返回基础信息
|
||||
const ext = path.extname(imagePath).toLowerCase().slice(1);
|
||||
return {
|
||||
width: 640, // 占位图尺寸
|
||||
height: 480,
|
||||
format: ext,
|
||||
size: stats.size,
|
||||
created_at: stats.birthtimeMs,
|
||||
modified_at: stats.mtimeMs
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error getting file metadata:', imagePath, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for a file (image/video/document)
|
||||
* 使用 480px 高度(与 Billfish 一致)
|
||||
*/
|
||||
async function generateImageThumbnails(imagePath, libraryPath) {
|
||||
const flypicDir = path.join(libraryPath, '.flypic');
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
const hash = crypto.createHash('md5').update(relativePath).digest('hex');
|
||||
const fileType = getFileType(imagePath);
|
||||
|
||||
console.log(`📝 Processing file: ${path.basename(imagePath)}, type: ${fileType}`);
|
||||
|
||||
// Sharding: use first 2 chars of hash for subdirectories (e.g. /ab/)
|
||||
const shard1 = hash.slice(0, 2);
|
||||
// 1-level sharding: .flypic/thumbnails/ab/hash.webp
|
||||
const out480 = path.join(flypicDir, 'thumbnails', shard1, `${hash}.webp`);
|
||||
fs.mkdirSync(path.dirname(out480), { recursive: true });
|
||||
|
||||
let thumbnailResult;
|
||||
|
||||
// 根据文件类型生成不同的缩略图
|
||||
const ext = path.extname(imagePath).slice(1).toUpperCase();
|
||||
|
||||
if (fileType === 'image' && canGenerateThumbnail(imagePath)) {
|
||||
// 图片:使用 Sharp 生成真实缩略图
|
||||
thumbnailResult = await generateThumbnail(imagePath, out480, 480);
|
||||
} else if (fileType === 'video') {
|
||||
// 视频:尝试提取封面
|
||||
console.log(`🎬 Extracting video thumbnail for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await extractVideoThumbnail(imagePath, out480);
|
||||
|
||||
// 如果提取失败,生成占位图
|
||||
if (!thumbnailResult) {
|
||||
console.log(`🎬 Generating video placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, 'video', ext);
|
||||
}
|
||||
} else if (fileType === 'design') {
|
||||
// 设计文件:尝试提取嵌入缩略图(仅 PSD)
|
||||
if (ext.toLowerCase() === 'psd') {
|
||||
console.log(`🎨 Extracting PSD thumbnail for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await extractPSDThumbnail(imagePath, out480);
|
||||
}
|
||||
|
||||
// 如果提取失败或不是 PSD,生成占位图
|
||||
if (!thumbnailResult) {
|
||||
console.log(`🎨 Generating design placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, 'design', ext);
|
||||
}
|
||||
} else {
|
||||
// 其他类型(音频/文档/未知):生成占位图
|
||||
console.log(`📦 Generating ${fileType} placeholder for: ${path.basename(imagePath)}`);
|
||||
thumbnailResult = await generatePlaceholderThumbnail(out480, fileType, ext);
|
||||
}
|
||||
|
||||
console.log(`✅ Thumbnail generated: ${path.basename(out480)}, ${thumbnailResult.width}x${thumbnailResult.height}, ${(thumbnailResult.size / 1024).toFixed(1)}KB`);
|
||||
|
||||
return {
|
||||
thumbnail_path: path.relative(flypicDir, out480),
|
||||
thumbnail_size: thumbnailResult.size,
|
||||
width: thumbnailResult.width,
|
||||
height: thumbnailResult.height,
|
||||
file_type: fileType
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 PSD 文件提取嵌入的缩略图
|
||||
*/
|
||||
async function extractPSDThumbnail(psdPath, outputPath) {
|
||||
try {
|
||||
const buffer = fs.readFileSync(psdPath);
|
||||
|
||||
// PSD 文件格式:
|
||||
// 前 4 字节: "8BPS" (签名)
|
||||
// 偏移 26: Image Resources Section
|
||||
// 查找 Resource ID 1036 (缩略图资源)
|
||||
|
||||
if (buffer.toString('utf8', 0, 4) !== '8BPS') {
|
||||
throw new Error('Not a valid PSD file');
|
||||
}
|
||||
|
||||
// 读取 Image Resources Section 长度
|
||||
const colorModeLength = buffer.readUInt32BE(26);
|
||||
const imageResourcesOffset = 26 + 4 + colorModeLength;
|
||||
const imageResourcesLength = buffer.readUInt32BE(imageResourcesOffset);
|
||||
|
||||
let offset = imageResourcesOffset + 4;
|
||||
const endOffset = offset + imageResourcesLength;
|
||||
|
||||
// 查找缩略图资源 (ID 1033 或 1036)
|
||||
while (offset < endOffset) {
|
||||
const signature = buffer.toString('utf8', offset, offset + 4);
|
||||
if (signature !== '8BIM') break;
|
||||
|
||||
const resourceId = buffer.readUInt16BE(offset + 4);
|
||||
const nameLength = buffer.readUInt8(offset + 6);
|
||||
const namePadding = nameLength % 2 === 0 ? nameLength + 2 : nameLength + 1;
|
||||
const dataSize = buffer.readUInt32BE(offset + 6 + namePadding);
|
||||
const dataPadding = dataSize % 2 === 0 ? dataSize : dataSize + 1;
|
||||
|
||||
// 1033 = 缩略图 (旧格式), 1036 = 缩略图 (新格式)
|
||||
if (resourceId === 1033 || resourceId === 1036) {
|
||||
const dataOffset = offset + 6 + namePadding + 4;
|
||||
|
||||
// 跳过前 28 字节的头部信息
|
||||
const jpegOffset = dataOffset + 28;
|
||||
const jpegData = buffer.slice(jpegOffset, jpegOffset + dataSize - 28);
|
||||
|
||||
// 先获取原始缩略图尺寸
|
||||
const metadata = await sharp(jpegData).metadata();
|
||||
console.log(` 📐 PSD embedded thumbnail: ${metadata.width}x${metadata.height}`);
|
||||
|
||||
// 使用高质量缩放,保持宽高比
|
||||
const aspectRatio = metadata.width / metadata.height;
|
||||
const targetHeight = 480;
|
||||
const targetWidth = Math.round(targetHeight * aspectRatio);
|
||||
|
||||
// 根据原始尺寸调整处理策略
|
||||
let resizeOptions, sharpenOptions, webpQuality;
|
||||
|
||||
if (metadata.width >= 1000 || metadata.height >= 1000) {
|
||||
// 高分辨率缩略图(≥1000px):正常缩放
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: true
|
||||
};
|
||||
sharpenOptions = { sigma: 0.8, m1: 0.5, m2: 1.0 };
|
||||
webpQuality = 95;
|
||||
} else if (metadata.width >= 500 || metadata.height >= 500) {
|
||||
// 中等分辨率(500-1000px):轻微放大 + 强锐化
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: false // 允许放大
|
||||
};
|
||||
sharpenOptions = { sigma: 1.2, m1: 1.0, m2: 2.0 }; // 强锐化
|
||||
webpQuality = 96;
|
||||
} else {
|
||||
// 低分辨率(<500px):放大 + 超强锐化
|
||||
resizeOptions = {
|
||||
fit: 'inside',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: false
|
||||
};
|
||||
sharpenOptions = { sigma: 1.5, m1: 1.2, m2: 2.5 }; // 超强锐化
|
||||
webpQuality = 98; // 最高质量
|
||||
}
|
||||
|
||||
await sharp(jpegData)
|
||||
.resize(targetWidth, targetHeight, resizeOptions)
|
||||
.sharpen(sharpenOptions)
|
||||
.webp({
|
||||
quality: webpQuality,
|
||||
effort: 4,
|
||||
smartSubsample: false
|
||||
})
|
||||
.toFile(outputPath);
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
console.log(` ✅ PSD thumbnail extracted: ${(stats.size / 1024).toFixed(1)}KB`);
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
offset += 6 + namePadding + 4 + dataPadding;
|
||||
}
|
||||
|
||||
throw new Error('No thumbnail found in PSD');
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract PSD thumbnail: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从视频提取封面(使用 ffmpeg 或系统工具)
|
||||
* 注意:这需要系统安装 ffmpeg,如果没有则回退到占位图
|
||||
*/
|
||||
async function extractVideoThumbnail(videoPath, outputPath) {
|
||||
try {
|
||||
const { exec } = require('child_process');
|
||||
const util = require('util');
|
||||
const execPromise = util.promisify(exec);
|
||||
|
||||
// 检查是否有 ffmpeg
|
||||
try {
|
||||
await execPromise('ffmpeg -version', { timeout: 2000 });
|
||||
} catch (e) {
|
||||
console.warn(' ⚠️ ffmpeg not found, skipping video thumbnail extraction');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 使用 ffmpeg 提取第 2 秒的帧(避免黑屏)
|
||||
const tempJpg = outputPath.replace('.webp', '_temp.jpg');
|
||||
const ffmpegCmd = `ffmpeg -i "${videoPath}" -ss 00:00:02 -vframes 1 -q:v 2 "${tempJpg}" -y`;
|
||||
|
||||
await execPromise(ffmpegCmd, { timeout: 10000 });
|
||||
|
||||
// 如果生成了 JPG,转换为 WebP
|
||||
if (fs.existsSync(tempJpg)) {
|
||||
// 先获取实际尺寸
|
||||
const metadata = await sharp(tempJpg).metadata();
|
||||
console.log(` 📐 Video frame: ${metadata.width}x${metadata.height}`);
|
||||
|
||||
// 保持宽高比缩放到 480 高度
|
||||
const aspectRatio = metadata.width / metadata.height;
|
||||
const targetHeight = 480;
|
||||
const targetWidth = Math.round(targetHeight * aspectRatio);
|
||||
|
||||
await sharp(tempJpg)
|
||||
.resize(targetWidth, targetHeight, {
|
||||
fit: 'cover',
|
||||
position: 'center',
|
||||
kernel: 'lanczos3',
|
||||
withoutEnlargement: true
|
||||
})
|
||||
.webp({ quality: 92, smartSubsample: false })
|
||||
.toFile(outputPath);
|
||||
|
||||
fs.unlinkSync(tempJpg); // 删除临时 JPG
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
console.log(` ✅ Video thumbnail extracted: ${targetWidth}x${targetHeight}, ${(stats.size / 1024).toFixed(1)}KB`);
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.warn(` ⚠️ Failed to extract video thumbnail: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成占位缩略图(用于视频/文档等)
|
||||
*/
|
||||
async function generatePlaceholderThumbnail(outputPath, type, label) {
|
||||
// 使用 Sharp 生成简单的占位图
|
||||
const width = 640;
|
||||
const height = 480;
|
||||
|
||||
// 不同类型的背景色和图标
|
||||
const typeConfig = {
|
||||
image: {
|
||||
color: { r: 99, g: 102, b: 241 }, // 靛蓝色
|
||||
icon: '🖼️',
|
||||
text: '图片'
|
||||
},
|
||||
video: {
|
||||
color: { r: 59, g: 130, b: 246 }, // 蓝色
|
||||
icon: '🎬',
|
||||
text: '视频'
|
||||
},
|
||||
audio: {
|
||||
color: { r: 236, g: 72, b: 153 }, // 粉色
|
||||
icon: '🎵',
|
||||
text: '音频'
|
||||
},
|
||||
document: {
|
||||
color: { r: 16, g: 185, b: 129 }, // 绿色
|
||||
icon: '📄',
|
||||
text: '文档'
|
||||
},
|
||||
design: {
|
||||
color: { r: 168, g: 85, b: 247 }, // 紫色
|
||||
icon: '🎨',
|
||||
text: '设计'
|
||||
},
|
||||
other: {
|
||||
color: { r: 107, g: 114, b: 128 }, // 灰色
|
||||
icon: '📁',
|
||||
text: '其他'
|
||||
}
|
||||
};
|
||||
|
||||
const config = typeConfig[type] || typeConfig.other;
|
||||
|
||||
const color = config.color;
|
||||
|
||||
// 创建渐变背景 + 图标 + 文件扩展名
|
||||
const svg = `
|
||||
<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:rgb(${color.r},${color.g},${color.b});stop-opacity:0.15" />
|
||||
<stop offset="100%" style="stop-color:rgb(${color.r},${color.g},${color.b});stop-opacity:0.05" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="${width}" height="${height}" fill="url(#grad)"/>
|
||||
<text x="50%" y="35%" font-family="Arial, sans-serif" font-size="100" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.35">
|
||||
${config.icon}
|
||||
</text>
|
||||
<text x="50%" y="55%" font-family="Arial, sans-serif" font-size="48" font-weight="700" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.7">
|
||||
.${label.toLowerCase()}
|
||||
</text>
|
||||
<text x="50%" y="68%" font-family="Arial, sans-serif" font-size="24" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.5">
|
||||
${config.text}文件
|
||||
</text>
|
||||
<text x="50%" y="78%" font-family="Arial, sans-serif" font-size="18" fill="rgb(${color.r},${color.g},${color.b})" text-anchor="middle" dominant-baseline="middle" opacity="0.4">
|
||||
双击在默认应用中打开
|
||||
</text>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
await sharp(Buffer.from(svg))
|
||||
.resize(640, 480)
|
||||
.webp({ quality: 85 })
|
||||
.toFile(outputPath);
|
||||
|
||||
const stats = fs.statSync(outputPath);
|
||||
return {
|
||||
width: 640,
|
||||
height: 480,
|
||||
size: stats.size,
|
||||
path: outputPath
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件类型对应的图标(Unicode)
|
||||
*/
|
||||
function getIconForType(type) {
|
||||
const icons = {
|
||||
video: '🎬',
|
||||
document: '📄',
|
||||
special: '🎨'
|
||||
};
|
||||
return icons[type] || '📁';
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isImageFile,
|
||||
getFileType,
|
||||
calculateFileHash,
|
||||
getThumbnailConfig,
|
||||
generateThumbnail,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails,
|
||||
SUPPORTED_FORMATS,
|
||||
ALL_FORMATS
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
@echo off
|
||||
echo ========================================
|
||||
echo FlyPic - Development Mode
|
||||
echo ========================================
|
||||
echo.
|
||||
echo Starting backend server...
|
||||
echo Backend: http://localhost:5002
|
||||
echo.
|
||||
echo Please open another terminal and run:
|
||||
echo npm run dev:frontend
|
||||
echo.
|
||||
echo Frontend will be at: http://localhost:5173
|
||||
echo.
|
||||
echo Press Ctrl+C to stop backend
|
||||
echo.
|
||||
|
||||
cd backend
|
||||
call npm run dev
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,245 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
class LibraryDatabase {
|
||||
constructor(libraryPath) {
|
||||
this.libraryPath = libraryPath;
|
||||
this.flypicDir = path.join(libraryPath, '.flypic');
|
||||
this.dbPath = path.join(this.flypicDir, 'metadata.db');
|
||||
|
||||
// Ensure .flypic directory exists
|
||||
if (!fs.existsSync(this.flypicDir)) {
|
||||
fs.mkdirSync(this.flypicDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Create thumbnails directory (优化:不再使用子文件夹)
|
||||
const thumbDir = path.join(this.flypicDir, 'thumbnails');
|
||||
if (!fs.existsSync(thumbDir)) {
|
||||
fs.mkdirSync(thumbDir, { recursive: true });
|
||||
}
|
||||
|
||||
this.db = new Database(this.dbPath);
|
||||
|
||||
// 优化数据库性能
|
||||
this.db.pragma('journal_mode = WAL'); // 启用 WAL 模式,支持并发读写
|
||||
this.db.pragma('synchronous = NORMAL'); // 平衡性能和安全性
|
||||
this.db.pragma('cache_size = -64000'); // 64MB 缓存
|
||||
this.db.pragma('temp_store = MEMORY'); // 临时表存储在内存
|
||||
this.db.pragma('mmap_size = 268435456'); // 256MB 内存映射
|
||||
|
||||
this.initTables();
|
||||
}
|
||||
|
||||
initTables() {
|
||||
// Images table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
path TEXT UNIQUE NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
size INTEGER,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
format TEXT,
|
||||
created_at INTEGER,
|
||||
modified_at INTEGER,
|
||||
file_hash TEXT,
|
||||
thumbnail_path TEXT,
|
||||
thumbnail_size INTEGER,
|
||||
indexed_at INTEGER
|
||||
)
|
||||
`);
|
||||
|
||||
// Folders table
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS folders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
path TEXT UNIQUE NOT NULL,
|
||||
parent_path TEXT,
|
||||
name TEXT NOT NULL,
|
||||
image_count INTEGER DEFAULT 0,
|
||||
last_scan INTEGER
|
||||
)
|
||||
`);
|
||||
|
||||
// Create indexes
|
||||
this.db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_filename ON images(filename);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder ON images(folder);
|
||||
CREATE INDEX IF NOT EXISTS idx_created_at ON images(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_file_hash ON images(file_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_path ON folders(path);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_parent ON folders(parent_path);
|
||||
`);
|
||||
}
|
||||
|
||||
// Image operations
|
||||
insertImage(imageData) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO images
|
||||
(path, filename, folder, size, width, height, format, created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
return stmt.run(
|
||||
imageData.path,
|
||||
imageData.filename,
|
||||
imageData.folder,
|
||||
imageData.size,
|
||||
imageData.width,
|
||||
imageData.height,
|
||||
imageData.format,
|
||||
imageData.created_at,
|
||||
imageData.modified_at,
|
||||
imageData.file_hash,
|
||||
imageData.thumbnail_path,
|
||||
imageData.thumbnail_size,
|
||||
Date.now()
|
||||
);
|
||||
}
|
||||
|
||||
getImageByPath(imagePath) {
|
||||
const stmt = this.db.prepare('SELECT * FROM images WHERE path = ?');
|
||||
return stmt.get(imagePath);
|
||||
}
|
||||
|
||||
getAllImages() {
|
||||
const stmt = this.db.prepare('SELECT * FROM images ORDER BY created_at DESC');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
searchImages(keywords, filters = {}) {
|
||||
let query = 'SELECT * FROM images WHERE 1=1';
|
||||
const params = [];
|
||||
|
||||
// Keyword search (AND logic)
|
||||
if (keywords && keywords.trim()) {
|
||||
const terms = keywords.trim().split(/\s+/);
|
||||
terms.forEach(term => {
|
||||
query += ' AND filename LIKE ?';
|
||||
params.push(`%${term}%`);
|
||||
});
|
||||
}
|
||||
|
||||
// Folder filter
|
||||
if (filters.folder) {
|
||||
query += ' AND folder LIKE ?';
|
||||
params.push(`${filters.folder}%`);
|
||||
}
|
||||
|
||||
// Format filter
|
||||
if (filters.formats && filters.formats.length > 0) {
|
||||
const placeholders = filters.formats.map(() => '?').join(',');
|
||||
query += ` AND format IN (${placeholders})`;
|
||||
params.push(...filters.formats);
|
||||
}
|
||||
|
||||
// Size filter (in KB)
|
||||
if (filters.minSize) {
|
||||
query += ' AND size >= ?';
|
||||
params.push(filters.minSize * 1024);
|
||||
}
|
||||
if (filters.maxSize) {
|
||||
query += ' AND size <= ?';
|
||||
params.push(filters.maxSize * 1024);
|
||||
}
|
||||
|
||||
// Date filter
|
||||
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';
|
||||
|
||||
const stmt = this.db.prepare(query);
|
||||
return stmt.all(...params);
|
||||
}
|
||||
|
||||
deleteImage(imagePath) {
|
||||
const stmt = this.db.prepare('DELETE FROM images WHERE path = ?');
|
||||
return stmt.run(imagePath);
|
||||
}
|
||||
|
||||
// Folder operations
|
||||
insertFolder(folderData) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO folders (path, parent_path, name, image_count, last_scan)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
return stmt.run(
|
||||
folderData.path,
|
||||
folderData.parent_path,
|
||||
folderData.name,
|
||||
folderData.image_count || 0,
|
||||
Date.now()
|
||||
);
|
||||
}
|
||||
|
||||
getAllFolders() {
|
||||
const stmt = this.db.prepare('SELECT * FROM folders ORDER BY path');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
getFolderByPath(folderPath) {
|
||||
const stmt = this.db.prepare('SELECT * FROM folders WHERE path = ?');
|
||||
return stmt.get(folderPath);
|
||||
}
|
||||
|
||||
deleteFolder(folderPath) {
|
||||
const stmt = this.db.prepare('DELETE FROM folders WHERE path = ?');
|
||||
return stmt.run(folderPath);
|
||||
}
|
||||
|
||||
deleteImagesByFolderPrefix(folderPath) {
|
||||
const stmt = this.db.prepare('DELETE FROM images WHERE folder = ? OR folder LIKE ?');
|
||||
return stmt.run(folderPath, `${folderPath}%`);
|
||||
}
|
||||
|
||||
deleteFoldersByPrefix(folderPath) {
|
||||
const stmt = this.db.prepare('DELETE FROM folders WHERE path = ? OR path LIKE ?');
|
||||
return stmt.run(folderPath, `${folderPath}%`);
|
||||
}
|
||||
|
||||
getFolderTree() {
|
||||
const folders = this.getAllFolders();
|
||||
const tree = [];
|
||||
const map = {};
|
||||
|
||||
// Build folder map
|
||||
folders.forEach(folder => {
|
||||
map[folder.path] = { ...folder, children: [] };
|
||||
});
|
||||
|
||||
// Build tree structure
|
||||
folders.forEach(folder => {
|
||||
if (folder.parent_path && map[folder.parent_path]) {
|
||||
map[folder.parent_path].children.push(map[folder.path]);
|
||||
} else {
|
||||
tree.push(map[folder.path]);
|
||||
}
|
||||
});
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
updateFolderImageCount(folderPath) {
|
||||
const stmt = this.db.prepare(`
|
||||
UPDATE folders
|
||||
SET image_count = (SELECT COUNT(*) FROM images WHERE folder LIKE ?)
|
||||
WHERE path = ?
|
||||
`);
|
||||
return stmt.run(`${folderPath}%`, folderPath);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LibraryDatabase;
|
||||
@@ -0,0 +1,157 @@
|
||||
const LibraryDatabase = require('./db');
|
||||
|
||||
/**
|
||||
* 数据库连接池管理器
|
||||
* 复用数据库连接,避免频繁创建/关闭
|
||||
*/
|
||||
class DatabasePool {
|
||||
constructor() {
|
||||
this.connections = new Map(); // libraryPath -> { db, lastUsed, refCount }
|
||||
this.maxIdleTime = 60000; // 60秒未使用则关闭
|
||||
this.cleanupInterval = null;
|
||||
|
||||
// 启动定期清理
|
||||
this.startCleanup();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库连接(复用或创建)
|
||||
* 优化:同时只保持一个活跃连接
|
||||
*/
|
||||
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 = {
|
||||
db,
|
||||
lastUsed: Date.now(),
|
||||
refCount: 0
|
||||
};
|
||||
this.connections.set(libraryPath, conn);
|
||||
console.log(`[DBPool] Created new connection for: ${libraryPath}`);
|
||||
}
|
||||
|
||||
// 更新使用时间和引用计数
|
||||
conn.lastUsed = Date.now();
|
||||
conn.refCount++;
|
||||
|
||||
return conn.db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放数据库连接(减少引用计数)
|
||||
*/
|
||||
release(libraryPath) {
|
||||
const conn = this.connections.get(libraryPath);
|
||||
if (conn) {
|
||||
conn.refCount = Math.max(0, conn.refCount - 1);
|
||||
conn.lastUsed = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制关闭指定连接
|
||||
*/
|
||||
close(libraryPath) {
|
||||
const conn = this.connections.get(libraryPath);
|
||||
if (conn) {
|
||||
try {
|
||||
// 强制设置引用计数为0
|
||||
conn.refCount = 0;
|
||||
|
||||
// 关闭数据库连接
|
||||
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();
|
||||
}
|
||||
|
||||
this.connections.delete(libraryPath);
|
||||
console.log(`[DBPool] Closed connection for: ${libraryPath}`);
|
||||
} catch (error) {
|
||||
console.error(`[DBPool] Error closing connection:`, error);
|
||||
// 即使出错也删除引用
|
||||
this.connections.delete(libraryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭所有连接
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定期清理空闲连接
|
||||
*/
|
||||
startCleanup() {
|
||||
this.cleanupInterval = setInterval(() => {
|
||||
const now = Date.now();
|
||||
const toClose = [];
|
||||
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
// 如果连接空闲超过阈值且没有引用,则关闭
|
||||
if (conn.refCount === 0 && now - conn.lastUsed > this.maxIdleTime) {
|
||||
toClose.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
toClose.forEach(path => this.close(path));
|
||||
|
||||
if (toClose.length > 0) {
|
||||
console.log(`[DBPool] Cleaned up ${toClose.length} idle connections`);
|
||||
}
|
||||
}, 30000); // 每30秒检查一次
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取连接池状态
|
||||
*/
|
||||
getStatus() {
|
||||
const status = [];
|
||||
for (const [path, conn] of this.connections.entries()) {
|
||||
status.push({
|
||||
path,
|
||||
refCount: conn.refCount,
|
||||
idleTime: Date.now() - conn.lastUsed
|
||||
});
|
||||
}
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
// 单例模式
|
||||
const dbPool = new DatabasePool();
|
||||
|
||||
module.exports = dbPool;
|
||||
Generated
+2789
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "flypic-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "FlyPic backend server",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"dev": "nodemon server.js",
|
||||
"start": "node server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^9.2.2",
|
||||
"chokidar": "^3.6.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto": "^1.0.1",
|
||||
"express": "^4.18.2",
|
||||
"glob": "^10.3.10",
|
||||
"sharp": "^0.33.0",
|
||||
"socket.io": "^4.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
(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 ws=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Jf={exports:{}},jo={},ed={exports:{}},_e={};/**
|
||||
* @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 us=Symbol.for("react.element"),rm=Symbol.for("react.portal"),im=Symbol.for("react.fragment"),sm=Symbol.for("react.strict_mode"),om=Symbol.for("react.profiler"),am=Symbol.for("react.provider"),lm=Symbol.for("react.context"),um=Symbol.for("react.forward_ref"),cm=Symbol.for("react.suspense"),fm=Symbol.for("react.memo"),dm=Symbol.for("react.lazy"),nc=Symbol.iterator;function hm(e){return e===null||typeof e!="object"?null:(e=nc&&e[nc]||e["@@iterator"],typeof e=="function"?e:null)}var td={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},nd=Object.assign,rd={};function pi(e,t,n){this.props=e,this.context=t,this.refs=rd,this.updater=n||td}pi.prototype.isReactComponent={};pi.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")};pi.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function id(){}id.prototype=pi.prototype;function Zl(e,t,n){this.props=e,this.context=t,this.refs=rd,this.updater=n||td}var Ql=Zl.prototype=new id;Ql.constructor=Zl;nd(Ql,pi.prototype);Ql.isPureReactComponent=!0;var rc=Array.isArray,sd=Object.prototype.hasOwnProperty,Gl={current:null},od={key:!0,ref:!0,__self:!0,__source:!0};function ad(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)sd.call(t,r)&&!od.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),u=0;u<a;u++)l[u]=arguments[u+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:us,type:e,key:s,ref:o,props:i,_owner:Gl.current}}function pm(e,t){return{$$typeof:us,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Jl(e){return typeof e=="object"&&e!==null&&e.$$typeof===us}function mm(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var ic=/\/+/g;function oa(e,t){return typeof e=="object"&&e!==null&&e.key!=null?mm(""+e.key):t.toString(36)}function Ws(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 us:case rm:o=!0}}if(o)return o=e,i=i(o),e=r===""?"."+oa(o,0):r,rc(i)?(n="",e!=null&&(n=e.replace(ic,"$&/")+"/"),Ws(i,t,n,"",function(u){return u})):i!=null&&(Jl(i)&&(i=pm(i,n+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(ic,"$&/")+"/")+e)),t.push(i)),1;if(o=0,r=r===""?".":r+":",rc(e))for(var a=0;a<e.length;a++){s=e[a];var l=r+oa(s,a);o+=Ws(s,t,n,l,i)}else if(l=hm(e),typeof l=="function")for(e=l.call(e),a=0;!(s=e.next()).done;)s=s.value,l=r+oa(s,a++),o+=Ws(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 xs(e,t,n){if(e==null)return e;var r=[],i=0;return Ws(e,r,"","",function(s){return t.call(n,s,i++)}),r}function gm(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 dt={current:null},Hs={transition:null},ym={ReactCurrentDispatcher:dt,ReactCurrentBatchConfig:Hs,ReactCurrentOwner:Gl};function ld(){throw Error("act(...) is not supported in production builds of React.")}_e.Children={map:xs,forEach:function(e,t,n){xs(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return xs(e,function(){t++}),t},toArray:function(e){return xs(e,function(t){return t})||[]},only:function(e){if(!Jl(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};_e.Component=pi;_e.Fragment=im;_e.Profiler=om;_e.PureComponent=Zl;_e.StrictMode=sm;_e.Suspense=cm;_e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ym;_e.act=ld;_e.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=nd({},e.props),i=e.key,s=e.ref,o=e._owner;if(t!=null){if(t.ref!==void 0&&(s=t.ref,o=Gl.current),t.key!==void 0&&(i=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(l in t)sd.call(t,l)&&!od.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 u=0;u<l;u++)a[u]=arguments[u+2];r.children=a}return{$$typeof:us,type:e.type,key:i,ref:s,props:r,_owner:o}};_e.createContext=function(e){return e={$$typeof:lm,_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 vm=ne,wm=Symbol.for("react.element"),xm=Symbol.for("react.fragment"),_m=Object.prototype.hasOwnProperty,km=vm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Sm={key:!0,ref:!0,__self:!0,__source:!0};function ud(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)_m.call(t,r)&&!Sm.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:wm,type:e,key:s,ref:o,props:i,_owner:km.current}}jo.Fragment=xm;jo.jsx=ud;jo.jsxs=ud;Jf.exports=jo;var C=Jf.exports,Ua={},cd={exports:{}},Nt={},fd={exports:{}},dd={};/**
|
||||
* @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,z){var j=H.length;H.push(z);e:for(;0<j;){var O=j-1>>>1,A=H[O];if(0<i(A,z))H[O]=z,H[j]=A,j=O;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var z=H[0],j=H.pop();if(j!==z){H[0]=j;e:for(var O=0,A=H.length,J=A>>>1;O<J;){var q=2*(O+1)-1,V=H[q],ce=q+1,Y=H[ce];if(0>i(V,j))ce<A&&0>i(Y,V)?(H[O]=Y,H[ce]=j,O=ce):(H[O]=V,H[q]=j,O=q);else if(ce<A&&0>i(Y,j))H[O]=Y,H[ce]=j,O=ce;else break e}}return z}function i(H,z){var j=H.sortIndex-z.sortIndex;return j!==0?j:H.id-z.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=[],u=[],h=1,y=null,w=3,p=!1,g=!1,d=!1,_=typeof setTimeout=="function"?setTimeout:null,c=typeof clearTimeout=="function"?clearTimeout:null,f=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(H){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=H)r(u),z.sortIndex=z.expirationTime,t(l,z);else break;z=n(u)}}function k(H){if(d=!1,x(H),!g)if(n(l)!==null)g=!0,se(R);else{var z=n(u);z!==null&&X(k,z.startTime-H)}}function R(H,z){g=!1,d&&(d=!1,c(L),L=-1),p=!0;var j=w;try{for(x(z),y=n(l);y!==null&&(!(y.expirationTime>z)||H&&!re());){var O=y.callback;if(typeof O=="function"){y.callback=null,w=y.priorityLevel;var A=O(y.expirationTime<=z);z=e.unstable_now(),typeof A=="function"?y.callback=A:y===n(l)&&r(l),x(z)}else r(l);y=n(l)}if(y!==null)var J=!0;else{var q=n(u);q!==null&&X(k,q.startTime-z),J=!1}return J}finally{y=null,w=j,p=!1}}var E=!1,N=null,L=-1,P=5,I=-1;function re(){return!(e.unstable_now()-I<P)}function T(){if(N!==null){var H=e.unstable_now();I=H;var z=!0;try{z=N(!0,H)}finally{z?D():(E=!1,N=null)}}else E=!1}var D;if(typeof f=="function")D=function(){f(T)};else if(typeof MessageChannel<"u"){var v=new MessageChannel,B=v.port2;v.port1.onmessage=T,D=function(){B.postMessage(null)}}else D=function(){_(T,0)};function se(H){N=H,E||(E=!0,D())}function X(H,z){L=_(function(){H(e.unstable_now())},z)}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(){g||p||(g=!0,se(R))},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"):P=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return w},e.unstable_getFirstCallbackNode=function(){return n(l)},e.unstable_next=function(H){switch(w){case 1:case 2:case 3:var z=3;break;default:z=w}var j=w;w=z;try{return H()}finally{w=j}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(H,z){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var j=w;w=H;try{return z()}finally{w=j}},e.unstable_scheduleCallback=function(H,z,j){var O=e.unstable_now();switch(typeof j=="object"&&j!==null?(j=j.delay,j=typeof j=="number"&&0<j?O+j:O):j=O,H){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,H={id:h++,callback:z,priorityLevel:H,startTime:j,expirationTime:A,sortIndex:-1},j>O?(H.sortIndex=j,t(u,H),n(l)===null&&H===n(u)&&(d?(c(L),L=-1):d=!0,X(k,j-O))):(H.sortIndex=A,t(l,H),g||p||(g=!0,se(R))),H},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(H){var z=w;return function(){var j=w;w=z;try{return H.apply(this,arguments)}finally{w=j}}}})(dd);fd.exports=dd;var bm=fd.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 Em=ne,Ct=bm;function te(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 hd=new Set,qi={};function Tr(e,t){si(e,t),si(e+"Capture",t)}function si(e,t){for(qi[e]=t,e=0;e<t.length;e++)hd.add(t[e])}var On=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),$a=Object.prototype.hasOwnProperty,Cm=/^[: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]*$/,sc={},oc={};function Nm(e){return $a.call(oc,e)?!0:$a.call(sc,e)?!1:Cm.test(e)?oc[e]=!0:(sc[e]=!0,!1)}function Rm(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 Tm(e,t,n,r){if(t===null||typeof t>"u"||Rm(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 Je={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Je[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];Je[t]=new ht(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Je[e]=new ht(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Je[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){Je[e]=new ht(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Je[e]=new ht(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Je[e]=new ht(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Je[e]=new ht(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Je[e]=new ht(e,5,!1,e.toLowerCase(),null,!1,!1)});var eu=/[\-:]([a-z])/g;function tu(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(eu,tu);Je[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(eu,tu);Je[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(eu,tu);Je[t]=new ht(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Je[e]=new ht(e,1,!1,e.toLowerCase(),null,!1,!1)});Je.xlinkHref=new ht("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Je[e]=new ht(e,1,!1,e.toLowerCase(),null,!0,!0)});function nu(e,t,n,r){var i=Je.hasOwnProperty(t)?Je[t]:null;(i!==null?i.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!=
Line truncated
|
||||
`+aa+e}var la=!1;function ua(e,t){if(!e||la)return"";la=!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(u){var r=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){r=u}e.call(t.prototype)}else{try{throw Error()}catch(u){r=u}e()}}catch(u){if(u&&r&&typeof u.stack=="string"){for(var i=u.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{la=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Pi(e):""}function Om(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=ua(e.type,!1),e;case 11:return e=ua(e.type.render,!1),e;case 1:return e=ua(e.type,!0),e;default:return""}}function qa(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 Ur:return"Fragment";case Mr:return"Portal";case Wa:return"Profiler";case ru:return"StrictMode";case Ha:return"Suspense";case Va: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 iu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case su:return t=e.displayName||null,t!==null?t:qa(e.type)||"Memo";case $n:t=e._payload,e=e._init;try{return qa(e(t))}catch{}}return null}function Am(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 qa(t);case 8:return t===ru?"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 ir(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function yd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Pm(e){var t=yd(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 ks(e){e._valueTracker||(e._valueTracker=Pm(e))}function vd(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=yd(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function lo(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 Ka(e,t){var n=t.checked;return Be({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function lc(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ir(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 wd(e,t){t=t.checked,t!=null&&nu(e,"checked",t,!1)}function Xa(e,t){wd(e,t);var n=ir(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")?Ya(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ya(e,t.type,ir(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function uc(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 Ya(e,t,n){(t!=="number"||lo(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var zi=Array.isArray;function Gr(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=""+ir(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 Za(e,t){if(t.dan
Line truncated
|
||||
`).replace($0,"")}function Os(e,t,n){if(t=Pc(t),Pc(e)!==t&&n)throw Error(te(425))}function yo(){}var ul=null,cl=null;function fl(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 dl=typeof setTimeout=="function"?setTimeout:void 0,W0=typeof clearTimeout=="function"?clearTimeout:void 0,zc=typeof Promise=="function"?Promise:void 0,H0=typeof queueMicrotask=="function"?queueMicrotask:typeof zc<"u"?function(e){return zc.resolve(null).then(e).catch(V0)}:dl;function V0(e){setTimeout(function(){throw e})}function ka(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),Qi(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=i}while(n);Qi(t)}function Gn(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 Lc(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 gi=Math.random().toString(36).slice(2),ln="__reactFiber$"+gi,ns="__reactProps$"+gi,An="__reactContainer$"+gi,hl="__reactEvents$"+gi,q0="__reactListeners$"+gi,K0="__reactHandles$"+gi;function gr(e){var t=e[ln];if(t)return t;for(var n=e.parentNode;n;){if(t=n[An]||n[ln]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Lc(e);e!==null;){if(n=e[ln])return n;e=Lc(e)}return t}e=n,n=e.parentNode}return null}function ds(e){return e=e[ln]||e[An],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Vr(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(te(33))}function Mo(e){return e[ns]||null}var pl=[],qr=-1;function ar(e){return{current:e}}function Le(e){0>qr||(e.current=pl[qr],pl[qr]=null,qr--)}function Oe(e,t){qr++,pl[qr]=e.current,e.current=t}var sr={},st=ar(sr),gt=ar(!1),Sr=sr;function oi(e,t){var n=e.type.contextTypes;if(!n)return sr;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 vo(){Le(gt),Le(st)}function jc(e,t,n){if(st.current!==sr)throw Error(te(168));Oe(st,t),Oe(gt,n)}function ah(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(te(108,Am(e)||"Unknown",i));return Be({},n,r)}function wo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||sr,Sr=st.current,Oe(st,e),Oe(gt,gt.current),!0}function Ic(e,t,n){var r=e.stateNode;if(!r)throw Error(te(169));n?(e=ah(e,t,Sr),r.__reactInternalMemoizedMergedChildContext=e,Le(gt),Le(st),Oe(st,e)):Le(gt),Oe(gt,n)}var En=null,Uo=!1,Sa=!1;function lh(e){En===null?En=[e]:En.push(e)}function X0(e){Uo=!0,lh(e)}function lr(){if(!Sa&&En!==null){Sa=!0;var e=0,t=Ne;try{var n=En;for(Ne=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}En=null,Uo=!1}catch(i){throw En!==null&&(En=En.slice(e+1)),zd(au,lr),i}finally{Ne=t,Sa=!1}}return null}var Kr=[],Xr=0,xo=null,_o=0,Lt=[],jt=0,br=null,Nn=1,Rn="";function hr(e,t){Kr[Xr++]=_o,Kr[Xr++]=xo,xo=e,_o=t}function uh(e,t,n){Lt[jt++]=Nn,Lt[jt++]=Rn,Lt[jt++]=br,br=e;var r=Nn;e=Rn;var i=32-Xt(r)-1;r&=~(1<<i),n+=1;var s=32-Xt(t)+i;if(30<s){var o=i-i%5;s=(r&(1<<o)-1).toString(32),r>>=o,i-=o,Nn=1<<32-Xt(t)+i|n<<i|r,Rn=s+e}else Nn=1<<s|n<<i|r,Rn=e}function gu(e){e.return!==null&&(hr(e,1),uh(e,1,0))}function yu(e){for(;e===xo;)xo=Kr[--Xr],Kr[Xr]=null,_o=Kr[--Xr],Kr[Xr]=null;for(;e===br;)br=Lt[--jt],Lt[jt]=null,Rn=Lt[--jt],Lt[jt]=null,Nn=Lt[--jt],Lt[jt]=null}var Et=null,bt=null,je=!1,Kt=null;function ch(e,t){var n=Ft(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 Fc(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=Gn(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=br!==null?{id:Nn,overflow:Rn}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=Ft(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,Et=e,bt=null,!0):!1;default:return!1}}function ml(e){return(e.mode&1)!==0&&(e.flags&128)===0}function gl(e){if(je){var t=bt;if(t){var n=t;if(!Fc(e,t)){if(ml(e))throw Error(te(418));t=Gn(n.nextSibling);var r=Et;t&&Fc(e,t)?ch(r,n):(e.flags=e.flags&-4097|2,je=!1,Et=e)}}else{if(ml(e))throw Error(te(418));e.flags=e.flags&-4097|2,je=!1,Et=e}}}function Bc(e){
Line truncated
|
||||
Error generating stack: `+s.message+`
|
||||
`+s.stack}return{value:e,source:t,stack:i,digest:null}}function Ra(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function xl(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var rg=typeof WeakMap=="function"?WeakMap:Map;function Fh(e,t,n){n=Tn(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){To||(To=!0,Ol=r),xl(e,t)},n}function Bh(e,t,n){n=Tn(-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(){xl(e,t)}}var s=e.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(n.callback=function(){xl(e,t),typeof r!="function"&&(er===null?er=new Set([this]):er.add(this));var o=t.stack;this.componentDidCatch(t.value,{componentStack:o!==null?o:""})}),n}function qc(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new rg;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=yg.bind(null,e,t,n),t.then(e,e))}function Kc(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 Xc(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=Tn(-1,1),t.tag=2,Jn(n,t,1))),n.lanes|=1),e)}var ig=Ln.ReactCurrentOwner,mt=!1;function ut(e,t,n,r){t.child=e===null?hh(t,null,n,r):li(t,e.child,n,r)}function Yc(e,t,n,r,i){n=n.render;var s=t.ref;return ni(t,i),r=Ru(e,t,n,r,s,i),n=Tu(),e!==null&&!mt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,zn(e,t,i)):(je&&n&&gu(t),t.flags|=1,ut(e,t,r,i),t.child)}function Zc(e,t,n,r,i){if(e===null){var s=n.type;return typeof s=="function"&&!Du(s)&&s.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=s,Dh(e,t,s,r,i)):(e=eo(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:Ji,n(o,r)&&e.ref===t.ref)return zn(e,t,i)}return t.flags|=1,e=nr(s,r),e.ref=t.ref,e.return=t,t.child=e}function Dh(e,t,n,r,i){if(e!==null){var s=e.memoizedProps;if(Ji(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 _l(e,t,n,r,i)}function Mh(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(Qr,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(Qr,St),St|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=s!==null?s.baseLanes:n,Oe(Qr,St),St|=r}else s!==null?(r=s.baseLanes|n,t.memoizedState=null):r=n,Oe(Qr,St),St|=r;return ut(e,t,i,n),t.child}function Uh(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function _l(e,t,n,r,i){var s=yt(n)?Sr:st.current;return s=oi(t,s),ni(t,i),n=Ru(e,t,n,r,s,i),r=Tu(),e!==null&&!mt?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,zn(e,t,i)):(je&&r&&gu(t),t.flags|=1,ut(e,t,n,i),t.child)}function Qc(e,t,n,r,i){if(yt(n)){var s=!0;wo(t)}else s=!1;if(ni(t,i),t.stateNode===null)Qs(e,t),Ih(t,n,r),wl(t,n,r,i),r=!0;else if(e===null){var o=t.stateNode,a=t.memoizedProps;o.props=a;var l=o.context,u=n.contextType;typeof u=="object"&&u!==null?u=Dt(u):(u=yt(n)?Sr:st.current,u=oi(t,u));var h=n.getDerivedStateFromProps,y=typeof h=="function"||typeof o.getSnapshotBeforeUpdate=="function";y||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==r||l!==u)&&Vc(t,o,r,u),Wn=!1;var w=t.memoizedState;o.state=w,bo(t,r,o,i),l=t.memoizedState,a!==r||w!==l||gt.current||Wn?(typeof h=="function"&&(vl(t,n,h,r),l=t.memoizedState),(a=Wn||Hc(t,n,a,r,w,l,u))?(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=u,r=a):(typeof o.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,mh(e,t),a=t.memoizedProps,u=t.type===t.elementType?a:Ht(t.type,a),o.props=u,y=t.pendingProps,w=o.context,l=n.contextType,typeof l=="object"&&l!==null?l=Dt(l):(l=yt(n)?Sr:st.current,l=oi(t,l));var p=n.getDerivedStateFromProps;(h=typeof p=="function"||typeof o.getSnapshotBeforeUpdate=="function")||typeof o.UNSAFE_componentWillReceiveProps!="function"&&typeof o.componentWillReceiveProps!="function"||(a!==y||w!==l)&&Vc(t,o,r,l),Wn=!1,w=t.memoizedState,o.state=w,bo(t,r,o,i);var g=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 di=ne;function Sy(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var by=typeof Object.is=="function"?Object.is:Sy,Ey=di.useState,Cy=di.useEffect,Ny=di.useLayoutEffect,Ry=di.useDebugValue;function Ty(e,t){var n=t(),r=Ey({inst:{value:n,getSnapshot:t}}),i=r[0].inst,s=r[1];return Ny(function(){i.value=n,i.getSnapshot=t,ja(i)&&s({inst:i})},[e,n,t]),Cy(function(){return ja(i)&&s({inst:i}),e(function(){ja(i)&&s({inst:i})})},[e]),Ry(n),n}function ja(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!by(e,n)}catch{return!0}}function Oy(e,t){return t()}var Ay=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Oy:Ty;Rp.useSyncExternalStore=di.useSyncExternalStore!==void 0?di.useSyncExternalStore:Ay;Np.exports=Rp;var Py=Np.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 Jo=ne,zy=Py;function Ly(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jy=typeof Object.is=="function"?Object.is:Ly,Iy=zy.useSyncExternalStore,Fy=Jo.useRef,By=Jo.useEffect,Dy=Jo.useMemo,My=Jo.useDebugValue;Cp.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var s=Fy(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=Dy(function(){function l(p){if(!u){if(u=!0,h=p,p=r(p),i!==void 0&&o.hasValue){var g=o.value;if(i(g,p))return y=g}return y=p}if(g=y,jy(h,p))return g;var d=r(p);return i!==void 0&&i(g,d)?(h=p,g):(h=p,y=d)}var u=!1,h,y,w=n===void 0?null:n;return[function(){return l(t())},w===null?void 0:function(){return l(w())}]},[t,n,r,i]);var a=Iy(e,s[0],s[1]);return By(function(){o.hasValue=!0,o.value=a},[a]),My(a),a};Ep.exports=Cp;var Uy=Ep.exports;const $y=Yl(Uy),Tp={},{useDebugValue:Wy}=ve,{useSyncExternalStoreWithSelector:Hy}=$y;let vf=!1;const Vy=e=>e;function qy(e,t=Vy,n){(Tp?"production":void 0)!=="production"&&n&&!vf&&(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"),vf=!0);const r=Hy(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Wy(r),r}const wf=e=>{(Tp?"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"?ky(e):e,n=(r,i)=>qy(t,r,i);return Object.assign(n,t),n},Ky=e=>e?wf(e):wf,Te=Ky((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}),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 Op(e,t){return function(){return e.apply(t,arguments)}}const{toString:Xy}=Object.prototype,{getPrototypeOf:Yu}=Object,{iterator:ea,toStringTag:Ap}=Symbol,ta=(e=>t=>{const n=Xy.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Qt=e=>(e=e.toLowerCase(),t=>ta(t)===e),na=e=>t=>typeof t===e,{isArray:vi}=Array,hi=na("undefined");function ps(e){return e!==null&&!hi(e)&&e.constructor!==null&&!hi(e.constructor)&&wt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Pp=Qt("ArrayBuffer");function Yy(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Pp(e.buffer),t}const Zy=na("string"),wt=na("function"),zp=na("number"),ms=e=>e!==null&&typeof e=="object",Qy=e=>e===!0||e===!1,so=e=>{if(ta(e)!=="object")return!1;const t=Yu(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ap in e)&&!(ea in e)},Gy=e=>{if(!ms(e)||ps(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Jy=Qt("Date"),ev=Qt("File"),tv=Qt("Blob"),nv=Qt("FileList"),rv=e=>ms(e)&&wt(e.pipe),iv=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||wt(e.append)&&((t=ta(e))==="formdata"||t==="object"&&wt(e.toString)&&e.toString()==="[object FormData]"))},sv=Qt("URLSearchParams"),[ov,av,lv,uv]=["ReadableStream","Request","Response","Headers"].map(Qt),cv=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\Line truncated
|
||||
`).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&Yv[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},bf=Symbol("internals");function Ai(e){return e&&String(e).trim().toLowerCase()}function oo(e){return e===!1||e==null?e:$.isArray(e)?e.map(oo):String(e)}function Qv(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 Gv=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ia(e,t,n,r,i){if($.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!$.isString(t)){if($.isString(r))return t.indexOf(r)!==-1;if($.isRegExp(r))return r.test(t)}}function Jv(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function e1(e,t){const n=$.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,u){const h=Ai(l);if(!h)throw new Error("header name must be a non-empty string");const y=$.findKey(i,h);(!y||i[y]===void 0||u===!0||u===void 0&&i[y]!==!1)&&(i[y||l]=oo(a))}const o=(a,l)=>$.forEach(a,(u,h)=>s(u,h,l));if($.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if($.isString(t)&&(t=t.trim())&&!Gv(t))o(Zv(t),n);else if($.isObject(t)&&$.isIterable(t)){let a={},l,u;for(const h of t){if(!$.isArray(h))throw TypeError("Object iterator must return a key-value pair");a[u=h[0]]=(l=a[u])?$.isArray(l)?[...l,h[1]]:[l,h[1]]:h[1]}o(a,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=Ai(t),t){const r=$.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return Qv(i);if($.isFunction(n))return n.call(this,i,r);if($.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Ai(t),t){const r=$.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Ia(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=Ai(o),o){const a=$.findKey(r,o);a&&(!n||Ia(r,r[a],a,n))&&(delete r[a],i=!0)}}return $.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||Ia(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return $.forEach(this,(i,s)=>{const o=$.findKey(r,s);if(o){n[o]=oo(i),delete n[s];return}const a=t?Jv(s):String(s).trim();a!==s&&delete n[s],n[a]=oo(i),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return $.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&$.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[bf]=this[bf]={accessors:{}}).accessors,i=this.prototype;function s(o){const a=Ai(o);r[a]||(e1(i,o),r[a]=!0)}return $.isArray(t)?t.forEach(s):s(t),this}};xt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);$.reduceDescriptors(xt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});$.freezeMethods(xt);function Fa(e,t){const n=this||ys,r=t||n,i=xt.from(r.headers);let s=r.data;return $.forEach(e,function(a){s=a.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Vp(e){return!!(e&&e.__CANCEL__)}function wi(e,t,n){me.call(this,e??"canceled",me.ERR_CANCELED,t,n),this.name="CanceledError"}$.inherits(wi,me,{__CANCEL__:!0});function qp(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new me("Request failed with status code "+n.status,[me.ERR_BAD_REQUEST,me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function t1(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function n1(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 u=Date.now(),h=r[s];o||(o=u),n[i]=l,r[i]=u;let y=s,w=0;for(;y!==i;)w+=n[y++],y=y%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),u-o<t)return;const p=h&&u-h;return p?Math.round(w*1e3/p):void 0}}function r1(e,t){let n=0,r=1e3/t,i,s;const o=(u,h=Date.now())=>{n=h,i=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const h=Date.now(),y=h-n;y>=r?o(u,h):(i=u,s||(s=setTimeout(()=>{s=null,o(i)},r-y)))},()=>i&&o(i)]}const zo=(e,t,n=3)=>{let r=0;const i=n1(50,250);return r1(s=>{const o=s.loaded,a=s.lengthComputable?s.total:void 0,l=o-r,u=i(l),h=o<=a;r=o;const y={loaded:o,total:a,progress:a?o/a:void 0,bytes:l,rate:u||void 0,estimated:u&&a&&h?(a-o)/u:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(y)},n)},Ef=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Cf=e=>(...t)=>$.asap(()=>e(...t)),i1=it.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,it.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(it.origin),it.navigator&&/(msie|trident)/i.test(it.navigator.userAgent)):()=>!0,s1=it.hasStandardBrowserEnv?{write(e,t,n,r,i,s,o){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];$.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),$.isString(r)&&a.push(`path=${r}`),$.isString(i)&&a.push(`domain=${i}`),s===!0&&a.push("secure"),$.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 o1(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function a1(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Kp(e,t,n){let r=!o1(t);return e&&(r||n==!1)?a1(e,t):t}const Nf=e=>e instanceof xt?{...e}:e;function Rr(e,t){t=t||{};const n={};function r(u,h,y,w){return $.isPlainObject(u)&&$.isPlainObject(h)?$.merge.call({caseless:w},u,h):$.isPlainObject(h)?$.merge({},h):$.isArray(h)?h.slice():h}function i(u,h,y,w){if($.isUndefined(h)){if(!$.isUndefined(u))return r(void 0,u,y,w)}else return r(u,h,y,w)}function s(u,h){if(!$.isUndefined(h))return r(void 0,h)}function o(u,h){if($.isUndefined(h)){if(!$.isUndefined(u))return r(void 0,u)}else return r(void 0,h)}function a(u,h,y){if(y in t)return r(u,h);if(y in e)return r(void 0,u)}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:(u,h,y)=>i(Nf(u),Nf(h),y,!0)};return $.forEach(Object.keys({...e,...t}),function(h){const y=l[h]||i,w=y(e[h],t[h],h);$.isUndefined(w)&&y!==a||(n[h]=w)}),n}const Xp=e=>{const t=Rr({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:a}=t;if(t.headers=o=xt.from(o),t.url=$p(Kp(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),$.isFormData(n)){if(it.hasStandardBrowserEnv||it.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if($.isFunction(n.getHeaders)){const l=n.getHeaders(),u=["content-type","content-length"];Object.entries(l).forEach(([h,y])=>{u.inclu
Line truncated
|
||||
`+o.map(zf).join(`
|
||||
`):" "+zf(o[0]):"as no adapter specified";throw new me("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i}const Zp={getAdapter:v1,adapters:Gu};function Ba(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new wi(null,e)}function Lf(e){return Ba(e),e.headers=xt.from(e.headers),e.data=Fa.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Zp.getAdapter(e.adapter||ys.adapter,e)(e).then(function(r){return Ba(e),r.data=Fa.call(e,e.transformResponse,r),r.headers=xt.from(r.headers),r},function(r){return Vp(r)||(Ba(e),r&&r.response&&(r.response.data=Fa.call(e,e.transformResponse,r.response),r.response.headers=xt.from(r.response.headers))),Promise.reject(r)})}const Qp="1.13.2",ia={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ia[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const jf={};ia.transitional=function(t,n,r){function i(s,o){return"[Axios v"+Qp+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,a)=>{if(t===!1)throw new me(i(o," has been removed"+(n?" in "+n:"")),me.ERR_DEPRECATED);return n&&!jf[o]&&(jf[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}};ia.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function w1(e,t,n){if(typeof e!="object")throw new me("options must be an object",me.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 me("option "+s+" must be "+l,me.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new me("Unknown option "+s,me.ERR_BAD_OPTION)}}const ao={assertOptions:w1,validators:ia},on=ao.validators;let kr=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Sf,response:new Sf}}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=Rr(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&ao.assertOptions(r,{silentJSONParsing:on.transitional(on.boolean),forcedJSONParsing:on.transitional(on.boolean),clarifyTimeoutError:on.transitional(on.boolean)},!1),i!=null&&($.isFunction(i)?n.paramsSerializer={serialize:i}:ao.assertOptions(i,{encode:on.function,serialize:on.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ao.assertOptions(n,{baseUrl:on.spelling("baseURL"),withXsrfToken:on.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&$.merge(s.common,s[n.method]);s&&$.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=xt.concat(o,s);const a=[];let l=!0;this.interceptors.request.forEach(function(d){typeof d.runWhen=="function"&&d.runWhen(n)===!1||(l=l&&d.synchronous,a.unshift(d.fulfilled,d.rejected))});const u=[];this.interceptors.response.forEach(function(d){u.push(d.fulfilled,d.rejected)});let h,y=0,w;if(!l){const g=[Lf.bind(this),void 0];for(g.unshift(...a),g.push(...u),w=g.length,h=Promise.resolve(n);y<w;)h=h.then(g[y++],g[y++]);return h}w=a.length;let p=n;for(;y<w;){const g=a[y++],d=a[y++];try{p=g(p)}catch(_){d.call(this,_);break}}try{h=Lf.call(this,p)}catch(g){return Promise.reject(g)}for(y=0,w=u.length;y<w;)h=h.then(u[y++],u[y++]);return h}getUri(t){t=Rr(this.defaults,t);const n=Kp(t.baseURL,t.url,t.allowAbsoluteUrls);return $p(n,t.params,t.paramsSerializer)}};$.forEach(["delete","get","head","options"],function(t){kr.prototype[t]=function(n,r){return this.request(Rr(r||{},{method:t,url:n,data:(r||{}).data}))}});$.forEach(["post","put","patch"],function(t){function n(r){return function(s,o,a){return this.request(Rr(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}kr.prototype[t]=n(),kr.prototype[t+"Form"]=n(!0)});let x1=class Gp{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 wi(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 Gp(function(i){t=i}),cancel:t}}};function _1(e){return function(n){return e.apply(null,n)}}function k1(e){return $.isObject(e)&&e.isAxiosError===!0}const Wl={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(Wl).forEach(([e,t])=>{Wl[t]=e});function Jp(e){const t=new kr(e),n=Op(kr.prototype.request,t);return $.extend(n,kr.prototype,t,{allOwnKeys:!0}),$.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return Jp(Rr(e,i))},n}const be=Jp(ys);be.Axios=kr;be.CanceledError=wi;be.CancelToken=x1;be.isCancel=Vp;be.VERSION=Qp;be.toFormData=ra;be.AxiosError=me;be.Cancel=be.CanceledError;be.all=function(t){return Promise.all(t)};be.spread=_1;be.isAxiosError=k1;be.mergeConfig=Rr;be.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 S1={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 b1=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),Ye=(e,t)=>{const n=ne.forwardRef(({color:r="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:o,className:a="",children:l,...u},h)=>ne.createElement("svg",{ref:h,...S1,width:i,height:i,stroke:r,strokeWidth:o?Number(s)*24/Number(i):s,className:["lucide",`lucide-${b1(e)}`,a].join(" "),...u},[...t.map(([y,w])=>ne.createElement(y,w)),...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 E1=Ye("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 C1=Ye("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 Ff=Ye("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 N1=Ye("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 R1=Ye("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 T1=Ye("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 O1=Ye("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 A1=Ye("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 Bf=Ye("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 P1=Ye("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 Df=Ye("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 Mf=Ye("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 Uf=Ye("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 Vl=Ye("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 $f=Ye("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 Wf=Ye("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 z1=Ye("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 L1=Ye("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);function Hf(){const{libraries:e,currentLibraryId:t,folders:n,selectedFolder:r,totalImageCount:i,setCurrentLibrary:s,setSelectedFolder:o,addLibrary:a,removeLibrary:l}=Te(),[u,h]=ne.useState(!1),[y,w]=ne.useState(""),[p,g]=ne.useState(""),[d,_]=ne.useState(""),[c,f]=ne.useState(new Set),[x,k]=ne.useState(!1),[R,E]=ne.useState(!1),N=async()=>{if(!y.trim()){alert("请输入素材库名称");return}if(!p.trim()){alert("请输入文件夹路径");return}k(!0),Te.getState().setScanProgress({current:0,total:0,percent:0,status:"preparing"});try{const z=await Cn.add(y.trim(),p.trim()),j=z.data.id,O=z.data.hasExistingIndex;a({id:j,name:y.trim(),path:p.trim()}),w(""),g(""),h(!1),await Cn.setCurrent(j),s(j),o(null),Te.getState().setImages([]),Te.getState().setFolders([]),O?(console.log("检测到已有索引,执行增量同步..."),Hl.sync(j,!1)):(console.log("首次添加,执行全量扫描..."),Hl.fullScan(j,!1))}catch(z){console.error("Error adding library:",z),alert("添加素材库失败: "+z.message)}finally{k(!1)}},L=async z=>{if(z!==t){E(!0);try{await Cn.setCurrent(z),s(z),o(null)}catch(j){console.error("Error setting current library:",j),alert("切换素材库失败: "+j.message)}finally{E(!1)}}},P=async()=>{if(!t)return;const z=e.find(O=>O.id===t);if(!(!z||!confirm(`确定要删除素材库"${z.name}"吗?
|
||||
|
||||
路径: ${z.path}
|
||||
|
||||
⚠️ 注意:
|
||||
• 将删除索引数据并释放数据库连接
|
||||
• 不会删除原始图片文件
|
||||
• .flypic 文件夹将保留,您可以手动删除`)))try{await Cn.delete(t),l(t),Te.getState().setImages([]),Te.getState().setFolders([]),Te.getState().setSelectedImage(null),Te.getState().setSelectedFolder(null);const O=e.filter(A=>A.id!==t);if(O.length>0){const A=O[0];await Cn.setCurrent(A.id),s(A.id)}console.log(`✅ 素材库已删除: ${z.name}`),console.log(`数据库连接已释放,可手动删除: ${z.path}\\.flypic`)}catch(O){console.error("Error deleting library:",O),alert("删除素材库失败: "+O.message)}},I=z=>{const j=new Set(c);j.has(z)?j.delete(z):j.add(z),f(j)},re=z=>{const j=[],O=A=>{A.forEach(J=>{J.children&&J.children.length>0&&(j.push(J.path),O(J.children))})};return O(z),j},T=()=>{const z=re(B.length>0?B:n);f(new Set(z))},D=()=>{f(new Set)},v=()=>{const z=re(B.length>0?B:n);return z.length>0&&z.every(j=>c.has(j))},B=ne.useMemo(()=>{if(!d)return n;const z=d.trim().toLowerCase().split(/\s+/).filter(J=>J.length>0);if(z.length===0)return n;const j=[],O=J=>J.reduce((q,V)=>{const ce=V.name.toLowerCase(),Y=V.path.toLowerCase(),Z=z.every(de=>ce.includes(de)),oe=z.every(de=>Y.includes(de));let ue=[];return V.children&&V.children.length>0&&(ue=O(V.children)),(Z||oe||ue.length>0)&&(q.push({...V,children:ue}),ue.length>0&&j.push(V.path)),q},[]),A=O(n);return j.length>0&&setTimeout(()=>{f(J=>{const q=new Set(J);return j.forEach(V=>q.add(V)),q})},0),A},[n,d]),se=(z,j)=>{z.stopPropagation(),I(j)},X=z=>{const j=z.children&&z.children.length>0;r!==z.path?o(z.path):j&&I(z.path)},H=(z,j=0)=>z.map(O=>{const A=c.has(O.path),J=O.children&&O.children.length>0,q=r===O.path;return C.jsxs("div",{children:[C.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:`${j*16+12}px`},onClick:()=>X(O),children:[J?C.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:V=>se(V,O.path),children:A?C.jsx(Ff,{className:"w-4 h-4 text-gray-500"}):C.jsx(N1,{className:"w-4 h-4 text-gray-500"})}):C.jsx("div",{className:"w-5 mr-1"}),C.jsx(Df,{className:"w-4 h-4 mr-2 text-gray-500 flex-shrink-0"}),C.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300 truncate flex-1",children:O.name}),C.jsx("span",{className:"text-xs text-gray-400 ml-2 flex-shrink-0",children:O.image_count})]}),J&&A&&H(O.children,j+1)]},O.path)});return C.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:[C.jsxs("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700",children:[C.jsx("div",{className:"flex items-center justify-between mb-3",children:C.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"素材库"})}),C.jsxs("div",{className:"flex gap-2",children:[C.jsxs("div",{className:"relative flex-1",children:[C.jsxs("select",{value:t||"",onChange:z=>{const j=z.target.value;j==="__add__"?h(!0):j&&L(j)},disabled:R,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&&C.jsx("option",{value:"",children:"暂无素材库"}),e.map(z=>C.jsx("option",{value:z.id,children:z.name},z.id)),C.jsx("option",{value:"__add__",style:{borderTop:"1px solid #ccc"},children:"+ 添加新素材库"})]}),C.jsx(Ff,{className:"absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none"})]}),t&&e.length>0&&C.jsx("button",{onClick:P,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:C.jsx(z1,{className:"w-4 h-4"})})]}),u&&C.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:[C.jsxs("div",{className:"flex items-center justify-between mb-2",children:[C.jsx("h3",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"添加素材库"}),C.jsx("button",{onClick:()=>h(!1),className:"p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600",children:C.jsx(L1,{className:"w-4 h-4 text-gray-500"})})]}),C.jsxs("div",{className:"space-y-2",children:[C.jsx("input",{type:"text",placeholder:"素材库名称",value:y,onChange:z=>w(z.target.value),onKeyDown:z=>z.key==="Enter"&&N(),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"}),C.jsx("input",{type:"text",placeholder:"文件夹路径(例如:C:\\Users\\Pictures)",value:p,onChange:z=>g(z.target.value),onKeyDown:z=>z.key==="Enter"&&N(),className:"w-full px-2 py-1.5 text-sm border border-gray-300 dark:
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(u,h){if(!i[u]){if(!r[u]){var y=typeof $s=="function"&&$s;if(!h&&y)return y(u,!0);if(a)return a(u,!0);var w=new Error("Cannot find module '"+u+"'");throw w.code="MODULE_NOT_FOUND",w}var p=i[u]={exports:{}};r[u][0].call(p.exports,function(g){var d=r[u][1][g];return o(d||g)},p,p.exports,n,r,i,s)}return i[u].exports}for(var a=typeof $s=="function"&&$s,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 u,h,y,w,p,g,d,_=[],c=0,f=l.length,x=f,k=s.getTypeOf(l)!=="string";c<l.length;)x=f-c,y=k?(u=l[c++],h=c<f?l[c++]:0,c<f?l[c++]:0):(u=l.charCodeAt(c++),h=c<f?l.charCodeAt(c++):0,c<f?l.charCodeAt(c++):0),w=u>>2,p=(3&u)<<4|h>>4,g=1<x?(15&h)<<2|y>>6:64,d=2<x?63&y:64,_.push(a.charAt(w)+a.charAt(p)+a.charAt(g)+a.charAt(d));return _.join("")},i.decode=function(l){var u,h,y,w,p,g,d=0,_=0,c="data:";if(l.substr(0,c.length)===c)throw new Error("Invalid base64 input, it looks like a data url.");var f,x=3*(l=l.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(l.charAt(l.length-1)===a.charAt(64)&&x--,l.charAt(l.length-2)===a.charAt(64)&&x--,x%1!=0)throw new Error("Invalid base64 input, bad content length.");for(f=o.uint8array?new Uint8Array(0|x):new Array(0|x);d<l.length;)u=a.indexOf(l.charAt(d++))<<2|(w=a.indexOf(l.charAt(d++)))>>4,h=(15&w)<<4|(p=a.indexOf(l.charAt(d++)))>>2,y=(3&p)<<6|(g=a.indexOf(l.charAt(d++))),f[_++]=u,p!==64&&(f[_++]=h),g!==64&&(f[_++]=y);return f}},{"./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 u(h,y,w,p,g){this.compressedSize=h,this.uncompressedSize=y,this.crc32=w,this.compression=p,this.compressedContent=g}u.prototype={getContentWorker:function(){var h=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),y=this;return h.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),h},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)}},u.createWorkerFrom=function(h,y,w){return h.pipe(new a).pipe(new l("uncompressedSize")).pipe(y.compressWorker(w)).pipe(new l("compressedSize")).withStreamInfo("compression",y)},r.exports=u},{"./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=[],u=0;u<256;u++){a=u;for(var h=0;h<8;h++)a=1&a?3988292384^a>>>1:a>>>1;l[u]=a}return l}();r.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(u,h,y,w){var p=o,g=w+y;u^=-1;for(var d=w;d<g;d++)u=u>>>8^p[255&(u^h[d])];return-1^u}(0|l,a,a.length,0):function(u,h,y,w){var p=o,g=w+y;u^=-1;for(var d=w;d<g;d++)u=u>>>8^p[255&(u^h.charCodeAt(d))];return-1^u}(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"),u=s?"uint8array":"array";function h(y,w){l.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=w,this.meta={}}i.magic="\b\0",a.inherits(h,l),h.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(u,y.data),!1)},h.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(w){y.push({data:w,meta:y.meta})}},i.compressWorker=function(y){return new h("Deflate",y)},i.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,i){function s(p,g){var d,_="";for(d=0;d<g;d++)_+=String.fromCharCode(255&p),p>>>=8;return _}function o(p,g,d,_,c,f){var x,k,R=p.file,E=p.compression,N=f!==u.Line truncated
|
||||
\0`,q+=s(O,2),q+=E.magic,q+=s(x,2),q+=s(k,2),q+=s(j.crc32,4),q+=s(j.compressedSize,4),q+=s(j.uncompressedSize,4),q+=s(L.length,2),q+=s(B.length,2),{fileRecord:y.LOCAL_FILE_HEADER+q+L+B,dirRecord:y.CENTRAL_FILE_HEADER+s(J,2)+q+s(re.length,2)+"\0\0\0\0"+s(A,4)+s(_,4)+L+B+re}}var a=n("../utils"),l=n("../stream/GenericWorker"),u=n("../utf8"),h=n("../crc32"),y=n("../signature");function w(p,g,d,_){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=d,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(w,l),w.prototype.push=function(p){var g=p.meta.percent||0,d=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:d?(g+100*(d-_-1))/d:100}}))},w.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var g=this.streamFiles&&!p.file.dir;if(g){var d=o(p,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:d.fileRecord,meta:{percent:0}})}else this.accumulate=!0},w.prototype.closedSource=function(p){this.accumulate=!1;var g=this.streamFiles&&!p.file.dir,d=o(p,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(d.dirRecord),g)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:d.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},w.prototype.flush=function(){for(var p=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var d=this.bytesWritten-p,_=function(c,f,x,k,R){var E=a.transformTo("string",R(k));return y.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(c,2)+s(c,2)+s(f,4)+s(x,4)+s(E.length,2)+E}(this.dirRecords.length,d,p,this.zipComment,this.encodeFileName);this.push({data:_,meta:{percent:100}})},w.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},w.prototype.registerPrevious=function(p){this._sources.push(p);var g=this;return p.on("data",function(d){g.processChunk(d)}),p.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),p.on("error",function(d){g.error(d)}),this},w.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))},w.prototype.error=function(p){var g=this._sources;if(!l.prototype.error.call(this,p))return!1;for(var d=0;d<g.length;d++)try{g[d].error(p)}catch{}return!0},w.prototype.lock=function(){l.prototype.lock.call(this);for(var p=this._sources,g=0;g<p.length;g++)p[g].lock()},r.exports=w},{"../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,u){var h=new o(l.streamFiles,u,l.platform,l.encodeFileName),y=0;try{a.forEach(function(w,p){y++;var g=function(f,x){var k=f||x,R=s[k];if(!R)throw new Error(k+" is not a valid compression method !");return R}(p.options.compression,l.compression),d=p.options.compressionOptions||l.compressionOptions||{},_=p.dir,c=p.date;p._compressWorker(g,d).withStreamInfo("file",{name:w,dir:_,date:c,comment:p.comment||"",unixPermissions:p.unixPermissions,dosPermissions:p.dosPermissions}).pipe(h)}),h.entriesCount=y}catch(w){h.error(w)}return h}},{"../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"),u=n("./stream/Crc32Probe"),h=n("./nodejsUtils");function y(w){return new o.Promise(function(p,g){var d=w.decompressed.getContentWorker().pipe(new u);d.on("error",function(_){g(_)}).on("end",function(){d.streamInfo.crc32!==w.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):p()}).resume()})}r.exports=function(w,p){var g=this
Line truncated
|
||||
`),J=j.map(q=>q.filename).join(`
|
||||
`);try{await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([A],{type:"text/html"}),"text/plain":new Blob([J],{type:"text/plain"})})]),c(!0),setTimeout(()=>c(!1),2e3)}catch(q){console.error("写入剪贴板失败:",q),alert(`复制失败。
|
||||
|
||||
提示:浏览器限制,多张图片会以 HTML 格式复制。
|
||||
可粘贴到 Word、富文本编辑器等。
|
||||
|
||||
如需单独使用,请使用"导出"功能。`)}}catch(j){console.error("复制图片失败:",j),alert("复制图片失败,请重试")}},se=async()=>{x(!0);try{const j=I?t:[e];if(j.length===1){const O=ct.getOriginalUrl(n,j[0].path),A=document.createElement("a");A.href=O,A.download=j[0].filename,A.target="_blank",document.body.appendChild(A),A.click(),document.body.removeChild(A)}else{const O=new Zf,A=O.folder("images");R(0);for(let V=0;V<j.length;V++){const ce=j[V],Y=ct.getOriginalUrl(n,ce.path);try{const oe=await(await fetch(Y)).blob();A.file(ce.filename,oe);const ue=Math.round((V+1)/j.length*90);R(ue),console.log(`已添加: ${ce.filename} (${V+1}/${j.length})`)}catch(Z){console.error(`下载失败: ${ce.filename}`,Z)}}R(95),console.log("正在生成 ZIP 文件...");const J=await O.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});R(100);const q=document.createElement("a");q.href=URL.createObjectURL(J),q.download=`FlyPic_导出_${j.length}张_${Date.now()}.zip`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(q.href),console.log("导出完成!")}}catch(j){console.error("导出失败:",j),alert("导出失败,请重试")}finally{x(!1)}},X=async()=>{if(!r){alert("请先选择一个文件夹");return}N(!0),P(0);try{const j=i.filter(ce=>ce.folder&&ce.folder.startsWith(r));if(j.length===0){alert("当前文件夹没有图片");return}const O=new Zf,A=r.split("/").pop()||"images",J=O.folder(A);for(let ce=0;ce<j.length;ce++){const Y=j[ce],Z=ct.getOriginalUrl(n,Y.path);try{const ue=await(await fetch(Z)).blob(),de=Y.folder.replace(r,"").replace(/^\//,""),ge=de?`${de}/${Y.filename}`:Y.filename;J.file(ge,ue);const we=Math.round((ce+1)/j.length*90);P(we),console.log(`已添加: ${ge} (${ce+1}/${j.length})`)}catch(oe){console.error(`下载失败: ${Y.filename}`,oe)}}P(95),console.log("正在生成 ZIP 文件...");const q=await O.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}});P(100);const V=document.createElement("a");V.href=URL.createObjectURL(q),V.download=`${A}_${j.length}张_${Date.now()}.zip`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(V.href),console.log("文件夹导出完成!")}catch(j){console.error("导出文件夹失败:",j),alert("导出文件夹失败,请重试")}finally{N(!1)}},H=j=>j<1024?j+" B":j<1024*1024?(j/1024).toFixed(2)+" KB":(j/(1024*1024)).toFixed(2)+" MB",z=j=>new Date(j).toLocaleString("zh-CN");return C.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&&C.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex items-center",children:C.jsxs("button",{onClick:()=>s("main"),className:"flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500",children:[C.jsx(E1,{className:"w-5 h-5"}),C.jsx("span",{className:"text-sm font-medium",children:"返回"})]})}),C.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0",children:C.jsxs("div",{className:"w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative",children:[C.jsx("img",{src:h,alt:re.filename,decoding:"async",className:`w-full h-full object-contain transition-opacity duration-300 ${w?"opacity-75":"opacity-100"}`}),w&&C.jsx("div",{className:"absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded",children:"加载原图中..."})]})}),C.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 min-h-0",children:C.jsxs("div",{children:[C.jsx("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"基本信息"}),C.jsxs("div",{className:"space-y-2 text-sm",children:[C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"文件名:"}),C.jsx("p",{className:"text-gray-900 dark:text-gray-100 break-all",children:e.filename})]}),C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"尺寸:"}),C.jsxs("p",{className:"text-gray-900 dark:text-gray-100",children:[e.width," × ",e.height]})]}),C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"大小:"}),C.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:H(e.size)})]}),C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"格式:"}),C.jsx("p",{className:"text-gray-900 dark:text-gray-100 uppercase",children:e.format})]}),C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"创建时间:"}),C.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:z(e.created_at)})]}),C.jsxs("div",{children:[C.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:"修改时间:"}),C.jsx("p",{className:"text-gray-900 dark:text-gray-100",children:z(e.modified_at)})]}),C.jsxs("div",{children:[C.jsx("span",{className:"tex
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,14 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FlyPic - 图片素材库管理</title>
|
||||
<script type="module" crossorigin src="/assets/index-Ct4ORqFz.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DYf0hRmn.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>␍
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,154 @@
|
||||
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 { getLibrary } = require('../utils/config');
|
||||
|
||||
// Get images with search and filters
|
||||
router.get('/', (req, res) => {
|
||||
try {
|
||||
const { libraryId, keywords, folder, formats, minSize, maxSize, startDate, endDate } = 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);
|
||||
|
||||
const images = db.searchImages(keywords || '', filters);
|
||||
|
||||
res.json({ images });
|
||||
} 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', (req, res) => {
|
||||
try {
|
||||
const { libraryId, filename } = req.params;
|
||||
|
||||
const library = getLibrary(libraryId);
|
||||
if (!library) {
|
||||
return res.status(404).json({ error: 'Library not found' });
|
||||
}
|
||||
|
||||
// 直接从 thumbnails 目录获取
|
||||
const thumbnailPath = path.join(library.path, '.flypic', 'thumbnails', filename);
|
||||
|
||||
if (!fs.existsSync(thumbnailPath)) {
|
||||
return res.status(404).json({ error: 'Thumbnail not found' });
|
||||
}
|
||||
|
||||
res.sendFile(thumbnailPath);
|
||||
} 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 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;
|
||||
@@ -0,0 +1,183 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
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');
|
||||
console.log(`[Delete] Closing database connection for: ${library.path}`);
|
||||
dbPool.close(library.path);
|
||||
|
||||
// 等待一下,确保连接完全关闭
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
// 删除索引
|
||||
removeLibrary(id);
|
||||
|
||||
console.log(`✅ Library removed and database connection released: ${library.name}`);
|
||||
|
||||
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', (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const config = loadConfig();
|
||||
const dbPool = require('../database/dbPool');
|
||||
|
||||
// 获取旧的当前素材库
|
||||
const oldLibraryId = config.currentLibraryId;
|
||||
if (oldLibraryId && oldLibraryId !== id) {
|
||||
const oldLibrary = config.libraries.find(lib => lib.id === oldLibraryId);
|
||||
if (oldLibrary) {
|
||||
// 关闭旧素材库的数据库连接
|
||||
console.log(`[Switch] Closing old library connection: ${oldLibrary.name}`);
|
||||
dbPool.close(oldLibrary.path);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新的当前素材库
|
||||
setCurrentLibrary(id);
|
||||
|
||||
const newLibrary = config.libraries.find(lib => lib.id === id);
|
||||
console.log(`[Switch] Switched to library: ${newLibrary?.name}`);
|
||||
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,121 @@
|
||||
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');
|
||||
|
||||
// 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
|
||||
res.json({ message: 'Scan started' });
|
||||
|
||||
scanLibrary(library.path, db, (progress) => {
|
||||
io.emit('scanProgress', {
|
||||
libraryId,
|
||||
...progress
|
||||
});
|
||||
}).then(results => {
|
||||
dbPool.release(library.path);
|
||||
updateLibrary(libraryId, { lastScan: Date.now() });
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
}).catch(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
|
||||
res.json({ message: 'Sync started' });
|
||||
|
||||
syncLibrary(library.path, db).then(results => {
|
||||
dbPool.release(library.path);
|
||||
updateLibrary(libraryId, { lastScan: Date.now() });
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
}).catch(error => {
|
||||
dbPool.release(library.path);
|
||||
io.emit('scanError', { libraryId, error: error.message });
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,73 @@
|
||||
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');
|
||||
|
||||
fileWatcher.watch(libraryId, io);
|
||||
|
||||
res.json({
|
||||
message: 'File watching started',
|
||||
libraryId,
|
||||
isWatching: true
|
||||
});
|
||||
} 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;
|
||||
@@ -0,0 +1,93 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const http = require('http');
|
||||
const { Server } = require('socket.io');
|
||||
const fileWatcher = require('./utils/fileWatcher');
|
||||
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server, {
|
||||
cors: {
|
||||
origin: process.env.FRONTEND_DIST ? false : 'http://localhost:5173',
|
||||
methods: ['GET', 'POST']
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = process.env.TRIM_SERVICE_PORT || process.env.PORT || 3000;
|
||||
|
||||
// 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')
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (require('fs').existsSync(p)) {
|
||||
FRONTEND_DIST = p;
|
||||
console.log('✅ Found frontend at:', p);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!FRONTEND_DIST) {
|
||||
console.log('⚠️ Frontend not found, tried:', possiblePaths);
|
||||
}
|
||||
}
|
||||
|
||||
// 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'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 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}`);
|
||||
});
|
||||
|
||||
// Cleanup on exit
|
||||
process.on('SIGINT', () => {
|
||||
console.log('\nShutting down...');
|
||||
fileWatcher.unwatchAll();
|
||||
process.exit(0);
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
/**
|
||||
* Get config directory based on environment
|
||||
*/
|
||||
function getConfigDir() {
|
||||
// Check if running on fnOS
|
||||
if (process.env.TRIM_PKGVAR) {
|
||||
return process.env.TRIM_PKGVAR;
|
||||
}
|
||||
|
||||
// Windows
|
||||
if (process.platform === 'win32') {
|
||||
return path.join(process.env.APPDATA || os.homedir(), 'FlyPic');
|
||||
}
|
||||
|
||||
// Linux/Mac
|
||||
return path.join(os.homedir(), '.flypic');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config file path
|
||||
*/
|
||||
function getConfigPath() {
|
||||
const configDir = getConfigDir();
|
||||
if (!fs.existsSync(configDir)) {
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
}
|
||||
return path.join(configDir, 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Load configuration
|
||||
*/
|
||||
function loadConfig() {
|
||||
const configPath = getConfigPath();
|
||||
|
||||
if (!fs.existsSync(configPath)) {
|
||||
const defaultConfig = {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
// UI preferences
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16,
|
||||
leftPanelWidth: 256, // 左侧边栏宽度
|
||||
rightPanelWidth: 320 // 右侧边栏宽度
|
||||
}
|
||||
};
|
||||
saveConfig(defaultConfig);
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = fs.readFileSync(configPath, 'utf8');
|
||||
const config = JSON.parse(data);
|
||||
|
||||
// Ensure preferences exist (for backward compatibility)
|
||||
if (!config.preferences) {
|
||||
config.preferences = {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
};
|
||||
}
|
||||
|
||||
return config;
|
||||
} catch (error) {
|
||||
console.error('Error loading config:', error);
|
||||
return {
|
||||
libraries: [],
|
||||
theme: 'light',
|
||||
currentLibraryId: null,
|
||||
preferences: {
|
||||
thumbnailHeight: 200,
|
||||
rowGap: 32,
|
||||
columnGap: 16
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save configuration
|
||||
*/
|
||||
function saveConfig(config) {
|
||||
const configPath = getConfigPath();
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error saving config:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add library to config
|
||||
*/
|
||||
function addLibrary(name, libraryPath) {
|
||||
const config = loadConfig();
|
||||
const id = Date.now().toString();
|
||||
|
||||
config.libraries.push({
|
||||
id,
|
||||
name,
|
||||
path: libraryPath,
|
||||
lastScan: null,
|
||||
createdAt: Date.now()
|
||||
});
|
||||
|
||||
if (!config.currentLibraryId) {
|
||||
config.currentLibraryId = id;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove library from config
|
||||
*/
|
||||
function removeLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.libraries = config.libraries.filter(lib => lib.id !== libraryId);
|
||||
|
||||
if (config.currentLibraryId === libraryId) {
|
||||
config.currentLibraryId = config.libraries.length > 0 ? config.libraries[0].id : null;
|
||||
}
|
||||
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update library
|
||||
*/
|
||||
function updateLibrary(libraryId, updates) {
|
||||
const config = loadConfig();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (library) {
|
||||
Object.assign(library, updates);
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get library by ID
|
||||
*/
|
||||
function getLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
return config.libraries.find(lib => lib.id === libraryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set current library
|
||||
*/
|
||||
function setCurrentLibrary(libraryId) {
|
||||
const config = loadConfig();
|
||||
config.currentLibraryId = libraryId;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update preferences
|
||||
*/
|
||||
function updatePreferences(preferences) {
|
||||
const config = loadConfig();
|
||||
config.preferences = { ...config.preferences, ...preferences };
|
||||
saveConfig(config);
|
||||
return config.preferences;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update theme
|
||||
*/
|
||||
function updateTheme(theme) {
|
||||
const config = loadConfig();
|
||||
config.theme = theme;
|
||||
saveConfig(config);
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getConfigDir,
|
||||
getConfigPath,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
addLibrary,
|
||||
removeLibrary,
|
||||
updateLibrary,
|
||||
getLibrary,
|
||||
setCurrentLibrary,
|
||||
updatePreferences,
|
||||
updateTheme
|
||||
};
|
||||
@@ -0,0 +1,230 @@
|
||||
const chokidar = require('chokidar');
|
||||
const path = require('path');
|
||||
const { getLibrary } = require('./config');
|
||||
const { syncLibrary, applyChangesFromEvents } = require('./scanner');
|
||||
const dbPool = require('../database/dbPool');
|
||||
|
||||
class FileWatcher {
|
||||
constructor() {
|
||||
this.watchers = new Map(); // libraryId -> watcher
|
||||
this.debounceTimers = new Map(); // libraryId -> { timer, forceRebuildFolders }
|
||||
this.changeBuffers = new Map(); // libraryId -> { filesAdded, filesChanged, filesRemoved, dirsAdded, dirsRemoved }
|
||||
}
|
||||
|
||||
// 获取或创建变更缓冲区
|
||||
_getBuffer(libraryId) {
|
||||
if (!this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
}
|
||||
return this.changeBuffers.get(libraryId);
|
||||
}
|
||||
|
||||
// 缓冲区事件数量
|
||||
_bufferCount(buf) {
|
||||
return (
|
||||
buf.filesAdded.size +
|
||||
buf.filesChanged.size +
|
||||
buf.filesRemoved.size +
|
||||
buf.dirsAdded.size +
|
||||
buf.dirsRemoved.size
|
||||
);
|
||||
}
|
||||
|
||||
// 启动监控
|
||||
watch(libraryId, io) {
|
||||
// 如果已经在监控,先停止
|
||||
if (this.watchers.has(libraryId)) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
|
||||
const library = getLibrary(libraryId);
|
||||
if (!library) {
|
||||
console.error(`Library ${libraryId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查路径是否存在和可访问
|
||||
const fs = require('fs');
|
||||
try {
|
||||
fs.accessSync(library.path, fs.constants.R_OK);
|
||||
} catch (error) {
|
||||
console.error(`Cannot access library path: ${library.path}`, error.message);
|
||||
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Starting file watcher for library: ${library.name} (${library.path})`);
|
||||
|
||||
// 支持的图片格式
|
||||
const imageExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff'];
|
||||
const pattern = `**/*.{${imageExtensions.join(',')}}`;
|
||||
|
||||
// 创建监控器(监控文件和文件夹)
|
||||
const watcher = chokidar.watch([pattern, '**/'], {
|
||||
cwd: library.path,
|
||||
ignored: [
|
||||
'**/node_modules/**',
|
||||
'**/.git/**',
|
||||
'**/.flypic/**', // 忽略自己的缓存目录
|
||||
'**/.*' // 忽略隐藏文件
|
||||
],
|
||||
persistent: true,
|
||||
ignoreInitial: true, // 忽略初始扫描
|
||||
awaitWriteFinish: {
|
||||
stabilityThreshold: 1200, // 文件稳定 1.2 秒后触发,提升响应
|
||||
pollInterval: 100
|
||||
}
|
||||
});
|
||||
|
||||
// 防抖处理:多个文件变化合并为一次同步(自适应时长)
|
||||
const debouncedSync = (forceRebuildFolders = false) => {
|
||||
const buf = this._getBuffer(libraryId);
|
||||
const changeCount = this._bufferCount(buf);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const oldTimer = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(oldTimer.timer);
|
||||
// 聚合 forceRebuildFolders 标记
|
||||
forceRebuildFolders = forceRebuildFolders || oldTimer.forceRebuildFolders;
|
||||
}
|
||||
|
||||
// 自适应防抖时间:少量变化更快响应
|
||||
let debounceMs = 5000;
|
||||
if (changeCount <= 1) debounceMs = 1200;
|
||||
else if (changeCount <= 10) debounceMs = 2000;
|
||||
else if (changeCount <= 50) debounceMs = 3500;
|
||||
else if (changeCount <= 200) debounceMs = 5000;
|
||||
else debounceMs = 8000; // 超大批量进一步聚合
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
const snapshot = this._getBuffer(libraryId);
|
||||
// 清空缓冲区(开始新一轮累计)
|
||||
this.changeBuffers.set(libraryId, {
|
||||
filesAdded: new Set(),
|
||||
filesChanged: new Set(),
|
||||
filesRemoved: new Set(),
|
||||
dirsAdded: new Set(),
|
||||
dirsRemoved: new Set()
|
||||
});
|
||||
|
||||
// 从连接池获取数据库连接
|
||||
const db = dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const total = this._bufferCount(snapshot);
|
||||
let results;
|
||||
|
||||
if (forceRebuildFolders || total > 200) {
|
||||
// 大量变化或目录级变化:走增量全量路径(更稳)
|
||||
results = await syncLibrary(library.path, db, true);
|
||||
} else {
|
||||
// 小批量变化:基于事件的快速同步
|
||||
results = await applyChangesFromEvents(library.path, db, {
|
||||
filesAdded: Array.from(snapshot.filesAdded),
|
||||
filesChanged: Array.from(snapshot.filesChanged),
|
||||
filesRemoved: Array.from(snapshot.filesRemoved),
|
||||
dirsAdded: Array.from(snapshot.dirsAdded),
|
||||
dirsRemoved: Array.from(snapshot.dirsRemoved)
|
||||
});
|
||||
}
|
||||
|
||||
// 通过 Socket.IO 通知前端
|
||||
io.emit('scanComplete', { libraryId, results });
|
||||
console.log(`Sync complete for ${library.name}:`, results);
|
||||
} catch (error) {
|
||||
console.error(`Sync error for ${library.name}:`, error);
|
||||
io.emit('scanError', { libraryId, error: error.message });
|
||||
} finally {
|
||||
// 释放数据库连接(不关闭,复用)
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}, debounceMs);
|
||||
|
||||
this.debounceTimers.set(libraryId, { timer, forceRebuildFolders });
|
||||
};
|
||||
|
||||
// 监听文件和文件夹变化(写入缓冲,统一合并处理)
|
||||
watcher
|
||||
.on('add', (filePath) => {
|
||||
this._getBuffer(libraryId).filesAdded.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('unlink', (filePath) => {
|
||||
this._getBuffer(libraryId).filesRemoved.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('change', (filePath) => {
|
||||
this._getBuffer(libraryId).filesChanged.add(filePath);
|
||||
debouncedSync();
|
||||
})
|
||||
.on('addDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsAdded.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('unlinkDir', (dirPath) => {
|
||||
this._getBuffer(libraryId).dirsRemoved.add(dirPath);
|
||||
debouncedSync(true); // 强制重建文件夹结构
|
||||
})
|
||||
.on('error', (error) => {
|
||||
console.error(`Watcher error for ${library.name}:`, error);
|
||||
})
|
||||
.on('ready', () => {
|
||||
console.log(`File watcher ready for: ${library.name}`);
|
||||
});
|
||||
|
||||
this.watchers.set(libraryId, watcher);
|
||||
}
|
||||
|
||||
// 停止监控
|
||||
unwatch(libraryId) {
|
||||
const watcher = this.watchers.get(libraryId);
|
||||
if (watcher) {
|
||||
watcher.close();
|
||||
this.watchers.delete(libraryId);
|
||||
console.log(`Stopped file watcher for library: ${libraryId}`);
|
||||
}
|
||||
|
||||
// 清除防抖定时器
|
||||
if (this.debounceTimers.has(libraryId)) {
|
||||
const timerObj = this.debounceTimers.get(libraryId);
|
||||
clearTimeout(timerObj.timer);
|
||||
this.debounceTimers.delete(libraryId);
|
||||
}
|
||||
|
||||
// 清空缓冲区
|
||||
if (this.changeBuffers.has(libraryId)) {
|
||||
this.changeBuffers.delete(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 停止所有监控
|
||||
unwatchAll() {
|
||||
for (const libraryId of this.watchers.keys()) {
|
||||
this.unwatch(libraryId);
|
||||
}
|
||||
}
|
||||
|
||||
// 获取监控状态
|
||||
isWatching(libraryId) {
|
||||
return this.watchers.has(libraryId);
|
||||
}
|
||||
|
||||
// 获取所有正在监控的库
|
||||
getWatchedLibraries() {
|
||||
return Array.from(this.watchers.keys());
|
||||
}
|
||||
}
|
||||
|
||||
// 单例模式
|
||||
const fileWatcher = new FileWatcher();
|
||||
|
||||
module.exports = fileWatcher;
|
||||
@@ -0,0 +1,445 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { glob } = require('glob');
|
||||
const {
|
||||
isImageFile,
|
||||
calculateFileHash,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails
|
||||
} = require('./thumbnail');
|
||||
|
||||
/**
|
||||
* Get all image files in a directory
|
||||
*/
|
||||
async function getAllImageFiles(libraryPath) {
|
||||
// 仅匹配常见图片扩展,避免遍历所有非图片文件,显著降低 IO
|
||||
const exts = '{jpg,jpeg,png,webp,gif,bmp,tiff}';
|
||||
const pattern = path.join(libraryPath, '**', `*.${exts}`).replace(/\\/g, '/');
|
||||
const files = await glob(pattern, {
|
||||
nodir: true,
|
||||
nocase: true, // 大小写不敏感(Windows/macOS)
|
||||
ignore: ['**/.flypic/**', '**/node_modules/**']
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a folder and its parents exist in DB
|
||||
*/
|
||||
function ensureFolderChain(db, folderPath) {
|
||||
if (!folderPath || folderPath === '.' || folderPath === '') return;
|
||||
let current = folderPath;
|
||||
const visited = new Set();
|
||||
while (current && current !== '.' && !visited.has(current)) {
|
||||
visited.add(current);
|
||||
const parent = path.dirname(current);
|
||||
const name = path.basename(current);
|
||||
const existing = db.getFolderByPath(current);
|
||||
if (!existing) {
|
||||
db.insertFolder({
|
||||
path: current,
|
||||
parent_path: parent === '.' ? '' : parent,
|
||||
name,
|
||||
image_count: 0
|
||||
});
|
||||
}
|
||||
if (parent === current) break;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply changes from file system events quickly without full rescan
|
||||
* events = {
|
||||
* filesAdded: [relPath],
|
||||
* filesChanged: [relPath],
|
||||
* filesRemoved: [relPath],
|
||||
* dirsAdded: [relDir],
|
||||
* dirsRemoved: [relDir]
|
||||
* }
|
||||
*/
|
||||
async function applyChangesFromEvents(libraryPath, db, events) {
|
||||
try {
|
||||
// Normalize helper to OS-specific separators to match DB records
|
||||
const norm = (p) => path.normalize(p);
|
||||
|
||||
const affectedFolders = new Set();
|
||||
const results = { added: 0, modified: 0, deleted: 0, foldersAdded: 0, foldersRemoved: 0 };
|
||||
|
||||
// Handle directory additions (ensure chain exists)
|
||||
for (const dir of (events.dirsAdded || [])) {
|
||||
const d = norm(dir);
|
||||
ensureFolderChain(db, d);
|
||||
results.foldersAdded++;
|
||||
// update parents too
|
||||
let cur = d;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file additions
|
||||
for (const file of (events.filesAdded || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const folder = path.dirname(rel);
|
||||
ensureFolderChain(db, folder);
|
||||
await processImage(full, libraryPath, db);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.added++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing added file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file changes
|
||||
for (const file of (events.filesChanged || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
const full = path.join(libraryPath, rel);
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(full)) {
|
||||
console.warn(`File not found, skipping: ${full}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await processImage(full, libraryPath, db);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
results.modified++;
|
||||
} catch (error) {
|
||||
console.error(`Error processing changed file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle file removals
|
||||
for (const file of (events.filesRemoved || [])) {
|
||||
try {
|
||||
const rel = norm(file);
|
||||
db.deleteImage(rel);
|
||||
const folder = path.dirname(rel);
|
||||
affectedFolders.add(folder);
|
||||
// parents
|
||||
let cur = folder;
|
||||
while (cur && cur !== '.') {
|
||||
affectedFolders.add(cur);
|
||||
const parent = path.dirname(cur);
|
||||
if (parent === cur) break;
|
||||
cur = parent;
|
||||
}
|
||||
results.deleted++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting file ${file}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle directory removals (bulk delete)
|
||||
for (const dir of (events.dirsRemoved || [])) {
|
||||
try {
|
||||
const d = norm(dir);
|
||||
// delete images and folders under this dir
|
||||
db.deleteImagesByFolderPrefix(d);
|
||||
db.deleteFoldersByPrefix(d);
|
||||
const parent = path.dirname(d);
|
||||
if (parent && parent !== '.') affectedFolders.add(parent);
|
||||
results.foldersRemoved++;
|
||||
} catch (error) {
|
||||
console.error(`Error deleting directory ${dir}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Update counts for all affected folders
|
||||
affectedFolders.forEach((folderPath) => {
|
||||
if (folderPath && folderPath !== '.') {
|
||||
try {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
} catch (error) {
|
||||
console.error(`Error updating folder count ${folderPath}:`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error in applyChangesFromEvents:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get folder structure
|
||||
*/
|
||||
async function getFolderStructure(libraryPath) {
|
||||
const folders = [];
|
||||
|
||||
function scanDir(dirPath, parentPath = '') {
|
||||
const items = fs.readdirSync(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const item of items) {
|
||||
if (item.isDirectory() && !item.name.startsWith('.')) {
|
||||
const fullPath = path.join(dirPath, item.name);
|
||||
const relativePath = path.relative(libraryPath, fullPath);
|
||||
|
||||
folders.push({
|
||||
path: relativePath,
|
||||
parent_path: parentPath,
|
||||
name: item.name,
|
||||
image_count: 0
|
||||
});
|
||||
|
||||
scanDir(fullPath, relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scanDir(libraryPath);
|
||||
return folders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single image file
|
||||
*/
|
||||
async function processImage(imagePath, libraryPath, db) {
|
||||
try {
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
const filename = path.basename(imagePath);
|
||||
const folder = path.dirname(relativePath);
|
||||
|
||||
// Check if image already exists in database
|
||||
const existing = db.getImageByPath(relativePath);
|
||||
const currentHash = calculateFileHash(imagePath);
|
||||
|
||||
// Skip if file hasn't changed
|
||||
if (existing && existing.file_hash === currentHash) {
|
||||
return { status: 'skipped', path: relativePath };
|
||||
}
|
||||
|
||||
// Get image metadata
|
||||
const metadata = await getImageMetadata(imagePath);
|
||||
if (!metadata) {
|
||||
return { status: 'error', path: relativePath, error: 'Failed to read metadata' };
|
||||
}
|
||||
|
||||
// Generate thumbnails
|
||||
const thumbnails = await generateImageThumbnails(imagePath, libraryPath);
|
||||
|
||||
// Insert/update in database
|
||||
db.insertImage({
|
||||
path: relativePath,
|
||||
filename: filename,
|
||||
folder: folder,
|
||||
size: metadata.size,
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
format: metadata.format,
|
||||
created_at: Math.floor(metadata.created_at),
|
||||
modified_at: Math.floor(metadata.modified_at),
|
||||
file_hash: currentHash,
|
||||
thumbnail_path: thumbnails.thumbnail_path,
|
||||
thumbnail_size: thumbnails.thumbnail_size
|
||||
});
|
||||
|
||||
return { status: 'processed', path: relativePath };
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', imagePath, error);
|
||||
return { status: 'error', path: imagePath, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan library and update database
|
||||
*/
|
||||
async function scanLibrary(libraryPath, db, onProgress) {
|
||||
try {
|
||||
// Get all image files
|
||||
const files = await getAllImageFiles(libraryPath);
|
||||
const total = files.length;
|
||||
|
||||
console.log(`Found ${total} images in library`);
|
||||
|
||||
// Get folder structure
|
||||
const folders = await getFolderStructure(libraryPath);
|
||||
folders.forEach(folder => db.insertFolder(folder));
|
||||
|
||||
// Process images in batches
|
||||
const batchSize = 50;
|
||||
const results = {
|
||||
processed: 0,
|
||||
skipped: 0,
|
||||
errors: 0
|
||||
};
|
||||
|
||||
for (let i = 0; i < files.length; i += batchSize) {
|
||||
const batch = files.slice(i, i + batchSize);
|
||||
|
||||
await Promise.all(
|
||||
batch.map(file => processImage(file, libraryPath, db))
|
||||
).then(batchResults => {
|
||||
batchResults.forEach(result => {
|
||||
if (result.status === 'processed') results.processed++;
|
||||
else if (result.status === 'skipped') results.skipped++;
|
||||
else if (result.status === 'error') results.errors++;
|
||||
});
|
||||
});
|
||||
|
||||
// Report progress
|
||||
if (onProgress) {
|
||||
onProgress({
|
||||
total,
|
||||
current: Math.min(i + batchSize, total),
|
||||
percent: Math.round((Math.min(i + batchSize, total) / total) * 100),
|
||||
currentFile: batch[batch.length - 1]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Update folder image counts
|
||||
folders.forEach(folder => {
|
||||
db.updateFolderImageCount(folder.path);
|
||||
});
|
||||
|
||||
console.log('Scan complete:', results);
|
||||
return results;
|
||||
} catch (error) {
|
||||
console.error('Error scanning library:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync library (incremental scan)
|
||||
*/
|
||||
async function syncLibrary(libraryPath, db, forceRebuildFolders = false) {
|
||||
try {
|
||||
// Get all current files
|
||||
const currentFiles = await getAllImageFiles(libraryPath);
|
||||
const currentPaths = new Set(
|
||||
currentFiles.map(file => path.relative(libraryPath, file))
|
||||
);
|
||||
|
||||
// Get database files
|
||||
const dbImages = db.getAllImages();
|
||||
const dbPaths = new Set(dbImages.map(img => img.path));
|
||||
|
||||
// Find new, modified, and deleted files
|
||||
const toAdd = [...currentPaths].filter(p => !dbPaths.has(p));
|
||||
const toCheck = [...currentPaths].filter(p => dbPaths.has(p));
|
||||
const toDelete = [...dbPaths].filter(p => !currentPaths.has(p));
|
||||
|
||||
console.log(`Sync: ${toAdd.length} new, ${toCheck.length} to check, ${toDelete.length} deleted`);
|
||||
|
||||
// Process new files
|
||||
for (const relativePath of toAdd) {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
}
|
||||
|
||||
// Check modified files
|
||||
for (const relativePath of toCheck) {
|
||||
const fullPath = path.join(libraryPath, relativePath);
|
||||
const existing = db.getImageByPath(relativePath);
|
||||
const currentHash = calculateFileHash(fullPath);
|
||||
|
||||
if (existing.file_hash !== currentHash) {
|
||||
await processImage(fullPath, libraryPath, db);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete removed files
|
||||
for (const relativePath of toDelete) {
|
||||
db.deleteImage(relativePath);
|
||||
// TODO: Clean up thumbnail files
|
||||
}
|
||||
|
||||
// Rebuild folder structure if there are changes or forced
|
||||
if (toAdd.length > 0 || toDelete.length > 0 || forceRebuildFolders) {
|
||||
console.log('Rebuilding folder structure...');
|
||||
|
||||
// Get current folder structure from file system
|
||||
const currentFolders = await getFolderStructure(libraryPath);
|
||||
|
||||
// Get existing folders from database
|
||||
const dbFolders = db.getAllFolders();
|
||||
const dbFolderPaths = new Set(dbFolders.map(f => f.path));
|
||||
|
||||
// Find new and deleted folders
|
||||
const currentFolderPaths = new Set(currentFolders.map(f => f.path));
|
||||
const foldersToAdd = currentFolders.filter(f => !dbFolderPaths.has(f.path));
|
||||
const foldersToDelete = dbFolders.filter(f => !currentFolderPaths.has(f.path));
|
||||
|
||||
// Add new folders
|
||||
foldersToAdd.forEach(folder => {
|
||||
db.insertFolder(folder);
|
||||
});
|
||||
|
||||
// Delete removed folders
|
||||
foldersToDelete.forEach(folder => {
|
||||
db.deleteFolder(folder.path);
|
||||
});
|
||||
|
||||
console.log(`Folders: +${foldersToAdd.length}, -${foldersToDelete.length}`);
|
||||
|
||||
// Update folder image counts
|
||||
console.log('Updating folder image counts...');
|
||||
const affectedFolders = new Set();
|
||||
|
||||
// Collect all affected folders (including parent folders)
|
||||
[...toAdd, ...toDelete].forEach(relativePath => {
|
||||
let folderPath = path.dirname(relativePath);
|
||||
|
||||
// Add current folder and all parent folders
|
||||
while (folderPath && folderPath !== '.') {
|
||||
affectedFolders.add(folderPath);
|
||||
const parent = path.dirname(folderPath);
|
||||
if (parent === folderPath) break; // Reached root
|
||||
folderPath = parent;
|
||||
}
|
||||
});
|
||||
|
||||
// Update counts for all affected folders
|
||||
affectedFolders.forEach(folderPath => {
|
||||
db.updateFolderImageCount(folderPath);
|
||||
});
|
||||
|
||||
console.log(`Updated ${affectedFolders.size} folder counts`);
|
||||
}
|
||||
|
||||
return {
|
||||
added: toAdd.length,
|
||||
modified: toCheck.length,
|
||||
deleted: toDelete.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error syncing library:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getAllImageFiles,
|
||||
getFolderStructure,
|
||||
processImage,
|
||||
scanLibrary,
|
||||
syncLibrary,
|
||||
applyChangesFromEvents
|
||||
};
|
||||
@@ -0,0 +1,180 @@
|
||||
const sharp = require('sharp');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const SUPPORTED_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff', 'tif'];
|
||||
|
||||
/**
|
||||
* Check if file is a supported image
|
||||
*/
|
||||
function isImageFile(filename) {
|
||||
const ext = path.extname(filename).toLowerCase().slice(1);
|
||||
return SUPPORTED_FORMATS.includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate file hash for change detection
|
||||
*/
|
||||
function calculateFileHash(filePath) {
|
||||
const fileBuffer = fs.readFileSync(filePath);
|
||||
const hashSum = crypto.createHash('md5');
|
||||
hashSum.update(fileBuffer);
|
||||
return hashSum.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thumbnail configuration based on original image size
|
||||
*/
|
||||
function getThumbnailConfig(originalWidth, originalHeight, targetHeight = 200) {
|
||||
const targetWidth = Math.round((originalWidth / originalHeight) * targetHeight);
|
||||
|
||||
// 优化质量配置:提高质量,减少模糊
|
||||
// WebP 格式建议质量范围:80-95
|
||||
let quality = 90;
|
||||
const originalSize = originalWidth * originalHeight;
|
||||
|
||||
if (originalSize > 10000000) { // >10MP
|
||||
quality = 85; // 提高到 85(之前 70)
|
||||
} else if (originalSize > 5000000) { // 5-10MP
|
||||
quality = 88; // 提高到 88(之前 75)
|
||||
} else if (originalSize > 2000000) { // 2-5MP
|
||||
quality = 90; // 提高到 90(之前 80)
|
||||
}
|
||||
|
||||
return {
|
||||
width: targetWidth,
|
||||
height: targetHeight,
|
||||
quality: quality,
|
||||
format: 'webp'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for an image with dynamic quality adjustment
|
||||
*/
|
||||
async function generateThumbnail(inputPath, outputPath, targetHeight = 200) {
|
||||
try {
|
||||
// Get image metadata
|
||||
const metadata = await sharp(inputPath).metadata();
|
||||
const config = getThumbnailConfig(metadata.width, metadata.height, targetHeight);
|
||||
|
||||
const TARGET_MIN_SIZE = 50 * 1024; // 50KB (提高下限)
|
||||
const TARGET_MAX_SIZE = 150 * 1024; // 150KB (提高上限)
|
||||
const MAX_ATTEMPTS = 3;
|
||||
|
||||
let quality = config.quality;
|
||||
let attempt = 0;
|
||||
let finalSize = 0;
|
||||
|
||||
// 动态调整质量,直到文件大小在目标范围内
|
||||
while (attempt < MAX_ATTEMPTS) {
|
||||
// Generate thumbnail with current quality
|
||||
await sharp(inputPath)
|
||||
.resize(config.width, config.height, {
|
||||
fit: 'cover',
|
||||
position: 'center',
|
||||
kernel: 'lanczos3' // 使用高质量的缩放算法
|
||||
})
|
||||
.webp({
|
||||
quality: quality,
|
||||
effort: 6, // 提高压缩质量(0-6,6最好但最慢)
|
||||
smartSubsample: true // 智能色度子采样
|
||||
})
|
||||
.toFile(outputPath);
|
||||
|
||||
// Check file size
|
||||
const stats = fs.statSync(outputPath);
|
||||
finalSize = stats.size;
|
||||
|
||||
// 如果在目标范围内,完成
|
||||
if (finalSize >= TARGET_MIN_SIZE && finalSize <= TARGET_MAX_SIZE) {
|
||||
console.log(`✅ Thumbnail generated: ${finalSize} bytes (quality: ${quality})`);
|
||||
break;
|
||||
}
|
||||
|
||||
// 如果太大,降低质量
|
||||
if (finalSize > TARGET_MAX_SIZE) {
|
||||
const ratio = TARGET_MAX_SIZE / finalSize;
|
||||
quality = Math.max(70, Math.round(quality * ratio * 0.9)); // 最低质量提高到 70
|
||||
console.log(`⬇️ File too large (${finalSize} bytes), reducing quality to ${quality}`);
|
||||
}
|
||||
// 如果太小,提高质量
|
||||
else if (finalSize < TARGET_MIN_SIZE) {
|
||||
const ratio = TARGET_MIN_SIZE / finalSize;
|
||||
quality = Math.min(98, Math.round(quality * ratio * 1.1)); // 最高质量提高到 98
|
||||
console.log(`⬆️ File too small (${finalSize} bytes), increasing quality to ${quality}`);
|
||||
}
|
||||
|
||||
attempt++;
|
||||
|
||||
// 最后一次尝试,接受结果
|
||||
if (attempt >= MAX_ATTEMPTS) {
|
||||
console.log(`⚠️ Max attempts reached, final size: ${finalSize} bytes (quality: ${quality})`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
size: finalSize,
|
||||
quality: quality,
|
||||
path: outputPath
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error generating thumbnail:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get image metadata
|
||||
*/
|
||||
async function getImageMetadata(imagePath) {
|
||||
try {
|
||||
const metadata = await sharp(imagePath).metadata();
|
||||
const stats = fs.statSync(imagePath);
|
||||
|
||||
return {
|
||||
width: metadata.width,
|
||||
height: metadata.height,
|
||||
format: metadata.format,
|
||||
size: stats.size,
|
||||
created_at: stats.birthtimeMs,
|
||||
modified_at: stats.mtimeMs
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error getting image metadata:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate thumbnail for an image
|
||||
* 优化:直接存储在 thumbnails/ 目录,不再使用子文件夹
|
||||
*/
|
||||
async function generateImageThumbnails(imagePath, libraryPath) {
|
||||
const flypicDir = path.join(libraryPath, '.flypic');
|
||||
const relativePath = path.relative(libraryPath, imagePath);
|
||||
const hash = crypto.createHash('md5').update(relativePath).digest('hex');
|
||||
|
||||
// 直接存储在 thumbnails 目录,不使用 200 子文件夹
|
||||
const thumbPath = path.join(flypicDir, 'thumbnails', `${hash}.webp`);
|
||||
const thumb = await generateThumbnail(imagePath, thumbPath, 200);
|
||||
|
||||
return {
|
||||
thumbnail_path: path.relative(flypicDir, thumbPath),
|
||||
thumbnail_size: thumb.size
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isImageFile,
|
||||
calculateFileHash,
|
||||
getThumbnailConfig,
|
||||
generateThumbnail,
|
||||
getImageMetadata,
|
||||
generateImageThumbnails,
|
||||
SUPPORTED_FORMATS
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
".url": {
|
||||
"flypic.Application": {
|
||||
"title": "FlyPic",
|
||||
"icon": "images/icon_{0}.png",
|
||||
"type": "url",
|
||||
"protocol": "http",
|
||||
"port": "5002"
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
LOG="${TRIM_TEMP_LOGFILE:-/tmp/flypic_install.log}"
|
||||
exec >> "$LOG" 2>&1
|
||||
set -x
|
||||
|
||||
echo "=== FlyPic 安装初始化开始 ==="
|
||||
echo "时间: $(date)"
|
||||
echo "应用名称: ${TRIM_APPNAME}"
|
||||
echo "应用版本: ${TRIM_APPVER}"
|
||||
echo "用户名: ${TRIM_USERNAME}"
|
||||
echo "用户组: ${TRIM_GROUPNAME}"
|
||||
echo "数据共享路径: ${TRIM_DATA_SHARE_PATHS}"
|
||||
echo "应用目录: ${TRIM_APPDEST}"
|
||||
echo "数据目录: ${TRIM_PKGVAR}"
|
||||
echo "临时目录: ${TRIM_PKGTMP}"
|
||||
echo "=== 安装初始化完成 ==="
|
||||
|
||||
exit 0
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
LOG_FILE="${TRIM_PKGVAR}/info.log"
|
||||
PID_FILE="${TRIM_PKGVAR}/app.pid"
|
||||
|
||||
export PATH=/var/apps/nodejs_v22/target/bin:$PATH
|
||||
|
||||
# 数据目录
|
||||
DATA_DIR="${TRIM_DATA_SHARE_PATHS%%:*}"
|
||||
# 启动命令
|
||||
CMD="DATA_DIR=${DATA_DIR} PORT=5002 node ${TRIM_APPDEST}/server/server.js"
|
||||
|
||||
log_msg() {
|
||||
local msg="$(date '+%Y-%m-%d %H:%M:%S') - $1"
|
||||
echo "$msg" | tee -a "${LOG_FILE}" >&2
|
||||
# 同时输出到系统日志(如果存在)
|
||||
if [ -n "${TRIM_TEMP_LOGFILE}" ]; then
|
||||
echo "$msg" >> "${TRIM_TEMP_LOGFILE}" 2>&1 || true
|
||||
fi
|
||||
}
|
||||
|
||||
start_process() {
|
||||
if status; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
log_msg "Starting FlyPic..."
|
||||
bash -c "${CMD}" >> ${LOG_FILE} 2>&1 &
|
||||
printf "%s" "$!" > ${PID_FILE}
|
||||
return 0
|
||||
}
|
||||
|
||||
stop_process() {
|
||||
log_msg "Stopping FlyPic..."
|
||||
|
||||
if [ -r "${PID_FILE}" ]; then
|
||||
pid=$(head -n 1 "${PID_FILE}" | tr -d '[:space:]')
|
||||
|
||||
log_msg "pid=${pid}"
|
||||
if ! check_process "${pid}"; then
|
||||
rm -f "${PID_FILE}"
|
||||
log_msg "remove pid file"
|
||||
return
|
||||
fi
|
||||
|
||||
log_msg "send TERM signal to PID:${pid}..."
|
||||
kill -TERM ${pid} >> ${LOG_FILE} 2>&1
|
||||
|
||||
local count=0
|
||||
while check_process "${pid}" && [ $count -lt 10 ]; do
|
||||
sleep 1
|
||||
count=$((count + 1))
|
||||
log_msg "waiting process terminal... (${count}s/10s)"
|
||||
done
|
||||
|
||||
if check_process "${pid}"; then
|
||||
log_msg "send KILL signal to PID:${pid}..."
|
||||
kill -KILL "${pid}"
|
||||
sleep 1
|
||||
rm -f "${PID_FILE}"
|
||||
else
|
||||
log_msg "process killed..."
|
||||
fi
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
check_process() {
|
||||
local pid=$1
|
||||
if kill -0 "${pid}" 2>/dev/null; then
|
||||
return 0
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
status() {
|
||||
if [ -f "${PID_FILE}" ]; then
|
||||
pid=$(head -n 1 "${PID_FILE}" | tr -d '[:space:]')
|
||||
if check_process "${pid}"; then
|
||||
return 0
|
||||
else
|
||||
rm -f "${PID_FILE}"
|
||||
fi
|
||||
fi
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
case $1 in
|
||||
start)
|
||||
start_process
|
||||
;;
|
||||
stop)
|
||||
stop_process
|
||||
;;
|
||||
status)
|
||||
if status; then
|
||||
exit 0
|
||||
else
|
||||
exit 3
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,2 @@
|
||||
#!/bin/bash
|
||||
exit 0
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"defaults": {
|
||||
"run-as": "package"
|
||||
},
|
||||
"username": "flypic",
|
||||
"groupname": "flypic"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"data-share": {
|
||||
"shares": [
|
||||
{
|
||||
"name": "flypic",
|
||||
"permission": {
|
||||
"rw": [
|
||||
"flypic"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
appname=flypic
|
||||
version=0.1.0
|
||||
desc=轻量、快速、稳定的图片检索浏览应用
|
||||
arch=x86_64
|
||||
display_name=FlyPic
|
||||
maintainer=ZangXincz
|
||||
distributor=ZangXincz
|
||||
desktop_uidir=ui
|
||||
desktop_applaunchname=flypic.Application
|
||||
source=thirdparty
|
||||
service_port=5002
|
||||
install_dep_apps=nodejs_v22
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FlyPic - 图片素材库管理</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "flypic-frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.6.2",
|
||||
"jszip": "^3.10.1",
|
||||
"lucide-react": "^0.300.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-photo-view": "^1.2.3",
|
||||
"react-virtualized-auto-sizer": "^1.0.20",
|
||||
"react-window": "^1.8.10",
|
||||
"socket.io-client": "^4.6.0",
|
||||
"zustand": "^4.4.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.43",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"autoprefixer": "^10.4.16",
|
||||
"postcss": "^8.4.32",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"vite": "^5.0.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { io } from 'socket.io-client';
|
||||
import useStore from './store/useStore';
|
||||
import { libraryAPI, imageAPI, scanAPI } from './services/api';
|
||||
import Sidebar from './components/Sidebar';
|
||||
import MainContent from './components/MainContent';
|
||||
import RightPanel from './components/RightPanel';
|
||||
import Header from './components/Header';
|
||||
|
||||
function App() {
|
||||
const {
|
||||
theme,
|
||||
setLibraries,
|
||||
setCurrentLibrary,
|
||||
setScanProgress,
|
||||
mobileView,
|
||||
setMobileView,
|
||||
selectedImage
|
||||
} = useStore();
|
||||
const [leftWidth, setLeftWidth] = useState(256); // 默认 256px (w-64)
|
||||
const [rightWidth, setRightWidth] = useState(320); // 默认 320px (w-80)
|
||||
const [isDraggingLeft, setIsDraggingLeft] = useState(false);
|
||||
const [isDraggingRight, setIsDraggingRight] = useState(false);
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const containerRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Apply theme
|
||||
if (theme === 'dark') {
|
||||
document.documentElement.classList.add('dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark');
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
// 检测屏幕尺寸
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
const mobile = window.innerWidth < 768; // < 768px 为移动端
|
||||
setIsMobile(mobile);
|
||||
};
|
||||
|
||||
checkMobile();
|
||||
window.addEventListener('resize', checkMobile);
|
||||
return () => window.removeEventListener('resize', checkMobile);
|
||||
}, []);
|
||||
|
||||
// 选中图片时自动切换到详情视图(移动端)
|
||||
useEffect(() => {
|
||||
if (isMobile && selectedImage) {
|
||||
setMobileView('detail');
|
||||
}
|
||||
}, [selectedImage, isMobile, setMobileView]);
|
||||
|
||||
useEffect(() => {
|
||||
// Setup Socket.IO - 开发模式连接后端端口,生产模式使用同源
|
||||
const socketUrl = import.meta.env.DEV
|
||||
? 'http://localhost:3000' // 开发模式:后端端口
|
||||
: window.location.origin; // 生产模式:同源
|
||||
|
||||
console.log('🔌 Connecting to Socket.IO:', socketUrl);
|
||||
const socket = io(socketUrl, {
|
||||
transports: ['websocket', 'polling'], // 优先使用 websocket
|
||||
reconnection: true,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionAttempts: 5
|
||||
});
|
||||
|
||||
socket.on('connect', () => {
|
||||
console.log('✅ Socket.IO connected:', socket.id);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('❌ Socket.IO disconnected');
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error) => {
|
||||
console.error('❌ Socket.IO connection error:', error);
|
||||
});
|
||||
|
||||
socket.on('scanProgress', (progress) => {
|
||||
// 只显示当前素材库的进度
|
||||
const currentLibId = useStore.getState().currentLibraryId;
|
||||
if (progress.libraryId === currentLibId) {
|
||||
setScanProgress(progress);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('scanComplete', ({ libraryId, results }) => {
|
||||
console.log('📊 Scan complete:', { libraryId, results });
|
||||
|
||||
// Only reload if this is the current library
|
||||
const currentLibId = useStore.getState().currentLibraryId;
|
||||
console.log('🔍 Current library:', currentLibId, 'Scan library:', libraryId, 'Match:', libraryId === currentLibId);
|
||||
|
||||
if (libraryId === currentLibId) {
|
||||
console.log('🔄 Reloading folders and images...');
|
||||
|
||||
// 获取当前的筛选条件
|
||||
const state = useStore.getState();
|
||||
const params = {
|
||||
keywords: state.searchKeywords,
|
||||
...state.filters
|
||||
};
|
||||
|
||||
// 只有选中了文件夹才添加 folder 参数
|
||||
if (state.selectedFolder) {
|
||||
params.folder = state.selectedFolder;
|
||||
}
|
||||
|
||||
// 并行加载文件夹和图片
|
||||
Promise.all([
|
||||
imageAPI.getFolders(libraryId),
|
||||
// 如果没有选中文件夹且没有搜索条件,不加载图片(保持在 Dashboard)
|
||||
(state.selectedFolder || state.searchKeywords || state.filters.formats.length > 0)
|
||||
? imageAPI.search(libraryId, params)
|
||||
: Promise.resolve({ data: { images: [] } }),
|
||||
// 扫描完成后总是重新获取总数
|
||||
imageAPI.getCount(libraryId)
|
||||
]).then(([foldersRes, imagesRes, countRes]) => {
|
||||
useStore.getState().setFolders(foldersRes.data.folders);
|
||||
useStore.getState().setImages(imagesRes.data.images);
|
||||
// 更新图片总数
|
||||
useStore.getState().setTotalImageCount(countRes.data.count);
|
||||
|
||||
console.log(`✅ Data reloaded, total: ${countRes.data.count}`);
|
||||
}).catch(err => {
|
||||
console.error('❌ Error reloading data:', err);
|
||||
}).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);
|
||||
});
|
||||
|
||||
socket.on('scanPaused', ({ libraryId, results }) => {
|
||||
console.log('⏸️ Scan paused:', { libraryId, results });
|
||||
// 保持进度显示,但标记为可以继续
|
||||
});
|
||||
|
||||
// Socket 监听已就绪后,再加载库并可能触发同步
|
||||
loadLibraries();
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadLibraries = async () => {
|
||||
try {
|
||||
const response = await libraryAPI.getAll();
|
||||
const { libraries, currentLibraryId: libId, theme: configTheme, preferences } = response.data;
|
||||
|
||||
// 立即更新基础状态
|
||||
setLibraries(libraries);
|
||||
setCurrentLibrary(libId);
|
||||
|
||||
// 加载主题和偏好设置
|
||||
if (configTheme) {
|
||||
useStore.getState().setTheme(configTheme);
|
||||
}
|
||||
if (preferences) {
|
||||
const { thumbnailHeight, leftPanelWidth, rightPanelWidth } = preferences;
|
||||
if (thumbnailHeight) useStore.getState().setThumbnailHeight(thumbnailHeight);
|
||||
if (leftPanelWidth) setLeftWidth(leftPanelWidth);
|
||||
if (rightPanelWidth) setRightWidth(rightPanelWidth);
|
||||
}
|
||||
|
||||
if (libId) {
|
||||
// 并行加载图片和文件夹(加快初始加载速度)
|
||||
// 优化:启动时不加载全部图片,只加载文件夹
|
||||
const [foldersRes] = await Promise.all([
|
||||
imageAPI.getFolders(libId)
|
||||
]);
|
||||
|
||||
useStore.getState().setFolders(foldersRes.data.folders);
|
||||
|
||||
// 获取总数
|
||||
try {
|
||||
const countRes = await imageAPI.getCount(libId);
|
||||
useStore.getState().setTotalImageCount(countRes.data.count);
|
||||
} catch (e) {
|
||||
console.error('Failed to get image count:', e);
|
||||
}
|
||||
|
||||
console.log('📂 数据加载完成,文件监控器将自动检测变化');
|
||||
|
||||
// 后台检查扫描状态(不阻塞主流程)
|
||||
scanAPI.getStatus(libId).then(scanStatus => {
|
||||
const { status, progress, pendingCount } = scanStatus.data;
|
||||
if (status === 'scanning' || status === 'paused') {
|
||||
console.log(`🔄 恢复扫描状态: ${status}, 进度: ${progress?.percent || 0}%`);
|
||||
setScanProgress({
|
||||
...progress,
|
||||
canStop: true,
|
||||
isPaused: status === 'paused',
|
||||
pendingCount: pendingCount
|
||||
});
|
||||
}
|
||||
}).catch(() => { }); // 忽略状态检查错误
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading libraries:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const loadImages = async (libraryId) => {
|
||||
try {
|
||||
const params = {};
|
||||
|
||||
// Get current selected folder
|
||||
const selectedFolder = useStore.getState().selectedFolder;
|
||||
if (selectedFolder) {
|
||||
params.folder = selectedFolder;
|
||||
}
|
||||
|
||||
const response = await imageAPI.search(libraryId, params);
|
||||
useStore.getState().setImages(response.data.images);
|
||||
} catch (error) {
|
||||
console.error('Error loading images:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const loadFolders = async (libraryId) => {
|
||||
try {
|
||||
const response = await imageAPI.getFolders(libraryId);
|
||||
useStore.getState().setFolders(response.data.folders);
|
||||
} catch (error) {
|
||||
console.error('Error loading folders:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 保存面板宽度
|
||||
const savePanelWidths = async (left, right) => {
|
||||
try {
|
||||
await libraryAPI.updatePreferences({
|
||||
leftPanelWidth: left,
|
||||
rightPanelWidth: right
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error saving panel widths:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理鼠标拖动(极致性能优化 + RAF 批处理)
|
||||
useEffect(() => {
|
||||
if (!isDraggingLeft && !isDraggingRight) return;
|
||||
|
||||
const leftPanel = document.getElementById('left-panel');
|
||||
const rightPanel = document.getElementById('right-panel');
|
||||
let currentLeftWidth = leftWidth;
|
||||
let currentRightWidth = rightWidth;
|
||||
|
||||
// 缓存容器位置,避免重复计算
|
||||
const containerRect = containerRef.current.getBoundingClientRect();
|
||||
const containerLeft = containerRect.left;
|
||||
const containerRight = containerRect.right;
|
||||
|
||||
// RAF 批处理,避免一帧多次样式写入
|
||||
let rafId = null;
|
||||
let pendingLeft = null;
|
||||
let pendingRight = null;
|
||||
|
||||
const flushStyle = () => {
|
||||
if (leftPanel && pendingLeft != null) {
|
||||
leftPanel.style.width = `${pendingLeft}px`;
|
||||
currentLeftWidth = pendingLeft;
|
||||
}
|
||||
if (rightPanel && pendingRight != null) {
|
||||
rightPanel.style.width = `${pendingRight}px`;
|
||||
currentRightWidth = pendingRight;
|
||||
}
|
||||
rafId = null;
|
||||
pendingLeft = null;
|
||||
pendingRight = null;
|
||||
};
|
||||
|
||||
const handleMouseMove = (e) => {
|
||||
let needSchedule = false;
|
||||
|
||||
if (isDraggingLeft && leftPanel) {
|
||||
const newWidth = e.clientX - containerLeft;
|
||||
if (newWidth >= 200 && newWidth <= 400) {
|
||||
pendingLeft = newWidth;
|
||||
needSchedule = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (isDraggingRight && rightPanel) {
|
||||
const newWidth = containerRight - e.clientX;
|
||||
if (newWidth >= 280 && newWidth <= 500) {
|
||||
pendingRight = newWidth;
|
||||
needSchedule = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (needSchedule && rafId == null) {
|
||||
rafId = requestAnimationFrame(flushStyle);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId);
|
||||
flushStyle();
|
||||
}
|
||||
// 更新 state 并保存
|
||||
setLeftWidth(currentLeftWidth);
|
||||
setRightWidth(currentRightWidth);
|
||||
savePanelWidths(currentLeftWidth, currentRightWidth);
|
||||
|
||||
setIsDraggingLeft(false);
|
||||
setIsDraggingRight(false);
|
||||
// 拖动结束,恢复
|
||||
useStore.getState().setIsResizingPanels(false);
|
||||
useStore.getState().setResizingSide(null);
|
||||
};
|
||||
|
||||
// 使用 passive: false 确保可以阻止默认行为
|
||||
document.addEventListener('mousemove', handleMouseMove, { passive: true });
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.userSelect = 'none';
|
||||
document.body.style.cursor = 'col-resize';
|
||||
// 禁用过渡动画
|
||||
if (leftPanel) leftPanel.style.transition = 'none';
|
||||
if (rightPanel) rightPanel.style.transition = 'none';
|
||||
|
||||
return () => {
|
||||
if (rafId) {
|
||||
cancelAnimationFrame(rafId);
|
||||
rafId = null;
|
||||
}
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
document.body.style.userSelect = '';
|
||||
document.body.style.cursor = '';
|
||||
// 恢复过渡动画
|
||||
if (leftPanel) leftPanel.style.transition = '';
|
||||
if (rightPanel) rightPanel.style.transition = '';
|
||||
};
|
||||
}, [isDraggingLeft, isDraggingRight]);
|
||||
|
||||
// 移动端布局
|
||||
if (isMobile) {
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
|
||||
<Header />
|
||||
<div className="flex-1 overflow-hidden relative">
|
||||
{/* 侧边栏视图 */}
|
||||
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
|
||||
}`}>
|
||||
<Sidebar />
|
||||
</div>
|
||||
|
||||
{/* 主内容视图 */}
|
||||
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'main' ? 'translate-x-0' :
|
||||
mobileView === 'sidebar' ? 'translate-x-full' : '-translate-x-full'
|
||||
}`}>
|
||||
<MainContent />
|
||||
</div>
|
||||
|
||||
{/* 详情视图 */}
|
||||
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'detail' ? 'translate-x-0' : 'translate-x-full'
|
||||
}`}>
|
||||
<RightPanel />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部导航 */}
|
||||
<div className="flex border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
|
||||
<button
|
||||
onClick={() => setMobileView('sidebar')}
|
||||
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'sidebar' ? 'text-blue-500' : 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="text-xs mt-1">文件夹</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMobileView('main')}
|
||||
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'main' ? 'text-blue-500' : 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className="text-xs mt-1">图片</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMobileView('detail')}
|
||||
disabled={!selectedImage}
|
||||
className={`flex-1 flex flex-col items-center py-2 ${mobileView === 'detail' ? 'text-blue-500' : 'text-gray-500'
|
||||
} disabled:opacity-30`}
|
||||
>
|
||||
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<span className="text-xs mt-1">详情</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 桌面端布局
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
|
||||
<Header />
|
||||
<div ref={containerRef} className="flex flex-1 overflow-hidden">
|
||||
{/* 左侧边栏 */}
|
||||
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full">
|
||||
<Sidebar />
|
||||
</div>
|
||||
|
||||
{/* 左侧拖动条 */}
|
||||
<div
|
||||
className={`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${isDraggingLeft ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700 hover:bg-blue-400'
|
||||
}`}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
// 标记正在拖动,供其他组件抑制重算
|
||||
useStore.getState().setIsResizingPanels(true);
|
||||
useStore.getState().setResizingSide('left');
|
||||
setIsDraggingLeft(true);
|
||||
}}
|
||||
>
|
||||
{/* 扩大点击区域 */}
|
||||
<div className="absolute inset-y-0 -left-2 -right-2 w-5" />
|
||||
</div>
|
||||
|
||||
{/* 中间主内容区 */}
|
||||
<div className="flex-1 min-w-0 h-full">
|
||||
<MainContent />
|
||||
</div>
|
||||
|
||||
{/* 右侧拖动条 */}
|
||||
<div
|
||||
className={`group relative w-1 h-full cursor-col-resize flex-shrink-0 transition-colors ${isDraggingRight ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700 hover:bg-blue-400'
|
||||
}`}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
// 标记正在拖动,供其他组件抑制重算
|
||||
useStore.getState().setIsResizingPanels(true);
|
||||
useStore.getState().setResizingSide('right');
|
||||
setIsDraggingRight(true);
|
||||
}}
|
||||
>
|
||||
{/* 扩大点击区域 */}
|
||||
<div className="absolute inset-y-0 -left-2 -right-2 w-5" />
|
||||
</div>
|
||||
|
||||
{/* 右侧边栏 */}
|
||||
<div id="right-panel" style={{ width: `${rightWidth}px` }} className="flex-shrink-0 h-full">
|
||||
<RightPanel />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,127 @@
|
||||
import React from 'react';
|
||||
import useStore from '../store/useStore';
|
||||
import { Folder, Image as ImageIcon, Search } from 'lucide-react';
|
||||
|
||||
function Dashboard() {
|
||||
const {
|
||||
totalImageCount,
|
||||
folders,
|
||||
currentLibraryId,
|
||||
getCurrentLibrary
|
||||
} = useStore();
|
||||
|
||||
const currentLibrary = getCurrentLibrary();
|
||||
|
||||
// Calculate stats
|
||||
const folderCount = folders.length;
|
||||
|
||||
// Group folders by parent to find top-level folders
|
||||
const topLevelFolders = folders.filter(f => !f.parent_path || f.parent_path === '.' || f.parent_path === '');
|
||||
|
||||
return (
|
||||
<div className="flex-1 h-full overflow-y-auto bg-gray-50 dark:bg-gray-900 p-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
||||
{currentLibrary?.name || '素材库'}
|
||||
</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">
|
||||
{currentLibrary?.path}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-12">
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg text-blue-600 dark:text-blue-400">
|
||||
<ImageIcon className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{totalImageCount.toLocaleString()}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">总图片数</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg text-indigo-600 dark:text-indigo-400">
|
||||
<Folder className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{folderCount.toLocaleString()}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">文件夹</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg text-purple-600 dark:text-purple-400">
|
||||
<Search className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white mb-1">
|
||||
快速开始
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
使用左侧目录树浏览或顶部搜索栏查找图片
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top Level Folders Preview */}
|
||||
{topLevelFolders.length > 0 && (
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
|
||||
根目录文件夹
|
||||
</h2>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{topLevelFolders.map(folder => (
|
||||
<div
|
||||
key={folder.path}
|
||||
className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer group"
|
||||
onClick={() => useStore.getState().setSelectedFolder(folder.path)}
|
||||
>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<Folder className="w-8 h-8 text-yellow-500 group-hover:text-yellow-400 transition-colors" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-gray-900 dark:text-white truncate" title={folder.name}>
|
||||
{folder.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{folder.image_count || 0} 张图片
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{topLevelFolders.length === 0 && (
|
||||
<div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-dashed border-gray-300 dark:border-gray-700">
|
||||
<Folder className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
|
||||
暂无文件夹
|
||||
</h3>
|
||||
<p className="text-gray-500 dark:text-gray-400 max-w-sm mx-auto">
|
||||
您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Dashboard;
|
||||
@@ -0,0 +1,124 @@
|
||||
import { X, ExternalLink } from 'lucide-react';
|
||||
import { imageAPI } from '../services/api';
|
||||
|
||||
/**
|
||||
* 文件查看器 - 支持视频播放和文档查看
|
||||
* 不依赖额外库,使用浏览器原生能力
|
||||
*/
|
||||
function FileViewer({ file, libraryId, onClose }) {
|
||||
if (!file) return null;
|
||||
|
||||
const fileType = file.file_type || 'image';
|
||||
const originalUrl = imageAPI.getOriginalUrl(libraryId, file.path);
|
||||
|
||||
// 在系统默认应用中打开
|
||||
const openInSystem = async () => {
|
||||
try {
|
||||
await imageAPI.openInExplorer(libraryId, file.path);
|
||||
} catch (error) {
|
||||
console.error('Failed to open file:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 bg-black bg-opacity-90 flex items-center justify-center">
|
||||
{/* 顶部工具栏 */}
|
||||
<div className="absolute top-0 left-0 right-0 h-16 bg-black bg-opacity-50 flex items-center justify-between px-4 z-10">
|
||||
<div className="text-white text-sm truncate max-w-md">
|
||||
{file.filename}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={openInSystem}
|
||||
className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
|
||||
title="在系统默认应用中打开"
|
||||
>
|
||||
<ExternalLink className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 text-white hover:bg-white hover:bg-opacity-20 rounded transition-colors"
|
||||
>
|
||||
<X className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 内容区域 */}
|
||||
<div className="w-full h-full flex items-center justify-center p-20">
|
||||
{fileType === 'video' && (
|
||||
<video
|
||||
src={originalUrl}
|
||||
controls
|
||||
autoPlay
|
||||
className="max-w-full max-h-full rounded shadow-2xl"
|
||||
onError={(e) => {
|
||||
console.error('Video load error:', e);
|
||||
alert('视频加载失败,请尝试在系统默认应用中打开');
|
||||
}}
|
||||
>
|
||||
您的浏览器不支持视频播放
|
||||
</video>
|
||||
)}
|
||||
|
||||
{fileType === 'audio' && (
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<div className="text-white text-6xl mb-8">🎵</div>
|
||||
<audio
|
||||
src={originalUrl}
|
||||
controls
|
||||
autoPlay
|
||||
className="w-96 rounded shadow-2xl"
|
||||
onError={(e) => {
|
||||
console.error('Audio load error:', e);
|
||||
alert('音频加载失败,请尝试在系统默认应用中打开');
|
||||
}}
|
||||
>
|
||||
您的浏览器不支持音频播放
|
||||
</audio>
|
||||
<p className="text-white mt-4 text-sm opacity-70">{file.filename}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fileType === 'document' && (
|
||||
<div className="w-full h-full bg-white rounded shadow-2xl overflow-hidden">
|
||||
{file.format === 'pdf' ? (
|
||||
<iframe
|
||||
src={originalUrl}
|
||||
className="w-full h-full"
|
||||
title={file.filename}
|
||||
/>
|
||||
) : (
|
||||
<iframe
|
||||
src={originalUrl}
|
||||
className="w-full h-full"
|
||||
title={file.filename}
|
||||
sandbox="allow-same-origin"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(fileType === 'design' || fileType === 'other' || !fileType) && (
|
||||
<div className="text-center text-white">
|
||||
<p className="mb-4">此文件类型需要在专业软件中打开</p>
|
||||
<button
|
||||
onClick={openInSystem}
|
||||
className="px-6 py-3 bg-blue-500 hover:bg-blue-600 rounded-lg transition-colors"
|
||||
>
|
||||
在系统默认应用中打开
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 点击背景关闭 */}
|
||||
<div
|
||||
className="absolute inset-0 -z-10"
|
||||
onClick={onClose}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FileViewer;
|
||||
@@ -0,0 +1,694 @@
|
||||
import { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import { Sun, Moon, Search, Filter, Sliders, RefreshCw } from 'lucide-react';
|
||||
import useStore from '../store/useStore';
|
||||
import { libraryAPI, scanAPI, watchAPI } from '../services/api';
|
||||
|
||||
function Header() {
|
||||
const {
|
||||
theme,
|
||||
toggleTheme,
|
||||
searchKeywords,
|
||||
thumbnailHeight,
|
||||
images,
|
||||
filteredImages,
|
||||
selectedFolder,
|
||||
currentLibraryId,
|
||||
setSearchKeywords,
|
||||
setThumbnailHeight,
|
||||
setFilteredImages,
|
||||
mobileView
|
||||
} = useStore();
|
||||
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
const [selectedFormats, setSelectedFormats] = useState([]);
|
||||
const [selectedSizes, setSelectedSizes] = useState([]);
|
||||
const [selectedOrientation, setSelectedOrientation] = useState('');
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [showMobileSettings, setShowMobileSettings] = useState(false);
|
||||
const [localSearchValue, setLocalSearchValue] = useState(searchKeywords);
|
||||
const searchDebounceRef = useRef(null);
|
||||
|
||||
// 检测移动端
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
setIsMobile(window.innerWidth < 768);
|
||||
};
|
||||
checkMobile();
|
||||
window.addEventListener('resize', checkMobile);
|
||||
return () => window.removeEventListener('resize', checkMobile);
|
||||
}, []);
|
||||
|
||||
// 监听文件夹变化,自动清空筛选
|
||||
useEffect(() => {
|
||||
setSelectedFormats([]);
|
||||
setSelectedSizes([]);
|
||||
setSelectedOrientation('');
|
||||
}, [selectedFolder]);
|
||||
|
||||
// 文件监控(默认启用,实时检测文件变化)
|
||||
useEffect(() => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
// 启动文件监控
|
||||
watchAPI.start(currentLibraryId)
|
||||
.then(() => {
|
||||
console.log('✅ 文件监控已启动(实时检测文件变化)');
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('启动文件监控失败:', error);
|
||||
console.error('提示:在飞牛 fnOS 上,请确保在应用设置中授予了文件夹访问权限');
|
||||
});
|
||||
|
||||
// 清理:关闭监控
|
||||
return () => {
|
||||
watchAPI.stop(currentLibraryId).catch(err => console.error('Stop watch error:', err));
|
||||
};
|
||||
}, [currentLibraryId]);
|
||||
|
||||
// 防抖搜索(300ms 延迟,减少请求频率)
|
||||
const handleSearchChange = (value) => {
|
||||
setLocalSearchValue(value);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (searchDebounceRef.current) {
|
||||
clearTimeout(searchDebounceRef.current);
|
||||
}
|
||||
|
||||
// 300ms 后触发实际搜索
|
||||
searchDebounceRef.current = setTimeout(() => {
|
||||
setSearchKeywords(value);
|
||||
}, 300);
|
||||
};
|
||||
|
||||
// 同步外部 searchKeywords 变化
|
||||
useEffect(() => {
|
||||
setLocalSearchValue(searchKeywords);
|
||||
}, [searchKeywords]);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchDebounceRef.current) {
|
||||
clearTimeout(searchDebounceRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 智能计算文件大小范围
|
||||
const calculateSizeRanges = (sizes) => {
|
||||
if (sizes.length === 0) return [];
|
||||
|
||||
const sorted = [...sizes].sort((a, b) => a - b);
|
||||
const min = sorted[0];
|
||||
const max = sorted[sorted.length - 1];
|
||||
|
||||
if (max - min < 10) {
|
||||
return [formatSizeRange(min, max)];
|
||||
}
|
||||
|
||||
const rangeCount = 5;
|
||||
const ranges = [];
|
||||
const logMin = Math.log10(min || 1);
|
||||
const logMax = Math.log10(max);
|
||||
const logStep = (logMax - logMin) / rangeCount;
|
||||
|
||||
for (let i = 0; i < rangeCount; i++) {
|
||||
const rangeStart = Math.pow(10, logMin + i * logStep);
|
||||
const rangeEnd = Math.pow(10, logMin + (i + 1) * logStep);
|
||||
const hasImages = sorted.some(size => size >= rangeStart && size < rangeEnd);
|
||||
|
||||
if (hasImages || i === rangeCount - 1) {
|
||||
ranges.push(formatSizeRange(rangeStart, rangeEnd, i === rangeCount - 1));
|
||||
}
|
||||
}
|
||||
|
||||
return ranges.filter(r => r);
|
||||
};
|
||||
|
||||
// 格式化大小范围
|
||||
const formatSizeRange = (start, end, isLast = false) => {
|
||||
const formatSize = (kb) => {
|
||||
const roundToFriendly = (num) => {
|
||||
if (num < 10) return Math.round(num);
|
||||
if (num < 100) return Math.round(num / 5) * 5;
|
||||
if (num < 1000) return Math.round(num / 10) * 10;
|
||||
return Math.round(num / 50) * 50;
|
||||
};
|
||||
|
||||
if (kb < 1) return `${roundToFriendly(kb * 1024)}B`;
|
||||
if (kb < 1024) return `${roundToFriendly(kb)}KB`;
|
||||
if (kb < 1024 * 1024) return `${roundToFriendly(kb / 1024)}MB`;
|
||||
return `${roundToFriendly(kb / (1024 * 1024))}GB`;
|
||||
};
|
||||
|
||||
return isLast ? `> ${formatSize(start)}` : `${formatSize(start)} - ${formatSize(end)}`;
|
||||
};
|
||||
|
||||
// 解析大小字符串
|
||||
const parseSizeToKB = (sizeStr) => {
|
||||
const match = sizeStr.match(/^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/);
|
||||
if (!match) return 0;
|
||||
const value = parseFloat(match[1]);
|
||||
const unit = match[2];
|
||||
switch (unit) {
|
||||
case 'B': return value / 1024;
|
||||
case 'KB': return value;
|
||||
case 'MB': return value * 1024;
|
||||
case 'GB': return value * 1024 * 1024;
|
||||
default: return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// 匹配大小范围
|
||||
const matchSizeRange = (sizeKB, range) => {
|
||||
if (range.startsWith('>')) {
|
||||
const minStr = range.substring(1).trim();
|
||||
const minKB = parseSizeToKB(minStr);
|
||||
return sizeKB >= minKB;
|
||||
} else if (range.includes(' - ')) {
|
||||
const [minStr, maxStr] = range.split(' - ').map(s => s.trim());
|
||||
const minKB = parseSizeToKB(minStr);
|
||||
const maxKB = parseSizeToKB(maxStr);
|
||||
return sizeKB >= minKB && sizeKB < maxKB;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// 分析当前文件夹的所有图片,生成可选项(只在images变化时计算一次)
|
||||
const filterOptions = useMemo(() => {
|
||||
if (images.length === 0) {
|
||||
return { formats: [], sizes: [], hasHorizontal: false, hasVertical: false };
|
||||
}
|
||||
|
||||
const formats = new Set();
|
||||
const sizes = [];
|
||||
let hasHorizontal = false;
|
||||
let hasVertical = false;
|
||||
|
||||
images.forEach(img => {
|
||||
// 格式
|
||||
if (img.format) {
|
||||
formats.add(img.format.toLowerCase());
|
||||
}
|
||||
// 文件大小
|
||||
sizes.push(img.size / 1024);
|
||||
// 横竖图
|
||||
if (img.width > img.height) hasHorizontal = true;
|
||||
if (img.height > img.width) hasVertical = true;
|
||||
});
|
||||
|
||||
// 计算文件大小范围
|
||||
const sizeRanges = calculateSizeRanges(sizes);
|
||||
|
||||
return {
|
||||
formats: Array.from(formats).sort(),
|
||||
sizes: sizeRanges,
|
||||
hasHorizontal,
|
||||
hasVertical
|
||||
};
|
||||
}, [images]);
|
||||
|
||||
// 使用 useMemo 缓存筛选结果,避免重复计算
|
||||
const filteredResult = useMemo(() => {
|
||||
// 如果没有任何筛选条件,直接返回原始图片
|
||||
if (selectedFormats.length === 0 &&
|
||||
selectedSizes.length === 0 &&
|
||||
!selectedOrientation) {
|
||||
return images;
|
||||
}
|
||||
|
||||
// 预先转换为 Set 以提高查找性能
|
||||
const formatSet = new Set(selectedFormats);
|
||||
const sizeSet = new Set(selectedSizes);
|
||||
|
||||
return images.filter(img => {
|
||||
// 格式筛选
|
||||
if (formatSet.size > 0) {
|
||||
if (!formatSet.has(img.format?.toLowerCase())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 文件大小筛选
|
||||
if (sizeSet.size > 0) {
|
||||
const sizeKB = img.size / 1024;
|
||||
let matchesSize = false;
|
||||
|
||||
for (const range of sizeSet) {
|
||||
if (matchSizeRange(sizeKB, range)) {
|
||||
matchesSize = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchesSize) return false;
|
||||
}
|
||||
|
||||
// 横竖图筛选
|
||||
if (selectedOrientation === 'horizontal') {
|
||||
if (img.width <= img.height) return false;
|
||||
} else if (selectedOrientation === 'vertical') {
|
||||
if (img.height <= img.width) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}, [images, selectedFormats, selectedSizes, selectedOrientation]);
|
||||
|
||||
// 更新 filteredImages
|
||||
useEffect(() => {
|
||||
setFilteredImages(filteredResult);
|
||||
}, [filteredResult, setFilteredImages]);
|
||||
|
||||
// 切换选项
|
||||
const toggleFormat = (format) => {
|
||||
setSelectedFormats(prev =>
|
||||
prev.includes(format) ? prev.filter(f => f !== format) : [...prev, format]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleSize = (size) => {
|
||||
setSelectedSizes(prev =>
|
||||
prev.includes(size) ? prev.filter(s => s !== size) : [...prev, size]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleOrientation = (orientation) => {
|
||||
setSelectedOrientation(prev => prev === orientation ? '' : orientation);
|
||||
};
|
||||
|
||||
// 清除筛选
|
||||
const clearFilters = () => {
|
||||
setSelectedFormats([]);
|
||||
setSelectedSizes([]);
|
||||
setSelectedOrientation('');
|
||||
};
|
||||
|
||||
const handleThemeToggle = async () => {
|
||||
toggleTheme();
|
||||
try {
|
||||
await libraryAPI.updateTheme(theme === 'light' ? 'dark' : 'light');
|
||||
} catch (error) {
|
||||
console.error('Error saving theme:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleThumbnailHeightChange = async (height) => {
|
||||
setThumbnailHeight(height);
|
||||
try {
|
||||
await libraryAPI.updatePreferences({ thumbnailHeight: height });
|
||||
} catch (error) {
|
||||
console.error('Error saving preferences:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefresh = async () => {
|
||||
if (!currentLibraryId || isRefreshing) return;
|
||||
|
||||
setIsRefreshing(true);
|
||||
try {
|
||||
await scanAPI.sync(currentLibraryId);
|
||||
// Socket.IO 会触发更新
|
||||
} catch (error) {
|
||||
console.error('Error refreshing:', error);
|
||||
alert('刷新失败: ' + error.message);
|
||||
} finally {
|
||||
setIsRefreshing(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 从 filterOptions 中提取可用选项
|
||||
const availableFormats = filterOptions.formats;
|
||||
const availableSizes = filterOptions.sizes.map(size => ({ label: size }));
|
||||
const availableOrientations = [
|
||||
{ value: 'horizontal', label: '横图' },
|
||||
{ value: 'vertical', label: '竖图' }
|
||||
].filter(o =>
|
||||
(o.value === 'horizontal' && filterOptions.hasHorizontal) ||
|
||||
(o.value === 'vertical' && filterOptions.hasVertical)
|
||||
);
|
||||
|
||||
// 移动端布局
|
||||
if (isMobile) {
|
||||
// 文件夹视图不显示搜索和筛选
|
||||
const showSearch = mobileView !== 'sidebar';
|
||||
|
||||
return (
|
||||
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
|
||||
{/* 顶部栏 */}
|
||||
<div className="h-14 flex items-center justify-between px-4">
|
||||
<h1 className="text-lg font-bold text-gray-900 dark:text-white">FlyPic</h1>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={!currentLibraryId || isRefreshing}
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowMobileSettings(!showMobileSettings)}
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
<Sliders className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleThemeToggle}
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
>
|
||||
{theme === 'light' ? (
|
||||
<Moon className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
) : (
|
||||
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 搜索栏(仅在图片和详情视图显示) */}
|
||||
{showSearch && (
|
||||
<div className="px-4 pb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索图片..."
|
||||
value={searchKeywords}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowFilters(!showFilters)}
|
||||
className={`p-2 border rounded-lg ${
|
||||
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-500/20'
|
||||
: 'border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
<Filter className={`w-5 h-5 ${
|
||||
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
|
||||
? 'text-blue-600 dark:text-blue-300'
|
||||
: 'text-gray-600 dark:text-gray-400'
|
||||
}`} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 移动端设置面板 */}
|
||||
{showMobileSettings && (
|
||||
<div className="px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">缩略图大小</span>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">{thumbnailHeight}px</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min="150"
|
||||
max="300"
|
||||
value={thumbnailHeight}
|
||||
onChange={(e) => handleThumbnailHeightChange(parseInt(e.target.value))}
|
||||
className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer"
|
||||
style={{
|
||||
background: `linear-gradient(to right, #3b82f6 0%, #3b82f6 ${((thumbnailHeight - 150) / 150) * 100}%, #e5e7eb ${((thumbnailHeight - 150) / 150) * 100}%, #e5e7eb 100%)`
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 筛选面板(仅在图片和详情视图显示) */}
|
||||
{showSearch && showFilters && (
|
||||
<div className="px-4 pb-3 border-t border-gray-200 dark:border-gray-700 pt-3">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">筛选条件</span>
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="text-xs text-blue-500"
|
||||
>
|
||||
清除全部
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 格式筛选 */}
|
||||
<div className="mb-3">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">格式</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{availableFormats.map(format => (
|
||||
<button
|
||||
key={format}
|
||||
onClick={() => toggleFormat(format)}
|
||||
className={`px-3 py-1 text-xs rounded-full ${
|
||||
selectedFormats.includes(format)
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
{format.toUpperCase()}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 尺寸筛选 */}
|
||||
<div className="mb-3">
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">尺寸</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{availableSizes.map(size => (
|
||||
<button
|
||||
key={size.label}
|
||||
onClick={() => toggleSize(size.label)}
|
||||
className={`px-3 py-1 text-xs rounded-full ${
|
||||
selectedSizes.includes(size.label)
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
{size.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 方向筛选 */}
|
||||
<div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mb-2">方向</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{availableOrientations.map(orientation => (
|
||||
<button
|
||||
key={orientation.value}
|
||||
onClick={() => toggleOrientation(orientation.value)}
|
||||
className={`px-3 py-1 text-xs rounded-full ${
|
||||
selectedOrientation === orientation.value
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
{orientation.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
// 桌面端布局
|
||||
return (
|
||||
<header className="border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
|
||||
<div className="h-14 flex items-center justify-between px-6">
|
||||
<div className="flex-shrink-0">
|
||||
<h1 className="text-xl font-bold text-gray-900 dark:text-white">FlyPic</h1>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的图片素材库管理</p>
|
||||
</div>
|
||||
|
||||
{/* 搜索栏 */}
|
||||
<div className="flex-1 max-w-2xl mx-6 flex items-center gap-3">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索图片... (多个关键词用空格分隔,即时搜索)"
|
||||
value={localSearchValue}
|
||||
onChange={(e) => handleSearchChange(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setShowFilters(!showFilters)}
|
||||
className={`relative p-2 border rounded-lg transition-colors ${
|
||||
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
|
||||
? 'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-500/20 hover:bg-blue-100 dark:hover:bg-blue-500/30'
|
||||
: 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
title={
|
||||
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
|
||||
? '筛选(已启用)'
|
||||
: '筛选'
|
||||
}
|
||||
>
|
||||
<Filter className={`w-5 h-5 ${
|
||||
selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation
|
||||
? 'text-blue-600 dark:text-blue-300'
|
||||
: 'text-gray-600 dark:text-gray-400'
|
||||
}`} />
|
||||
{(selectedFormats.length > 0 || selectedSizes.length > 0 || selectedOrientation) && (
|
||||
<span
|
||||
className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: '#3b82f6' }}
|
||||
></span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 缩略图大小滑块 */}
|
||||
<div className="flex items-center gap-3 flex-shrink-0">
|
||||
<Sliders className="w-4 h-4 text-gray-500" />
|
||||
<input
|
||||
type="range"
|
||||
min="150"
|
||||
max="300"
|
||||
value={thumbnailHeight}
|
||||
onChange={(e) => handleThumbnailHeightChange(parseInt(e.target.value))}
|
||||
className="w-32"
|
||||
/>
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400 w-12">{thumbnailHeight}px</span>
|
||||
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={!currentLibraryId || isRefreshing}
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ml-2"
|
||||
title="手动刷新素材库(文件监控已自动启用)"
|
||||
>
|
||||
<RefreshCw className={`w-5 h-5 text-gray-700 dark:text-gray-300 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleThemeToggle}
|
||||
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||
title={theme === 'light' ? '切换到暗色模式' : '切换到亮色模式'}
|
||||
>
|
||||
{theme === 'light' ? (
|
||||
<Moon className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
) : (
|
||||
<Sun className="w-5 h-5 text-gray-700 dark:text-gray-300" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 筛选面板 */}
|
||||
{showFilters && (
|
||||
<div className="px-6 pb-3">
|
||||
<div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-300">筛选条件(实时生效)</div>
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="text-xs text-blue-500 hover:text-blue-600 dark:hover:text-blue-400"
|
||||
>
|
||||
清除全部
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 三列布局 */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{/* 格式筛选 */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">格式</label>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{filterOptions.formats.length > 0 ? (
|
||||
filterOptions.formats.map(format => (
|
||||
<button
|
||||
key={format}
|
||||
onClick={() => toggleFormat(format)}
|
||||
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
|
||||
selectedFormats.includes(format)
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
|
||||
}`}
|
||||
>
|
||||
{format.toUpperCase()}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<span className="text-xs text-gray-400 py-2">暂无格式数据</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 文件大小筛选 */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">文件大小</label>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{filterOptions.sizes.length > 0 ? (
|
||||
filterOptions.sizes.map(size => (
|
||||
<button
|
||||
key={size}
|
||||
onClick={() => toggleSize(size)}
|
||||
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
|
||||
selectedSizes.includes(size)
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
|
||||
}`}
|
||||
>
|
||||
{size}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<span className="text-xs text-gray-400 py-2">暂无大小数据</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 横竖图筛选 */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">图片方向</label>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{filterOptions.hasHorizontal && (
|
||||
<button
|
||||
onClick={() => toggleOrientation('horizontal')}
|
||||
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
|
||||
selectedOrientation === 'horizontal'
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
|
||||
}`}
|
||||
>
|
||||
横图
|
||||
</button>
|
||||
)}
|
||||
{filterOptions.hasVertical && (
|
||||
<button
|
||||
onClick={() => toggleOrientation('vertical')}
|
||||
className={`px-3 py-1.5 text-xs rounded transition-colors text-left ${
|
||||
selectedOrientation === 'vertical'
|
||||
? 'bg-blue-500 text-white'
|
||||
: 'bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-500'
|
||||
}`}
|
||||
>
|
||||
竖图
|
||||
</button>
|
||||
)}
|
||||
{!filterOptions.hasHorizontal && !filterOptions.hasVertical && (
|
||||
<span className="text-xs text-gray-400 py-2">暂无方向数据</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
export default Header;
|
||||
@@ -0,0 +1,516 @@
|
||||
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
|
||||
import { PhotoProvider, PhotoView } from 'react-photo-view';
|
||||
import 'react-photo-view/dist/react-photo-view.css';
|
||||
import { VariableSizeList as List } from 'react-window';
|
||||
import { Play, FileText, Palette, Music, File } from 'lucide-react';
|
||||
import useStore from '../store/useStore';
|
||||
import { imageAPI } from '../services/api';
|
||||
import FileViewer from './FileViewer';
|
||||
|
||||
// 虚拟滚动阈值:超过此数量启用虚拟滚动
|
||||
const VIRTUAL_SCROLL_THRESHOLD = 500;
|
||||
|
||||
// Web Worker 阈值:超过此数量使用 Worker 计算布局
|
||||
const WORKER_THRESHOLD = 200;
|
||||
|
||||
function ImageWaterfall() {
|
||||
const {
|
||||
filteredImages,
|
||||
currentLibraryId,
|
||||
thumbnailHeight,
|
||||
selectedImage,
|
||||
setSelectedImage,
|
||||
selectedImages,
|
||||
setSelectedImages,
|
||||
toggleImageSelection,
|
||||
clearSelection,
|
||||
isResizingPanels
|
||||
} = useStore();
|
||||
const containerRef = useRef(null);
|
||||
const listRef = useRef(null);
|
||||
const workerRef = useRef(null);
|
||||
const requestIdRef = useRef(0);
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const [containerHeight, setContainerHeight] = useState(0);
|
||||
const [photoIndex, setPhotoIndex] = useState(-1);
|
||||
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
|
||||
const [viewerFile, setViewerFile] = useState(null);
|
||||
const [workerRows, setWorkerRows] = useState([]); // Worker 计算的行
|
||||
|
||||
// 监听容器宽度变化(使用 ResizeObserver + 去抖/阈值抑制)
|
||||
useEffect(() => {
|
||||
let resizeObserver = null;
|
||||
let retryCount = 0;
|
||||
const maxRetries = 10;
|
||||
|
||||
// 使用 ref 记录上次宽度,避免频繁 setState
|
||||
const lastWidthRef = { current: 0 };
|
||||
let debounceTimer = null;
|
||||
|
||||
const emitSize = (width, height) => {
|
||||
// 仅当差异超过阈值时更新,减少重算次数
|
||||
const threshold = 12; // px
|
||||
if (Math.abs(width - lastWidthRef.current) < threshold) return true;
|
||||
|
||||
lastWidthRef.current = width;
|
||||
|
||||
// 去抖:在一小段静止后再更新(拖动时降低重算频率)
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
setContainerWidth(width);
|
||||
setContainerHeight(height);
|
||||
}, 50);
|
||||
return true;
|
||||
};
|
||||
|
||||
const measureAndEmit = () => {
|
||||
if (containerRef.current) {
|
||||
// 预留 padding:与现有布局保持一致
|
||||
const width = containerRef.current.offsetWidth - 32;
|
||||
const height = containerRef.current.offsetHeight;
|
||||
if (width > 0) {
|
||||
return emitSize(width, height);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const tryInit = () => {
|
||||
if (measureAndEmit()) {
|
||||
// 成功获取宽度,设置 ResizeObserver
|
||||
if (containerRef.current) {
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
// 拖动时跳过更新,避免频繁重算布局
|
||||
if (useStore.getState().isResizingPanels) return;
|
||||
measureAndEmit();
|
||||
});
|
||||
resizeObserver.observe(containerRef.current);
|
||||
}
|
||||
} else if (retryCount < maxRetries) {
|
||||
// 重试
|
||||
retryCount++;
|
||||
requestAnimationFrame(tryInit);
|
||||
}
|
||||
};
|
||||
|
||||
// 使用 requestAnimationFrame 确保 DOM 已渲染
|
||||
requestAnimationFrame(tryInit);
|
||||
|
||||
return () => {
|
||||
if (resizeObserver) {
|
||||
resizeObserver.disconnect();
|
||||
}
|
||||
if (debounceTimer) {
|
||||
clearTimeout(debounceTimer);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 拖动结束时(isResizingPanels 从 true -> false)立即测量一次
|
||||
useEffect(() => {
|
||||
if (isResizingPanels) return;
|
||||
if (!containerRef.current) return;
|
||||
const width = containerRef.current.offsetWidth - 32;
|
||||
const height = containerRef.current.offsetHeight;
|
||||
if (width > 0) {
|
||||
setContainerWidth(width);
|
||||
setContainerHeight(height);
|
||||
// 重置虚拟列表缓存
|
||||
if (listRef.current) {
|
||||
listRef.current.resetAfterIndex(0);
|
||||
}
|
||||
}
|
||||
}, [isResizingPanels]);
|
||||
|
||||
// 是否使用 Worker 计算布局
|
||||
const useWorker = filteredImages.length > WORKER_THRESHOLD;
|
||||
|
||||
// 当图片数据变化时重置 Worker 状态(更可靠的重置方式)
|
||||
const prevImagesLengthRef = useRef(0);
|
||||
useEffect(() => {
|
||||
// 图片列表从有到无或数量大幅变化时重置
|
||||
const prevLen = prevImagesLengthRef.current;
|
||||
const currLen = filteredImages.length;
|
||||
|
||||
if (prevLen > 0 && currLen === 0) {
|
||||
// 图片被清空,重置 Worker 状态
|
||||
setWorkerRows([]);
|
||||
requestIdRef.current = 0;
|
||||
} else if (currLen > 0 && Math.abs(currLen - prevLen) > prevLen * 0.5) {
|
||||
// 数量变化超过50%,可能是切换素材库,重置
|
||||
setWorkerRows([]);
|
||||
requestIdRef.current = 0;
|
||||
}
|
||||
|
||||
prevImagesLengthRef.current = currLen;
|
||||
}, [filteredImages.length]);
|
||||
|
||||
// 初始化 Web Worker
|
||||
useEffect(() => {
|
||||
if (typeof Worker !== 'undefined') {
|
||||
workerRef.current = new Worker(
|
||||
new URL('../workers/layoutWorker.js', import.meta.url),
|
||||
{ type: 'module' }
|
||||
);
|
||||
|
||||
workerRef.current.onmessage = (e) => {
|
||||
const { rows, requestId, duration, imageCount } = e.data;
|
||||
// 只处理最新的请求结果
|
||||
if (requestId === requestIdRef.current) {
|
||||
setWorkerRows(rows);
|
||||
if (imageCount > 500) {
|
||||
console.log(`📐 Worker layout: ${imageCount} images in ${duration.toFixed(1)}ms`);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (workerRef.current) {
|
||||
workerRef.current.terminate();
|
||||
workerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 使用 Worker 计算布局(大量图片时)
|
||||
useEffect(() => {
|
||||
if (!useWorker || !workerRef.current || !filteredImages.length || !containerWidth) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = ++requestIdRef.current;
|
||||
workerRef.current.postMessage({
|
||||
images: filteredImages,
|
||||
containerWidth,
|
||||
targetHeight: thumbnailHeight,
|
||||
requestId
|
||||
});
|
||||
}, [filteredImages, containerWidth, thumbnailHeight, useWorker]);
|
||||
|
||||
// 同步计算布局(少量图片时直接在主线程计算)
|
||||
const syncRows = useMemo(() => {
|
||||
// 使用 Worker 时返回空数组,由 workerRows 提供数据
|
||||
if (useWorker) return [];
|
||||
|
||||
if (!filteredImages.length || !containerWidth) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const gap = 16;
|
||||
const targetHeight = thumbnailHeight;
|
||||
|
||||
const calculatedRows = [];
|
||||
let currentRow = [];
|
||||
let currentRowWidthSum = 0;
|
||||
|
||||
filteredImages.forEach((image, index) => {
|
||||
const aspectRatio = image.width / image.height;
|
||||
const imageWidth = targetHeight * aspectRatio;
|
||||
|
||||
currentRow.push({
|
||||
...image,
|
||||
originalWidth: imageWidth,
|
||||
aspectRatio: aspectRatio
|
||||
});
|
||||
currentRowWidthSum += imageWidth;
|
||||
|
||||
const currentGaps = (currentRow.length - 1) * gap;
|
||||
const totalWidth = currentRowWidthSum + currentGaps;
|
||||
const isLastImage = index === filteredImages.length - 1;
|
||||
|
||||
let shouldFinishRow = false;
|
||||
|
||||
if (isLastImage) {
|
||||
shouldFinishRow = true;
|
||||
} else if (totalWidth >= containerWidth * 0.95) {
|
||||
// Row is almost full (95% or more) - finish it
|
||||
shouldFinishRow = true;
|
||||
} else {
|
||||
// Check if adding next image would overflow too much
|
||||
const nextImage = filteredImages[index + 1];
|
||||
if (nextImage) {
|
||||
const nextAspectRatio = nextImage.width / nextImage.height;
|
||||
const nextImageWidth = targetHeight * nextAspectRatio;
|
||||
const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
|
||||
|
||||
// If adding next image would exceed 120% of container width, finish current row
|
||||
if (nextTotalWidth > containerWidth * 1.2) {
|
||||
shouldFinishRow = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldFinishRow) {
|
||||
const totalGaps = (currentRow.length - 1) * gap;
|
||||
const availableWidth = containerWidth - totalGaps;
|
||||
|
||||
// For last row with few images, limit the scale to avoid over-stretching
|
||||
let scale = availableWidth / currentRowWidthSum;
|
||||
|
||||
if (isLastImage && currentRow.length < 3) {
|
||||
// Last row with 1-2 images: don't stretch too much
|
||||
scale = Math.min(scale, 1.2);
|
||||
}
|
||||
|
||||
const rowHeight = targetHeight * scale;
|
||||
|
||||
currentRow = currentRow.map(img => ({
|
||||
...img,
|
||||
calculatedWidth: img.originalWidth * scale,
|
||||
calculatedHeight: rowHeight
|
||||
}));
|
||||
|
||||
calculatedRows.push(currentRow);
|
||||
|
||||
// Reset for next row
|
||||
currentRow = [];
|
||||
currentRowWidthSum = 0;
|
||||
}
|
||||
});
|
||||
|
||||
return calculatedRows;
|
||||
}, [filteredImages, thumbnailHeight, containerWidth, useWorker]);
|
||||
|
||||
// 统一使用的行数据:Worker 模式用 workerRows,否则用 syncRows
|
||||
const rows = useWorker ? workerRows : syncRows;
|
||||
|
||||
const getThumbnailUrl = (image) => {
|
||||
if (!currentLibraryId || !image.thumbnail_path) return '';
|
||||
// 提取文件名(兼容反斜杠)
|
||||
const filename = image.thumbnail_path.replace(/\\/g, '/').split('/').pop();
|
||||
// 统一使用 480 尺寸(与 Billfish 一致)
|
||||
return imageAPI.getThumbnailUrl(currentLibraryId, '480', filename);
|
||||
};
|
||||
|
||||
const getOriginalUrl = (image) => {
|
||||
if (!currentLibraryId) return '';
|
||||
return imageAPI.getOriginalUrl(currentLibraryId, image.path);
|
||||
};
|
||||
|
||||
// PhotoProvider 使用与布局无关的列表,避免随 containerWidth 变化重建
|
||||
const providerImages = useMemo(() => {
|
||||
return filteredImages.map(img => ({ src: getOriginalUrl(img), key: img.id }));
|
||||
}, [filteredImages, currentLibraryId]);
|
||||
|
||||
// 是否启用虚拟滚动
|
||||
const useVirtualScroll = filteredImages.length > VIRTUAL_SCROLL_THRESHOLD;
|
||||
|
||||
// 获取行高(用于虚拟滚动)
|
||||
const getRowHeight = useCallback((index) => {
|
||||
if (!rows[index] || rows[index].length === 0) return thumbnailHeight + 40;
|
||||
// 行高 = 图片高度 + 文件名区域 + 行间距
|
||||
return rows[index][0].calculatedHeight + 28 + 32;
|
||||
}, [rows, thumbnailHeight]);
|
||||
|
||||
// 当行数据变化时,重置虚拟列表缓存
|
||||
useEffect(() => {
|
||||
if (listRef.current && useVirtualScroll) {
|
||||
listRef.current.resetAfterIndex(0);
|
||||
}
|
||||
}, [rows, useVirtualScroll]);
|
||||
|
||||
// 扁平化的图片列表(用于 Shift 多选)
|
||||
const flatImages = useMemo(() => rows.flat(), [rows]);
|
||||
|
||||
// 处理图片点击(支持 Ctrl/Shift 多选)
|
||||
const handleImageClick = useCallback((image, event, imageIndex) => {
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
// Ctrl/Cmd 点击:切换选中状态
|
||||
event.preventDefault();
|
||||
toggleImageSelection(image);
|
||||
setLastSelectedIndex(imageIndex);
|
||||
} else if (event.shiftKey && lastSelectedIndex !== null) {
|
||||
// Shift 点击:范围选择
|
||||
event.preventDefault();
|
||||
const start = Math.min(lastSelectedIndex, imageIndex);
|
||||
const end = Math.max(lastSelectedIndex, imageIndex);
|
||||
const rangeImages = flatImages.slice(start, end + 1);
|
||||
setSelectedImages(rangeImages);
|
||||
} else {
|
||||
// 普通点击:单选
|
||||
clearSelection();
|
||||
setSelectedImage(image);
|
||||
setLastSelectedIndex(imageIndex);
|
||||
}
|
||||
}, [flatImages, lastSelectedIndex, toggleImageSelection, setSelectedImages, clearSelection, setSelectedImage]);
|
||||
|
||||
// 渲染单个图片单元格
|
||||
const renderImageCell = (image, flatIndex) => {
|
||||
const isSingleSelected = selectedImage?.id === image.id;
|
||||
const isMultiSelected = selectedImages.some(img => img.id === image.id);
|
||||
const isSelected = isSingleSelected || isMultiSelected;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={image.id}
|
||||
className="flex-shrink-0"
|
||||
style={{ width: `${image.calculatedWidth}px` }}
|
||||
>
|
||||
<div
|
||||
className="relative group cursor-pointer overflow-hidden rounded-lg transition-all hover:shadow-lg"
|
||||
style={{
|
||||
height: `${image.calculatedHeight}px`,
|
||||
backgroundColor: '#2a2a2a',
|
||||
border: isSelected ? '3px solid #3b82f6' : '3px solid transparent'
|
||||
}}
|
||||
onClick={(e) => handleImageClick(image, e, flatIndex)}
|
||||
onDoubleClick={() => {
|
||||
const fileType = image.file_type || 'image';
|
||||
if (fileType === 'image') {
|
||||
setPhotoIndex(flatIndex);
|
||||
} else {
|
||||
setViewerFile(image);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={getThumbnailUrl(image)}
|
||||
alt={image.filename}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
e.target.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 文件类型标识 */}
|
||||
{image.file_type && image.file_type !== 'image' && (
|
||||
<div className={`absolute top-2 right-2 rounded-md px-2 py-1 flex items-center gap-1 shadow-lg ${
|
||||
image.file_type === 'video' ? 'bg-blue-500 bg-opacity-90' :
|
||||
image.file_type === 'audio' ? 'bg-pink-500 bg-opacity-90' :
|
||||
image.file_type === 'document' ? 'bg-green-500 bg-opacity-90' :
|
||||
image.file_type === 'design' ? 'bg-purple-500 bg-opacity-90' :
|
||||
'bg-gray-500 bg-opacity-90'
|
||||
}`}>
|
||||
{image.file_type === 'video' && <Play className="w-4 h-4 text-white fill-white" />}
|
||||
{image.file_type === 'audio' && <Music className="w-4 h-4 text-white" />}
|
||||
{image.file_type === 'document' && <FileText className="w-4 h-4 text-white" />}
|
||||
{image.file_type === 'design' && <Palette className="w-4 h-4 text-white" />}
|
||||
{image.file_type === 'other' && <File className="w-4 h-4 text-white" />}
|
||||
<span className="text-white text-xs font-semibold uppercase">
|
||||
{image.format || image.filename.split('.').pop()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all pointer-events-none" />
|
||||
</div>
|
||||
<div className="mt-1 px-1">
|
||||
<p
|
||||
className="text-xs truncate text-center transition-colors"
|
||||
style={{
|
||||
color: isSelected ? '#3b82f6' : '#909090',
|
||||
fontWeight: isSelected ? '600' : '400'
|
||||
}}
|
||||
>
|
||||
{image.filename}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染一行(用于虚拟滚动)
|
||||
const renderRow = ({ index, style }) => {
|
||||
const row = rows[index];
|
||||
if (!row) return null;
|
||||
|
||||
// 计算该行之前的所有图片数量
|
||||
let flatIndexBase = 0;
|
||||
for (let i = 0; i < index; i++) {
|
||||
flatIndexBase += rows[i]?.length || 0;
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ ...style, paddingBottom: '32px' }} className="flex gap-4">
|
||||
{row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (!filteredImages.length) {
|
||||
return (
|
||||
<div ref={containerRef} className="flex items-center justify-center h-full text-gray-500 dark:text-gray-400">
|
||||
<div className="text-center">
|
||||
<p className="text-lg mb-2">暂无图片</p>
|
||||
<p className="text-sm">请添加素材库或调整搜索条件</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Worker 正在计算中,显示加载状态(只在容器宽度已知且 Worker 已触发时)
|
||||
if (useWorker && rows.length === 0 && filteredImages.length > 0 && containerWidth > 0) {
|
||||
return (
|
||||
<div ref={containerRef} className="flex items-center justify-center h-full text-gray-500 dark:text-gray-400">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2"></div>
|
||||
<p className="text-sm">正在计算布局...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 等待容器宽度初始化
|
||||
if (!containerWidth && filteredImages.length > 0) {
|
||||
return (
|
||||
<div ref={containerRef} className="h-full overflow-hidden" />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="h-full overflow-hidden">
|
||||
<PhotoProvider
|
||||
images={providerImages}
|
||||
visible={photoIndex >= 0}
|
||||
onClose={() => setPhotoIndex(-1)}
|
||||
index={photoIndex}
|
||||
onIndexChange={setPhotoIndex}
|
||||
>
|
||||
{useVirtualScroll ? (
|
||||
/* 虚拟滚动模式(>500张图片) */
|
||||
<List
|
||||
ref={listRef}
|
||||
height={containerHeight || 600}
|
||||
width={containerWidth + 32}
|
||||
itemCount={rows.length}
|
||||
itemSize={getRowHeight}
|
||||
className="p-4"
|
||||
overscanCount={3}
|
||||
>
|
||||
{renderRow}
|
||||
</List>
|
||||
) : (
|
||||
/* 普通渲染模式(≤500张图片) */
|
||||
<div className="h-full overflow-y-auto p-4">
|
||||
<div className="space-y-8">
|
||||
{rows.map((row, rowIndex) => {
|
||||
let flatIndexBase = 0;
|
||||
for (let i = 0; i < rowIndex; i++) {
|
||||
flatIndexBase += rows[i]?.length || 0;
|
||||
}
|
||||
return (
|
||||
<div key={rowIndex} className="flex gap-4">
|
||||
{row.map((image, imageIndex) => renderImageCell(image, flatIndexBase + imageIndex))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</PhotoProvider>
|
||||
|
||||
{/* 文件查看器 */}
|
||||
{viewerFile && (
|
||||
<FileViewer
|
||||
file={viewerFile}
|
||||
libraryId={currentLibraryId}
|
||||
onClose={() => setViewerFile(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ImageWaterfall;
|
||||
@@ -0,0 +1,310 @@
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { Pause, Play } from 'lucide-react';
|
||||
import useStore from '../store/useStore';
|
||||
import { imageAPI, scanAPI } from '../services/api';
|
||||
import ImageWaterfall from './ImageWaterfall';
|
||||
import Dashboard from './Dashboard';
|
||||
|
||||
function MainContent() {
|
||||
const {
|
||||
currentLibraryId,
|
||||
searchKeywords,
|
||||
filters,
|
||||
selectedFolder,
|
||||
setImages,
|
||||
setTotalImageCount,
|
||||
scanProgress,
|
||||
scanStartTime
|
||||
} = useStore();
|
||||
|
||||
// 使用 ref 跟踪最新的请求
|
||||
const loadingRequestRef = useRef(0);
|
||||
// 文件夹切换防抖
|
||||
const folderDebounceRef = useRef(null);
|
||||
const [isLoadingImages, setIsLoadingImages] = useState(false);
|
||||
|
||||
// 计算预估剩余时间(优先使用后端提供的estimatedTimeLeft)
|
||||
const getEstimatedTime = () => {
|
||||
if (!scanProgress || scanProgress.current === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 优先使用后端提供的预估时间
|
||||
if (scanProgress.estimatedTimeLeft !== undefined) {
|
||||
const seconds = scanProgress.estimatedTimeLeft;
|
||||
if (seconds < 1) return '即将完成';
|
||||
if (seconds < 60) return `剩余约 ${seconds} 秒`;
|
||||
if (seconds < 3600) {
|
||||
const min = Math.floor(seconds / 60);
|
||||
const sec = seconds % 60;
|
||||
return sec > 0 ? `剩余约 ${min} 分 ${sec} 秒` : `剩余约 ${min} 分钟`;
|
||||
}
|
||||
const hrs = Math.floor(seconds / 3600);
|
||||
const min = Math.floor((seconds % 3600) / 60);
|
||||
return min > 0 ? `剩余约 ${hrs} 小时 ${min} 分钟` : `剩余约 ${hrs} 小时`;
|
||||
}
|
||||
|
||||
// 降级:使用前端计算
|
||||
if (!scanStartTime) return null;
|
||||
const elapsed = Date.now() - scanStartTime;
|
||||
const progress = scanProgress.current / scanProgress.total;
|
||||
if (progress === 0) return null;
|
||||
|
||||
const remaining = (elapsed / progress) - elapsed;
|
||||
const seconds = Math.ceil(remaining / 1000);
|
||||
|
||||
if (seconds < 60) return `剩余约 ${seconds} 秒`;
|
||||
if (seconds < 3600) {
|
||||
const min = Math.floor(seconds / 60);
|
||||
const sec = seconds % 60;
|
||||
return sec > 0 ? `剩余约 ${min} 分 ${sec} 秒` : `剩余约 ${min} 分钟`;
|
||||
}
|
||||
const hrs = Math.floor(seconds / 3600);
|
||||
const min = Math.floor((seconds % 3600) / 60);
|
||||
return min > 0 ? `剩余约 ${hrs} 小时 ${min} 分钟` : `剩余约 ${hrs} 小时`;
|
||||
};
|
||||
|
||||
// 使用 ref 追踪上次的 libraryId,避免重复加载
|
||||
const lastLibraryIdRef = useRef(null);
|
||||
// 扫描控制
|
||||
const [scanPaused, setScanPaused] = useState(false);
|
||||
const [isStoppingOrResuming, setIsStoppingOrResuming] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentLibraryId) {
|
||||
// 文件夹切换使用防抖(30ms),避免快速点击导致多次请求
|
||||
if (folderDebounceRef.current) {
|
||||
clearTimeout(folderDebounceRef.current);
|
||||
}
|
||||
|
||||
folderDebounceRef.current = setTimeout(() => {
|
||||
loadImages();
|
||||
}, selectedFolder !== null ? 30 : 0); // 选择文件夹时防抖,清空时立即加载
|
||||
|
||||
// 只在切换素材库时加载文件夹和总数
|
||||
if (lastLibraryIdRef.current !== currentLibraryId) {
|
||||
loadFolders();
|
||||
lastLibraryIdRef.current = currentLibraryId;
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (folderDebounceRef.current) {
|
||||
clearTimeout(folderDebounceRef.current);
|
||||
}
|
||||
};
|
||||
}, [currentLibraryId, searchKeywords, filters, selectedFolder]);
|
||||
|
||||
const loadImages = useCallback(async () => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
// 递增请求ID
|
||||
const requestId = ++loadingRequestRef.current;
|
||||
|
||||
// Optimization: If no folder selected and no search/filters, do NOT fetch images
|
||||
// This prevents loading all images when showing Dashboard
|
||||
if (!selectedFolder && !searchKeywords && filters.formats.length === 0) {
|
||||
if (requestId === loadingRequestRef.current) {
|
||||
setImages([]); // Clear images to save memory
|
||||
setIsLoadingImages(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoadingImages(true);
|
||||
|
||||
try {
|
||||
const params = {
|
||||
keywords: searchKeywords,
|
||||
...filters
|
||||
};
|
||||
|
||||
// 只有选中了文件夹才添加 folder 参数
|
||||
if (selectedFolder) {
|
||||
params.folder = selectedFolder;
|
||||
}
|
||||
|
||||
const response = await imageAPI.search(currentLibraryId, params);
|
||||
|
||||
// 只有当这是最新的请求时才更新状态
|
||||
if (requestId === loadingRequestRef.current) {
|
||||
setImages(response.data.images);
|
||||
|
||||
// 无筛选条件时,同步更新总数
|
||||
if (!selectedFolder && !searchKeywords) {
|
||||
setTotalImageCount(response.data.images.length);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 只有当这是最新的请求时才显示错误
|
||||
if (requestId === loadingRequestRef.current) {
|
||||
console.error('Error loading images:', error);
|
||||
}
|
||||
} finally {
|
||||
if (requestId === loadingRequestRef.current) {
|
||||
setIsLoadingImages(false);
|
||||
}
|
||||
}
|
||||
}, [currentLibraryId, searchKeywords, filters, selectedFolder, setImages, setTotalImageCount]);
|
||||
|
||||
const loadFolders = async () => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
try {
|
||||
const response = await imageAPI.getFolders(currentLibraryId);
|
||||
useStore.getState().setFolders(response.data.folders);
|
||||
} catch (error) {
|
||||
console.error('Error loading folders:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 停止扫描
|
||||
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) {
|
||||
// 应用重启后的恢复:使用增量同步
|
||||
console.log('🔄 使用增量同步恢复扫描');
|
||||
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) {
|
||||
// 从 Sidebar/App 恢复的暂停状态
|
||||
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 - 只有当有进度数据时才显示 */}
|
||||
{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="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 dark:text-yellow-400'
|
||||
: 'text-blue-600 dark:text-blue-400'
|
||||
}`}>
|
||||
{scanProgress?.percent || 0}%
|
||||
</span>
|
||||
{/* 停止/继续按钮 */}
|
||||
{(scanProgress?.canStop || scanPaused) && (
|
||||
<button
|
||||
onClick={scanPaused ? handleResumeScan : handleStopScan}
|
||||
disabled={isStoppingOrResuming}
|
||||
className={`p-1.5 rounded-md transition-colors ${scanPaused
|
||||
? 'bg-green-500 hover:bg-green-600 text-white'
|
||||
: 'bg-yellow-500 hover:bg-yellow-600 text-white'
|
||||
} ${isStoppingOrResuming ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
title={scanPaused ? '继续扫描' : '暂停扫描'}
|
||||
>
|
||||
{isStoppingOrResuming ? (
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
) : scanPaused ? (
|
||||
<Play className="w-4 h-4" />
|
||||
) : (
|
||||
<Pause className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={`w-full rounded-full h-2 mb-2 ${scanPaused
|
||||
? 'bg-yellow-200 dark:bg-yellow-800'
|
||||
: 'bg-blue-200 dark:bg-blue-800'
|
||||
}`}>
|
||||
<div
|
||||
className={`h-2 rounded-full transition-all duration-300 ${scanPaused
|
||||
? 'bg-yellow-500'
|
||||
: scanProgress?.status === 'preparing'
|
||||
? 'bg-blue-400 animate-pulse'
|
||||
: 'bg-blue-500'
|
||||
}`}
|
||||
style={{ width: `${scanProgress?.percent || 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className={`flex items-center justify-between text-xs ${scanPaused
|
||||
? 'text-yellow-600 dark:text-yellow-400'
|
||||
: 'text-blue-600 dark:text-blue-400'
|
||||
}`}>
|
||||
<span>
|
||||
{scanPaused
|
||||
? scanProgress?.needsRescan
|
||||
? `上次扫描中断于 ${scanProgress?.current || 0} 张,点击继续完成`
|
||||
: `已处理 ${scanProgress?.current || 0} 张,剩余 ${scanProgress?.pendingCount || (scanProgress?.total - scanProgress?.current) || 0} 张待处理`
|
||||
: scanProgress?.status === 'preparing'
|
||||
? '正在初始化...'
|
||||
: `已处理 ${scanProgress?.current || 0} / ${scanProgress?.total || 0} 张图片`
|
||||
}
|
||||
</span>
|
||||
<span>
|
||||
{scanPaused
|
||||
? scanProgress?.needsRescan ? '需要继续' : '暂停中'
|
||||
: (getEstimatedTime() || '扫描完成后将自动显示')
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Content Area */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{(!selectedFolder && !searchKeywords && filters.formats.length === 0) ? (
|
||||
<Dashboard />
|
||||
) : (
|
||||
<ImageWaterfall />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MainContent;
|
||||
@@ -0,0 +1,553 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Copy, Download, Check, FolderDown, ArrowLeft } from 'lucide-react';
|
||||
import useStore from '../store/useStore';
|
||||
import { imageAPI } from '../services/api';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
function RightPanel() {
|
||||
const { selectedImage, selectedImages, currentLibraryId, selectedFolder, images, setMobileView, isResizingPanels, resizingSide } = useStore();
|
||||
const [isMobile, setIsMobile] = useState(false);
|
||||
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
||||
const [isLoadingOriginal, setIsLoadingOriginal] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [imageCopied, setImageCopied] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [exportProgress, setExportProgress] = useState(0);
|
||||
const [isExportingFolder, setIsExportingFolder] = useState(false);
|
||||
const [folderExportProgress, setFolderExportProgress] = useState(0);
|
||||
|
||||
// 判断是单选还是多选
|
||||
const isMultiSelect = selectedImages.length > 0;
|
||||
const displayImage = isMultiSelect ? selectedImages[0] : selectedImage;
|
||||
|
||||
// 检测移动端
|
||||
useEffect(() => {
|
||||
const checkMobile = () => {
|
||||
setIsMobile(window.innerWidth < 768);
|
||||
};
|
||||
checkMobile();
|
||||
window.addEventListener('resize', checkMobile);
|
||||
return () => window.removeEventListener('resize', checkMobile);
|
||||
}, []);
|
||||
|
||||
// 图片加载策略:先显示缩略图,后台加载原图;拖动右侧面板时只显示缩略图
|
||||
useEffect(() => {
|
||||
if (!selectedImage || !currentLibraryId) {
|
||||
setImageUrl('');
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. 立即显示缩略图
|
||||
const thumbnailUrl = getThumbnailUrl();
|
||||
setImageUrl(thumbnailUrl);
|
||||
setIsLoadingOriginal(true);
|
||||
|
||||
// 如果正在拖动任一面板,则先不加载原图,降低主线程和解码压力
|
||||
if (isResizingPanels) {
|
||||
setIsLoadingOriginal(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 后台预加载原图
|
||||
const originalUrl = getOriginalUrl();
|
||||
const img = new Image();
|
||||
|
||||
img.onload = () => {
|
||||
// 原图加载完成,切换到原图
|
||||
setImageUrl(originalUrl);
|
||||
setIsLoadingOriginal(false);
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
// 原图加载失败,保持显示缩略图
|
||||
console.error('Failed to load original image');
|
||||
setIsLoadingOriginal(false);
|
||||
};
|
||||
|
||||
img.src = originalUrl;
|
||||
|
||||
// 清理函数
|
||||
return () => {
|
||||
img.onload = null;
|
||||
img.onerror = null;
|
||||
};
|
||||
}, [selectedImage, currentLibraryId, isResizingPanels, resizingSide]);
|
||||
|
||||
if (!selectedImage && selectedImages.length === 0) {
|
||||
return (
|
||||
<div className="w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex items-center justify-center">
|
||||
<p className="text-gray-400 dark:text-gray-500 text-sm">选择图片查看详情</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const getThumbnailUrl = () => {
|
||||
if (!currentLibraryId || !selectedImage.thumbnail_path) return '';
|
||||
// Handle both forward and backslash
|
||||
const filename = selectedImage.thumbnail_path.replace(/\\/g, '/').split('/').pop();
|
||||
return imageAPI.getThumbnailUrl(currentLibraryId, '200', filename);
|
||||
};
|
||||
|
||||
const getOriginalUrl = () => {
|
||||
if (!currentLibraryId || !selectedImage.path) return '';
|
||||
return imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
||||
};
|
||||
|
||||
// 复制图片到剪贴板(支持粘贴到聊天软件和文件管理器)
|
||||
const copyImageToClipboard = async () => {
|
||||
try {
|
||||
// 获取原图URL
|
||||
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
||||
|
||||
// 获取图片数据
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 创建临时图片元素
|
||||
const img = new Image();
|
||||
const loadPromise = new Promise((resolve, reject) => {
|
||||
img.onload = resolve;
|
||||
img.onerror = reject;
|
||||
});
|
||||
img.src = URL.createObjectURL(blob);
|
||||
await loadPromise;
|
||||
|
||||
// 使用 canvas 转换为 PNG
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(img, 0, 0);
|
||||
|
||||
// 转换为 PNG blob
|
||||
canvas.toBlob(async (pngBlob) => {
|
||||
try {
|
||||
// 创建包含多种格式的剪贴板项
|
||||
const clipboardItem = new ClipboardItem({
|
||||
'image/png': pngBlob,
|
||||
// 添加 HTML 格式(支持更多粘贴场景)
|
||||
'text/html': new Blob(
|
||||
[`<img src="${imageUrl}" alt="${selectedImage.filename}">`],
|
||||
{ type: 'text/html' }
|
||||
),
|
||||
// 添加纯文本格式(文件路径)
|
||||
'text/plain': new Blob(
|
||||
[imageUrl],
|
||||
{ type: 'text/plain' }
|
||||
)
|
||||
});
|
||||
|
||||
await navigator.clipboard.write([clipboardItem]);
|
||||
|
||||
setImageCopied(true);
|
||||
setTimeout(() => setImageCopied(false), 2000);
|
||||
} catch (err) {
|
||||
console.error('写入剪贴板失败:', err);
|
||||
// 如果多格式失败,尝试只复制图像
|
||||
try {
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({ 'image/png': pngBlob })
|
||||
]);
|
||||
setImageCopied(true);
|
||||
setTimeout(() => setImageCopied(false), 2000);
|
||||
} catch (fallbackErr) {
|
||||
console.error('备用方案也失败:', fallbackErr);
|
||||
alert('复制失败,请重试');
|
||||
}
|
||||
}
|
||||
}, 'image/png');
|
||||
|
||||
// 清理
|
||||
URL.revokeObjectURL(img.src);
|
||||
|
||||
} catch (error) {
|
||||
console.error('复制图片失败:', error);
|
||||
alert('复制图片失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
// 批量复制图片
|
||||
const copyMultipleImages = async () => {
|
||||
try {
|
||||
const imagesToCopy = isMultiSelect ? selectedImages : [selectedImage];
|
||||
|
||||
if (imagesToCopy.length === 1) {
|
||||
// 单张图片:直接复制
|
||||
await copyImageToClipboard();
|
||||
return;
|
||||
}
|
||||
|
||||
// 多张图片:浏览器限制,只能复制为 HTML 格式(包含多个 img 标签)
|
||||
// 这样粘贴到支持 HTML 的应用时,会显示为多张图片
|
||||
|
||||
// 加载所有图片并转换为 base64
|
||||
const imageDataList = await Promise.all(
|
||||
imagesToCopy.map(async (img) => {
|
||||
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, img.path);
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 转换为 base64
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
resolve({
|
||||
dataUrl: reader.result,
|
||||
filename: img.filename
|
||||
});
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// 创建 HTML 格式(多个图片)
|
||||
const htmlContent = imageDataList.map(({ dataUrl, filename }) =>
|
||||
`<img src="${dataUrl}" alt="${filename}" style="display:block; margin:10px 0;">`
|
||||
).join('\n');
|
||||
|
||||
// 创建纯文本格式(文件名列表)
|
||||
const textContent = imagesToCopy.map(img => img.filename).join('\n');
|
||||
|
||||
try {
|
||||
// 尝试写入多种格式
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'text/html': new Blob([htmlContent], { type: 'text/html' }),
|
||||
'text/plain': new Blob([textContent], { type: 'text/plain' })
|
||||
})
|
||||
]);
|
||||
|
||||
setImageCopied(true);
|
||||
setTimeout(() => setImageCopied(false), 2000);
|
||||
} catch (err) {
|
||||
console.error('写入剪贴板失败:', err);
|
||||
alert(`复制失败。\n\n提示:浏览器限制,多张图片会以 HTML 格式复制。\n可粘贴到 Word、富文本编辑器等。\n\n如需单独使用,请使用"导出"功能。`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('复制图片失败:', error);
|
||||
alert('复制图片失败,请重试');
|
||||
}
|
||||
};
|
||||
|
||||
// 批量导出图片(打包成 ZIP)
|
||||
const exportMultipleImages = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const imagesToExport = isMultiSelect ? selectedImages : [selectedImage];
|
||||
|
||||
if (imagesToExport.length === 1) {
|
||||
// 单张图片直接下载
|
||||
const url = imageAPI.getOriginalUrl(currentLibraryId, imagesToExport[0].path);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = imagesToExport[0].filename;
|
||||
link.target = '_blank';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
} else {
|
||||
// 多张图片:打包成 ZIP
|
||||
const zip = new JSZip();
|
||||
const folder = zip.folder('images');
|
||||
|
||||
setExportProgress(0);
|
||||
|
||||
// 下载所有图片并添加到 ZIP
|
||||
for (let i = 0; i < imagesToExport.length; i++) {
|
||||
const img = imagesToExport[i];
|
||||
const url = imageAPI.getOriginalUrl(currentLibraryId, img.path);
|
||||
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 添加到 ZIP,使用原文件名
|
||||
folder.file(img.filename, blob);
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.round(((i + 1) / imagesToExport.length) * 90); // 90% 用于下载
|
||||
setExportProgress(progress);
|
||||
|
||||
console.log(`已添加: ${img.filename} (${i + 1}/${imagesToExport.length})`);
|
||||
} catch (error) {
|
||||
console.error(`下载失败: ${img.filename}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成 ZIP 文件
|
||||
setExportProgress(95);
|
||||
console.log('正在生成 ZIP 文件...');
|
||||
const zipBlob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
});
|
||||
|
||||
// 下载 ZIP 文件
|
||||
setExportProgress(100);
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(zipBlob);
|
||||
link.download = `FlyPic_导出_${imagesToExport.length}张_${Date.now()}.zip`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(link.href);
|
||||
|
||||
console.log('导出完成!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
alert('导出失败,请重试');
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 导出当前文件夹的所有图片
|
||||
const exportCurrentFolder = async () => {
|
||||
if (!selectedFolder) {
|
||||
alert('请先选择一个文件夹');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsExportingFolder(true);
|
||||
setFolderExportProgress(0);
|
||||
|
||||
try {
|
||||
// 获取当前文件夹下的所有图片
|
||||
const folderImages = images.filter(img => {
|
||||
// 检查图片是否在当前文件夹或其子文件夹中
|
||||
return img.folder && img.folder.startsWith(selectedFolder);
|
||||
});
|
||||
|
||||
if (folderImages.length === 0) {
|
||||
alert('当前文件夹没有图片');
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建 ZIP
|
||||
const zip = new JSZip();
|
||||
const folderName = selectedFolder.split('/').pop() || 'images';
|
||||
const folder = zip.folder(folderName);
|
||||
|
||||
// 下载所有图片并添加到 ZIP
|
||||
for (let i = 0; i < folderImages.length; i++) {
|
||||
const img = folderImages[i];
|
||||
const url = imageAPI.getOriginalUrl(currentLibraryId, img.path);
|
||||
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 保持相对路径结构
|
||||
const relativePath = img.folder.replace(selectedFolder, '').replace(/^\//, '');
|
||||
const filePath = relativePath ? `${relativePath}/${img.filename}` : img.filename;
|
||||
|
||||
folder.file(filePath, blob);
|
||||
|
||||
// 更新进度
|
||||
const progress = Math.round(((i + 1) / folderImages.length) * 90);
|
||||
setFolderExportProgress(progress);
|
||||
|
||||
console.log(`已添加: ${filePath} (${i + 1}/${folderImages.length})`);
|
||||
} catch (error) {
|
||||
console.error(`下载失败: ${img.filename}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 生成 ZIP 文件
|
||||
setFolderExportProgress(95);
|
||||
console.log('正在生成 ZIP 文件...');
|
||||
const zipBlob = await zip.generateAsync({
|
||||
type: 'blob',
|
||||
compression: 'DEFLATE',
|
||||
compressionOptions: { level: 6 }
|
||||
});
|
||||
|
||||
// 下载 ZIP 文件
|
||||
setFolderExportProgress(100);
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(zipBlob);
|
||||
link.download = `${folderName}_${folderImages.length}张_${Date.now()}.zip`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(link.href);
|
||||
|
||||
console.log('文件夹导出完成!');
|
||||
} catch (error) {
|
||||
console.error('导出文件夹失败:', error);
|
||||
alert('导出文件夹失败,请重试');
|
||||
} finally {
|
||||
setIsExportingFolder(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes) => {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
|
||||
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
|
||||
};
|
||||
|
||||
const formatDate = (timestamp) => {
|
||||
return new Date(timestamp).toLocaleString('zh-CN');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full border-l border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col h-full">
|
||||
{/* 移动端返回按钮 */}
|
||||
{isMobile && (
|
||||
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center">
|
||||
<button
|
||||
onClick={() => setMobileView('main')}
|
||||
className="flex items-center gap-2 text-gray-700 dark:text-gray-300 hover:text-blue-500"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
<span className="text-sm font-medium">返回</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Progressive Image Preview */}
|
||||
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
|
||||
<div className="w-full aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden relative">
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt={displayImage.filename}
|
||||
decoding="async"
|
||||
className={`w-full h-full object-contain transition-opacity duration-300 ${
|
||||
isLoadingOriginal ? 'opacity-75' : 'opacity-100'
|
||||
}`}
|
||||
/>
|
||||
{isLoadingOriginal && (
|
||||
<div className="absolute top-2 right-2 bg-blue-500 text-white text-xs px-2 py-1 rounded">
|
||||
加载原图中...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image Info - 可滚动区域 */}
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">基本信息</h3>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">文件名:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100 break-all">{selectedImage.filename}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100">
|
||||
{selectedImage.width} × {selectedImage.height}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">大小:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100">{formatFileSize(selectedImage.size)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">格式:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100 uppercase">{selectedImage.format}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">创建时间:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100">{formatDate(selectedImage.created_at)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">修改时间:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100">{formatDate(selectedImage.modified_at)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-gray-500 dark:text-gray-400">路径:</span>
|
||||
<p className="text-gray-900 dark:text-gray-100 text-xs break-all">{selectedImage.path}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions - 仅桌面端显示 */}
|
||||
{!isMobile && (
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
|
||||
{/* 复制按钮 */}
|
||||
<button
|
||||
onClick={copyMultipleImages}
|
||||
className={`w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg transition-all ${
|
||||
imageCopied
|
||||
? 'bg-green-500 text-white'
|
||||
: 'bg-blue-500 text-white hover:bg-blue-600'
|
||||
}`}
|
||||
>
|
||||
{imageCopied ? (
|
||||
<>
|
||||
<Check className="w-4 h-4" />
|
||||
<span>已复制{isMultiSelect ? ` ${selectedImages.length} 张` : ''}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="w-4 h-4" />
|
||||
<span>复制图片{isMultiSelect ? ` (${selectedImages.length})` : ''}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* 导出按钮 */}
|
||||
<button
|
||||
onClick={exportMultipleImages}
|
||||
disabled={isExporting}
|
||||
className="w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
<span>
|
||||
{isExporting
|
||||
? `打包中... ${exportProgress}%`
|
||||
: `导出图片${isMultiSelect ? ` (${selectedImages.length})` : ''}`
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
{isExporting && isMultiSelect && (
|
||||
<div className="w-full bg-gray-300 dark:bg-gray-600 rounded-full h-1.5 mt-1">
|
||||
<div
|
||||
className="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
|
||||
style={{ width: `${exportProgress}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* 导出文件夹按钮 */}
|
||||
{selectedFolder && (
|
||||
<button
|
||||
onClick={exportCurrentFolder}
|
||||
disabled={isExportingFolder}
|
||||
className="w-full flex flex-col items-center justify-center gap-2 px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderDown className="w-4 h-4" />
|
||||
<span>
|
||||
{isExportingFolder
|
||||
? `打包文件夹... ${folderExportProgress}%`
|
||||
: '导出当前文件夹'
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
{isExportingFolder && (
|
||||
<div className="w-full bg-purple-300 rounded-full h-1.5 mt-1">
|
||||
<div
|
||||
className="bg-white h-1.5 rounded-full transition-all duration-300"
|
||||
style={{ width: `${folderExportProgress}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default RightPanel;
|
||||
@@ -0,0 +1,601 @@
|
||||
import { useState, useMemo, useEffect, useRef } from 'react';
|
||||
import { Folder, Search, ChevronRight, ChevronDown, X, Trash2, ChevronsRight, ChevronsDown } from 'lucide-react';
|
||||
import useStore from '../store/useStore';
|
||||
import { libraryAPI, scanAPI, imageAPI } from '../services/api';
|
||||
|
||||
// 检查素材库是否有暂停的扫描
|
||||
const checkPausedScan = async (libraryId) => {
|
||||
try {
|
||||
const response = await scanAPI.getStatus(libraryId);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
function Sidebar() {
|
||||
const {
|
||||
libraries,
|
||||
currentLibraryId,
|
||||
folders,
|
||||
selectedFolder,
|
||||
totalImageCount,
|
||||
setCurrentLibrary,
|
||||
setSelectedFolder,
|
||||
addLibrary,
|
||||
removeLibrary
|
||||
} = useStore();
|
||||
|
||||
const [showAddLibrary, setShowAddLibrary] = useState(false);
|
||||
const [newLibraryName, setNewLibraryName] = useState('');
|
||||
const [newLibraryPath, setNewLibraryPath] = useState('');
|
||||
const [folderSearch, setFolderSearch] = useState('');
|
||||
const [localFolderSearch, setLocalFolderSearch] = useState(''); // 本地输入值
|
||||
const [expandedFolders, setExpandedFolders] = useState(new Set());
|
||||
const [isAdding, setIsAdding] = useState(false);
|
||||
const [isSwitching, setIsSwitching] = useState(false);
|
||||
const folderSearchDebounceRef = useRef(null);
|
||||
|
||||
// 文件夹搜索防抖(300ms)
|
||||
const handleFolderSearchChange = (value) => {
|
||||
setLocalFolderSearch(value);
|
||||
|
||||
if (folderSearchDebounceRef.current) {
|
||||
clearTimeout(folderSearchDebounceRef.current);
|
||||
}
|
||||
|
||||
folderSearchDebounceRef.current = setTimeout(() => {
|
||||
setFolderSearch(value);
|
||||
}, 300);
|
||||
};
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (folderSearchDebounceRef.current) {
|
||||
clearTimeout(folderSearchDebounceRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleAddLibrary = async () => {
|
||||
if (!newLibraryName.trim()) {
|
||||
alert('请输入素材库名称');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!newLibraryPath.trim()) {
|
||||
alert('请输入文件夹路径');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsAdding(true);
|
||||
|
||||
try {
|
||||
// 1. 添加素材库
|
||||
console.log('📝 添加素材库...');
|
||||
const response = await libraryAPI.add(newLibraryName.trim(), newLibraryPath.trim());
|
||||
const newLibId = response.data.id;
|
||||
const hasExistingIndex = response.data.hasExistingIndex;
|
||||
|
||||
addLibrary({
|
||||
id: newLibId,
|
||||
name: newLibraryName.trim(),
|
||||
path: newLibraryPath.trim()
|
||||
});
|
||||
|
||||
// 2. 关闭表单
|
||||
setNewLibraryName('');
|
||||
setNewLibraryPath('');
|
||||
setShowAddLibrary(false);
|
||||
setIsAdding(false); // 立即释放按钮
|
||||
|
||||
// 3. 切换到新素材库
|
||||
console.log('🔄 切换到新素材库...');
|
||||
await libraryAPI.setCurrent(newLibId);
|
||||
setCurrentLibrary(newLibId);
|
||||
setSelectedFolder(null);
|
||||
|
||||
// 4. 清空当前显示
|
||||
useStore.getState().setImages([]);
|
||||
useStore.getState().setFolders([]);
|
||||
useStore.getState().setSelectedImage(null);
|
||||
useStore.getState().setTotalImageCount(0); // 清空总数
|
||||
|
||||
// 5. 显示初始进度(立即显示,不等待后端)
|
||||
useStore.getState().setScanProgress({
|
||||
libraryId: newLibId,
|
||||
current: 0,
|
||||
total: 0,
|
||||
percent: 0,
|
||||
status: 'preparing'
|
||||
});
|
||||
|
||||
// 6. 如果有已有索引,先快速加载数据库中的数据
|
||||
if (hasExistingIndex) {
|
||||
console.log('检测到已有索引,先加载现有数据...');
|
||||
try {
|
||||
const [foldersRes, countRes] = await Promise.all([
|
||||
imageAPI.getFolders(newLibId),
|
||||
imageAPI.getCount(newLibId)
|
||||
]);
|
||||
useStore.getState().setFolders(foldersRes.data.folders);
|
||||
useStore.getState().setTotalImageCount(countRes.data.count);
|
||||
console.log('✅ 已加载现有数据');
|
||||
} catch (err) {
|
||||
console.warn('⚠️ 加载现有数据失败:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// 7. 开始异步扫描(不等待,Socket.IO 会推送进度)
|
||||
console.log('🔍 开始异步扫描...');
|
||||
if (hasExistingIndex) {
|
||||
console.log('执行增量同步,检测变化...');
|
||||
scanAPI.sync(newLibId, false); // wait=false,异步执行
|
||||
} else {
|
||||
console.log('首次添加,执行全量扫描...');
|
||||
scanAPI.fullScan(newLibId, false); // wait=false,异步执行
|
||||
}
|
||||
|
||||
// 扫描在后台进行,Socket.IO 会推送进度和完成事件
|
||||
// App.jsx 中的 scanComplete 监听器会自动刷新数据
|
||||
console.log('✅ 扫描已启动,请等待进度显示...');
|
||||
} catch (error) {
|
||||
console.error('❌ Error adding library:', error);
|
||||
alert('添加素材库失败: ' + error.message);
|
||||
useStore.getState().setScanProgress(null);
|
||||
setIsAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLibraryClick = async (libraryId) => {
|
||||
if (libraryId === currentLibraryId) return;
|
||||
|
||||
setIsSwitching(true);
|
||||
try {
|
||||
// 切换前清理当前素材库的状态
|
||||
useStore.getState().setScanProgress(null);
|
||||
useStore.getState().setSelectedImage(null);
|
||||
setSelectedFolder(null);
|
||||
|
||||
// 并行执行:切换素材库 + 预加载数据
|
||||
const [, foldersRes, imagesRes] = await Promise.all([
|
||||
libraryAPI.setCurrent(libraryId),
|
||||
imageAPI.getFolders(libraryId),
|
||||
imageAPI.search(libraryId, {})
|
||||
]);
|
||||
|
||||
// 更新状态
|
||||
setCurrentLibrary(libraryId);
|
||||
useStore.getState().setFolders(foldersRes.data.folders);
|
||||
useStore.getState().setImages(imagesRes.data.images);
|
||||
useStore.getState().setTotalImageCount(imagesRes.data.images.length);
|
||||
|
||||
// 后台检查新素材库是否有暂停的扫描(不阻塞主流程)
|
||||
checkPausedScan(libraryId).then(scanStatus => {
|
||||
if (scanStatus && scanStatus.status === 'paused') {
|
||||
if (scanStatus.needsRescan) {
|
||||
useStore.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) {
|
||||
useStore.getState().setScanProgress({
|
||||
...scanStatus.progress,
|
||||
libraryId,
|
||||
canStop: true,
|
||||
isPaused: true,
|
||||
pendingCount: scanStatus.pendingCount
|
||||
});
|
||||
console.log(`⏸️ 发现暂停的扫描,待处理: ${scanStatus.pendingCount} 张`);
|
||||
}
|
||||
}
|
||||
}).catch(() => { }); // 忽略状态检查错误
|
||||
} catch (error) {
|
||||
console.error('Error setting current library:', error);
|
||||
alert('切换素材库失败: ' + error.message);
|
||||
} finally {
|
||||
setIsSwitching(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const handleDeleteLibrary = async () => {
|
||||
if (!currentLibraryId) return;
|
||||
|
||||
const currentLib = libraries.find(lib => lib.id === currentLibraryId);
|
||||
if (!currentLib) return;
|
||||
|
||||
// 确认删除
|
||||
const confirmDelete = confirm(
|
||||
`确定要删除素材库"${currentLib.name}"吗?\n\n` +
|
||||
`路径: ${currentLib.path}\n\n` +
|
||||
`⚠️ 注意:\n` +
|
||||
`• 将删除索引数据并释放数据库连接\n` +
|
||||
`• 不会删除原始图片文件\n` +
|
||||
`• .flypic 文件夹将保留,您可以手动删除`
|
||||
);
|
||||
|
||||
if (!confirmDelete) return;
|
||||
|
||||
try {
|
||||
// 删除素材库(会自动关闭数据库连接)
|
||||
await libraryAPI.delete(currentLibraryId);
|
||||
removeLibrary(currentLibraryId);
|
||||
|
||||
// Clear UI state
|
||||
useStore.getState().setImages([]);
|
||||
useStore.getState().setFolders([]);
|
||||
useStore.getState().setSelectedImage(null);
|
||||
useStore.getState().setSelectedFolder(null);
|
||||
|
||||
// Switch to first available library if exists
|
||||
const remainingLibs = libraries.filter(lib => lib.id !== currentLibraryId);
|
||||
if (remainingLibs.length > 0) {
|
||||
const firstLib = remainingLibs[0];
|
||||
await libraryAPI.setCurrent(firstLib.id);
|
||||
setCurrentLibrary(firstLib.id);
|
||||
}
|
||||
|
||||
// 静默成功,不弹窗
|
||||
console.log(`✅ 素材库已删除: ${currentLib.name}`);
|
||||
console.log(`数据库连接已释放,可手动删除: ${currentLib.path}\\.flypic`);
|
||||
} catch (error) {
|
||||
console.error('Error deleting library:', error);
|
||||
alert('删除素材库失败: ' + error.message);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleFolder = (folderPath) => {
|
||||
const newExpanded = new Set(expandedFolders);
|
||||
if (newExpanded.has(folderPath)) {
|
||||
newExpanded.delete(folderPath);
|
||||
} else {
|
||||
newExpanded.add(folderPath);
|
||||
}
|
||||
setExpandedFolders(newExpanded);
|
||||
};
|
||||
|
||||
// 收集所有文件夹路径
|
||||
const getAllFolderPaths = (folderList) => {
|
||||
const paths = [];
|
||||
const traverse = (folders) => {
|
||||
folders.forEach(folder => {
|
||||
if (folder.children && folder.children.length > 0) {
|
||||
paths.push(folder.path);
|
||||
traverse(folder.children);
|
||||
}
|
||||
});
|
||||
};
|
||||
traverse(folderList);
|
||||
return paths;
|
||||
};
|
||||
|
||||
// 全部展开
|
||||
const expandAll = () => {
|
||||
const allPaths = getAllFolderPaths(filteredFolders.length > 0 ? filteredFolders : folders);
|
||||
setExpandedFolders(new Set(allPaths));
|
||||
};
|
||||
|
||||
// 全部折叠
|
||||
const collapseAll = () => {
|
||||
setExpandedFolders(new Set());
|
||||
};
|
||||
|
||||
// 判断是否全部展开
|
||||
const isAllExpanded = () => {
|
||||
const allPaths = getAllFolderPaths(filteredFolders.length > 0 ? filteredFolders : folders);
|
||||
return allPaths.length > 0 && allPaths.every(path => expandedFolders.has(path));
|
||||
};
|
||||
|
||||
// 使用 useMemo 缓存过滤结果(支持多关键词搜索)
|
||||
const filteredFolders = useMemo(() => {
|
||||
if (!folderSearch) return folders;
|
||||
|
||||
// 分割搜索词,支持空格分隔的多个关键词
|
||||
const keywords = folderSearch
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(k => k.length > 0);
|
||||
|
||||
if (keywords.length === 0) return folders;
|
||||
|
||||
const pathsToExpand = [];
|
||||
|
||||
const filterRecursive = (folderList) => {
|
||||
return folderList.reduce((acc, folder) => {
|
||||
const folderName = folder.name.toLowerCase();
|
||||
const folderPath = folder.path.toLowerCase();
|
||||
|
||||
// 检查是否所有关键词都匹配(AND 逻辑)
|
||||
const nameMatches = keywords.every(keyword =>
|
||||
folderName.includes(keyword)
|
||||
);
|
||||
const pathMatches = keywords.every(keyword =>
|
||||
folderPath.includes(keyword)
|
||||
);
|
||||
|
||||
let filteredChildren = [];
|
||||
if (folder.children && folder.children.length > 0) {
|
||||
filteredChildren = filterRecursive(folder.children);
|
||||
}
|
||||
|
||||
// 如果文件夹名称匹配,或者路径匹配,或者有子文件夹匹配,则包含此文件夹
|
||||
if (nameMatches || pathMatches || filteredChildren.length > 0) {
|
||||
acc.push({
|
||||
...folder,
|
||||
children: filteredChildren
|
||||
});
|
||||
|
||||
// 记录需要展开的路径
|
||||
if (filteredChildren.length > 0) {
|
||||
pathsToExpand.push(folder.path);
|
||||
}
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, []);
|
||||
};
|
||||
|
||||
const result = filterRecursive(folders);
|
||||
|
||||
// 使用 setTimeout 来更新展开状态
|
||||
if (pathsToExpand.length > 0) {
|
||||
setTimeout(() => {
|
||||
setExpandedFolders(prev => {
|
||||
const newSet = new Set(prev);
|
||||
pathsToExpand.forEach(path => newSet.add(path));
|
||||
return newSet;
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [folders, folderSearch]);
|
||||
|
||||
// 点击箭头图标:只展开/折叠,不选中
|
||||
const handleToggleClick = (e, folderPath) => {
|
||||
e.stopPropagation(); // 阻止事件冒泡
|
||||
toggleFolder(folderPath);
|
||||
};
|
||||
|
||||
// 点击文件夹主体:首次选中,再次点击展开/折叠
|
||||
const handleFolderClick = (folder) => {
|
||||
const hasChildren = folder.children && folder.children.length > 0;
|
||||
|
||||
// 如果是第一次点击(未选中),则选中
|
||||
if (selectedFolder !== folder.path) {
|
||||
setSelectedFolder(folder.path);
|
||||
} else if (hasChildren) {
|
||||
// 如果已经选中,且有子文件夹,则展开/折叠
|
||||
toggleFolder(folder.path);
|
||||
}
|
||||
};
|
||||
|
||||
const renderFolderTree = (folders, level = 0) => {
|
||||
return folders.map((folder) => {
|
||||
const isExpanded = expandedFolders.has(folder.path);
|
||||
const hasChildren = folder.children && folder.children.length > 0;
|
||||
const isSelected = selectedFolder === folder.path;
|
||||
|
||||
return (
|
||||
<div key={folder.path}>
|
||||
<div
|
||||
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${isSelected
|
||||
? 'bg-blue-50 dark:bg-blue-900'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
style={{ paddingLeft: `${level * 16 + 12}px` }}
|
||||
onClick={() => handleFolderClick(folder)}
|
||||
>
|
||||
{/* 展开/折叠图标 - 独立点击区域 */}
|
||||
{hasChildren ? (
|
||||
<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={(e) => handleToggleClick(e, folder.path)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-gray-500" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-gray-500" />
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-5 mr-1" />
|
||||
)}
|
||||
|
||||
{/* 文件夹图标 */}
|
||||
<Folder className="w-4 h-4 mr-2 text-gray-500 flex-shrink-0" />
|
||||
|
||||
{/* 文件夹名称 */}
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 truncate flex-1">
|
||||
{folder.name}
|
||||
</span>
|
||||
|
||||
{/* 图片数量 */}
|
||||
<span className="text-xs text-gray-400 ml-2 flex-shrink-0">{folder.image_count}</span>
|
||||
</div>
|
||||
{hasChildren && isExpanded && renderFolderTree(folder.children, level + 1)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full h-full border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex flex-col">
|
||||
{/* Library Management */}
|
||||
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300">素材库</h2>
|
||||
</div>
|
||||
|
||||
{/* Library Selector with Delete Button */}
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<select
|
||||
value={currentLibraryId || ''}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
if (value === '__add__') {
|
||||
setShowAddLibrary(true);
|
||||
} else if (value) {
|
||||
handleLibraryClick(value);
|
||||
}
|
||||
}}
|
||||
disabled={isSwitching}
|
||||
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' }}
|
||||
>
|
||||
{libraries.length === 0 && (
|
||||
<option value="">暂无素材库</option>
|
||||
)}
|
||||
{libraries.map((library) => (
|
||||
<option key={library.id} value={library.id}>
|
||||
{library.name}
|
||||
</option>
|
||||
))}
|
||||
<option value="__add__" style={{ borderTop: '1px solid #ccc' }}>
|
||||
+ 添加新素材库
|
||||
</option>
|
||||
</select>
|
||||
<ChevronDown className="absolute right-2 top-2.5 w-4 h-4 text-gray-400 pointer-events-none" />
|
||||
</div>
|
||||
|
||||
{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="删除当前素材库"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Add Library Form */}
|
||||
{showAddLibrary && (
|
||||
<div className="mt-3 p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">添加素材库</h3>
|
||||
<button
|
||||
onClick={() => setShowAddLibrary(false)}
|
||||
className="p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
|
||||
>
|
||||
<X className="w-4 h-4 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="素材库名称"
|
||||
value={newLibraryName}
|
||||
onChange={(e) => setNewLibraryName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleAddLibrary()}
|
||||
autoFocus
|
||||
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"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="文件夹路径(例如:C:\Users\Pictures)"
|
||||
value={newLibraryPath}
|
||||
onChange={(e) => setNewLibraryPath(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleAddLibrary()}
|
||||
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"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setShowAddLibrary(false)}
|
||||
className="flex-1 px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded text-sm hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
onClick={handleAddLibrary}
|
||||
disabled={isAdding}
|
||||
className="flex-1 px-3 py-1.5 bg-blue-500 text-white rounded text-sm hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isAdding ? '添加中...' : '添加'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Folder Tree */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="mb-3 space-y-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2 top-2 w-4 h-4 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索文件夹(支持多关键词)..."
|
||||
value={localFolderSearch}
|
||||
onChange={(e) => handleFolderSearchChange(e.target.value)}
|
||||
className="w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={isAllExpanded() ? collapseAll : expandAll}
|
||||
className="px-2 py-1.5 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-400 transition-colors"
|
||||
title={isAllExpanded() ? "折叠全部" : "展开全部"}
|
||||
>
|
||||
{isAllExpanded() ? (
|
||||
<ChevronsRight className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronsDown className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
{/* 全部图片选项 */}
|
||||
<div
|
||||
className={`flex items-center px-3 py-2 cursor-pointer rounded-md transition-colors ${selectedFolder === null
|
||||
? 'bg-blue-50 dark:bg-blue-900'
|
||||
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
|
||||
}`}
|
||||
onClick={() => setSelectedFolder(null)}
|
||||
>
|
||||
<div className="w-5 mr-1" />
|
||||
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 font-medium flex-1">
|
||||
全部图片
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400 ml-2">
|
||||
{totalImageCount}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 分隔线 */}
|
||||
{(filteredFolders.length > 0 || folders.length > 0) && (
|
||||
<div className="h-px bg-gray-200 dark:bg-gray-700 my-2" />
|
||||
)}
|
||||
|
||||
{/* 文件夹树 */}
|
||||
{filteredFolders.length > 0 ? (
|
||||
renderFolderTree(filteredFolders)
|
||||
) : folderSearch ? (
|
||||
<div className="text-center py-8 text-gray-400 dark:text-gray-500 text-sm">
|
||||
未找到匹配的文件夹
|
||||
</div>
|
||||
) : folders.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-400 dark:text-gray-500 text-sm">
|
||||
暂无文件夹
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Sidebar;
|
||||
@@ -0,0 +1,388 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
#root {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 暗色主题 - 纯黑灰色调 */
|
||||
.dark {
|
||||
--tw-bg-opacity: 1;
|
||||
}
|
||||
|
||||
/* 背景色 - 纯黑灰 */
|
||||
.dark .bg-gray-900 {
|
||||
background-color: #0a0a0a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-800 {
|
||||
background-color: #252525 !important; /* 侧边栏/顶部 - 稍微亮一些 */
|
||||
}
|
||||
|
||||
.dark .bg-gray-700 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-600 {
|
||||
background-color: #3a3a3a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-500 {
|
||||
background-color: #3a3a3a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-400 {
|
||||
background-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-300 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-200:not(img):not(.image-container) {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-100 {
|
||||
background-color: #1a1a1a !important;
|
||||
}
|
||||
|
||||
.dark .bg-gray-50 {
|
||||
background-color: #1a1a1a !important;
|
||||
}
|
||||
|
||||
.dark .bg-white {
|
||||
background-color: #1a1a1a !important;
|
||||
}
|
||||
|
||||
/* 边框色 - 深灰 */
|
||||
.dark .border-gray-700 {
|
||||
border-color: #333333 !important;
|
||||
}
|
||||
|
||||
.dark .border-gray-600 {
|
||||
border-color: #444444 !important;
|
||||
}
|
||||
|
||||
.dark .border-gray-300 {
|
||||
border-color: #333333 !important;
|
||||
}
|
||||
|
||||
.dark .border-gray-200 {
|
||||
border-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .border-gray-100 {
|
||||
border-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
/* 文字色 - 纯白灰 */
|
||||
.dark .text-gray-900 {
|
||||
color: #f5f5f5 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-700 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-600 {
|
||||
color: #b0b0b0 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-500 {
|
||||
color: #909090 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-400 {
|
||||
color: #707070 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-300 {
|
||||
color: #d0d0d0 !important;
|
||||
}
|
||||
|
||||
.dark .text-white {
|
||||
color: #ffffff !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-800 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-200 {
|
||||
color: #d0d0d0 !important;
|
||||
}
|
||||
|
||||
.dark .text-gray-100 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
/* 透明度覆盖 */
|
||||
.dark .bg-opacity-0 {
|
||||
--tw-bg-opacity: 0 !important;
|
||||
}
|
||||
|
||||
.dark .bg-opacity-10 {
|
||||
--tw-bg-opacity: 0.1 !important;
|
||||
}
|
||||
|
||||
.dark .bg-opacity-20 {
|
||||
--tw-bg-opacity: 0.2 !important;
|
||||
}
|
||||
|
||||
.dark .bg-opacity-30 {
|
||||
--tw-bg-opacity: 0.3 !important;
|
||||
}
|
||||
|
||||
.dark .bg-opacity-50 {
|
||||
--tw-bg-opacity: 0.5 !important;
|
||||
}
|
||||
|
||||
/* 悬停效果 - 深灰 */
|
||||
.dark .hover\:bg-gray-100:hover {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-gray-700:hover {
|
||||
background-color: #333333 !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-gray-600:hover {
|
||||
background-color: #3a3a3a !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-gray-200:hover {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-gray-50:hover {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
/* 黑色相关 - 但不影响透明遮罩 */
|
||||
.dark .bg-black:not(.bg-opacity-0):not(.bg-opacity-10):not(.bg-opacity-20):not(.bg-opacity-30) {
|
||||
background-color: #0a0a0a !important;
|
||||
}
|
||||
|
||||
.dark .text-black {
|
||||
color: #ffffff !important;
|
||||
}
|
||||
|
||||
.dark .border-black {
|
||||
border-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
/* 移除所有颜色调,统一为黑灰 */
|
||||
|
||||
/* 蓝色系 -> 黑灰 */
|
||||
.dark .bg-blue-50 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-100 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-200 {
|
||||
background-color: #3a3a3a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-500 {
|
||||
background-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-600 {
|
||||
background-color: #3a3a3a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-800 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-900 {
|
||||
background-color: #1a1a1a !important;
|
||||
}
|
||||
|
||||
.dark .text-blue-300 {
|
||||
color: #d0d0d0 !important;
|
||||
}
|
||||
|
||||
.dark .text-blue-400 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark .text-blue-500 {
|
||||
color: #f0f0f0 !important;
|
||||
}
|
||||
|
||||
.dark .text-blue-600 {
|
||||
color: #f0f0f0 !important;
|
||||
}
|
||||
|
||||
.dark .text-blue-700 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark .border-blue-200 {
|
||||
border-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .border-blue-500 {
|
||||
border-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .border-blue-700 {
|
||||
border-color: #333333 !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-blue-600:hover {
|
||||
background-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-blue-50:hover {
|
||||
background-color: #333333 !important;
|
||||
}
|
||||
|
||||
/* 绿色系 -> 黑灰 */
|
||||
.dark .bg-green-50 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .text-green-600 {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
/* 红色系 -> 黑灰 */
|
||||
.dark .bg-red-50 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .text-red-600 {
|
||||
color: #f0a0a0 !important;
|
||||
}
|
||||
|
||||
/* 黄色系 -> 黑灰 */
|
||||
.dark .bg-yellow-50 {
|
||||
background-color: #2a2a2a !important;
|
||||
}
|
||||
|
||||
.dark .text-yellow-600 {
|
||||
color: #e0e0a0 !important;
|
||||
}
|
||||
|
||||
/* 图片容器不要覆盖 */
|
||||
.dark img {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
/* 输入框和选择框 */
|
||||
.dark input,
|
||||
.dark select,
|
||||
.dark textarea {
|
||||
background-color: #1a1a1a !important;
|
||||
border-color: #333333 !important;
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark input:focus,
|
||||
.dark select:focus,
|
||||
.dark textarea:focus {
|
||||
border-color: #4a4a4a !important;
|
||||
outline: none !important;
|
||||
--tw-ring-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark input::placeholder {
|
||||
color: #707070 !important;
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.dark button {
|
||||
color: #e0e0e0 !important;
|
||||
}
|
||||
|
||||
.dark .bg-blue-500 {
|
||||
background-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .hover\:bg-blue-600:hover {
|
||||
background-color: #5a5a5a !important;
|
||||
}
|
||||
|
||||
/* 阴影 */
|
||||
.dark .shadow-lg {
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3) !important;
|
||||
}
|
||||
|
||||
.dark .shadow-xl {
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.3) !important;
|
||||
}
|
||||
|
||||
.dark .hover\:shadow-lg:hover {
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5), 0 4px 6px -2px rgba(0, 0, 0, 0.3) !important;
|
||||
}
|
||||
|
||||
/* Ring (focus outline) */
|
||||
.dark .ring-blue-500 {
|
||||
--tw-ring-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .focus\:ring-blue-500:focus {
|
||||
--tw-ring-color: #4a4a4a !important;
|
||||
}
|
||||
|
||||
.dark .focus\:ring-2:focus {
|
||||
--tw-ring-offset-shadow: 0 0 0 0px #000 !important;
|
||||
--tw-ring-shadow: 0 0 0 2px #4a4a4a !important;
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
/* 亮色主题滚动条 */
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
/* 暗色主题滚动条 */
|
||||
.dark ::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE = '/api';
|
||||
|
||||
// Library API
|
||||
export const libraryAPI = {
|
||||
getAll: () => axios.get(`${API_BASE}/library`),
|
||||
add: (name, path) => axios.post(`${API_BASE}/library`, { name, path }),
|
||||
update: (id, updates) => axios.put(`${API_BASE}/library/${id}`, updates),
|
||||
delete: (id) => axios.delete(`${API_BASE}/library/${id}`),
|
||||
setCurrent: (id) => axios.post(`${API_BASE}/library/${id}/set-current`),
|
||||
updatePreferences: (preferences) => axios.put(`${API_BASE}/library/preferences`, preferences),
|
||||
updateTheme: (theme) => axios.put(`${API_BASE}/library/theme`, { theme })
|
||||
};
|
||||
|
||||
// Image API
|
||||
export const imageAPI = {
|
||||
search: (libraryId, params = {}) => {
|
||||
const query = new URLSearchParams({
|
||||
libraryId,
|
||||
...params
|
||||
});
|
||||
return axios.get(`${API_BASE}/image?${query}`);
|
||||
},
|
||||
getCount: (libraryId) => axios.get(`${API_BASE}/image/count?libraryId=${libraryId}`),
|
||||
getFolders: (libraryId) => axios.get(`${API_BASE}/image/folders?libraryId=${libraryId}`),
|
||||
getThumbnailUrl: (libraryId, size, filename) => `${API_BASE}/image/thumbnail/${libraryId}/${size}/${filename}`,
|
||||
getOriginalUrl: (libraryId, path) => `${API_BASE}/image/original/${libraryId}/${path}`,
|
||||
openInExplorer: (libraryId, path) => axios.post(`${API_BASE}/image/${libraryId}/open-file`, { path })
|
||||
};
|
||||
|
||||
// Scan API
|
||||
export const scanAPI = {
|
||||
fullScan: (libraryId, wait = false) => axios.post(`${API_BASE}/scan/full`, { libraryId, wait }),
|
||||
sync: (libraryId, wait = false) => axios.post(`${API_BASE}/scan/sync`, { libraryId, wait }),
|
||||
stop: (libraryId) => axios.post(`${API_BASE}/scan/stop`, { libraryId }),
|
||||
resume: (libraryId) => axios.post(`${API_BASE}/scan/resume`, { libraryId }),
|
||||
getStatus: (libraryId) => axios.get(`${API_BASE}/scan/status/${libraryId}`),
|
||||
fixFolders: (libraryId) => axios.post(`${API_BASE}/scan/fix-folders`, { libraryId })
|
||||
};
|
||||
|
||||
// Watch API
|
||||
export const watchAPI = {
|
||||
start: (libraryId) => axios.post(`${API_BASE}/watch/start/${libraryId}`),
|
||||
stop: (libraryId) => axios.post(`${API_BASE}/watch/stop/${libraryId}`),
|
||||
status: (libraryId) => axios.get(`${API_BASE}/watch/status/${libraryId}`),
|
||||
list: () => axios.get(`${API_BASE}/watch/list`)
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import { create } from 'zustand';
|
||||
|
||||
const useStore = create((set, get) => ({
|
||||
// Theme
|
||||
theme: 'light',
|
||||
setTheme: (theme) => set({ theme }),
|
||||
toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
|
||||
|
||||
// Libraries
|
||||
libraries: [],
|
||||
currentLibraryId: null,
|
||||
setLibraries: (libraries) => set({ libraries }),
|
||||
setCurrentLibrary: (id) => set({ currentLibraryId: id }),
|
||||
addLibrary: (library) => set((state) => ({ libraries: [...state.libraries, library] })),
|
||||
removeLibrary: (id) => set((state) => ({
|
||||
libraries: state.libraries.filter((lib) => lib.id !== id),
|
||||
currentLibraryId: state.currentLibraryId === id ? null : state.currentLibraryId
|
||||
})),
|
||||
|
||||
// Images
|
||||
images: [],
|
||||
filteredImages: [],
|
||||
totalImageCount: 0, // 整个素材库的总图片数
|
||||
setImages: (images) => set({ images, filteredImages: images }),
|
||||
setFilteredImages: (filteredImages) => set({ filteredImages }),
|
||||
setTotalImageCount: (count) => set({ totalImageCount: count }),
|
||||
|
||||
// Folders
|
||||
folders: [],
|
||||
selectedFolder: null,
|
||||
setFolders: (folders) => set({ folders }),
|
||||
setSelectedFolder: (folder) => set({ selectedFolder: folder }),
|
||||
|
||||
// Search and filters
|
||||
searchKeywords: '',
|
||||
filters: {
|
||||
formats: [],
|
||||
minSize: null,
|
||||
maxSize: null,
|
||||
startDate: null,
|
||||
endDate: null
|
||||
},
|
||||
setSearchKeywords: (keywords) => set({ searchKeywords: keywords }),
|
||||
setFilters: (filters) => set((state) => ({ filters: { ...state.filters, ...filters } })),
|
||||
resetFilters: () => set({
|
||||
searchKeywords: '',
|
||||
filters: {
|
||||
formats: [],
|
||||
minSize: null,
|
||||
maxSize: null,
|
||||
startDate: null,
|
||||
endDate: null
|
||||
}
|
||||
}),
|
||||
|
||||
// Selected image (单选)
|
||||
selectedImage: null,
|
||||
setSelectedImage: (image) => set({ selectedImage: image }),
|
||||
|
||||
// Selected images (多选)
|
||||
selectedImages: [],
|
||||
setSelectedImages: (images) => set({ selectedImages: images }),
|
||||
toggleImageSelection: (image) => set((state) => {
|
||||
const isSelected = state.selectedImages.some(img => img.path === image.path);
|
||||
if (isSelected) {
|
||||
return { selectedImages: state.selectedImages.filter(img => img.path !== image.path) };
|
||||
} else {
|
||||
return { selectedImages: [...state.selectedImages, image] };
|
||||
}
|
||||
}),
|
||||
clearSelection: () => set({ selectedImages: [], selectedImage: null }),
|
||||
|
||||
// Scan progress
|
||||
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 };
|
||||
}),
|
||||
|
||||
// Panel resizing state(拖动侧边栏时置为 true,用于抑制重算)
|
||||
isResizingPanels: false,
|
||||
setIsResizingPanels: (value) => set({ isResizingPanels: value }),
|
||||
|
||||
// 正在拖动的侧边:'left' | 'right' | null
|
||||
resizingSide: null,
|
||||
setResizingSide: (side) => set({ resizingSide: side }),
|
||||
|
||||
// Thumbnail size
|
||||
thumbnailHeight: 200,
|
||||
setThumbnailHeight: (height) => set({ thumbnailHeight: height }),
|
||||
|
||||
// Mobile view state
|
||||
mobileView: 'main', // 'sidebar' | 'main' | 'detail'
|
||||
setMobileView: (view) => set({ mobileView: view }),
|
||||
|
||||
// Get current library
|
||||
getCurrentLibrary: () => {
|
||||
const state = get();
|
||||
return state.libraries.find((lib) => lib.id === state.currentLibraryId);
|
||||
}
|
||||
}));
|
||||
|
||||
export default useStore;
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 瀑布流布局计算 Worker
|
||||
* 将耗时的布局计算移到后台线程,避免阻塞主线程
|
||||
*/
|
||||
|
||||
/**
|
||||
* 计算瀑布流布局
|
||||
* @param {Array} images - 图片列表
|
||||
* @param {number} containerWidth - 容器宽度
|
||||
* @param {number} targetHeight - 目标行高
|
||||
* @returns {Array} 计算后的行数组
|
||||
*/
|
||||
function calculateLayout(images, containerWidth, targetHeight) {
|
||||
if (!images.length || !containerWidth) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const gap = 16;
|
||||
const calculatedRows = [];
|
||||
let currentRow = [];
|
||||
let currentRowWidthSum = 0;
|
||||
|
||||
images.forEach((image, index) => {
|
||||
const aspectRatio = image.width / image.height;
|
||||
const imageWidth = targetHeight * aspectRatio;
|
||||
|
||||
// Add to current row
|
||||
currentRow.push({
|
||||
...image,
|
||||
originalWidth: imageWidth,
|
||||
aspectRatio: aspectRatio
|
||||
});
|
||||
currentRowWidthSum += imageWidth;
|
||||
|
||||
// Calculate if current row is ready to be finalized
|
||||
const currentGaps = (currentRow.length - 1) * gap;
|
||||
const totalWidth = currentRowWidthSum + currentGaps;
|
||||
const isLastImage = index === images.length - 1;
|
||||
|
||||
// Decide if we should finish this row
|
||||
let shouldFinishRow = false;
|
||||
|
||||
if (isLastImage) {
|
||||
shouldFinishRow = true;
|
||||
} else if (totalWidth >= containerWidth * 0.95) {
|
||||
shouldFinishRow = true;
|
||||
} else {
|
||||
const nextImage = images[index + 1];
|
||||
if (nextImage) {
|
||||
const nextAspectRatio = nextImage.width / nextImage.height;
|
||||
const nextImageWidth = targetHeight * nextAspectRatio;
|
||||
const nextTotalWidth = currentRowWidthSum + nextImageWidth + (currentRow.length * gap);
|
||||
|
||||
if (nextTotalWidth > containerWidth * 1.2) {
|
||||
shouldFinishRow = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldFinishRow) {
|
||||
const totalGaps = (currentRow.length - 1) * gap;
|
||||
const availableWidth = containerWidth - totalGaps;
|
||||
|
||||
let scale = availableWidth / currentRowWidthSum;
|
||||
|
||||
if (isLastImage && currentRow.length < 3) {
|
||||
scale = Math.min(scale, 1.2);
|
||||
}
|
||||
|
||||
const rowHeight = targetHeight * scale;
|
||||
|
||||
currentRow = currentRow.map(img => ({
|
||||
...img,
|
||||
calculatedWidth: img.originalWidth * scale,
|
||||
calculatedHeight: rowHeight
|
||||
}));
|
||||
|
||||
calculatedRows.push(currentRow);
|
||||
|
||||
currentRow = [];
|
||||
currentRowWidthSum = 0;
|
||||
}
|
||||
});
|
||||
|
||||
return calculatedRows;
|
||||
}
|
||||
|
||||
// 监听主线程消息
|
||||
self.onmessage = function(e) {
|
||||
const { images, containerWidth, targetHeight, requestId } = e.data;
|
||||
|
||||
const startTime = performance.now();
|
||||
const rows = calculateLayout(images, containerWidth, targetHeight);
|
||||
const duration = performance.now() - startTime;
|
||||
|
||||
// 返回结果
|
||||
self.postMessage({
|
||||
rows,
|
||||
requestId,
|
||||
duration,
|
||||
imageCount: images.length,
|
||||
rowCount: rows.length
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
],
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: process.env.VITE_API_URL || 'http://localhost:3000',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
assetsDir: 'assets',
|
||||
emptyOutDir: true
|
||||
}
|
||||
})
|
||||
Generated
+5580
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "flypic-monorepo",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "FlyPic - A lightweight and fast image library manager for fnOS",
|
||||
"workspaces": [
|
||||
"frontend",
|
||||
"backend"
|
||||
],
|
||||
"scripts": {
|
||||
"dev:frontend": "npm --workspace frontend run dev",
|
||||
"dev:backend": "npm --workspace backend run dev",
|
||||
"dev": "npm run dev:backend",
|
||||
"build:fpk": "node scripts/build-fpk.js",
|
||||
"build:fpk:docker": "node scripts/build-fpk-docker.js",
|
||||
"test:docker": "node scripts/test-in-docker.js"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"cross-env": "^7.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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": "5002"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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 文件即可使用');
|
||||
@@ -0,0 +1,132 @@
|
||||
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": "5002"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
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');
|
||||
@@ -0,0 +1,55 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user