seewo-kit: 重名检测 / 恢复保留身份 / 清理重复与孤儿文件
- resolveCourseware 同名多份直接报错并列出 localId/RemoteId/Revision - 开/关课件时用 RemoteId 核对,避免同名副本操作错 - restore_courseware 默认 keepIdentity=true,只恢复内容保留 Name/RemoteId - syncShell 轮询备课界面,遇「必须处于备课界面」自动重试 - 新增 prune_orphan_files(默认 dryRun,清理前备份并移入回收目录) - 新增 remove_local_courseware(目录进回收站 + 删 DB 行,不动云端) - verify_courseware 返回每页动画数 animations / animationTotal - 文档补充新工具与身份冲突处理
This commit is contained in:
+267
-27
@@ -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(/<Animation>/g) || []).length);
|
||||
const id = slideXmlId(xml);
|
||||
if (!id) { add('error', 'slide-id-missing', `${rec.RelativePath} 没有 <Id>`); 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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user