/** * 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(/([\s\S]*?)<\/Slides>/)?.[1] ?? ''; const ids = [...block.matchAll(/([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(/\s*([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() === `${elementId}`); 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() !== ``) end++; if (end >= lines.length) return null; return { start, end, tag }; }; const unesc = s => String(s).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); const esc = s => String(s).replace(/&/g, '&').replace(//g, '>'); const elementText = body => { const cands = [...body.matchAll(/([^<]*)<\/Text>/g)].map(m => unesc(m[1])).filter(t => t.trim()); cands.sort((a, b) => b.length - a.length); return cands[0] ?? ''; }; 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() !== ``) k++; const body = lines.slice(i + 1, k).join('\n'); const id = body.match(/([0-9a-fA-F]{32})<\/Id>/)?.[1]; if (!id) return; out.push({ id, type: tag, body, x: Number(body.match(/([^<]*)<\/X>/)?.[1]), y: Number(body.match(/([^<]*)<\/Y>/)?.[1]), w: Number(body.match(/([^<]*)<\/Width>/)?.[1]), text: elementText(body), animated: body.includes(''), }); }); return out; } /** 给文本块写「固定框宽 + 单行折行」,避免只改 后按旧折行渲染 */ function collapseLines(block, text, width) { if (width != null) { const wi = block.findIndex(l => /^\s*[^<]*<\/Width>$/.test(l)); if (wi >= 0) block[wi] = `${block[wi].match(/^\s*/)[0]}${width}`; const sc = block.findIndex(l => //.test(l)); if (sc >= 0) block[sc] = block[sc].replace(/>[^<]*Manual<'); } const ls = block.findIndex(l => l.trim() === ''); const n = [...text].length; if (ls >= 0) { let le = ls; while (le < block.length && block[le].trim() !== '') le++; block.splice(ls + 1, le - ls - 1, ' ', ' 0', ` ${n}`, ' '); return; } for (let i = 0; i < block.length; i++) { const m = block[i].match(/^(\s*)\d+<\/Length>$/); if (m) { block[i] = `${m[1]}${n}`; break; } } } // ---------------------------------------------------------------- 动画 const animNode = (id, o) => [ ' ', ' ', ` ${o.type}`, ` ${id}`, ' 1', ' Appearance', ` ${o.trigger}`, ' ', ` ${Math.round(o.duration * 10000000)}`, ` ${Math.round(o.delay * 10000000)}`, ' 1', ' 0', ' 1', ' 0', ' 1', ' ', ' ', ]; 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 === '' || t === '') { const close = t.replace('<', ':先删旧的,再按元素在页面里的先后重新排 */ function rebuildOrders(lines) { const oStart = lines.findIndex(l => l.trim() === ''); if (oStart >= 0) { let oEnd = oStart; while (oEnd < lines.length && lines[oEnd].trim() !== '') oEnd++; lines.splice(oStart, oEnd - oStart + 1); } const ids = []; for (const el of listElements(lines)) { const m = el.body.match(/[\s\S]*?([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(''); lines.splice(closeIdx, 0, ' ', ...ids.map(x => ` ${x}`), ' '); 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() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') b++; replaced = 1; block.splice(a, b - a + 1); } const animId = randomBytes(16).toString('hex'); let at = block.findIndex(l => l.trim() === ''); if (at < 0) at = block.findIndex(l => l.trim() === ''); 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(/([\s\S]*?)<\/Animations>/g)) { for (const a of block[1].matchAll(/([\s\S]*?)<\/Animation>/g)) { const g = t => a[1].match(new RegExp(`<${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() === ''); if (start < 0) return []; let end = start; while (end < lines.length && lines[end].trim() !== '') end++; return lines.slice(start + 1, end) .map(l => l.match(/([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(/[\s\S]*?([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() === ''); if (start < 0) return; let end = start; while (end < lines.length && lines[end].trim() !== '') end++; lines.splice(start, end - start + 1, ' ', ...next.map(x => ` ${x}`), ' '); } // ---------------------------------------------------------------- 数据库 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) }; } // ---------------------------------------------------------------- 关/开/同步 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(//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() === ''); if (a >= 0) { let b = a; while (b < block.length && block[b].trim() !== '') 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 }; }); } // ---------------------------------------------------------------- 工具:改文字 export async function replaceText({ courseware, page, replacements = [], reopen = true, sync = false, force = false, backup = true, } = {}) { const cw = resolveCourseware(courseware); if (!Array.isArray(replacements) || !replacements.length) throw new Error('replacements 不能为空'); return runEdit(cw, { reopen, sync, force, backup }, async c => { const { file, rec } = slideAt(c, page); const { lines, eol } = readLines(file); const changes = []; const missing = []; for (const spec of replacements) { let el = null; if (spec.elementId) { el = listElements(lines).find(e => e.id === spec.elementId); if (!el) { missing.push({ elementId: spec.elementId, reason: '元素不存在' }); continue; } } else 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) { throw new Error(`「${spec.find}」匹配到 ${hits.length} 个元素,请加 elementId:` + hits.map(h => h.id).join(', ')); } el = hits[0]; } else { missing.push({ reason: '需要 elementId 或 find' }); continue; } if (spec.text == null && spec.find == null) { missing.push({ elementId: el.id, reason: '需要 text 或 find' }); continue; } const r = blockRange(lines, el.id); 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>/g)] .map(m => unesc(m[1])).filter(Boolean)); if (nonEmpty.size > 1) { throw new Error(`元素 ${el.id} 有多个不同文本片段,无法整段替换;请改用 find/replace`); } const oldTag = `${esc(before)}`; for (let i = 0; i < block.length; i++) { if (block[i].includes(oldTag)) block[i] = block[i].split(oldTag).join(`${esc(after)}`); } } else { const find = String(spec.find); const rep = String(spec.replace ?? ''); if (!before.includes(find)) { missing.push({ elementId: el.id, reason: `文本里没有「${find}」` }); continue; } after = before.split(find).join(rep); for (let i = 0; i < block.length; i++) { block[i] = block[i].replace(/([^<]*)<\/Text>/g, (m, t) => { const plain = unesc(t); return plain.includes(find) ? `${esc(plain.split(find).join(rep))}` : 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); changes.push({ elementId: el.id, before, after }); } if (changes.length) { writeLines(file, lines, eol); saveSlideRecord(c, rec, file); } return { courseware: c.name, page, changes, missing }; }); } // ---------------------------------------------------------------- 工具:校验 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(//g) || []).length); const id = slideXmlId(xml); if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 `); 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(/([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(/([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(/([0-9a-fA-F]{32})<\/Id>/g, (m, id) => `${get(id)}`); out = out.replace(/([0-9a-fA-F]{32})<\/Item>/g, (m, id) => `${get(id)}`); 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, '\n \n \n\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(/([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 => [ ' ', ` ${it.id}`, ` ${it.target}`, ` ${it.hash}`, ' ', ].join('\n')).join('\n'); if (!xml.includes(' ')) return { added: 0, warning: 'Reference.xml 结构异常,未写入资源关系' }; xml = xml.replace(' ', `${block}\n `); 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(/[\s\S]*?<\/Slides>/, '\n' + merged.map(s => ` ${s.id}`).join('\n') + '\n '); 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 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; } }); }