Files
seewo/kit/core.mjs
T
wangfar 32b0e74e9d seewo-kit: 新增审计/改样式/删页排序/备份列表
- inspect_courseware:按页序审计文字、字号、颜色、位置、动画与点击顺序,支持全课件搜索
- set_text_style:批量改字号/加粗/颜色/对齐/框宽,只改 TextRun,保护默认属性与项目符号
- replace_text:支持 pages/allPages、matchAll、dryRun 预览
- delete_slides / move_slides:重写 Board 页序与索引映射,删页默认进回收目录
- list_backups:列出快照,供 restore_courseware 取 backupId
- README 更新到 17 个工具
2026-11-13 08:12:27 +08:00

2075 lines
83 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* seewo-kit 核心库
*
* 希沃白板 5 的 MCP 没有动画 / 跨课件复制 / 文本改写 / 课件自检能力,
* 但课件缓存都是明文(索引 JSON + 每页 XML + SQLite 缓存库),
* 所以这里直接操作缓存文件,并通过希沃自己的 MCP 负责「关课件 / 开课件 / 同步」。
*
* 约定:
* · 所有写操作前,如果目标课件正开着,先关闭(syncBeforeClose=false)
* · 关闭前检查「内存里的页数/大小」和磁盘索引是否一致,防止丢掉未同步的新页
* · 写完后更新索引 JSON(FileHash/FileSize/Revision)和 CoursewareCacheData.db
* · 默认重新打开课件;sync=true 时再触发一次云同步
*/
import {
readFileSync, writeFileSync, readdirSync, statSync, existsSync,
mkdirSync, copyFileSync, rmSync, renameSync,
} from 'node:fs';
import { createHash, randomUUID, randomBytes } from 'node:crypto';
import path from 'node:path';
import os from 'node:os';
import { DatabaseSync } from 'node:sqlite';
// ---------------------------------------------------------------- 常量
const MCP_PORT = process.env.SEEWO_MCP_PORT || '7916';
const APP_DATA = path.join(os.homedir(), 'AppData', 'Roaming', 'Seewo', 'EasiNote5', 'Data');
const BACKUP_ROOT = path.join(os.tmpdir(), 'opencode', 'seewo-kit-backups');
const MAX_BACKUPS = 10;
const SLIDE_RE = /^Slides[\\/]Slide_\d+\.xml$/i;
const TMP = path.join(os.tmpdir(), 'opencode');
mkdirSync(BACKUP_ROOT, { recursive: true });
const sleep = ms => new Promise(r => setTimeout(r, ms));
const md5 = buf => createHash('md5').update(buf).digest('hex');
const md5File = f => md5(readFileSync(f));
const rand = n => {
const cs = 'abcdefghijkmnopqrstuvwxyz0123456789';
let s = '';
for (let i = 0; i < n; i++) s += cs[Math.floor(Math.random() * cs.length)];
return s;
};
const stamp = () => {
const d = new Date();
const p = n => String(n).padStart(2, '0');
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
};
const isSlidePath = p => SLIDE_RE.test(String(p || '').replace(/\//g, '\\'));
// ---------------------------------------------------------------- 希沃 MCP 客户端
let sessionId = null;
let rpcId = 100;
let initialized = false;
async function post(body, timeoutMs = 30000) {
const headers = { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' };
if (sessionId) headers['Mcp-Session-Id'] = sessionId;
const res = await fetch(`http://127.0.0.1:${MCP_PORT}/mcp`, {
method: 'POST', headers, body: JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
const sid = res.headers.get('mcp-session-id');
if (sid) sessionId = sid;
const text = await res.text();
if (text.includes('data:')) {
const data = text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join('');
try { return JSON.parse(data); } catch { return { raw: data }; }
}
try { return JSON.parse(text); } catch { return { raw: text }; }
}
async function rpc(name, args = {}, { timeoutMs } = {}) {
const r = await post({ jsonrpc: '2.0', id: rpcId++, method: 'tools/call', params: { name, arguments: args } }, timeoutMs);
if (r.error) throw new Error(`${name}: ${JSON.stringify(r.error)}`);
const txt = (r.result?.content ?? []).filter(c => c.type === 'text').map(c => c.text).join('\n');
if (r.result?.isError) throw new Error(`${name}: ${txt}`);
return { text: txt, data: r.result?.structuredContent };
}
async function ensureInit() {
if (initialized) return;
await post({
jsonrpc: '2.0', id: 1, method: 'initialize',
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'seewo-kit', version: '1.0' } },
});
await post({ jsonrpc: '2.0', method: 'notifications/initialized' });
initialized = true;
}
async function mcp(name, args = {}, { timeoutMs } = {}) {
await ensureInit();
try {
return await rpc(name, args, { timeoutMs });
} catch (e) {
// 会话过期时重新握手一次
if (/session|会话|ShellId/i.test(String(e.message))) {
sessionId = null;
initialized = false;
await ensureInit();
return await rpc(name, args, { timeoutMs });
}
throw e;
}
}
const shells = () => mcp('en_find_shells', { searchingMode: 'All' })
.then(r => r.data?.shells ?? [])
.catch(() => []);
// ---------------------------------------------------------------- 课件定位
export function listCoursewares() {
const out = [];
if (!existsSync(APP_DATA)) return out;
for (const user of readdirSync(APP_DATA)) {
const root = path.join(APP_DATA, user, 'Courseware');
if (!existsSync(root)) continue;
for (const id of readdirSync(root)) {
const dir = path.join(root, id);
if (!statSync(dir).isDirectory()) continue;
const jsonPath = path.join(dir, `${id}.json`);
if (!existsSync(jsonPath)) continue;
try {
const json = JSON.parse(readFileSync(jsonPath, 'utf8').replace(/^\uFEFF/, ''));
if (!json.Courseware) continue;
out.push({
dir, jsonPath, json, userDir: path.dirname(root),
name: json.Courseware.Name ?? '', localId: id,
mtime: statSync(jsonPath).mtimeMs,
});
} catch { /* 跳过坏索引 */ }
}
}
return out.sort((a, b) => b.mtime - a.mtime);
}
export function duplicatesOf(coursewares, target) {
const name = String(target.name || '').trim();
return coursewares.filter(
c => c.localId !== target.localId && String(c.name || '').trim() === name,
);
}
/** 同名多份时直接报错,避免按 mtime 静默选错课件 */
export function resolveCourseware(query) {
const all = listCoursewares();
if (!all.length) throw new Error('找不到本地课件缓存(希沃是否安装并登录过?)');
if (!query) return assertUniqueLocalName(all[0], all);
const q = String(query).trim();
const byId = all.find(c => c.localId === q);
if (byId) return byId;
const hits = all.filter(c => c.name.includes(q));
if (!hits.length) {
throw new Error(`没有名字含「${q}」的课件。可选:${all.slice(0, 8).map(c => c.name).join(' / ')}`);
}
const groups = new Map();
for (const c of hits) {
const n = String(c.name).trim();
if (!groups.has(n)) groups.set(n, []);
groups.get(n).push(c);
}
const dupes = [...groups.entries()].filter(([, v]) => v.length > 1);
if (dupes.length) {
const lines = dupes.flatMap(([n, v]) => v.map(c =>
` · ${n} localId=${c.localId} remoteId=${c.json.Courseware.RemoteId || '(无)'} rev=${c.json.Courseware.Revision}`));
throw new Error(`匹配到重名课件,无法确定要操作哪一份:\n${lines.join('\n')}\n`
+ '请改用 localId 指定,或先调用 remove_local_courseware 清理重复。');
}
return hits[0];
}
function assertUniqueLocalName(cw, all = listCoursewares()) {
const dupes = duplicatesOf(all, cw);
if (dupes.length) {
throw new Error(`课件「${cw.name}」还有 ${dupes.length} 份同名本地副本:`
+ dupes.map(c => `${c.localId}(remoteId=${c.json.Courseware.RemoteId || '无'})`).join('、')
+ '。为避免开错/覆盖错课件,请先用 localId 指定,或调用 remove_local_courseware 清理重复。');
}
return cw;
}
// ---------------------------------------------------------------- 文件 / XML
const readText = f => readFileSync(f, 'utf8');
const readJson = f => JSON.parse(readFileSync(f, 'utf8').replace(/^\uFEFF/, ''));
const readLines = f => {
const raw = readText(f);
return { lines: raw.split(/\r?\n/), eol: raw.includes('\r\n') ? '\r\n' : '\n' };
};
const writeLines = (f, lines, eol) => writeFileSync(f, lines.join(eol), 'utf8');
function writeJson(cw) {
writeFileSync(cw.jsonPath, '\uFEFF' + JSON.stringify(cw.json, null, 2), 'utf8');
}
export function slideRecords(cw) {
return cw.json.CoursewareFiles.filter(f => isSlidePath(f.RelativePath));
}
function boardRecord(cw) {
const rec = cw.json.CoursewareFiles.find(f => String(f.RelativePath).replace(/\//g, '\\') === 'Board.xml');
if (!rec) throw new Error(`课件「${cw.name}」没有 Board.xml 记录`);
return rec;
}
export function readBoard(cw) {
const rec = boardRecord(cw);
const xml = readText(path.join(cw.dir, rec.FileName));
const block = xml.match(/<Slides>([\s\S]*?)<\/Slides>/)?.[1] ?? '';
const ids = [...block.matchAll(/<Item>([0-9a-fA-F]{32})<\/Item>/g)].map(m => m[1]);
return { rec, file: path.join(cw.dir, rec.FileName), xml, ids };
}
const slideXmlId = xml => xml.match(/<Slide>\s*<Id>([0-9a-fA-F]{32})<\/Id>/)?.[1] ?? null;
/** 按 Board.xml 的页序返回 [{page, id, rec, file, xml}] */
export function slidesInBoardOrder(cw) {
const { ids } = readBoard(cw);
const byId = new Map();
for (const rec of slideRecords(cw)) {
const file = path.join(cw.dir, rec.FileName);
if (!existsSync(file)) continue;
const xml = readText(file);
const id = slideXmlId(xml);
if (id) byId.set(id.toLowerCase(), { rec, file, xml });
}
const out = [];
const missing = [];
ids.forEach((id, i) => {
const hit = byId.get(id.toLowerCase());
if (!hit) missing.push({ page: i + 1, id });
else out.push({ page: i + 1, id, ...hit });
});
if (missing.length) {
throw new Error(`页序表里有 ${missing.length} 页在索引中找不到对应 XML:${JSON.stringify(missing.slice(0, 5))}`);
}
return out;
}
export function slideAt(cw, page) {
const list = slidesInBoardOrder(cw);
if (!Number.isInteger(page) || page < 1 || page > list.length) {
throw new Error(`页码 ${page} 超出范围(1-${list.length})`);
}
return list[page - 1];
}
const blockRange = (lines, elementId) => {
const idIdx = lines.findIndex(l => l.trim() === `<Id>${elementId}</Id>`);
if (idIdx < 0) return null;
let start = idIdx;
while (start >= 0 && !/^ {4}<[A-Za-z]+>\s*$/.test(lines[start])) start--;
if (start < 0) return null;
const tag = lines[start].trim().replace(/[<>]/g, '');
let end = idIdx;
while (end < lines.length && lines[end].trim() !== `</${tag}>`) end++;
if (end >= lines.length) return null;
return { start, end, tag };
};
const unesc = s => String(s).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const elementText = body => {
const cands = [...body.matchAll(/<Text>([^<]*)<\/Text>/g)].map(m => unesc(m[1])).filter(t => t.trim());
cands.sort((a, b) => b.length - a.length);
return cands[0] ?? '';
};
/** 把 #RGB / #RRGGBB / #AARRGGBB 统一成希沃用的 #AARRGGBB */
function normalizeColor(value) {
if (value == null || value === '') return null;
let s = String(value).trim();
if (!s.startsWith('#')) s = '#' + s;
s = s.toUpperCase();
if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map(ch => ch + ch).join('');
if (/^#[0-9A-F]{6}$/.test(s)) return '#FF' + s.slice(1);
if (/^#[0-9A-F]{8}$/.test(s)) return s;
throw new Error(`颜色格式不支持:${value}(用 #RRGGBB 或 #AARRGGBB)`);
}
/** 粗略估算一行文字的像素宽度:中文按 1em,英文/数字按 0.55em */
function estimateTextWidth(text, fontSize) {
let units = 0;
for (const ch of String(text)) {
const code = ch.codePointAt(0);
if (ch === ' ') units += 0.5;
else if (code >= 0x2E80) units += 1;
else if (/[A-Za-z0-9]/.test(ch)) units += 0.55;
else units += 0.6;
}
return units * (Number(fontSize) || 28);
}
const textStyleOf = el => ({
fontSize: el?.fontSizes?.[0] ?? null,
bold: !!el?.bold,
color: el?.color ?? null,
align: el?.body?.match(/<TextAlignment>([^<]*)<\/TextAlignment>/)?.[1] ?? null,
width: el?.w ?? null,
});
/** page / pages / allPages 三种写法统一成页码数组 */
function selectedPagesFor(cw, { page, pages, allPages = false } = {}) {
const all = slidesInBoardOrder(cw);
if (allPages) return all.map(s => s.page);
if (Array.isArray(pages) && pages.length) {
const out = [...new Set(pages.map(Number))];
for (const n of out) {
if (!Number.isInteger(n) || n < 1 || n > all.length) {
throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
}
}
return out;
}
if (page == null) throw new Error('需要 page,或传 pages / allPages=true');
const n = Number(page);
if (!Number.isInteger(n) || n < 1 || n > all.length) {
throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
}
return [n];
}
/** 按新页序重写索引里的 Slides\Slide_N.xml 映射;被删页的记录直接丢弃 */
function reindexSlides(cw, ordered) {
const nonSlides = cw.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath));
ordered.forEach((s, i) => {
s.rec.RelativePath = `Slides\\Slide_${i}.xml`;
s.rec.FilePath = `${cw.localId}\\${s.rec.FileName}`;
});
cw.json.CoursewareFiles = [...nonSlides, ...ordered.map(s => s.rec)];
}
/** 按新页序重写 Board.xml 的 <Slides> 列表 */
function writeBoardOrder(cw, ordered) {
const board = readBoard(cw);
const xml = board.xml.replace(/<Slides>[\s\S]*?<\/Slides>/,
'<Slides>\n' + ordered.map(s => ` <Item>${s.id}</Item>`).join('\n') + '\n </Slides>');
writeFileSync(board.file, xml, 'utf8');
saveSlideRecord(cw, board.rec, board.file);
}
function inspectSlide(slide, { includeAnimations = true } = {}) {
const { lines } = readLines(slide.file);
const orders = parseOrders(lines);
const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1]));
const elements = listElements(lines).map(el => {
const anims = includeAnimations
? parseAnimations(el.body).map(a => ({ ...a, order: orderIndex.get(String(a.id).toLowerCase()) ?? null }))
: [];
const fontSize = el.fontSizes[0] ?? null;
const overflow = !!(fontSize && el.text && el.w > 0
&& estimateTextWidth(el.text, fontSize) > el.w * 1.05);
return {
id: el.id, type: el.type, text: el.text,
fontSize, fontSizes: el.fontSizes, bold: el.bold, color: el.color,
x: el.x, y: el.y, w: el.w, h: el.h,
blank: /_{3,}/.test(el.text),
animated: el.animated,
animations: anims,
overflow,
};
});
const textElements = elements.filter(e => e.type === 'Text' && e.text);
return {
page: slide.page, slideId: slide.id, file: path.basename(slide.file),
elementCount: elements.length,
textCount: textElements.length,
animationCount: elements.reduce((a, e) => a + e.animations.length, 0),
fontSizes: [...new Set(textElements.map(e => e.fontSize).filter(Boolean))].sort((a, b) => a - b),
clickOrder: orders,
warnings: elements.filter(e => e.overflow).map(e => `${e.id} 可能超宽:${e.text.slice(0, 40)}`),
elements,
};
}
function renderInspectText(result) {
const out = [];
if (result.matches?.length) {
out.push(`匹配「${result.query}」共 ${result.matches.length} 处:`);
for (const m of result.matches) {
out.push(` 第 ${m.page} 页 ${m.fontSize ?? '-'}px ${m.elementId} ${m.text.slice(0, 80)}`);
}
out.push('');
}
for (const p of result.items) {
out.push(`第 ${p.page} 页 ${p.file} 元素 ${p.elementCount} 文本 ${p.textCount} 动画 ${p.animationCount} 字号 ${p.fontSizes.join('/') || '-'}`);
for (const e of p.elements) {
if (!e.text && !e.animated) continue;
const flag = e.animated ? '[动画]' : '[ ]';
const size = e.fontSize == null ? ' - ' : String(e.fontSize).padStart(3) + 'px';
const body = e.text
? ` ${e.text.replace(/\s+/g, ' ').slice(0, 90)}`
: ` <${e.type}> x=${e.x} y=${e.y} w=${e.w} h=${e.h}`;
out.push(` ${flag} ${size} ${body}${e.overflow ? ' ⚠可能超宽' : ''}`);
}
}
return out.join('\n');
}
/** 重新导出给 inspect_courseware 使用 */
export function inspectCourseware({
courseware, page, pages, query, includeElements, includeAnimations = true, format = 'json',
} = {}) {
const cw = resolveCourseware(courseware);
const all = slidesInBoardOrder(cw);
let selected;
if (Array.isArray(pages) && pages.length) {
const nums = [...new Set(pages.map(Number))];
for (const n of nums) {
if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${n} 超出范围(1-${all.length})`);
}
selected = nums.map(n => all[n - 1]);
} else if (page != null) {
const n = Number(page);
if (!Number.isInteger(n) || n < 1 || n > all.length) throw new Error(`页码 ${page} 超出范围(1-${all.length})`);
selected = [all[n - 1]];
} else {
selected = all;
}
const showElements = includeElements ?? selected.length <= 2;
const items = selected.map(s => {
const item = inspectSlide(s, { includeAnimations });
if (!showElements) {
item.elements = item.elements.map(e => ({
id: e.id, type: e.type, text: e.text.slice(0, 120),
fontSize: e.fontSize, animated: e.animated, overflow: e.overflow,
}));
}
return item;
});
const hasQuery = query != null && String(query) !== '';
const matches = [];
if (hasQuery) {
const needle = String(query);
for (const s of all) {
const { lines } = readLines(s.file);
for (const el of listElements(lines)) {
if (el.text && el.text.includes(needle)) {
matches.push({
page: s.page, elementId: el.id, type: el.type, text: el.text,
fontSize: el.fontSizes[0] ?? null, x: el.x, y: el.y,
animated: el.animated,
});
}
}
}
}
const result = {
courseware: cw.name, localId: cw.localId, pages: all.length,
revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision,
inspectedPages: selected.map(s => s.page), items,
};
if (hasQuery) { result.query = String(query); result.matches = matches; }
if (format === 'text') {
return {
courseware: result.courseware, localId: result.localId, pages: result.pages,
revision: result.revision, syncedRevision: result.syncedRevision,
inspectedPages: result.inspectedPages, query: result.query,
matchCount: matches.length, text: renderInspectText(result),
};
}
return result;
}
/** 去掉默认文本属性 / 项目符号属性,只留真正渲染文本的 TextRun 属性 */
function textRunsBody(body) {
return String(body)
.replace(/<DefaultRunProperty>[\s\S]*?<\/DefaultRunProperty>/g, '')
.replace(/<TextMarkerStyle>[\s\S]*?<\/TextMarkerStyle>/g, '');
}
/** 在元素 XML 上改样式;DefaultRunProperty / TextMarkerStyle 原样保留 */
function applyStyleToXml(xml, opts) {
const keep = [];
const masked = xml.replace(/<(DefaultRunProperty|TextMarkerStyle)>[\s\S]*?<\/\1>/g, m => {
keep.push(m);
return `\u0000KEEP${keep.length - 1}\u0000`;
});
let out = masked;
if (opts.fontSize != null) {
out = out.replace(/<FontSize>[^<]*<\/FontSize>/g, `<FontSize>${opts.fontSize}</FontSize>`);
}
if (opts.bold != null) {
out = out.replace(/<FontWeight>[^<]*<\/FontWeight>/g, `<FontWeight>${opts.bold ? 'Bold' : 'Normal'}</FontWeight>`);
}
if (opts.color) {
out = out.replace(/(<Foreground>\s*<ColorBrush>)[^<]*(<\/ColorBrush>)/g, `$1${opts.color}$2`);
}
if (opts.align) {
out = out.replace(/<TextAlignment>[^<]*<\/TextAlignment>/g, `<TextAlignment>${opts.align}</TextAlignment>`);
}
if (opts.width != null) {
out = out.replace(/<Width>[^<]*<\/Width>/, `<Width>${opts.width}</Width>`);
}
return out.replace(/\u0000KEEP(\d+)\u0000/g, (m, i) => keep[Number(i)]);
}
export function listElements(lines) {
const out = [];
lines.forEach((l, i) => {
if (!/^ {4}<[A-Za-z]+>\s*$/.test(l)) return;
const tag = l.trim().replace(/[<>]/g, '');
let k = i + 1;
while (k < lines.length && lines[k].trim() !== `</${tag}>`) k++;
const body = lines.slice(i + 1, k).join('\n');
const id = body.match(/<Id>([0-9a-fA-F]{32})<\/Id>/)?.[1];
if (!id) return;
const styleBody = textRunsBody(body);
out.push({
id, type: tag, body,
x: Number(body.match(/<X>([^<]*)<\/X>/)?.[1]),
y: Number(body.match(/<Y>([^<]*)<\/Y>/)?.[1]),
w: Number(body.match(/<Width>([^<]*)<\/Width>/)?.[1]),
h: Number(body.match(/<Height>([^<]*)<\/Height>/)?.[1]),
fontSizes: [...new Set(
[...styleBody.matchAll(/<FontSize>([\d.]+)<\/FontSize>/g)]
.map(m => Number(m[1])).filter(n => Number.isFinite(n) && n > 0),
)],
bold: /<FontWeight>Bold<\/FontWeight>/.test(styleBody),
color: styleBody.match(/<Foreground>\s*<ColorBrush>(#[0-9A-Fa-f]{6,8})<\/ColorBrush>/)?.[1] ?? null,
text: elementText(body),
animated: body.includes('<Animations>'),
});
});
return out;
}
/** 给文本块写「固定框宽 + 单行折行」,避免只改 <Text> 后按旧折行渲染 */
function collapseLines(block, text, width) {
if (width != null) {
const wi = block.findIndex(l => /^\s*<Width>[^<]*<\/Width>$/.test(l));
if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}<Width>${width}</Width>`;
const sc = block.findIndex(l => /<SizeToContent>/.test(l));
if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*</, '>Manual<');
}
const ls = block.findIndex(l => l.trim() === '<Lines>');
const n = [...text].length;
if (ls >= 0) {
let le = ls;
while (le < block.length && block[le].trim() !== '</Lines>') le++;
block.splice(ls + 1, le - ls - 1,
' <LineProperty>',
' <StartOffset>0</StartOffset>',
` <Length>${n}</Length>`,
' </LineProperty>');
return;
}
for (let i = 0; i < block.length; i++) {
const m = block[i].match(/^(\s*)<Length>\d+<\/Length>$/);
if (m) { block[i] = `${m[1]}<Length>${n}</Length>`; break; }
}
}
// ---------------------------------------------------------------- 动画
const animNode = (id, o) => [
' <Animations>',
' <Animation>',
` <Type>${o.type}</Type>`,
` <Id>${id}</Id>`,
' <Number>1</Number>',
' <Category>Appearance</Category>',
` <Trigger>${o.trigger}</Trigger>`,
' <TriggerSource></TriggerSource>',
` <Duration>${Math.round(o.duration * 10000000)}</Duration>`,
` <Delay>${Math.round(o.delay * 10000000)}</Delay>`,
' <AccelerationRatio>1</AccelerationRatio>',
' <DecelerationRatio>0</DecelerationRatio>',
' <RepeatBehavior>1</RepeatBehavior>',
' <Start>0</Start>',
' <End>1</End>',
' </Animation>',
' </Animations>',
];
const ANIM_TYPES = ['FadeIn', 'FadeOut', 'WipeIn', 'WipeOut', 'ZoomIn', 'ZoomOut', 'FlyIn', 'FloatIn', 'Appear'];
const TRIGGERS = ['Click', 'WithPrevious', 'AfterPrevious'];
function stripAnimations(lines) {
const out = [];
for (let i = 0; i < lines.length; i++) {
const t = lines[i].trim();
if (t === '<Animations>' || t === '<AnimationOrders>') {
const close = t.replace('<', '</');
while (i < lines.length && lines[i].trim() !== close) i++;
continue;
}
out.push(lines[i]);
}
return out;
}
/** 重建 <AnimationOrders>:先删旧的,再按元素在页面里的先后重新排 */
function rebuildOrders(lines) {
const oStart = lines.findIndex(l => l.trim() === '<AnimationOrders>');
if (oStart >= 0) {
let oEnd = oStart;
while (oEnd < lines.length && lines[oEnd].trim() !== '</AnimationOrders>') oEnd++;
lines.splice(oStart, oEnd - oStart + 1);
}
const ids = [];
for (const el of listElements(lines)) {
const m = el.body.match(/<Animations>[\s\S]*?<Id>([0-9a-fA-F]{32})<\/Id>/);
if (m) ids.push(m[1]);
}
if (!ids.length) return ids;
const closeIdx = lines.map(l => l.trim()).lastIndexOf('</Slide>');
lines.splice(closeIdx, 0, ' <AnimationOrders>', ...ids.map(x => ` <Item>${x}</Item>`), ' </AnimationOrders>');
return ids;
}
function addAnimationToElement(lines, elementId, o) {
const r = blockRange(lines, elementId);
if (!r) return null;
const block = lines.slice(r.start, r.end + 1);
let replaced = 0;
const a = block.findIndex(l => l.trim() === '<Animations>');
if (a >= 0) {
let b = a;
while (b < block.length && block[b].trim() !== '</Animations>') b++;
replaced = 1;
block.splice(a, b - a + 1);
}
const animId = randomBytes(16).toString('hex');
let at = block.findIndex(l => l.trim() === '<HasMask>');
if (at < 0) at = block.findIndex(l => l.trim() === '<RotateOrigin>');
if (at < 0) at = block.length - 1;
block.splice(at, 0, ...animNode(animId, o));
lines.splice(r.start, r.end - r.start + 1, ...block);
return { animId, replaced };
}
function parseAnimations(body) {
const out = [];
for (const block of body.matchAll(/<Animations>([\s\S]*?)<\/Animations>/g)) {
for (const a of block[1].matchAll(/<Animation>([\s\S]*?)<\/Animation>/g)) {
const g = t => a[1].match(new RegExp(`<${t}>([^<]*)</${t}>`))?.[1];
out.push({
id: g('Id'), type: g('Type'), trigger: g('Trigger'),
duration: Number(g('Duration') || 0) / 1e7,
delay: Number(g('Delay') || 0) / 1e7,
});
}
}
return out;
}
function parseOrders(lines) {
const start = lines.findIndex(l => l.trim() === '<AnimationOrders>');
if (start < 0) return [];
let end = start;
while (end < lines.length && lines[end].trim() !== '</AnimationOrders>') end++;
return lines.slice(start + 1, end)
.map(l => l.match(/<Item>([0-9a-fA-F]{32})<\/Item>/)?.[1])
.filter(Boolean);
}
function resolveTargets(lines, { elementIds = [], textMatches = [], matchAll = false }) {
const els = listElements(lines).filter(e => e.type === 'Text' || e.type === 'Picture' || e.type === 'Shape');
const byId = new Map(els.map(e => [e.id, e]));
const picked = [];
const missing = [];
for (const id of elementIds) {
if (byId.has(id)) picked.push(byId.get(id));
else missing.push({ elementId: id, reason: '元素不存在' });
}
for (const needle of textMatches) {
const hits = els.filter(e => e.text && e.text.includes(needle));
if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' });
else if (hits.length > 1 && !matchAll) {
throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请改用 elementIds:`
+ hits.map(h => `${h.id}(${h.text.slice(0, 20)})`).join(' | '));
} else picked.push(...hits);
}
return { targets: [...new Map(picked.map(e => [e.id, e])).values()], missing };
}
function applyCustomOrder(lines, elementOrder = []) {
if (!elementOrder.length) return;
const els = listElements(lines);
const animOf = new Map();
for (const el of els) {
const m = el.body.match(/<Animations>[\s\S]*?<Id>([0-9a-fA-F]{32})<\/Id>/);
if (m) animOf.set(el.id, m[1]);
}
const current = parseOrders(lines);
const desired = elementOrder.map(id => animOf.get(id)).filter(Boolean);
const rest = current.filter(x => !desired.includes(x));
const next = [...desired, ...rest];
const start = lines.findIndex(l => l.trim() === '<AnimationOrders>');
if (start < 0) return;
let end = start;
while (end < lines.length && lines[end].trim() !== '</AnimationOrders>') end++;
lines.splice(start, end - start + 1, ' <AnimationOrders>', ...next.map(x => ` <Item>${x}</Item>`), ' </AnimationOrders>');
}
// ---------------------------------------------------------------- 数据库
const dbPathOf = cw => path.join(cw.userDir, 'Courseware', 'CoursewareCacheData.db');
function withDb(cw, fn, { write = false } = {}) {
const p = dbPathOf(cw);
if (!existsSync(p)) return null;
let db;
try {
db = new DatabaseSync(p, { readOnly: !write });
return fn(db);
} finally {
try { db?.close(); } catch { /* ignore */ }
}
}
export function readDbRow(cw) {
return withDb(cw, db => db.prepare(
'select LocalId,RemoteId,Name,UpdateTime,Size,LocalRevision,SyncedRevision,Hash,Files from Courseware where LocalId=?',
).get(cw.localId) ?? null);
}
function writeDb(cw) {
return withDb(cw, db => {
const j = cw.json;
const localId = cw.localId;
db.exec('BEGIN');
try {
db.prepare('delete from CoursewareFile where FileRelativePath like ?').run(localId + '\\%');
const ins = db.prepare(
'insert into CoursewareFile (FileId,FileHash,FileName,FileSize,FileRelativePath,DocumentRelativePath,FileIntValueOne) values (?,?,?,?,?,?,0)',
);
for (const f of j.CoursewareFiles) {
ins.run(f.FileId, f.FileHash, f.FileName, f.FileSize, localId + '\\' + f.FileName, f.RelativePath);
}
db.prepare('update Courseware set Name=?,RemoteId=?,UpdateTime=?,Size=?,LocalRevision=?,SyncedRevision=?,Files=? where LocalId=?')
.run(j.Courseware.Name, j.Courseware.RemoteId, j.Courseware.UpdateTime, j.Courseware.Size,
j.Courseware.Revision, j.Courseware.SyncedRevision, j.Courseware.Files, localId);
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
throw e;
}
return true;
}, { write: true });
}
/** 写回索引 + DB:重算 Size/Files,Revision 取 JSON 与 DB 的较大值再 +1 */
function finalize(cw) {
const j = cw.json;
j.CoursewareFiles = j.CoursewareFiles.filter(f => f && f.FileId && f.FileName);
j.Courseware.Files = j.CoursewareFiles.map(f => f.FileId).join(';') + ';';
j.Courseware.Size = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0);
const dbRow = readDbRow(cw);
const base = Math.max(j.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0);
j.Courseware.Revision = base + 1;
j.Courseware.SyncedRevision = Math.min(
j.Courseware.Revision - 1,
Math.max(j.Courseware.SyncedRevision ?? 0, dbRow?.SyncedRevision ?? 0),
);
j.Courseware.UpdateTime = Date.now();
writeJson(cw);
writeDb(cw);
}
const saveSlideRecord = (cw, rec, file) => {
const buf = readFileSync(file);
rec.FileHash = md5(buf);
rec.FileSize = buf.length;
};
// ---------------------------------------------------------------- 备份
function backupManifestPath(dir) { return path.join(dir, 'manifest.json'); }
export function backupCourseware({ courseware, note = '' } = {}) {
const cw = resolveCourseware(courseware);
const id = `${cw.localId}-${stamp()}`;
const dir = path.join(BACKUP_ROOT, id);
mkdirSync(dir, { recursive: true });
const warnings = [];
for (const f of cw.json.CoursewareFiles) {
const src = path.join(cw.dir, f.FileName);
if (!existsSync(src)) { warnings.push(`缺文件:${f.FileName}`); continue; }
copyFileSync(src, path.join(dir, f.FileName));
}
copyFileSync(cw.jsonPath, path.join(dir, 'index.json'));
const manifest = {
id, createdAt: new Date().toISOString(), note,
localId: cw.localId, remoteId: cw.json.Courseware.RemoteId,
name: cw.name,
revision: cw.json.Courseware.Revision,
syncedRevision: cw.json.Courseware.SyncedRevision,
size: cw.json.Courseware.Size,
dbRow: readDbRow(cw),
files: cw.json.CoursewareFiles.map(f => ({
FileId: f.FileId, FileName: f.FileName, FileHash: f.FileHash,
FileSize: f.FileSize, RelativePath: f.RelativePath,
})),
warnings,
};
writeFileSync(backupManifestPath(dir), JSON.stringify(manifest, null, 2), 'utf8');
// 只保留最近 N 份
const siblings = readdirSync(BACKUP_ROOT)
.filter(n => n.startsWith(cw.localId + '-'))
.sort();
for (const old of siblings.slice(0, Math.max(0, siblings.length - MAX_BACKUPS))) {
rmSync(path.join(BACKUP_ROOT, old), { recursive: true, force: true });
}
return { backupId: id, dir, files: manifest.files.length, warnings };
}
function resolveBackup(backupId) {
const raw = String(backupId || '').trim();
if (!raw) throw new Error('缺少 backupId');
let dir = raw;
if (!path.isAbsolute(raw)) dir = path.join(BACKUP_ROOT, raw);
if (!existsSync(dir)) throw new Error(`找不到备份:${raw}`);
const mf = backupManifestPath(dir);
if (!existsSync(mf)) throw new Error(`备份缺少 manifest.json:${dir}`);
return { dir, manifest: readJson(mf) };
}
/** 列出备份快照,可按课件过滤;restore_courseware 的 backupId 就从这里取 */
export function listBackups({ courseware, limit = 50 } = {}) {
const localId = courseware ? resolveCourseware(courseware).localId : null;
let names = [];
try { names = readdirSync(BACKUP_ROOT); } catch { names = []; }
const items = [];
for (const name of names) {
if (localId && !name.startsWith(localId + '-')) continue;
const dir = path.join(BACKUP_ROOT, name);
const mf = backupManifestPath(dir);
if (!existsSync(mf)) continue;
try {
const m = readJson(mf);
items.push({
backupId: name, dir,
createdAt: m.createdAt, note: m.note,
name: m.name, localId: m.localId, remoteId: m.remoteId,
revision: m.revision, syncedRevision: m.syncedRevision, size: m.size,
files: Array.isArray(m.files) ? m.files.length : null,
pages: Array.isArray(m.files) ? m.files.filter(f => isSlidePath(f.RelativePath)).length : null,
warnings: m.warnings ?? [],
});
} catch { /* 跳过坏 manifest */ }
}
items.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))
|| String(b.backupId).localeCompare(String(a.backupId)));
const n = Math.max(1, Number(limit) || 50);
return { count: items.length, backups: items.slice(0, n) };
}
// ---------------------------------------------------------------- 关/开/同步
function sameCourseware(shell, cw) {
const n = String(shell.coursewareName || '').trim();
return n === cw.name.trim();
}
/**
* 找出属于这份课件的 shell。
* 如果本地存在同名副本,仅靠名字会匹配错,这时再用 remoteId 逐个核对。
*/
async function shellsForCourseware(cw) {
const list = await shells();
const sameName = list.filter(s => sameCourseware(s, cw));
if (!sameName.length) return [];
if (!duplicatesOf(listCoursewares(), cw).length) return sameName;
const want = String(cw.json?.Courseware?.RemoteId ?? '').toLowerCase();
if (!want) {
throw new Error(
`课件「${cw.name}」存在同名副本,且目标课件没有 RemoteId,无法判断该操作哪个窗口。`
+ '请手动关闭课件后重试,或先清理重复副本。',
);
}
const out = [];
for (const s of sameName) {
const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null);
const rid = String(info?.data?.remoteId ?? '').toLowerCase();
if (rid === want) out.push(s);
}
return out;
}
/**
* 等课件真正加载完:希沃刚打开云端课件时,get_current_courseware_info 会先返回 1 页,
* 直接拿它和磁盘比较会被误判成「有未同步改动」。这里轮询到页数与磁盘一致,
* 或页数连续稳定且不少于磁盘页数(用户本地新增了页)为止。
*/
async function waitCoursewareLoaded(shellId, expectedPages, { timeoutMs = 25000 } = {}) {
const deadline = Date.now() + timeoutMs;
let last = null;
let stable = 0;
while (Date.now() < deadline) {
let info = null;
try {
info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 });
} catch {
// 单次查询超时 / 界面暂时无响应:继续等,别把它当成 0 页
await sleep(800);
continue;
}
const d = info?.data ?? {};
if (typeof d.slideCount === 'number') {
if (d.slideCount === expectedPages) return { loaded: true, info: d };
if (last && d.slideCount === last.slideCount) stable++;
else stable = 0;
last = d;
if (stable >= 2 && d.slideCount > expectedPages) return { loaded: true, info: d };
}
await sleep(500);
}
return { loaded: false, info: last ?? {} };
}
async function closeForWrite(cw, force) {
await ensureInit();
const open = await shellsForCourseware(cw);
if (!open.length) return { wasOpen: false, closed: 0 };
const diskPages = slideRecords(cw).length;
const diskSize = cw.json.Courseware.Size;
for (const s of open) {
// 先切回备课界面:授课模式下页面列表可能还没就绪,get_current_courseware_info 会卡住或返回 0 页
await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {});
await sleep(600);
let { loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages);
if (!loaded) {
// 再给一次机会:重新切界面后再等
await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {});
await sleep(1000);
({ loaded, info: d } = await waitCoursewareLoaded(s.id, diskPages));
}
if (!loaded && (d.slideCount ?? 0) <= 1 && diskPages > 1) {
throw new Error(
`课件「${cw.name}」还没加载完成(当前只看到 ${d.slideCount ?? 0} 页 / 磁盘 ${diskPages} 页)。`
+ '请等希沃界面显示完整后再试,或传 force=true 忽略检查。',
);
}
const bad = [];
if (typeof d.slideCount === 'number' && d.slideCount !== diskPages) {
bad.push(`内存 ${d.slideCount} 页 / 磁盘 ${diskPages} 页`);
}
if (typeof d.size === 'number' && d.size !== diskSize) {
bad.push(`内存 ${d.size} 字节 / 磁盘 ${diskSize} 字节`);
}
if (bad.length && !force) {
throw new Error(
`课件「${cw.name}」有未同步的内存改动(${bad.join(';')})。`
+ '请先用 seewo 的 sync_current_courseware 同步,或传 force=true 丢弃这些改动。',
);
}
}
for (const s of open) {
await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {});
}
let stillOpen = true;
for (let i = 0; i < 20; i++) {
await sleep(500);
stillOpen = (await shellsForCourseware(cw)).length > 0;
if (!stillOpen) break;
}
if (stillOpen) {
throw new Error(
`课件「${cw.name}」关闭失败(希沃界面可能卡住),已中止写操作以免内存内容覆盖磁盘。`
+ '请手动关闭课件或重启希沃后重试。',
);
}
return { wasOpen: true, closed: open.length };
}
async function openCourseware(cwOrName, expectedPages = null) {
await ensureInit();
const cw = typeof cwOrName === 'string' ? resolveCourseware(cwOrName) : cwOrName;
const name = cw.name;
let s = (await shells()).find(x => String(x.coursewareName || '').trim() === name.trim());
for (let attempt = 0; attempt < 2 && !s; attempt++) {
await mcp('open_cloud_courseware', { coursewareName: name }).catch(() => {});
for (let i = 0; i < 20; i++) {
await sleep(700);
s = (await shells()).find(x => String(x.coursewareName || '').trim() === name.trim());
if (s) break;
}
}
if (!s) return null;
// 同名副本时用 remoteId 核对,防止打开/同步到另一份
const want = String(cw.json?.Courseware?.RemoteId ?? '').toLowerCase();
if (want) {
const info = await mcp('get_current_courseware_info', { shellId: s.id }, { timeoutMs: 12000 }).catch(() => null);
const got = String(info?.data?.remoteId ?? '').toLowerCase();
if (got && got !== want) {
await mcp('close_current_courseware', { shellId: s.id, syncBeforeClose: false }).catch(() => {});
throw new Error(
`打开到的是另一份同名课件(云端 ${got},期望 ${want})。`
+ '请先在希沃里删除多余副本,或改用正确的 localId。',
);
}
}
if (expectedPages != null) await waitCoursewareLoaded(s.id, expectedPages);
await mcp('en_goto_app_ui', { ui: 'Edit', shellId: s.id }).catch(() => {});
return s.id;
}
/** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */
async function touch(shellId) {
const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 15000 }).catch(() => null);
const count = info?.data?.slideCount ?? 0;
if (!count) return;
const add = await mcp('add_slide', { shellId, slideNumber: count }).catch(() => null);
const added = add?.data?.slideNumber;
if (added) {
await mcp('delete_slide', { shellId, slideNumber: added }).catch(() => {});
}
}
/** 轮询到备课(Edit)界面。刚打开的课件常常还停留在 Display。 */
async function ensureEditMode(shellId, { timeoutMs = 20000 } = {}) {
const deadline = Date.now() + timeoutMs;
let mode = null;
let tries = 0;
while (Date.now() < deadline) {
const info = await mcp('get_current_courseware_info', { shellId }, { timeoutMs: 12000 }).catch(() => null);
mode = info?.data?.shellContext?.workingMode ?? mode;
if (mode === 'Edit') return true;
if (tries % 2 === 0) await mcp('en_goto_app_ui', { ui: 'Edit', shellId }).catch(() => {});
tries++;
await sleep(700);
}
return mode === 'Edit';
}
async function syncShell(shellId) {
const opts = { timeoutMs: 180000 };
const push = () => mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts)
.catch(e => ({ text: 'ERR ' + e.message }));
await ensureEditMode(shellId);
await touch(shellId);
let r = await push();
// 刚打开的课件偶尔还没真正进入备课界面,重试几轮
for (let i = 0; i < 3 && /备课界面|Edit|必须/.test(String(r.text)); i++) {
await ensureEditMode(shellId);
await sleep(800);
await touch(shellId);
r = await push();
}
if (String(r.text).includes('下载')) {
await touch(shellId);
r = await push();
}
return r.text;
}
// 串行化写操作,避免两个工具同时开/关课件
let chain = Promise.resolve();
function serial(fn) {
const p = chain.then(fn, fn);
chain = p.catch(() => {});
return p;
}
async function runEdit(cw, opts, action) {
return serial(async () => {
const { wasOpen, closed } = await closeForWrite(cw, opts.force);
const backup = opts.backup === false ? null : backupCourseware({ courseware: cw.localId, note: 'auto-before-write' });
let result;
try {
result = await action(cw);
finalize(cw);
} catch (e) {
e.message += backup ? `\n(改动前备份:${backup.backupId})` : '';
throw e;
}
let shellId = null;
let syncText = null;
if (opts.reopen !== false) {
shellId = await openCourseware(cw, slideRecords(cw).length);
if (opts.sync && shellId) syncText = await syncShell(shellId);
}
return {
...result,
backupId: backup?.backupId ?? null,
wasOpen, closed,
reopened: !!shellId,
shellId,
sync: syncText,
};
});
}
// ---------------------------------------------------------------- 工具:动画
export async function setAnimations({
courseware, page, elementIds = [], textMatches = [], matchAll = false,
type = 'FadeIn', trigger = 'Click', duration = 0.3, delay = 0, order = [],
reopen = true, sync = false, force = false, backup = true,
} = {}) {
const cw = resolveCourseware(courseware);
if (!ANIM_TYPES.includes(type)) throw new Error(`type 只能是:${ANIM_TYPES.join(' / ')}`);
if (!TRIGGERS.includes(trigger)) throw new Error(`trigger 只能是:${TRIGGERS.join(' / ')}`);
const o = { type, trigger, duration: Number(duration), delay: Number(delay) };
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const { file, rec } = slideAt(c, page);
const { lines, eol } = readLines(file);
const { targets, missing } = resolveTargets(lines, { elementIds, textMatches, matchAll });
if (!targets.length) throw new Error('没有匹配到任何元素' + (missing.length ? `:${JSON.stringify(missing)}` : ''));
let replaced = 0;
const added = [];
for (const t of targets) {
const r = addAnimationToElement(lines, t.id, o);
if (r) { replaced += r.replaced; added.push({ elementId: t.id, animationId: r.animId, text: t.text.slice(0, 30) }); }
else missing.push({ elementId: t.id, reason: '写动画失败' });
}
rebuildOrders(lines);
applyCustomOrder(lines, order);
writeLines(file, lines, eol);
saveSlideRecord(c, rec, file);
return { courseware: c.name, page, added, replaced, missing, order: parseOrders(lines), options: o };
});
}
export function getAnimations({ courseware, page } = {}) {
const cw = resolveCourseware(courseware);
const { lines } = readLines(slideAt(cw, page).file);
const orders = parseOrders(lines);
const orderIndex = new Map(orders.map((id, i) => [id.toLowerCase(), i + 1]));
const elements = [];
const known = new Set();
for (const el of listElements(lines)) {
const anims = parseAnimations(el.body);
if (!anims.length) continue;
for (const a of anims) {
if (a.id) known.add(a.id.toLowerCase());
elements.push({
elementId: el.id, elementType: el.type, text: el.text.slice(0, 60),
x: el.x, y: el.y,
...a,
order: orderIndex.get(String(a.id).toLowerCase()) ?? null,
});
}
}
const issues = [];
for (const e of elements) if (e.order == null) issues.push(`动画 ${e.id} 不在 AnimationOrders 里,不会播放`);
for (const id of orders) if (!known.has(id.toLowerCase())) issues.push(`AnimationOrders 里的 ${id} 找不到对应动画`);
return { courseware: cw.name, page, count: elements.length, order: orders, elements, issues };
}
export async function clearAnimations({
courseware, page, allPages = false, elementIds = [],
reopen = true, sync = false, force = false, backup = true,
} = {}) {
const cw = resolveCourseware(courseware);
if (!allPages && !Number.isInteger(Number(page))) throw new Error('需要 page,或传 allPages=true');
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const pages = allPages ? slidesInBoardOrder(c).map(s => s.page) : [Number(page)];
const report = [];
for (const n of pages) {
const { file, rec } = slideAt(c, n);
const { lines, eol } = readLines(file);
const before = (lines.join('\n').match(/<Animations>/g) ?? []).length;
let out;
if (!elementIds.length) {
out = stripAnimations(lines);
} else {
out = lines;
for (const id of elementIds) {
const r = blockRange(out, id);
if (!r) continue;
const block = out.slice(r.start, r.end + 1);
const a = block.findIndex(l => l.trim() === '<Animations>');
if (a >= 0) {
let b = a;
while (b < block.length && block[b].trim() !== '</Animations>') b++;
block.splice(a, b - a + 1);
out.splice(r.start, r.end - r.start + 1, ...block);
}
}
}
const orders = rebuildOrders(out);
writeLines(file, out, eol);
saveSlideRecord(c, rec, file);
report.push({ page: n, before, after: orders.length, cleared: Math.max(0, before - orders.length) });
}
return { courseware: c.name, pages: report };
});
}
// ---------------------------------------------------------------- 工具:改文字
function replaceOneElement(lines, el, spec) {
if (spec.text == null && spec.find == null) {
return { missing: { elementId: el.id, reason: '需要 text 或 find' } };
}
const r = blockRange(lines, el.id);
if (!r) return { missing: { elementId: el.id, reason: '元素块定位失败' } };
const block = lines.slice(r.start, r.end + 1);
const before = elementText(block.join('\n'));
let after;
if (spec.text != null) {
after = String(spec.text);
const nonEmpty = new Set([...block.join('\n').matchAll(/<Text>([^<]*)<\/Text>/g)]
.map(m => unesc(m[1])).filter(Boolean));
if (nonEmpty.size > 1) {
throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`);
}
const oldTag = `<Text>${esc(before)}</Text>`;
for (let i = 0; i < block.length; i++) {
if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`<Text>${esc(after)}</Text>`);
}
} else {
const find = String(spec.find);
const rep = String(spec.replace ?? '');
if (!before.includes(find)) return { missing: { elementId: el.id, reason: `文本里没有「${find}」` } };
after = before.split(find).join(rep);
for (let i = 0; i < block.length; i++) {
block[i] = block[i].replace(/<Text>([^<]*)<\/Text>/g, (m, t) => {
const plain = unesc(t);
return plain.includes(find) ? `<Text>${esc(plain.split(find).join(rep))}</Text>` : m;
});
}
}
if (spec.width != null) collapseLines(block, after, Number(spec.width));
else collapseLines(block, after);
lines.splice(r.start, r.end - r.start + 1, ...block);
return { change: { elementId: el.id, before, after, find: spec.find ?? null } };
}
function applyReplacements(lines, replacements, { matchAll = false } = {}) {
const changes = [];
const missing = [];
for (const spec of replacements) {
if (spec.elementId) {
const el = listElements(lines).find(e => e.id === spec.elementId);
if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; }
const r = replaceOneElement(lines, el, spec);
if (r.change) changes.push(r.change); else missing.push(r.missing);
continue;
}
if (spec.find) {
const hits = listElements(lines).filter(e => e.type === 'Text' && e.text.includes(spec.find));
if (!hits.length) { missing.push({ find: spec.find, reason: '没有文本含这段文字' }); continue; }
if (hits.length > 1 && !matchAll) {
throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:`
+ hits.map(h => h.id).join(', '));
}
for (const el of (matchAll ? hits : [hits[0]])) {
const r = replaceOneElement(lines, el, spec);
if (r.change) changes.push(r.change); else missing.push(r.missing);
}
continue;
}
missing.push({ reason: '需要 elementId 或 find' });
}
return { changes, missing };
}
/** 多页时把「这一页没找到」的噪音去掉;真正一次都没命中的才保留 */
function pruneMissing(missing, changes) {
const foundIds = new Set(changes.map(c => c.elementId));
const foundFinds = new Set(changes.map(c => c.find).filter(Boolean));
const seen = new Set();
return missing.filter(m => {
if (m.elementId && foundIds.has(m.elementId)) return false;
if (m.find && foundFinds.has(m.find)) return false;
const key = m.elementId ? `id:${m.elementId}` : m.find ? `find:${m.find}` : `reason:${m.reason}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
export async function replaceText({
courseware, page, pages, allPages = false, replacements = [], matchAll = false, dryRun = false,
reopen = true, sync = false, force = false, backup = true,
} = {}) {
const cw = resolveCourseware(courseware);
if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空');
const pageNumbers = selectedPagesFor(cw, { page, pages, allPages });
if (dryRun) {
const allChanges = [];
const allMissing = [];
const reports = [];
for (const n of pageNumbers) {
const { lines } = readLines(slideAt(cw, n).file);
const { changes, missing } = applyReplacements(lines, replacements, { matchAll });
reports.push({ page: n, changes, missing });
allChanges.push(...changes.map(c => ({ page: n, ...c })));
allMissing.push(...missing.map(m => ({ page: n, ...m })));
}
return {
courseware: cw.name, dryRun: true,
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
changes: allChanges,
missing: pruneMissing(allMissing, allChanges),
...(pageNumbers.length === 1 ? {} : { reports }),
};
}
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const allChanges = [];
const allMissing = [];
const reports = [];
for (const n of pageNumbers) {
const { file, rec } = slideAt(c, n);
const { lines, eol } = readLines(file);
const { changes, missing } = applyReplacements(lines, replacements, { matchAll });
if (changes.length) {
writeLines(file, lines, eol);
saveSlideRecord(c, rec, file);
}
reports.push({ page: n, changes, missing });
allChanges.push(...changes.map(x => ({ page: n, ...x })));
allMissing.push(...missing.map(x => ({ page: n, ...x })));
}
return {
courseware: c.name,
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
changes: allChanges,
missing: pruneMissing(allMissing, allChanges),
...(pageNumbers.length === 1 ? {} : { reports }),
};
});
}
// ---------------------------------------------------------------- 工具:改样式
export async function setTextStyle({
courseware, page, pages, allPages = false,
elementIds = [], textMatches = [], matchAll = false,
fontSize, bold, color, align, width, dryRun = false,
reopen = true, sync = false, force = false, backup = true,
} = {}) {
const cw = resolveCourseware(courseware);
const pageNumbers = selectedPagesFor(cw, { page, pages, allPages });
const opts = {
elementIds, textMatches, matchAll,
fontSize: fontSize == null ? null : Number(fontSize),
bold: bold == null ? null : !!bold,
color: color == null || color === '' ? null : normalizeColor(color),
align: align == null || align === '' ? null : String(align),
width: width == null ? null : Number(width),
};
if (opts.fontSize != null && (!Number.isFinite(opts.fontSize) || opts.fontSize <= 0)) {
throw new Error('fontSize 必须是正数');
}
if (opts.width != null && (!Number.isFinite(opts.width) || opts.width <= 0)) {
throw new Error('width 必须是正数');
}
if (opts.align && !['Left', 'Center', 'Right'].includes(opts.align)) {
throw new Error('align 只能是:Left / Center / Right');
}
if (opts.fontSize == null && opts.bold == null && opts.color == null && opts.align == null && opts.width == null) {
throw new Error('至少要传一个样式参数:fontSize / bold / color / align / width');
}
const applyPage = lines => {
const els = listElements(lines).filter(e => e.type === 'Text');
const picked = [];
const missing = [];
if (elementIds.length) {
const byId = new Map(els.map(e => [e.id, e]));
for (const id of elementIds) {
const el = byId.get(id);
if (el) picked.push(el); else missing.push({ elementId: id, reason: '元素不存在' });
}
}
if (textMatches.length) {
for (const needle of textMatches) {
const hits = els.filter(e => e.text.includes(needle));
if (!hits.length) missing.push({ text: needle, reason: '没有文本含这段文字' });
else if (hits.length > 1 && !matchAll) {
throw new Error(`「${needle}」匹配到 ${hits.length} 个元素,请加 elementId 或 matchAll=true:`
+ hits.map(h => h.id).join(', '));
} else picked.push(...(matchAll ? hits : [hits[0]]));
}
}
if (!elementIds.length && !textMatches.length) picked.push(...els);
const targets = [...new Map(picked.map(e => [e.id, e])).values()];
const changes = [];
for (const el of targets) {
const r = blockRange(lines, el.id);
if (!r) { missing.push({ elementId: el.id, reason: '元素块定位失败' }); continue; }
const block = lines.slice(r.start, r.end + 1);
const before = textStyleOf(el);
const nextBlock = applyStyleToXml(block.join('\n'), opts).split('\n');
collapseLines(nextBlock, el.text, opts.width ?? undefined);
lines.splice(r.start, r.end - r.start + 1, ...nextBlock);
const updated = listElements(lines).find(e => e.id === el.id) ?? el;
const after = textStyleOf(updated);
const textWidth = estimateTextWidth(el.text, after.fontSize ?? before.fontSize ?? 28);
changes.push({
elementId: el.id, text: el.text.slice(0, 60), before, after,
estimatedWidth: Math.round(textWidth),
overflow: after.width != null && textWidth > after.width * 1.05,
});
}
return { changes, missing };
};
if (dryRun) {
const allChanges = [];
const allMissing = [];
const reports = [];
for (const n of pageNumbers) {
const { lines } = readLines(slideAt(cw, n).file);
const { changes, missing } = applyPage(lines);
reports.push({ page: n, changes, missing });
allChanges.push(...changes.map(c => ({ page: n, ...c })));
allMissing.push(...missing.map(m => ({ page: n, ...m })));
}
return {
courseware: cw.name, dryRun: true,
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
changes: allChanges,
missing: pruneMissing(allMissing, allChanges),
...(pageNumbers.length === 1 ? {} : { reports }),
};
}
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const allChanges = [];
const allMissing = [];
const reports = [];
for (const n of pageNumbers) {
const { file, rec } = slideAt(c, n);
const { lines, eol } = readLines(file);
const { changes, missing } = applyPage(lines);
if (changes.length) {
writeLines(file, lines, eol);
saveSlideRecord(c, rec, file);
}
reports.push({ page: n, changes, missing });
allChanges.push(...changes.map(x => ({ page: n, ...x })));
allMissing.push(...missing.map(x => ({ page: n, ...x })));
}
return {
courseware: c.name,
...(pageNumbers.length === 1 ? { page: pageNumbers[0] } : { pages: pageNumbers }),
changes: allChanges,
missing: pruneMissing(allMissing, allChanges),
...(pageNumbers.length === 1 ? {} : { reports }),
};
});
}
// ---------------------------------------------------------------- 工具:校验
export function verifyCourseware({ courseware, hashes = true, deep = true } = {}) {
const cw = resolveCourseware(courseware);
const issues = [];
const add = (level, code, message, extra = {}) => issues.push({ level, code, message, ...extra });
const j = cw.json;
let board = null;
try { board = readBoard(cw); } catch (e) { add('error', 'board-missing', e.message); }
const slides = slideRecords(cw);
const ids = [];
const seenSlideIds = new Map();
const elementOwner = new Map();
const animCounts = new Map();
for (const rec of slides) {
const file = path.join(cw.dir, rec.FileName);
if (!existsSync(file)) { add('error', 'slide-file-missing', `索引里的页面文件不存在:${rec.FileName}`, { relativePath: rec.RelativePath }); continue; }
const buf = readFileSync(file);
if (hashes) {
if (buf.length !== rec.FileSize) add('error', 'slide-size-mismatch', `${rec.RelativePath} 大小不符:索引 ${rec.FileSize} / 实际 ${buf.length}`);
const h = md5(buf);
if (h !== rec.FileHash) add('error', 'slide-hash-mismatch', `${rec.RelativePath} MD5 不符`, { expected: rec.FileHash, actual: h });
}
const xml = buf.toString('utf8');
animCounts.set(rec.FileName, (xml.match(/<Animation>/g) || []).length);
const id = slideXmlId(xml);
if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 <Id>`); continue; }
ids.push({ rec, id });
if (seenSlideIds.has(id)) add('error', 'duplicate-slide-id', `页面 Id 重复:${id}`);
else seenSlideIds.set(id, rec.RelativePath);
if (deep) {
for (const m of xml.matchAll(/<Id>([0-9a-fA-F]{32})<\/Id>/g)) {
const eid = m[1].toLowerCase();
if (eid === id.toLowerCase()) continue;
if (elementOwner.has(eid)) {
add('warn', 'duplicate-element-id', `元素 Id ${eid} 同时出现在 ${elementOwner.get(eid)} 和 ${rec.RelativePath}`);
} else elementOwner.set(eid, rec.RelativePath);
}
}
}
if (board) {
const idToRec = new Map(ids.map(x => [x.id.toLowerCase(), x.rec]));
if (board.ids.length !== slides.length) {
add('error', 'page-count-mismatch', `Board.xml 有 ${board.ids.length} 页,索引有 ${slides.length} 页`);
}
board.ids.forEach((id, i) => {
const rec = idToRec.get(id.toLowerCase());
if (!rec) {
add('error', 'board-page-missing', `Board.xml 第 ${i + 1} 页的 Id ${id} 在索引里找不到`);
return;
}
const expect = `Slides\\Slide_${i}.xml`;
if (String(rec.RelativePath).replace(/\//g, '\\').toLowerCase() !== expect.toLowerCase()) {
add('warn', 'page-order-mismatch', `第 ${i + 1} 页在索引里是 ${rec.RelativePath},与页序不一致`);
}
});
const inBoard = new Set(board.ids.map(x => x.toLowerCase()));
for (const x of ids) if (!inBoard.has(x.id.toLowerCase())) add('error', 'page-not-in-board', `${x.rec.RelativePath} 不在 Board.xml 的页序里(会显示不出来)`);
}
// 索引 / 资源 / 孤儿文件
const byName = new Map();
for (const f of j.CoursewareFiles) {
const file = path.join(cw.dir, f.FileName);
if (!existsSync(file)) { add('error', 'file-missing', `索引文件不存在:${f.FileName}`); continue; }
const size = statSync(file).size;
if (size !== f.FileSize) add('error', 'file-size-mismatch', `${f.FileName} 大小不符(索引 ${f.FileSize} / 实际 ${size})`);
if (hashes && f.FileHash) {
const h = md5File(file);
if (h !== f.FileHash) add('error', 'file-hash-mismatch', `${f.FileName} MD5 不符`);
}
byName.set(f.FileName, f);
}
const sum = j.CoursewareFiles.reduce((a, f) => a + (f.FileSize || 0), 0);
if (sum !== j.Courseware.Size) add('warn', 'size-sum-mismatch', `Courseware.Size=${j.Courseware.Size},文件合计=${sum}`);
const refRec = j.CoursewareFiles.find(
f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml',
);
let refIds = null;
if (refRec) {
const rf = path.join(cw.dir, refRec.FileName);
if (existsSync(rf)) {
refIds = new Set([...readText(rf).matchAll(/<Id>([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase()));
}
}
for (const slide of slides) {
const file = path.join(cw.dir, slide.FileName);
if (!existsSync(file)) continue;
const xml = readText(file);
for (const m of xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)) {
const rid = m[1].toLowerCase();
const rec = j.CoursewareFiles.find(f => {
const n = f.FileName.toLowerCase();
return n === rid || n.startsWith(rid + '.');
});
if (!rec) add('error', 'resource-missing', `${slide.RelativePath} 引用的资源 ${rid} 不在索引里`);
else if (!existsSync(path.join(cw.dir, rec.FileName))) add('error', 'resource-file-missing', `${slide.RelativePath} 引用的资源文件不存在:${rec.FileName}`);
if (refIds && !refIds.has(rid)) {
add('error', 'resource-not-referenced', `${slide.RelativePath} 的资源 ${rid} 没有登记在 Reference.xml(会显示成占位图)`);
}
}
}
const referenced = new Set(j.CoursewareFiles.map(f => f.FileName));
const metaFiles = new Set([`${cw.localId}.json`, 'CoursewareSourceTrace.json']);
const orphans = readdirSync(cw.dir).filter(n => {
const p = path.join(cw.dir, n);
return statSync(p).isFile()
&& !referenced.has(n)
&& !metaFiles.has(n)
&& !/\.db$/i.test(n);
});
if (orphans.length) add('info', 'orphan-files', `目录里有 ${orphans.length} 个未被索引引用的文件(多为旧版页面残留,可忽略)`, { examples: orphans.slice(0, 5) });
const filesField = j.Courseware.Files || '';
const fileIds = new Set(j.CoursewareFiles.map(f => f.FileId));
const listed = filesField.split(';').filter(Boolean);
if (listed.length !== fileIds.size || listed.some(x => !fileIds.has(x))) {
add('warn', 'files-field-mismatch', 'Courseware.Files 与 CoursewareFiles 不一致');
}
let dbRow = null;
try {
dbRow = readDbRow(cw);
if (!dbRow) add('error', 'db-row-missing', 'CoursewareCacheData.db 里没有这份课件');
else {
if (dbRow.LocalRevision !== j.Courseware.Revision) add('warn', 'db-revision-mismatch', `DB LocalRevision=${dbRow.LocalRevision},JSON Revision=${j.Courseware.Revision}`);
if (dbRow.SyncedRevision !== j.Courseware.SyncedRevision) add('warn', 'db-synced-mismatch', `DB SyncedRevision=${dbRow.SyncedRevision},JSON SyncedRevision=${j.Courseware.SyncedRevision}`);
if (dbRow.Size !== j.Courseware.Size) add('warn', 'db-size-mismatch', `DB Size=${dbRow.Size},JSON Size=${j.Courseware.Size}`);
const n = withDb(cw, db => db.prepare('select count(*) c from CoursewareFile where FileRelativePath like ?').get(cw.localId + '\\%').c);
if (n !== j.CoursewareFiles.length) add('warn', 'db-file-count-mismatch', `DB 文件行 ${n} 条,索引 ${j.CoursewareFiles.length} 条`);
}
} catch (e) {
add('warn', 'db-unreadable', `读 DB 失败:${e.message}`);
}
// 每页动画数(按 Board 页序),方便一次调用做回归核对
const animByFile = new Map(ids.map(x => [x.rec.FileName, animCounts.get(x.rec.FileName) ?? 0]));
const animations = {};
if (board) {
board.ids.forEach((id, i) => {
const hit = ids.find(x => x.id.toLowerCase() === id.toLowerCase());
animations[i + 1] = hit ? (animByFile.get(hit.rec.FileName) ?? 0) : 0;
});
} else {
slides.forEach((rec, i) => { animations[i + 1] = animByFile.get(rec.FileName) ?? 0; });
}
const animationTotal = Object.values(animations).reduce((a, b) => a + b, 0);
return {
ok: !issues.some(x => x.level === 'error'),
courseware: cw.name,
localId: cw.localId,
pages: board?.ids.length ?? slides.length,
revision: j.Courseware.Revision,
syncedRevision: j.Courseware.SyncedRevision,
size: j.Courseware.Size,
animations,
animationTotal,
db: dbRow && { localRevision: dbRow.LocalRevision, syncedRevision: dbRow.SyncedRevision, size: dbRow.Size },
counts: { errors: issues.filter(x => x.level === 'error').length, warnings: issues.filter(x => x.level === 'warn').length, infos: issues.filter(x => x.level === 'info').length },
issues,
};
}
// ---------------------------------------------------------------- 工具:恢复
export async function restoreCourseware({
backupId, courseware, confirm = false,
reopen = true, sync = false, force = false, keepIdentity = true,
} = {}) {
if (!confirm) throw new Error('恢复会覆盖当前课件,请传 confirm=true');
const { dir, manifest } = resolveBackup(backupId);
const cw = resolveCourseware(courseware ?? manifest.localId);
return serial(async () => {
// 备份里的 index.json 带的是备份时的身份(Name/RemoteId),恢复内容时不能把身份也带回去,
// 否则会把本地指针指到另一份云端副本。
const before = {
name: cw.json.Courseware.Name,
remoteId: cw.json.Courseware.RemoteId,
syncedRevision: cw.json.Courseware.SyncedRevision,
};
const { wasOpen } = await closeForWrite(cw, force);
for (const f of manifest.files) {
const src = path.join(dir, f.FileName);
if (existsSync(src)) copyFileSync(src, path.join(cw.dir, f.FileName));
}
const idx = path.join(dir, 'index.json');
if (!existsSync(idx)) throw new Error('备份缺少 index.json');
writeFileSync(cw.jsonPath, readFileSync(idx));
cw.json = readJson(cw.jsonPath);
if (keepIdentity) {
if (before.name) cw.json.Courseware.Name = before.name;
if (before.remoteId) cw.json.Courseware.RemoteId = before.remoteId;
}
cw.name = cw.json.Courseware.Name ?? cw.name;
const dbRow = readDbRow(cw);
const base = Math.max(cw.json.Courseware.Revision ?? 0, dbRow?.LocalRevision ?? 0);
const synced = keepIdentity
? (before.syncedRevision ?? dbRow?.SyncedRevision ?? 0)
: (manifest.syncedRevision ?? cw.json.Courseware.SyncedRevision ?? 0);
cw.json.Courseware.Revision = Math.max(base + 1, synced + 1);
cw.json.Courseware.SyncedRevision = synced;
cw.json.Courseware.UpdateTime = Date.now();
writeJson(cw);
writeDb(cw);
let shellId = null;
let syncText = null;
if (reopen) {
shellId = await openCourseware(cw, slideRecords(cw).length);
if (sync && shellId) syncText = await syncShell(shellId);
}
return {
restored: manifest.id, courseware: cw.name,
revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision,
keepIdentity, wasOpen, reopened: !!shellId, shellId, sync: syncText,
};
});
}
// ---------------------------------------------------------------- 工具:跨课件复制
function regenerateIds(xml) {
const map = new Map();
const get = id => {
const k = id.toLowerCase();
if (!map.has(k)) map.set(k, randomBytes(16).toString('hex'));
return map.get(k);
};
let out = xml.replace(/<Id>([0-9a-fA-F]{32})<\/Id>/g, (m, id) => `<Id>${get(id)}</Id>`);
out = out.replace(/<Item>([0-9a-fA-F]{32})<\/Item>/g, (m, id) => `<Item>${get(id)}</Item>`);
return out;
}
function resourceRefs(xml) {
return [...new Set([...xml.matchAll(/id:\/\/([0-9a-fA-F]{32})/g)].map(m => m[1].toLowerCase()))];
}
/**
* 希沃真正解析 id://<32hex> 用的是 Reference.xml 里的关系表,
* 只把资源文件 + 索引/DB 记录复制过来,页面上的图片仍会显示成占位图,
* 保存时希沃还会把这条资源记录当成孤儿删掉。复制页面时必须同步合并关系表。
*/
function referenceRecord(cw) {
const rec = cw.json.CoursewareFiles.find(
f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === 'reference.xml',
);
if (!rec) return null;
const file = path.join(cw.dir, rec.FileName);
if (!existsSync(file)) return null;
return { rec, file };
}
function ensureReferenceDoc(cw) {
const existing = referenceRecord(cw);
if (existing) return existing;
const fileName = `Reference_S${String(Date.now()).slice(-6)}.${rand(11)}.${rand(3)}.xml`;
const file = path.join(cw.dir, fileName);
writeFileSync(file, '<Reference>\n <Relationships>\n </Relationships>\n</Reference>\n', 'utf8');
const buf = readFileSync(file);
const rec = {
FileId: randomUUID(), FileName: fileName, FileHash: md5(buf), FileSize: buf.length,
FilePath: `${cw.localId}\\${fileName}`, RelativePath: 'Reference.xml', FilePartialState: 0,
};
cw.json.CoursewareFiles.push(rec);
return { rec, file };
}
function mergeReferences(cw, items) {
const ref = ensureReferenceDoc(cw);
let xml = readText(ref.file);
const have = new Set([...xml.matchAll(/<Id>([0-9a-fA-F]{32})<\/Id>/g)].map(m => m[1].toLowerCase()));
const add = [];
for (const it of items) {
const id = String(it.id).toLowerCase();
if (have.has(id)) continue;
have.add(id);
add.push(it);
}
if (!add.length) return { added: 0 };
const block = add.map(it => [
' <Relationship>',
` <Id>${it.id}</Id>`,
` <Target>${it.target}</Target>`,
` <Hash>${it.hash}</Hash>`,
' </Relationship>',
].join('\n')).join('\n');
if (!xml.includes(' </Relationships>')) return { added: 0, warning: 'Reference.xml 结构异常,未写入资源关系' };
xml = xml.replace(' </Relationships>', `${block}\n </Relationships>`);
writeFileSync(ref.file, xml, 'utf8');
saveSlideRecord(cw, ref.rec, ref.file);
return { added: add.length };
}
export async function copySlides({
source, target, pages = [], position = null,
reopen = true, sync = false, force = false, backup = true,
} = {}) {
if (!source || !target) throw new Error('需要 source 和 target');
if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空');
const src = resolveCourseware(source);
const dst = resolveCourseware(target);
return runEdit(dst, { reopen, sync, force, backup }, async c => {
const srcSlides = slidesInBoardOrder(src);
const dstSlides = slidesInBoardOrder(c);
const picked = pages.map(n => {
const s = srcSlides[n - 1];
if (!s) throw new Error(`源课件没有第 ${n} 页(共 ${srcSlides.length} 页)`);
return s;
});
const at = position == null ? dstSlides.length : Math.max(0, Math.min(dstSlides.length, Number(position)));
const ts = String(Date.now()).slice(-4);
const copied = [];
const warnings = [];
const refItems = [];
for (const s of picked) {
let xml = regenerateIds(s.xml);
const newFile = `Slide_${dstSlides.length + copied.length}_S${ts}.${rand(11)}.${rand(3)}.xml`;
writeFileSync(path.join(c.dir, newFile), xml, 'utf8');
const buf = readFileSync(path.join(c.dir, newFile));
const newId = slideXmlId(xml);
copied.push({
id: newId,
rec: {
FileId: randomUUID(), FileName: newFile, FileHash: md5(buf), FileSize: buf.length,
FilePath: `${c.localId}\\${newFile}`, RelativePath: '', FilePartialState: 0,
},
});
// 复制这一页引用的图片/音频资源,并登记到 Reference.xml
for (const rid of resourceRefs(xml)) {
const srec = src.json.CoursewareFiles.find(f => {
const n = f.FileName.toLowerCase();
return n === rid || n.startsWith(rid + '.');
});
if (!srec) { warnings.push(`第 ${s.page} 页引用的资源 ${rid} 在源课件索引里找不到`); continue; }
const relPath = String(srec.RelativePath).replace(/\//g, '\\');
refItems.push({ id: rid, target: relPath, hash: srec.FileHash });
const exists = c.json.CoursewareFiles.some(
f => String(f.RelativePath).replace(/\//g, '\\').toLowerCase() === relPath.toLowerCase(),
);
const srcFile = path.join(src.dir, srec.FileName);
const dstFile = path.join(c.dir, srec.FileName);
if (!existsSync(srcFile)) { warnings.push(`资源文件不存在:${srec.FileName}`); continue; }
if (!existsSync(dstFile) || statSync(dstFile).size !== srec.FileSize) copyFileSync(srcFile, dstFile);
if (exists) continue;
c.json.CoursewareFiles.push({
FileId: randomUUID(), FileName: srec.FileName, FileHash: srec.FileHash, FileSize: srec.FileSize,
FilePath: `${c.localId}\\${srec.FileName}`, RelativePath: srec.RelativePath, FilePartialState: 0,
});
}
}
// 重排页序:目标原页 + 插入页
const merged = [...dstSlides.slice(0, at), ...copied, ...dstSlides.slice(at)];
const nonSlides = c.json.CoursewareFiles.filter(f => !isSlidePath(f.RelativePath));
merged.forEach((s, i) => {
s.rec.RelativePath = `Slides\\Slide_${i}.xml`;
s.rec.FilePath = `${c.localId}\\${s.rec.FileName}`;
});
c.json.CoursewareFiles = [...nonSlides, ...merged.map(s => s.rec)];
// 更新 Board.xml 页序
const board = readBoard(c);
const newBoardXml = board.xml.replace(/<Slides>[\s\S]*?<\/Slides>/,
'<Slides>\n' + merged.map(s => ` <Item>${s.id}</Item>`).join('\n') + '\n </Slides>');
writeFileSync(board.file, newBoardXml, 'utf8');
saveSlideRecord(c, board.rec, board.file);
const refResult = mergeReferences(c, refItems);
if (refResult.warning) warnings.push(refResult.warning);
return {
courseware: c.name, source: src.name,
insertedAt: at, pages: picked.map(s => s.page),
newPages: merged.map((s, i) => ({ page: i + 1, slideId: s.id })).filter((x, i) => i >= at && i < at + copied.length),
referencesAdded: refResult.added,
warnings,
};
});
}
// ---------------------------------------------------------------- 工具:删页 / 排序
export async function deleteSlides({
courseware, pages = [], trash = true,
reopen = true, sync = false, force = false, backup = true,
} = {}) {
if (!Array.isArray(pages) || !pages.length) throw new Error('pages 不能为空');
const cw = resolveCourseware(courseware);
const initial = slidesInBoardOrder(cw);
const nums = [...new Set(pages.map(Number))];
for (const n of nums) {
if (!Number.isInteger(n) || n < 1 || n > initial.length) {
throw new Error(`页码 ${n} 超出范围(1-${initial.length})`);
}
}
if (nums.length >= initial.length) throw new Error('不能删除全部页面,至少保留 1 页');
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const all = slidesInBoardOrder(c);
const del = new Set(nums);
const kept = all.filter(s => !del.has(s.page));
const removed = all.filter(s => del.has(s.page));
if (!kept.length) throw new Error('不能删除全部页面,至少保留 1 页');
let trashDir = null;
if (trash) {
trashDir = path.join(TMP, 'seewo-kit-trash', `${c.localId}-${stamp()}`);
mkdirSync(trashDir, { recursive: true });
}
const deleted = [];
for (const s of removed) {
const name = path.basename(s.file);
if (trash) {
const dst = path.join(trashDir, name);
try { renameSync(s.file, dst); } catch {
copyFileSync(s.file, dst);
rmSync(s.file, { force: true });
}
} else {
rmSync(s.file, { force: true });
}
deleted.push({ page: s.page, slideId: s.id, file: name });
}
reindexSlides(c, kept);
writeBoardOrder(c, kept);
return {
courseware: c.name,
deleted, remaining: kept.length, trashDir,
pages: kept.map((s, i) => ({ page: i + 1, slideId: s.id })),
};
});
}
export async function moveSlides({
courseware, from, to, order,
reopen = true, sync = false, force = false, backup = true,
} = {}) {
const cw = resolveCourseware(courseware);
const initial = slidesInBoardOrder(cw);
if (!(Array.isArray(order) && order.length) && (from == null || to == null)) {
throw new Error('需要 order(完整页序),或 from + to(把 from 页移到 to 位置)');
}
const resolveOrder = (all, list) => {
if (list.length !== all.length) throw new Error(`order 必须包含全部 ${all.length} 页`);
const seen = new Set();
return list.map(value => {
const p = Number(value);
if (!Number.isInteger(p) || p < 1 || p > all.length) {
throw new Error(`order 里的页码 ${value} 超出范围(1-${all.length})`);
}
if (seen.has(p)) throw new Error(`order 里的页码 ${p} 重复`);
seen.add(p);
return all[p - 1];
});
};
const resolveMove = (all, f, t) => {
if (!Number.isInteger(f) || f < 1 || f > all.length) throw new Error(`from 页码 ${f} 超出范围(1-${all.length})`);
if (!Number.isInteger(t) || t < 1 || t > all.length) throw new Error(`to 页码 ${t} 超出范围(1-${all.length})`);
const next = [...all];
const [moved] = next.splice(f - 1, 1);
next.splice(t - 1, 0, moved);
return next;
};
const preview = Array.isArray(order) && order.length
? resolveOrder(initial, order)
: resolveMove(initial, Number(from), Number(to));
const oldOrder = initial.map(s => s.page).join(',');
const newOrder = preview.map(s => s.page).join(',');
if (oldOrder === newOrder) {
return { courseware: cw.name, changed: false, order: preview.map(s => s.page) };
}
return runEdit(cw, { reopen, sync, force, backup }, async c => {
const all = slidesInBoardOrder(c);
const next = Array.isArray(order) && order.length
? resolveOrder(all, order)
: resolveMove(all, Number(from), Number(to));
reindexSlides(c, next);
writeBoardOrder(c, next);
return {
courseware: c.name, changed: true,
from: from == null ? null : Number(from),
to: to == null ? null : Number(to),
order: next.map(s => s.page),
pages: next.map((s, i) => ({ page: i + 1, slideId: s.id, oldPage: s.page })),
};
});
}
// ---------------------------------------------------------------- 工具:单独同步
export async function syncCourseware({ courseware } = {}) {
const cw = resolveCourseware(courseware);
return serial(async () => {
await ensureInit();
let shell = (await shells()).find(s => sameCourseware(s, cw));
let opened = false;
if (!shell) {
const id = await openCourseware(cw, slideRecords(cw).length);
if (!id) throw new Error(`打开课件「${cw.name}」失败`);
shell = { id };
opened = true;
}
const text = await syncShell(shell.id);
const info = await mcp('get_current_courseware_info', { shellId: shell.id }, { timeoutMs: 15000 })
.then(r => r.data ?? null).catch(() => null);
return {
courseware: cw.name,
shellId: shell.id,
opened,
sync: text,
isSynced: info?.isSynced ?? null,
slideCount: info?.slideCount ?? null,
};
});
}
// ---------------------------------------------------------------- 工具:清理孤儿文件
const ORPHAN_ROOT = path.join(TMP, 'seewo-kit-orphans');
const TRASH_ROOT = path.join(TMP, 'seewo-kit-trash');
/** 磁盘上存在、但索引里没引用的文件(旧版页面残留等) */
function orphanFilesOf(cw) {
const referenced = new Set(cw.json.CoursewareFiles.map(f => f.FileName));
const metaFiles = new Set([`${cw.localId}.json`, 'CoursewareSourceTrace.json']);
return readdirSync(cw.dir).filter(n => {
let st;
try { st = statSync(path.join(cw.dir, n)); } catch { return false; }
return st.isFile() && !referenced.has(n) && !metaFiles.has(n) && !/\.db$/i.test(n);
});
}
export async function pruneOrphanFiles({
courseware, dryRun = true, confirm = false,
force = false, backup = true, reopen = true,
} = {}) {
const cw = resolveCourseware(courseware);
return serial(async () => {
const orphans = orphanFilesOf(cw);
const bytes = orphans.reduce((a, n) => {
try { return a + statSync(path.join(cw.dir, n)).size; } catch { return a; }
}, 0);
const preview = {
courseware: cw.name, localId: cw.localId,
count: orphans.length, bytes, files: orphans.slice(0, 100),
};
if (dryRun) return { ...preview, dryRun: true, removed: 0, trashDir: null, backupId: null };
if (!confirm) {
throw new Error(`将移走 ${orphans.length} 个未被索引引用的文件(${bytes} 字节),请传 confirm=true;`
+ '可先传 dryRun=true 预览。');
}
if (!orphans.length) {
return { ...preview, dryRun: false, removed: 0, trashDir: null, backupId: null, wasOpen: false };
}
const { wasOpen } = await closeForWrite(cw, force);
const backupId = backup
? backupCourseware({ courseware: cw.localId, note: 'auto-before-prune' }).backupId
: null;
mkdirSync(ORPHAN_ROOT, { recursive: true });
const trashDir = path.join(ORPHAN_ROOT, `${cw.localId}-${stamp()}`);
mkdirSync(trashDir, { recursive: true });
const moved = [];
for (const n of orphans) {
try {
renameSync(path.join(cw.dir, n), path.join(trashDir, n));
moved.push(n);
} catch { /* 跳过被占用的文件 */ }
}
let shellId = null;
if (wasOpen && reopen !== false) shellId = await openCourseware(cw, slideRecords(cw).length);
return {
...preview, dryRun: false, removed: moved.length, trashDir, backupId,
wasOpen, reopened: !!shellId, shellId,
};
});
}
// ---------------------------------------------------------------- 工具:移除本地重复课件
export async function removeLocalCourseware({
courseware, confirm = false, force = false, trash = true,
} = {}) {
if (!confirm) throw new Error('会移走课件缓存并删除 DB 记录,请传 confirm=true');
const cw = resolveCourseware(courseware);
return serial(async () => {
await ensureInit();
const { wasOpen, closed } = await closeForWrite(cw, force);
let trashDir = null;
try {
if (trash) {
mkdirSync(TRASH_ROOT, { recursive: true });
trashDir = path.join(TRASH_ROOT, `${cw.localId}-${stamp()}`);
renameSync(cw.dir, trashDir);
} else {
rmSync(cw.dir, { recursive: true, force: true });
}
const removed = withDb(cw, db => {
db.exec('BEGIN');
try {
const files = db.prepare('delete from CoursewareFile where FileRelativePath like ?')
.run(cw.localId + '\\%');
const row = db.prepare('delete from Courseware where LocalId=?').run(cw.localId);
db.exec('COMMIT');
return { files: files.changes, courseware: row.changes };
} catch (e) {
db.exec('ROLLBACK');
throw e;
}
}, { write: true });
return {
removed: cw.name, localId: cw.localId,
remoteId: cw.json.Courseware.RemoteId ?? null,
wasOpen, closed, trashDir, db: removed,
};
} catch (e) {
// DB 删除失败时把目录挪回来,避免文件没了但记录还在
if (trashDir && existsSync(trashDir) && !existsSync(cw.dir)) {
try { renameSync(trashDir, cw.dir); } catch { /* ignore */ }
}
throw e;
}
});
}