// ==UserScript== // @name 学习通小助手|网课自动刷|重构优化版 + AI 答题 // @namespace Aeolus // @version 1.21.1 // @description 重构版:Promise 化网络层、去轮询、增量 DOM 渲染、跨域 top 访问保护、全局变量污染与多处逻辑 bug 修复;内置 AI 答题(默认接入 DeepSeek,兼容 OpenAI/中转/Ollama,本地缓存 + 题库兜底 + 连通测试),支持任意改 Key / 多 Key 历史切换;v2.3 起可开启循环模式刷完自动回第一章。仅供个人学习研究。可在代码中修改配置 // @author Aeolus / refactor // @run-at document-end // @storageName unrivalxxt // @match *://*.chaoxing.com/* // @match *://*.edu.cn/* // @match *://*.nbdlib.cn/* // @match *://*.hnsyu.net/* // @match *://*.ac.cn/* // @icon http://pan-yz.chaoxing.com/favicon.ico // @grant unsafeWindow // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @grant GM_addValueChangeListener // @grant GM_info // @connect mooc1-1.chaoxing.com // @connect mooc1.chaoxing.com // @connect mooc1-2.chaoxing.com // @connect passport2-api.chaoxing.com // @connect cx.icodef.com // @connect 14.29.190.187 // @connect api.deepseek.com // @connect * // @license GPL-3.0-or-later // ==/UserScript== (() => { 'use strict'; /* ===================================================================== * 0. 运行环境 & 单例守卫 * 原脚本没有防重复注入:同域多 frame / 浏览器往返缓存恢复时会同时跑两份 * 任务队列,导致同一个视频被重复上报。这里加一把每 frame 的锁。 * ===================================================================== */ if (window.__XXT_HELPER__) { console.warn('[xxt] 本页面已注入,跳过重复执行'); return; } window.__XXT_HELPER__ = { version: '2.0.0' }; const W = (typeof unsafeWindow !== 'undefined' && unsafeWindow) || window; const D = W.document; const L = W.location; const UA = W.navigator.userAgent; const GM_INFO = (() => { try { return typeof GM_info !== 'undefined' ? GM_info : {}; } catch (_) { return {}; } })(); const IS_CAT = GM_INFO.scriptHandler === 'ScriptCat'; const IS_FF = UA.includes('Firefox'); const IS_MOBILE = UA.includes('Android'); // top 可能是跨域的:直接 _w.top.xxx 会抛 SecurityError 并中断整条调用链 const topWin = (() => { try { return W.top || null; } catch (_) { return null; } })(); /* ===================================================================== * 1. 配置(原脚本散落在顶部的 var 变量,集中在这里,改起来只有一处) * ===================================================================== */ const CONFIG = { jumpType: 1, // 0 智能模式 / 1 遍历模式 / 2 不跳转 disableMonitor: 0, // 1 = 解除多端学习监控(有清进度风险) accuracy: 75, // 章节测试最低提交正确率 randomDo: 1, // 找不到答案时随机填 backGround: 0, // 是否对接挂机小助手 autoLogin: 0, // 掉线自动登录 phoneNumber: '', password: '', autoConfirm: 1, // 接管原生 confirm enforceSpeedLimit: 0, // 1 = 遇到不允许倍速的视频强制回到 1 倍 maxDailyMinutes: 0, // 单日累计学习上限(分钟);0 = 不限,循环模式下建议保持 0 loopMode: 0, // 1 = 循环模式:刷完最后一节回到第一章第一节重来(面板可切) loopMax: 0, // 循环轮数上限,0 = 不限 loopCooldownMs: 45000, // 两次「回到第一章」之间的最小间隔,防止空转刷屏 logLimit: 50, answerConcurrency: 3, // 答题并发数 // AI 答题(OpenAI /chat/completions 兼容端点,默认接 DeepSeek)。 // enabled / provider / baseUrl / model / apiKey 会被面板里保存的值覆盖, // 存在脚本管理器里,改面板即生效。 ai: { enabled: 0, // 0 关闭 / 1 开启 provider: 'deepseek', // deepseek / openai / ollama / custom baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat', // 想让它先思考再答可换 deepseek-reasoner(更慢更贵) apiKey: '', timeout: 25000, // 单题超时 maxTokens: 64, // 只回一行 JSON,不需要长输出 temperature: 0, jsonMode: 1, // 1 = 带 response_format:json_object(不支持的端点会自动去掉重试) minConfidence: 0.5, // 低于此置信度先问题库,题库也没有才用 AI 结果 concurrency: 2, // AI 请求独立并发,避免把题库接口拖慢 cacheLimit: 800, // 本地答案缓存条数 cacheTtlDays: 30, // 面板上一键切换的预设;只影响 baseUrl/model,不动 key presets: { deepseek: { label: 'DeepSeek', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat' }, openai: { label: 'OpenAI', baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini' }, ollama: { label: '本地 Ollama', baseUrl: 'http://127.0.0.1:11434/v1', model: 'qwen2.5:7b' }, }, }, api: { base: 'http://14.29.190.187:54223/', answer: 'https://cx.icodef.com/wyn-nb?v=4', encPath: 'chaoXing/v3/getEnc.php', fallbackPath: 'chaoXing/v3/getAnswer.php', }, timing: { taskGap: 500, tick: 1000, reportEvery: 30, // 每 N 秒上报一次观看进度 uiPoll: 100, bgProbe: 15000, iframePoll: 500, }, // 原脚本把这两段 base64 直接内联在源码里(合计约 250KB), // 每次解析脚本都要重新解码。抽成常量,构建时再注入或留空即可。 assets: { qr: '', // data:image/png;base64,... audio: '', // data:audio/ogg;base64,... }, }; /* ===================================================================== * 2. 基础工具 * ===================================================================== */ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function topGet(key, fallback) { try { return topWin && topWin[key] !== undefined ? topWin[key] : fallback; } catch (_) { return fallback; } } function topSet(key, value) { try { if (topWin) topWin[key] = value; } catch (_) { /* 跨域 top 忽略 */ } } /** 循环模式:面板开关优先,缺省看 CONFIG.loopMode */ function isLoopMode() { const flag = topGet('unrivalLoop', null); if (flag === null || flag === undefined) return CONFIG.loopMode === 1; return flag === '1' || flag === 1 || flag === true; } const GM = { get(key, fallback) { try { const v = typeof GM_getValue === 'function' ? GM_getValue(key) : undefined; return v === undefined || v === null ? fallback : v; } catch (_) { return fallback; } }, set(key, value) { try { if (typeof GM_setValue === 'function') GM_setValue(key, value); } catch (_) { /* ignore */ } }, listen(key, handler) { try { if (typeof GM_addValueChangeListener === 'function') GM_addValueChangeListener(key, handler); } catch (_) { /* ignore */ } }, }; const state = { stopped: false, rate: normalizeRate(GM.get('unrivalrate', '1')), token: GM.get('tikutoken', ''), timers: new Set(), observers: [], }; /** 原写法 `parseFloat(x) === parseInt(x) ? parseInt(x) : parseFloat(x)` 两边等价,直接返回浮点值 */ function normalizeRate(value) { const n = parseFloat(value); return Number.isFinite(n) ? n : 1; } /** 统一登记定时器,出错时能一把清干净(原脚本大量 setInterval 无句柄,永远不会释放) */ function every(ms, fn) { const id = setInterval(() => { if (state.stopped) { stopTick(id); return; } fn(); }, ms); state.timers.add(id); return id; } function after(ms, fn) { const id = setTimeout(() => { state.timers.delete(id); fn(); }, ms); state.timers.add(id); return id; } /** 清定时器的同时把它从登记表里摘掉,否则 Set 会随运行时长无限膨胀 */ function stopTick(id) { clearInterval(id); clearTimeout(id); state.timers.delete(id); } function stopAll() { state.stopped = true; state.timers.forEach((id) => { clearInterval(id); clearTimeout(id); }); state.timers.clear(); state.observers.forEach((ob) => { try { ob.disconnect(); } catch (_) { /* ignore */ } }); state.observers = []; } const el = (id) => D.getElementById(id); function getQueryVariable(name) { const params = L.search.replace(/^\?/, '').split('&'); for (const param of params) { if (!param) continue; const idx = param.indexOf('='); if (idx < 0) continue; if (param.slice(0, idx) === name) return param.slice(idx + 1); } return null; } /** 原实现没找到时返回整条 cookie 字符串,会让后续判断意外成立 */ function getCookie(name) { const match = D.cookie.match(new RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); return match ? match[1] : null; } function handleImgs(html) { if (!html) return ''; return html.replace(/]*src=["']([^"']+)["'][^>]*>/gi, (_, url) => url.replace(/^https?:\/\//, '')); } /** 智能模式用的题干清洗(与原脚本保持一致,只把 replaceAll 换成一次正则) */ function trim(html) { if (!html) return ''; const normalized = handleImgs(html) .replace(/javascript:void\(0\);?/g, '') .replace(/ /g, '') .replace(/[,。:;?!()""!]/g, (ch) => ({ ',': ',', '。': '.', ':': ':', ';': ';', '?': '?', '(': '(', ')': ')', '“': '"', '”': '"', '!': '!', }[ch] || ch)) .replace(/-/g, ' '); return normalized .replace(/(<([^>]+)>)/gi, '') .replace(/^\s+/i, '') .replace(/\s+$/i, ''); } function formatTime(date = new Date()) { const pad = (n) => String(n).padStart(2, '0'); return { hour: pad(date.getHours()), minute: pad(date.getMinutes()), second: pad(date.getSeconds()) }; } function formatDuration(seconds = 0) { const total = Math.max(0, Math.floor(Number(seconds) || 0)); const pad = (n) => String(n).padStart(2, '0'); const h = Math.floor(total / 3600); const m = Math.floor((total % 3600) / 60); const s = total % 60; return h > 0 ? `${pad(h)}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`; } const clampPercent = (v) => { const n = Number(v); if (!Number.isFinite(n)) return 0; return Math.max(0, Math.min(100, Math.round(n))); }; function safeJSON(text) { try { return JSON.parse(text); } catch (_) { return null; } } const qs = (obj) => Object.keys(obj) .filter((k) => obj[k] !== undefined && obj[k] !== null) .map((k) => `${k}=${encodeURIComponent(obj[k])}`) .join('&'); /* ===================================================================== * 3. 网络层:GM_xmlhttpRequest → Promise(原脚本全是回调套回调 + busyThread 计数) * ===================================================================== */ function hasXHR() { return typeof GM_xmlhttpRequest === 'function'; } function http({ url, method = 'GET', headers = {}, data, timeout = 8000 }) { return new Promise((resolve, reject) => { if (!hasXHR()) return reject(new Error('GM_xmlhttpRequest 不可用,请检查脚本管理器')); try { GM_xmlhttpRequest({ method, url, headers, data, timeout, onload: (res) => resolve(res), onerror: (err) => reject(new Error((err && err.error) || '网络错误')), ontimeout: () => reject(new Error('请求超时')), }); } catch (err) { reject(err); } }); } async function httpJSON(options) { const res = await http(options); const data = safeJSON(res.responseText); if (!data) throw new Error('响应不是合法 JSON'); return data; } function isConnectError(err) { return String((err && err.message) || '').includes('@connect list'); } function reportConnectError() { Log.addHTML( '请添加安全网址:把 //@connect  ' + L.hostname + ' 加到脚本头部注释里,否则请求会被管理器拦截。', '#e53935' ); } /* ===================================================================== * 4. 日志:改成 DOM 增量追加(原来每次 addLog 都 join 全量 HTML 重设 innerHTML) * ===================================================================== */ const Log = (() => { let box = null; const entries = []; // { text, color, html } // 页面外壳会被整体替换(挂机页/主界面),缓存的节点失效时要重新取 const ensure = () => { if (box && box.isConnected) return box; box = el('log'); return box; }; function autoScroll() { const panel = D.querySelector('#tab-log .panel-body'); if (!box) return; try { box.scrollTop = box.scrollHeight; if (panel) panel.scrollTop = panel.scrollHeight; } catch (_) { /* ignore */ } } function node(entry) { const span = D.createElement('span'); span.style.color = entry.color; if (entry.html) span.innerHTML = entry.text; else span.textContent = entry.text; return span; } function append(entry) { entries.push(entry); if (entries.length > CONFIG.logLimit) entries.shift(); const host = ensure(); if (!host) return; host.appendChild(node(entry)); while (host.children.length > CONFIG.logLimit) host.removeChild(host.firstChild); autoScroll(); } /** UI 挂载前产生的日志先缓存在内存里,挂载后一次性补渲染(否则前几条会凭空消失) */ function flush() { const host = ensure(); if (!host) return; host.textContent = ''; entries.forEach((entry) => host.appendChild(node(entry))); autoScroll(); } function add(text, color = '#333') { const { hour, minute, second } = formatTime(); append({ text: `[${hour}:${minute}:${second}] ${text}`, color, html: false }); } /** 少数几条日志确实需要 //,单独走这个入口,避免正文被当 HTML 解析 */ function addHTML(html, color = '#333') { const { hour, minute, second } = formatTime(); append({ text: `[${hour}:${minute}:${second}] ${html}`, color, html: true }); } function clear() { entries.length = 0; const host = ensure(); if (host) host.textContent = ''; } function dump() { return entries.map((entry) => (entry.html ? entry.text.replace(/<[^>]+>/g, '') : entry.text)).join('\n'); } return { add, addHTML, clear, dump, autoScroll, flush }; })(); /* ===================================================================== * 5. 进度面板 * ===================================================================== */ const Progress = { state: { name: '暂无任务', percent: 0, type: '-', detail: '等待任务开始' }, els: null, init() { if (this.els && this.els.name) return true; this.els = { name: el('progressTaskName'), percent: el('progressTaskPercent'), bar: el('progressBarFill'), detail: el('progressTaskDetail'), type: el('progressTaskType'), }; return !!(this.els.name && this.els.percent && this.els.bar); }, render() { if (!this.init()) return; const s = this.state; this.els.name.textContent = s.name; this.els.percent.textContent = `${s.percent}%`; this.els.bar.style.width = `${s.percent}%`; this.els.bar.setAttribute('aria-valuenow', String(s.percent)); if (this.els.detail) this.els.detail.textContent = s.detail; if (this.els.type) this.els.type.textContent = `类型:${s.type}`; }, update(patch = {}) { this.state = Object.assign({}, this.state, patch); this.state.percent = clampPercent(this.state.percent); this.render(); }, reset(detail = '等待任务开始') { this.update({ name: '暂无任务', percent: 0, type: '-', detail }); }, }; const taskName = (item) => { if (!item) return '未命名任务'; if (item.name) return item.name; const p = item.property || {}; return p.name || p.title || '未命名任务'; }; function report(typeLabel, item, percent, detail) { Progress.update({ name: `[${typeLabel}] ${taskName(item)}`, type: typeLabel, percent, detail, }); } /* ===================================================================== * 6. 页面外壳(只构建一次;原来每个 tab 都用 innerHTML 拼接 + base64 重排) * ===================================================================== */ function shellHTML() { const qr = CONFIG.assets.qr ? `二维码` : ''; return ` 学习通小助手
任务配置
任务列表
运行日志
学习进度
保存 复习模式 循环模式 后台挂机 激活挂机 (要最小化页面请先激活挂机)
保存 关注公众号「一之哥哥」发送 token 可提升正确率(第三方运营)。
${qr}

