重构 更规范性的文件组织
This commit is contained in:
1 parent
59abbf30d9
commit
ea6c87ad25
53 files changed
+3274
-2110
No files matched your search
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Express 应用配置
|
||||
* 使用新的架构:Config → Model → Service → Route
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const { errorHandler } = require('./middleware/errorHandler');
|
||||
|
||||
// 导入服务
|
||||
const LibraryService = require('./services/LibraryService');
|
||||
const ImageService = require('./services/ImageService');
|
||||
const ScanService = require('./services/ScanService');
|
||||
|
||||
/**
|
||||
* 创建 Express 应用
|
||||
*/
|
||||
function createApp(dependencies) {
|
||||
const {
|
||||
configManager,
|
||||
dbPool,
|
||||
scanner,
|
||||
scanManager,
|
||||
lightweightWatcher,
|
||||
io
|
||||
} = dependencies;
|
||||
|
||||
const app = express();
|
||||
|
||||
// 中间件
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// 初始化服务
|
||||
const libraryService = new LibraryService(
|
||||
configManager,
|
||||
dbPool,
|
||||
scanManager,
|
||||
lightweightWatcher,
|
||||
io
|
||||
);
|
||||
|
||||
const imageService = new ImageService(
|
||||
configManager,
|
||||
dbPool
|
||||
);
|
||||
|
||||
const scanService = new ScanService(
|
||||
configManager,
|
||||
dbPool,
|
||||
scanner,
|
||||
scanManager,
|
||||
io
|
||||
);
|
||||
|
||||
// 将服务注入到 app 中,供路由使用
|
||||
app.set('libraryService', libraryService);
|
||||
app.set('imageService', imageService);
|
||||
app.set('scanService', scanService);
|
||||
|
||||
// API 路由
|
||||
const libraryRouter = require('./routes/library');
|
||||
const imageRouter = require('./routes/image');
|
||||
const scanRouter = require('./routes/scan');
|
||||
|
||||
app.use('/api/library', libraryRouter);
|
||||
app.use('/api/image', imageRouter);
|
||||
app.use('/api/scan', scanRouter);
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({
|
||||
success: true,
|
||||
status: 'ok',
|
||||
timestamp: Date.now()
|
||||
});
|
||||
});
|
||||
|
||||
// 静态文件服务(前端)
|
||||
const FRONTEND_DIST = process.env.FRONTEND_DIST;
|
||||
if (FRONTEND_DIST) {
|
||||
app.use(express.static(FRONTEND_DIST));
|
||||
app.get('*', (req, res) => {
|
||||
res.sendFile(path.join(FRONTEND_DIST, 'index.html'));
|
||||
});
|
||||
}
|
||||
|
||||
// 错误处理中间件(必须放在最后)
|
||||
app.use(errorHandler);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
module.exports = { createApp };
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 应用常量配置
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
// 支持的图片格式
|
||||
SUPPORTED_FORMATS: ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'tiff'],
|
||||
|
||||
// 缩略图配置
|
||||
THUMBNAIL: {
|
||||
SIZES: {
|
||||
SMALL: 200,
|
||||
MEDIUM: 480,
|
||||
LARGE: 800
|
||||
},
|
||||
QUALITY: 80,
|
||||
FORMAT: 'webp',
|
||||
SHARD_LENGTH: 2 // 分片目录长度
|
||||
},
|
||||
|
||||
// 分页配置
|
||||
PAGINATION: {
|
||||
DEFAULT_SIZE: 100,
|
||||
MAX_SIZE: 500
|
||||
},
|
||||
|
||||
// 扫描配置
|
||||
SCAN: {
|
||||
BATCH_SIZE: 50,
|
||||
CONCURRENT_LIMIT: 10,
|
||||
PROGRESS_UPDATE_INTERVAL: 100
|
||||
},
|
||||
|
||||
// 内存配置
|
||||
MEMORY: {
|
||||
WARNING_THRESHOLD_MB: 200,
|
||||
DANGER_THRESHOLD_MB: 300,
|
||||
CACHE_SIZE_KB: 4096,
|
||||
CLEANUP_INTERVAL_MS: 60000,
|
||||
DB_IDLE_TIMEOUT_MS: 300000
|
||||
},
|
||||
|
||||
// 数据库配置
|
||||
DATABASE: {
|
||||
PRAGMA: {
|
||||
journal_mode: 'DELETE',
|
||||
synchronous: 'NORMAL',
|
||||
cache_size: -4096,
|
||||
temp_store: 'FILE',
|
||||
page_size: 4096,
|
||||
mmap_size: 0
|
||||
}
|
||||
},
|
||||
|
||||
// 路径配置
|
||||
PATHS: {
|
||||
FLYPIC_DIR: '.flypic',
|
||||
THUMBNAILS_DIR: 'thumbnails',
|
||||
DATABASE_FILE: 'metadata.db',
|
||||
CONFIG_FILE: 'config.json'
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 配置管理入口
|
||||
*/
|
||||
|
||||
const constants = require('./constants');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* 获取 FlyPic 目录路径
|
||||
*/
|
||||
function getFlypicPath(libraryPath) {
|
||||
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缩略图目录路径
|
||||
*/
|
||||
function getThumbnailsPath(libraryPath) {
|
||||
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.THUMBNAILS_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据库文件路径
|
||||
*/
|
||||
function getDatabasePath(libraryPath) {
|
||||
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.DATABASE_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配置文件路径
|
||||
*/
|
||||
function getConfigPath(libraryPath) {
|
||||
return path.join(libraryPath, constants.PATHS.FLYPIC_DIR, constants.PATHS.CONFIG_FILE);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
constants,
|
||||
getFlypicPath,
|
||||
getThumbnailsPath,
|
||||
getDatabasePath,
|
||||
getConfigPath
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* 统一错误处理中间件
|
||||
*/
|
||||
|
||||
/**
|
||||
* 应用错误类
|
||||
*/
|
||||
class AppError extends Error {
|
||||
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
this.code = code;
|
||||
this.isOperational = true;
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证错误
|
||||
*/
|
||||
class ValidationError extends AppError {
|
||||
constructor(message, field = null) {
|
||||
super(message, 400, 'VALIDATION_ERROR');
|
||||
this.field = field;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源未找到错误
|
||||
*/
|
||||
class NotFoundError extends AppError {
|
||||
constructor(resource, id = null) {
|
||||
super(
|
||||
`${resource} not found${id ? `: ${id}` : ''}`,
|
||||
404,
|
||||
'NOT_FOUND'
|
||||
);
|
||||
this.resource = resource;
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 冲突错误
|
||||
*/
|
||||
class ConflictError extends AppError {
|
||||
constructor(message) {
|
||||
super(message, 409, 'CONFLICT');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 错误处理中间件
|
||||
*/
|
||||
const errorHandler = (err, req, res, next) => {
|
||||
// 操作性错误(预期的错误)
|
||||
if (err.isOperational) {
|
||||
return res.status(err.statusCode).json({
|
||||
success: false,
|
||||
error: {
|
||||
code: err.code,
|
||||
message: err.message,
|
||||
...(err.field && { field: err.field })
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 编程错误(未预期的错误)
|
||||
console.error('💥 Unexpected Error:', err);
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: process.env.NODE_ENV === 'development'
|
||||
? err.message
|
||||
: 'Internal server error',
|
||||
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 异步路由处理器包装
|
||||
*/
|
||||
const asyncHandler = (fn) => (req, res, next) => {
|
||||
Promise.resolve(fn(req, res, next)).catch(next);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
AppError,
|
||||
ValidationError,
|
||||
NotFoundError,
|
||||
ConflictError,
|
||||
errorHandler,
|
||||
asyncHandler
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 请求参数验证中间件
|
||||
*/
|
||||
|
||||
const { ValidationError } = require('./errorHandler');
|
||||
|
||||
/**
|
||||
* 验证必需参数
|
||||
*/
|
||||
function validateRequired(fields) {
|
||||
return (req, res, next) => {
|
||||
const source = req.method === 'GET' ? req.query : req.body;
|
||||
|
||||
for (const field of fields) {
|
||||
if (!source[field]) {
|
||||
return next(new ValidationError(`${field} is required`, field));
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证素材库 ID
|
||||
*/
|
||||
function validateLibraryId(req, res, next) {
|
||||
const libraryId = req.params.id || req.query.libraryId || req.body.libraryId;
|
||||
|
||||
if (!libraryId) {
|
||||
return next(new ValidationError('Library ID is required', 'libraryId'));
|
||||
}
|
||||
|
||||
req.libraryId = libraryId;
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证分页参数
|
||||
*/
|
||||
function validatePagination(req, res, next) {
|
||||
const { offset, limit } = req.query;
|
||||
|
||||
if (offset !== undefined) {
|
||||
const offsetNum = parseInt(offset, 10);
|
||||
if (isNaN(offsetNum) || offsetNum < 0) {
|
||||
return next(new ValidationError('Invalid offset', 'offset'));
|
||||
}
|
||||
req.pagination = { offset: offsetNum };
|
||||
}
|
||||
|
||||
if (limit !== undefined) {
|
||||
const limitNum = parseInt(limit, 10);
|
||||
if (isNaN(limitNum) || limitNum < 1 || limitNum > 500) {
|
||||
return next(new ValidationError('Invalid limit (1-500)', 'limit'));
|
||||
}
|
||||
req.pagination = { ...req.pagination, limit: limitNum };
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validateRequired,
|
||||
validateLibraryId,
|
||||
validatePagination
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* 基础数据模型
|
||||
* 提供通用的数据库操作方法
|
||||
*/
|
||||
|
||||
class BaseModel {
|
||||
constructor(db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行查询并返回单条记录
|
||||
*/
|
||||
findOne(query, params = []) {
|
||||
const stmt = this.db.prepare(query);
|
||||
return stmt.get(...params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行查询并返回多条记录
|
||||
*/
|
||||
findMany(query, params = []) {
|
||||
const stmt = this.db.prepare(query);
|
||||
return stmt.all(...params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行插入/更新/删除操作
|
||||
*/
|
||||
execute(query, params = []) {
|
||||
const stmt = this.db.prepare(query);
|
||||
return stmt.run(...params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行事务
|
||||
*/
|
||||
transaction(fn) {
|
||||
const transaction = this.db.transaction(fn);
|
||||
return transaction();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BaseModel;
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 文件夹数据模型
|
||||
*/
|
||||
|
||||
const BaseModel = require('./BaseModel');
|
||||
const { mapFolderForFrontend } = require('../utils/fieldMapper');
|
||||
|
||||
class FolderModel extends BaseModel {
|
||||
/**
|
||||
* 根据路径查找文件夹
|
||||
*/
|
||||
findByPath(path) {
|
||||
const query = 'SELECT * FROM folders WHERE path = ?';
|
||||
const folder = this.findOne(query, [path]);
|
||||
return folder ? mapFolderForFrontend(folder) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有文件夹
|
||||
*/
|
||||
findAll() {
|
||||
const query = 'SELECT * FROM folders ORDER BY path';
|
||||
return this.findMany(query).map(mapFolderForFrontend);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件夹树
|
||||
*/
|
||||
getTree() {
|
||||
const folders = this.findAll();
|
||||
return this._buildTree(folders);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入文件夹
|
||||
*/
|
||||
insert(data) {
|
||||
const query = `
|
||||
INSERT OR REPLACE INTO folders
|
||||
(path, parent_path, name, image_count, last_scan)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
return this.execute(query, [
|
||||
data.path,
|
||||
data.parentPath || '',
|
||||
data.name,
|
||||
data.imageCount || 0,
|
||||
data.lastScan || Date.now()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新文件夹图片数量
|
||||
*/
|
||||
updateImageCount(path) {
|
||||
const query = `
|
||||
UPDATE folders
|
||||
SET image_count = (
|
||||
SELECT COUNT(*) FROM images
|
||||
WHERE folder = ? OR folder LIKE ?
|
||||
)
|
||||
WHERE path = ?
|
||||
`;
|
||||
return this.execute(query, [path, `${path}/%`, path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件夹
|
||||
*/
|
||||
deleteByPath(path) {
|
||||
const query = 'DELETE FROM folders WHERE path = ?';
|
||||
return this.execute(query, [path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按前缀批量删除
|
||||
*/
|
||||
deleteByPrefix(prefix) {
|
||||
const query = 'DELETE FROM folders WHERE path = ? OR path LIKE ?';
|
||||
return this.execute(query, [prefix, `${prefix}/%`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建文件夹树
|
||||
*/
|
||||
_buildTree(folders) {
|
||||
const folderMap = new Map();
|
||||
const rootFolders = [];
|
||||
|
||||
// 第一遍:创建映射
|
||||
folders.forEach(folder => {
|
||||
folderMap.set(folder.path, { ...folder, children: [] });
|
||||
});
|
||||
|
||||
// 第二遍:构建树结构
|
||||
folders.forEach(folder => {
|
||||
const node = folderMap.get(folder.path);
|
||||
if (!folder.parentPath || folder.parentPath === '') {
|
||||
rootFolders.push(node);
|
||||
} else {
|
||||
const parent = folderMap.get(folder.parentPath);
|
||||
if (parent) {
|
||||
parent.children.push(node);
|
||||
} else {
|
||||
rootFolders.push(node);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return rootFolders;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FolderModel;
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* 图片数据模型
|
||||
*/
|
||||
|
||||
const BaseModel = require('./BaseModel');
|
||||
const { mapImageForFrontend } = require('../utils/fieldMapper');
|
||||
|
||||
class ImageModel extends BaseModel {
|
||||
/**
|
||||
* 根据 ID 查找图片
|
||||
*/
|
||||
findById(id) {
|
||||
const query = 'SELECT * FROM images WHERE id = ?';
|
||||
const image = this.findOne(query, [id]);
|
||||
return image ? mapImageForFrontend(image) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据路径查找图片
|
||||
*/
|
||||
findByPath(path) {
|
||||
const query = 'SELECT * FROM images WHERE path = ?';
|
||||
const image = this.findOne(query, [path]);
|
||||
return image ? mapImageForFrontend(image) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索图片(支持分页)
|
||||
*/
|
||||
search(filters = {}, pagination = null) {
|
||||
const { query, params } = this._buildSearchQuery(filters, pagination);
|
||||
|
||||
// 获取总数(不包含分页参数)
|
||||
const { query: countQueryBase, params: countParams } = this._buildSearchQuery(filters, null);
|
||||
const countQuery = countQueryBase
|
||||
.replace('SELECT *', 'SELECT COUNT(*) as total')
|
||||
.split('ORDER BY')[0];
|
||||
const { total } = this.findOne(countQuery, countParams);
|
||||
|
||||
// 获取数据
|
||||
const images = this.findMany(query, params).map(mapImageForFrontend);
|
||||
|
||||
// 统一返回对象格式
|
||||
if (pagination) {
|
||||
return {
|
||||
images,
|
||||
total,
|
||||
offset: pagination.offset,
|
||||
limit: pagination.limit,
|
||||
hasMore: pagination.offset + images.length < total
|
||||
};
|
||||
}
|
||||
|
||||
// 无分页时也返回对象格式
|
||||
return {
|
||||
images,
|
||||
total
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入图片
|
||||
*/
|
||||
insert(data) {
|
||||
const query = `
|
||||
INSERT OR REPLACE INTO images
|
||||
(path, filename, folder, size, width, height, format, file_type,
|
||||
created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
return this.execute(query, [
|
||||
data.path,
|
||||
data.filename,
|
||||
data.folder,
|
||||
data.size,
|
||||
data.width,
|
||||
data.height,
|
||||
data.format,
|
||||
data.fileType || 'image',
|
||||
data.createdAt,
|
||||
data.modifiedAt,
|
||||
data.fileHash,
|
||||
data.thumbnailPath,
|
||||
data.thumbnailSize,
|
||||
Date.now()
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入图片
|
||||
*/
|
||||
insertBatch(images) {
|
||||
const query = `
|
||||
INSERT OR REPLACE INTO images
|
||||
(path, filename, folder, size, width, height, format, file_type,
|
||||
created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
return this.transaction(() => {
|
||||
const stmt = this.db.prepare(query);
|
||||
for (const data of images) {
|
||||
stmt.run(
|
||||
data.path, data.filename, data.folder, data.size,
|
||||
data.width, data.height, data.format, data.fileType || 'image',
|
||||
data.createdAt, data.modifiedAt, data.fileHash,
|
||||
data.thumbnailPath, data.thumbnailSize, Date.now()
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新图片
|
||||
*/
|
||||
update(path, data) {
|
||||
const fields = [];
|
||||
const params = [];
|
||||
|
||||
Object.entries(data).forEach(([key, value]) => {
|
||||
fields.push(`${key} = ?`);
|
||||
params.push(value);
|
||||
});
|
||||
|
||||
params.push(path);
|
||||
|
||||
const query = `UPDATE images SET ${fields.join(', ')} WHERE path = ?`;
|
||||
return this.execute(query, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除图片
|
||||
*/
|
||||
deleteByPath(path) {
|
||||
const query = 'DELETE FROM images WHERE path = ?';
|
||||
return this.execute(query, [path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按文件夹前缀批量删除
|
||||
*/
|
||||
deleteByFolderPrefix(folderPrefix) {
|
||||
const query = 'DELETE FROM images WHERE folder = ? OR folder LIKE ?';
|
||||
return this.execute(query, [folderPrefix, `${folderPrefix}/%`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片总数
|
||||
*/
|
||||
count(filters = {}) {
|
||||
const { query, params } = this._buildSearchQuery(filters);
|
||||
const countQuery = query
|
||||
.replace('SELECT *', 'SELECT COUNT(*) as count')
|
||||
.split('ORDER BY')[0];
|
||||
const { count } = this.findOne(countQuery, params);
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建搜索查询
|
||||
*/
|
||||
_buildSearchQuery(filters = {}, pagination = null) {
|
||||
let query = 'SELECT * FROM images WHERE 1=1';
|
||||
const params = [];
|
||||
|
||||
// 关键词搜索(AND 逻辑)
|
||||
if (filters.keywords) {
|
||||
const terms = filters.keywords.trim().split(/\s+/);
|
||||
terms.forEach(term => {
|
||||
query += ' AND filename LIKE ?';
|
||||
params.push(`%${term}%`);
|
||||
});
|
||||
}
|
||||
|
||||
// 文件夹过滤(包含子文件夹)
|
||||
if (filters.folder) {
|
||||
query += ' AND (folder = ? OR folder LIKE ?)';
|
||||
params.push(filters.folder, `${filters.folder}/%`);
|
||||
}
|
||||
|
||||
// 格式过滤
|
||||
if (filters.formats && filters.formats.length > 0) {
|
||||
const placeholders = filters.formats.map(() => '?').join(',');
|
||||
query += ` AND format IN (${placeholders})`;
|
||||
params.push(...filters.formats);
|
||||
}
|
||||
|
||||
// 大小过滤
|
||||
if (filters.minSize) {
|
||||
query += ' AND size >= ?';
|
||||
params.push(filters.minSize);
|
||||
}
|
||||
if (filters.maxSize) {
|
||||
query += ' AND size <= ?';
|
||||
params.push(filters.maxSize);
|
||||
}
|
||||
|
||||
// 日期过滤
|
||||
if (filters.startDate) {
|
||||
query += ' AND created_at >= ?';
|
||||
params.push(filters.startDate);
|
||||
}
|
||||
if (filters.endDate) {
|
||||
query += ' AND created_at <= ?';
|
||||
params.push(filters.endDate);
|
||||
}
|
||||
|
||||
// 排序
|
||||
query += ' ORDER BY created_at DESC';
|
||||
|
||||
// 分页
|
||||
if (pagination) {
|
||||
query += ' LIMIT ? OFFSET ?';
|
||||
params.push(pagination.limit, pagination.offset);
|
||||
}
|
||||
|
||||
return { query, params };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ImageModel;
|
||||
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* 图片路由(新架构)
|
||||
* 薄层路由,业务逻辑在 Service 层
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { asyncHandler } = require('../middleware/errorHandler');
|
||||
const { validatePagination } = require('../middleware/validator');
|
||||
const { getFlypicPath } = require('../config');
|
||||
|
||||
// 服务实例(从 app 中获取)
|
||||
let imageService;
|
||||
|
||||
router.use((req, res, next) => {
|
||||
if (!imageService) {
|
||||
imageService = req.app.get('imageService');
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
/**
|
||||
* 搜索图片
|
||||
* GET /api/image?libraryId=xxx&keywords=xxx&folder=xxx&offset=0&limit=100
|
||||
*/
|
||||
router.get('/',
|
||||
validatePagination,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, keywords, folder, formats, offset, limit } = req.query;
|
||||
|
||||
const filters = {};
|
||||
if (keywords) filters.keywords = keywords;
|
||||
if (folder) filters.folder = folder;
|
||||
if (formats) filters.formats = formats.split(',');
|
||||
|
||||
const pagination = (offset !== undefined && limit !== undefined)
|
||||
? { offset: parseInt(offset), limit: parseInt(limit) }
|
||||
: null;
|
||||
|
||||
const result = await imageService.searchImages(libraryId, filters, pagination);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取图片总数
|
||||
* GET /api/image/count?libraryId=xxx
|
||||
*/
|
||||
router.get('/count', asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.query;
|
||||
const count = await imageService.getImageCount(libraryId);
|
||||
res.json({ success: true, data: { count } });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取图片统计
|
||||
* GET /api/image/stats?libraryId=xxx
|
||||
*/
|
||||
router.get('/stats', asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.query;
|
||||
const stats = await imageService.getImageStats(libraryId);
|
||||
res.json({ success: true, data: stats });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取文件夹列表
|
||||
* GET /api/image/folders?libraryId=xxx
|
||||
*/
|
||||
router.get('/folders', asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.query;
|
||||
const folders = await imageService.getFolders(libraryId);
|
||||
res.json({ success: true, data: { folders } });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取缓存元数据
|
||||
* GET /api/image/cache-meta?libraryId=xxx
|
||||
*/
|
||||
router.get('/cache-meta', asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.query;
|
||||
const meta = await imageService.getCacheMeta(libraryId);
|
||||
res.json({ success: true, data: meta });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取图片详情
|
||||
* GET /api/image/:id?libraryId=xxx
|
||||
*/
|
||||
router.get('/:id', asyncHandler(async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { libraryId } = req.query;
|
||||
const image = await imageService.getImageById(libraryId, id);
|
||||
res.json({ success: true, data: image });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 获取缩略图
|
||||
* GET /api/image/thumbnail/:libraryId/:filename
|
||||
* 使用分片结构:.flypic/thumbnails/ab/hash.webp
|
||||
*/
|
||||
router.get('/thumbnail/:libraryId/:filename', (req, res) => {
|
||||
const { libraryId, filename } = req.params;
|
||||
|
||||
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); // 使用 == 宽松比较
|
||||
}
|
||||
|
||||
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 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);
|
||||
res.status(500).send('Error serving thumbnail');
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 获取原图
|
||||
* GET /api/image/original/:libraryId/:path
|
||||
*/
|
||||
router.get('/original/:libraryId/*', (req, res) => {
|
||||
const { libraryId } = req.params;
|
||||
const imagePath = req.params[0]; // 获取通配符匹配的路径
|
||||
|
||||
try {
|
||||
const config = require('../../utils/config').loadConfig();
|
||||
|
||||
// 尝试两种方式查找:数字和字符串
|
||||
let library = config.libraries.find(lib => lib.id === parseInt(libraryId));
|
||||
if (!library) {
|
||||
library = config.libraries.find(lib => lib.id == libraryId);
|
||||
}
|
||||
|
||||
if (!library) {
|
||||
return res.status(404).send('Library not found');
|
||||
}
|
||||
|
||||
const fullPath = path.join(library.path, imagePath);
|
||||
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
return res.status(404).send('Image not found');
|
||||
}
|
||||
|
||||
res.sendFile(fullPath);
|
||||
} catch (error) {
|
||||
console.error('Error serving original image:', error);
|
||||
res.status(500).send('Error serving image');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* 素材库路由(新架构)
|
||||
* 薄层路由,业务逻辑在 Service 层
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { asyncHandler } = require('../middleware/errorHandler');
|
||||
const { validateRequired } = require('../middleware/validator');
|
||||
|
||||
// 服务实例(从 app 中获取)
|
||||
let libraryService;
|
||||
|
||||
router.use((req, res, next) => {
|
||||
if (!libraryService) {
|
||||
libraryService = req.app.get('libraryService');
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
/**
|
||||
* 获取所有素材库
|
||||
* GET /api/library
|
||||
*/
|
||||
router.get('/', asyncHandler(async (req, res) => {
|
||||
const data = libraryService.getAllLibraries();
|
||||
res.json({ success: true, data });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 创建素材库
|
||||
* POST /api/library
|
||||
* Body: { name, path }
|
||||
*/
|
||||
router.post('/',
|
||||
validateRequired(['name', 'path']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { name, path } = req.body;
|
||||
const result = await libraryService.createLibrary(name, path);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 更新素材库
|
||||
* PUT /api/library/:id
|
||||
* Body: { name?, path? }
|
||||
*/
|
||||
router.put('/:id', asyncHandler(async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const result = await libraryService.updateLibrary(id, req.body);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 删除素材库
|
||||
* DELETE /api/library/:id
|
||||
*/
|
||||
router.delete('/:id', asyncHandler(async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const result = await libraryService.deleteLibrary(id);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 设置当前素材库
|
||||
* POST /api/library/:id/set-current
|
||||
*/
|
||||
router.post('/:id/set-current', asyncHandler(async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const result = await libraryService.setCurrentLibrary(id);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 更新偏好设置
|
||||
* PUT /api/library/preferences
|
||||
* Body: { preferences }
|
||||
*/
|
||||
router.put('/preferences', asyncHandler(async (req, res) => {
|
||||
const result = libraryService.updatePreferences(req.body);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 更新主题
|
||||
* PUT /api/library/theme
|
||||
* Body: { theme }
|
||||
*/
|
||||
router.put('/theme',
|
||||
validateRequired(['theme']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { theme } = req.body;
|
||||
const result = libraryService.updateTheme(theme);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 获取素材库统计
|
||||
* GET /api/library/:id/stats
|
||||
*/
|
||||
router.get('/:id/stats', asyncHandler(async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const result = await libraryService.getLibraryStats(id);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* 扫描路由(新架构)
|
||||
* 薄层路由,业务逻辑在 Service 层
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { asyncHandler } = require('../middleware/errorHandler');
|
||||
const { validateRequired } = require('../middleware/validator');
|
||||
|
||||
// 服务实例(从 app 中获取)
|
||||
let scanService;
|
||||
|
||||
router.use((req, res, next) => {
|
||||
if (!scanService) {
|
||||
scanService = req.app.get('scanService');
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
/**
|
||||
* 全量扫描
|
||||
* POST /api/scan/full
|
||||
* Body: { libraryId, wait? }
|
||||
*/
|
||||
router.post('/full',
|
||||
validateRequired(['libraryId']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, wait = false } = req.body;
|
||||
const result = await scanService.fullScan(libraryId, wait);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 增量同步
|
||||
* POST /api/scan/sync
|
||||
* Body: { libraryId, wait? }
|
||||
*/
|
||||
router.post('/sync',
|
||||
validateRequired(['libraryId']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, wait = false } = req.body;
|
||||
const result = await scanService.incrementalSync(libraryId, wait);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* 停止扫描
|
||||
* 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
|
||||
*/
|
||||
router.get('/status/:libraryId', asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.params;
|
||||
const result = scanService.getScanStatus(libraryId);
|
||||
res.json({ success: true, data: result });
|
||||
}));
|
||||
|
||||
/**
|
||||
* 修复文件夹路径
|
||||
* POST /api/scan/fix-folders
|
||||
* Body: { libraryId }
|
||||
*/
|
||||
router.post('/fix-folders',
|
||||
validateRequired(['libraryId']),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId } = req.body;
|
||||
const result = await scanService.fixFolders(libraryId);
|
||||
res.json({ success: true, data: result });
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* 图片服务层
|
||||
* 封装图片相关的业务逻辑
|
||||
*/
|
||||
|
||||
const { NotFoundError, ValidationError } = require('../middleware/errorHandler');
|
||||
const ImageModel = require('../models/ImageModel');
|
||||
const FolderModel = require('../models/FolderModel');
|
||||
|
||||
class ImageService {
|
||||
constructor(configManager, dbPool) {
|
||||
this.configManager = configManager;
|
||||
this.dbPool = dbPool;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索图片
|
||||
*/
|
||||
async searchImages(libraryId, filters = {}, pagination = null) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
return imageModel.search(filters, pagination);
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片详情
|
||||
*/
|
||||
async getImageById(libraryId, imageId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
const image = imageModel.findById(imageId);
|
||||
|
||||
if (!image) {
|
||||
throw new NotFoundError('Image', imageId);
|
||||
}
|
||||
|
||||
return image;
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据路径获取图片
|
||||
*/
|
||||
async getImageByPath(libraryId, imagePath) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
const image = imageModel.findByPath(imagePath);
|
||||
|
||||
if (!image) {
|
||||
throw new NotFoundError('Image', imagePath);
|
||||
}
|
||||
|
||||
return image;
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片总数
|
||||
*/
|
||||
async getImageCount(libraryId, filters = {}) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const imageModel = new ImageModel(db.db);
|
||||
return imageModel.count(filters);
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片统计信息
|
||||
*/
|
||||
async getImageStats(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const stats = db.db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(size) as totalSize,
|
||||
AVG(size) as avgSize,
|
||||
MAX(size) as maxSize,
|
||||
MIN(size) as minSize,
|
||||
COUNT(DISTINCT format) as formatCount,
|
||||
COUNT(DISTINCT folder) as folderCount
|
||||
FROM images
|
||||
`).get();
|
||||
|
||||
const formatStats = db.db.prepare(`
|
||||
SELECT format, COUNT(*) as count
|
||||
FROM images
|
||||
GROUP BY format
|
||||
ORDER BY count DESC
|
||||
`).all();
|
||||
|
||||
return {
|
||||
...stats,
|
||||
formats: formatStats
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件夹列表
|
||||
*/
|
||||
async getFolders(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const folderModel = new FolderModel(db.db);
|
||||
return folderModel.getTree();
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存元数据
|
||||
*/
|
||||
async getCacheMeta(libraryId) {
|
||||
const library = this._getLibrary(libraryId);
|
||||
const db = this.dbPool.acquire(library.path);
|
||||
|
||||
try {
|
||||
const result = db.db.prepare(`
|
||||
SELECT
|
||||
COUNT(*) as totalImages,
|
||||
COUNT(DISTINCT folder) as totalFolders,
|
||||
MAX(indexed_at) as lastIndexed
|
||||
FROM images
|
||||
`).get();
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
...result,
|
||||
dbPath: library.path
|
||||
};
|
||||
} finally {
|
||||
this.dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取素材库对象
|
||||
* @private
|
||||
*/
|
||||
_getLibrary(libraryId) {
|
||||
const config = this.configManager.load();
|
||||
const library = config.libraries.find(lib => lib.id === libraryId);
|
||||
|
||||
if (!library) {
|
||||
throw new NotFoundError('Library', libraryId);
|
||||
}
|
||||
|
||||
return library;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ImageService;
|
||||
@@ -0,0 +1,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;
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 数据库字段映射工具
|
||||
* 将 snake_case 转换为 camelCase
|
||||
*/
|
||||
|
||||
// 数据库字段到前端字段的映射
|
||||
const DB_TO_FRONTEND_MAP = {
|
||||
// Image fields
|
||||
file_type: 'fileType',
|
||||
created_at: 'createdAt',
|
||||
modified_at: 'modifiedAt',
|
||||
file_hash: 'fileHash',
|
||||
thumbnail_path: 'thumbnailPath',
|
||||
thumbnail_size: 'thumbnailSize',
|
||||
indexed_at: 'indexedAt',
|
||||
|
||||
// Folder fields
|
||||
parent_path: 'parentPath',
|
||||
image_count: 'imageCount',
|
||||
last_scan: 'lastScan'
|
||||
};
|
||||
|
||||
/**
|
||||
* 映射单个对象的字段
|
||||
*/
|
||||
function mapFields(obj, mapping) {
|
||||
if (!obj) return null;
|
||||
|
||||
const result = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const newKey = mapping[key] || key;
|
||||
result[newKey] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 映射图片对象
|
||||
*/
|
||||
function mapImageForFrontend(image) {
|
||||
return mapFields(image, DB_TO_FRONTEND_MAP);
|
||||
}
|
||||
|
||||
/**
|
||||
* 映射文件夹对象
|
||||
*/
|
||||
function mapFolderForFrontend(folder) {
|
||||
return mapFields(folder, DB_TO_FRONTEND_MAP);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量映射图片数组
|
||||
*/
|
||||
function mapImagesForFrontend(images) {
|
||||
return images.map(mapImageForFrontend);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量映射文件夹数组
|
||||
*/
|
||||
function mapFoldersForFrontend(folders) {
|
||||
return folders.map(mapFolderForFrontend);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
mapImageForFrontend,
|
||||
mapFolderForFrontend,
|
||||
mapImagesForFrontend,
|
||||
mapFoldersForFrontend,
|
||||
mapFields
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 简单的日志工具
|
||||
*/
|
||||
|
||||
const LOG_LEVELS = {
|
||||
DEBUG: 0,
|
||||
INFO: 1,
|
||||
WARN: 2,
|
||||
ERROR: 3
|
||||
};
|
||||
|
||||
const currentLevel = process.env.LOG_LEVEL
|
||||
? LOG_LEVELS[process.env.LOG_LEVEL.toUpperCase()]
|
||||
: LOG_LEVELS.INFO;
|
||||
|
||||
function log(level, message, ...args) {
|
||||
if (LOG_LEVELS[level] >= currentLevel) {
|
||||
const timestamp = new Date().toISOString();
|
||||
const prefix = `[${timestamp}] [${level}]`;
|
||||
console.log(prefix, message, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = {
|
||||
debug: (message, ...args) => log('DEBUG', message, ...args),
|
||||
info: (message, ...args) => log('INFO', message, ...args),
|
||||
warn: (message, ...args) => log('WARN', message, ...args),
|
||||
error: (message, ...args) => log('ERROR', message, ...args)
|
||||
};
|
||||
|
||||
module.exports = logger;
|
||||
Reference in new issue
Block a user