// ==UserScript== // @name 国企学习网络学院 · 自动刷课助手 // @namespace https://ecbead.com/gq-study-bot // @version 1.0.2 // @description 国企学习网络学院(知学云/ecbead)专题班自动学习:自动进入专题班、逐课播放、静音防暂停、自动下一节、弹题与"继续学习"弹窗处理、可视化进度面板 // @author Hermes // @match https://ecbead.com/* // @match https://*.ecbead.com/* // @run-at document-idle // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_addStyle // @grant unsafeWindow // @noframes // @license MIT // ==/UserScript== (function () { 'use strict'; /* ========================================================= * 0. 基础环境 * =======================================================*/ const W = (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window; const APP = () => (W.app || window.app || null); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const $ = (sel, root) => (root || document).querySelector(sel); const $$ = (sel, root) => Array.from((root || document).querySelectorAll(sel)); const norm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim(); const visible = (el) => { if (!el || !el.getBoundingClientRect) return false; const r = el.getBoundingClientRect(); const st = getComputedStyle(el); return r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none' && Number(st.opacity || 1) > 0.05; }; const pad2 = (n) => String(n).padStart(2, '0'); const hhmmss = (sec) => { sec = Math.max(0, Math.floor(Number(sec) || 0)); const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60; return h ? `${h}:${pad2(m)}:${pad2(s)}` : `${pad2(m)}:${pad2(s)}`; }; /* ========================================================= * 1. 配置与存储(GM → localStorage 兜底) * =======================================================*/ const NS = 'gq.study.'; const hasGM = typeof GM_getValue === 'function' && typeof GM_setValue === 'function'; const store = { get(k, d) { try { if (hasGM) { const v = GM_getValue(NS + k, null); if (v !== null && v !== undefined) return v; } } catch (e) {} try { const v = localStorage.getItem(NS + k); if (v != null) return JSON.parse(v); } catch (e) {} return d; }, set(k, v) { try { if (hasGM) GM_setValue(NS + k, v); } catch (e) {} try { localStorage.setItem(NS + k, JSON.stringify(v)); } catch (e) {} }, del(k) { try { if (hasGM && typeof GM_deleteValue === 'function') GM_deleteValue(NS + k); } catch (e) {} try { localStorage.removeItem(NS + k); } catch (e) {} } }; const DEFAULT_CFG = { speed: 1, // 播放倍速:本站按真实播放时长计学时,倍速会少计,默认 1x onlyRequired: true, // 只刷必修 removeSequence: true,// 解除章节顺序限制 autoQuiz: true, // 自动处理弹题/随堂练习 keepAwake: true, // 保持屏幕唤醒,避免后台节流 autoScore: true, // 课程刷完后上报"学完" docWaitMin: 8 // 文档类小节最长停留(分钟) }; let CFG = Object.assign({}, DEFAULT_CFG, store.get('config', {})); // 迁移:早期版本默认 1.5x,本站倍速会少计学时 → 统一拉回 1x if (store.get('cfgVer', 1) < 2) { CFG.speed = 1; store.set('cfgVer', 2); } if (Number(CFG.speed) > 1) CFG.speed = 1; const saveCfg = () => store.set('config', CFG); /* ========================================================= * 2. 接口封装(复用站点自身的 OAuth 头) * =======================================================*/ function getToken() { try { const g = APP() && APP().global; if (!g) return null; const O = g.OAuth || {}; const t = O.token || g.token; if (!t) return null; return { type: t.token_type || t.tokenType || O.tokenType || 'Bearer', value: t.access_token || t.accessToken || t.token || t }; } catch (e) { return null; } } const isLoggedIn = () => { try { const t = getToken(); const u = APP() && APP().global && APP().global.currentUser; return !!(t && t.value) || !!(u && (u.id || u.userId || u.name)); } catch (e) { return false; } }; function apiHeaders(form) { const h = { 'Content-Type': form ? 'application/x-www-form-urlencoded; charset=utf-8' : 'application/json; charset=UTF-8', 'Version': (APP() && APP().projectConfig && APP().projectConfig.apiVersion) || '10.7.0' }; const t = getToken(); if (t) h.Authorization = `${t.type}__${t.value}`; return h; } async function api(path, opt) { opt = opt || {}; let url = path.charAt(0) === '/' ? path : '/api/v1/' + path; if (opt.query) { const qs = new URLSearchParams(); Object.keys(opt.query).forEach((k) => { if (opt.query[k] !== undefined) qs.append(k, opt.query[k]); }); url += (url.indexOf('?') >= 0 ? '&' : '?') + qs.toString(); } const init = { method: opt.method || 'GET', headers: apiHeaders(!!opt.form), credentials: 'include' }; if (opt.body != null) init.body = opt.form ? new URLSearchParams(opt.body).toString() : JSON.stringify(opt.body); const res = await fetch(url, init); const text = await res.text(); let data = null; try { data = text ? JSON.parse(text) : null; } catch (e) { data = text; } if (res.status === 401) { const err = new Error('登录状态已过期'); err.code = 401; throw err; } if (!res.ok) { const err = new Error(`HTTP ${res.status} ${path}`); err.code = res.status; err.body = data; throw err; } return data; } /* ========================================================= * 3. 面板 UI * =======================================================*/ const CSS = ` #gq-bot{position:fixed;right:16px;bottom:16px;width:330px;z-index:2147483000;background:rgba(17,21,28,.95); color:#e7ecf3;border:1px solid rgba(255,255,255,.13);border-radius:12px;box-shadow:0 12px 34px rgba(0,0,0,.45); font:12.5px/1.65 "Microsoft YaHei","PingFang SC",system-ui,sans-serif;backdrop-filter:blur(6px);overflow:hidden;user-select:none} #gq-bot *{box-sizing:border-box} #gq-bot .h{display:flex;align-items:center;gap:8px;padding:8px 10px;background:rgba(255,255,255,.05);cursor:move} #gq-bot .dot{width:8px;height:8px;border-radius:50%;background:#8a94a6;flex:none;box-shadow:0 0 0 3px rgba(138,148,166,.15)} #gq-bot .dot.run{background:#3ecf8e;box-shadow:0 0 0 3px rgba(62,207,142,.18);animation:gqp 1.6s infinite} #gq-bot .dot.pause{background:#f5b544;box-shadow:0 0 0 3px rgba(245,181,68,.18)} #gq-bot .dot.err{background:#f2637b;box-shadow:0 0 0 3px rgba(242,99,123,.18)} @keyframes gqp{0%,100%{opacity:1}50%{opacity:.45}} #gq-bot .t{font-weight:600;font-size:12.5px;flex:1;letter-spacing:.2px} #gq-bot .x{cursor:pointer;color:#8a94a6;padding:0 4px;font-size:14px} #gq-bot .x:hover{color:#fff} #gq-bot .b{padding:8px 10px} #gq-bot .row{display:flex;justify-content:space-between;gap:8px;margin:2px 0;color:#9aa5b6} #gq-bot .row b{color:#e7ecf3;font-weight:500;max-width:210px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #gq-bot .bar{height:5px;border-radius:3px;background:rgba(255,255,255,.1);overflow:hidden;margin:7px 0 3px} #gq-bot .bar>i{display:block;height:100%;width:0;background:linear-gradient(90deg,#2f9bff,#3ecf8e);transition:width .4s} #gq-bot .log{margin-top:6px;max-height:132px;overflow:auto;background:rgba(0,0,0,.28);border-radius:7px;padding:6px 7px; font:11px/1.55 Consolas,"Courier New",monospace;color:#adb8c8;white-space:pre-wrap;word-break:break-all;user-select:text} #gq-bot .log .w{color:#f5b544}#gq-bot .log .e{color:#f2637b}#gq-bot .log .s{color:#3ecf8e} #gq-bot .btns{display:flex;gap:6px;margin-top:8px;flex-wrap:wrap} #gq-bot button{flex:1;min-width:60px;cursor:pointer;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.07); color:#e7ecf3;border-radius:7px;padding:6px 4px;font:12px/1.2 inherit;transition:.15s} #gq-bot button:hover{background:rgba(255,255,255,.15)} #gq-bot button.pri{background:#2f7cf6;border-color:#2f7cf6;font-weight:600} #gq-bot button.pri:hover{background:#4a90ff} #gq-bot button:disabled{opacity:.45;cursor:not-allowed} #gq-bot .set{display:none;margin-top:8px;border-top:1px dashed rgba(255,255,255,.13);padding-top:7px} #gq-bot .set.on{display:block} #gq-bot .set label{display:flex;align-items:center;justify-content:space-between;margin:4px 0;color:#c2cbd9} #gq-bot .set select{background:#1c2330;color:#e7ecf3;border:1px solid rgba(255,255,255,.16);border-radius:5px;padding:1px 4px;font-size:11.5px} #gq-bot .set input[type=checkbox]{accent-color:#2f7cf6;width:14px;height:14px;cursor:pointer} #gq-bot .tip{color:#7e8899;font-size:11px;margin-top:6px;line-height:1.5} #gq-bot.min .b{display:none} #gq-bot .diag{display:none;margin-top:6px} #gq-bot .diag.on{display:block} #gq-bot .diag textarea{width:100%;height:150px;background:rgba(0,0,0,.35);color:#b6c1d0;border:1px solid rgba(255,255,255,.13); border-radius:6px;font:10.5px/1.45 Consolas,monospace;padding:5px;resize:vertical;user-select:text} `; const UI = { el: null, logEl: null, statusEls: {}, logs: [], mount() { if ($('#gq-bot')) return; const box = document.createElement('div'); box.id = 'gq-bot'; box.innerHTML = `
国企学习 · 刷课助手 —
状态未开始
班级—
课程—
小节—
本站按真实播放时长计学时:脚本固定 1x 播放(平台上手动调倍速也会被自动拉回 1x)。
切换课程时请保持本窗口在前台,最小化或被其他窗口完全遮挡可能被浏览器节流。
`; document.documentElement.appendChild(box); const style = document.createElement('style'); style.textContent = CSS; document.head.appendChild(style); this.el = box; this.logEl = $('#gq-log'); this.statusEls = { state: $('#gq-state'), cls: $('#gq-class'), course: $('#gq-course'), sec: $('#gq-sec'), bar: $('#gq-bar'), dot: $('#gq-dot') }; // 拖动 const head = $('.h', box); let drag = null; head.addEventListener('mousedown', (e) => { if (e.target.id === 'gq-min') return; const r = box.getBoundingClientRect(); drag = { x: e.clientX - r.left, y: e.clientY - r.top }; e.preventDefault(); }); document.addEventListener('mousemove', (e) => { if (!drag) return; box.style.left = Math.max(0, e.clientX - drag.x) + 'px'; box.style.top = Math.max(0, e.clientY - drag.y) + 'px'; box.style.right = 'auto'; box.style.bottom = 'auto'; }); document.addEventListener('mouseup', () => { drag = null; }); $('#gq-min').onclick = () => box.classList.toggle('min'); $('#gq-set').onclick = () => $('#gq-setbox').classList.toggle('on'); $('#gq-diag').onclick = async () => { const d = $('#gq-diagbox'); if (!d.classList.contains('on')) { $('#gq-diagtext').value = '正在收集…'; d.classList.add('on'); try { const snap = await DIAG.snapshot(); $('#gq-diagtext').value = JSON.stringify(snap, null, 2); } catch (e) { $('#gq-diagtext').value = '自检失败:' + (e && e.message || e); } } else d.classList.remove('on'); }; $('#gq-start').onclick = () => BOT.start(); $('#gq-pause').onclick = () => BOT.togglePause(); // 设置回填与保存 const bind = (id, key, isCheck, isNum) => { const el = $('#' + id); if (isCheck) el.checked = !!CFG[key]; else el.value = CFG[key]; el.onchange = () => { CFG[key] = isCheck ? el.checked : (isNum ? Number(el.value) : el.value); saveCfg(); log(`设置已保存:${key} = ${CFG[key]}`); }; }; bind('gq-speed', 'speed', false, true); bind('gq-onlyreq', 'onlyRequired', true); bind('gq-seq', 'removeSequence', true); bind('gq-quiz', 'autoQuiz', true); bind('gq-awake', 'keepAwake', true); bind('gq-score', 'autoScore', true); bind('gq-docwait', 'docWaitMin', false, true); }, setState(text, mode) { if (!this.statusEls.state) return; this.statusEls.state.textContent = text; const dot = this.statusEls.dot; dot.className = 'dot' + (mode ? ' ' + mode : ''); }, setClass(name) { if (this.statusEls.cls) this.statusEls.cls.textContent = name || '—'; }, setCourse(text) { if (this.statusEls.course) this.statusEls.course.textContent = text || '—'; }, setSection(text) { if (this.statusEls.sec) this.statusEls.sec.textContent = text || '—'; }, setProgress(done, total) { if (!this.statusEls.bar) return; const p = total ? Math.round((done / total) * 100) : 0; this.statusEls.bar.style.width = p + '%'; this.statusEls.bar.title = `${done}/${total}`; }, log(msg, type) { const t = new Date(); const line = `[${pad2(t.getHours())}:${pad2(t.getMinutes())}:${pad2(t.getSeconds())}] ${msg}`; this.logs.push({ line, type: type || '' }); if (this.logs.length > 400) this.logs.shift(); try { console.log('%c[刷课助手]', 'color:#2f7cf6', msg); } catch (e) {} if (!this.logEl) return; const div = document.createElement('div'); if (type) div.className = type; div.textContent = line; this.logEl.appendChild(div); while (this.logEl.childElementCount > 200) this.logEl.removeChild(this.logEl.firstChild); this.logEl.scrollTop = this.logEl.scrollHeight; }, setButtons(running) { const s = $('#gq-start'), p = $('#gq-pause'); if (!s) return; s.textContent = running ? '运行中…' : '开始刷课'; s.disabled = running; p.disabled = !running; p.textContent = BOT && BOT.paused ? '继续' : '暂停'; } }; const log = (m, t) => UI.log(m, t); /* ========================================================= * 4. 页面解析工具 * =======================================================*/ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'; function currentClassId() { const h = decodeURIComponent(location.hash || '') + ' ' + location.href; let m = h.match(new RegExp(`train-new/class-detail/(${UUID})`, 'i')); if (m) return m[1]; m = h.match(new RegExp(`[?&]classId=(${UUID})`, 'i')); if (m) return m[1]; m = h.match(new RegExp(`study/(?:course|subject)/detail/[^/]+/[^/]+/[^/]+/(${UUID})`, 'i')); if (m) return m[1]; m = h.match(new RegExp(`class-detail/(${UUID})`, 'i')); if (m) return m[1]; return null; } function studyHash(courseId, classId) { return classId ? `#/study/course/detail/11&${courseId}/5/1/${classId}` : `#/study/course/detail/10&${courseId}/6/1`; } /** 在 window.app._modules 里找课程/专题的 Vuex 模块;preferId 命中优先 */ function findCourseStore(kind, preferId) { const app = APP(); if (!app || !app._modules) return null; const prefixes = kind === 'subject' ? ['study/subject/detail--', 'study/subject/detail'] : ['study/course/detail--', 'study/course/detail']; let keys = Object.keys(app._modules); keys = keys.filter((k) => prefixes.some((p) => k.indexOf(p) === 0)).concat(keys); const hits = []; for (const k of keys) { const mod = app._modules[k]; try { const models = mod && mod.store && mod.store.models; if (!models) continue; const node = models.course || models.subject; if (node && node.data && Array.isArray(node.data.courseChapters)) { const d = node.data; hits.push({ key: k, store: mod.store, data: d, id: d.id || d.courseId || d.resourceId }); } } catch (e) {} } if (!hits.length) return null; if (preferId) { const hit = hits.find((h) => h.id && String(h.id) === String(preferId)); if (hit) return hit; } return hits[0]; } async function waitCourseStore(ms, kind, expectId) { const t0 = Date.now(); while (Date.now() - t0 < ms) { const st = findCourseStore(kind, expectId); if (st) { const id = st.data.id || st.data.courseId || st.data.resourceId; if (!expectId || !id || String(id) === String(expectId)) return st; } if (/oauth\/#login/.test(location.href)) return null; await sleep(700); } return null; } function flattenSections(data) { const out = []; (data.courseChapters || []).forEach((ch, ci) => { (ch.courseChapterSections || []).forEach((sec, si) => { out.push({ raw: sec, name: sec.name || sec.sectionName || '', id: sec.id, resourceId: sec.resourceId, sectionType: sec.sectionType, required: !!sec.required, chapter: ch, ci, si, chapterId: sec.chapterId || ch.id }); }); }); return out; } const finishOf = (sec) => { const p = (sec.raw && sec.raw.progress) || {}; const v = (p.finishStatus !== undefined && p.finishStatus !== null) ? p.finishStatus : (sec.raw && sec.raw.finishStatus); return Number(v); }; const isFinished = (sec) => [2, 4].includes(finishOf(sec)); /** 在 Vue 组件树里找带 toLink 的课程组件 */ function findVueComponent(pred, maxDepth) { const roots = []; try { if (W.zxyVue && W.zxyVue.$children) roots.push(W.zxyVue); } catch (e) {} try { const appEl = document.querySelector('#app'); if (appEl && appEl.__vue__) roots.push(appEl.__vue__); } catch (e) {} try { if (W.app && W.app.$root) roots.push(W.app.$root); } catch (e) {} const seen = new Set(); const walk = (node, depth) => { if (!node || depth > (maxDepth || 12) || seen.has(node)) return null; seen.add(node); try { if (pred(node)) return node; } catch (e) {} const kids = node.$children || []; for (const k of kids) { const r = walk(k, depth + 1); if (r) return r; } return null; }; for (const r of roots) { const hit = walk(r, 0); if (hit) return hit; } return null; } /* ========================================================= * 5. 业务动作 * =======================================================*/ const Dom = { clickText(re) { const el = $$('button,a,span,div,li').filter((e) => { const t = norm(e.textContent); return re.test(t) && visible(e) && (e.tagName === 'BUTTON' || e.tagName === 'A' || e.children.length === 0); })[0]; if (!el) return false; try { el.click(); return true; } catch (e) { return false; } }, /** 点击"去上课/继续学习"进入专题班 */ async enterClass() { const links = $$('a[href*="train-new/class-detail"]').filter(visible); if (links.length) { links[0].click(); return true; } if (this.clickText(/^(去上课|去学习|继续学习|开始学习|进入学习)$/)) return true; // 左侧菜单「我的专题班」 const menu = $$('a,div,span,li').filter((el) => el.children.length === 0 && /^我的专题班$/.test(norm(el.textContent)) && visible(el))[0]; if (menu) { try { menu.click(); } catch (e) {} await sleep(2500); if (this.clickText(/^去上课$/)) return true; } // 兜底:先回个人中心 if (!/\/center/.test(location.hash || '')) { location.hash = '#/center'; await sleep(3000); if (this.clickText(/^去上课$/)) return true; } return false; }, /** 点击某个小节;优先模拟点击,其次调用组件方法 */ async openSection(sec) { const items = $$('.chapter-list-box .section, .courseChapters .section, .section, [class*="section-item"]'); let el = items.find((e) => { const id = e.getAttribute('data-id') || e.getAttribute('data-section-id') || e.getAttribute('data-key') || ''; return sec.id && id && String(id).indexOf(String(sec.id)) >= 0; }); if (!el) { const key = norm(sec.name).slice(0, 14); if (key) el = items.find((e) => norm(e.textContent).indexOf(key) >= 0); } if (el) { if (el.offsetParent === null) { const box = el.closest('.chapter-list-box, .chapter-box, .chapter, [class*="collapse"]'); if (box) { try { box.click(); } catch (e) {} await sleep(700); } } try { el.click(); return true; } catch (e) {} } // 组件方法兜底 const comp = findVueComponent((c) => c && c.courseData && (typeof c.changeSection === 'function' || typeof c.toSection === 'function' || typeof c.toggleChapter === 'function' || typeof c.selectSection === 'function')); if (comp) { try { if (typeof comp.changeSection === 'function') { comp.changeSection(sec.id); return true; } if (typeof comp.toSection === 'function') { comp.toSection(sec.raw); return true; } if (typeof comp.selectSection === 'function') { comp.selectSection(sec.id); return true; } if (typeof comp.toggleChapter === 'function') { comp.toggleChapter(sec.raw); return true; } } catch (e) { log('组件方法切换小节失败:' + e.message, 'warn'); } } return false; }, /** 处理"继续学习/我知道了"等弹窗 */ handleDialogs() { const WORDS = /^(继续学习|继续观看|继续播放|我知道了|知道了|确定|好的|仍要继续|继续)$/; const scope = '[class*="modal"],[class*="dialog"],[class*="popup"],[class*="mask"],[class*="ant-modal"],[class*="layer"],[class*="countdown"],[class*="Countdown"]'; const cands = $$('button,a,span,div').filter((el) => { const t = norm(el.textContent); if (!WORDS.test(t) || !visible(el) || !el.closest(scope)) return false; if (el.tagName === 'BUTTON' || el.tagName === 'A') return true; return el.children.length === 0; }); if (!cands.length) { const cd = $('.countdownText'); if (cd && visible(cd)) { try { cd.click(); log('已点击学习提醒弹窗'); } catch (e) {} } return; } cands.slice(0, 2).forEach((el) => { try { el.click(); log('已点击弹窗按钮:' + norm(el.textContent)); } catch (e) {} }); }, /** 弹题/随堂练习:尽量自动作答 */ handleQuiz() { const box = $$('.split-section-detail, .split-section-detail-header--interact').find(visible) || $$('[class*="interact"], [class*="quiz"], [class*="exercise"]').filter(visible).find((b) => { const t = norm(b.textContent); return t.length > 8 && /题|选择|判断/.test(t) && $$('button,[class*="btn"]', b).some((x) => /提交|继续学习|继续播放|确定/.test(norm(x.textContent))); }); if (!box) return; const opts = $$('.option, .answer-item, li, [class*="option"]', box).filter(visible); if (opts.length < 2) return; log('检测到弹题,自动选择并提交(如答错请手动处理)', 'warn'); try { opts[0].click(); } catch (e) {} setTimeout(() => { const btns = $$('button,a,[class*="btn"]', box).filter((b) => visible(b) && /提交|继续学习|继续播放|确定|下一题/.test(norm(b.textContent))); if (btns[0]) btns[0].click(); }, 400); }, /** 人脸识别等无法自动完成的风控 */ checkFace() { // 只看可见弹窗/提示区域,避免整页 innerText 带来的性能开销 const boxes = $$('[class*="modal"],[class*="dialog"],[class*="popup"],[class*="mask"],[class*="face"],[class*="Face"]').filter(visible); if (!boxes.length) { if (Date.now() - (this._faceT || 0) < 15000) return false; this._faceT = Date.now(); const t = norm(document.body.innerText || ''); return /人脸识别|活体检测|请正对摄像头|请眨眼/.test(t); } const t = boxes.map((b) => norm(b.innerText || '')).join(' '); return /人脸识别|活体检测|请正对摄像头|请眨眼/.test(t); }, media() { const list = $$('video,audio').filter((m) => m.readyState > 0 || m.currentSrc); if (!list.length) return $$('video,audio')[0] || null; // 多个媒体时选面积最大的(避免选到广告/预览片) return list.sort((a, b) => { const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return rb.width * rb.height - ra.width * ra.height; })[0]; } }; /** 接口不可用时,从专题班页面的课程链接兜底枚举 */ function scrapeCoursesFromDom() { const map = new Map(); $$('a[href*="study/course/detail"], a[href*="course/detail"]').forEach((a) => { const href = decodeURIComponent(a.getAttribute('href') || a.href || ''); const m = href.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i); if (m && !map.has(m[1])) map.set(m[1], norm(a.getAttribute('title') || a.textContent).slice(0, 60) || m[1]); }); // 卡片上的"去学习"按钮无法可靠定位课程ID,此处不做猜测 return Array.from(map, ([id, name]) => ({ id, name, required: true, finish: 0, fromDom: true })); } /** 站点改版后,接口可能换名:直接扫 Vuex 里形如活动列表的数据 */ function classActivitiesFromStores() { const app = APP(); if (!app || !app._modules) return []; const found = []; const seen = new Set(); const isAct = (o) => o && typeof o === 'object' && (o.businessId || o.businessName) && ('businessType' in o || 'required' in o); const walk = (node, depth) => { if (!node || depth > 6 || seen.has(node)) return; if (Array.isArray(node)) { if (node.length && node.every(isAct)) { node.forEach((n) => found.push(n)); return; } node.forEach((n) => walk(n, depth + 1)); return; } if (typeof node !== 'object') return; seen.add(node); Object.keys(node).forEach((k) => walk(node[k], depth + 1)); }; Object.keys(app._modules).forEach((k) => { try { const models = app._modules[k].store && app._modules[k].store.models; if (!models) return; Object.keys(models).forEach((m) => walk(models[m] && models[m].data, 0)); } catch (e) {} }); const map = new Map(); found.forEach((a) => { if (a.businessId && !map.has(a.businessId)) map.set(a.businessId, a); }); return Array.from(map.values()); } async function fetchClassCourses(classId) { const chapters = await api('/api/v1/training/student/class-info/safe/chapter/paas', { query: { classId: classId } }); const chList = Array.isArray(chapters) ? chapters : ((chapters && (chapters.items || chapters.list)) || []); const out = []; const PAGE = 20; for (const ch of chList) { let page = 1, more = true, total = null; while (more && page <= 30) { let r; try { r = await api('/api/v1/training/student/class-info/safe/chapter-activity-list/paas/more', { query: { classId: classId, chapterId: ch.id || ch.chapterId, page: page, pageSize: PAGE } }); } catch (e) { break; } const items = (r && (r.items || r.list || r.records || r.rows)) || (Array.isArray(r) ? r : []); if (total === null && r && !Array.isArray(r) && (r.total !== undefined || r.count !== undefined)) total = Number(r.total !== undefined ? r.total : r.count); items.forEach((it) => out.push(Object.assign({}, it, { _chapterName: ch.name || ch.chapterName }))); more = total !== null ? (page * PAGE < total) : items.length >= PAGE; page++; await sleep(120); } } return out; } /* ========================================================= * 6. 机器人 * =======================================================*/ const BOT = { running: false, paused: false, busy: false, classId: null, className: '', courses: [], ci: 0, current: null, section: null, attempts: {}, async start() { if (this.running) return; UI.mount(); if (!isLoggedIn()) { log('未检测到登录状态,正在跳转登录页…', 'warn'); UI.setState('需要登录', 'pause'); store.set('autostart', true); setTimeout(() => { location.href = this.loginUrl(); }, 800); return; } this.running = true; this.paused = false; this.done = false; this.attempts = {}; this.courses = []; UI.setButtons(true); UI.setState('启动中', 'run'); try { await this.loop(); } catch (e) { log('运行异常:' + (e && e.message ? e.message : e), 'e'); UI.setState('异常', 'err'); this.running = false; } finally { if (!this.running) { UI.setButtons(false); UI.setState(this.done ? '全部完成' : '已停止', this.done ? 'run' : ''); } } }, togglePause() { if (!this.running) return; this.paused = !this.paused; UI.setState(this.paused ? '已暂停' : '运行中', this.paused ? 'pause' : 'run'); $('#gq-pause').textContent = this.paused ? '继续' : '暂停'; log(this.paused ? '已暂停' : '继续运行'); }, stop() { this.running = false; this.paused = false; UI.setButtons(false); UI.setState('已停止'); log('已停止'); }, loginUrl() { const state = (location.hash || '').replace(/^#/, ''); const q = [ 'response_type=token', 'client_id=999', 'redirect_uri=' + encodeURIComponent(location.origin), 'state=' + encodeURIComponent(state || '/'), 'lang=cn', 'cancelRememberState=0' ].join('&'); return location.origin + '/oauth/#login/' + btoa(q); }, async loop() { // 1) 定位专题班 let classId = currentClassId(); if (!classId) { log('当前不在专题班页面,尝试自动进入…', 'warn'); const ok = await Dom.enterClass(); if (ok) { for (let i = 0; i < 10 && !classId; i++) { await sleep(1000); classId = currentClassId(); } } } if (!classId) { UI.setState('未找到专题班', 'err'); log('未识别到专题班。请按此路径打开后重新点"开始刷课":个人中心 → 我的专题班 → 进行中 → 去上课。', 'e'); this.running = false; return; } this.classId = classId; UI.setClass(classId); log('专题班 ID:' + classId); // 2) 拉课程 UI.setState('获取课程列表', 'run'); let acts = []; try { acts = await fetchClassCourses(classId); log(`班级活动共 ${acts.length} 条`); } catch (e) { log('课程列表接口失败:' + (e && e.message), 'e'); } const courses = acts.filter((a) => Number(a.businessType) === 8); this.courses = courses.map((a) => { const prog = a.classStudentActivityProgress || a.studentActivityProgress || a.classActivityProgress || a.activityProgress || {}; return { id: a.businessId, name: a.businessName || a.businessId, required: !!a.required, finish: Number(prog.finishStatus !== undefined ? prog.finishStatus : prog.status), raw: a }; }); try { const info = await api('/api/v1/training/student/class-info/front/find-by-ids', { query: { ids: classId } }); const one = Array.isArray(info) ? info[0] : (info && (info[0] || info.data || info)); const nm = one && (one.name || one.className || one.title); if (nm) { this.className = nm; UI.setClass(nm); log('专题班:' + nm); } } catch (e) {} const others = acts.filter((a) => Number(a.businessType) !== 8); if (others.length) log(`另有 ${others.length} 个非课程活动(考试/直播等),不自动处理:` + others.slice(0, 3).map((o) => o.businessName).join('、'), 'warn'); if (!this.courses.length) { const acts2 = classActivitiesFromStores(); if (acts2.length) { log(`接口不可用,改从页面数据里拿到 ${acts2.length} 条活动`, 'warn'); this.courses = acts2.filter((a) => Number(a.businessType) === 8).map((a) => { const prog = a.classStudentActivityProgress || a.studentActivityProgress || a.activityProgress || {}; return { id: a.businessId, name: a.businessName || a.businessId, required: !!a.required, finish: Number(prog.finishStatus), raw: a }; }); } } if (!this.courses.length) { const sc = scrapeCoursesFromDom(); if (sc.length) { this.courses = sc; log(`接口未返回课程,改用页面链接枚举到 ${sc.length} 门课程`, 'warn'); } } if (!this.courses.length) { UI.setState('课程列表为空', 'err'); log('未取到课程,可能是接口结构与预期不同。请点"自检"把结果发我,我来适配。', 'e'); try { log('页面模块:' + Object.keys(APP()._modules || {}).join(' | ').slice(0, 700)); } catch (e) {} try { log('页面线索:.section=' + $$('.section').length + ',含"学习"按钮=' + $$('button,a,div,span').filter((el) => el.children.length === 0 && /学习|上课/.test(norm(el.textContent))).length); } catch (e) {} this.running = false; return; } const target = this.courses.filter((c) => !(CFG.onlyRequired && !c.required) && ![1, 2, 4].includes(c.finish)); log(`待学习课程 ${target.length} / ${this.courses.length}`); UI.setProgress(0, target.length); // 3) 逐课学习 for (let i = 0; i < target.length; i++) { if (!this.running) return; while (this.paused && this.running) await sleep(600); if (!this.running) return; const c = target[i]; UI.setCourse(`(${i + 1}/${target.length}) ${c.name}`); UI.setProgress(i, target.length); UI.setState('学习中', 'run'); try { await this.studyCourse(c, target.length); } catch (e) { log(`课程《${c.name}》异常:${e && e.message}`, 'e'); } } UI.setProgress(target.length, target.length); this.done = true; this.running = false; UI.setState('全部完成', 'run'); log('全部课程已处理完毕,请到"个人中心 → 我的证书"下载结业证书。', 's'); UI.setButtons(false); }, async loopOnce() { /* 兼容占位:暂停恢复由 loop 内部循环自动接管 */ }, async studyCourse(course) { log(`▸ 打开课程:${course.name}`); if (!(location.hash || '').includes(course.id)) { location.hash = studyHash(course.id, this.classId); await sleep(1500); } const st = await waitCourseStore(70000, null, course.id); if (!st) { log('课程页 70 秒未就绪,改用备用入口重试…', 'warn'); location.hash = `#/study/course/detail/10&${course.id}/6/1`; const st2 = await waitCourseStore(45000, null, course.id); if (!st2) { log('备用入口仍失败:可能未登录、课程已归档或无权限。', 'e'); return; } return await this.runSections(st2, course); } return await this.runSections(st, course); }, async runSections(st, course) { if (CFG.removeSequence) this.removeSequence(st); let guard = 0; while (this.running && guard++ < 200) { if (this.paused) { await sleep(800); continue; } const sections = flattenSections(st.data); const todo = sections.filter((s) => !isFinished(s) && !s.raw.__gqSkip && !(CFG.onlyRequired && !s.required)); if (!todo.length) break; const sec = todo[0]; this.section = sec; UI.setSection(`${sec.name} (${sec.sectionType})`); log(` · 小节:${sec.name}|类型 ${sec.sectionType}|必修 ${sec.required ? '是' : '否'}`); const MANUAL = [9, 12, 13, 14, 17]; if (MANUAL.indexOf(Number(sec.sectionType)) >= 0) { log(' 该小节是考试/问卷/直播/任务类,需人工完成,已跳过', 'warn'); sec.raw.__gqSkip = true; continue; } await this.studySection(st, sec); await sleep(1200); if (!isFinished(sec) && !this.paused) { const key = sec.id; this.attempts[key] = (this.attempts[key] || 0) + 1; if (this.attempts[key] >= 3) { log(' 该小节连续 3 次仍未完成,跳过。', 'warn'); sec.raw.__gqSkip = true; } } } // 课程收尾 const left = flattenSections(st.data).filter((s) => !isFinished(s) && !(CFG.onlyRequired && !s.required)); if (left.length === 0) { log(` ✔ 课程完成:${course.name}`, 's'); if (CFG.autoScore) { try { await api('/api/v1/course-study/course-front/score', { method: 'POST', form: true, body: { score: 10, businessId: course.id, businessType: 1 } }); log(' 已上报课程完成状态'); } catch (e) { log(' 上报完成状态失败(可忽略):' + e.message, 'warn'); } } } else { log(` 课程《${course.name}》仍有 ${left.length} 个未完成小节:` + left.slice(0, 3).map((s) => s.name).join('、'), 'warn'); } }, removeSequence(st) { try { let n = 0; const d = st.data; if (d.learnSequence) { d.learnSequence = null; n++; } (d.courseChapters || []).forEach((ch) => { if (ch.learnSequence) { ch.learnSequence = null; n++; } (ch.courseChapterSections || []).forEach((s) => { if (s.learnSequence) { s.learnSequence = null; n++; } }); }); try { const mod = APP()._modules[st.key]; const subj = mod && mod.store && mod.store.models && mod.store.models.subject; if (subj && subj.data && subj.data.learnSequence) { subj.data.learnSequence = null; n++; } } catch (e) {} if (n) log(`已解除 ${n} 处章节顺序限制`); } catch (e) {} }, async studySection(st, sec) { if (sec.raw.__gqSkip) return; const ok = await Dom.openSection(sec); if (!ok) { log(' 无法定位小节 DOM,跳过', 'e'); sec.raw.__gqSkip = true; return; } await sleep(1800); let media = Dom.media(); if (!media) { // 有些课程先显示封面,需要点"开始学习/继续学习"才出播放器 const startBtn = $$('button,a,span,div').filter((el) => visible(el) && /^(开始学习|继续学习|开始播放|进入学习)$/.test(norm(el.textContent)) && el.closest('[class*="player"],[class*="course"],[class*="study"],[class*="detail"]')) .filter((el) => el.tagName === 'BUTTON' || el.tagName === 'A' || el.children.length === 0)[0]; if (startBtn) { try { startBtn.click(); log(' 已点击"开始学习"'); } catch (e) {} await sleep(2500); media = Dom.media(); } } if (media) { await this.driveVideo(sec); return; } // 无媒体:文档/网页类,等待其自行计时完成 await this.driveDoc(sec); }, async driveVideo(sec) { const t0 = Date.now(); let limit = 40 * 60 * 1000; let lastTick = 0; let endedAt = 0; while (this.running && !this.paused) { const v = Dom.media(); if (v) { try { if (v.muted !== true) v.muted = true; if (Math.abs((v.playbackRate || 1) - CFG.speed) > 0.01) v.playbackRate = CFG.speed; if (v.paused && !v.ended) await v.play().catch(() => {}); } catch (e) {} const total = isFinite(v.duration) && v.duration > 0 ? v.duration : 0; if (total) limit = Math.max(8 * 60 * 1000, (total / Math.max(0.5, CFG.speed)) * 1000 + 4 * 60 * 1000); if (Date.now() - lastTick > 4000) { lastTick = Date.now(); UI.setSection(`${sec.name} ${hhmmss(v.currentTime)} / ${hhmmss(v.duration)}`); } if (v.ended) { if (!endedAt) endedAt = Date.now(); if (Date.now() - endedAt > 20000) { log(' 视频已播完但平台未回写完成状态,先跳到下一节', 'warn'); return; } } } this.guards(); if (isFinished(sec)) { log(' ✔ 本节完成', 's'); return; } if (Date.now() - t0 > limit) { log(' 视频等待超时,跳过本节', 'warn'); return; } await sleep(1200); } }, async driveDoc(sec) { const t0 = Date.now(); const limit = Math.max(3, CFG.docWaitMin) * 60 * 1000; let last = 0; while (this.running && !this.paused) { this.guards(); if (isFinished(sec)) { log(' ✔ 本节完成', 's'); return; } if (Date.now() - t0 > limit) { log(' 文档小节停留超时,跳过', 'warn'); return; } if (Date.now() - last > 8000) { last = Date.now(); // 尝试翻页/滚动,促进阅读计时 const nexts = $$('button,a,i').filter((el) => visible(el) && /下一页|下一頁|next|page-next/i.test((el.getAttribute('title') || '') + norm(el.className) + norm(el.textContent))); if (nexts[0]) { try { nexts[0].click(); } catch (e) {} } else { const sc = $$('div').filter((el) => el.scrollHeight > el.clientHeight + 50 && visible(el)) .sort((a, b) => b.clientHeight - a.clientHeight)[0]; if (sc) sc.scrollTop = Math.min(sc.scrollHeight, sc.scrollTop + sc.clientHeight * 0.8); } } await sleep(1500); } }, guards() { if (Date.now() - (this._g || 0) < 2500) return; this._g = Date.now(); if (Dom.checkFace()) { this.paused = true; UI.setState('需要人脸识别', 'err'); log('检测到人脸识别/实名弹窗,脚本无法代替,请手动完成后点"继续"。', 'e'); $('#gq-pause').textContent = '继续'; return; } Dom.handleDialogs(); if (CFG.autoQuiz) Dom.handleQuiz(); } }; /* ========================================================= * 7. 自检(把结构信息导出,便于适配) * =======================================================*/ const DIAG = { async snapshot() { const cut = (v, n) => { const s = typeof v === 'string' ? v : JSON.stringify(v); return s ? s.slice(0, n || 3000) : s; }; const out = { time: new Date().toLocaleString(), version: '1.0.2', href: location.href, hash: location.hash, loggedIn: isLoggedIn(), user: (() => { try { const u = APP().global.currentUser; return u && (u.name || u.realName || u.loginName || u.id); } catch (e) { return null; } })(), appModules: (() => { try { return Object.keys(APP()._modules || {}); } catch (e) { return []; } })(), classId: currentClassId(), perf: (() => { try { const set = new Set(); performance.getEntriesByType('resource').forEach((e) => { if (/\/api\/|oauth\/api/.test(e.name)) set.add(String(e.name).replace(location.origin, '')); }); return Array.from(set).slice(-100); } catch (e) { return []; } })(), dom: { chapterListBox: $$('.chapter-list-box').length, sections: $$('.section').length, videos: $$('video,audio').length, quizBoxes: $$('.split-section-detail').length, links: (() => { try { return Array.from(new Set($$('a[href]').map((a) => a.getAttribute('href')).filter((h) => h && h !== '#' && h !== 'javascript:;'))).slice(0, 40); } catch (e) { return []; } })(), actionTexts: (() => { try { return Array.from(new Set($$('button,a,span,div,li').filter((el) => el.children.length === 0 && /学习|上课|查看|继续|开始/.test(norm(el.textContent)) && norm(el.textContent).length < 14) .map((el) => norm(el.textContent)))).slice(0, 40); } catch (e) { return []; } })(), textExcerpt: norm((document.body && document.body.innerText) || '').slice(0, 800) }, store: null, api: {} }; const st = findCourseStore(); if (st) { const secs = flattenSections(st.data); out.store = { key: st.key, courseName: st.data.name || st.data.courseName, chapters: (st.data.courseChapters || []).length, sections: secs.slice(0, 40).map((s) => ({ name: s.name, type: s.sectionType, required: s.required, finishStatus: finishOf(s), id: s.id })) }; } const cid = out.classId; if (cid) { try { out.api.classInfo = cut(await api('/api/v1/training/student/class-info/front/find-by-ids', { query: { ids: cid } }), 4000); } catch (e) { out.api.classInfoError = String(e && e.message || e); } try { out.api.chaptersStatus = 'try'; out.api.chapters = cut(await api('/api/v1/training/student/class-info/safe/chapter/paas', { query: { classId: cid } }), 1500); } catch (e) { out.api.chaptersError = String(e && e.message || e); } try { out.api.branchActivityList = cut(await api('/api/v1/training/student/class-info/branch-activity-list', { query: { classId: cid } }), 1500); } catch (e) { out.api.branchActivityError = String(e && e.message || e); } } return out; } }; /* ========================================================= * 8. 登录页增强 & 路由监听 * =======================================================*/ const LOGIN_SCOPE = /\/oauth\//.test(location.pathname); function loginPageHelper() { const btnStart = $('#gq-start'); if (btnStart) { btnStart.textContent = '请先登录'; btnStart.disabled = true; } const panel = $('#gq-bot'); if (panel && !panel.dataset.moved) { panel.dataset.moved = '1'; panel.style.right = 'auto'; panel.style.left = '16px'; } const user = $('#D43username'); if (!user || user.dataset.gq) return; user.dataset.gq = '1'; const saved = store.get('account', ''); if (saved && !user.value) { user.value = saved; user.dispatchEvent(new Event('input', { bubbles: true })); } const remember = () => { if (user.value) store.set('account', user.value); }; user.addEventListener('blur', remember); const btn = $('.btn-login'); if (btn) btn.addEventListener('click', () => setTimeout(remember, 100)); log('登录页已就绪:请输入密码和图形码后点"登录",登录成功后脚本会自动开始刷课。'); } function onRoute() { UI.mount(); if (LOGIN_SCOPE || /oauth/.test(location.pathname)) { setTimeout(loginPageHelper, 1200); return; } if (isLoggedIn()) { UI.setState(BOT.running ? '运行中' : '已登录', BOT.running ? 'run' : ''); if (store.get('autostart', false) && !BOT.running) { store.del('autostart'); log('已登录,3 秒后自动开始刷课…'); setTimeout(() => BOT.start(), 3000); } } } /* ========================================================= * 9. 启动 * =======================================================*/ (function boot() { const start = () => { try { UI.mount(); onRoute(); window.addEventListener('hashchange', () => setTimeout(onRoute, 500)); // SPA 路由兜底轮询 setInterval(() => { if (location.href !== UI._lastHref) { UI._lastHref = location.href; onRoute(); } }, 1500); // 保持屏幕唤醒 (async () => { try { if (CFG.keepAwake && 'wakeLock' in navigator) { BOT._wake = await navigator.wakeLock.request('screen').catch(() => null); } } catch (e) {} })(); log('脚本已加载 v1.0.2。打开"个人中心 → 我的专题班 → 去上课"后点"开始刷课"。'); } catch (e) { console.error('[刷课助手] 启动失败', e); } }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => setTimeout(start, 500)); else setTimeout(start, 500); })(); })();