显示 复制 保存 清空 Key
默认接 DeepSeek:https://api.deepseek.com/v1 + deepseek-chat,在 platform.deepseek.com 生成 Key 填进去即可, 也兼容 OpenAI、中转站、Ollama、vLLM 等 /chat/completions 端点。 填完点「保存」→「测试连接」→「AI 答题」打开开关。改 Key 不需要先清空:直接覆盖输入框点保存/测试即可, 输入框留空保存表示「不改动」;用过的 Key 会进右侧「历史 Key」下拉,随时切回;点「清空 Key」只清当前配置,历史仍在。
答案按「题干 + 选项」哈希缓存在本地,同一题只请求一次;置信度低于 ${CONFIG.ai.minConfidence} 时先问题库,题库没有答案才采用 AI 结果。
提示:Ctrl+1~4 切换面板
当前任务
暂无任务
0%
类型:-
等待任务开始
`; } const BUTTON_CLASS = { DEFAULT: 'btn btn-default', SUCCESS: 'btn btn-success' }; /** 挂载 UI 并绑定一次事件(原脚本把 bind 写在 100ms 轮询里,重复绑定过多次) */ function mountShell() { D.documentElement.innerHTML = shellHTML(); el('unrivalRate').value = state.rate; el('token').value = state.token; el('updateToken').onclick = () => { const next = el('token').value.trim(); state.token = next; GM.set('tikutoken', next); Log.add(`题库 Token 已更新:${next || '(空)'}`, 'green'); }; el('updateRateButton').onclick = () => { const next = normalizeRate(el('unrivalRate').value); state.rate = next; GM.set('unrivalrate', next); Log.add(next > 0 ? `倍速已更新为 ${next}x,3 秒内生效` : '倍速为 0,将跳过所有视频', next > 0 ? 'green' : 'orange'); }; el('backGround').onclick = () => { topSet('backNow', 1); Log.add('挂机已激活,可以最小化页面了', 'green'); }; if (!CONFIG.backGround) el('fuckMeModeButton').style.display = 'none'; bindToggle('reviewModeButton', 'unrivalreview', 'unrivalReviewMode', '复习模式已开启:已完成的视频也会重刷', '复习模式已关闭:已完成的视频自动跳过'); bindToggle('loopModeButton', 'unrivalloop', 'unrivalLoop', '循环模式已开启:刷完最后一节会回到第一章第一节,并强制重刷已完成视频', '循环模式已关闭:刷完最后一章就停下'); bindToggle('autoDoWorkButton', 'unrivaldowork', 'unrivalDoWork', '自动做章节测试已开启', '自动做章节测试已关闭'); bindToggle('autoSubmitButton', 'unrivalautosubmit', 'unrivalAutoSubmit', '达到正确率将自动提交', '不会自动提交,请手动提交'); bindToggle('autoSaveButton', 'unrivalautosave', 'unrivalAutoSave', '未达正确率将自动保存', '不会自动保存,请手动操作'); restoreToggleStates(); bindAI(); bindTabs(); bindLogTools(); bindHotkeys(); Progress.render(); Log.flush(); // 补渲染挂载前缓存的日志 // 只启动一条中继:把 iframe 里的状态字符串搬到日志里(原来每次 doWork 都新建一条) every(200, () => { const info = topGet('unrivalWorkInfo', ''); if (info) { Log.add(info, 'blue'); topSet('unrivalWorkInfo', ''); } }); } function restoreToggleStates() { const restore = (id, key, message) => { const node = el(id); if (!node) return; const on = topGet(key, '0') === '1'; node.setAttribute('class', on ? BUTTON_CLASS.SUCCESS : BUTTON_CLASS.DEFAULT); if (on && message) Log.add(message, 'green'); }; restore('reviewModeButton', 'unrivalReviewMode', '复习模式已开启'); restore('loopModeButton', 'unrivalLoop', '循环模式已开启:刷完最后一节会回到第一章第一节'); restore('autoDoWorkButton', 'unrivalDoWork', '自动做章节测试已开启'); restore('autoSubmitButton', 'unrivalAutoSubmit'); restore('autoSaveButton', 'unrivalAutoSave'); } function bindToggle(buttonId, storageKey, topKey, onText, offText) { const button = el(buttonId); if (!button) return; button.onclick = () => { const isOn = button.getAttribute('class') === BUTTON_CLASS.SUCCESS; const next = isOn ? '0' : '1'; button.setAttribute('class', isOn ? BUTTON_CLASS.DEFAULT : BUTTON_CLASS.SUCCESS); GM.set(storageKey, next); topSet(topKey, next); Log.add(isOn ? offText : onText, 'green'); }; } function bindTabs() { const items = Array.from(D.querySelectorAll('.tab-item')); const panes = Array.from(D.querySelectorAll('.tab-content')); const activate = (name) => { const target = D.querySelector(`[data-tab="${name}"]`); const pane = el(`tab-${name}`); if (!target || !pane) return; items.forEach((i) => i.classList.remove('active')); panes.forEach((p) => p.classList.remove('active')); target.classList.add('active'); pane.classList.add('active'); GM.set('lastSelectedTab', name); if (name === 'log') setTimeout(() => Log.autoScroll(), 60); }; items.forEach((item) => { item.onclick = () => activate(item.dataset.tab); }); const last = GM.get('lastSelectedTab', 'config'); if (last && last !== 'config') setTimeout(() => activate(last), 150); state.activateTab = activate; } function bindLogTools() { el('clearLogBtn').onclick = () => { if (!W.confirm('确定清空日志?')) return; Log.clear(); Log.add('日志已清空', 'green'); }; el('exportLogBtn').onclick = () => { const blob = new Blob([Log.dump()], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = D.createElement('a'); a.href = url; a.download = `学习通日志_${new Date().toISOString().replace(/[:.]/g, '-')}.txt`; D.body.appendChild(a); a.click(); D.body.removeChild(a); URL.revokeObjectURL(url); }; } function bindHotkeys() { D.addEventListener('keydown', (e) => { if (!e.ctrlKey) return; const map = { 1: 'config', 2: 'joblist', 3: 'log', 4: 'progress' }; const name = map[e.key]; if (!name) return; e.preventDefault(); if (state.activateTab) state.activateTab(name); }); } function addJobRow(label, name) { const box = el('joblist'); if (!box) return; const wrap = D.createElement('div'); wrap.className = 'panel panel-default'; const body = D.createElement('div'); body.className = 'panel-body'; body.textContent = `[${label}] ${name}`; wrap.appendChild(body); box.appendChild(wrap); } /* ===================================================================== * 7. 知识卡片页(knowledge/cards) * ===================================================================== */ function detectChromeVersion() { if (IS_FF) return 999; const m = UA.match(/Chrome\/(\d{2,3})/); return m ? parseInt(m[1], 10) : 999; } function handleClosedChapter() { if (!L.href.includes('knowledge/cards')) return true; for (const span of D.getElementsByTagName('span')) { if (!String(span.innerHTML).includes('章节未开放')) continue; if (L.href.includes('ut=s')) { L.href = L.href.replace('ut=s', 'ut=t').replace(/&cpi=[0-9]{1,10}/, ''); } else if (L.href.includes('ut=t')) { span.innerHTML = '此课程为闯关模式,请回到上一章节完成学习任务!'; return false; } break; } return true; } /** 从内联