/**
* 文件夹批量水印/重命名路由
* - POST /api/batch/start 启动批量任务(加水印 / 去水印 / 重命名),返回 taskId 立即返回
* - POST /api/batch/rename-preview 批量重命名预览(不执行)
* - GET /api/batch/status/:id 查询任务进度
* - POST /api/batch/cancel/:id 取消任务
*
* 加水印:sharp 合成 SVG 文字水印(九宫格 / 平铺、透明度、旋转、字号按图宽百分比)
* 去水印:按百分比矩形区域生成 mask → 调 flypic-ai sidecar 的 LaMa /inpaint
*/
const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const sharp = require('sharp');
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const ImageModel = require('../models/ImageModel');
const logger = require('../utils/logger');
const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003';
const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']);
const SHARP_FMT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' };
// ---------- 任务表(内存) ----------
const tasks = new Map();
let taskSeq = 0;
function newTask(type, payload) {
const id = `bt_${Date.now()}_${++taskSeq}`;
const task = {
id,
type, // 'add' | 'remove'
status: 'running', // running | done | cancelled | error
total: 0,
done: 0,
failed: 0,
skipped: 0,
current: '',
errors: [],
cancelled: false,
startedAt: Date.now(),
finishedAt: null,
payload
};
tasks.set(id, task);
return task;
}
// 完成的任务 30 分钟后清理
setInterval(() => {
const cutoff = Date.now() - 30 * 60 * 1000;
for (const [id, t] of tasks) {
if (t.finishedAt && t.finishedAt < cutoff) tasks.delete(id);
}
}, 60 * 1000).unref();
// ---------- 工具 ----------
/** 按百分比区域生成 mask(白色=待修复)→ 渲染为 PNG(PIL 不认 SVG) */
async function makeMaskBuffer(width, height, region) {
const x = Math.max(0, Math.round((width * region.x) / 100));
const y = Math.max(0, Math.round((height * region.y) / 100));
const w = Math.max(1, Math.min(width - x, Math.round((width * region.w) / 100)));
const h = Math.max(1, Math.min(height - y, Math.round((height * region.h) / 100)));
const svg = ``;
return sharp(Buffer.from(svg)).png().toBuffer();
}
/** 生成文字水印 SVG(支持九宫格单个 / 平铺) */
function makeWatermarkSvg(width, height, opts) {
const text = String(opts.text || '').trim();
const fontSize = Math.max(8, Math.round((width * (opts.fontSizePct || 4)) / 100));
const opacity = Math.max(0, Math.min(100, opts.opacity ?? 50)) / 100;
const color = opts.color || '#ffffff';
const margin = Math.round((width * (opts.marginPct ?? 2)) / 100);
const stroke = opts.stroke ? ` stroke="#000000" stroke-opacity="${opacity * 0.5}" stroke-width="${Math.max(1, fontSize / 14)}"` : '';
const fill = color.startsWith('#')
? (color.length === 4 || color.length === 7 ? color : '#ffffff')
: color;
const escape = (s) => s.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"').replace(/'/g, ''');
const esc = escape(text);
const font = "font-family=\"Noto Sans CJK SC, Noto Sans SC, WenQuanYi Zen Hei, sans-serif\"";
const items = [];
if (opts.tile) {
// 平铺:按角度旋转整块排布
const rotate = Number(opts.rotate ?? -30);
const gapX = fontSize * 8;
const gapY = fontSize * 5;
let row = 0;
for (let y = -height; y < height * 2; y += gapY) {
const offset = row % 2 === 0 ? 0 : gapX / 2;
for (let x = -width; x < width * 2; x += gapX) {
items.push(
`${esc}`
);
}
row++;
}
const cx = width / 2;
const cy = height / 2;
return ``;
}
// 单个水印:九宫格定位
const pos = opts.position || 'bottom-right';
const [va, ha] = pos.split('-');
const rotate = Number(opts.rotate || 0);
let x, y, anchor;
if (ha === 'left') { x = margin; anchor = 'start'; }
else if (ha === 'right') { x = width - margin; anchor = 'end'; }
else { x = width / 2; anchor = 'middle'; }
if (va === 'top') y = margin + fontSize;
else if (va === 'middle') y = height / 2;
else y = height - margin;
const transform = rotate ? ` transform="rotate(${rotate} ${x} ${y})"` : '';
items.push(
`${esc}`
);
return ``;
}
/** 结果 buffer 按原格式落盘(覆盖原图或另存) */
async function writeResult(absPath, pngBuffer, opts = {}) {
const ext = path.extname(absPath).toLowerCase();
const fmt = SHARP_FMT[ext];
if (!fmt) throw new Error(`不支持的格式: ${ext}`);
let target = absPath;
if (opts.mode === 'new') {
const base = absPath.slice(0, absPath.length - ext.length);
const suffix = opts.suffix || '_wm';
target = `${base}${suffix}${ext}`;
let n = 1;
while (fs.existsSync(target)) {
target = `${base}${suffix}${n}${ext}`;
n++;
}
}
const pipeline = sharp(pngBuffer);
if (fmt === 'jpeg') await pipeline.jpeg({ quality: 92 }).toFile(target);
else if (fmt === 'webp') await pipeline.webp({ quality: 92 }).toFile(target);
else await pipeline.png().toFile(target);
return target;
}
/** 串行并发池 */
async function runPool(items, concurrency, worker) {
let idx = 0;
const runners = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
for (;;) {
const i = idx++;
if (i >= items.length) break;
await worker(items[i], i);
}
});
await Promise.all(runners);
}
/** 调 sidecar 去水印 */
async function callInpaint(imageBuffer, maskBuffer) {
const form = new FormData();
form.append('image', new Blob([imageBuffer], { type: 'image/png' }), 'image.png');
form.append('mask', new Blob([maskBuffer], { type: 'image/png' }), 'mask.png');
const resp = await fetch(`${AI_BASE}/inpaint`, {
method: 'POST',
body: form,
signal: AbortSignal.timeout(300 * 1000)
});
if (!resp.ok) {
let msg = `AI 服务错误 (${resp.status})`;
try {
const j = await resp.json();
msg = j.detail || j.error || msg;
} catch (_) { /* 非 JSON */ }
throw new Error(msg);
}
return Buffer.from(await resp.arrayBuffer());
}
/** 收集文件夹内图片(含子文件夹) */
function collectImages(req, libraryId, folder) {
return collectRenameTargets(req, { libraryId, folder, scope: 'folder' });
}
/**
* 收集重命名目标
* scope=folder(默认):文件夹递归(沿用 collectImages 语义)
* scope=search:按关键词模糊匹配整个库(filename/ocr_text LIKE,跨文件夹)
*/
function collectRenameTargets(req, { libraryId, folder, scope, keywords }) {
const configManager = req.app.get('configManager');
const dbPool = req.app.get('dbPool');
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
const config = configManager.load();
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
if (!library) throw new NotFoundError('Library', libraryId);
const db = dbPool.acquire(library.path);
try {
const model = new ImageModel(db.db);
if (scope === 'search') {
const kw = String(keywords || '').trim();
if (!kw) throw new ValidationError('搜索关键词不能为空');
// folder 与搜索列表同款过滤(含子目录):选中文件夹时范围一致,未选中则全库
const { images } = model.search({ keywords: kw, folder: folder || undefined }, null);
return { library, images };
}
const { images } = model.search({ folder }, null);
return { library, images };
} finally {
dbPool.release(library.path);
}
}
/** 每张图处理完后重建缩略图并更新 DB(每张独立 acquire,避免长占连接) */
async function reindex(req, libraryPath, absPath) {
const dbPool = req.app.get('dbPool');
const db = dbPool.acquire(libraryPath);
try {
await processImage(absPath, libraryPath, db);
} finally {
dbPool.release(libraryPath);
}
}
// ---------- 任务执行 ----------
async function runAddWatermark(req, task) {
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
const opts = task.payload.options;
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
task.total = images.length;
const targets = [];
for (const img of images) {
const abs = path.join(library.path, img.path);
const ext = path.extname(abs).toLowerCase();
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
task.skipped++;
continue;
}
targets.push({ img, abs, ext });
}
task.total = targets.length + task.skipped;
await runPool(targets, 3, async ({ img, abs, ext }) => {
if (task.cancelled) return;
task.current = img.path;
try {
const base = sharp(abs);
const meta = await base.metadata();
const w = meta.width || 1024;
const h = meta.height || 1024;
const svg = makeWatermarkSvg(w, h, opts);
let out = await base.rotate().composite([{ input: Buffer.from(svg), top: 0, left: 0 }]).png().toBuffer();
// rotate() 可能改变尺寸(EXIF),重取
const m2 = await sharp(out).metadata();
if (m2.width !== w || m2.height !== h) {
const svg2 = makeWatermarkSvg(m2.width, m2.height, opts);
out = await sharp(out).composite([{ input: Buffer.from(svg2), top: 0, left: 0 }]).png().toBuffer();
}
await writeResult(abs, out, { mode: outMode, suffix: '_wm' });
await reindex(req, library.path, abs);
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}`);
}
});
}
async function runRemoveWatermark(req, task) {
const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder);
const region = task.payload.options.region;
const outMode = task.payload.output === 'new' ? 'new' : 'overwrite';
task.total = images.length;
const targets = [];
for (const img of images) {
const abs = path.join(library.path, img.path);
const ext = path.extname(abs).toLowerCase();
if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) {
task.skipped++;
continue;
}
targets.push({ img, abs, ext });
}
task.total = targets.length + task.skipped;
// LaMa CPU 推理较慢且 sidecar 为单模型,串行处理
await runPool(targets, 1, async ({ img, abs }) => {
if (task.cancelled) return;
task.current = img.path;
try {
const srcBuf = fs.readFileSync(abs);
const meta = await sharp(srcBuf).metadata();
const w = meta.width || 1024;
const h = meta.height || 1024;
const mask = await makeMaskBuffer(w, h, region);
const result = await callInpaint(srcBuf, mask);
await writeResult(abs, result, { mode: outMode, suffix: '_nowm' });
await reindex(req, library.path, abs);
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}`);
}
});
}
// ---------- 批量重命名 ----------
/** 文件系统非法文件名字符(Windows 兼容) */
const ILLEGAL_NAME_RE = /[\\/:*?"<>|]/;
/**
* 计算重命名计划(preview 与执行共用,保证一致)
* @param {object} opts { images, folder, mode: 'prefix'|'suffix'|'replace'|'keyword', text, find?, includeSubdirs }
* keyword 模式:把文件名中的 find 全部替换为 text(text 可为空 = 删除关键词),
* 不含 find 的文件标记 skipReason='不含关键词'
* @returns {Array<{img, newFilename, newPath, absNew, skipReason?}>}
*/
function computeRenamePlan({ images, folder, mode, text, find, includeSubdirs }) {
const cleanText = String(text || '').trim();
const cleanFind = String(find || '').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 if (mode === 'keyword') {
// 关键词替换:文件名中所有出现的 find 换成 text;不含 find 跳过
newBase = base.includes(cleanFind) ? base.split(cleanFind).join(cleanText) : base;
} 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 (mode === 'keyword' && !base.includes(cleanFind)) {
entry.skipReason = '不含关键词';
} else 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 p = task.payload;
const { library, images } = collectRenameTargets(req, {
libraryId: p.libraryId,
folder: p.folder,
scope: p.scope,
keywords: p.keywords
});
const opts = task.payload.options;
const isSearch = p.scope === 'search';
const plan = computeRenamePlan({
images,
folder: task.payload.folder,
mode: opts.mode,
text: opts.text,
find: opts.find,
includeSubdirs: isSearch ? true : 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?, scope?: 'folder'|'search', keywords?, options: { mode, text, find?, includeSubdirs } }
* scope=search 时按 keywords 模糊匹配全库(跨文件夹),folder 可不传
* 返回重命名预览(不执行)
*/
router.post(
'/rename-preview',
asyncHandler(async (req, res) => {
const { libraryId, folder, scope, options } = req.body || {};
if (!libraryId) throw new ValidationError('缺少 libraryId');
const isSearch = scope === 'search';
if (!isSearch && !folder) throw new ValidationError('缺少 libraryId 或 folder');
const mode = options && options.mode;
if (!['prefix', 'suffix', 'replace', 'keyword'].includes(mode)) {
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
}
const text = String((options && options.text) || '').trim();
const find = String((options && options.find) || '').trim();
if (mode === 'keyword') {
if (!find) throw new ValidationError('请填写要查找的关键词');
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
} else {
if (!text) throw new ValidationError('重命名文本不能为空');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
}
const targets = collectRenameTargets(req, {
libraryId, folder, scope, keywords: options && options.keywords
});
const plan = computeRenamePlan({
images: targets.images,
folder: isSearch ? null : folder,
mode, text, find,
includeSubdirs: isSearch ? true : 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 }
* add options: { text, tile?, position?, fontSizePct?, opacity?, color?, marginPct?, rotate?, stroke? }
* remove options: { region: { x, y, w, h } // 图片宽高的百分比 }
*/
router.post(
'/start',
asyncHandler(async (req, res) => {
const { libraryId, folder, type, output, options, scope } = req.body || {};
if (!libraryId) throw new ValidationError('缺少 libraryId');
const isSearch = type === 'rename' && scope === 'search';
if (!folder && !isSearch) throw new ValidationError('缺少 libraryId 或 folder');
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', 'keyword'].includes(mode)) {
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
}
const text = String((options && options.text) || '').trim();
const find = String((options && options.find) || '').trim();
if (mode === 'keyword') {
if (!find) throw new ValidationError('请填写要查找的关键词');
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
} else {
if (!text) throw new ValidationError('重命名文本不能为空');
if (ILLEGAL_NAME_RE.test(text)) 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)) {
throw new ValidationError('缺少水印区域 region {x,y,w,h}(百分比)');
}
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
}
const { images } = collectRenameTargets(req, {
libraryId, folder, scope, keywords: options && options.keywords
});
if (images.length === 0) {
throw new ValidationError(
scope === 'search' ? '搜索没有匹配到文件' : (type === 'rename' ? '该文件夹下没有文件' : '该文件夹下没有图片')
);
}
const task = newTask(type, {
libraryId,
folder: folder || null,
scope: scope || 'folder',
keywords: scope === 'search' ? String(options?.keywords || '').trim() : null,
output,
options
});
task.total = images.length;
logger.info(`▶️ 批量${type === 'add' ? '加水印' : type === 'remove' ? '去水印' : '重命名'}启动: ${folder} (${images.length} 张)`);
// 立即返回,后台执行
const runner = type === 'add' ? runAddWatermark : type === 'remove' ? runRemoveWatermark : runRename;
runner(req, task)
.then(() => {
task.status = task.cancelled ? 'cancelled' : 'done';
})
.catch((err) => {
task.status = 'error';
task.errors.push({ path: '', error: err.message });
logger.error(`❌ 批量任务异常: ${err.message}`);
})
.finally(() => {
task.current = '';
task.finishedAt = Date.now();
});
res.json({ taskId: task.id, total: images.length });
})
);
/** GET /api/batch/status/:id */
router.get(
'/status/:id',
asyncHandler(async (req, res) => {
const task = tasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
res.json({
id: task.id,
type: task.type,
status: task.status,
total: task.total,
done: task.done,
failed: task.failed,
skipped: task.skipped,
current: task.current,
errors: task.errors,
startedAt: task.startedAt,
finishedAt: task.finishedAt
});
})
);
/** POST /api/batch/cancel/:id */
router.post(
'/cancel/:id',
asyncHandler(async (req, res) => {
const task = tasks.get(req.params.id);
if (!task) throw new NotFoundError('Task', req.params.id);
if (task.status === 'running') {
task.cancelled = true;
task.status = 'cancelled';
}
res.json({ ok: true, status: task.status });
})
);
module.exports = router;