feat(v1.4.6): 文件夹右键批量重命名文件(前缀/后缀/全替换+子目录+实时预览)
This commit is contained in:
1 parent
7d0023949b
commit
58900d0d45
10 files changed
+596
-11
No files matched your search
+171
-6
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* 文件夹批量水印路由
|
||||
* - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回
|
||||
* 文件夹批量水印/重命名路由
|
||||
* - POST /api/batch/start 启动批量任务(加水印 / 去水印 / 重命名),返回 taskId 立即返回
|
||||
* - POST /api/batch/rename-preview 批量重命名预览(不执行)
|
||||
* - GET /api/batch/status/:id 查询任务进度
|
||||
* - POST /api/batch/cancel/:id 取消任务
|
||||
*
|
||||
@@ -312,8 +313,163 @@ async function runRemoveWatermark(req, task) {
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 批量重命名 ----------
|
||||
|
||||
/** 文件系统非法文件名字符(Windows 兼容) */
|
||||
const ILLEGAL_NAME_RE = /[\\/:*?"<>|]/;
|
||||
|
||||
/**
|
||||
* 计算重命名计划(preview 与执行共用,保证一致)
|
||||
* @param {object} opts { images, folder, mode: 'prefix'|'suffix'|'replace', text, includeSubdirs }
|
||||
* @returns {Array<{img, newFilename, newPath, absNew, skipReason?}>}
|
||||
*/
|
||||
function computeRenamePlan({ images, folder, mode, text, includeSubdirs }) {
|
||||
const cleanText = String(text || '').trim();
|
||||
let list = images;
|
||||
if (!includeSubdirs) {
|
||||
// 只重命名该文件夹直接子项,排除子目录内文件
|
||||
list = images.filter((img) => img.folder === folder);
|
||||
}
|
||||
// 按目录分组 + 原文件名升序,保证序号顺序稳定
|
||||
const sorted = [...list].sort(
|
||||
(a, b) => a.folder.localeCompare(b.folder) || a.filename.localeCompare(b.filename)
|
||||
);
|
||||
|
||||
const dirGroups = new Map();
|
||||
for (const img of sorted) {
|
||||
if (!dirGroups.has(img.folder)) dirGroups.set(img.folder, []);
|
||||
dirGroups.get(img.folder).push(img);
|
||||
}
|
||||
|
||||
const used = new Set(); // 已分配的目标路径(小写归一,防大小写不敏感 FS 撞名)
|
||||
const plan = [];
|
||||
for (const [, group] of dirGroups) {
|
||||
const width = Math.max(3, String(group.length).length);
|
||||
for (let i = 0; i < group.length; i++) {
|
||||
const img = group[i];
|
||||
const ext = path.extname(img.filename); // 含点,保留原样
|
||||
const base = img.filename.slice(0, img.filename.length - ext.length);
|
||||
let newBase;
|
||||
if (mode === 'prefix') newBase = cleanText + base;
|
||||
else if (mode === 'suffix') newBase = base + cleanText;
|
||||
else if (mode === 'replace') {
|
||||
// 全部改名:整段替换原文件名,同目录多个文件自动编号避免撞名
|
||||
newBase = group.length > 1
|
||||
? `${cleanText}-${String(i + 1).padStart(width, '0')}`
|
||||
: cleanText;
|
||||
} else newBase = base;
|
||||
|
||||
const newFilename = `${newBase}${ext}`;
|
||||
const newPath = `${img.folder ? img.folder + '/' : ''}${newFilename}`;
|
||||
const absNew = newPath; // 相对库根,执行时再 join
|
||||
|
||||
const entry = { img, newFilename, newPath, skipReason: null };
|
||||
if (newFilename === img.filename) {
|
||||
entry.skipReason = '文件名未变化';
|
||||
} else if (used.has(newPath.toLowerCase())) {
|
||||
entry.skipReason = '目标文件名冲突(本次内)';
|
||||
}
|
||||
used.add(newPath.toLowerCase());
|
||||
plan.push(entry);
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
async function runRename(req, task) {
|
||||
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
|
||||
const opts = task.payload.options;
|
||||
|
||||
const plan = computeRenamePlan({
|
||||
images,
|
||||
folder: task.payload.folder,
|
||||
mode: opts.mode,
|
||||
text: opts.text,
|
||||
includeSubdirs: opts.includeSubdirs !== false
|
||||
});
|
||||
task.total = plan.length;
|
||||
|
||||
const dbPool = req.app.get('dbPool');
|
||||
const dbUpdates = [];
|
||||
|
||||
for (const entry of plan) {
|
||||
if (task.cancelled) break;
|
||||
const { img, newFilename, newPath, skipReason } = entry;
|
||||
task.current = img.path;
|
||||
if (skipReason) {
|
||||
task.skipped++;
|
||||
continue;
|
||||
}
|
||||
const absOld = path.join(library.path, img.path);
|
||||
const absNew = path.join(library.path, newPath);
|
||||
try {
|
||||
if (!fs.existsSync(absOld)) {
|
||||
task.skipped++;
|
||||
if (task.errors.length < 20) task.errors.push({ path: img.path, error: '源文件不存在' });
|
||||
continue;
|
||||
}
|
||||
if (absOld !== absNew && fs.existsSync(absNew)) {
|
||||
task.skipped++;
|
||||
if (task.errors.length < 20) task.errors.push({ path: img.path, error: `目标已存在: ${newFilename}` });
|
||||
continue;
|
||||
}
|
||||
if (absOld !== absNew) await fs.promises.rename(absOld, absNew);
|
||||
dbUpdates.push({ oldPath: img.path, newPath, newFilename });
|
||||
task.done++;
|
||||
} catch (err) {
|
||||
task.failed++;
|
||||
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
|
||||
logger.warn(`⚠️ 批量重命名失败 ${img.path}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 统一更新 DB(缩略图按内容 hash 存储,与文件名无关,无需重建)
|
||||
if (dbUpdates.length > 0) {
|
||||
const db = dbPool.acquire(library.path);
|
||||
try {
|
||||
const stmt = db.db.prepare('UPDATE images SET path = ?, filename = ? WHERE path = ?');
|
||||
for (const u of dbUpdates) stmt.run(u.newPath, u.newFilename, u.oldPath);
|
||||
} finally {
|
||||
dbPool.release(library.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 路由 ----------
|
||||
|
||||
/**
|
||||
* POST /api/batch/rename-preview
|
||||
* body: { libraryId, folder, options: { mode, text, includeSubdirs } }
|
||||
* 返回重命名预览(不执行)
|
||||
*/
|
||||
router.post(
|
||||
'/rename-preview',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, folder, options } = req.body || {};
|
||||
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
|
||||
const mode = options && options.mode;
|
||||
if (!['prefix', 'suffix', 'replace'].includes(mode)) {
|
||||
throw new ValidationError('mode 必须是 prefix / suffix / replace');
|
||||
}
|
||||
const text = String((options && options.text) || '').trim();
|
||||
if (!text) throw new ValidationError('重命名文本不能为空');
|
||||
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||
|
||||
const { images } = collectImages(req, libraryId, folder);
|
||||
const plan = computeRenamePlan({
|
||||
images, folder, mode, text,
|
||||
includeSubdirs: options.includeSubdirs !== false
|
||||
});
|
||||
const effective = plan.filter((p) => !p.skipReason);
|
||||
res.json({
|
||||
count: effective.length,
|
||||
total: plan.length,
|
||||
samples: plan.slice(0, 6).map((p) => ({ from: p.img.filename, to: p.newFilename })),
|
||||
skipped: plan.filter((p) => p.skipReason).length
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/batch/start
|
||||
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
|
||||
@@ -325,10 +481,19 @@ router.post(
|
||||
asyncHandler(async (req, res) => {
|
||||
const { libraryId, folder, type, output, options } = req.body || {};
|
||||
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
|
||||
if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove');
|
||||
if (!['add', 'remove', 'rename'].includes(type)) throw new ValidationError('type 必须是 add / remove / rename');
|
||||
|
||||
if (type === 'add') {
|
||||
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
|
||||
} else if (type === 'rename') {
|
||||
const mode = options && options.mode;
|
||||
if (!['prefix', 'suffix', 'replace'].includes(mode)) {
|
||||
throw new ValidationError('mode 必须是 prefix / suffix / replace');
|
||||
}
|
||||
if (!String(options.text || '').trim()) throw new ValidationError('重命名文本不能为空');
|
||||
if (ILLEGAL_NAME_RE.test(String(options.text).trim())) {
|
||||
throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||
}
|
||||
} else {
|
||||
const r = options && options.region;
|
||||
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
|
||||
@@ -338,14 +503,14 @@ router.post(
|
||||
}
|
||||
|
||||
const { images } = collectImages(req, libraryId, folder);
|
||||
if (images.length === 0) throw new ValidationError('该文件夹下没有图片');
|
||||
if (images.length === 0) throw new ValidationError(type === 'rename' ? '该文件夹下没有文件' : '该文件夹下没有图片');
|
||||
|
||||
const task = newTask(type, { libraryId, folder, output, options });
|
||||
task.total = images.length;
|
||||
logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`);
|
||||
logger.info(`▶️ 批量${type === 'add' ? '加水印' : type === 'remove' ? '去水印' : '重命名'}启动: ${folder} (${images.length} 张)`);
|
||||
|
||||
// 立即返回,后台执行
|
||||
const runner = type === 'add' ? runAddWatermark : runRemoveWatermark;
|
||||
const runner = type === 'add' ? runAddWatermark : type === 'remove' ? runRemoveWatermark : runRename;
|
||||
runner(req, task)
|
||||
.then(() => {
|
||||
task.status = task.cancelled ? 'cancelled' : 'done';
|
||||
|
||||
Reference in new issue
Block a user