// ==UserScript== // @name 超星学习通课程资源助手 // @namespace https://gitee.com/fieldlu/chaoxing-course-helper // @version 1.0.0.4 // @description 自动发现超星学习通课程的 PPT/PDF/Word、教学视频与章节测验/作业/考试/随堂练习题目,按章节目录树分组,支持单个与批量下载、题目导出 Word // @license GPL-3.0 // @icon http://pan-yz.chaoxing.com/favicon.ico // @copyright 2026 WorkBuddy (GPL-3.0) // @author WorkBuddy // @homepageURL https://gitee.com/fieldlu/chaoxing-course-helper // @supportURL https://gitee.com/fieldlu/chaoxing-course-helper/issues // @match https://mooc1.chaoxing.com/* // @match https://mooc2-ans.chaoxing.com/* // @match https://mooc1-1.chaoxing.com/* // @match https://mooc1-2.chaoxing.com/* // @match https://mobilelearn.chaoxing.com/* // @match https://pan-yz.chaoxing.com/* // @exclude https://passport2.chaoxing.com/* // @exclude https://passport.chaoxing.com/* // @exclude https://i.chaoxing.com/* // @exclude https://sso.chaoxing.com/* // @connect gitee.com // @connect raw.giteeusercontent.com // @require https://cdn.jsdmirror.com/npm/docx@7.1.0/build/index.min.js // @grant GM_xmlhttpRequest // @grant GM_download // @grant GM_getValue // @grant GM_setValue // @connect chaoxing.com // @connect cldisk.com // @run-at document-idle // ==/UserScript== (function () { 'use strict'; /* ============================================================ * 0. 环境 * ============================================================ */ const MSG = '__CXDL_V2__'; const VERSION = '1.0.0.4'; const HOST = location.hostname; const IS_TOP = (() => { try { return window.top === window; } catch (e) { return false; } })(); const IS_PAN = /^pan-yz\.chaoxing\.com$/i.test(HOST); // 登录页 / 门户 / 单点登录:一律不介入,避免影响登录 const IS_LOGIN_PAGE = /^(passport2?|sso|i)\.chaoxing\.com$/i.test(HOST) || /(^|\/)(login|passport|sso|cas)(\/|\.|$)/i.test(location.pathname) || /loginType=|\/login\?/i.test(location.pathname + location.search) || !!document.querySelector('#loginForm, .loginForm, input[name="uname"], input[name="phone"], #phone'); if (IS_LOGIN_PAGE) return; const IS_COURSE = /(^|\.)chaoxing\.com$/i.test(HOST) && !IS_PAN; const CONCURRENCY = 2; const SCAN_DEBOUNCE = 500; const WORKER_TIMEOUT = 25000; /* ============================================================ * 1. 工具 * ============================================================ */ const DOC_EXT = ['pdf', 'ppt', 'pptx', 'pps', 'ppsx', 'doc', 'docx', 'wps', 'rtf', 'txt', 'xls', 'xlsx', 'et', 'csv', 'zip', 'rar', '7z']; const EXT_RE = new RegExp('\\.(' + DOC_EXT.join('|') + ')(?=$|[?#&])', 'i'); function fmtSize(n) { n = Number(n) || 0; if (!n) return ''; const u = ['B', 'KB', 'MB', 'GB']; let i = 0, v = n; while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; } return (i === 0 || v >= 100 ? Math.round(v) : v.toFixed(1)) + ' ' + u[i]; } function fmtDuration(sec) { sec = Math.round(Number(sec) || 0); if (!sec) return ''; const m = Math.floor(sec / 60), s = sec % 60; return (m >= 60 ? Math.floor(m / 60) + ':' + String(m % 60).padStart(2, '0') : String(m)) + ':' + String(s).padStart(2, '0'); } function extOf(name, fallback) { const m = String(name || '').toLowerCase().match(/\.([a-z0-9]{1,5})$/); return m ? m[1] : String(fallback || '').toLowerCase().replace(/^\./, ''); } function groupOf(ext) { ext = String(ext || '').toLowerCase(); if (ext === 'pdf') return 'pdf'; if (/^(pptx?|ppsx?|dps)$/.test(ext)) return 'ppt'; if (/^(docx?|wps|rtf|txt)$/.test(ext)) return 'doc'; if (/^(xlsx?|et|csv)$/.test(ext)) return 'xls'; return 'other'; } const GROUP_LABEL = { pdf: 'PDF', ppt: 'PPT', doc: 'DOC', xls: 'XLS', other: '其他', video: '视频', paper: '题目' }; function absUrl(u, base) { if (!u) return ''; const s = String(u).trim(); if (!s || /^(javascript|blob|data|mailto):/i.test(s) || s === '#') return ''; try { return new URL(s, base || location.href).href; } catch (e) { return ''; } } function isChaoxingOrigin(o) { try { return /(^|\.)chaoxing\.com$/i.test(new URL(o).hostname); } catch (e) { return false; } } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function cleanErr(e) { const s = String((e && (e.message || e)) || '未知错误').replace(/\s+/g, ' '); return s.length > 42 ? s.slice(0, 42) + '…' : s; } function readCtx(href) { let u; try { u = new URL(href || location.href); } catch (e) { return { origin: location.origin, courseid: '', clazzid: '', cpi: '', enc: '', t: '', stuenc: '' }; } const q = u.searchParams; const pick = (...ks) => { for (const k of ks) { const v = q.get(k); if (v) return v; } return ''; }; return { origin: u.origin, courseid: pick('courseid', 'courseId'), clazzid: pick('clazzid', 'classId'), cpi: pick('cpi'), enc: pick('enc'), t: pick('t'), stuenc: pick('stuenc'), chapterid: pick('chapterId', 'knowledgeid', 'knowledgeId') }; } // 接口偶尔会返回登录页/风控页 HTML,直接 JSON.parse 会抛「Unexpected token '<'」 function parseJson(text) { const t = String(text || '').trim(); if (!t) return null; if (t.charAt(0) === '<') return { __html: true }; try { return JSON.parse(t); } catch (e) { return null; } } function stripTags(doc) { try { doc.querySelectorAll('script,style,noscript').forEach((n) => n.remove()); } catch (e) { /* 忽略 */ } return doc; } function domToText(node) { const out = []; (function walk(n) { if (!n) return; if (n.nodeType === 3) { out.push(n.nodeValue); return; } if (n.nodeType !== 1) return; const tag = n.tagName.toLowerCase(); if (tag === 'br') { out.push('\n'); return; } const block = /^(p|div|li|tr|h[1-6]|section|article|table|blockquote|pre)$/.test(tag); if (block) out.push('\n'); for (let i = 0; i < n.childNodes.length; i++) walk(n.childNodes[i]); if (block) out.push('\n'); })(node); return out.join('').replace(/[ \t\u00a0]+/g, ' ').replace(/\n[ ]+/g, '\n').replace(/\n{3,}/g, '\n\n').trim(); } /* ============================================================ * 2. pan-yz 预览页工作线程(文档下载) * ============================================================ */ if (IS_PAN) { initPanWorker(); return; } function initPanWorker() { const file = readPanFileinfo(); if (!file) return; const post = (msg, transfer) => { try { window.top.postMessage(Object.assign({ [MSG]: 1 }, msg), '*', transfer || []); } catch (e) { /* 忽略 */ } }; const announce = () => post({ type: 'FILEINFO', objectid: file.objectid, name: file.name, size: file.size, download: file.download, page: location.href }); window.addEventListener('message', (ev) => { const d = ev.data; if (!d || d[MSG] !== 1) return; if (d.type === 'QUERY') { announce(); return; } if (d.type === 'FETCH') { streamFetch(d.url || file.download, d.id, d.name || file.name, post) .catch((err) => post({ type: 'FETCH_ERR', id: d.id, error: cleanErr(err) })); } }); announce(); setTimeout(announce, 600); setTimeout(announce, 2000); } function readPanFileinfo() { let txt = ''; try { txt = Array.from(document.querySelectorAll('script:not([src])')).map((s) => s.textContent).join('\n'); } catch (e) { return null; } const box = txt.match(/fileinfo\s*=\s*\{([\s\S]{0,4000}?)\}\s*;/); if (!box) return null; const scope = box[1]; const grab = (k) => { const m = scope.match(new RegExp("['\"]" + k + "['\"]\\s*:\\s*['\"]([^'\"]*)['\"]", 'i')); return m ? m[1] : ''; }; const download = grab('download'); if (!download) return null; let name = ''; try { name = decodeURIComponent((download.match(/[?&]fn=([^&]+)/) || [])[1] || ''); } catch (e) { name = ''; } if (!name) name = grab('name'); const pid = (location.pathname.match(/file_([0-9a-f]{32})/i) || [])[1] || ''; return { download, name: name || 'document', size: Number(grab('filesize')) || 0, objectid: (pid || grab('objectId') || grab('objectid') || '').toLowerCase() }; } async function streamFetch(url, id, name, post) { if (!url) throw new Error('缺少下载地址'); const res = await fetch(url, { credentials: 'omit', cache: 'no-store' }); if (!res.ok) throw new Error('HTTP ' + res.status); const total = Number(res.headers.get('content-length')) || 0; let cdName = ''; const cd = res.headers.get('content-disposition') || ''; const m = cd.match(/filename\*=utf-8''([^;]+)/i) || cd.match(/filename="?([^";]+)"?/i); if (m) { try { cdName = decodeURIComponent(m[1]); } catch (e) { cdName = m[1]; } } const reader = res.body.getReader(); const chunks = []; let got = 0, last = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); got += value.length; const now = Date.now(); if (now - last > 150) { last = now; post({ type: 'PROGRESS', id, got, total }); } } post({ type: 'PROGRESS', id, got, total }); const buf = await new Blob(chunks).arrayBuffer(); post({ type: 'BLOB', id, buf, name: name || cdName || 'document', size: got }, [buf]); } /* ============================================================ * 3. 课程框架:当前页面扫描(文档 / 视频) * ============================================================ */ if (!IS_COURSE) return; const seenSig = new Set(); function pushItem(list, item) { const name = String(item.name || '').trim(); if (!name) return; const ext = extOf(name, item.type); const key = item.key || (item.objectid ? 'obj:' + item.objectid : item.dataId ? 'data:' + item.dataId : 'url:' + (item.link || name)); const sig = key + '|' + name; if (seenSig.has(sig)) return; seenSig.add(sig); if (item.kind === 'paper') { list.push({ key, name, ext: '', group: 'paper', size: 0, objectid: '', dataId: '', link: item.link || '', kind: 'paper', duration: 0, status: item.status || '', source: item.source || 'task', paperType: item.paperType || '', workid: item.workid || '', knowledgeid: item.knowledgeid || '', questions: item.questions || null }); return; } list.push({ key, name, ext, group: item.kind === 'video' ? 'video' : groupOf(ext), size: Number(item.size) || 0, objectid: (item.objectid || '').toLowerCase(), dataId: String(item.dataId || ''), link: item.link || '', kind: item.kind || 'doc', duration: Number(item.duration) || 0, source: item.source || 'dom' }); } function parseToOpen(code) { if (!code) return null; const m = code.match(/toOpen\(\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'?(\d+)'?\s*,\s*'([^']*)'\s*,\s*'([^']*)'/); if (!m) return null; let name = m[1]; try { name = decodeURIComponent(name); } catch (e) { /* 保留原值 */ } return { name, type: m[2].toLowerCase(), dataId: m[3], objectid: (m[5] || '').toLowerCase() }; } function extractUrlFromJs(code) { if (!code) return ''; const m = code.match(/(?:window\.open|location\.href\s*=)\s*\(?\s*['"]([^'"]+)['"]/); return m ? absUrl(m[1]) : ''; } const SKIP_TYPE = new Set(['zt', 'zt_chapter', 'swift_course', 'book', 'periodical', 'note', 'topic', 'url']); const VIDEO_EXT = /^(mp4|flv|avi|mov|wmv|mkv|m4v|mp3|m4a|wav)$/; function scanDocument(doc) { const list = []; if (!doc || !doc.querySelectorAll) return list; // ① 章节附件(文档 / 视频 / 章节测验) doc.querySelectorAll('iframe[data], iframe.ans-attach-online[objectid]').forEach((f) => { const cls = String(f.className || ''); let meta = {}; try { meta = JSON.parse(f.getAttribute('data') || '{}') || {}; } catch (e) { meta = {}; } if (meta.workid) { // 章节测验 / 课内作业:标题里有题就是题目资源 const wid = String(meta.workid); const kid = pageChapterId(); pushItem(list, { key: 'work:' + wid, name: meta.title || meta.name || ('章节测验 ' + wid.slice(0, 6)), kind: 'paper', paperType: /workB/.test(meta.worktype || '') ? '作业' : '章节测验', workid: wid, knowledgeid: kid, status: '', source: 'chapter', sectionKey: 'chwork:' + (kid || ''), chapter: chapterPaths.get(kid) || '章节测验' }); return; } const objectid = (meta.objectid || meta.objectId || f.getAttribute('objectid') || '').toLowerCase(); if (!objectid) return; const nm = meta.name || meta.title || ''; const isVideo = /insertvideo/i.test(cls) || VIDEO_EXT.test(extOf(nm, meta.type)); pushItem(list, { name: nm, size: meta.size, type: meta.type, duration: meta.duration, objectid, kind: isVideo ? 'video' : 'doc', source: 'chapter' }); }); // ② 资料列表 toOpen(...) doc.querySelectorAll('[onclick*="toOpen("]').forEach((el) => { const info = parseToOpen(el.getAttribute('onclick')); if (!info || info.type === 'afolder' || SKIP_TYPE.has(info.type)) return; const isVid = info.type === 'video' || VIDEO_EXT.test(info.type); pushItem(list, { name: info.name, type: info.type, dataId: info.dataId, objectid: info.objectid, kind: isVid ? 'video' : 'doc', source: 'data' }); }); // ③ 普通文档链接 doc.querySelectorAll('a[href]').forEach((a) => { const href = a.getAttribute('href') || ''; if (!EXT_RE.test(href)) return; const url = absUrl(href, doc.baseURI); if (!url) return; let name = a.getAttribute('download') || a.getAttribute('title') || a.textContent.trim(); if (!name || !EXT_RE.test(name)) { try { name = decodeURIComponent(new URL(url).pathname.split('/').pop() || ''); } catch (e) { name = ''; } } pushItem(list, { name, link: url, type: extOf(name), source: 'link' }); }); // ④ onclick 里 window.open / location.href 指向的文档 doc.querySelectorAll('[onclick*="window.open"], [onclick*="location.href"]').forEach((el) => { const url = extractUrlFromJs(el.getAttribute('onclick')); if (!url || !EXT_RE.test(url)) return; let name = el.getAttribute('title') || el.textContent.trim(); if (!name || !EXT_RE.test(name)) { try { name = decodeURIComponent(new URL(url).pathname.split('/').pop() || ''); } catch (e) { name = ''; } } pushItem(list, { name, link: url, type: extOf(name), source: 'link' }); }); // ⑤ 任务列表里的随堂练习(mobilelearn 活动列表:li[activetype=42]) if (/^mobilelearn\./i.test(location.hostname)) { doc.querySelectorAll('li[activeid][activetype]').forEach((li) => { if (String(li.getAttribute('activetype')) !== '42') return; const activeId = (li.getAttribute('activeid') || '').trim(); if (!activeId) return; const nameEl = li.querySelector('.overHidden2') || li.querySelector('.right-content p'); let name = (nameEl ? nameEl.textContent : li.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 60); const dm = (li.textContent || '').match(/(\d{2}-\d{2})\s+\d{2}:\d{2}/); const date = dm ? dm[1] : ''; if (date && name.indexOf(date) < 0) name = name + ' ' + date; if (!name) name = '随堂练习 ' + activeId; const liTxt = li.textContent || ''; const ended = /已结束|已截止/.test(liTxt) || (/结束时间/.test(liTxt) && !/剩余/.test(liTxt)); pushItem(list, { name, link: quizUrl(activeId), type: 'task', kind: 'paper', source: 'quiz', status: ended ? '已结束' : '进行中' }); }); } // ⑥ 当前框架本身就是「已批阅测验/作业」页面:题目直接就在 DOM 里 try { if (doc.querySelectorAll('.TiMu').length) { const qs = parseWorkQuestions(doc); const head = ((doc.querySelector('.mark_title, .mark_name, .title, h1, h2') || {}).textContent || doc.title || '') .replace(/已完成|查看已批阅作业|\s+/g, ' ').trim(); const wkey = workKeyFromDoc(doc); if (wkey && qs.length) { pushItem(list, { key: 'work:' + wkey, name: head.slice(0, 60) || ('章节测验 ' + wkey.slice(0, 6)), kind: 'paper', paperType: '章节测验', workid: wkey, knowledgeid: '', status: '已作答', source: 'chapter', questions: qs, sectionKey: 'chwork:' }); } } } catch (e) { /* 忽略 */ } return list; } function workKeyFromDoc(doc) { try { const u = (doc.defaultView && doc.defaultView.location.href) || ''; const m = u.match(/[?&]oldWorkId=([0-9a-f]{32})/i); if (m) return m[1].toLowerCase(); const j = u.match(/[?&]jobid=work-([0-9a-f]{32})/i); if (j) return j[1].toLowerCase(); } catch (e) { /* 忽略 */ } return ''; } // 当前页面所属章节 id(学生学习页 / 章节页都在 URL 里带 chapterId) function pageChapterId() { const pick = (u) => { try { const q = new URL(u, location.href).searchParams; return q.get('chapterId') || q.get('knowledgeid') || q.get('knowledgeId') || ''; } catch (e) { return ''; } }; let id = pick(location.href); if (id) return id; try { const q = new URLSearchParams(location.search); id = q.get('chapterId') || q.get('knowledgeid') || ''; } catch (e) { /* 忽略 */ } return id; } // 拼随堂练习答题页地址(mobilelearn 域内) function quizUrl(activeId) { const q = new URLSearchParams(location.search); const pick = (...ks) => { for (const k of ks) { const v = q.get(k); if (v) return v; } return ''; }; const cid = pick('courseid', 'courseId'); const cla = pick('clazzid', 'classId'); const fid = pick('fid'); return 'https://mobilelearn.chaoxing.com/page/quiz/stu/answerQuestion2?' + new URLSearchParams({ courseId: cid, classId: cla, activeId, fid, timetable: '' }).toString(); } // 递归扫描同源框架:章节学习页里测验嵌在「cards → work 模块 → 题目页」三层 iframe 内 function scanAll() { const out = scanDocument(document); const seen = new Set([document]); let level = [document]; for (let depth = 0; depth < 4 && level.length; depth++) { const next = []; level.forEach((d) => { const frames = d.querySelectorAll('iframe'); for (let i = 0; i < frames.length; i++) { let cd = null; try { cd = frames[i].contentDocument; } catch (e) { continue; } if (!cd || seen.has(cd)) continue; seen.add(cd); next.push(cd); try { out.push(...scanDocument(cd)); } catch (e) { /* 忽略 */ } } }); level = next; } return out; } const state = { scanned: false }; function postToTop(msg) { try { window.top.postMessage(Object.assign({ [MSG]: 1 }, msg), '*'); } catch (e) { /* 忽略 */ } } function report() { const items = scanAll(); state.scanned = true; postToTop({ type: 'RESOURCES', items, ctx: readCtx(location.href), url: location.href }); } function openAttachment(objectid) { const nodes = document.querySelectorAll('iframe.ans-attach-online[objectid], [objectid]'); for (const n of nodes) { if ((n.getAttribute('objectid') || '').toLowerCase() !== objectid) continue; try { n.scrollIntoView({ block: 'center', behavior: 'smooth' }); (n.closest('.ans-attach, .attach, li') || n).click(); return true; } catch (e) { /* 继续 */ } } return false; } if (!IS_TOP) { window.addEventListener('message', async (ev) => { const d = ev.data; if (!d || d[MSG] !== 1) return; if (d.type === 'HELLO') { report(); return; } if (d.type === 'VIDEO_INFO') { try { const u = '/ananas/status/' + d.objectid + '?k=' + (d.fid || hiddenVars().fid || '1730') + '&flag=normal&ro=0&_dc=' + Date.now(); const r = await fetch(u, { credentials: 'include' }); postToTop({ type: 'VIDEO_INFO_RESULT', id: d.id, text: await r.text() }); } catch (e) { postToTop({ type: 'VIDEO_INFO_RESULT', id: d.id, error: cleanErr(e) }); } return; } if (d.type === 'OPEN') { const ok = openAttachment(String(d.objectid || '').toLowerCase()); postToTop({ type: 'OPEN_RESULT', key: d.key, ok }); } }); let timer = 0; const schedule = () => { clearTimeout(timer); timer = setTimeout(report, SCAN_DEBOUNCE); }; report(); [1200, 3000, 7000].forEach((t) => setTimeout(report, t)); try { new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true }); } catch (e) { /* 忽略 */ } return; } /* ============================================================ * 4. 顶层:状态 * ============================================================ */ if (document.documentElement.hasAttribute('data-cxdl')) return; document.documentElement.setAttribute('data-cxdl', VERSION); const store = { get(k, dflt) { try { if (typeof GM_getValue === 'function') return GM_getValue(k, dflt); } catch (e) { /* 回退 */ } try { const v = localStorage.getItem('cxdl.' + k); return v == null ? dflt : JSON.parse(v); } catch (e) { return dflt; } }, set(k, v) { try { if (typeof GM_setValue === 'function') { GM_setValue(k, v); return; } } catch (e) { /* 回退 */ } try { localStorage.setItem('cxdl.' + k, JSON.stringify(v)); } catch (e) { /* 忽略 */ } } }; const docs = new Map(); // key -> doc item const videos = new Map(); // key -> video item const papers = new Map(); // key -> paper item(作业/考试) const statusMap = new Map(); // key -> { state, pct, msg } const owners = new Map(); const ownerMeta = new Map(); const fileIndex = new Map(); const previewWaiters = new Map(); const pendingTasks = new Map(); const videoIndex = new Map(); // objectid -> { http, download, filename, length } const ui = { tab: store.get('tab', 'docs'), groupBy: store.get('groupBy', 'place'), folded: new Set(), exportFields: store.get('exportFields', { stem: true, correct: true, mine: true, analysis: false }), filter: store.get('filter', 'all'), selected: new Set(), collapsed: !!store.get('collapsed', false), pos: store.get('pos', null), size: store.get('size', null), scanning: false }; const queue = []; let running = 0; let seqCounter = 0; /* ============================================================ * 5. 网络与解析 * ============================================================ */ function httpGet(url) { return new Promise((resolve, reject) => { let same = false; try { same = new URL(url, location.href).origin === location.origin; } catch (e) { same = false; } if (same) { fetch(url, { credentials: 'include' }) .then(async (r) => resolve({ status: r.status, text: await r.text() })) .catch((e) => reject(new Error('请求失败:' + cleanErr(e)))); return; } if (typeof GM_xmlhttpRequest !== 'function') { fetch(url, { credentials: 'include' }) .then(async (r) => resolve({ status: r.status, text: await r.text() })) .catch((e) => reject(new Error('请求失败:' + cleanErr(e)))); return; } GM_xmlhttpRequest({ method: 'GET', url, timeout: 30000, onload: (r) => resolve({ status: r.status, text: r.responseText }), onerror: () => reject(new Error('跨域请求失败')), ontimeout: () => reject(new Error('请求超时')) }); }); } async function getDoc(url) { const r = await httpGet(url); return stripTags(new DOMParser().parseFromString(r.text || '', 'text/html')); } function ctx() { const c = readCtx(location.href); if (c.courseid && c.clazzid) return c; // 从任意同源框架补齐 const frames = document.querySelectorAll('iframe'); for (const f of frames) { try { const c2 = readCtx(f.contentWindow.location.href); if (c2.courseid && c2.clazzid) return c2; } catch (e) { /* 忽略 */ } } return c; } // 课程页把各模块的 enc / 机构 id 放在隐藏域里,作业、考试接口必须带上 function hiddenVars() { const ids = ['workEnc', 'examEnc', 'enc', 'oldenc', 'fid', 'cpi', 'courseId', 'courseid', 'classId', 'clazzid']; const out = {}; const read = (doc) => { ids.forEach((id) => { if (out[id]) return; try { const el = doc.getElementById(id); if (el && el.value) out[id] = el.value; } catch (e) { /* 忽略 */ } }); }; read(document); document.querySelectorAll('iframe').forEach((f) => { try { if (f.contentDocument) read(f.contentDocument); } catch (e) { /* 跨域 */ } }); return out; } // 隐藏域不存在时(例如在章节页),从课程主页 HTML 里抓模块 enc async function moduleEncs(c) { const vars = hiddenVars(); if (vars.workEnc && vars.examEnc) return vars; try { const q = new URLSearchParams({ courseid: c.courseid, clazzid: c.clazzid, cpi: c.cpi, enc: c.enc || '', t: c.t || '', pageHeader: 1 }).toString(); const r = await httpGet('https://mooc2-ans.chaoxing.com/mooc2-ans/mycourse/stu?' + q); const html = r.text || ''; const grab = (id) => { const m = html.match(new RegExp('id="' + id + '"[^>]*value="([^"]*)"')); return m ? m[1] : ''; }; return Object.assign(vars, { workEnc: vars.workEnc || grab('workEnc'), examEnc: vars.examEnc || grab('examEnc'), oldenc: vars.oldenc || grab('oldenc') }); } catch (e) { return vars; } } /* ============================================================ * 5.5 章节测验(work 模块):地址构建与题目解析 * ============================================================ */ const chapterCardsCache = new Map(); // kid -> { host, html, setting, mooc2 } const chapterPaths = new Map(); // kid -> 「1 改革开放拉开大幕」 // 课件页 HTML 里内嵌了一份 AttachmentSetting(含 ktoken 与每个任务点的 enc), // 测验接口必须带这两个参数,否则一律 403。用括号配对把它整段切出来。 function extractSettingJson(html) { if (!html) return null; const start = html.indexOf('"hiddenConfig"'); if (start < 0) return null; const open = html.lastIndexOf('{', start); if (open < 0) return null; let depth = 0, inStr = false, esc = false; for (let i = open; i < html.length; i++) { const ch = html[i]; if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; } if (ch === '"') { inStr = true; continue; } if (ch === '{') depth++; else if (ch === '}') { depth--; if (depth === 0) { try { return JSON.parse(html.slice(open, i + 1)); } catch (e) { return null; } } } } return null; } function cardHosts(c) { return (c && c.oldCourse) ? ['https://mooc1-1.chaoxing.com', 'https://mooc1.chaoxing.com'] : ['https://mooc1.chaoxing.com', 'https://mooc1-1.chaoxing.com']; } // 取某章的课件页(顺带拿到 AttachmentSetting),结果缓存,扫描和导出复用 async function fetchCards(c, ch) { const kid = ch && ch.id ? String(ch.id) : ''; if (!kid) return { host: cardHosts(c)[0], html: '', setting: null, kid: '' }; const hit = chapterCardsCache.get(kid); if (hit) return hit; const hosts = cardHosts(c); let fallback = null; for (const host of hosts) { for (const m2 of [1, 0]) { const u = host + '/mooc-ans/knowledge/cards?' + new URLSearchParams({ clazzid: c.clazzid, courseid: c.courseid, knowledgeid: kid, num: 0, ut: 's', cpi: c.cpi || '', mooc2: m2 }).toString(); let html = ''; try { html = (await httpGet(u)).text || ''; } catch (e) { html = ''; } if (!html || html.length < 400) continue; const set = extractSettingJson(html); const rec = { host, html, setting: set, mooc2: m2, kid }; if (set) { chapterCardsCache.set(kid, rec); return rec; } if (!fallback) fallback = rec; } } const rec = fallback || { host: hosts[0], html: '', setting: null, kid }; chapterCardsCache.set(kid, rec); return rec; } async function chapterSetting(c, kid) { if (!kid) return { host: cardHosts(c)[0], setting: null, kid: '' }; const hit = chapterCardsCache.get(kid); if (hit) return hit; return fetchCards(c, { id: kid, name: kid }); } // /mooc-ans/api/work:带齐 ktoken/enc 才会 302 到「已批阅作业」题目页 function workApiUrl(c, p, rec) { const wid = String(p.workid || ''); if (!wid) return ''; const set = rec && rec.setting; const d = (set && set.defaults) || {}; const atts = (set && set.attachments) || []; const att = atts.find((a) => a && a.property && String(a.property.workid) === wid) || atts.find((a) => a && String(a.jobid || '') === 'work-' + wid) || {}; const host = (rec && rec.host) || cardHosts(c)[0]; const qs = new URLSearchParams({ api: '1', workId: wid, jobid: 'work-' + wid, originJobId: 'work-' + wid, needRedirect: 'true', skipHeader: 'true', knowledgeid: String(p.knowledgeid || (rec && rec.kid) || ''), ktoken: String(d.ktoken || ''), cpi: String(d.cpi || c.cpi || ''), ut: 's', clazzId: String(d.clazzId || c.clazzid || ''), type: '', enc: String(att.enc || '') }); try { if (window.utEnc) qs.set('utenc', window.utEnc); } catch (e) { /* 忽略 */ } qs.set('courseid', String(d.courseid || c.courseid || '')); return host + '/mooc-ans/api/work?' + qs.toString(); } async function fetchWorkQuestions(c, p) { const kid = String(p.knowledgeid || ''); const rec = await chapterSetting(c, kid); if (!rec || !rec.setting) throw new Error('未取到章节设置(先在课程里打开该章)'); const url = workApiUrl(c, p, rec); if (!url) throw new Error('缺少测验 id'); const r = await httpGet(url); const html = r.text || ''; if (!html) throw new Error('测验接口无返回'); if (html.length < 5000 && /没有权限|无权限|\[3004\]/.test(html)) { throw new Error('该测验没开放查看(需先作答或已过期)'); } const qs = parseWorkQuestions(html); if (!qs.length) throw new Error('未解析到题目'); return qs.map((q, i) => Object.assign({}, q, { no: i + 1 })); } const QTYPE_HINT = /(单选题|多选题|判断题|填空题|简答题|名词解释|论述题|计算题|材料题|辨析题|问答题|其他题)/; function parseWorkQuestions(input) { let doc = input; if (typeof input === 'string') { try { doc = new DOMParser().parseFromString(input, 'text/html'); } catch (e) { return []; } } if (!doc || !doc.querySelectorAll) return []; try { doc.querySelectorAll('script,style,noscript').forEach((n) => n.remove()); } catch (e) { /* 忽略 */ } const out = []; doc.querySelectorAll('.TiMu, .questionLi').forEach((node, i) => { const q = readWorkQuestion(node, i); if (q && (q.stem || (q.options || []).length)) out.push(q); }); if (out.length) return out; const text = domToText(doc.body || doc.documentElement); return splitQuestions(text).map((q) => ({ no: q.no, type: q.type, stem: q.stem, options: [], correct: q.correct, mine: q.mine, analysis: q.analysis })); } // 答案统一成「A. 选项正文;B. 选项正文」这种可读形式 function formatAnswer(mark, text, options) { const m = String(mark || '').trim(); const t = String(text || '').trim(); if (/^[A-Za-z]+$/.test(m) && options && options.length) { return m.split('').map((L) => { const hit = options.find((o) => String(o.name || '').toUpperCase() === L.toUpperCase()); return L + (hit ? '. ' + hit.text : ''); }).join(';'); } if (!m) return t; if (!t) return m; if (t.indexOf(m) === 0) return t; return m + ' ' + t; } function readWorkQuestion(node, i) { const titleEl = node.querySelector('.Zy_TItle, .TiMu_title, .question-title') || node; const titleText = (titleEl.textContent || '').replace(/\s+/g, ' ').trim(); let typeName = ''; const tm = titleText.match(/【\s*([^】]{1,12})\s*】/); if (tm) typeName = tm[1].trim(); if (!typeName) { let prev = node.previousElementSibling; for (let k = 0; prev && k < 4; k++, prev = prev.previousElementSibling) { const m = ((prev.textContent || '').replace(/\s+/g, ' ')).match(QTYPE_HINT); if (m) { typeName = m[1]; break; } } } const clone = titleEl.cloneNode(true); Array.from(clone.querySelectorAll('i')).forEach((n) => { if (/^\s*\d+\s*$/.test(n.textContent || '')) n.remove(); }); const stem = domToText(clone).replace(/^【[^】]{1,12}】\s*/, '').replace(/\s+/g, ' ').trim(); const options = Array.from(node.querySelectorAll('ul.Zy_ulTop > li, .Zy_ulTop li')).map((li) => { const markEl = li.querySelector('i'); const name = markEl ? (markEl.textContent || '').trim().replace(/[、..::\s]/g, '') : ''; const bodyEl = li.querySelector('a') || li; return { name, text: domToText(bodyEl).replace(/\s+/g, ' ').trim() }; }).filter((o) => o.text); let correct = '', mine = '', score = '', analysis = ''; const py = node.querySelector('.Py_answer'); if (py) { const sm = (py.textContent || '').match(/得分\s*[::]\s*([\d.]+)/); if (sm) score = sm[1]; // 填空 / 简答:按「第 N 空」逐空给出作答内容 const blanks = Array.from(py.querySelectorAll('.blankcon')); if (blanks.length) { mine = blanks.map((b, i) => { const t = domToText(b).replace(/\s+/g, ' ').trim(); return t ? (i + 1) + ') ' + t : ''; }).filter(Boolean).join(';'); } const parts = []; Array.from(py.children).forEach((c) => { const cls = String(c.className || ''); if (/element-invisible-hidden/.test(cls)) { const last = parts[parts.length - 1]; if (last && !last.text) { last.text = domToText(c).replace(/^[::;;\s]+/, '').replace(/[;;]\s*$/, '').replace(/\s+/g, ' ').trim(); } return; } // 只取直接文本节点做标题,避免把内部的「得分:」也算进答案 const own = Array.from(c.childNodes) .filter((n) => n.nodeType === 3).map((n) => n.nodeValue).join('') .replace(/\s+/g, ' ').trim(); const full = (c.textContent || '').replace(/\s+/g, ' ').trim(); if (/^正确答案/.test(full) || /^我的答案/.test(full)) { const label = /^正确答案/.test(full) ? 'correct' : 'mine'; if (parts.some((p) => p.k === label)) return; const mark = full.slice(own.length).trim() || full.replace(/^(正确答案|我的答案)\s*[::]?/, '').trim() .replace(/得分\s*[::].*$/, '').trim(); parts.push({ k: label, mark, text: '' }); } }); parts.forEach((p) => { const val = formatAnswer(p.mark, p.text, options); if (p.k === 'correct' && val) correct = val; // 填空/简答已按「逐空」取到作答,别被外层「我的答案:得分…」覆盖 else if (p.k === 'mine' && val && !blanks.length) mine = val; }); } const an = node.querySelector('.analysis, .Py_analysis, .answerAnalysis, .Py_answer2'); if (an) analysis = domToText(an).replace(/^【?\s*答案解析\s*】?\s*[::]?/, '').replace(/\s+/g, ' ').trim(); const numEl = titleEl.querySelector('i'); const no = Number((numEl && numEl.textContent || '').trim()) || (i + 1); return { no, type: typeName + (score ? '(' + score + ' 分)' : ''), stem, options, correct, mine, analysis }; } /* ============================================================ * 6. 全课程扫描 * ============================================================ */ const scanState = { done: false, total: 0, finished: 0, label: '' }; function setScanLabel(label, finished, total) { scanState.label = label; if (typeof finished === 'number') scanState.finished = finished; if (typeof total === 'number') scanState.total = total; updateFoot(); } async function scanCourse() { if (ui.scanning) return; const c = ctx(); if (!c.courseid || !c.clazzid) { setScanLabel('未识别到课程参数,请在课程页面使用'); return; } ui.scanning = true; render(); const mk = (origin, path, params) => { const q = new URLSearchParams(params).toString(); return origin + path + (q ? '?' + q : ''); }; const mooc1 = 'https://mooc1.chaoxing.com'; let chapters = []; let done = 0; try { // ---- 6.1 章节树 ---- setScanLabel('读取章节列表…', 0, 0); const treeUrl = mk(mooc1, '/mooc-ans/mycourse/studentstudycourselist', { courseId: c.courseid, chapterId: c.chapterid || '', clazzid: c.clazzid, cpi: c.cpi, mooc2: 1, isMicroCourse: 'false' }); const treeDoc = await getDoc(treeUrl); chapters = parseChapters(treeDoc); chapters.forEach((ch) => chapterPaths.set(ch.id, ch.path)); } catch (e) { setScanLabel('章节列表读取失败,先读资料区…', 0, 0); } // 旧版泛雅课程(公选课等):目录页用 toOld(...),卡片接口也是旧版 if (!chapters.length) { try { setScanLabel('检测到旧版课程,读取旧版目录…', 0, 0); const ocUrl = mk('https://mooc2-ans.chaoxing.com', '/mooc2-ans/mycourse/studentcourse', { courseid: c.courseid, clazzid: c.clazzid, cpi: c.cpi, ut: 's', t: c.t || '', stuenc: c.stuenc || c.enc || '' }); const ocDoc = await getDoc(ocUrl); chapters = parseOldChapters(ocDoc); if (chapters.length) c.oldCourse = true; } catch (e) { /* 忽略 */ } } try { // ---- 6.2 逐章课件 ---- if (chapters.length) { setScanLabel('章节 ' + chapters.length + ' 个,开始读取课件…', 0, chapters.length); const chunks = []; for (let i = 0; i < chapters.length; i += 3) { const batch = chapters.slice(i, i + 3); const res = await Promise.all(batch.map(async (ch) => { try { // fetchCards 会同时拿到课件与 AttachmentSetting(测验接口要用的 ktoken/enc) const got = await fetchCards(c, ch); if (!got || !got.html) return []; const d = new DOMParser().parseFromString(got.html, 'text/html'); return parseCards(stripTags(d), ch); } catch (e) { return []; } })); res.forEach((arr) => chunks.push(...arr)); done += batch.length; setScanLabel('读取课件 ' + done + '/' + chapters.length, done, chapters.length); await sleep(120); } chunks.forEach((it) => ingest(it, null)); } // ---- 6.3 资料区(含文件夹递归) ---- setScanLabel('读取资料区…', done, chapters.length); try { await scanDataArea(c, (label) => setScanLabel(label, done, chapters.length)); } catch (e) { /* 资料区可能无权限,忽略 */ } // ---- 6.4 作业 / 6.5 考试(需要模块 enc) ---- const encs = await moduleEncs(c); setScanLabel('读取作业…', done, chapters.length); try { const wl = mk(mooc1, '/mooc2/work/list', { courseId: c.courseid, classId: c.clazzid, cpi: c.cpi, ut: 's', t: c.t || '', stuenc: c.stuenc || '', enc: encs.workEnc || c.enc || '' }); const wd = await getDoc(wl); parseWorkList(wd).forEach((p) => ingestPaper(p)); } catch (e) { /* 忽略 */ } setScanLabel('读取考试…', done, chapters.length); try { const el = mk(mooc1, '/exam-ans/mooc2/exam/exam-list', { courseid: c.courseid, clazzid: c.clazzid, cpi: c.cpi, ut: 's', t: c.t || '', stuenc: c.stuenc || '', enc: encs.examEnc || c.enc || '' }); const ed = await getDoc(el); parseExamList(ed).forEach((p) => ingestPaper(p)); } catch (e) { /* 忽略 */ } scanState.done = true; saveCache(c.courseid); let doneMsg = '扫描完成:文档 ' + docs.size + ' · 视频 ' + videos.size + ' · 题目 ' + papers.size; if (c.oldCourse && !docs.size && !videos.size) { doneMsg = '旧版课程未发现可下载附件 · 打开章节学习页可自动收录'; } else if (!docs.size && !videos.size && !papers.size) { doneMsg = '扫描结果为空(可能未登录或被限流)· 请重试'; } setScanLabel(doneMsg, 1, 1); render(); } catch (e) { setScanLabel('扫描失败:' + cleanErr(e), 0, 0); } finally { ui.scanning = false; render(); } } const CACHE_TTL = 6 * 3600 * 1000; function cacheKey(cid) { return 'scan:' + cid; } function saveCache(cid) { if (!docs.size && !videos.size && !papers.size) return; // 空结果绝不写缓存 try { const old = store.get(cacheKey(cid), null) || {}; const merge = (a, b) => { const m = new Map(); (a || []).forEach((x) => { if (x && x.key) m.set(x.key, x); }); (b || []).forEach((x) => { if (x && x.key) m.set(x.key, x); }); return Array.from(m.values()); }; // 合并写:某个页面只能看到部分资源时,不覆盖已有缓存 store.set(cacheKey(cid), { t: Date.now(), docs: merge(old.docs, Array.from(docs.values())), videos: merge(old.videos, Array.from(videos.values())), papers: merge(old.papers, Array.from(papers.values())) }); } catch (e) { /* 忽略 */ } } function hydrateCache(payload) { if (!payload) return 0; let n = 0; (payload.docs || []).forEach((it) => { ingest(it, null); n++; }); (payload.videos || []).forEach((it) => { ingest(it, null); n++; }); (payload.papers || []).forEach((pp) => { ingestPaper(pp); n++; }); return n; } function autoScan(force) { if (ui.scanning) return; if (document.querySelector('#loginForm, .loginForm, input[name="uname"], #phone')) { setScanLabel('当前是登录页,已暂停自动扫描', 0, 0); return; } const c = ctx(); if (!c.courseid || !c.clazzid) return; const cached = store.get(cacheKey(c.courseid), null); const empty = cached && !(cached.docs || []).length && !(cached.videos || []).length && !(cached.papers || []).length; if (cached && !empty && !force) { const added = hydrateCache(cached); if (added) render(); const fresh = Date.now() - (cached.t || 0) < CACHE_TTL; if (fresh) { scanState.done = true; const mins = Math.round((Date.now() - cached.t) / 60000); const when = mins < 1 ? '刚刚' : (mins < 60 ? mins + ' 分钟前' : Math.round(mins / 60) + ' 小时前'); setScanLabel('已载入缓存(' + when + ')· 点「扫描」可刷新', 1, 1); return; } } scanCourse(); } // 目录树两级结构:div.posCatalog_select.firstLayer 是「章」,其下的 .posCatalog_name 是「节」。 // 保留「1.1」这类编号,并按章分组,避免旧课程 26 个章节平铺。 function parseChapters(doc) { const out = []; const seen = new Set(); let unitNo = '', unitTitle = ''; const blocks = doc.querySelectorAll('.posCatalog_select, [onclick*="getTeacherAjax"]'); blocks.forEach((el) => { const isFirst = /\.firstLayer|\bfirstLayer\b/.test(String(el.className || '')); if (isFirst) { const t = el.querySelector('.posCatalog_title, span[title]') || el; const nm = (t.getAttribute && t.getAttribute('title')) || ''; const noEl = el.querySelector('.posCatalog_sbar, em'); unitNo = noEl ? (noEl.textContent || '').trim() : ''; unitTitle = (nm || (el.textContent || '')).replace(/\s+/g, ' ').trim(); return; } const link = el.matches && el.matches('[onclick*="getTeacherAjax"]') ? el : el.querySelector('[onclick*="getTeacherAjax"]'); if (!link) return; const m = (link.getAttribute('onclick') || '').match(/getTeacherAjax\(\s*'[^']*'\s*,\s*'[^']*'\s*,\s*'(\d+)'/); if (!m) return; const id = m[1]; if (seen.has(id)) return; seen.add(id); const noEl = el.querySelector('.posCatalog_sbar, em'); const no = noEl ? (noEl.textContent || '').trim() : ''; const t = link.getAttribute('title') || (el.textContent || '').replace(/\s+/g, ' ').trim(); const title = t.replace(/\s+/g, ' ').trim(); out.push({ id, name: (no ? no + ' ' : '') + (title || id), level: 1, unitNo, unitTitle }); }); out.forEach((ch, i) => { const head = [ch.unitNo, ch.unitTitle].filter(Boolean).join(' '); ch.path = head || '课程章节'; ch.order = i; }); return out; } // 旧版目录:.chapter_item + toOld('courseid','knowledgeid','clazzid',0) function parseOldChapters(doc) { const out = []; const seen = new Set(); doc.querySelectorAll('[onclick*="toOld("]').forEach((el) => { const m = (el.getAttribute('onclick') || '').match(/toOld\(\s*'[^']*'\s*,\s*'(\d+)'\s*,\s*'[^']*'/); if (!m) return; const id = m[1]; if (seen.has(id)) return; seen.add(id); const name = (el.getAttribute('title') || el.textContent.replace(/\s+/g, ' ').trim() || id) .replace(/已完成$/, '').trim() || id; out.push({ id, name, level: 1, path: name, order: out.length }); }); return out; } function parseCards(doc, ch) { const list = []; doc.querySelectorAll('iframe[data], iframe.ans-attach-online[objectid]').forEach((f) => { const cls = String(f.className || ''); let meta = {}; try { meta = JSON.parse(f.getAttribute('data') || '{}') || {}; } catch (e) { meta = {}; } const objectid = (meta.objectid || meta.objectId || f.getAttribute('objectid') || '').toLowerCase(); if (meta.workid) { const wid = String(meta.workid); list.push({ key: 'work:' + wid, name: meta.title || meta.name || ('章节测验 ' + wid.slice(0, 6)), kind: 'paper', paperType: /workB/.test(meta.worktype || '') ? '作业' : '章节测验', workid: wid, knowledgeid: ch ? ch.id : '', status: '', chapter: ch ? (ch.path || ch.name) : '', sectionKey: ch ? 'chwork:' + ch.id : '', order: ch ? ch.order : 9000, source: 'chapter' }); return; } if (!objectid) return; const name = meta.name || meta.title || objectid; const ext = extOf(name, meta.type); const isVideo = /insertvideo/i.test(cls) || VIDEO_EXT.test(ext); if (!isVideo && groupOf(ext) === 'other') return; list.push({ key: 'obj:' + objectid, name, ext, group: isVideo ? 'video' : groupOf(ext), size: Number(meta.size) || 0, objectid, dataId: '', link: '', kind: isVideo ? 'video' : 'doc', duration: Number(meta.duration) || 0, chapter: ch ? (ch.path || ch.name) : '', sectionKey: ch ? 'ch:' + ch.id : '', order: ch ? ch.order : 9000, source: 'chapter' }); }); return list; } // 资料区解析:同时返回文件与子文件夹 function parseDatalistAll(doc) { const items = [], folders = []; doc.querySelectorAll('[onclick*="toOpen("]').forEach((el) => { const code = el.getAttribute('onclick'); const m = code.match(/toOpen\(\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'?(\d+)'?\s*,\s*'([^']*)'\s*,\s*'([^']*)'/); if (!m) return; let name = m[1]; try { name = decodeURIComponent(name); } catch (e) { /* 保留 */ } const type = m[2].toLowerCase(); const dataId = m[3]; if (type === 'afolder') { folders.push({ name, dataId }); return; } if (SKIP_TYPE.has(type)) return; const objectid = (m[5] || '').toLowerCase(); const ext = extOf(name, type); const isVid = type === 'video' || VIDEO_EXT.test(type) || VIDEO_EXT.test(ext); if (!isVid && groupOf(ext) === 'other') return; items.push({ key: objectid ? 'obj:' + objectid : 'data:' + dataId, name, ext, group: isVid ? 'video' : groupOf(ext), size: 0, objectid, dataId, link: '', kind: isVid ? 'video' : 'doc', source: 'data' }); }); return { items, folders }; } // 逐层遍历资料区文件夹(type=1 + dataId 即进入子目录) async function scanDataArea(c, onLabel) { const base = 'https://mooc2-ans.chaoxing.com/mooc2-ans/coursedata/stu-datalist'; const mkUrl = (extra) => base + '?' + new URLSearchParams(Object.assign({ courseid: c.courseid, clazzid: c.clazzid, cpi: c.cpi, ut: 's', t: c.t || '', stuenc: c.stuenc || '' }, extra)).toString(); const visited = new Set(); const queue = [{ name: '', id: '', path: '资料', order: 5000, depth: 0 }]; let foldersDone = 0; while (queue.length && visited.size < 40) { const node = queue.shift(); const vkey = node.id || 'root'; if (visited.has(vkey)) continue; visited.add(vkey); let doc; try { doc = await getDoc(node.id ? mkUrl({ type: 1, dataName: node.name, dataId: node.id }) : mkUrl({})); } catch (e) { continue; } const { items, folders } = parseDatalistAll(doc); const order = node.order + node.depth * 0.01; items.forEach((it, idx) => { it.chapter = node.path; it.sectionKey = 'dir:' + (node.id || 'root'); it.order = order; it.seq = idx; ingest(it, null); }); folders.forEach((f, fi) => { if (!visited.has(f.dataId)) { queue.push({ name: f.name, id: f.dataId, path: node.path + ' / ' + f.name, order: order + (fi + 1) * 0.5, depth: node.depth + 1 }); } }); foldersDone++; if (onLabel) onLabel('读取资料 ' + foldersDone + ' 个目录 · 待处理 ' + queue.length); await sleep(90); } } function parseWorkList(doc) { const out = []; doc.querySelectorAll('li[data]').forEach((li) => { const url = li.getAttribute('data') || ''; if (!/workId=\d+/.test(url)) return; const name = (li.querySelector('.overHidden2') || {}).textContent; const status = (li.querySelector('.status') || {}).textContent; out.push({ key: 'work:' + (url.match(/workId=(\d+)/) || [])[1], name: (name || '未命名作业').trim(), kind: 'paper', paperType: '作业', status: (status || '').trim(), url: url.replace(/\/task\?/, '/view?'), sectionKey: 'paper:work', chapter: '作业', order: 0, source: 'work' }); }); return out; } function parseExamList(doc) { const out = []; const seen = new Set(); doc.querySelectorAll('[onclick*="viewExamAnswer"]').forEach((el) => { const m = (el.getAttribute('onclick') || '').match(/viewExamAnswer\(\s*'(\d+)'\s*,\s*'(\d+)'/); if (!m) return; const [, examId, answerId] = m; if (seen.has(examId)) return; seen.add(examId); const box = el.closest('li') || el.parentElement; const name = ((box && box.querySelector('.overHidden2')) || el).textContent.trim(); const status = ((box && box.querySelector('.status')) || {}).textContent || ''; out.push({ key: 'exam:' + examId, name: name || '未命名考试', kind: 'paper', paperType: '考试', status: (status || '').trim(), examId, answerId, sectionKey: 'paper:exam', chapter: '考试', order: 1, source: 'exam' }); }); return out; } /* ============================================================ * 7. 消息总线(当前页面发现 / 预览页回报) * ============================================================ */ window.addEventListener('message', (ev) => { const d = ev.data; if (!d || d[MSG] !== 1 || !isChaoxingOrigin(ev.origin)) return; if (d.type === 'RESOURCES') { const before = docs.size + videos.size; (d.items || []).forEach((it) => ingest(it, ev.source, d.url)); if (docs.size + videos.size !== before) render(); return; } if (d.type === 'FILEINFO') { const oid = String(d.objectid || '').toLowerCase(); if (!oid) return; fileIndex.set(oid, { download: d.download, name: d.name, size: Number(d.size) || 0, win: ev.source }); docs.forEach((item) => { if (item.objectid !== oid) return; if (d.name && (!item.name || item.name === oid)) item.name = d.name; if (d.size && !item.size) item.size = Number(d.size); if (statusMap.get(item.key) && statusMap.get(item.key).state === 'needpreview') setStatus(item.key, { state: 'idle' }); }); flushPreviewWaiters('obj:' + oid, fileIndex.get(oid)); render(); return; } if (d.type === 'VIDEO_INFO_RESULT') { const fn = videoWaiters.get(d.id); if (!fn) return; videoWaiters.delete(d.id); fn(d.text || ''); return; } if (d.type === 'PROGRESS') { const t = pendingTasks.get(d.id); if (t && t.onProgress) t.onProgress(d.got, d.total); return; } if (d.type === 'BLOB') { const t = pendingTasks.get(d.id); if (!t) return; pendingTasks.delete(d.id); t.resolve({ buf: d.buf, name: d.name, size: d.size }); return; } if (d.type === 'FETCH_ERR') { const t = pendingTasks.get(d.id); if (!t) return; pendingTasks.delete(d.id); t.reject(new Error(d.error || '下载失败')); } }); function flushPreviewWaiters(key, value) { const arr = previewWaiters.get(key); if (!arr || !arr.length) return; previewWaiters.delete(key); arr.forEach((fn) => fn(value)); } function ingest(raw, source, frameUrl) { if (!raw || !raw.key) return; if (raw.kind === 'paper') { const isQuiz = raw.source === 'quiz'; const isChapter = raw.source === 'chapter'; ingestPaper({ key: raw.key, name: raw.name, kind: 'paper', paperType: raw.paperType || (isQuiz ? '随堂练习' : (isChapter ? '章节测验' : '任务')), status: raw.status || '', url: raw.link || '', workid: raw.workid || '', knowledgeid: raw.knowledgeid || '', questions: raw.questions || null, sectionKey: raw.sectionKey || (isQuiz ? 'paper:quiz' : (isChapter ? 'chwork' : 'paper:task')), chapter: raw.chapter || (isQuiz ? '随堂练习' : (isChapter ? '章节测验' : '任务')), order: raw.order != null ? raw.order : (isQuiz ? 2 : 3), source: raw.source || 'task' }); return; } const isVideo = raw.kind === 'video' || raw.group === 'video'; const bucket = isVideo ? videos : docs; const name = String(raw.name || '').trim(); if (!name) return; if (source) { owners.set(raw.key, source); if (frameUrl) { try { ownerMeta.set(raw.key, { origin: new URL(frameUrl).origin, url: frameUrl }); } catch (e) { /* 忽略 */ } } } const existing = bucket.get(raw.key); if (existing) { if (name && name !== raw.objectid && (!existing.name || existing.name === existing.objectid)) existing.name = name; if (raw.size && !existing.size) existing.size = Number(raw.size); if (raw.link && !existing.link) existing.link = raw.link; if (raw.dataId && !existing.dataId) existing.dataId = raw.dataId; // 扫描得到的目录信息优先于页面即时抓到的(后者没有路径) if (raw.sectionKey && raw.source !== 'dom') { existing.sectionKey = raw.sectionKey; existing.chapter = raw.chapter || existing.chapter; existing.order = raw.order; if (raw.seq != null) existing.seq = raw.seq; } return; } bucket.set(raw.key, { key: raw.key, name: name || raw.objectid, ext: raw.ext || extOf(name), group: raw.group || (isVideo ? 'video' : groupOf(raw.ext || extOf(name))), size: Number(raw.size) || 0, objectid: raw.objectid || '', dataId: raw.dataId || '', link: raw.link || '', kind: isVideo ? 'video' : 'doc', duration: Number(raw.duration) || 0, chapter: raw.chapter || '', sectionKey: raw.sectionKey || '', order: raw.order != null ? raw.order : 9000, seq: raw.seq != null ? raw.seq : seqCounter++, source: raw.source || 'dom' }); if (!statusMap.has(raw.key)) statusMap.set(raw.key, { state: 'idle', pct: 0, msg: '' }); } function ingestPaper(p) { if (!p || !p.key) return; const old = papers.get(p.key); if (old) { old.status = p.status || old.status; old.url = p.url || old.url; old.name = p.name || old.name; if (p.paperType) old.paperType = p.paperType; if (p.workid) old.workid = p.workid; if (p.knowledgeid) old.knowledgeid = p.knowledgeid; if (p.questions && p.questions.length) old.questions = p.questions; const generic = !p.chapter || p.chapter === '章节测验' || p.chapter === '题目'; if (p.sectionKey && p.source !== 'dom') { if (!(generic && old.chapter && old.chapter !== '章节测验')) { old.sectionKey = p.sectionKey; old.chapter = p.chapter || old.chapter; if (p.order != null) old.order = p.order; } } return; } papers.set(p.key, p); if (!statusMap.has(p.key)) statusMap.set(p.key, { state: 'idle', pct: 0, msg: '' }); } /* ============================================================ * 8. 文档下载 * ============================================================ */ function broadcast(msg) { document.querySelectorAll('iframe').forEach((f) => { try { f.contentWindow.postMessage(Object.assign({ [MSG]: 1 }, msg), '*'); } catch (e) { /* 忽略 */ } }); } function waitPreview(key, timeout) { return new Promise((resolve) => { const arr = previewWaiters.get(key) || []; arr.push(resolve); previewWaiters.set(key, arr); setTimeout(() => { const cur = previewWaiters.get(key); if (!cur) return; const i = cur.indexOf(resolve); if (i >= 0) cur.splice(i, 1); resolve(null); }, timeout || WORKER_TIMEOUT); }); } function spawnWorker(url) { const f = document.createElement('iframe'); f.setAttribute('data-cxdl-worker', '1'); f.style.cssText = 'position:fixed;left:-10000px;top:0;width:2px;height:2px;opacity:0;border:0;pointer-events:none;'; f.src = url; document.documentElement.appendChild(f); return f; } function waitForObjectid(objectid, timeout) { const hit = fileIndex.get(objectid); if (hit && hit.download) return Promise.resolve(hit); if (!objectid) return Promise.resolve(null); return waitPreview('obj:' + objectid, timeout || WORKER_TIMEOUT) .then((v) => (v && v.download ? v : fileIndex.get(objectid) || null)); } async function previewUrlByDataId(item) { const c = ctx(); if (!c.courseid || !c.clazzid || !item.dataId) return ''; const q = new URLSearchParams({ dataId: item.dataId, cpi: c.cpi || '', clazzid: c.clazzid, ut: 's', courseid: c.courseid }).toString(); try { const r = await httpGet('https://mooc2-ans.chaoxing.com/mooc2-ans/coursedata/get-preview-url?' + q); const j = parseJson(r.text); return j && j.url ? j.url : ''; } catch (e) { return ''; } } async function resolveDoc(item) { const cached = fileIndex.get(item.objectid); if (cached && cached.download) return cached; // ① 预览框架回报(最快,且能取到原始文件名) if (item.objectid) { const origin = (ownerMeta.get(item.key) || {}).origin || 'https://mooc1.chaoxing.com'; const url = origin + '/mooc-ans/screen/file?objectid=' + encodeURIComponent(item.objectid); const worker = spawnWorker(url); const info = await waitForObjectid(item.objectid, 8000); if (info && info.download) { info.win = info.win || worker.contentWindow; retireWorker(worker); return info; } worker.remove(); } if (item.dataId && !item.objectid) { const pu = await previewUrlByDataId(item); if (pu) { const worker = spawnWorker(pu); const info = await waitForObjectid(item.objectid, 8000); if (info && info.download) { info.win = info.win || worker.contentWindow; retireWorker(worker); return info; } worker.remove(); } } // ② 后备:直接抓预览页 HTML 解析 fileinfo(不依赖框架注入) try { const info = await resolveByHtml(item); if (info && info.download) return info; } catch (e) { /* 继续向下 */ } // ③ 普通链接 if (item.link) return { direct: item.link, name: item.name }; throw new Error('缺少可下载地址'); } // 通过 GM_xhr 抓预览页 HTML,从 fileinfo 里取签名直链 async function resolveByHtml(item) { let html = ''; if (item.objectid) { const origin = (ownerMeta.get(item.key) || {}).origin || 'https://mooc1.chaoxing.com'; try { html = (await httpGet(origin + '/mooc-ans/screen/file?objectid=' + encodeURIComponent(item.objectid))).text || ''; } catch (e) { html = ''; } } if (!html && item.dataId) { const pu = await previewUrlByDataId(item); if (pu) { try { html = (await httpGet(pu)).text || ''; } catch (e) { html = ''; } } } if (!html) return null; const box = html.match(/fileinfo\s*=\s*\{([\s\S]{0,4000}?)\}\s*;/); if (!box) return null; const scope = box[1]; const grab = (k) => { const m = scope.match(new RegExp("['\"]" + k + "['\"]\\s*:\\s*['\"]([^'\"]*)['\"]", 'i')); return m ? m[1] : ''; }; const download = grab('download'); if (!download) return null; let name = ''; try { name = decodeURIComponent((download.match(/[?&]fn=([^&]+)/) || [])[1] || ''); } catch (e) { name = ''; } return { download, name: name || grab('name'), size: Number(grab('filesize')) || 0, win: null }; } // GM_xhr 取二进制(浏览器内无需 CORS,且可带 Referer) function gmBinary(url) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') return reject(new Error('缺少跨域请求能力')); GM_xmlhttpRequest({ method: 'GET', url, responseType: 'arraybuffer', timeout: 300000, headers: { Referer: 'https://pan-yz.chaoxing.com/' }, onload: (r) => { if (r.status >= 200 && r.status < 300 && r.response && r.response.byteLength) resolve(r.response); else reject(new Error('CDN 拒绝(HTTP ' + r.status + ')')); }, onerror: () => reject(new Error('下载失败')), ontimeout: () => reject(new Error('下载超时')) }); }); } function retireWorker(frame) { setTimeout(() => { try { frame.remove(); } catch (e) { /* 忽略 */ } }, 180000); } function requestBlob(win, url, name, taskId, onProgress) { return new Promise((resolve, reject) => { if (!win) return reject(new Error('预览框架已失效')); pendingTasks.set(taskId, { resolve, reject, onProgress }); try { win.postMessage({ [MSG]: 1, type: 'FETCH', id: taskId, url, name }, '*'); } catch (e) { pendingTasks.delete(taskId); return reject(new Error('无法与预览框架通信')); } setTimeout(() => { if (pendingTasks.has(taskId)) { pendingTasks.delete(taskId); reject(new Error('下载超时')); } }, 180000); }); } function saveBlob(buf, name, mime) { const blob = new Blob([buf], { type: mime || 'application/octet-stream' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = name || 'document'; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 60000); } function saveText(text, name) { saveBlob(new TextEncoder().encode(text).buffer, name, 'text/markdown;charset=utf-8'); } function saveBlobFile(blob, name) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = name || 'document.docx'; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 60000); } // docx 库:@require 在部分管理器里只注入到沙箱作用域,window.docx 取不到, // 所以按 裸标识符 → window → unsafeWindow → globalThis 依次找,全没有再去 CDN 现拉。 function pickDocx() { const cands = []; try { if (typeof docx !== 'undefined' && docx) cands.push(docx); } catch (e) { /* 忽略 */ } try { if (window.docx) cands.push(window.docx); } catch (e) { /* 忽略 */ } try { if (typeof unsafeWindow !== 'undefined' && unsafeWindow && unsafeWindow.docx) cands.push(unsafeWindow.docx); } catch (e) { /* 忽略 */ } try { if (typeof globalThis !== 'undefined' && globalThis.docx) cands.push(globalThis.docx); } catch (e) { /* 忽略 */ } for (let i = 0; i < cands.length; i++) { const c = cands[i]; if (c && c.Document && c.Packer) return c; } return null; } function loadScriptOnce(src) { return new Promise((resolve, reject) => { const s = document.createElement('script'); s.src = src; s.async = true; s.onload = () => { s.onload = s.onerror = null; resolve(); }; s.onerror = () => { s.onload = s.onerror = null; reject(new Error('脚本加载失败')); }; (document.head || document.documentElement).appendChild(s); setTimeout(() => reject(new Error('脚本加载超时')), 15000); }); } let docxLoading = null; function ensureDocx() { const hit = pickDocx(); if (hit) return Promise.resolve(hit); if (docxLoading) return docxLoading; docxLoading = (async () => { const urls = [ 'https://cdn.jsdmirror.com/npm/docx@7.1.0/build/index.min.js', 'https://cdn.jsdelivr.net/npm/docx@7.1.0/build/index.min.js', 'https://unpkg.com/docx@7.1.0/build/index.min.js' ]; for (let i = 0; i < urls.length; i++) { try { await loadScriptOnce(urls[i]); } catch (e) { continue; } const d = pickDocx(); if (d) return d; } docxLoading = null; // 允许下次重试 return null; })(); return docxLoading; } // 题干/答案 → Word 文档(依赖 docx 库) async function paperToDocx(p, questions) { const D = await ensureDocx(); if (!D || !D.Document) throw new Error('docx 库加载失败'); const { Document, Packer, Paragraph, TextRun, HeadingLevel } = D; const f = ui.exportFields || {}; const kids = []; kids.push(new Paragraph({ text: p.name || '题目', heading: HeadingLevel.HEADING_1 })); const meta = ['类型:' + (p.paperType || '作业'), '状态:' + (p.status || '')]; if (questions.length) meta.push('题量:' + questions.length + ' 题'); kids.push(new Paragraph({ children: [new TextRun({ text: meta.join(' '), size: 20, color: '666666' })], spacing: { after: 200 } })); questions.forEach((q) => { kids.push(new Paragraph({ children: [new TextRun({ text: (q.no || '') + '. ' + (q.type || ''), bold: true, size: 24 })], spacing: { before: 220, after: 90 } })); if (f.stem && q.stem) { kids.push(new Paragraph({ children: [new TextRun({ text: q.stem, size: 22 })] })); } (q.options || []).forEach((o) => { kids.push(new Paragraph({ children: [new TextRun({ text: o.name + '. ' + o.text, size: 22 })], indent: { left: 260 } })); }); if (f.correct && q.correct) { kids.push(new Paragraph({ children: [new TextRun({ text: '标准答案:', bold: true, size: 22 }), new TextRun({ text: q.correct, size: 22, color: '1F7A3D' })], spacing: { before: 60 } })); } if (f.mine && q.mine) { kids.push(new Paragraph({ children: [new TextRun({ text: '我的作答:', bold: true, size: 22 }), new TextRun({ text: q.mine, size: 22, color: '1F63CC' })] })); } if (f.analysis && q.analysis) { kids.push(new Paragraph({ children: [new TextRun({ text: '解析:' + q.analysis, size: 20, color: '666666' })] })); } }); const doc = new Document({ styles: { default: { document: { run: { font: '宋体', size: 22 } } } }, sections: [{ children: kids }] }); return Packer.toBlob(doc); } // 随堂练习 JSON → 统一题目数组 function quizQuestions(json) { const d = (json && (json.data || json)) || {}; const list = d.questionList || []; return list.map((q, i) => { const typeName = QUIZ_TYPE[q.type] || ('题型' + q.type); let opts = []; try { const arr = JSON.parse(q.options || '[]'); if (Array.isArray(arr)) opts = arr.map((o) => ({ name: o.name || '', text: htmlToText(o.content || o.answer || '') })).filter((o) => o.text); } catch (e) { opts = []; } let correct = htmlToText(q.rightAnswer); if (!correct) { try { const arr = JSON.parse(q.answer || '[]'); if (Array.isArray(arr)) correct = arr.map((a) => htmlToText(a.content || a.answer || '')).filter(Boolean).join('、'); } catch (e) { /* 忽略 */ } } if (!correct && opts.length === 1) correct = opts[0].text; if (/第\d+空/.test(correct)) { const blanks = []; correct.replace(/第(\d+)空\s*([^第]*)/g, (m, n, v) => { blanks.push(n + ') ' + v.trim()); return ''; }); if (blanks.length) correct = blanks.join(';'); } const isChoice = /单选|多选|判断/.test(typeName); return { no: q.sequence || i + 1, type: typeName + (q.score ? '(' + q.score + ' 分)' : ''), stem: htmlToText(q.content), options: isChoice ? opts.filter((o) => /^[A-Za-z0-9]+$/.test(o.name)) : [], correct, mine: myAnswerText(q, opts), analysis: htmlToText(q.answerAnalysis) }; }); } function saveLink(url, name) { const a = document.createElement('a'); a.href = url; if (name) a.download = name; a.target = '_blank'; a.rel = 'noopener'; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => a.remove(), 4000); } function setStatus(key, patch) { const cur = statusMap.get(key) || { state: 'idle', pct: 0, msg: '' }; const next = Object.assign({}, cur, patch); statusMap.set(key, next); paintRow(key, next); } async function runDocTask(key) { const item = docs.get(key); if (!item) return; try { setStatus(key, { state: 'resolving', pct: 0, msg: '' }); const info = await resolveDoc(item); if (info.direct) { setStatus(key, { state: 'downloading', pct: 0, msg: '浏览器接续下载' }); saveLink(info.direct, item.name); setStatus(key, { state: 'done', pct: 100 }); return; } setStatus(key, { state: 'downloading', pct: 0, msg: '' }); if (!info.win) { try { const buf = await gmBinary(info.download); saveBlob(buf, info.name || item.name); if (!item.size) item.size = buf.byteLength; setStatus(key, { state: 'done', pct: 100 }); } catch (e) { // 最后兜底:交给浏览器自己的下载器(页面 Referer 已被 CDN 接受) saveLink(info.download, info.name || item.name); setStatus(key, { state: 'done', pct: 100, msg: '已交给浏览器' }); } return; } const out = await requestBlob(info.win, info.download, item.name || info.name, key + '#' + Date.now(), (got, total) => { const pct = total ? Math.min(99, Math.round((got / total) * 100)) : 0; setStatus(key, { state: 'downloading', pct, msg: fmtSize(got) + (total ? ' / ' + fmtSize(total) : '') }); }); saveBlob(out.buf, out.name || item.name); if (!item.size && out.size) item.size = out.size; setStatus(key, { state: 'done', pct: 100, msg: '' }); } catch (e) { const msg = cleanErr(e); setStatus(key, { state: /缺少可下载地址|预览页未返回|取不到/.test(msg) ? 'needpreview' : 'error', msg }); } } /* ============================================================ * 9. 视频下载 * ============================================================ */ const videoWaiters = new Map(); let videoTaskSeq = 0; // 在 mooc1 框架里代取 /ananas/status(同源请求,Referer 天然正确) function videoInfoViaFrame(objectid, fid) { return new Promise((resolve) => { const id = 'v' + (++videoTaskSeq); const win = document.createElement('iframe'); win.setAttribute('data-cxdl-worker', '1'); win.style.cssText = 'position:fixed;left:-10000px;top:0;width:2px;height:2px;opacity:0;border:0;pointer-events:none;'; win.src = 'https://mooc1.chaoxing.com/ananas/modules/video/index.html?v=2026-1113-2201'; document.documentElement.appendChild(win); videoWaiters.set(id, (text) => { try { win.remove(); } catch (e) { /* 忽略 */ } resolve(text); }); const send = () => { try { win.contentWindow.postMessage({ [MSG]: 1, type: 'VIDEO_INFO', id, objectid, fid }, '*'); } catch (e) { /* 忽略 */ } }; win.addEventListener('load', () => { send(); setTimeout(send, 800); }); setTimeout(send, 1200); setTimeout(() => { if (!videoWaiters.has(id)) return; videoWaiters.delete(id); try { win.remove(); } catch (e) { /* 忽略 */ } resolve(''); }, 12000); }); } async function videoInfo(objectid) { const hit = videoIndex.get(objectid); if (hit) return hit; const fid = hiddenVars().fid || '1730'; const url = 'https://mooc1.chaoxing.com/ananas/status/' + objectid + '?k=' + fid + '&flag=normal&ro=0&_dc=' + Date.now(); let j = null; // ① 同源(在 mooc1 页面或 mooc1 框架里) if (/(^|\.)mooc1[\w-]*\.chaoxing\.com$/i.test(location.hostname)) { try { j = parseJson((await httpGet(url)).text); } catch (e) { j = null; } } // ② GM 跨域 if ((!j || j.__html) && typeof GM_xmlhttpRequest === 'function') { j = parseJson((await httpGet(url)).text); } // ③ 借 mooc1 框架代取 if (!j || j.__html) { const txt = await videoInfoViaFrame(objectid, fid); if (txt) j = parseJson(txt); } if (!j || j.__html) throw new Error('视频接口取不到数据,可先点「打开」预览该视频再试'); if (!j.http && !j.download) throw new Error('取不到视频地址'); const info = { http: j.http || '', download: j.download || '', filename: j.filename || '', length: Number(j.length) || 0, duration: Number(j.duration) || 0 }; videoIndex.set(objectid, info); return info; } async function runVideoTask(key) { const item = videos.get(key); if (!item) return; try { setStatus(key, { state: 'resolving', pct: 0, msg: '解析视频地址' }); const info = await videoInfo(item.objectid); if (!item.size && info.length) item.size = info.length; if (!item.name || item.name === item.objectid) item.name = info.filename || item.name; const name = item.name && /\.mp4$/i.test(item.name) ? item.name : (info.filename || (item.name + '.mp4')); // CDN 的 download 字段常是 http://,在 https 页面会被混合内容策略拦截,统一升为 https const url = String(info.download || info.http || '').replace(/^http:\/\//i, 'https://'); const size = info.length || item.size || 0; setStatus(key, { state: 'downloading', pct: 0, msg: '提交下载' }); let via = ''; if (typeof GM_download === 'function') { try { await new Promise((resolve, reject) => { GM_download({ url, name, saveAs: false, headers: { Referer: 'https://mooc1.chaoxing.com/' }, onload: () => resolve(), onerror: (e) => reject(new Error((e && e.error) || 'GM_download 失败')), ontimeout: () => reject(new Error('GM_download 超时')) }); }); via = '下载器'; } catch (e) { via = ''; } } if (!via && size && size < 80 * 1024 * 1024 && typeof GM_xmlhttpRequest === 'function') { // 小文件走二进制取回,能给出正确文件名 try { const buf = await gmBinary(url); saveBlob(buf, name); via = '直取'; } catch (e) { via = ''; } } if (!via) { saveLink(url, name); toast('已发起下载;若没反应,请在地址栏右侧允许本站弹窗/下载'); via = '浏览器'; } setStatus(key, { state: 'done', pct: 100, msg: '已提交(' + via + ')' }); render(); } catch (e) { setStatus(key, { state: 'error', msg: cleanErr(e) }); } } /* ============================================================ * 10. 题目导出 * ============================================================ */ function paperUrl(p) { const c = ctx(); if (p.source === 'chapter' || (p.workid && p.source !== 'quiz' && p.source !== 'exam')) { const rec = chapterCardsCache.get(String(p.knowledgeid || '')); const u = rec ? workApiUrl(c, p, rec) : ''; if (u) return u; return 'https://mooc1.chaoxing.com/mooc-ans/work/selectWorkQuestionYiPiYue?workId=' + encodeURIComponent(p.workid || '') + '&courseId=' + encodeURIComponent(c.courseid || '') + '&classId=' + encodeURIComponent(c.clazzid || ''); } if (p.source === 'exam') { const look = '/exam-ans/exam/test/look?courseId=' + encodeURIComponent(c.courseid) + '&classId=' + encodeURIComponent(c.clazzid) + '&examId=' + encodeURIComponent(p.examId) + '&examAnswerId=' + encodeURIComponent(p.answerId) + '&cpi=' + encodeURIComponent(c.cpi || ''); return 'https://mooc1.chaoxing.com/exam-ans/exam/test/reVersionPaperMarkContentNew?courseId=' + encodeURIComponent(c.courseid) + '&classId=' + encodeURIComponent(c.clazzid) + '&p=1&id=' + encodeURIComponent(p.answerId) + '&ut=s&newMooc=true&qbanksystem=1' + '&qbankbackurl=' + encodeURIComponent(look) + '&cpi=' + encodeURIComponent(c.cpi || ''); } return p.url; } const QUIZ_TYPE = { 1: '单选题', 2: '填空题', 3: '多选题', 4: '简答题', 5: '判断改错', 16: '判断题' }; function htmlToText(html) { if (!html) return ''; try { const d = new DOMParser().parseFromString(String(html), 'text/html'); d.querySelectorAll('script,style').forEach((n) => n.remove()); return (d.body ? d.body.textContent : '').replace(/\s+/g, ' ').trim(); } catch (e) { return String(html).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); } } // 「我的作答」在 personAnswer 里,且各题型结构不同 function myAnswerText(q, opts) { const strip = htmlToText; const mapOpt = (v) => { const hit = (opts || []).find((o) => o.name === String(v).trim()); return hit ? hit.text : String(v); }; let pa = q.personAnswer; if (pa && typeof pa === 'string') { try { pa = JSON.parse(pa); } catch (e) { /* 保留字符串 */ } } if (pa && typeof pa === 'object') { if (Array.isArray(pa.blankAnswer) && pa.blankAnswer.length) { return pa.blankAnswer.map((b) => (b.name ? b.name + ') ' : '') + strip(b.content)).join(';'); } if (pa.myoption != null) { const arr = Array.isArray(pa.myoption) ? pa.myoption : String(pa.myoption).split(/[,,]/); const txt = arr.map((v) => mapOpt(v)).filter(Boolean).join('、'); if (txt) return txt; } if (Array.isArray(pa.answer)) return pa.answer.map((x) => strip(x && x.content ? x.content : x)).join('、'); if (pa.answer != null) return strip(String(pa.answer)); if (pa.content != null) return strip(String(pa.content)); } if (typeof pa === 'string' && pa && pa !== 'null') return strip(pa); const stu = strip(q.studentAnswer); if (stu && stu !== 'null') return stu; return ''; } // 随堂练习(JSON)→ Markdown,按导出字段开关组装 function quizToMarkdown(json, p) { const d = (json && (json.data || json)) || {}; const list = d.questionList || []; const f = ui.exportFields || {}; const act = d.active || {}; const pick = []; if (f.stem) pick.push('题目'); if (f.correct) pick.push('标准答案'); if (f.mine) pick.push('我的作答'); const head = [ '# ' + (p.name || act.name || '随堂练习'), '', '- 类型:随堂练习', '- 题量:' + (d.questioncount || list.length) + ' 题', '- 状态:' + (p.status || ''), '- 来源:' + p.url, '> 导出字段:' + (pick.join(' · ') || '(未选字段,仅标题)'), '', '---', '' ]; const body = list.map((q, i) => { const typeName = QUIZ_TYPE[q.type] || ('题型' + q.type); let stem = htmlToText(q.content); let opts = []; try { const arr = JSON.parse(q.options || '[]'); if (Array.isArray(arr)) { opts = arr.map((o) => ({ name: o.name || '', text: htmlToText(o.content || o.answer || '') })).filter((o) => o.text); } } catch (e) { opts = []; } let correct = htmlToText(q.rightAnswer); if (!correct) { try { const arr = JSON.parse(q.answer || '[]'); if (Array.isArray(arr)) correct = arr.map((a) => htmlToText(a.content || a.answer || '')).filter(Boolean).join('、'); } catch (e) { /* 忽略 */ } } if (!correct && opts.length === 1) correct = opts[0].text; // 简答题参考答案放在 options 里 // 填空题的「第N空」拆成逐空答案 if (/第\d+空/.test(correct)) { const blanks = []; correct.replace(/第(\d+)空\s*([^第]*)/g, (m, n, v) => { blanks.push(n + ') ' + v.trim()); return ''; }); if (blanks.length) correct = blanks.join(';'); } const mine = myAnswerText(q, opts); const isChoice = /单选|多选|判断/.test(typeName); const lines = ['### ' + (q.sequence || i + 1) + '. ' + typeName + (q.score ? '(' + q.score + ' 分)' : '')]; if (f.stem) { lines.push('', stem); const named = opts.filter((o) => o.name && /^[A-Za-z0-9]+$/.test(o.name)); if (isChoice && named.length) { lines.push(''); named.forEach((o) => lines.push('- ' + o.name + '. ' + o.text)); } } if (f.correct && correct) lines.push('', '**标准答案:** ' + correct); if (f.mine && mine && mine !== 'null') lines.push('', '**我的作答:** ' + mine); return lines.join('\n'); }).join('\n\n'); return head.concat([body]).join('\n'); } // 结构化题目数组 -> Markdown(章节测验 / 作业 / 考试共用) function questionsToMarkdown(p, qs) { const f = ui.exportFields || {}; const on = (k) => !!f[k]; const head = [ '# ' + (p.name || '题目'), '', '- 类型:' + (p.paperType || '题目'), '- 状态:' + (p.status || ''), '- 题量:' + qs.length + ' 题' ]; const src = paperUrl(p); if (src && /^https?:/i.test(src)) head.push('- 来源:' + src); const pick = []; if (on('stem')) pick.push('题目'); if (on('correct')) pick.push('标准答案'); if (on('mine')) pick.push('我的作答'); if (on('analysis')) pick.push('解析'); head.push('> 导出字段:' + (pick.join(' · ') || '(未选字段,仅标题)'), '', '---', ''); const body = qs.map((q, i) => { const lines = ['### ' + (i + 1) + '. ' + (q.type || '')]; if (on('stem') && q.stem) lines.push('', q.stem); (q.options || []).forEach((o) => { lines.push('- ' + (o.name ? o.name + '. ' : '') + o.text); }); if (on('correct') && q.correct) lines.push('', '**标准答案:** ' + q.correct); if (on('mine') && q.mine) lines.push('', '**我的作答:** ' + q.mine); if (on('analysis') && q.analysis) lines.push('', '**解析:** ' + q.analysis); return lines.join('\n'); }); return head.concat([body.join('\n\n')]).join('\n'); } // 把页面文本切成「题号 / 题型 / 题干 / 我的作答 / 标准答案 / 解析」 function splitQuestions(text) { const out = []; const chunks = String(text || '').split(/\n(?=\s*\d{1,3}\s*[.、]\s*[((])/); chunks.forEach((raw) => { const m = raw.match(/^\s*(\d{1,3})\s*[.、]\s*(?:[((]\s*([^))]{1,18})\s*[))]|\[\s*([^\]]{1,18})\s*\])\s*([\s\S]*)$/); if (!m) return; const rest = m[4]; const cut = rest.search(/我的答案\s*[::]|正确答案\s*[::]|答案解析\s*[::]/); const stem = (cut >= 0 ? rest.slice(0, cut) : rest).replace(/\s+/g, ' ').trim(); const grab = (label, nexts) => { const idx = rest.search(new RegExp(label + '\\s*[::]')); if (idx < 0) return ''; let sub = rest.slice(idx).replace(new RegExp(label + '\\s*[::]'), ''); nexts.forEach((nl) => { const j = sub.search(new RegExp('\\s*' + nl + '\\s*[::]')); if (j >= 0) sub = sub.slice(0, j); }); return sub.replace(/\s+/g, ' ').trim(); }; out.push({ no: m[1], type: (m[2] || m[3] || '').trim(), stem, mine: grab('我的答案', ['正确答案', '答案解析', '知识点']), correct: grab('正确答案', ['答案解析', '我的答案', '知识点']), analysis: grab('答案解析', ['知识点', '我的答案', '正确答案']) }); }); return out; } function composePaper(p, text) { const f = ui.exportFields || { stem: true, correct: true, mine: true }; const qs = splitQuestions(text); const head = [ '# ' + p.name, '', '- 类型:' + (p.paperType || '作业'), '- 状态:' + (p.status || '未知'), '- 来源:' + paperUrl(p), '' ]; if (!qs.length) { // 无法结构化(如任务/活动页),整段导出 return head.concat(['---', '', text]).join('\n'); } const on = (k) => !!f[k]; const body = qs.map((q) => { const lines = ['### ' + q.no + '. ' + q.type]; if (on('stem') && q.stem) lines.push('', q.stem); if (on('correct') && q.correct) lines.push('', '**标准答案:** ' + q.correct); if (on('mine') && q.mine) lines.push('', '**我的作答:** ' + q.mine); if (on('analysis') && q.analysis) lines.push('', '**解析:** ' + q.analysis); return lines.join('\n'); }).join('\n\n'); const pick = []; if (on('stem')) pick.push('题目'); if (on('correct')) pick.push('标准答案'); if (on('mine')) pick.push('我的作答'); if (on('analysis')) pick.push('解析'); return head.concat(['> 导出字段:' + (pick.join(' · ') || '(未选字段,仅标题)'), '', '---', '', body]).join('\n'); } async function runPaperTask(key) { const p = papers.get(key); if (!p) return; const safeName = String(p.name || '题目').replace(/[\\/:*?"<>|]/g, '_').slice(0, 60); try { setStatus(key, { state: 'resolving', pct: 0, msg: '抓取题目' }); let questions = []; let text = ''; let quizJson = null; if (p.source === 'chapter' || p.workid) { // 章节测验 / 课内作业:走 /mooc-ans/api/work 拿到整张卷子 if (p.questions && p.questions.length) { questions = p.questions; } else { questions = await fetchWorkQuestions(ctx(), p); } text = questions.map((q) => (q.no || '') + '. ' + (q.type || '') + '\n' + (q.stem || '')).join('\n'); } else if (p.source === 'quiz') { const activeId = ((p.url || '').match(/activeId=(\d+)/) || [])[1]; if (!activeId) throw new Error('缺少随堂练习 id'); const r = await httpGet('https://mobilelearn.chaoxing.com/v2/apis/studentQuestion/getAnswerResult?activeId=' + activeId); const json = parseJson(r.text); if (json && json.__html) throw new Error('随堂练习接口返回网页,先刷新或重新登录'); if (!json || !json.data) throw new Error('接口未返回题目'); quizJson = json; questions = quizQuestions(json); } else { const doc = await getDoc(paperUrl(p)); text = domToText(doc.body || doc.documentElement); if (/\[3004\]|没有此页面访问权限/.test(text)) { throw new Error(p.source === 'exam' ? '网页端取不到试卷(多为仅限手机 APP 或未开放查看)' : '没有查看权限(需先完成作答)'); } if (p.source === 'exam' && text.length < 500) { text += '\n\n说明:该考试为在线答卷,题目正文未随页面直接返回(平台限制),可在浏览器中打开完整试卷。\n' + paperUrl(p); } else if (text.length < 30) { throw new Error('页面无可提取文本'); } questions = splitQuestions(text).map((q) => ({ no: q.no, type: q.type, stem: q.stem, options: [], correct: q.correct, mine: q.mine, analysis: q.analysis })); } // 优先导出 Word;docx 库不可用时退回 Markdown try { const blob = await paperToDocx(p, questions); saveBlobFile(blob, safeName + '.docx'); setStatus(key, { state: 'done', pct: 100, msg: '已导出 DOCX(' + questions.length + ' 题)' }); } catch (e) { let md; if (p.source === 'quiz') md = quizToMarkdown(quizJson, p); else if (questions.length) md = questionsToMarkdown(p, questions); else md = composePaper(p, text); saveText(md, safeName + '.md'); setStatus(key, { state: 'done', pct: 100, msg: '已导出 MD(' + cleanErr(e) + ')' }); } } catch (e) { setStatus(key, { state: 'error', msg: cleanErr(e) }); } } /* ============================================================ * 11. 队列 * ============================================================ */ function kindOf(key) { if (videos.has(key)) return 'video'; if (papers.has(key)) return 'paper'; return 'doc'; } async function runTask(key) { const kind = kindOf(key); if (kind === 'video') return runVideoTask(key); if (kind === 'paper') return runPaperTask(key); return runDocTask(key); } function pump() { while (running < CONCURRENCY && queue.length) { const key = queue.shift(); const st = statusMap.get(key); if (!st || st.state === 'done' || st.state === 'downloading' || st.state === 'resolving') continue; running++; runTask(key).finally(() => { running--; pump(); }); } updateFoot(); } function enqueue(keys) { keys.forEach((k) => { const st = statusMap.get(k) || { state: 'idle' }; if (['queued', 'downloading', 'resolving', 'done'].includes(st.state)) return; if (queue.includes(k)) return; statusMap.set(k, Object.assign({}, st, { state: 'queued', msg: '' })); paintRow(k, statusMap.get(k)); queue.push(k); }); pump(); } /* ============================================================ * 12. 界面 * ============================================================ */ const CSS = ` :host { all: initial; } .panel, .panel * { box-sizing: border-box; } .panel { --paper: #f7f2e7; --paper-2: #fbf7ef; --line: #d9cdb3; --line-soft: #e9dfc9; --ink: #2e2a24; --ink-2: #6d6353; --ink-3: #9a8f7b; --zhu: #a63a2f; --zhu-soft: #f3e3de; --jin: #96783f; --dai: #3c5a63; --cui: #4a6b4f; position: fixed; right: 18px; bottom: 86px; width: 396px; background: var(--paper); color: var(--ink); border: 1px solid var(--line); border-radius: 5px; box-shadow: 0 6px 22px rgba(66, 48, 20, .16), inset 0 0 0 1px #fdfaf2; font-size: 13px; line-height: 1.55; overflow: hidden; z-index: 2147483000; font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; } .head { display: flex; align-items: center; gap: 9px; padding: 9px 12px 8px; cursor: move; user-select: none; border-bottom: 1px solid var(--line); } .seal { width: 22px; height: 22px; flex: none; background: #fff; color: #fdf6e8; border-radius: 2px; display: flex; align-items: center; justify-content: center; overflow: hidden; border: 1px solid var(--line); font-family: "Songti SC", "Noto Serif SC", "STSong", "SimSun", serif; font-size: 12px; } .seal img { width: 100%; height: 100%; object-fit: cover; display: block; } .title { font-family: "Songti SC", "Noto Serif SC", "STSong", "SimSun", serif; font-size: 15px; letter-spacing: 2px; } .badge { font-size: 11px; color: var(--zhu); border: 1px solid var(--zhu-soft); background: #fbf0ec; border-radius: 2px; padding: 0 5px; font-variant-numeric: tabular-nums; } .spacer { flex: 1 1 auto; } .icon { border: 0; background: transparent; color: var(--ink-2); font-size: 12px; line-height: 1; padding: 4px 5px; border-radius: 2px; cursor: pointer; letter-spacing: 1px; } .icon:hover { background: #efe7d4; color: var(--zhu); } .icon:disabled { opacity: .4; cursor: default; background: transparent; color: var(--ink-2); } .icon#updateBtn.is-new { background: var(--zhu); color: #fdf6e8; border-radius: 2px; } .icon#updateBtn.is-checking { color: var(--ink3); } .tabs { display: flex; gap: 14px; padding: 0 12px; border-bottom: 1px solid var(--line-soft); background: var(--paper-2); } .tab { border: 0; background: transparent; color: var(--ink-2); padding: 7px 1px 6px; cursor: pointer; border-bottom: 2px solid transparent; font-size: 13px; letter-spacing: 1px; } .tab.on { color: var(--zhu); border-bottom-color: var(--zhu); } .tab .n { font-size: 11px; color: var(--ink-3); margin-left: 3px; font-variant-numeric: tabular-nums; } .upd-mask { position: fixed; inset: 0; background: rgba(46, 42, 36, .45); display: flex; align-items: center; justify-content: center; z-index: 2147483647; backdrop-filter: blur(4px); /* 弹窗是 .panel 的兄弟节点,CSS 变量需在此重新声明 */ --paper: #fbf7ef; --paper-2: #fdf9f0; --line: #d9cdb3; --line-soft: #e9dfc9; --ink: #2e2a24; --ink2: #6d6353; --ink3: #9a8f7b; --zhu: #a63a2f; --zhu-soft: #f3e3de; --dai: #3c5a63; --cui: #4a6b4f; --jin: #96783f; font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; } .upd-card { position: relative; box-sizing: border-box; width: 340px; max-width: 92%; background: var(--paper); border: 1px solid var(--line); border-radius: 6px; padding: 22px 24px; box-shadow: 0 12px 34px rgba(66, 48, 20, .3); overflow: hidden; font-family: var(--font-body); } .upd-bar { position: absolute; top: 0; left: 0; right: 0; height: 3px; background: var(--zhu); } .upd-head { display: flex; align-items: center; gap: 12px; margin-bottom: 18px; } .upd-ico { width: 40px; height: 40px; border-radius: 6px; background: var(--zhu-soft); color: var(--zhu); display: flex; align-items: center; justify-content: center; font-size: 20px; border: 1px solid var(--line); } .upd-h3 { font-family: var(--font-display); font-size: 17px; color: var(--ink); letter-spacing: 2px; } .upd-sub { font-size: 11px; color: var(--ink3); margin-top: 2px; } .upd-cards { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 14px; } .upd-card2 { background: var(--paper-2); border: 1px solid var(--line); border-radius: 4px; padding: 12px; text-align: center; } .upd-card2.is-new { border-color: var(--cui); background: #f0f5ee; } .upd-lbl { font-size: 11px; color: var(--ink3); letter-spacing: 1px; margin-bottom: 4px; } .upd-ver { font-family: var(--font-display); font-size: 21px; font-variant-numeric: tabular-nums; } .upd-status { font-size: 13px; font-weight: 500; margin-bottom: 12px; letter-spacing: 1px; } .upd-ta { width: 100%; height: 76px; resize: none; margin-bottom: 12px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 3px; background: var(--paper-2); color: var(--ink); font-size: 12px; line-height: 1.6; word-break: break-all; box-sizing: border-box; font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; } .upd-ta:focus { outline: 1px solid var(--zhu); } .upd-notes { background: var(--paper-2); border: 1px solid var(--line-soft); border-radius: 4px; padding: 10px 12px; margin-bottom: 12px; } .upd-nl { font-family: var(--font-display); font-size: 12px; color: var(--ink); letter-spacing: 1px; margin-bottom: 6px; } .upd-notes ul { margin: 0; padding-left: 16px; font-size: 12px; color: var(--ink2); line-height: 1.7; } .upd-btns { display: flex; gap: 8px; justify-content: flex-end; flex-wrap: wrap; } .ubtn { padding: 7px 16px; border: 1px solid var(--line); background: var(--paper-2); color: var(--ink); border-radius: 3px; font-size: 12px; cursor: pointer; font-family: inherit; letter-spacing: 1px; } .ubtn:hover:not(:disabled) { border-color: var(--zhu); color: var(--zhu); } .ubtn:disabled { opacity: .45; cursor: not-allowed; } .ubtn.primary { background: var(--zhu); border-color: var(--zhu); color: #fdf6e8; } .ubtn.primary:hover:not(:disabled) { background: #8e2f26; color: #fdf6e8; } .notice { border-bottom: 1px solid var(--line-soft); background: #fbf3e0; overflow: hidden; } .notice-head { display: flex; align-items: center; gap: 8px; padding: 6px 12px; cursor: pointer; user-select: none; } .notice-head .nseal { width: 18px; height: 18px; background: var(--zhu); color: #fdf6e8; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-family: "Songti SC", "STSong", "SimSun", serif; font-size: 11px; flex: none; } .notice-head .ntitle { font-family: "Songti SC", "STSong", "SimSun", serif; font-size: 13px; letter-spacing: 2px; color: var(--ink); } .notice-head .ndate { font-size: 11px; color: var(--ink3); } .notice-head .arrow { margin-left: auto; font-size: 11px; color: var(--ink3); transition: transform .15s; } .notice-head.closed .arrow { transform: rotate(-90deg); } .notice-content { padding: 2px 14px 10px 34px; font-size: 12px; color: var(--ink2); line-height: 1.8; } .notice-content .nt { font-family: "Songti SC", "STSong", "SimSun", serif; font-size: 13px; color: var(--zhu); letter-spacing: 1px; margin-bottom: 6px; } .notice-content ul { margin: 0; padding-left: 4px; list-style: none; } .notice-content li { margin-bottom: 4px; padding-left: 12px; position: relative; overflow-wrap: anywhere; word-break: break-word; } .notice-content li::before { content: "·"; position: absolute; left: 0; color: var(--jin); font-weight: bold; } .notice-content a { color: var(--zhu); text-decoration: underline; overflow-wrap: anywhere; } .notice-content b { color: var(--ink); font-weight: 500; } .toolbar { display: flex; align-items: center; gap: 8px; padding: 8px 12px; } .check { display: inline-flex; align-items: center; gap: 6px; color: var(--ink-2); cursor: pointer; } .check input { width: 13px; height: 13px; accent-color: var(--zhu); cursor: pointer; margin: 0; } .hint { color: var(--ink-3); font-size: 12px; } .btn { border: 1px solid var(--line); background: var(--paper-2); color: var(--ink); border-radius: 3px; padding: 3px 9px; font-size: 12px; cursor: pointer; line-height: 18px; white-space: nowrap; font-family: inherit; } .btn:hover { border-color: var(--zhu); color: var(--zhu); } .btn.primary { background: var(--zhu); border-color: var(--zhu); color: #fdf6e8; } .btn.primary:hover { background: #8e2f26; color: #fdf6e8; } .btn:disabled { opacity: .45; cursor: not-allowed; } .btn.mini { padding: 1px 5px; font-size: 11px; color: var(--ink-2); border-color: var(--line-soft); } .filters { display: flex; gap: 5px; padding: 0 12px 8px; flex-wrap: wrap; } .chip { border: 1px solid var(--line); background: var(--paper-2); color: var(--ink-2); border-radius: 2px; padding: 0 7px; font-size: 12px; cursor: pointer; line-height: 19px; letter-spacing: .5px; } .chip.on { border-color: var(--zhu); background: var(--zhu); color: #fdf6e8; } .list { max-height: 44vh; overflow-y: auto; border-top: 1px solid var(--line-soft); } .sect { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 6px; padding: 4px 10px; background: #efe6d2; border-bottom: 1px solid var(--line-soft); cursor: pointer; user-select: none; } .sect:hover { background: #e9dfc6; } .sect .ar { font-size: 9px; color: var(--ink-3); width: 9px; transition: transform .15s; } .sect.folded .ar { transform: rotate(-90deg); } .sect .no { font-family: "Songti SC", "STSong", "SimSun", serif; font-size: 11px; color: #fdf6e8; background: var(--jin); border-radius: 2px; padding: 0 4px; letter-spacing: .5px; } .sect .st { flex: 1 1 auto; min-width: 0; font-family: "Songti SC", "STSong", "SimSun", serif; font-size: 12.5px; color: var(--ink); letter-spacing: .6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sect .cnt { font-size: 11px; color: var(--ink-3); font-variant-numeric: tabular-nums; } .sect.d0 { background: #ece2cb; } .sect.d0 .st { font-size: 13px; color: #4a3a22; } .sect.d1 { background: #f2e9d6; } .sect.d1 .st { font-size: 12.5px; } .sect.d1 .no { background: #b09455; } .sect.d2 { background: #f6efe1; } .sect.d2 .st { font-size: 12px; color: var(--ink-2); } .sect.d2 .no { background: #bda870; font-size: 10px; } .sect.d3 { background: #faf5ea; } .sect.d3 .st { font-size: 11.5px; color: var(--ink-3); } .list::-webkit-scrollbar { width: 6px; } .list::-webkit-scrollbar-thumb { background: #cdbfa3; border-radius: 0; } .row { display: flex; align-items: center; gap: 8px; padding: 7px 12px; border-bottom: 1px solid var(--line-soft); } .row:hover { background: #f1e9d6; } .row .sel { width: 13px; height: 13px; accent-color: var(--zhu); flex: none; cursor: pointer; margin: 0; } .tag { flex: none; width: 34px; text-align: center; font-size: 11px; border-radius: 2px; padding: 1px 0; font-family: "Songti SC", "STSong", "SimSun", serif; letter-spacing: .5px; } .t-pdf { color: #a63a2f; background: #f7e5e1; } .t-ppt { color: #8a6c33; background: #f6eddb; } .t-doc { color: #3c5a63; background: #e7eef0; } .t-xls { color: #4a6b4f; background: #e8f0e8; } .t-other { color: #6d6353; background: #efe7d4; } .t-video { color: #6b4a6b; background: #f0e8f0; } .t-paper { color: #8a5a2b; background: #f5ebdf; } .meta { flex: 1 1 auto; min-width: 0; } .name { font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--ink); } .sub { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--ink-3); margin-top: 1px; } .sub .pt { color: #b3a68d; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 132px; } .st-done { color: var(--cui); } .st-run { color: var(--zhu); } .st-err { color: #8c2f24; } .prog { height: 2px; background: #e6dbc4; margin-top: 4px; overflow: hidden; } .prog i { display: block; height: 100%; width: 0; background: var(--zhu); transition: width .18s linear; } .act-group { flex: none; display: flex; align-items: center; gap: 4px; } .foot { display: flex; align-items: center; gap: 8px; padding: 6px 12px; background: #f1ead9; color: var(--ink-3); font-size: 12px; border-top: 1px solid var(--line); } .linkbtn { border: 0; background: transparent; color: var(--zhu); font-size: 12px; cursor: pointer; padding: 0; white-space: nowrap; } .linkbtn.ver { flex: none; color: var(--ink-3); font-size: 11px; letter-spacing: .3px; font-variant-numeric: tabular-nums; padding-left: 2px; } .linkbtn.ver:hover { color: var(--zhu); } .linkbtn:hover { text-decoration: underline; } .empty { padding: 26px 18px; text-align: center; color: var(--ink-3); font-size: 12px; line-height: 1.9; letter-spacing: .5px; } .toast { position: absolute; left: 50%; bottom: 46px; transform: translateX(-50%); background: #3a332a; color: #f7f2e7; font-size: 12px; padding: 5px 12px; border-radius: 3px; opacity: 0; pointer-events: none; transition: opacity .2s; white-space: nowrap; max-width: 90%; } .toast.show { opacity: .95; } /* 可拉伸:sized 态改成 flex 列布局,列表吃掉剩余高度 */ .panel.sized { display: flex; flex-direction: column; } .panel.sized .head, .panel.sized .tabs, .panel.sized .toolbar, .panel.sized .filters, .panel.sized .notice, .panel.sized .foot { flex: 0 0 auto; } .panel.sized .list { flex: 1 1 auto; max-height: none; min-height: 56px; } .rs { position: absolute; z-index: 6; touch-action: none; } .rs-n { top: 0; left: 10px; right: 10px; height: 5px; cursor: ns-resize; } .rs-s { bottom: 0; left: 10px; right: 10px; height: 5px; cursor: ns-resize; } .rs-w { left: 0; top: 10px; bottom: 10px; width: 5px; cursor: ew-resize; } .rs-e { right: 0; top: 10px; bottom: 10px; width: 5px; cursor: ew-resize; } .rs-nw { left: 0; top: 0; width: 11px; height: 11px; cursor: nwse-resize; } .rs-ne { right: 0; top: 0; width: 11px; height: 11px; cursor: nesw-resize; } .rs-sw { left: 0; bottom: 0; width: 11px; height: 11px; cursor: nesw-resize; } .rs-se { right: 0; bottom: 0; width: 11px; height: 11px; cursor: nwse-resize; } .rs-se::after { content: ""; position: absolute; right: 2px; bottom: 2px; width: 6px; height: 6px; border-right: 1px solid #b3a68d; border-bottom: 1px solid #b3a68d; pointer-events: none; } .panel.sized .rs-se::after { border-color: var(--zhu); } .fab { position: fixed; right: 18px; bottom: 86px; z-index: 2147483000; border: 1px solid var(--line, #d9cdb3); background: #a63a2f; color: #fdf6e8; border-radius: 3px; padding: 7px 13px; font-size: 13px; cursor: pointer; letter-spacing: 2px; box-shadow: 0 4px 14px rgba(66, 48, 20, .18), inset 0 0 0 1px rgba(253, 246, 232, .5); font-family: "Songti SC", "STSong", "SimSun", serif; } .fab:hover { background: #8e2f26; } `; const HTML = `