// ==UserScript== // @name 云学堂助手 // @namespace yun-xue-tang-assistant.local // @version 2.5.1 // @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并按列表批量推进课程 // @match *://kfmic.yunxuetang.cn/* // @match *://*.yunxuetang.cn/* // @grant none // @run-at document-idle // ==/UserScript== /* * 用法: * 1. 浏览器安装 Tampermonkey,新建脚本,粘贴本文件全部内容并保存。 * 2. 打开 https://kfmic.yunxuetang.cn/login.html,在右下角面板填账号/密码, * 点「一键登录并刷课」;登录成功后会自动进入课程列表并开始批量学习。 * 3. 也可以手动登录后,在列表页点「一键刷课」。 * * 密码保存: * - 只有勾选「记住密码」才会写入本机 localStorage,使用 base64 混淆(不是加密, * 本机其他脚本仍可读取)。公用电脑请不要勾选。 * - 不勾选时密码只用于本次登录,不会落盘。 * * 重要说明: * - 平台按“真实播放时长”计时,快进、倍速都不省时间,脚本只做自动播放和自动切节。 * - 批量刷课时,进入每门课都会先对齐到「第一个未学完的课时」,即从第一章第一节起 * 顺序学习,不沿用平台上次停留的位置(否则前面的课时会被跳过,整门课永远学不完)。 * 切换成功与否以目录高亮为准:没切过去会重试并如实提示「未能切换」,不会假装已切换。 * - 试跑稳定后,把下面 CFG.maxCourses 改成 0 即可不限门数(会持续很久)。 * - 平台若有防挂机检测/答题环节,脚本会跳过该课程并在面板提示。 * 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」; * 答题/考试、滑块拼图类验证仍会跳过该课程。 * - 验证码/滑块需要手动完成,脚本不会绕过。 * - 课程/单位如有相关规定,请自行确认风险。 * * 开发热加载: * - 本文件可直接被 dev/dev-loader.user.js 热注入:脚本暴露 window.__ytDispose(), * 加载器在注入新版本前会先调用它清理定时器、监听器与面板,因此保存文件后 * 约 1 秒内即可生效,无需手动刷新页面。 */ (function () { 'use strict'; // ======== 配置 ======== const CFG = { mute: true, // 静音(自动播放更稳) autoNext: true, // 手动打开课程时,本节结束后自动下一节 tickMs: 2000, // 主循环间隔 startClickCooldownMs: 15000, // 「开始学习」重复点击冷却 stuckMs: 5 * 60 * 1000, // 连续多久没有计时进展就放弃当前课程 maxCourses: 10, // 本次最多完成多少门;0 = 不限 maxConsecutiveFailures: 5, // 连续失败多少门后自动停止 alignToFirstIncomplete: true, // 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置 }; // 版本号:与文件头 @version 保持一致,悬浮窗和控制台都用它 const VERSION = '2.5.1'; const LS_ENABLED = 'yt-auto-play-enabled'; const LS_BATCH = 'yt-batch-v2'; const LS_LOGIN = 'yt-login-v1'; const LS_PENDING = 'yt-auto-start-after-login'; const PANEL_ID = 'yt-auto-panel'; const TAG = '[云学堂助手]'; // ======== 生命周期(支持热替换:新版本注入前先 dispose 旧实例) ======== const TIMERS = []; // setInterval id const DELAYS = []; // setTimeout id const WINDOW_LISTENERS = []; // [target, type, fn] const ELEMENT_LISTENERS = []; // [el, type, fn] function every(fn, ms) { const id = setInterval(fn, ms); TIMERS.push(id); return id; } function later(fn, ms) { const id = setTimeout(function () { const i = DELAYS.indexOf(id); if (i >= 0) DELAYS.splice(i, 1); try { fn(); } catch (e) { console.error(TAG, e); } }, ms); DELAYS.push(id); return id; } function onWindow(target, type, fn) { target.addEventListener(type, fn); WINDOW_LISTENERS.push([target, type, fn]); } function onElement(el, type, fn) { el.addEventListener(type, fn); ELEMENT_LISTENERS.push([el, type, fn]); } function dispose() { TIMERS.splice(0).forEach(function (id) { try { clearInterval(id); } catch (e) {} }); DELAYS.splice(0).forEach(function (id) { try { clearTimeout(id); } catch (e) {} }); WINDOW_LISTENERS.splice(0).forEach(function (x) { try { x[0].removeEventListener(x[1], x[2]); } catch (e) {} }); ELEMENT_LISTENERS.splice(0).forEach(function (x) { try { x[0].removeEventListener(x[1], x[2]); } catch (e) {} }); try { document.querySelectorAll('video[data-yt-hooked]').forEach(function (v) { v.removeAttribute('data-yt-hooked'); }); } catch (e) {} const panel = document.getElementById(PANEL_ID); if (panel && panel.parentNode) panel.parentNode.removeChild(panel); try { delete window.__ytAuto; } catch (e) {} try { if (window.__ytDispose === dispose) delete window.__ytDispose; } catch (e) {} console.log(TAG, '旧实例已释放'); } try { Object.defineProperty(window, '__ytDispose', { value: dispose, configurable: true, writable: true, }); } catch (e) { /* 重复注入时忽略 */ } // ======== 基础工具 ======== const norm = (s) => String(s || '').replace(/[\s ]/g, '').trim(); const truncate = (s, n) => (s.length > n ? s.slice(0, n) + '…' : s); function textOf(el) { try { return norm(el.innerText || el.textContent || ''); } catch (e) { return ''; } } function isVisible(el) { try { const win = (el.ownerDocument && el.ownerDocument.defaultView) || window; const r = el.getBoundingClientRect(); if (r.width === 0 || r.height === 0) return false; const cs = win.getComputedStyle(el); return cs.display !== 'none' && cs.visibility !== 'hidden' && Number(cs.opacity) > 0; } catch (e) { return false; } } function findVisibleButton(re) { const els = document.querySelectorAll('button, [role="button"], a'); for (const el of els) { if (re.test(textOf(el)) && isVisible(el)) return el; } return null; } function collectDocuments(win, out) { win = win || window; out = out || []; try { if (win.document) out.push(win.document); } catch (e) { /* 跨域 */ } try { for (let i = 0; i < win.frames.length; i++) { collectDocuments(win.frames[i], out); } } catch (e) { /* 跨域 */ } return out; } // ======== 状态 ======== const state = { enabled: true, // 手动打开的课程:自动连播 }; try { state.enabled = localStorage.getItem(LS_ENABLED) !== '0'; } catch (e) { /* ignore */ } function defaultBatch() { return { running: false, runFinished: false, completedThisRun: 0, consecutiveFailures: 0, listUrl: '', listPage: 1, current: null, // { title, status, startedAt, page } returning: false, phase: 'idle', // idle | entering | learning done: {}, // title -> timestamp failed: {}, // title -> { reason, at } }; } let S = defaultBatch(); try { const raw = localStorage.getItem(LS_BATCH); if (raw) S = Object.assign(defaultBatch(), JSON.parse(raw)); } catch (e) { /* ignore */ } function save() { try { localStorage.setItem(LS_BATCH, JSON.stringify(S)); } catch (e) { /* ignore */ } } // 运行时状态(不持久化) const R = { hooked: new WeakSet(), lastCardClickAt: 0, lastPageJumpAt: 0, pageChangeAt: 0, pageChangeSig: '', listWithCurrentSince: 0, lastGoListAt: 0, lastStartClickAt: 0, lastAdvanceAt: 0, manualAdvanceAt: 0, lastLessonKey: '', lastSummary: null, lastCountdown: null, lastProgressAt: Date.now(), waitStart: 0, waitSummaryX: -1, waitLessonKey: '', quizChecked: false, initialLessonChecked: false, phaseSince: 0, alignTries: 0, alignStable: 0, alignFailed: false, lastIdleClickAt: 0, idlePassed: 0, idleDialogText: '', idleDialogClicks: 0, idleGaveUp: false, restoreAttempts: 0, loginFilled: false, loginSubmittingAt: 0, loginAutoTried: false, loginBoundUser: null, loginBoundPwd: null, }; function resetCourseRuntime() { R.lastLessonKey = ''; R.lastSummary = null; R.lastCountdown = null; R.lastProgressAt = Date.now(); R.waitStart = 0; R.waitSummaryX = -1; R.waitLessonKey = ''; R.quizChecked = false; R.initialLessonChecked = false; R.phaseSince = 0; R.alignTries = 0; R.alignStable = 0; R.alignFailed = false; R.lastAdvanceAt = 0; R.restoreAttempts = 0; } // ======== 面板 ======== let statusEl = null; let statsEl = null; let cbBatch = null; let btnSkip = null; let labelAuto = null; let labelBatch = null; let loginBox = null; let loginUserEl = null; let loginPassEl = null; let loginRememberEl = null; let loginAutoEl = null; let btnOne = null; let btnClearCreds = null; function setStatus(text) { console.log(TAG, text); if (statusEl) statusEl.textContent = text; } function updatePanel() { if (cbBatch) cbBatch.checked = S.running; if (statsEl) { const limit = CFG.maxCourses > 0 ? CFG.maxCourses : '∞'; statsEl.textContent = '本次 ' + S.completedThisRun + '/' + limit + ' · 失败 ' + Object.keys(S.failed).length + (R.idlePassed ? ' · 验证 ' + R.idlePassed : ''); } if (btnSkip) { btnSkip.style.display = S.current && route() === 'course' ? 'block' : 'none'; } const cbAuto = document.getElementById('yt-auto-enabled'); if (cbAuto) cbAuto.checked = state.enabled; const onLogin = isLoginPage(); if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none'; if (labelAuto) labelAuto.style.display = onLogin ? 'none' : 'flex'; if (labelBatch) labelBatch.style.display = onLogin ? 'none' : 'flex'; if (statsEl) statsEl.style.display = onLogin ? 'none' : 'block'; if (btnOne) { // 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」 const onCourse = route() === 'course' && !!S.current; btnOne.textContent = onLogin ? '一键登录并刷课' : (onCourse && S.running ? '停止刷课' : '一键刷课'); btnOne.title = onCourse && S.running ? '停止批量刷课' : '开始 / 继续批量刷课'; } } function buildPanel() { if (window.top !== window.self) return; if (document.getElementById(PANEL_ID)) return; const box = document.createElement('div'); box.id = PANEL_ID; box.style.cssText = [ 'position:fixed', 'right:16px', 'bottom:16px', 'z-index:2147483647', 'background:rgba(24,24,28,.88)', 'color:#eee', 'padding:10px 12px', 'border-radius:8px', 'box-shadow:0 4px 16px rgba(0,0,0,.35)', 'font:12px/1.5 system-ui,-apple-system,"Microsoft YaHei",sans-serif', 'user-select:none', 'max-width:280px', 'min-width:220px', ].join(';'); const title = document.createElement('div'); title.style.cssText = 'display:flex;align-items:baseline;gap:6px;margin-bottom:6px;'; const titleText = document.createElement('span'); titleText.textContent = '云学堂助手'; titleText.style.cssText = 'font-weight:600;'; const titleVer = document.createElement('span'); titleVer.id = 'yt-version'; titleVer.textContent = 'v' + VERSION; titleVer.title = '脚本版本 v' + VERSION; titleVer.style.cssText = 'font-weight:400;font-size:10px;color:#8ee6c0;opacity:.85;'; title.appendChild(titleText); title.appendChild(titleVer); btnOne = document.createElement('button'); btnOne.type = 'button'; btnOne.id = 'yt-oneclick'; btnOne.textContent = '一键刷课'; btnOne.style.cssText = [ 'width:100%', 'margin:2px 0 6px', 'padding:5px 8px', 'cursor:pointer', 'background:#2f7d5b', 'color:#fff', 'border:1px solid #3a9a70', 'border-radius:5px', 'font-size:12px', 'font-weight:600', ].join(';'); btnOne.addEventListener('click', function () { if (isLoginPage()) { doLoginAndStart(); return; } // 只有播放页的按钮才是「停止」;列表页/门户页点它一律是开始/继续,避免误停 if (route() === 'course' && S.current && S.running) { S.running = false; save(); setStatus('自动刷课已暂停'); } else { startBatch(); } updatePanel(); }); loginBox = document.createElement('div'); loginBox.id = 'yt-login-box'; loginBox.style.cssText = 'display:none;margin-bottom:6px;'; const mkInput = function (id, type, ph) { const el = document.createElement('input'); el.id = id; el.type = type; el.placeholder = ph; el.autocomplete = type === 'password' ? 'off' : 'username'; el.style.cssText = [ 'width:100%', 'box-sizing:border-box', 'margin:0 0 4px', 'padding:4px 6px', 'background:#2a2a30', 'color:#eee', 'border:1px solid #555', 'border-radius:4px', 'font-size:12px', 'user-select:text', ].join(';'); return el; }; loginUserEl = mkInput('yt-login-user', 'text', '员工邮箱/账号'); loginPassEl = mkInput('yt-login-pass', 'password', '密码'); const mkCheck = function (id, text) { const label = document.createElement('label'); label.style.cssText = 'display:inline-flex;align-items:center;gap:4px;cursor:pointer;margin-right:10px;'; const cb = document.createElement('input'); cb.type = 'checkbox'; cb.id = id; label.appendChild(cb); label.appendChild(document.createTextNode(text)); return { label: label, cb: cb }; }; const rem = mkCheck('yt-login-remember', '记住密码'); loginRememberEl = rem.cb; const auto = mkCheck('yt-login-auto', '自动登录'); loginAutoEl = auto.cb; loginRememberEl.addEventListener('change', function () { if (!loginRememberEl.checked) clearSavedCreds(); }); const remRow = document.createElement('div'); remRow.style.cssText = 'margin:2px 0 4px;font-size:11px;color:#bbb;'; remRow.appendChild(rem.label); remRow.appendChild(auto.label); btnClearCreds = document.createElement('button'); btnClearCreds.type = 'button'; btnClearCreds.textContent = '清除密码'; btnClearCreds.style.cssText = [ 'padding:1px 6px', 'cursor:pointer', 'background:#444', 'color:#eee', 'border:1px solid #666', 'border-radius:4px', 'font-size:10px', ].join(';'); btnClearCreds.addEventListener('click', function () { clearSavedCreds(); if (loginPassEl) loginPassEl.value = ''; if (loginUserEl) loginUserEl.value = ''; setStatus('已清除保存的密码'); }); const loginHint = document.createElement('div'); loginHint.textContent = '密码仅存本机(base64 混淆,非加密),公用电脑请勿勾选记住'; loginHint.style.cssText = 'color:#d9a441;font-size:10px;line-height:1.35;margin-top:2px;'; loginBox.appendChild(loginUserEl); loginBox.appendChild(loginPassEl); loginBox.appendChild(remRow); loginBox.appendChild(btnClearCreds); loginBox.appendChild(loginHint); labelAuto = document.createElement('label'); labelAuto.style.cssText = 'display:flex;align-items:center;gap:6px;cursor:pointer;'; const cbAuto = document.createElement('input'); cbAuto.type = 'checkbox'; cbAuto.id = 'yt-auto-enabled'; cbAuto.checked = state.enabled; cbAuto.addEventListener('change', function () { state.enabled = cbAuto.checked; try { localStorage.setItem(LS_ENABLED, cbAuto.checked ? '1' : '0'); } catch (e) {} setStatus(cbAuto.checked ? '自动连播已开启' : '自动连播已关闭'); }); labelAuto.appendChild(cbAuto); labelAuto.appendChild(document.createTextNode('手动课程自动连播')); labelBatch = document.createElement('label'); labelBatch.style.cssText = 'display:flex;align-items:center;gap:6px;cursor:pointer;margin-top:4px;'; cbBatch = document.createElement('input'); cbBatch.type = 'checkbox'; cbBatch.id = 'yt-batch-enabled'; cbBatch.checked = S.running; cbBatch.addEventListener('change', function () { if (cbBatch.checked) { startBatch(); } else { S.running = false; save(); setStatus('自动刷课已暂停'); } updatePanel(); }); labelBatch.appendChild(cbBatch); labelBatch.appendChild(document.createTextNode('自动刷课(批量)')); statusEl = document.createElement('div'); statusEl.id = 'yt-status'; statusEl.textContent = '待机…'; statusEl.style.cssText = 'margin-top:6px;color:#8ee6c0;word-break:break-all;'; statsEl = document.createElement('div'); statsEl.id = 'yt-stats'; statsEl.style.cssText = 'margin-top:2px;color:#aaa;'; btnSkip = document.createElement('button'); btnSkip.type = 'button'; btnSkip.textContent = '跳过本课'; btnSkip.style.cssText = [ 'display:none', 'margin-top:6px', 'padding:2px 8px', 'cursor:pointer', 'background:#444', 'color:#eee', 'border:1px solid #666', 'border-radius:4px', 'font-size:12px', ].join(';'); btnSkip.addEventListener('click', function () { if (S.current) failCurrent('手动跳过'); }); const clearFail = document.createElement('button'); clearFail.type = 'button'; clearFail.textContent = '清除失败记录'; clearFail.style.cssText = [ 'display:inline-block', 'margin-top:6px', 'padding:2px 8px', 'cursor:pointer', 'background:#444', 'color:#eee', 'border:1px solid #666', 'border-radius:4px', 'font-size:12px', ].join(';'); clearFail.addEventListener('click', function () { S.failed = {}; S.consecutiveFailures = 0; S.runFinished = false; save(); updatePanel(); setStatus('已清除失败记录'); }); const hint = document.createElement('div'); hint.textContent = '真实播放计时 · 保持窗口可见'; hint.style.cssText = 'margin-top:6px;color:#777;font-size:11px;'; box.appendChild(title); box.appendChild(loginBox); box.appendChild(btnOne); box.appendChild(labelAuto); box.appendChild(labelBatch); box.appendChild(statusEl); box.appendChild(statsEl); box.appendChild(btnSkip); box.appendChild(clearFail); box.appendChild(hint); document.documentElement.appendChild(box); } function ensurePanel() { if (window.top !== window.self) return; if (!document.getElementById(PANEL_ID)) buildPanel(); updatePanel(); } // ======== 路由 ======== function route() { const h = location.hash || ''; if (h.indexOf('#/list') === 0) return 'list'; if (h.indexOf('#/course/play') === 0) return 'course'; return 'other'; } function goToList() { if (Date.now() - R.lastGoListAt < 5000) return; R.lastGoListAt = Date.now(); const url = S.listUrl || location.origin + '/kng/#/list'; if (route() === 'list') { S.returning = true; save(); return; } try { location.href = url; } catch (e) { location.hash = '#/list'; } } // ======== 登录 / 一键刷课 ======== function isLoginPage() { if (/\/login(\.html)?($|[?#])/i.test(location.pathname + location.search)) return true; if (/^#\/login/i.test(location.hash)) return true; return !!document.querySelector('input[type="password"]') && /登录/.test(document.title); } function loginFields() { const pwd = [...document.querySelectorAll('input[type="password"]')].find(isVisible) || null; const all = [...document.querySelectorAll('input')].filter(isVisible); let user = all.find(function (el) { return /员工邮箱|账号|用户名|邮箱|手机号/.test(el.placeholder || ''); }) || null; if (!user && pwd) { const pi = all.indexOf(pwd); for (let i = pi - 1; i >= 0; i--) { const el = all[i]; if (el.type === 'text' || el.type === 'email' || !el.type) { user = el; break; } } } return { user: user, pwd: pwd }; } function setNativeValue(el, value) { if (!el) return false; try { const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const setter = Object.getOwnPropertyDescriptor(proto, 'value').set; setter.call(el, value); } catch (e) { el.value = value; } el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); el.dispatchEvent(new Event('blur', { bubbles: true })); return true; } function findLoginVm() { const btn = findVisibleButton(/^登录$/); let vm = btn && btn.__vue__; while (vm && vm.$options.name !== 'Login') vm = vm.$parent; if (vm) return vm; for (const el of document.querySelectorAll('#app, #app *')) { const v = el.__vue__; if (v && v.pwdLoginForm) return v; } return null; } function fillLoginForm(user, pass) { const f = loginFields(); if (!f.user || !f.pwd) return false; setNativeValue(f.user, user); setNativeValue(f.pwd, pass); const vm = findLoginVm(); if (vm && vm.pwdLoginForm) { vm.pwdLoginForm.userName = user; vm.pwdLoginForm.password = pass; } return true; } function checkLoginAgreement() { const labels = [...document.querySelectorAll('label')].filter(function (l) { return /已阅读并同意|隐私政策/.test(l.innerText || '') && isVisible(l); }); if (!labels.length) return true; for (const label of labels) { const cb = label.querySelector('input[type="checkbox"]'); if (!cb) continue; if (!cb.checked) { try { label.click(); } catch (e) {} } if (!cb.checked) { try { cb.click(); } catch (e) {} } if (cb.checked) return true; } return false; } function b64enc(s) { const bytes = new TextEncoder().encode(String(s)); let bin = ''; for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); return btoa(bin); } function b64dec(s) { const bin = atob(String(s)); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); return new TextDecoder().decode(bytes); } function saveCreds(user, pass, remember, auto) { try { if (!remember) { localStorage.removeItem(LS_LOGIN); return; } localStorage.setItem(LS_LOGIN, b64enc(JSON.stringify({ u: user, p: pass, auto: !!auto }))); } catch (e) { /* ignore */ } } function loadCreds() { try { const raw = localStorage.getItem(LS_LOGIN); if (!raw) return null; const obj = JSON.parse(b64dec(raw)); if (!obj || !obj.u || !obj.p) return null; return { u: String(obj.u), p: String(obj.p), auto: !!obj.auto }; } catch (e) { return null; } } function clearSavedCreds() { try { localStorage.removeItem(LS_LOGIN); } catch (e) {} if (loginRememberEl) loginRememberEl.checked = false; } function startBatch() { if (S.runFinished) { S.completedThisRun = 0; S.consecutiveFailures = 0; S.runFinished = false; } S.running = true; if (!S.current) S.phase = 'idle'; save(); setStatus('自动刷课已开启'); const r = route(); if (r === 'list' || (r === 'course' && S.current)) { tick(); } else { goToList(); } updatePanel(); } function consumePendingStart() { let ts = 0; try { ts = Number(localStorage.getItem(LS_PENDING) || 0); } catch (e) {} if (!ts) return false; if (Date.now() - ts > 5 * 60 * 1000) { try { localStorage.removeItem(LS_PENDING); } catch (e) {} return false; } if (isLoginPage()) return false; try { localStorage.removeItem(LS_PENDING); } catch (e) {} startBatch(); return true; } function watchLoginResult() { if (!isLoginPage()) return; const vm = findLoginVm(); if (vm && vm.captchaVisible) { setStatus('需要手动完成验证码/滑块,完成后会自动继续'); return; // 保留 pending,手动完成登录后仍会自动开始 } if (vm && typeof vm.pwd_tips === 'string' && vm.pwd_tips.trim()) { try { localStorage.removeItem(LS_PENDING); } catch (e) {} R.loginSubmittingAt = 0; setStatus('登录失败:' + truncate(vm.pwd_tips.trim(), 50)); return; } const txt = document.body.innerText || ''; const err = txt.match(/(用户名密码错误[^\n]{0,60}|账号或密码错误[^\n]{0,60}|密码错误[^\n]{0,60}|账号不存在[^\n]{0,60}|登录失败[^\n]{0,60})/); if (err) { try { localStorage.removeItem(LS_PENDING); } catch (e) {} R.loginSubmittingAt = 0; setStatus('登录失败:' + truncate(err[0], 50)); return; } if (/验证码|安全验证|滑块/.test(txt) && R.loginSubmittingAt) { setStatus('需要手动完成验证码/滑块'); return; // 保留 pending,手动完成登录后仍会自动开始 } if (R.loginSubmittingAt && Date.now() - R.loginSubmittingAt > 12000) { R.loginSubmittingAt = 0; setStatus('尚未登录成功:请检查账号密码,或手动完成验证'); } } function doLoginAndStart() { const f = loginFields(); const user = (loginUserEl ? loginUserEl.value.trim() : '') || (f.user ? String(f.user.value || '').trim() : ''); const pass = (loginPassEl ? loginPassEl.value : '') || (f.pwd ? String(f.pwd.value || '') : ''); if (!user || !pass) { setStatus('请先填写账号和密码'); return; } if (loginUserEl) loginUserEl.value = user; if (loginPassEl) loginPassEl.value = pass; const remember = !!(loginRememberEl && loginRememberEl.checked); const auto = !!(loginAutoEl && loginAutoEl.checked); saveCreds(user, pass, remember, auto); fillLoginForm(user, pass); if (!checkLoginAgreement()) { setStatus('请先勾选《隐私政策》'); return; } try { localStorage.setItem(LS_PENDING, String(Date.now())); } catch (e) {} R.loginSubmittingAt = Date.now(); R.loginAutoTried = true; setStatus('正在登录…'); const vm = findLoginVm(); if (vm) { try { if (vm.pwdLoginForm) { vm.pwdLoginForm.userName = user; vm.pwdLoginForm.password = pass; } try { vm.agreeSecretProtocol = true; } catch (e) {} const p = vm.handleLogin(); if (p && typeof p.catch === 'function') { p.catch(function (e) { setStatus('登录异常:' + (e && e.message ? e.message : e)); }); } } catch (e) { setStatus('登录异常:' + (e && e.message ? e.message : e)); } } else { const btn = findVisibleButton(/^登录$/); if (btn) { try { btn.click(); } catch (e) {} } else { setStatus('未找到登录按钮,请手动点击'); } } later(watchLoginResult, 2500); } function loginPageTick() { if (!isLoginPage()) return; const f = loginFields(); if (f.user && f.pwd && (R.loginBoundUser !== f.user || R.loginBoundPwd !== f.pwd)) { R.loginBoundUser = f.user; R.loginBoundPwd = f.pwd; const sync = function () { if (loginUserEl) loginUserEl.value = f.user.value; if (loginPassEl) loginPassEl.value = f.pwd.value; }; onElement(f.user, 'input', sync); onElement(f.pwd, 'input', sync); } if (!R.loginFilled) { if (f.user && f.pwd) { R.loginFilled = true; const creds = loadCreds(); if (creds) { fillLoginForm(creds.u, creds.p); if (loginUserEl) loginUserEl.value = creds.u; if (loginPassEl) loginPassEl.value = creds.p; if (loginRememberEl) loginRememberEl.checked = true; if (loginAutoEl) loginAutoEl.checked = !!creds.auto; setStatus('已填充保存的账号,可点「一键登录并刷课」'); if (creds.auto && !R.loginAutoTried) { R.loginAutoTried = true; later(function () { doLoginAndStart(); }, 800); } } else { setStatus('填写账号密码后,点「一键登录并刷课」'); } } } if (R.loginSubmittingAt) watchLoginResult(); } // ======== 列表页 ======== function scanCards() { return [...document.querySelectorAll('li.kng-list-new__item')].map((li, i) => { const titleEl = li.querySelector('.yxtf-tooltip'); const tags = [...li.querySelectorAll('.kng-list-new__tag')].map(textOf); const status = tags.find((t) => /已学完|学习中|未开始|未学习|已完成/.test(t)) || tags.find((t) => t !== '课程') || ''; return { li: li, i: i, title: norm(titleEl ? titleEl.innerText : ''), status: status, tags: tags, }; }); } function currentPage() { const el = document.querySelector('.yxtf-pager .number.active'); if (!el) return null; const n = Number(textOf(el)); return Number.isFinite(n) ? n : null; } function maxPageNumber() { const nums = [...document.querySelectorAll('.yxtf-pager .number')] .map((e) => Number(textOf(e))) .filter((n) => Number.isFinite(n) && n > 0); return nums.length ? Math.max.apply(null, nums) : null; } function cardsSignature(cards) { cards = cards || scanCards(); if (!cards.length) return ''; return cards.length + '|' + cards[0].title + '|' + cards[cards.length - 1].title; } function jumpToPage(target) { if (!target) return false; if (Date.now() - R.lastPageJumpAt < 3000) return false; R.lastPageJumpAt = Date.now(); R.pageChangeAt = Date.now(); R.pageChangeSig = cardsSignature(); const input = document.querySelector( '.yxtf-pagination__editor input, .yxtf-pagination input[type="number"]' ); if (input) { try { const setter = Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype, 'value' ).set; setter.call(input, String(target)); } catch (e) { input.value = String(target); } input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, })); console.log(TAG, '跳转到第', target, '页'); return true; } const btn = [...document.querySelectorAll('.yxtf-pager .number')] .find((e) => Number(textOf(e)) === target); if (btn) { btn.click(); return true; } return false; } function nextPage() { if (Date.now() - R.lastPageJumpAt < 3000) return; R.lastPageJumpAt = Date.now(); R.pageChangeAt = Date.now(); R.pageChangeSig = cardsSignature(); const btn = document.querySelector('.yxtf-pagination .btn-next'); if (btn && !btn.disabled) { btn.click(); console.log(TAG, '翻到下一页'); } } function listTick() { const cards = scanCards(); if (!cards.length) return; // 列表还没渲染 // 等待翻页后的新卡片,避免用旧卡片做判断 if (R.pageChangeSig) { if (cardsSignature(cards) === R.pageChangeSig && Date.now() - R.pageChangeAt < 10000) { return; } R.pageChangeSig = ''; } if (R.pageChangeAt && Date.now() - R.pageChangeAt < 1500) return; if (S.listUrl !== location.href) { S.listUrl = location.href; save(); } const page = currentPage(); // 回到列表后,恢复到课程所在的页码 if (S.returning) { if (page != null && S.listPage && page !== S.listPage) { R.restoreAttempts++; if (R.restoreAttempts > 12) { console.warn(TAG, '页码恢复失败,改用当前页继续'); S.listPage = page || 1; S.returning = false; save(); } else if (S.listPage > page) { nextPage(); return; } else { jumpToPage(S.listPage); return; } } else { S.returning = false; R.restoreAttempts = 0; save(); setStatus('回到列表第 ' + (page || 1) + ' 页,继续…'); } } // 记录当前页 if (!S.returning && page != null && page !== S.listPage) { S.listPage = page; save(); } // 已在进入课程的过程中:等路由跳转 if (S.current && S.phase === 'entering') { if (Date.now() - (S.current.startedAt || 0) > 15000) { failCurrent('未能进入课程页面'); } return; } // 从课程页意外回到列表:判断当前课程是已完成还是中断 if (S.current && S.phase === 'learning') { if (!R.listWithCurrentSince) R.listWithCurrentSince = Date.now(); if (Date.now() - R.listWithCurrentSince < 5000) return; const card = cards.find(function (c) { return c.title === S.current.title; }); if (card && card.status === '已学完') { S.done[S.current.title] = Date.now(); S.completedThisRun = (S.completedThisRun || 0) + 1; } S.current = null; S.phase = 'idle'; S.returning = false; R.listWithCurrentSince = 0; save(); setStatus('已重置中断的课程状态,继续…'); } if (S.current) return; // 其他异常情况,等路由 const pending = cards.filter((c) => { if (!c.title) return false; if (c.status === '已学完') return false; if (S.done[c.title]) return false; if (S.failed[c.title]) return false; return true; }); if (pending.length) { if (Date.now() - R.lastCardClickAt < 5000) return; startCourse(pending[0]); return; } const max = maxPageNumber(); if (page != null && max && page < max) { nextPage(); return; } stopBatch('所有页面的未学完课程都已处理完毕'); } function startCourse(card) { const page = currentPage() || S.listPage || 1; S.current = { title: card.title, status: card.status, startedAt: Date.now(), page: page, }; S.listPage = page; S.phase = 'entering'; S.returning = false; R.lastCardClickAt = Date.now(); resetCourseRuntime(); save(); setStatus('进入课程:' + truncate(card.title, 28)); console.log(TAG, '进入课程', card.title, '状态', card.status); try { card.li.click(); } catch (e) { console.error(TAG, e); failCurrent('课程卡片点击失败'); } } // ======== 播放器 ======== function applyMute(v) { if (!CFG.mute) return; try { if (!v.muted) v.muted = true; v.defaultMuted = true; } catch (e) { /* ignore */ } } function playVideo(v) { if (!v) return; if (state.enabled || S.running) { try { const p = v.play(); if (p && typeof p.catch === 'function') p.catch(() => {}); } catch (e) { /* ignore */ } } } function hookVideo(v) { if (!v) return; if (v.getAttribute && v.getAttribute('data-yt-hooked') === '1') return; if (R.hooked.has(v)) return; R.hooked.add(v); try { v.setAttribute('data-yt-hooked', '1'); } catch (e) {} applyMute(v); onElement(v, 'play', function () { applyMute(v); R.lastProgressAt = Date.now(); }); onElement(v, 'ended', function () { R.lastProgressAt = Date.now(); }); onElement(v, 'timeupdate', function () { R.lastProgressAt = Date.now(); }); } function hookAllVideos() { for (const doc of collectDocuments()) { let vids; try { vids = doc.querySelectorAll('video'); } catch (e) { continue; } for (const v of vids) hookVideo(v); } } function findPlayableVideo() { const vids = [...document.querySelectorAll('video')].filter(function (v) { return v.duration > 0 || v.currentSrc; }); return vids.find(function (v) { return !v.paused; }) || vids.find(function (v) { return v.duration > 0; }) || vids[0] || null; } function ensurePlaying(v) { if (!v) return; applyMute(v); if (S.current) { try { if (Math.abs(v.playbackRate - 1) > 0.01) v.playbackRate = 1; } catch (e) { /* ignore */ } } if (!v.paused) return; // 已播完就交给「进度/切节」逻辑处理。 // 平台在切到下一节后会自动挂出「还需 5分钟…」,那是下一节的时长, // 不能据此把已结束的视频拉回开头重播。 if (v.ended) return; playVideo(v); } function readSummary() { const el = document.querySelector('[class*="course-summary"]'); if (!el) return null; const m = textOf(el).match(/已完成(\d+)\/(\d+)/); if (!m) return null; return { x: Number(m[1]), y: Number(m[2]), text: m[0] }; } function readCountdown() { const el = document.querySelector('.yxtulcdsdk-course-player__countdown'); if (!el) return null; const t = textOf(el); // 平台文案可能是「还需 2小时 7分钟 59秒」,也可能只剩「还需 5分钟」 const m = t.match(/还需(?:(\d+)小时)?(?:(\d+)分钟)?(?:(\d+)秒)?/); if (m && (m[1] || m[2] || m[3])) { return Number(m[1] || 0) * 3600 + Number(m[2] || 0) * 60 + Number(m[3] || 0); } if (/已完成|学习完成|已学完/.test(t)) return 0; return null; } function readActiveLessonKey() { const active = document.querySelector('.yxtulcdsdk-catalog .liactive'); if (!active) return ''; const li = active.closest('li'); return norm(li ? li.innerText : active.innerText); } // 目录里「章」节点也带 .hand 且包含子 ul;只取真正的课时 li function lessonItems() { return [...document.querySelectorAll('.yxtulcdsdk-catalog ul > li')] .filter(function (li) { return !li.querySelector('ul'); }); } function findNextLessonElement() { const active = document.querySelector('.yxtulcdsdk-catalog .liactive'); const activeLi = active ? active.closest('li') : null; if (!activeLi) return null; const lis = lessonItems(); const idx = lis.indexOf(activeLi); if (idx >= 0 && idx + 1 < lis.length) { const nextLi = lis[idx + 1]; return nextLi.querySelector('.hand') || nextLi; } return null; } function isLessonCompleted(li) { try { // 1) 完成态图标(平台用勾选 svg 标记已学完的课时) const ds = [...li.querySelectorAll('svg path')] .map(function (p) { return String(p.getAttribute('d') || ''); }); if (ds.some(function (d) { return d.indexOf('M10 2.75') === 0; })) return true; // 2) 文本兜底 if (/(已学完|已完成)$/.test(textOf(li))) return true; return false; } catch (e) { return false; } } function findFirstIncompleteLessonElement() { for (const li of lessonItems()) { if (!isLessonCompleted(li)) return li.querySelector('.hand') || li; } return null; } // ---- 课时切换(对齐起点 / 纠偏时使用,带多种点击方式与校验) ---- function lessonActiveLi() { const el = document.querySelector('.yxtulcdsdk-catalog .liactive'); return el ? el.closest('li') : null; } // 浏览器里有布局信息;jsdom 之类的无布局环境下返回 false,避免误判“隐藏” function layoutAvailable() { try { const r = document.body.getBoundingClientRect(); return r.width > 0 && r.height > 0; } catch (e) { return false; } } // 目录诊断快照:起点纠正失败时打到控制台,便于定位平台为什么不响应点击 function dumpCatalog() { return lessonItems().map(function (li, i) { return { i: i + 1, text: truncate(textOf(li), 36), active: li.classList.contains('liactive') || !!li.querySelector('.liactive'), done: isLessonCompleted(li), cls: String(li.className || '').slice(0, 48), }; }); } function fireMouse(el, type) { try { el.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window, button: 0, })); } catch (e) { /* ignore */ } } function firePointer(el, type) { try { el.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'mouse', isPrimary: true, })); } catch (e) { fireMouse(el, type.replace('pointer', 'mouse')); } } // 第 1 次点 li 本身;第 2 次点内部句柄;第 3 次补完整鼠标事件序列; // 第 4 次优先点该课时自带的「开始学习/继续学习」按钮 function clickLesson(li, attempt) { const inner = li.querySelector('.hand') || li.querySelector('a') || li.querySelector('span'); const targets = inner && inner !== li ? [li, inner] : [li]; if (attempt >= 4) { const startBtn = [...li.querySelectorAll('button, [role="button"], span, div')] .find(function (el) { return el.children.length <= 1 && /^(开始学习|继续学习)$/.test(textOf(el)); }); if (startBtn) { try { startBtn.click(); } catch (e) { /* ignore */ } return; } } const target = targets[(attempt - 1) % targets.length]; try { target.click(); } catch (e) { /* ignore */ } if (attempt >= 3) { for (const el of targets) { firePointer(el, 'pointerdown'); fireMouse(el, 'mousedown'); firePointer(el, 'pointerup'); fireMouse(el, 'mouseup'); fireMouse(el, 'click'); } } } // 平台切课时可能弹「确认切换/退出当前学习」,自动点掉 function confirmLessonDialog() { const els = [...document.querySelectorAll( '.yxt-dialog__wrapper button, .yxt-dialog__wrapper [role="button"], [class*="dialog"] button, button' )]; for (const el of els) { if (!isVisible(el)) continue; if (/^(确定|确认|继续|是|切换)$/.test(textOf(el))) { try { el.click(); } catch (e) { /* ignore */ } return true; } } return false; } function findNextButton() { const els = [...document.querySelectorAll( '[class*="kng-operate"] div, [class*="kng-operate"] span, [class*="kng-operate"] button' )]; for (const el of els) { if (textOf(el) === '下一个' && isVisible(el)) return el; } const generic = [...document.querySelectorAll('div, span, button, a')]; for (const el of generic) { if (el.children.length <= 1 && textOf(el) === '下一个' && isVisible(el)) return el; } return null; } function courseHasQuizLesson() { const tags = [...document.querySelectorAll('.yxtulcdsdk-catalog ul > li .tag-type')]; if (!tags.length) return false; return tags.some(function (t) { return /考试|测验|问卷|答题/.test(textOf(t)); }); } function detectQuiz() { const pat = /^(开始答题|继续答题|提交答案|提交试卷|开始考试)$/; for (const doc of collectDocuments()) { let els; try { els = doc.querySelectorAll('button, [role="button"], a'); } catch (e) { continue; } for (const el of els) { if (pat.test(textOf(el)) && isVisible(el)) return true; } } const dialogs = [...document.querySelectorAll('.yxt-dialog__wrapper, [class*="dialog"]')]; for (const d of dialogs) { if (!isVisible(d)) continue; const t = textOf(d); if (/开始考试|提交试卷|开始答题/.test(t)) return true; } return false; } // 防挂机验证:平台每 10 分钟(kngConf/cheat.maxMin)弹一次, // 文案「已触发防挂机验证,请点击“继续学习”,否则学习将被停止」,120 秒内不点就停止计时。 function findAntiIdleDialog() { const pat = /防挂机|不要走开|学习将被停止|请点击.?继续学习/; let best = null; let bestLen = Infinity; for (const doc of collectDocuments()) { let cands; try { // 只认 dialog/modal,别把 [class*="popup"] 之类的外层容器算进来: // 平台会把
整个页面套进去,误判成弹窗。 cands = doc.querySelectorAll('[class*="dialog"], [class*="modal"], [role="dialog"]'); } catch (e) { continue; } for (const el of cands) { if (!isVisible(el)) continue; const t = textOf(el); if (t.length > 400) continue; // 包住整页的外层容器直接排除 if (!pat.test(t)) continue; // 取文案最短的那层(即最内层弹窗),避免选到大 wrapper if (t.length < bestLen) { best = el; bestLen = t.length; } } } return best; } function findAntiIdleButton(dialog) { if (!dialog) return null; const want = /^(继续学习|我知道了|继续观看)$/; const pick = function (sel) { return [...dialog.querySelectorAll(sel)].find(function (el) { return want.test(textOf(el)) && isVisible(el); }) || null; }; // 必须优先点真正的