重构 更规范性的文件组织
This commit is contained in:
1 parent
59abbf30d9
commit
ea6c87ad25
53 files changed
+3274
-2110
No files matched your search
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* 图片服务层
|
||||
* 封装图片相关的业务逻辑
|
||||
*/
|
||||
|
||||
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
|
||||
const ImageModel = require('../models/ImageModel');
|
||||
const FolderModel = require('../models/FolderModel');
|
||||
|
||||
class ImageService {
|
||||
constructor(configManager, dbPool) {
|
||||
this.configManager = configManager;
|
||||
this.dbPool = dbPool;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索图片
|
||||
*/
|
||||
async searchImages(libraryId, filters = {}, pagination = null) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
return imageModel.search(filters, pagination);
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片详情
|
||||
*/
|
||||
async getImageById(libraryId, imageId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
const image = imageModel.findById(imageId);
|
||||
|
||||
if (!image) {
|
||||
throw new NotFoundError('Image', imageId);
|
||||
}
|
||||
|
||||
return image;
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据路径获取图片
|
||||
*/
|
||||
async getImageByPath(libraryId, imagePath) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
const image = imageModel.findByPath(imagePath);
|
||||
|
||||
if (!image) {
|
||||
throw new NotFoundError('Image', imagePath);
|
||||
}
|
||||
|
||||
return image;
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片总数
|
||||
*/
|
||||
async getImageCount(libraryId, filters = {}) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
return imageModel.count(filters);
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片统计信息
|
||||
*/
|
||||
async getImageStats(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const stats = db.db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(size) as totalSize,
|
||||
AVG(size) as avgSize,
|
||||
MAX(size) as maxSize,
|
||||
MIN(size) as minSize,
|
||||
COUNT(DISTINCT format) as formatCount,
|
||||
COUNT(DISTINCT folder) as folderCount
|
||||
FROM images
|
||||
`).get();
|
||||
|
||||
const formatStats = db.db.prepare(`
|
||||
SELECT format, COUNT(*) as count
|
||||
FROM images
|
||||
GROUP BY format
|
||||
ORDER BY count DESC
|
||||
`).all();
|
||||
|
||||
return {
|
||||
...stats,
|
||||
formats: formatStats
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件夹列表
|
||||
*/
|
||||
async getFolders(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const folderModel = new FolderModel(db.db);
|
||||
return folderModel.getTree();
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存元数据
|
||||
*/
|
||||
async getCacheMeta(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const result = db.db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as totalImages,
|
||||
COUNT(DISTINCT folder) as totalFolders,
|
||||
MAX(indexed_at) as lastIndexed
|
||||
FROM images
|
||||
`).get();
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
...result,
|
||||
dbPath: library.path
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取素材库对象
|
||||
* @private
|
||||
*/
|
||||
_getLibrary(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', libraryId);
|
||||
}
|
||||
|
||||
return library;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ImageService;
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* 素材库服务层
|
||||
* 封装素材库相关的业务逻辑
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
|
||||
const { getFlypicPath, getDatabasePath } = require('../config');
|
||||
|
||||
class LibraryService {
|
||||
constructor(configManager, dbPool, scanManager, lightweightWatcher, io) {
|
||||
this.configManager = configManager;
|
||||
this.dbPool = dbPool;
|
||||
this.scanManager = scanManager;
|
||||
this.lightweightWatcher = lightweightWatcher;
|
||||
this.io = io;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有素材库
|
||||
*/
|
||||
getAllLibraries() {
|
||||
const config = this.configManager.load();
|
||||
return {
|
||||
libraries: config.libraries || [],
|
||||
currentLibraryId: config.currentLibraryId,
|
||||
theme: config.theme || 'light',
|
||||
preferences: config.preferences || {}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新素材库
|
||||
*/
|
||||
async createLibrary(name, libraryPath) {
|
||||
// 验证参数
|
||||
if (!name || !libraryPath) {
|
||||
throw new ValidationError('Name and path are required');
|
||||
}
|
||||
|
||||
if (!fs.existsSync(libraryPath)) {
|
||||
throw new ValidationError('Path does not exist', 'path');
|
||||
}
|
||||
|
||||
// 检查路径是否已存在
|
||||
const config = this.configManager.load();
|
||||
const existingLib = config.libraries.find(lib => lib.path === libraryPath);
|
||||
if (existingLib) {
|
||||
throw new ValidationError('Library path already exists', 'path');
|
||||
}
|
||||
|
||||
// 创建素材库
|
||||
const id = this.configManager.addLibrary(name, libraryPath);
|
||||
|
||||
// 检查是否有现有索引
|
||||
const flypicDir = getFlypicPath(libraryPath);
|
||||
const dbPath = getDatabasePath(libraryPath);
|
||||
const hasExistingIndex = fs.existsSync(flypicDir) && fs.existsSync(dbPath);
|
||||
|
||||
return {
|
||||
id,
|
||||
hasExistingIndex,
|
||||
message: hasExistingIndex
|
||||
? 'Library created with existing index'
|
||||
: 'Library created, please scan to build index'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新素材库
|
||||
*/
|
||||
updateLibrary(id, updates) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === id);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', id);
|
||||
}
|
||||
|
||||
// 验证更新的路径是否存在
|
||||
if (updates.path && !fs.existsSync(updates.path)) {
|
||||
throw new ValidationError('Path does not exist', 'path');
|
||||
}
|
||||
|
||||
const success = this.configManager.updateLibrary(id, updates);
|
||||
return { success };
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除素材库
|
||||
*/
|
||||
async deleteLibrary(id) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === id);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', id);
|
||||
}
|
||||
|
||||
// 清理资源
|
||||
await this._cleanupLibraryResources(id, library.path);
|
||||
|
||||
// 删除配置
|
||||
this.configManager.removeLibrary(id);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
path: library.path,
|
||||
message: 'Library deleted successfully'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置当前素材库
|
||||
*/
|
||||
async setCurrentLibrary(id) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === id);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', id);
|
||||
}
|
||||
|
||||
// 切换前清理旧素材库资源
|
||||
if (config.currentLibraryId && config.currentLibraryId !== id) {
|
||||
const oldLibrary = config.libraries.find(lib => lib.id === config.currentLibraryId);
|
||||
if (oldLibrary) {
|
||||
await this._cleanupLibraryResources(config.currentLibraryId, oldLibrary.path, false);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置新素材库
|
||||
this.configManager.setCurrentLibrary(id);
|
||||
|
||||
// 预热数据库连接
|
||||
try {
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
db.db.prepare('SELECT 1').get();
|
||||
this.dbPool.release(library.path);
|
||||
} catch (e) {
|
||||
// 忽略预热错误
|
||||
}
|
||||
|
||||
// 启动文件监控
|
||||
if (this.lightweightWatcher && this.io) {
|
||||
try {
|
||||
this.lightweightWatcher.watch(id, library.path, library.name, this.io);
|
||||
} catch (e) {
|
||||
console.warn('Failed to start file watcher:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
libraryId: id,
|
||||
message: 'Current library set successfully'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新偏好设置
|
||||
*/
|
||||
updatePreferences(preferences) {
|
||||
this.configManager.updatePreferences(preferences);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新主题
|
||||
*/
|
||||
updateTheme(theme) {
|
||||
if (!['light', 'dark'].includes(theme)) {
|
||||
throw new ValidationError('Invalid theme, must be light or dark', 'theme');
|
||||
}
|
||||
|
||||
this.configManager.updateTheme(theme);
|
||||
return { success: true, theme };
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理素材库资源
|
||||
* @private
|
||||
*/
|
||||
async _cleanupLibraryResources(libraryId, libraryPath, deleteConfig = true) {
|
||||
// 停止扫描
|
||||
if (this.scanManager) {
|
||||
this.scanManager.clearState(libraryId);
|
||||
}
|
||||
|
||||
// 停止文件监控
|
||||
if (this.lightweightWatcher) {
|
||||
this.lightweightWatcher.unwatch(libraryId);
|
||||
}
|
||||
|
||||
// 关闭数据库连接
|
||||
if (this.dbPool) {
|
||||
this.dbPool.close(libraryPath);
|
||||
}
|
||||
|
||||
// 等待资源释放
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取素材库统计信息
|
||||
*/
|
||||
async getLibraryStats(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', libraryId);
|
||||
}
|
||||
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
try {
|
||||
const imageCount = db.db.prepare('SELECT COUNT(*) as count FROM images').get().count;
|
||||
const folderCount = db.db.prepare('SELECT COUNT(*) as count FROM folders').get().count;
|
||||
|
||||
const sizeResult = db.db.prepare('SELECT SUM(size) as totalSize FROM images').get();
|
||||
const totalSize = sizeResult.totalSize || 0;
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
imageCount,
|
||||
folderCount,
|
||||
totalSize,
|
||||
path: library.path,
|
||||
name: library.name
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LibraryService;
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 扫描服务层
|
||||
* 封装扫描相关的业务逻辑
|
||||
*/
|
||||
|
||||
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
|
||||
|
||||
class ScanService {
|
||||
constructor(configManager, dbPool, scanner, scanManager, io) {
|
||||
this.configManager = configManager;
|
||||
this.dbPool = dbPool;
|
||||
this.scanner = scanner;
|
||||
this.scanManager = scanManager;
|
||||
this.io = io;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全量扫描
|
||||
*/
|
||||
async fullScan(libraryId, wait = false) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
// 检查是否已在扫描
|
||||
if (this.scanManager.isScanning(libraryId)) {
|
||||
throw new ValidationError('Scan already in progress', 'libraryId');
|
||||
}
|
||||
|
||||
// 开始扫描
|
||||
if (wait) {
|
||||
// 同步模式:等待扫描完成
|
||||
await this.scanner.scanLibrary(
|
||||
library.path,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan completed',
|
||||
libraryId
|
||||
};
|
||||
} else {
|
||||
// 异步模式:后台扫描
|
||||
this._startAsyncScan(libraryId, library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Scan started',
|
||||
libraryId,
|
||||
async: true
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
this.dbPool.release(library.path);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量同步
|
||||
*/
|
||||
async incrementalSync(libraryId, wait = false) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
// 检查是否已在扫描
|
||||
if (this.scanManager.isScanning(libraryId)) {
|
||||
throw new ValidationError('Scan already in progress', 'libraryId');
|
||||
}
|
||||
|
||||
// 开始增量同步
|
||||
if (wait) {
|
||||
// 同步模式
|
||||
await this.scanner.incrementalSync(
|
||||
library.path,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Sync completed',
|
||||
libraryId
|
||||
};
|
||||
} else {
|
||||
// 异步模式
|
||||
this._startAsyncSync(libraryId, library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Sync started',
|
||||
libraryId,
|
||||
async: true
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
this.dbPool.release(library.path);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
*/
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取扫描状态
|
||||
*/
|
||||
getScanStatus(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const state = this.scanManager.getState(libraryId);
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
isScanning: this.scanManager.isScanning(libraryId),
|
||||
isPaused: this.scanManager.isPaused(libraryId),
|
||||
progress: state?.progress || null,
|
||||
startTime: state?.startTime || null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复文件夹路径
|
||||
*/
|
||||
async fixFolders(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
await this.scanner.fixFolderPaths(library.path, db);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Folders fixed',
|
||||
libraryId
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步扫描
|
||||
* @private
|
||||
*/
|
||||
_startAsyncScan(libraryId, libraryPath, db) {
|
||||
this.scanner.scanLibrary(
|
||||
libraryPath,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
).then(() => {
|
||||
this._emitComplete(libraryId);
|
||||
this.dbPool.release(libraryPath);
|
||||
}).catch((error) => {
|
||||
this._emitError(libraryId, error);
|
||||
this.dbPool.release(libraryPath);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动异步同步
|
||||
* @private
|
||||
*/
|
||||
_startAsyncSync(libraryId, libraryPath, db) {
|
||||
this.scanner.incrementalSync(
|
||||
libraryPath,
|
||||
db,
|
||||
(progress) => this._emitProgress(libraryId, progress)
|
||||
).then(() => {
|
||||
this._emitComplete(libraryId);
|
||||
this.dbPool.release(libraryPath);
|
||||
}).catch((error) => {
|
||||
this._emitError(libraryId, error);
|
||||
this.dbPool.release(libraryPath);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送进度更新
|
||||
* @private
|
||||
*/
|
||||
_emitProgress(libraryId, progress) {
|
||||
if (this.io) {
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取素材库对象
|
||||
* @private
|
||||
*/
|
||||
_getLibrary(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', libraryId);
|
||||
}
|
||||
|
||||
return library;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ScanService;
|
||||
Reference in new issue
Block a user