diff --git a/README.md b/README.md index 91f91b3..5f821c5 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,15 @@ node seewo-anim.mjs fix --slide 5 --minY 90 # 只改正文行(默认 ## 相关:seewo-kit(MCP 版) `kit/` 下是把本工具能力接进 MCP 的版本,另外补了课件自检、备份/恢复、跨课件复制页面、 -批量改文字。注册后可直接在 OpenCode 里调用 `seewokit_*` 工具,无需命令行。 +批量改文字、清理重复课件与孤儿文件。注册后可直接在 OpenCode 里调用 `seewokit_*` 工具,无需命令行。 + +两个特别有用的只读/维护工具: + +- `verify_courseware`:一次返回页数、MD5、重复 Id、DB 一致性,以及每页动画数 + (`animations: { 页码: 动画数 }`、`animationTotal`),适合改完后做回归核对。 +- `prune_orphan_files`:默认 `dryRun` 只预览「磁盘上有、索引里没引用」的旧文件, + 确认后移进回收目录(清理前自动备份)。 +- `remove_local_courseware`:清理同名重复课件,目录进回收站并删 DB 行(不动云端)。 + 详见 [`kit/README.md`](kit/README.md)。 diff --git a/kit/README.md b/kit/README.md index 0a6c039..aedfb60 100644 --- a/kit/README.md +++ b/kit/README.md @@ -38,11 +38,13 @@ kit/ | `get_animations` | 读某页动画、点击顺序、`AnimationOrders` 一致性 | 否 | | `clear_animations` | 清整页 / 指定元素 / 全部页的动画 | 是 | | `replace_text` | 批量改文本(整段或子串),可顺手规范折行 | 是 | -| `verify_courseware` | 课件自检:页数、页序、MD5、重复 Id、资源引用、DB 一致性 | 否 | +| `verify_courseware` | 课件自检:页数、页序、MD5、重复 Id、资源引用、DB 一致性、每页动画数 | 否 | | `backup_courseware` | 全量快照到临时目录,返回 `backupId` | 否 | -| `restore_courseware` | 从快照恢复(需 `confirm=true`) | 是 | +| `restore_courseware` | 从快照恢复(需 `confirm=true`;默认保留当前身份) | 是 | | `copy_slides` | 跨课件复制页面(含图片/音频/动画/背景) | 是 | | `sync_courseware` | 只做云同步,不改内容(用于清理 Revision 脏状态) | 是(同步) | +| `prune_orphan_files` | 清理未被索引引用的旧文件(默认只预览,可恢复) | 是 | +| `remove_local_courseware` | 移除本地重复课件(目录进回收站 + 删 DB 行) | 是 | | `list_coursewares` | 列出本地缓存课件 | 否 | 公共参数: @@ -69,6 +71,9 @@ kit/ 6. **重开**:`open_cloud_courseware`,等页面加载完成再返回。 7. **可选同步**:`sync=true` 时先做一次「加页+删页」把课件弄脏,再上传。 +> 关闭/打开时先按名字匹配;本地存在同名副本时再用 `RemoteId` 逐个核对,防止操作到另一份。 +> 同步前会轮询到备课(Edit)界面;遇到「必须处于备课界面」会自动重新切界面并重试 3 轮。 + ## 各工具要点 ### set_animations / clear_animations @@ -110,19 +115,37 @@ kit/ - `id://` 资源是否存在、是否登记在 `Reference.xml`; - JSON 与 `CoursewareCacheData.db` 的 Revision / Size / 文件行数是否一致。 +另外返回 `animations: { 页码: 动画数 }` 和 `animationTotal`,一次调用就能做回归核对。 + ### backup / restore - `backup_courseware` 返回 `backupId`,目录在 `%TEMP%\opencode\seewo-kit-backups\-<时间>`。 - `restore_courseware` 必须传 `confirm=true`;会用快照覆盖当前缓存文件与索引/DB。 -- 恢复只改本地,`Revision` 会在当前值上再 +1;需要上传时传 `sync=true`。 +- 默认 `keepIdentity=true`:只恢复内容,保留当前课件的 `Name` / `RemoteId`。 + 备份里的 `index.json` 带的是备份时的身份,直接写回会把本地指针指到另一份云端副本。 +- 恢复只改本地,`Revision` 会在当前值和云端版本上取较大者再 +1;需要上传时传 `sync=true`。 ### sync_courseware -只同步、不改内容。课件没开会先打开,然后 `add_slide` + `delete_slide` 做一次无害改动再上传。 -适合清理测试留下的 Revision 脏状态。 +只同步、不改内容。课件没开会先打开,然后轮询到备课界面,再做一次无害改动(`add_slide` + `delete_slide`)后上传。 +如果提示「必须处于备课界面」,会自动重新切界面并重试 3 轮。 > 不要用 `clear_animations(allPages=true)` 来「顺手触发同步」——它会真的删掉所有页面上的动画。 +### prune_orphan_files + +- 默认 `dryRun=true`,只返回将要清理的文件、数量和字节数。 +- 真正清理传 `dryRun=false` + `confirm=true`;清理前自动备份,文件移到 + `%TEMP%\opencode\seewo-kit-orphans\-<时间>`,不是硬删除。 +- 希沃在成功同步后通常会自己清理孤儿文件,所以清理前先看一眼 `count`,大多是 0。 + +### remove_local_courseware + +- 用于清理同名副本:关闭课件 → 目录移到 `%TEMP%\opencode\seewo-kit-trash\-<时间>` → + 删除 DB 里的 `Courseware` 行和 `CoursewareFile` 行。 +- 必须传 `confirm=true`;只影响本地缓存,**不会删除云端课件**。 +- 重名时必须用 `LocalId` 指定要删哪一份。 + ## 坑 ### 1. 加载轮询:刚打开的课件只有 1 页 @@ -154,20 +177,25 @@ kit/ ### 3. 课件身份冲突:同名副本 / 自动改名 希沃检测到版本冲突时会把课件改名成 `名称(MM-dd HHmm 修改)`,并可能新建 `RemoteId`,本地也会出现 -两个同 `Name` 的缓存目录。此时 `resolveCourseware("名称片段")` 会按 mtime 命中其中一个,容易改错。 +两个同 `Name` 的缓存目录。 -排查与修复: +现在的处理: -- 用 `list_coursewares` 看清每个 `localId` 的 `RemoteId` / 页数 / Revision; -- 用希沃的 `search_cloud_courseware` 确认云端有哪些同名副本; -- 以「有内容的那份」的 `RemoteId` 为准,把它的本地 JSON + DB 行保留;重复目录连同 - `Courseware` 行、`CoursewareFile` 行一起移除(先移出 `Courseware\` 而不是直接删); -- 恢复备份时注意:备份里的 `index.json` 带的是旧 `Name` / `RemoteId`,恢复后要把这两项改回目标云课件, - 再同步,否则会把本地指针指到另一份云端副本。 +- `resolveCourseware` 匹配到同名多份会**直接报错**,并列出每个副本的 `localId` / `RemoteId` / Revision, + 不再按 mtime 静默选一个;用 `localId` 可以精确指定。 +- 打开/关闭窗口时会用 `RemoteId` 核对,避免同名副本时开到或同步到另一份。 +- `restore_courseware` 默认 `keepIdentity=true`,恢复内容时保留当前 `Name` / `RemoteId`。 +- 用 `remove_local_courseware` 清理多余副本(目录进回收站 + 删 DB 行)。 + +排查顺序: + +- `list_coursewares` 看每个 `localId` 的 `RemoteId` / 页数 / Revision; +- 希沃 `search_cloud_courseware` 确认云端有哪些同名副本; +- 保留有内容的那份,删掉它多余的本地目录。 MCP 没有「删除云课件」的工具,云端多余副本只能在希沃 App 里手动删。 -### 2. 图片占位图:`Reference.xml` 才是资源清单 +### 4. 图片占位图:`Reference.xml` 才是资源清单 希沃解析 `id://<32位hex>` **不是**只看索引 JSON,而是读课件里的 `Reference.xml`: @@ -194,12 +222,12 @@ MCP 没有「删除云课件」的工具,云端多余副本只能在希沃 App `verify_courseware` 也加了 `resource-not-referenced` 检查,以后再漏会直接报错。 -### 3. 同步要先「弄脏」 +### 5. 同步要先「弄脏」 本地只有 `Revision` 变大时,希沃 `sync` 只会「下载」不会「上传」。 `sync=true` 时工具会先 `add_slide` + `delete_slide` 做一次真实改动,再调 `sync_current_courseware`。 -### 4. JSON 与 DB 必须一起改 +### 6. JSON 与 DB 必须一起改 只改索引 JSON 的 `Revision`、不改 `CoursewareCacheData.db`,重新打开云端课件时会被云端旧版本覆盖(已实测)。 所有写操作都会在同一事务里更新: @@ -207,11 +235,11 @@ MCP 没有「删除云课件」的工具,云端多余副本只能在希沃 App - `Courseware.Revision` / `SyncedRevision` / `Size` / `Files` - `CoursewareFile` 的文件行 -### 5. 别在课件开着时直接改文件 +### 7. 别在课件开着时直接改文件 课件开着时内容在内存里,关闭会覆盖磁盘文件。必须走「关 → 改 → 开」。 -### 6. 授课模式不保存 +### 8. 授课模式不保存 MCP 加的元素在 Display 模式下不会被保存;写操作前后尽量让课件处于 Edit(备课)模式。 `kit` 的写操作走的是关闭后改文件,不依赖界面模式,但同步前建议 `en_goto_app_ui({ ui: 'Edit' })`(`syncShell` 已内置)。 diff --git a/kit/core.mjs b/kit/core.mjs index e6377d2..9ab0bf9 100644 --- a/kit/core.mjs +++ b/kit/core.mjs @@ -13,7 +13,7 @@ */ import { readFileSync, writeFileSync, readdirSync, statSync, existsSync, - mkdirSync, copyFileSync, rmSync, + mkdirSync, copyFileSync, rmSync, renameSync, } from 'node:fs'; import { createHash, randomUUID, randomBytes } from 'node:crypto'; import path from 'node:path'; @@ -132,10 +132,18 @@ export function listCoursewares() { 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 all[0]; + if (!query) return assertUniqueLocalName(all[0], all); const q = String(query).trim(); const byId = all.find(c => c.localId === q); if (byId) return byId; @@ -143,9 +151,32 @@ export function resolveCourseware(query) { 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/, '')); @@ -457,8 +488,9 @@ function writeDb(cw) { 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 UpdateTime=?, Size=?, LocalRevision=?, SyncedRevision=?, Files=? where LocalId=?') - .run(j.Courseware.UpdateTime, j.Courseware.Size, j.Courseware.Revision, j.Courseware.SyncedRevision, j.Courseware.Files, localId); + 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'); @@ -550,6 +582,31 @@ function sameCourseware(shell, cw) { 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 页, * 直接拿它和磁盘比较会被误判成「有未同步改动」。这里轮询到页数与磁盘一致, @@ -583,7 +640,7 @@ async function waitCoursewareLoaded(shellId, expectedPages, { timeoutMs = 25000 async function closeForWrite(cw, force) { await ensureInit(); - const open = (await shells()).filter(s => sameCourseware(s, cw)); + const open = await shellsForCourseware(cw); if (!open.length) return { wasOpen: false, closed: 0 }; const diskPages = slideRecords(cw).length; const diskSize = cw.json.Courseware.Size; @@ -624,7 +681,7 @@ async function closeForWrite(cw, force) { let stillOpen = true; for (let i = 0; i < 20; i++) { await sleep(500); - stillOpen = (await shells()).some(s => sameCourseware(s, cw)); + stillOpen = (await shellsForCourseware(cw)).length > 0; if (!stillOpen) break; } if (stillOpen) { @@ -636,18 +693,33 @@ async function closeForWrite(cw, force) { return { wasOpen: true, closed: open.length }; } -async function openCourseware(cwName, expectedPages = null) { +async function openCourseware(cwOrName, expectedPages = null) { await ensureInit(); - let s = (await shells()).find(x => String(x.coursewareName || '').trim() === cwName.trim()); + 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: cwName }).catch(() => {}); + 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() === cwName.trim()); + 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; @@ -655,25 +727,52 @@ async function openCourseware(cwName, expectedPages = null) { /** 做一次无害改动,让希沃认为课件「未同步」,否则 sync 只会下载 */ async function touch(shellId) { - const info = await mcp('get_current_courseware_info', { shellId }); - const count = info.data?.slideCount ?? 0; + 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); - if (add?.data?.slideNumber) { - await mcp('delete_slide', { shellId, slideNumber: add.data.slideNumber }).catch(() => {}); + 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) { - await mcp('en_goto_app_ui', { ui: 'Edit', shellId }).catch(() => {}); - await sleep(1200); - await touch(shellId); const opts = { timeoutMs: 180000 }; - let r = await mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts) + 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 mcp('sync_current_courseware', { shellId, waitUntilSynced: true, waitSeconds: 120 }, opts) - .catch(e => ({ text: 'ERR ' + e.message })); + r = await push(); } return r.text; } @@ -701,7 +800,7 @@ async function runEdit(cw, opts, action) { let shellId = null; let syncText = null; if (opts.reopen !== false) { - shellId = await openCourseware(cw.name, slideRecords(cw).length); + shellId = await openCourseware(cw, slideRecords(cw).length); if (opts.sync && shellId) syncText = await syncShell(shellId); } return { @@ -900,6 +999,7 @@ export function verifyCourseware({ courseware, hashes = true, deep = true } = {} 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); @@ -911,6 +1011,7 @@ export function verifyCourseware({ courseware, hashes = true, deep = true } = {} 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 }); @@ -1026,6 +1127,19 @@ export function verifyCourseware({ courseware, hashes = true, deep = true } = {} 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, @@ -1034,6 +1148,8 @@ export function verifyCourseware({ courseware, hashes = true, deep = true } = {} 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, @@ -1043,12 +1159,19 @@ export function verifyCourseware({ courseware, hashes = true, deep = true } = {} // ---------------------------------------------------------------- 工具:恢复 export async function restoreCourseware({ backupId, courseware, confirm = false, - reopen = true, sync = false, force = 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); @@ -1059,23 +1182,33 @@ export async function restoreCourseware({ 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); - cw.json.Courseware.Revision = base + 1; + 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(); - cw.json.Courseware.SyncedRevision = manifest.syncedRevision ?? cw.json.Courseware.SyncedRevision; writeJson(cw); writeDb(cw); let shellId = null; let syncText = null; if (reopen) { - shellId = await openCourseware(cw.name, slideRecords(cw).length); + 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, wasOpen, reopened: !!shellId, shellId, sync: syncText, + revision: cw.json.Courseware.Revision, syncedRevision: cw.json.Courseware.SyncedRevision, + keepIdentity, wasOpen, reopened: !!shellId, shellId, sync: syncText, }; }); } @@ -1251,7 +1384,7 @@ export async function syncCourseware({ courseware } = {}) { let shell = (await shells()).find(s => sameCourseware(s, cw)); let opened = false; if (!shell) { - const id = await openCourseware(cw.name, slideRecords(cw).length); + const id = await openCourseware(cw, slideRecords(cw).length); if (!id) throw new Error(`打开课件「${cw.name}」失败`); shell = { id }; opened = true; @@ -1269,3 +1402,110 @@ export async function syncCourseware({ courseware } = {}) { }; }); } + +// ---------------------------------------------------------------- 工具:清理孤儿文件 +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; + } + }); +} diff --git a/kit/server.mjs b/kit/server.mjs index 1d3e10b..c0322cf 100644 --- a/kit/server.mjs +++ b/kit/server.mjs @@ -15,7 +15,7 @@ import { createInterface } from 'node:readline'; import { setAnimations, getAnimations, clearAnimations, replaceText, verifyCourseware, backupCourseware, restoreCourseware, copySlides, - listCoursewares, syncCourseware, + listCoursewares, syncCourseware, pruneOrphanFiles, removeLocalCourseware, } from './core.mjs'; const log = (...a) => console.error('[seewo-kit]', ...a); @@ -123,7 +123,8 @@ const TOOLS = [ name: 'verify_courseware', description: '课件自检(只读):页数、Board.xml 页序、索引与磁盘文件的 MD5/大小、重复 Id、图片资源引用、' - + 'DB 里的 Revision/行数是否一致、孤儿文件。返回 { ok, issues[] }。', + + 'DB 里的 Revision/行数是否一致、孤儿文件,以及每页动画数(animations / animationTotal)。' + + '返回 { ok, issues[] }。', inputSchema: { type: 'object', properties: { @@ -148,6 +149,7 @@ const TOOLS = [ name: 'restore_courseware', description: '从 backup_courseware 的快照恢复(覆盖当前缓存文件与索引/DB)。必须传 confirm=true。\n' + + '默认 keepIdentity=true:只恢复内容,保留当前课件的 Name/RemoteId,避免把本地指针指到备份里的另一份云端副本。\n' + '恢复是本地操作:Revision 会比当前值再 +1,不会自动上传;需要时传 sync=true。', inputSchema: { type: 'object', @@ -155,6 +157,7 @@ const TOOLS = [ backupId: { type: 'string', description: 'backup_courseware 返回的 backupId' }, courseware: { type: 'string', description: '覆盖到哪份课件;默认用备份里的 LocalId' }, confirm: { type: 'boolean', description: '必须为 true' }, + keepIdentity: { type: 'boolean', default: true, description: '保留当前 Name/RemoteId(推荐)' }, reopen: { type: 'boolean', default: true }, sync: { type: 'boolean', default: false }, force: { type: 'boolean', default: false }, @@ -162,6 +165,40 @@ const TOOLS = [ required: ['backupId', 'confirm'], }, }, + { + name: 'prune_orphan_files', + description: + '清理课件目录里「存在但未被索引引用」的旧文件(每次恢复/复制都会堆积)。\n' + + '默认 dryRun=true 只预览;真正清理需要 dryRun=false + confirm=true。\n' + + '清理前会自动备份,文件移进 %TEMP%\\opencode\\seewo-kit-orphans,不会硬删除。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId' }, + dryRun: { type: 'boolean', default: true, description: 'true=只列出将要清理的文件' }, + confirm: { type: 'boolean', default: false, description: 'dryRun=false 时必须为 true' }, + force: { type: 'boolean', default: false, description: '忽略未同步检查' }, + backup: { type: 'boolean', default: true }, + reopen: { type: 'boolean', default: true, description: '原本开着的话,清理后重新打开' }, + }, + }, + }, + { + name: 'remove_local_courseware', + description: + '移除本地重复课件:关闭课件 → 把缓存目录移到 %TEMP%\\opencode\\seewo-kit-trash → 删除 Courseware / CoursewareFile 记录。\n' + + '只影响本地缓存和 DB,不会删除云端课件。必须传 confirm=true。', + inputSchema: { + type: 'object', + properties: { + courseware: { type: 'string', description: '课件名片段或 LocalId(重名时必须用 LocalId)' }, + confirm: { type: 'boolean', description: '必须为 true' }, + force: { type: 'boolean', default: false, description: '忽略未同步检查' }, + trash: { type: 'boolean', default: true, description: 'true=移到回收目录,false=直接删除' }, + }, + required: ['confirm'], + }, + }, { name: 'copy_slides', description: @@ -213,6 +250,8 @@ const HANDLERS = { restore_courseware: restoreCourseware, copy_slides: copySlides, sync_courseware: syncCourseware, + prune_orphan_files: pruneOrphanFiles, + remove_local_courseware: removeLocalCourseware, list_coursewares: () => { const all = listCoursewares(); let dbCountHint = null;