// ==UserScript== // @name 超星学习通课程资源助手 // @namespace https://gitee.com/fieldlu/chaoxing-course-helper // @version 1.0.0.2 // @description 自动发现超星学习通课程的 PPT/PDF/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.2'; 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.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' }); 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) 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 ? '已结束' : '进行中' }); }); } return list; } // 拼随堂练习答题页地址(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(); } function scanAll() { const out = scanDocument(document); const frames = document.querySelectorAll('iframe'); for (let i = 0; i < frames.length; i++) { try { const cd = frames[i].contentDocument; if (cd) out.push(...scanDocument(cd)); } catch (e) { /* 跨域,跳过 */ } } 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), 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; } } /* ============================================================ * 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); } 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 { const u = c.oldCourse ? mk('https://mooc1-1.chaoxing.com', '/knowledge/cards', { clazzid: c.clazzid, courseid: c.courseid, knowledgeid: ch.id, num: 0, ut: 's', cpi: c.cpi, mooc2: 0 }) : mk(mooc1, '/mooc-ans/knowledge/cards', { clazzid: c.clazzid, courseid: c.courseid, knowledgeid: ch.id, num: 0, ut: 's', cpi: c.cpi, mooc2: 1 }); const d = await getDoc(u); return parseCards(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(); } function parseChapters(doc) { const out = []; const seen = new Set(); doc.querySelectorAll('[onclick*="getTeacherAjax"]').forEach((el) => { const m = (el.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); let name = el.getAttribute('title') || el.textContent.replace(/\s+/g, ' ').trim(); name = name.replace(/^[\d..\s]+/, '').trim() || id; // 层级:向上数几层 posCatalog_level let level = 0, p = el; while (p && level < 6) { if (p.className && /posCatalog_level/.test(String(p.className))) level++; p = p.parentElement; } out.push({ id, name, level }); }); // 按课程目录树生成「第 n 章 / 小节」路径与顺序号 const stack = []; out.forEach((ch, i) => { const depth = Math.max(0, Math.min(5, ch.level)); stack.length = depth + 1; stack[depth] = ch.name; ch.path = stack.filter(Boolean).join(' / '); 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 (!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'; ingestPaper({ key: raw.key, name: raw.name, kind: 'paper', paperType: isQuiz ? '随堂练习' : '任务', status: raw.status || '', url: raw.link || '', sectionKey: isQuiz ? 'paper:quiz' : 'paper:task', chapter: isQuiz ? '随堂练习' : '任务', 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; 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); } // 题干/答案 → Word 文档(依赖 @require 的 docx 库) async function paperToDocx(p, questions) { const D = window.docx; 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 === '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'); } // 把页面文本切成「题号 / 题型 / 题干 / 我的作答 / 标准答案 / 解析」 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 === '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 (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) { const md = p.source === 'quiz' ? quizToMarkdown(quizJson, p) : composePaper(p, text); saveText(md, safeName + '.md'); setStatus(key, { state: 'done', pct: 100, msg: '已导出 Markdown(Word 组件不可用)' }); } } 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#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; 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-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: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; } .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 = `
已选 0 项
告 公告 ▾
空闲
`; const host = document.createElement('div'); host.id = 'cxdl-host'; host.style.cssText = 'all:initial;position:static;'; const shadow = host.attachShadow({ mode: 'open' }); shadow.innerHTML = '' + HTML; document.documentElement.appendChild(host); const $ = (s) => shadow.querySelector(s); const panelEl = $('.panel'); const fabEl = $('#fab'); const listEl = $('#list'); const rowEls = new Map(); function currentBucket() { if (ui.tab === 'videos') return videos; if (ui.tab === 'papers') return papers; return docs; } function typeClass(group) { return ({ pdf: 't-pdf', ppt: 't-ppt', doc: 't-doc', xls: 't-xls', video: 't-video', paper: 't-paper' })[group] || 't-other'; } function statusText(st, item) { switch (st.state) { case 'resolving': return [st.msg || '解析中…', 'st-run']; case 'queued': return ['排队中', '']; case 'downloading': return ['下载中 ' + (st.pct || 0) + '%' + (st.msg ? ' · ' + st.msg : ''), 'st-run']; case 'done': return [st.msg || '已完成', 'st-done']; case 'error': return ['失败:' + (st.msg || ''), 'st-err']; case 'needpreview': return ['需先打开预览', 'st-err']; default: if (ui.tab === 'papers') return [item.status || '待导出', '']; return ['', '']; } } function visibleItems() { const bucket = currentBucket(); let arr = Array.from(bucket.values()).filter((it) => it.name && it.name !== it.objectid); if (ui.tab === 'docs' && ui.filter !== 'all') arr = arr.filter((it) => it.group === ui.filter); return arr; } // 按课程单元 / 资料目录 / 题目类型分组,保持原始顺序 // 按「一级目录 / 二级目录 / 三级目录」建树 function buildTree(arr) { const root = { key: '', title: '', depth: -1, order: 1e9, children: new Map(), items: [] }; arr.forEach((it) => { const raw = it.chapter || (ui.tab === 'papers' ? '题目' : '当前页面'); const parts = String(raw).split(/\s*\/\s*/).filter(Boolean); let node = root; parts.forEach((p, i) => { const key = parts.slice(0, i + 1).join('/'); let child = node.children.get(key); if (!child) { child = { key, title: p, depth: i, order: 1e9, children: new Map(), items: [] }; node.children.set(key, child); } const ord = it.order != null ? it.order : 9000; if (ord < child.order) child.order = ord; node = child; }); node.items.push(it); }); return root; } function collectGroupKeys(node, acc, prefix) { node.children.forEach((k) => { acc.push(prefix + k.key); collectGroupKeys(k, acc, prefix); }); return acc; } function countNode(node) { let n = node.items.length; node.children.forEach((c) => { n += countNode(c); }); return n; } // 深度优先展开成渲染行(折叠状态记在 ui.folded) function flattenTree(root) { const rows = []; const bySeq = (a, b) => (a.seq || 0) - (b.seq || 0); const walk = (node, parentNo) => { const kids = Array.from(node.children.values()) .sort((a, b) => (a.order - b.order) || String(a.title).localeCompare(String(b.title), 'zh')); kids.forEach((k, i) => { const no = parentNo ? parentNo + '.' + (i + 1) : String(i + 1).padStart(2, '0'); const key = ui.tab + ':' + k.key; const folded = ui.folded.has(key); rows.push({ type: 'sect', key, title: k.title, depth: k.depth, no, count: countNode(k), folded }); if (folded) return; k.items.slice().sort(bySeq).forEach((item) => rows.push({ type: 'item', item })); walk(k, no); }); }; root.items.slice().sort(bySeq).forEach((item) => rows.push({ type: 'item', item })); walk(root, ''); return rows; } const DOC_CHIPS = [['all', '全部'], ['pdf', 'PDF'], ['ppt', 'PPT'], ['doc', 'Word'], ['xls', '表格'], ['other', '其他']]; const FIELD_CHIPS = [['stem', '题目'], ['correct', '标准答案'], ['mine', '我的作答'], ['analysis', '解析']]; function renderFilters() { const box = $('#filters'); if (!box) return; box.innerHTML = ''; if (ui.tab === 'videos') { box.style.display = 'none'; return; } box.style.display = 'flex'; if (ui.tab === 'papers') { const tip = document.createElement('span'); tip.className = 'hint'; tip.textContent = '导出含:'; box.appendChild(tip); FIELD_CHIPS.forEach(([k, label]) => { const b = document.createElement('button'); b.className = 'chip' + (ui.exportFields[k] ? ' on' : ''); b.dataset.field = k; b.textContent = label; box.appendChild(b); }); return; } DOC_CHIPS.forEach(([f, label]) => { const b = document.createElement('button'); b.className = 'chip' + (ui.filter === f ? ' on' : ''); b.dataset.f = f; b.textContent = label; box.appendChild(b); }); } function render() { $('#n-docs').textContent = docs.size; $('#n-videos').textContent = videos.size; $('#n-papers').textContent = papers.size; $('#count').textContent = String(docs.size + videos.size + papers.size); renderFilters(); $('#batch').textContent = ui.tab === 'papers' ? '导出全部' : '批量下载'; $('#groupBy').textContent = ui.groupBy === 'place' ? '位置' : '名称'; shadow.querySelectorAll('.tab').forEach((t) => t.classList.toggle('on', t.dataset.t === ui.tab)); renderList(); } function renderList() { const items = visibleItems(); listEl.innerHTML = ''; rowEls.clear(); if (!items.length) { const div = document.createElement('div'); div.className = 'empty'; div.innerHTML = ui.tab === 'papers' ? '暂无题目记录
点击右上角「扫描」读取作业与考试' : '暂未发现资源
点击右上角「扫描」读取整门课程'; listEl.appendChild(div); updateCounters(); return; } const frag = document.createDocumentFragment(); if (ui.groupBy === 'name') { items.slice() .sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh-Hans-CN')) .forEach((item) => frag.appendChild(buildRow(item))); listEl.appendChild(frag); updateCounters(); return; } const rows = flattenTree(buildTree(items)); rows.forEach((r) => { if (r.type === 'item') { frag.appendChild(buildRow(r.item)); return; } const head = document.createElement('div'); head.className = 'sect d' + Math.min(r.depth, 3) + (r.folded ? ' folded' : ''); head.style.paddingLeft = (10 + r.depth * 13) + 'px'; head.dataset.k = r.key; const ar = document.createElement('span'); ar.className = 'ar'; ar.textContent = r.folded ? '\u25b8' : '\u25be'; head.appendChild(ar); const no = document.createElement('span'); no.className = 'no'; no.textContent = r.no; head.appendChild(no); const st = document.createElement('span'); st.className = 'st'; st.textContent = r.title; st.title = r.title; head.appendChild(st); const cnt = document.createElement('span'); cnt.className = 'cnt'; cnt.textContent = r.count; head.appendChild(cnt); head.addEventListener('click', () => { if (ui.folded.has(r.key)) ui.folded.delete(r.key); else ui.folded.add(r.key); renderList(); }); frag.appendChild(head); }); listEl.appendChild(frag); updateCounters(); } function buildRow(item) { const st = statusMap.get(item.key) || { state: 'idle' }; const row = document.createElement('div'); row.className = 'row'; const sel = document.createElement('input'); sel.type = 'checkbox'; sel.className = 'sel'; sel.checked = ui.selected.has(item.key); sel.addEventListener('change', () => { if (sel.checked) ui.selected.add(item.key); else ui.selected.delete(item.key); updateCounters(); }); const tag = document.createElement('span'); const group = ui.tab === 'papers' ? 'paper' : item.group; tag.className = 'tag ' + typeClass(group); tag.textContent = ui.tab === 'papers' ? (item.paperType === '考试' ? '考试' : '作业') : (GROUP_LABEL[item.group] || '其他'); const meta = document.createElement('div'); meta.className = 'meta'; const nameEl = document.createElement('div'); nameEl.className = 'name'; nameEl.textContent = item.name; nameEl.title = item.name; const sub = document.createElement('div'); sub.className = 'sub'; const sizeEl = document.createElement('span'); sizeEl.textContent = ui.tab === 'papers' ? '' : fmtSize(item.size); const durEl = document.createElement('span'); durEl.className = 'pt'; if (item.duration) durEl.textContent = '时长 ' + fmtDuration(item.duration); const sttEl = document.createElement('span'); const [txt, cls] = statusText(st, item); sttEl.textContent = txt; sttEl.className = 'stt ' + cls; sub.appendChild(sizeEl); if (durEl.textContent) sub.appendChild(durEl); // 章节/目录名已在树状标题里,行内不再重复 sub.appendChild(sttEl); meta.appendChild(nameEl); meta.appendChild(sub); if (st.state === 'downloading') { const prog = document.createElement('div'); prog.className = 'prog'; const bar = document.createElement('i'); bar.style.width = (st.pct || 0) + '%'; prog.appendChild(bar); meta.appendChild(prog); } const act = document.createElement('button'); act.className = 'btn act'; act.textContent = ui.tab === 'papers' ? '导出' : (st.state === 'done' ? '重新下载' : (st.state === 'needpreview' ? '打开' : '下载')); act.addEventListener('click', () => { if (st.state === 'needpreview') { const owner = owners.get(item.key); if (owner && item.objectid) { owner.postMessage({ [MSG]: 1, type: 'OPEN', key: item.key, objectid: item.objectid }, '*'); setStatus(item.key, { state: 'resolving', msg: '正在打开预览' }); } return; } if (st.state === 'downloading' || st.state === 'resolving') return; if (st.state === 'done') statusMap.set(item.key, { state: 'idle', pct: 0, msg: '' }); enqueue([item.key]); }); row.appendChild(sel); row.appendChild(tag); row.appendChild(meta); const actGroup = document.createElement('div'); actGroup.className = 'act-group'; if (ui.tab !== 'papers') { const copyBtn = document.createElement('button'); copyBtn.className = 'btn mini'; copyBtn.textContent = '链'; copyBtn.title = '复制直链(可丢给 IDM / aria2)'; copyBtn.addEventListener('click', () => copyLink(item)); actGroup.appendChild(copyBtn); } actGroup.appendChild(act); row.appendChild(actGroup); rowEls.set(item.key, { row, sttEl, act }); return row; } function paintRow(key, st) { const ref = rowEls.get(key); if (!ref) return; const item = (docs.get(key) || videos.get(key) || papers.get(key)); if (!item) return; const [txt, cls] = statusText(st, item); ref.sttEl.textContent = txt; ref.sttEl.className = 'stt ' + cls; ref.act.textContent = ui.tab === 'papers' ? '导出' : (st.state === 'done' ? '重新下载' : (st.state === 'needpreview' ? '打开' : '下载')); let prog = ref.row.querySelector('.prog'); if (st.state === 'downloading') { if (!prog) { prog = document.createElement('div'); prog.className = 'prog'; prog.appendChild(document.createElement('i')); ref.row.querySelector('.meta').appendChild(prog); } prog.firstChild.style.width = (st.pct || 0) + '%'; } else if (prog) { prog.remove(); } } function updateCounters() { const n = Array.from(ui.selected).filter((k) => currentBucket().has(k)).length; $('#selHint').textContent = '已选 ' + n + ' 项'; $('#batch').disabled = n === 0; } function updateFoot() { const total = queue.length + running; let text = total > 0 ? '队列 ' + total + ' 项进行中' : '空闲'; if (ui.scanning) text = scanState.label || '扫描中…'; else if (scanState.done) text = scanState.label; $('#queueInfo').textContent = text; $('#cancel').style.display = (queue.length || running) ? 'inline' : 'none'; } /* ---------- 12.2 公告栏(借鉴小雅辅助工具:远程 JSON + 缓存 + 内置兜底) ---------- */ const NOTICE_CFG = { url: 'https://gitee.com/fieldlu/chaoxing-course-helper/raw/master/notice.json', cacheKey: 'notice_cache', fallback: { title: '📢 v1.0.0.2 已发布 · 旧版课程兼容', items: [ '旧版泛雅课程(公选课等)现已支持自动扫描', '🎓 安装 / 更新:https://gitee.com/fieldlu/chaoxing-course-helper/raw/master/chaoxing-course-downloader.user.js', '提示:进入课程页即自动扫描,题目导出字段在「题目」页自由组合' ] } }; function escapeHtml(t) { return String(t == null ? '' : t) .replace(/&/g, '&').replace(//g, '>') .replace(/"/g, '"').replace(/'/g, '''); } function autoLink(text) { const parts = []; const re = /(https?:\/\/[^\s<"']+)/gi; let last = 0, m; while ((m = re.exec(text)) !== null) { parts.push(escapeHtml(text.slice(last, m.index))); parts.push('' + escapeHtml(m[0]) + ''); last = m.index + m[0].length; } parts.push(escapeHtml(text.slice(last))); return parts.join(''); } function renderNotice(data) { const box = $('#notice-content'); if (!box || !data) return; const title = escapeHtml(data.title || '公告'); const items = (data.items || []).map((it) => '
  • ' + autoLink(String(it)) + '
  • ').join(''); box.innerHTML = '
    ' + autoLink(title) + '
    '; box.style.display = sessionStorage.getItem('cxdl_notice') === 'closed' ? 'none' : 'block'; const head = $('#noticeToggle'); if (head) head.classList.toggle('closed', sessionStorage.getItem('cxdl_notice') === 'closed'); } function fetchNotice() { try { const cached = store.get(NOTICE_CFG.cacheKey, null); if (cached) { renderNotice(cached); } else { renderNotice(NOTICE_CFG.fallback); try { store.set(NOTICE_CFG.cacheKey, NOTICE_CFG.fallback); } catch (e) {} } httpGet(NOTICE_CFG.url).then((r) => { const data = parseJson(r.text); if (!data || data.__html || !data.title) return; try { store.set(NOTICE_CFG.cacheKey, data); } catch (e) {} renderNotice(data); }).catch(() => {}); } catch (e) { /* 公告失败不影响主功能 */ } } /* ---------- 12.3 检查更新(借鉴小雅:头部三态按钮 + 更新弹窗 + 24h 静默自检) ---------- */ const UPDATE_STATE = { isLoaded: false, isChecking: false, info: null, error: '', hasNew: false }; let updateModal = null; function compareVersion(a, b) { const pa = String(a || '0').split(/[^\d]+/).filter(Boolean).map(Number); const pb = String(b || '0').split(/[^\d]+/).filter(Boolean).map(Number); const len = Math.max(pa.length, pb.length, 1); for (let i = 0; i < len; i++) { const av = Number.isFinite(pa[i]) ? pa[i] : 0; const bv = Number.isFinite(pb[i]) ? pb[i] : 0; if (av !== bv) return av > bv ? 1 : -1; } return 0; } function setUpdateBtn() { const btn = $('#updateBtn'); if (!btn) return; btn.classList.remove('is-new', 'is-checking'); if (UPDATE_STATE.isChecking) { btn.classList.add('is-checking'); btn.textContent = '检查中'; } else if (UPDATE_STATE.hasNew) { btn.classList.add('is-new'); btn.textContent = '有新版'; } else { btn.textContent = '↻ 更新'; } if (updateModal) renderUpdateModal(); } function checkUpdate(manual) { if (UPDATE_STATE.isChecking) return; UPDATE_STATE.isChecking = true; UPDATE_STATE.error = ''; setUpdateBtn(); httpGet(NOTICE_CFG.url + '?t=' + Date.now()).then((r) => { const data = parseJson(r.text); if (!data || data.__html || !data.version) throw new Error('更新清单缺少 version'); UPDATE_STATE.info = data; UPDATE_STATE.isLoaded = true; UPDATE_STATE.hasNew = compareVersion(data.version, VERSION) > 0; try { store.set(NOTICE_CFG.cacheKey, data); } catch (e) {} renderNotice(data); store.set('update_last_check', Date.now()); if (!manual && UPDATE_STATE.hasNew) { const key = 'update_notified_' + data.version; if (store.get(key, null) !== '1') { toast('发现新版本 ' + data.version + ' · 点右上角「有新版」更新'); store.set(key, '1'); } } }).catch((e) => { UPDATE_STATE.error = cleanErr(e); UPDATE_STATE.hasNew = false; }).finally(() => { UPDATE_STATE.isChecking = false; setUpdateBtn(); }); } function renderUpdateModal() { const modal = updateModal; if (!modal) return; const box = modal.querySelector('#upd-box'); if (!box) return; const info = UPDATE_STATE.info || {}; const latest = info.version || '—'; const hasInfo = !!info.version; const hasNew = hasInfo && compareVersion(latest, VERSION) > 0; const status = UPDATE_STATE.isChecking ? '正在检查更新' : (UPDATE_STATE.error ? '检查失败:' + UPDATE_STATE.error : (hasInfo ? (hasNew ? '发现新版本 ' + latest : '当前已是最新版本') : '尚未检查')); const statusColor = UPDATE_STATE.error ? '#8c2f24' : (hasNew ? 'var(--cui)' : 'var(--dai)'); const notes = Array.isArray(info.notes) ? info.notes : []; const dlUrl = info.downloadURL || 'https://gitee.com/fieldlu/chaoxing-course-helper/raw/master/chaoxing-course-downloader.user.js'; const repoUrl = info.projectURL || 'https://gitee.com/fieldlu/chaoxing-course-helper'; box.innerHTML = '
    ' + '
    ' + '
    ↻
    脚本更新
    ' + '
    通过 Gitee 版本清单检查新版
    ' + '
    ' + '
    当前版本
    ' + VERSION + '
    ' + '
    最新版本
    ' + '
    ' + latest + '
    ' + '
    ' + '
    ' + status + '
    ' + (notes.length ? '
    更新内容
    ' : '') + '
    ' + '' + '' + '' + '
    ' + '
    '; const cb = box.querySelector('#upd-check'); if (cb) cb.addEventListener('click', (e) => { e.stopPropagation(); checkUpdate(true); }); const ob = box.querySelector('#upd-open'); if (ob) ob.addEventListener('click', (e) => { e.stopPropagation(); window.open(dlUrl, '_blank'); }); const rb = box.querySelector('#upd-repo'); if (rb) rb.addEventListener('click', (e) => { e.stopPropagation(); window.open(repoUrl, '_blank'); }); } function showUpdateModal() { if (updateModal && updateModal.isConnected) { renderUpdateModal(); return; } updateModal = null; const modal = document.createElement('div'); modal.className = 'upd-mask'; const box = document.createElement('div'); box.id = 'upd-box'; modal.appendChild(box); shadow.appendChild(modal); updateModal = modal; modal.addEventListener('click', (e) => { if (e.target === modal) { modal.remove(); updateModal = null; } }); renderUpdateModal(); if (!UPDATE_STATE.isLoaded && !UPDATE_STATE.isChecking) checkUpdate(false); } $('#updateBtn').addEventListener('click', () => showUpdateModal()); // 每 24 小时静默自检一次 const lastCheck = Number(store.get('update_last_check', 0)) || 0; if (Date.now() - lastCheck > 24 * 3600 * 1000) setTimeout(() => checkUpdate(false), 3000); $('#noticeToggle').addEventListener('click', () => { const box = $('#notice-content'); const head = $('#noticeToggle'); const closed = sessionStorage.getItem('cxdl_notice') === 'closed'; if (closed) { sessionStorage.setItem('cxdl_notice', 'open'); box.style.display = 'block'; head.classList.remove('closed'); } else { sessionStorage.setItem('cxdl_notice', 'closed'); box.style.display = 'none'; head.classList.add('closed'); } }); let toastTimer = 0; function toast(msg) { const el = $('#toast'); el.textContent = msg; el.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('show'), 2000); } async function copyText(text) { try { const ok = await Promise.race([ navigator.clipboard.writeText(text).then(() => true).catch(() => false), sleep(1200).then(() => false) ]); if (ok) return true; } catch (e) { /* 继续回退 */ } try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;left:-9999px;top:0;'; document.body.appendChild(ta); ta.select(); const done = document.execCommand('copy'); ta.remove(); return !!done; } catch (e) { return false; } } async function copyLink(item) { try { toast('正在取直链…'); let url = ''; if (item.kind === 'video') { const info = await videoInfo(item.objectid); url = info.download || info.http; } else if (item.link) { url = item.link; } else { const info = await resolveDoc(item); url = info.direct || info.download; } if (!url) throw new Error('未取到链接'); const copied = await copyText(url); toast(copied ? '直链已复制' : '已生成直链,请手动复制:' + url.slice(0, 40) + '…'); } catch (e) { toast('复制失败:' + cleanErr(e)); } } /* ---------- 12.1 交互 ---------- */ $('#tabs').addEventListener('click', (e) => { const btn = e.target.closest('.tab'); if (!btn) return; ui.tab = btn.dataset.t; store.set('tab', ui.tab); ui.selected.clear(); $('#selAll').checked = false; render(); }); $('#selAll').addEventListener('change', (e) => { const on = e.target.checked; visibleItems().forEach((it) => { if (on) ui.selected.add(it.key); else ui.selected.delete(it.key); }); rowEls.forEach((ref) => { ref.row.querySelector('.sel').checked = on; }); updateCounters(); }); $('#batch').addEventListener('click', () => { const keys = Array.from(ui.selected).filter((k) => currentBucket().has(k)); if (!keys.length) return; enqueue(keys); ui.selected.clear(); rowEls.forEach((ref) => { ref.row.querySelector('.sel').checked = false; }); $('#selAll').checked = false; updateCounters(); }); $('#groupBy').addEventListener('click', () => { ui.groupBy = ui.groupBy === 'place' ? 'name' : 'place'; store.set('groupBy', ui.groupBy); $('#groupBy').textContent = ui.groupBy === 'place' ? '位置' : '名称'; renderList(); }); $('#filters').addEventListener('click', (e) => { const btn = e.target.closest('.chip'); if (!btn) return; if (btn.dataset.field) { const k = btn.dataset.field; ui.exportFields[k] = !ui.exportFields[k]; store.set('exportFields', ui.exportFields); btn.classList.toggle('on', !!ui.exportFields[k]); return; } ui.filter = btn.dataset.f; store.set('filter', ui.filter); shadow.querySelectorAll('.chip').forEach((c) => c.classList.toggle('on', c === btn)); renderList(); }); $('#refresh').addEventListener('click', () => { seenSig.clear(); broadcast({ type: 'HELLO' }); const items = scanAll(); items.forEach((it) => ingest(it, null)); render(); }); $('#scan').addEventListener('click', () => { const c = ctx(); if (c.courseid) { try { store.set(cacheKey(c.courseid), null); } catch (e) { /* 忽略 */ } } scanCourse(); }); $('#clear').addEventListener('click', () => { statusMap.forEach((st, k) => { if (st.state === 'done' || st.state === 'error') statusMap.set(k, { state: 'idle', pct: 0, msg: '' }); }); render(); }); $('#foldAll').addEventListener('click', () => { const keys = collectGroupKeys(buildTree(visibleItems()), [], ui.tab + ':'); const foldedCount = keys.filter((k) => ui.folded.has(k)).length; if (foldedCount) { keys.forEach((k) => ui.folded.delete(k)); toast('已展开全部目录'); } else { keys.forEach((k) => ui.folded.add(k)); toast('已折叠全部目录'); } renderList(); }); $('#cancel').addEventListener('click', () => { const n = queue.length; queue.length = 0; statusMap.forEach((st, k) => { if (st.state === 'queued') { statusMap.set(k, { state: 'idle', pct: 0, msg: '' }); paintRow(k, statusMap.get(k)); } }); toast(n ? '已取消 ' + n + ' 项排队任务' : '没有排队中的任务'); updateFoot(); }); $('#collapse').addEventListener('click', () => setCollapsed(true)); fabEl.addEventListener('click', () => setCollapsed(false)); (function initSeal() { const seal = $('#seal'); if (!seal) return; const img = document.createElement('img'); img.src = 'https://pan-yz.chaoxing.com/favicon.ico'; img.alt = ''; img.addEventListener('error', () => { seal.textContent = '藏'; }); img.addEventListener('load', () => { seal.appendChild(img); }); })(); function setCollapsed(v) { ui.collapsed = v; store.set('collapsed', v); panelEl.style.display = v ? 'none' : 'block'; fabEl.style.display = v ? 'block' : 'none'; } /* ---------- 12.2 拖动 ---------- */ (function drag() { const head = $('#head'); let sx = 0, sy = 0, ox = 0, oy = 0, dragging = false; if (ui.pos) { panelEl.style.left = ui.pos.left + 'px'; panelEl.style.top = ui.pos.top + 'px'; panelEl.style.right = 'auto'; panelEl.style.bottom = 'auto'; } head.addEventListener('mousedown', (e) => { if (e.target.closest('button')) return; dragging = true; const r = panelEl.getBoundingClientRect(); sx = e.clientX; sy = e.clientY; ox = r.left; oy = r.top; panelEl.style.left = r.left + 'px'; panelEl.style.top = r.top + 'px'; panelEl.style.right = 'auto'; panelEl.style.bottom = 'auto'; e.preventDefault(); }); window.addEventListener('mousemove', (e) => { if (!dragging) return; const w = panelEl.offsetWidth, h = panelEl.offsetHeight; panelEl.style.left = Math.min(Math.max(4, ox + e.clientX - sx), window.innerWidth - w - 4) + 'px'; panelEl.style.top = Math.min(Math.max(4, oy + e.clientY - sy), window.innerHeight - h - 4) + 'px'; }); window.addEventListener('mouseup', () => { if (!dragging) return; dragging = false; const r = panelEl.getBoundingClientRect(); ui.pos = { left: Math.round(r.left), top: Math.round(r.top) }; store.set('pos', ui.pos); }); })(); /* ---------- 12.3 启动 ---------- */ (function bootstrap() { setCollapsed(ui.collapsed); broadcast({ type: 'HELLO' }); [600, 1800, 4000, 8000].forEach((t) => setTimeout(() => broadcast({ type: 'HELLO' }), t)); scanAll().forEach((it) => ingest(it, null)); render(); updateFoot(); fetchNotice(); let timer = 0; const schedule = () => { clearTimeout(timer); timer = setTimeout(() => { const items = scanAll(); const before = docs.size + videos.size; items.forEach((it) => ingest(it, null)); if (docs.size + videos.size !== before) render(); }, SCAN_DEBOUNCE); }; try { new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true }); } catch (e) { /* 忽略 */ } // 进入课程即自动扫描:有缓存先秒开,缓存过期或首次访问再后台拉全量 setTimeout(() => autoScan(false), 1200); // 单页应用切换(章节 / 资料 / 作业 / 任务)也要跟上 let lastUrl = location.href; setInterval(() => { if (location.href === lastUrl) return; lastUrl = location.href; clearTimeout(timer); setTimeout(() => autoScan(false), 1000); }, 1500); })(); })();