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

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

No files matched your search

+3 -23
View File
@@ -103,52 +103,32 @@ router.get('/:id', asyncHandler(async (req, res) => {
router.get('/thumbnail/:libraryId/:filename', (req, res) => {
const { libraryId, filename } = req.params;
console.log(`[Thumbnail] ========== NEW REQUEST ==========`);
console.log(`[Thumbnail] LibraryId: ${libraryId}, Filename: ${filename}`);
try {
const config = require('../../utils/config').loadConfig();
console.log(`[Thumbnail] All libraries:`, config.libraries.map(l => ({ id: l.id, type: typeof l.id })));
// 尝试两种方式查找:数字和字符串
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
if (!library) {
library = config.libraries.find(lib => lib.id == libraryId); // 使用 == 宽松比较
library = config.libraries.find(lib => lib.id == libraryId);
}
if (!library) {
console.log(`[Thumbnail] Library not found: ${libraryId} (type: ${typeof libraryId})`);
return res.status(404).send('Library not found');
}
console.log(`[Thumbnail] Library path: ${library.path}`);
// 使用分片结构:取文件名前2个字符作为分片目录
const hash = filename.replace(/\.[^/.]+$/, ''); // 移除扩展名
const hash = filename.replace(/\.[^/.]+$/, '');
const shard = hash.slice(0, 2);
const flypicPath = getFlypicPath(library.path);
const thumbnailPath = path.join(flypicPath, 'thumbnails', shard, filename);
console.log(`[Thumbnail] Hash: ${hash}, Shard: ${shard}`);
console.log(`[Thumbnail] Full path: ${thumbnailPath}`);
console.log(`[Thumbnail] File exists: ${fs.existsSync(thumbnailPath)}`);
if (!fs.existsSync(thumbnailPath)) {
// 列出分片目录的内容
const shardDir = path.join(flypicPath, 'thumbnails', shard);
if (fs.existsSync(shardDir)) {
const files = fs.readdirSync(shardDir);
console.log(`[Thumbnail] Files in shard dir (${shard}):`, files.slice(0, 5));
} else {
console.log(`[Thumbnail] Shard directory does not exist: ${shardDir}`);
}
return res.status(404).send('Thumbnail not found');
}
console.log(`[Thumbnail] ✅ Serving file`);
res.sendFile(thumbnailPath);
} catch (error) {
console.error('[Thumbnail] Error:', error);
console.error('❌ 缩略图错误:', error.message);
res.status(500).send('Error serving thumbnail');
}
});
+9 -28
View File
@@ -46,34 +46,6 @@ router.post('/sync',
})
);
/**
* 停止扫描
* POST /api/scan/stop
* Body: { libraryId }
*/
router.post('/stop',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId } = req.body;
const result = scanService.stopScan(libraryId);
res.json({ success: true, data: result });
})
);
/**
* 继续扫描
* POST /api/scan/resume
* Body: { libraryId }
*/
router.post('/resume',
validateRequired(['libraryId']),
asyncHandler(async (req, res) => {
const { libraryId } = req.body;
const result = scanService.resumeScan(libraryId);
res.json({ success: true, data: result });
})
);
/**
* 获取扫描状态
* GET /api/scan/status/:libraryId
@@ -84,6 +56,15 @@ router.get('/status/:libraryId', asyncHandler(async (req, res) => {
res.json({ success: true, data: result });
}));
/**
* 获取所有活跃的扫描状态
* GET /api/scan/active-states
*/
router.get('/active-states', asyncHandler(async (req, res) => {
const result = scanService.getAllActiveStates();
res.json({ success: true, data: result });
}));
/**
* 修复文件夹路径
* POST /api/scan/fix-folders
+42 -5
View File
@@ -39,23 +39,60 @@ class LibraryService {
throw new ValidationError('Name and path are required');
}
if (!fs.existsSync(libraryPath)) {
// 规范化路径
const normalizedPath = path.normalize(libraryPath);
console.log(`[LibraryService] Creating library: name=${name}, path=${normalizedPath}`);
if (!fs.existsSync(normalizedPath)) {
console.log(`[LibraryService] Path does not exist: ${normalizedPath}`);
throw new ValidationError('Path does not exist', 'path');
}
// 检查文件夹访问权限
try {
// 尝试读取目录
fs.readdirSync(normalizedPath);
// 尝试在目录中创建测试文件(检查写权限)
const testFile = path.join(normalizedPath, '.flypic-test');
try {
fs.writeFileSync(testFile, 'test');
fs.unlinkSync(testFile);
} catch (writeError) {
console.log(`[LibraryService] No write permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
} catch (readError) {
if (readError.code === 'EACCES' || readError.code === 'EPERM') {
console.log(`[LibraryService] No access permission: ${normalizedPath}`);
throw new ValidationError(
'无法访问该文件夹。请在飞牛 fnOS 的"数据共享"中将此文件夹添加到 FlyPic 应用的访问权限。',
'permission'
);
}
// 如果不是权限错误,继续抛出
if (readError.name !== 'ValidationError') {
throw readError;
}
throw readError;
}
// 检查路径是否已存在
const config = this.configManager.load();
const existingLib = config.libraries.find(lib => lib.path === libraryPath);
const existingLib = config.libraries.find(lib => lib.path === normalizedPath);
if (existingLib) {
throw new ValidationError('Library path already exists', 'path');
}
// 创建素材库
const id = this.configManager.addLibrary(name, libraryPath);
const id = this.configManager.addLibrary(name, normalizedPath);
// 检查是否有现有索引
const flypicDir = getFlypicPath(libraryPath);
const dbPath = getDatabasePath(libraryPath);
const flypicDir = getFlypicPath(normalizedPath);
const dbPath = getDatabasePath(normalizedPath);
const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath);
return {
+25 -114
View File
@@ -1,6 +1,6 @@
/**
* 扫描服务层
* 封装扫描相关的业务逻辑
* 扫描服务层(简化版)
* 无暂停功能,只负责扫描和进度推送
*/
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
@@ -22,35 +22,21 @@ class ScanService {
const db = this.dbPool.acquire(library.path);
try {
// 检查是否已在扫描
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
// 开始扫描
if (wait) {
// 同步模式:等待扫描完成
await this.scanner.scanLibrary(
library.path,
db,
(progress) => this._emitProgress(libraryId, progress)
);
return {
success: true,
message: 'Scan completed',
(progress) => this._emitProgress(libraryId, progress),
libraryId
};
);
return { success: true, message: 'Scan completed', libraryId };
} else {
// 异步模式:后台扫描
this._startAsyncScan(libraryId, library.path, db);
return {
success: true,
message: 'Scan started',
libraryId,
async: true
};
return { success: true, message: 'Scan started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
@@ -66,35 +52,21 @@ class ScanService {
const db = this.dbPool.acquire(library.path);
try {
// 检查是否已在扫描
if (this.scanManager.isScanning(libraryId)) {
throw new ValidationError('Scan already in progress', 'libraryId');
}
// 开始增量同步
if (wait) {
// 同步模式
await this.scanner.incrementalSync(
await this.scanner.syncLibrary(
library.path,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
);
return {
success: true,
message: 'Sync completed',
libraryId
};
return { success: true, message: 'Sync completed', libraryId };
} else {
// 异步模式
this._startAsyncSync(libraryId, library.path, db);
return {
success: true,
message: 'Sync started',
libraryId,
async: true
};
return { success: true, message: 'Sync started', libraryId, async: true };
}
} catch (error) {
this.dbPool.release(library.path);
@@ -102,44 +74,6 @@ class ScanService {
}
}
/**
* 停止扫描
*/
stopScan(libraryId) {
const library = this._getLibrary(libraryId);
if (!this.scanManager.isScanning(libraryId)) {
throw new ValidationError('No scan in progress', 'libraryId');
}
this.scanManager.pauseScan(libraryId);
return {
success: true,
message: 'Scan stopped',
libraryId
};
}
/**
* 继续扫描
*/
resumeScan(libraryId) {
const library = this._getLibrary(libraryId);
if (!this.scanManager.isPaused(libraryId)) {
throw new ValidationError('No paused scan found', 'libraryId');
}
this.scanManager.resumeScan(libraryId);
return {
success: true,
message: 'Scan resumed',
libraryId
};
}
/**
* 获取扫描状态
*/
@@ -149,13 +83,19 @@ class ScanService {
return {
libraryId,
isScanning: this.scanManager.isScanning(libraryId),
isPaused: this.scanManager.isPaused(libraryId),
status: state?.status || 'idle',
progress: state?.progress || null,
startTime: state?.startTime || null
};
}
/**
* 获取所有活跃状态
*/
getAllActiveStates() {
return this.scanManager.getAllActiveStates();
}
/**
* 修复文件夹路径
*/
@@ -165,12 +105,7 @@ class ScanService {
try {
await this.scanner.fixFolderPaths(library.path, db);
return {
success: true,
message: 'Folders fixed',
libraryId
};
return { success: true, message: 'Folders fixed', libraryId };
} finally {
this.dbPool.release(library.path);
}
@@ -178,13 +113,13 @@ class ScanService {
/**
* 启动异步扫描
* @private
*/
_startAsyncScan(libraryId, libraryPath, db) {
this.scanner.scanLibrary(
libraryPath,
db,
(progress) => this._emitProgress(libraryId, progress)
(progress) => this._emitProgress(libraryId, progress),
libraryId
).then(() => {
this._emitComplete(libraryId);
this.dbPool.release(libraryPath);
@@ -196,12 +131,12 @@ class ScanService {
/**
* 启动异步同步
* @private
*/
_startAsyncSync(libraryId, libraryPath, db) {
this.scanner.incrementalSync(
this.scanner.syncLibrary(
libraryPath,
db,
false,
(progress) => this._emitProgress(libraryId, progress)
).then(() => {
this._emitComplete(libraryId);
@@ -212,54 +147,30 @@ class ScanService {
});
}
/**
* 发送进度更新
* @private
*/
_emitProgress(libraryId, progress) {
if (this.io) {
this.io.emit('scanProgress', {
libraryId,
...progress
});
this.io.emit('scanProgress', { libraryId, ...progress });
}
}
/**
* 发送完成事件
* @private
*/
_emitComplete(libraryId) {
if (this.io) {
this.io.emit('scanComplete', { libraryId });
}
}
/**
* 发送错误事件
* @private
*/
_emitError(libraryId, error) {
if (this.io) {
this.io.emit('scanError', {
libraryId,
error: error.message
});
this.io.emit('scanError', { libraryId, error: error.message });
}
}
/**
* 获取素材库对象
* @private
*/
_getLibrary(libraryId) {
const config = this.configManager.load();
const library = config.libraries.find(lib => lib.id === libraryId);
if (!library) {
throw new NotFoundError('Library', libraryId);
}
return library;
}
}