// ==UserScript== // @name 平凡公需 // @namespace https://jxjyjd.hnu.edu.cn/ // @version 1.1.1 // @description 湖大公需课:自动播放、防暂停、自动下一节、自动完成算术验证题;切后台/进入新页面自动恢复播放,自动处理平台「继续学习」暂停遮罩(本人账号学习辅助) // @author local // @match https://jxjyjd.hnu.edu.cn/* // @match https://*.qiqiuyun.net/* // @grant none // @run-at document-start // @tag 自动播放 // @tag 学习辅助 // @tag 继续教育 // @tag 公需课 // @license MIT // ==/UserScript== (function () { 'use strict'; /* ============================================================ * 公共部分:算术题解析 / 安全计算 / 填表提交 * ============================================================ */ const TAG = '__hnu2026__'; function normText(s) { return String(s || '') .replace(/[0-9]/g, d => String.fromCharCode(d.charCodeAt(0) - 0xFEE0)) .replace(/[+]/g, '+') .replace(/[-—–−]/g, '-') .replace(/[×✕✖xX]/g, '*') .replace(/[÷/]/g, '/') .replace(/[(]/g, '(') .replace(/[)]/g, ')') .replace(/[=]/g, '=') .replace(/[?]/g, '?') .replace(/[,,]/g, ' ') .replace(/\s+/g, ' '); } function visible(el) { if (!el || !el.isConnected) return false; const st = getComputedStyle(el); if (st.display === 'none' || st.visibility === 'hidden' || st.opacity === '0') return false; const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; } // 从一段文字里提取算术式,如 "请计算:12 + 7 = ?" -> {expr:"12+7", value:19} function extractMath(raw) { let s = normText(raw); if (!s) return null; // 中文运算符 s = s.replace(/(\d)\s*加上?\s*(\d)/g, '$1+$2') .replace(/(\d)\s*减去?\s*(\d)/g, '$1-$2') .replace(/(\d)\s*乘以?\s*(\d)/g, '$1*$2') .replace(/(\d)\s*除以?\s*(\d)/g, '$1/$2'); // 把连续的数字/运算符/括号切成候选式子 const chunks = s.match(/[0-9()+\-*/.\s]+/g) || []; const cands = []; for (let c of chunks) { c = c.trim(); // 去掉首尾多余的运算符/空格 c = c.replace(/^[+*/.\s]+/, '').replace(/[+*/\s]+$/, ''); if (!c) continue; if (!/[+\-*/]/.test(c)) continue; if ((c.match(/\d/g) || []).length < 2) continue; const expr = c.replace(/\s+/g, ''); const value = evalMath(expr); if (value === null) continue; cands.push({ expr: expr, value: value }); } if (!cands.length) return null; // 优先含乘除或括号的,其次最长的 const score = x => (/[*/]/.test(x) ? 10 : 0) + (/\(/.test(x) ? 5 : 0) + x.length / 100; cands.sort((a, b) => score(b.expr) - score(a.expr)); return { expr: cands[0].expr, value: cands[0].value, text: s }; } // 四则运算求值(递归下降,不使用 eval) function evalMath(expr) { let i = 0; const s = expr.replace(/\s+/g, ''); function peek() { return s[i]; } function eat(ch) { if (s[i] === ch) { i++; return true; } return false; } function parseExpr() { let v = parseTerm(); if (v === null) return null; for (;;) { if (eat('+')) { const r = parseTerm(); if (r === null) return null; v += r; } else if (eat('-')) { const r = parseTerm(); if (r === null) return null; v -= r; } else break; } return v; } function parseTerm() { let v = parseFactor(); if (v === null) return null; for (;;) { if (eat('*')) { const r = parseFactor(); if (r === null) return null; v *= r; } else if (eat('/')) { const r = parseFactor(); if (r === null || r === 0) return null; v /= r; } else break; } return v; } function parseFactor() { let sign = 1; while (eat('-')) sign = -sign; if (eat('(')) { const v = parseExpr(); if (v === null || !eat(')')) return null; return sign * v; } const start = i; while (i < s.length && /[0-9.]/.test(s[i])) i++; if (i === start) return null; const num = parseFloat(s.slice(start, i)); if (!isFinite(num)) return null; return sign * num; } const v = parseExpr(); if (v === null || i !== s.length || !isFinite(v)) return null; // 保留 4 位小数,去掉末尾 0 return Math.round(v * 10000) / 10000; } function setNativeValue(el, value) { if (!el) return; const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const desc = Object.getOwnPropertyDescriptor(proto, 'value'); if (desc && desc.set) desc.set.call(el, String(value)); else el.value = String(value); el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); el.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'Enter' })); } function findQuizContainer(doc) { if (!doc || !doc.body) return null; const hasInput = el => !!el.querySelector( 'input:not([type="range"]):not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), textarea, [contenteditable="true"]' ); const hasOption = el => !!el.querySelector( 'input[type="radio"], input[type="checkbox"], [class*="option"], [class*="choice"], li' ); const notPlayerBar = el => !el.closest('.vjs-control-bar, .vjs-menu, .vjs-volume-panel, .vjs-progress-control'); // 1) 明确的弹题/验证类名:允许填空或选择 const strong = [ '.plugin-exampop-prompt', '.exam-modal', '[class*="exam-question"]', '[class*="exam_question"]', '[class*="captcha"]', '[class*="verify"]', '[class*="validate"]', '[class*="quiz"]', '[class*="anti-cheat"]', '[class*="anti_cheat"]' ]; for (const sel of strong) { let list; try { list = doc.querySelectorAll(sel); } catch (e) { continue; } for (const el of list) { if (!visible(el) || !notPlayerBar(el)) continue; const t = (el.innerText || '').trim(); if (t.length < 2) continue; const examBox = /exampop|exam-|exam_/.test(sel); if (examBox && /开始答题|开始作答|进入答题|继续答题|请回答/.test(t)) return el; if (!/[0-9]/.test(t) && !examBox) continue; if (hasInput(el) || hasOption(el)) return el; } } // 2) 通用对话框:必须有输入框,避免把目录/列表误判成题目 const dialogs = [ '.vjs-modal-dialog', '[role="dialog"]', '.modal.in', '.modal.show', '.modal[style*="display: block"]', '.swal2-popup', '.layui-layer', '.el-dialog', '.ant-modal', '[class*="dialog"]' ]; for (const sel of dialogs) { let list; try { list = doc.querySelectorAll(sel); } catch (e) { continue; } for (const el of list) { if (!visible(el) || !notPlayerBar(el)) continue; if (!hasInput(el)) continue; const t = (el.innerText || '').trim(); if (t.length < 2) continue; if (!/[0-9]/.test(t) && !/验证|回答|题目|答案|计算/.test(t)) continue; return el; } } return null; } function solveQuiz(container, log, opts) { if (!container || !container.isConnected || !visible(container)) return false; const text = (container.innerText || '').trim(); if (!text) return false; const math = extractMath(text); if (!math) { // 有些弹题先显示“开始答题”确认框,先点进去,下一轮再作答 const startBtns = Array.from(container.querySelectorAll('button, a, [role="button"], .btn')) .filter(visible); for (const b of startBtns) { const t = (b.innerText || b.textContent || '').trim(); if (/开始答题|开始作答|进入答题|继续答题|开始练习/.test(t)) { log('点击「' + t + '」进入答题'); try { b.click(); } catch (e) {} return true; } } const key = 'no-math:' + text.slice(0, 120); if (opts && opts.lastKey !== key) { opts.lastKey = key; log('⚠ 检测到题目但不是算术式,需要人工作答:' + text.slice(0, 100).replace(/\s+/g, ' ')); if (opts.onManual) opts.onManual(text); } return false; } const ans = (math.value !== undefined && math.value !== null) ? math.value : evalMath(math.expr); if (ans === null) { const key = 'bad-math:' + math.expr; if (opts && opts.lastKey !== key) { opts.lastKey = key; log('⚠ 无法计算:' + math.expr); } return false; } const key = 'ans:' + math.expr + '=' + ans; if (opts && opts.lastKey === key && Date.now() - (opts.lastAt || 0) < 5000) return true; if (opts) { opts.lastKey = key; opts.lastAt = Date.now(); } // 1) 选择题:找与答案相同的选项 let optionClicked = false; const labels = container.querySelectorAll('label, li, [class*="option"], [class*="choice"]'); for (const lab of labels) { if (!visible(lab)) continue; const t = normText(lab.innerText || '').replace(/\s+/g, ''); if (!t) continue; const nums = t.match(/-?\d+(?:\.\d+)?/g); const num = nums && nums.length ? nums[nums.length - 1] : null; if (num !== null && Math.abs(parseFloat(num) - ans) < 1e-9) { const clickable = lab.querySelector('input[type="radio"], input[type="checkbox"]') || lab; try { clickable.click(); optionClicked = true; } catch (e) {} break; } } // 2) 填空题:写入第一个可见输入框 let inputFilled = false; if (!optionClicked) { const inputs = Array.from(container.querySelectorAll( 'input:not([type="range"]):not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), textarea, [contenteditable="true"]' )).filter(visible); if (inputs.length) { const el = inputs[0]; if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') setNativeValue(el, ans); else { el.textContent = String(ans); el.dispatchEvent(new Event('input', { bubbles: true })); } inputFilled = true; } } if (!optionClicked && !inputFilled) { log('⚠ 找到算式 ' + math.expr + ' = ' + ans + ',但没找到可填写的位置'); return false; } log('✅ 自动答题:' + math.expr + ' = ' + ans + (optionClicked ? '(选项)' : '(填空)')); // 3) 提交按钮(优先确认/提交,其次下一题/完成) const btns = Array.from(container.querySelectorAll('button, a, [role="button"], .btn, [class*="btn"]')).filter(visible); const priority = [ /确认答案|提交答案|确认|提交|验证|确定/, /下一题|继续|下一步/, /完成|关闭/ ]; for (const re of priority) { for (const b of btns) { const t = (b.innerText || b.textContent || '').trim(); if (!t || t.length > 12) continue; if (re.test(t)) { try { b.click(); } catch (e) {} return true; } } } // 没有按钮时尝试回车 const inp = container.querySelector('input:not([type="range"]), textarea'); if (inp) { inp.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter', keyCode: 13 })); inp.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'Enter', keyCode: 13 })); } return true; } /* ============================================================ * 播放器 iframe 内的逻辑(qiqiuyun.net/media-player) * ============================================================ */ if (window.top !== window && /qiqiuyun\.net$/i.test(location.hostname) && /\/media-player\//.test(location.pathname)) { initPlayerFrame(); return; } function initPlayerFrame() { // 只接管湖大公需课的播放器;referrer 为空时保守放行 if (document.referrer && !/jxjyjd\.hnu\.edu\.cn/i.test(document.referrer)) return; let video = null; let quizOpen = false; let quizState = { lastKey: '', lastAt: 0 }; let muted = true; let autoResume = true; let lastPost = 0; let lastPlayTry = 0; let lastResumeTry = 0; let lastPauseAt = 0; let lastTrustedAt = 0; let lastResumeLogAt = 0; // 防止平台用 visibility 暂停 try { ['hidden', 'webkitHidden', 'mozHidden', 'msHidden'].forEach(p => { if (p in document) Object.defineProperty(document, p, { configurable: true, get: () => false }); }); ['visibilityState', 'webkitVisibilityState'].forEach(p => { if (p in document) Object.defineProperty(document, p, { configurable: true, get: () => 'visible' }); }); // 记录真实用户输入:自己点的暂停给更长缓冲,平台打断的暂停快速恢复 ['pointerdown', 'mousedown', 'touchstart', 'keydown'].forEach(evt => { document.addEventListener(evt, e => { if (e.isTrusted) lastTrustedAt = Date.now(); }, true); }); document.addEventListener('visibilitychange', e => { e.stopImmediatePropagation(); setTimeout(() => resumeIfPaused('回到播放器'), 500); }, true); window.addEventListener('blur', e => e.stopImmediatePropagation(), true); window.addEventListener('focus', () => setTimeout(() => resumeIfPaused('窗口获得焦点'), 400), true); window.addEventListener('pageshow', () => setTimeout(() => resumeIfPaused('页面恢复'), 400), true); } catch (e) {} function post(obj) { try { window.top.postMessage(Object.assign({ __hnu2026: true, from: 'player' }, obj), '*'); } catch (e) {} } function findVideo() { if (video && video.isConnected) return video; video = document.querySelector('video'); if (video) { video.addEventListener('ended', () => post({ type: 'ended' })); video.addEventListener('play', () => post({ type: 'playing', playing: true })); video.addEventListener('pause', () => { post({ type: 'playing', playing: false }); lastPauseAt = Date.now(); // 平台打断的暂停 1.5 秒后自动恢复;用户自己点的暂停给 15 秒缓冲 const byUser = lastTrustedAt && lastPauseAt - lastTrustedAt < 3000; setTimeout(() => resumeIfPaused(byUser ? '用户暂停后自动恢复' : '暂停后自动恢复'), byUser ? 15000 : 1500); }); video.addEventListener('loadeddata', () => setTimeout(() => resumeIfPaused('视频加载完成'), 800)); video.addEventListener('canplay', () => { if (video.paused && !video.ended) setTimeout(() => resumeIfPaused('可以播放'), 1000); }); } return video; } function applyMute() { const v = findVideo(); if (!v) return; v.muted = muted; v.volume = muted ? 0 : 1; } // 暂停/被平台打断时自动恢复:先调 video.play(),被拒绝再模拟点击播放按钮 function resumeIfPaused(reason) { const v = findVideo(); if (!v || v.ended || !v.paused || !autoResume) return; if (quizOpen || findQuizContainer(document)) return; const now = Date.now(); if (now - lastResumeTry < 1500) return; lastResumeTry = now; applyMute(); try { const p = v.play(); if (p && p.catch) p.catch(() => setTimeout(clickPlayUI, 300)); } catch (e) { setTimeout(clickPlayUI, 300); } setTimeout(() => { if (v.paused && !v.ended && autoResume) clickPlayUI(); }, 900); if (now - lastResumeLogAt > 10000) { lastResumeLogAt = now; post({ type: 'log', text: '播放器内自动恢复播放' + (reason ? '(' + reason + ')' : '') }); } } function clickPlayUI() { const v = findVideo(); if (!v || !v.paused) return; const sels = ['.vjs-big-play-button', '.vjs-play-control', '[class*="play-btn"]', '[class*="playBtn"]', '[class*="big-play"]']; for (const s of sels) { let el = null; try { el = document.querySelector(s); } catch (e) {} if (el && visible(el)) { try { el.click(); } catch (e) {} return; } } // 兜底:点击视频本体(Video.js 在暂停状态下会切换为播放) try { v.click(); } catch (e) {} } function scanQuiz() { if (!document.body) return; const container = findQuizContainer(document); if (container) { if (!quizOpen) { quizOpen = true; post({ type: 'quiz', status: 'open', text: (container.innerText || '').slice(0, 500) }); } quizState.onManual = text => post({ type: 'quiz', status: 'manual', text: text.slice(0, 500) }); solveQuiz(container, msg => { console.log('[公需课助手]', msg); post({ type: 'log', text: msg }); }, quizState); } else if (quizOpen) { quizOpen = false; quizState = { lastKey: '', lastAt: 0 }; post({ type: 'quiz', status: 'closed' }); } } function loop() { const v = findVideo(); applyMute(); if (v) { const now = Date.now(); if (now - lastPost > 900) { lastPost = now; post({ type: 'time', cur: v.currentTime || 0, dur: isFinite(v.duration) ? v.duration : 0, paused: v.paused, ended: v.ended }); } // 巡检:新页面起播被浏览器拦截、平台打断、用户长时间忘记恢复,都会自动续播 if (autoResume && v.paused && !v.ended && v.readyState >= 2) { const pausedFor = lastPauseAt ? now - lastPauseAt : Infinity; const byUser = lastPauseAt && lastTrustedAt && lastPauseAt - lastTrustedAt < 3000; if (pausedFor > (byUser ? 15000 : 2500)) resumeIfPaused('巡检'); } // 播放/恢复统一交给顶层通过 SDK 调用,避免绕过 SDK 导致平台不计学时 } scanQuiz(); } try { new MutationObserver(() => scanQuiz()).observe(document.documentElement, { childList: true, subtree: true }); } catch (e) {} window.addEventListener('message', e => { const d = e.data; if (!d || d.__hnu2026 !== true) return; if (d.type === 'set-muted') { muted = !!d.muted; applyMute(); } else if (d.type === 'set-conf') { autoResume = d.autoResume !== false; if (typeof d.muted === 'boolean') muted = d.muted; applyMute(); } else if (d.type === 'resume') { lastPauseAt = 0; resumeIfPaused(d.reason || '顶层请求'); } }); setInterval(loop, 1000); loop(); post({ type: 'ready' }); } /* ============================================================ * 顶层平台页逻辑 * ============================================================ */ if (window.top !== window) return; if (window[TAG]) return; // 只在具体任务播放页运行;课程目录页不显示面板 if (!/\/task\/\d+\/show/.test(location.pathname)) return; window[TAG] = true; const CFG = { autoPlay: true, autoNext: true, mute: true, autoAnswer: true, autoResume: true, keepAlive: true, tickMs: 1000, nextDelayMs: 5000 }; const S = { iframe: null, player: null, actDoc: null, cur: 0, dur: 0, lastCur: -1, lastProgressAt: 0, lastPlayTry: 0, quizOpen: false, manualQuiz: false, quizState: null, nextScheduled: false, navigated: false, finishAt: 0, logs: [], lastLogUI: 0, playerTimeAt: 0, playerDur: 0, playerPaused: null, nonVideo: false, nonVideoLogged: false, attachAt: 0, lastWakeAt: 0, maskSig: '', lastMaskAt: 0, lastMaskLogAt: 0 }; function log(msg) { const line = '[' + new Date().toLocaleTimeString() + '] ' + msg; S.logs.push(line); if (S.logs.length > 200) S.logs.shift(); console.log('[公需课助手]', msg); updateUI(true); } function $(sel) { return document.querySelector(sel); } function $$(sel) { return Array.from(document.querySelectorAll(sel)); } function getTaskId() { const m = location.href.match(/\/task\/(\d+)\//); return m ? m[1] : ''; } function getCourseId() { const m = location.href.match(/\/course\/(\d+)\//); return m ? m[1] : ''; } function getRemainSec() { const el = $('.js-remain-time'); if (el) { const txt = el.innerText || ''; const m = txt.match(/(\d+)\s*分(?:钟)?/); const s = txt.match(/(\d+)\s*秒/); if (m || s) return (m ? +m[1] * 60 : 0) + (s ? +s[1] : 0); } const ifr = $('#task-content-iframe'); if (ifr) { const mins = Number(ifr.getAttribute('data-finish-detail') || 0); if (mins > 0) return Math.max(0, mins * 60 - S.cur); } return null; } function finishTipsVisible() { const el = $('.js-finish-tips'); if (!el) return false; const st = getComputedStyle(el); return st.display !== 'none' && (el.innerText || '').includes('完成'); } function patchVisibility(win, doc) { if (!win || !doc || win.__hnu_vis__) return; win.__hnu_vis__ = true; try { ['hidden', 'webkitHidden', 'mozHidden', 'msHidden'].forEach(p => { if (p in doc) Object.defineProperty(doc, p, { configurable: true, get: () => false }); }); ['visibilityState', 'webkitVisibilityState', 'mozVisibilityState', 'msVisibilityState'].forEach(p => { if (p in doc) Object.defineProperty(doc, p, { configurable: true, get: () => 'visible' }); }); } catch (e) {} try { win.hasFocus = () => true; } catch (e) {} try { ['visibilitychange', 'webkitvisibilitychange', 'blur'].forEach(evt => { (evt === 'blur' ? win : doc).addEventListener(evt, e => e.stopImmediatePropagation(), true); }); } catch (e) {} if (!win.__hnu_move_timer__) { win.__hnu_move_timer__ = setInterval(() => { try { doc.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 1, clientY: 1, movementX: 1, movementY: 0 })); } catch (e) {} }, 15000); } } const SILENT_WAV = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAACAgICA'; function unlockKeepAlive() { try { const a = window.__hnu_audio__; if (a && a.paused) a.play().catch(() => {}); } catch (e) {} try { const c = window.__hnu_ctx__; if (c && c.state === 'suspended') c.resume().catch(() => {}); } catch (e) {} } function startKeepAlive() { if (!CFG.keepAlive) return; try { if (!window.__hnu_audio__) { const a = document.createElement('audio'); a.loop = true; a.volume = 0.0005; a.src = SILENT_WAV; window.__hnu_audio__ = a; a.play().catch(() => {}); } } catch (e) {} try { const AC = window.AudioContext || window.webkitAudioContext; if (AC && !window.__hnu_ctx__) { const ctx = new AC(); const osc = ctx.createOscillator(); const g = ctx.createGain(); g.gain.value = 0.0005; osc.frequency.value = 440; osc.connect(g); g.connect(ctx.destination); osc.start(); window.__hnu_ctx__ = ctx; } } catch (e) {} if (!window.__hnu_worker__) { try { const blob = new Blob(['setInterval(function(){postMessage(1)},20000)'], { type: 'text/javascript' }); const wk = new Worker(URL.createObjectURL(blob)); window.__hnu_worker__ = wk; wk.onmessage = () => { pumpKeepAlive(); try { document.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: 1, clientY: 1 })); } catch (e) {} if (CFG.autoResume) { checkMasks(); if (S.player && CFG.autoPlay && !S.quizOpen) { const t = Date.now(); if (t - S.lastProgressAt > 20000) tryPlay(); } } }; } catch (e) {} } // 浏览器自动播放策略要求用户手势后才能播放静音保活音频 ['pointerdown', 'click', 'keydown', 'touchstart'].forEach(evt => { try { document.addEventListener(evt, unlockKeepAlive, true); } catch (e) {} }); } function pumpKeepAlive() { try { const c = window.__hnu_ctx__; if (c && c.state === 'suspended') c.resume().catch(() => {}); } catch (e) {} try { const a = window.__hnu_audio__; if (a && a.paused) a.play().catch(() => {}); } catch (e) {} try { const w = getActivityWindow(); if (w && w !== window) { const c = w.__hnu_ctx__; if (c && c.state === 'suspended') c.resume().catch(() => {}); const a = w.__hnu_audio__; if (a && a.paused) a.play().catch(() => {}); } } catch (e) {} } function getActivityIframe() { return document.getElementById('task-content-iframe') || document.querySelector('.task-content-iframe'); } function getActivityWindow() { const ifr = getActivityIframe(); try { return ifr ? ifr.contentWindow : null; } catch (e) { return null; } } function attachPlayer() { const ifr = getActivityIframe(); if (!ifr) return; let w = null; try { w = ifr.contentWindow; } catch (e) { return; } if (!w) return; S.iframe = ifr; const ttype = ifr.getAttribute('data-task-type') || ''; if (ttype && !/video|audio/i.test(ttype) && !S.nonVideoLogged) { S.nonVideoLogged = true; S.nonVideo = true; log('当前任务类型为 ' + ttype + ',不是视频,请手动完成'); } if (!w.__hnu_patched__) { w.__hnu_patched__ = true; patchVisibility(w, w.document); try { startKeepAliveIn(w); } catch (e) {} } // 监听活动 iframe 里的题目 if (w.document && S.actDoc !== w.document) { S.actDoc = w.document; try { new MutationObserver(() => scanDoc(w.document, 'activity')).observe(w.document.documentElement, { childList: true, subtree: true }); } catch (e) {} } const p = w.player; if (p && p !== S.player) { S.player = p; S.attachAt = Date.now(); setTimeout(sendPlayerConf, 600); try { if (typeof p.on === 'function') { p.on('ended', () => onEnded('player')); p.on('answered', d => log('平台记录答题:' + JSON.stringify(d).slice(0, 80))); } } catch (e) {} log('已连接播放器'); // 关键:平台的学习计时器要收到一次 playing 事件才开始累计。 // 云播放器自动播放时可能早于计时器绑定,导致视频在播但学时不动。 // 这里用 SDK 做一次“暂停→播放”,让计时器重新收到 playing。 setTimeout(() => { if (S.player !== p) return; try { p.pause(); } catch (e) {} setTimeout(() => { if (S.player !== p) return; try { p.play(); } catch (e) {} }, 400); }, 1800); } } function startKeepAliveIn(win) { // 活动 iframe 内也放一份静音音频,避免后台节流 if (!CFG.keepAlive || win.__hnu_audio__) return; try { const a = win.document.createElement('audio'); a.loop = true; a.volume = 0.0005; a.src = SILENT_WAV; win.__hnu_audio__ = a; a.play().catch(() => {}); } catch (e) {} } function isPlayerPaused() { // 顶层拿不到 video,只能看播放器时间是否推进 if (!S.player) return false; if (!S.lastProgressAt) { // 新页面刚连上播放器:5 秒还没起播就视为需要自动恢复 return Date.now() - (S.attachAt || Date.now()) > 5000; } return Date.now() - S.lastProgressAt > 4000; } function tryPlay() { if (!S.player || S.quizOpen) return; const t = Date.now(); if (t - S.lastPlayTry < 2500) return; S.lastPlayTry = t; try { const r = S.player.play(); if (r && r.catch) r.catch(e => log('播放失败:' + e.message)); } catch (e) { log('播放异常:' + e.message); } } function applyMute() { if (!S.player || typeof S.player.setVolume !== 'function') return; try { S.player.setVolume(CFG.mute ? 0 : 1); } catch (e) {} const ifr = getActivityIframe(); try { const pw = ifr && ifr.contentDocument && ifr.contentDocument.querySelector('iframe'); if (pw) pw.contentWindow.postMessage({ __hnu2026: true, type: 'set-muted', muted: CFG.mute }, '*'); } catch (e) {} } function onEnded(from) { const now = Date.now(); if (now - S.finishAt < 3000) return; S.finishAt = now; const remain = getRemainSec(); log('视频结束(' + from + '),剩余 ' + (remain === null ? '未知' : remain + ' 秒')); if (remain === null && !finishTipsVisible()) { // 页面没给剩余时间,按视频自然结束处理,交给下一页 log('未读到剩余时间,按任务完成处理'); scheduleNext(3000); return; } if (remain !== null && remain > 0) { // 没看够,重播 log('学习时长未满,从头重播继续计时'); try { if (S.player && typeof S.player.setCurrentTime === 'function') S.player.setCurrentTime(0); if (S.player && typeof S.player.play === 'function') S.player.play(); } catch (e) {} return; } scheduleNext(3000); } function scheduleNext(delay) { if (S.nextScheduled || S.navigated) return; if (!CFG.autoNext) { log('学习已完成,但连播已关闭'); return; } S.nextScheduled = true; log('准备切换下一节…'); setTimeout(goNext, delay); } function goNext(force) { if (S.navigated) return; const btn = $('.js-next-mobile-btn'); const url = btn && (btn.getAttribute('href') || btn.getAttribute('data-url')); if (force && url && url !== '#' && !/^javascript:/i.test(url)) { S.navigated = true; log('手动跳转:' + url); location.href = url.startsWith('http') ? url : location.origin + url; return; } // 优先问服务端要“已解锁的下一节”,避免直接点按钮跳到未解锁页 fetchNextUrl(0); } function fetchNextUrl(retry) { retry = retry || 0; const tid = getTaskId(); if (!tid) { log('未取到任务 ID'); return; } fetch('/course/next_task_url/' + tid, { credentials: 'include' }) .then(r => r.text()) .then(u => { u = (u || '').trim().replace(/^"|"$/g, ''); if (u && /^(https?:\/\/|\/)/.test(u)) { log('接口返回下一节:' + u); location.href = u; } else if (retry < 5) { log('下一节还没解锁,3 秒后重试(' + (retry + 1) + '/5)'); setTimeout(() => fetchNextUrl(retry + 1), 3000); } else { const btn = $('.js-next-mobile-btn'); const u2 = btn && (btn.getAttribute('href') || btn.getAttribute('data-url')); if (u2 && u2 !== '#' && !/^javascript:/i.test(u2) && !btn.classList.contains('disabled')) { log('接口未返回,使用页面下一节按钮:' + u2); location.href = u2.startsWith('http') ? u2 : location.origin + u2; return; } const fallback = '/my/course/' + (getCourseId() || ''); log('没有下一节,返回课程页'); location.href = fallback; } }) .catch(e => { if (retry < 3) setTimeout(() => fetchNextUrl(retry + 1), 3000); else log('获取下一节失败:' + e.message); }); } // 扫描某个文档里的验证题 function scanDoc(doc, ctx) { if (!doc || !doc.body) return; if (!CFG.autoAnswer) return; const container = findQuizContainer(doc); if (container) { if (!S.quizOpen) { S.quizOpen = true; log('检测到弹题(' + ctx + '),尝试自动作答'); } if (!S.quizState) S.quizState = { lastKey: '', lastAt: 0 }; S.quizState.onManual = text => { S.manualQuiz = true; log('❗ 不是计算题,请手动作答:' + text.slice(0, 120).replace(/\s+/g, ' ')); }; solveQuiz(container, log, S.quizState); } else if (S.quizOpen) { S.quizOpen = false; S.manualQuiz = false; S.quizState = { lastKey: '', lastAt: 0 }; log('弹题已关闭,恢复播放'); setTimeout(tryPlay, 1000); } } /* ---------- 平台暂停/多开提示自动处理 ---------- */ const PROMPT_GUARD_KEY = 'hnu2026_prompt_guard'; function readPromptGuard() { try { return JSON.parse(localStorage.getItem(PROMPT_GUARD_KEY) || 'null') || {}; } catch (e) { return {}; } } function promptGuardState() { const now = Date.now(); const g = readPromptGuard(); return { now: now, last: Number(g.last) || 0, times: (Array.isArray(g.times) ? g.times : []).filter(t => now - t < 10 * 60 * 1000) }; } function notePromptClick() { const st = promptGuardState(); st.times.push(st.now); try { localStorage.setItem(PROMPT_GUARD_KEY, JSON.stringify({ task: getTaskId(), times: st.times.slice(-20), last: st.now })); } catch (e) {} } function promptClickAllowed() { const st = promptGuardState(); if (st.now - st.last < 90 * 1000) { return { ok: false, why: '刚刚处理过暂停提示(' + Math.round((st.now - st.last) / 1000) + ' 秒前),先等页面自行恢复' }; } if (st.times.length >= 3) { return { ok: false, why: '10 分钟内已自动处理 ' + st.times.length + ' 次暂停提示,疑似同一账号多开/多设备学习;已停止自动刷新以免循环,请只保留一个学习页签' }; } return { ok: true }; } function findPromptContainers(doc) { const out = []; if (!doc || !doc.body) return out; try { doc.querySelectorAll('.out-focue-mask, [class*="out-focue"]').forEach(el => { if (visible(el)) out.push(el); }); } catch (e) {} if (out.length) return out; // 通用弹窗:只认明确提到“暂停/多开/计时”的对话框,避免误点完成提示 const sels = ['.modal.in', '.modal.show', '[role="dialog"]', '.swal2-popup', '.layui-layer', '.el-dialog', '.ant-modal']; for (const sel of sels) { let list = []; try { list = doc.querySelectorAll(sel); } catch (e) { continue; } for (const el of list) { if (!visible(el)) continue; const t = el.innerText || ''; if (!/暂停|多开|一心多用|计时错误|学习中断|离开学习|继续观看/.test(t)) continue; if (/完成|恭喜|退出学习|结束学习/.test(t)) continue; out.push(el); } if (out.length) break; } return out; } const CONTINUE_TEXT = /^(继续学习|继续播放|继续观看|继续|重新加载|刷新页面|我知道了|知道了|确定|好的|开始学习)$/; function clickContinueButton(mask) { const strong = ['.js-continue-studying', '.js-network-continue-studying']; for (const s of strong) { let b = null; try { b = mask.querySelector(s); } catch (e) {} if (b && visible(b)) { try { b.click(); return true; } catch (e) {} } } let btns = []; try { btns = Array.from(mask.querySelectorAll('button, a, [role="button"], .btn')).filter(visible); } catch (e) {} for (const b of btns) { const t = (b.innerText || b.textContent || '').trim().replace(/\s+/g, ''); if (!t || t.length > 12) continue; if (CONTINUE_TEXT.test(t)) { try { b.click(); return true; } catch (e) {} } } return false; } // 扫描顶层和活动页 iframe 里的暂停提示;返回 true 表示存在遮罩(此时不要盲目 tryPlay) function checkMasks() { if (!CFG.autoResume) return false; const docs = [{ name: 'activity', doc: S.actDoc }, { name: 'top', doc: document }]; for (const item of docs) { if (!item.doc) continue; const masks = findPromptContainers(item.doc); if (!masks.length) continue; const mask = masks[0]; const text = (mask.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 80); const sig = item.name + '|' + text; const now = Date.now(); if (sig !== S.maskSig || now - S.lastMaskAt > 30000) { S.maskSig = sig; S.lastMaskAt = now; log('检测到平台提示:' + (text || '暂停遮罩')); } const allowed = promptClickAllowed(); if (!allowed.ok) { if (now - S.lastMaskLogAt > 30000) { S.lastMaskLogAt = now; log('⚠ ' + allowed.why); } return true; } if (clickContinueButton(mask)) { notePromptClick(); S.lastMaskLogAt = 0; log('✅ 已自动点击「继续学习」,页面会刷新并从上次进度继续'); setTimeout(() => resumePlayback('遮罩已处理'), 1500); } else { log('⚠ 检测到暂停提示,但没找到「继续学习」按钮,请在页面上手动点击'); } return true; } return false; } function postToPlayer(obj) { try { const ifr = getActivityIframe(); const inner = ifr && ifr.contentDocument && ifr.contentDocument.querySelector('iframe'); if (inner && inner.contentWindow) { inner.contentWindow.postMessage(Object.assign({ __hnu2026: true, from: 'top' }, obj), '*'); } } catch (e) {} } function sendPlayerConf() { postToPlayer({ type: 'set-conf', autoResume: CFG.autoResume, muted: CFG.mute }); } function resumePlayback(reason) { if (!CFG.autoResume || S.nonVideo || S.quizOpen) return; if (checkMasks()) return; if (S.player) tryPlay(); postToPlayer({ type: 'resume', reason: reason || '' }); } // 读取真实页面可见性:patchVisibility 把 document.visibilityState 改成了常量 function isRealHidden() { try { if (Object.prototype.hasOwnProperty.call(document, 'visibilityState')) { delete document.visibilityState; const v = document.visibilityState; Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' }); return v === 'hidden' || v === 'prerender'; } return document.visibilityState === 'hidden'; } catch (e) { return false; } } let wakeTimer = 0; function onWake(source) { if (isRealHidden()) return; // 真的是切到后台:视频继续播放即可 if (wakeTimer) return; wakeTimer = setTimeout(() => { wakeTimer = 0; sendPlayerConf(); if (!CFG.autoResume) return; attachPlayer(); if (checkMasks()) return; if (S.player) tryPlay(); postToPlayer({ type: 'resume', reason: 'wake:' + source }); }, 400); } function installWakeListeners() { try { document.addEventListener('visibilitychange', () => onWake('visibilitychange'), true); document.addEventListener('webkitvisibilitychange', () => onWake('webkitvisibilitychange'), true); window.addEventListener('focus', () => onWake('focus'), true); window.addEventListener('pageshow', e => { if (e.persisted) onWake('pageshow'); }, true); } catch (e) {} } function tick() { attachPlayer(); if (!S.iframe) return; patchVisibility(window, document); patchVisibility(getActivityWindow(), S.actDoc); pumpKeepAlive(); const maskFound = checkMasks(); let cur = S.cur; try { if (S.player && typeof S.player.getCurrentTime === 'function') cur = Number(S.player.getCurrentTime()) || 0; } catch (e) {} if (cur > S.lastCur + 0.3) { S.lastProgressAt = Date.now(); S.lastCur = cur; } S.cur = cur; if (!S.dur && S.playerDur) S.dur = S.playerDur; const remain = getRemainSec(); if (S.nonVideo) { updateUI(); return; } if (remain !== null && remain <= 0) { if (!S.nextScheduled) { log('学习时长达标(剩余 0)'); scheduleNext(CFG.nextDelayMs); } } else if (finishTipsVisible()) { if (!S.nextScheduled) { log('页面提示任务完成'); scheduleNext(CFG.nextDelayMs); } } else if (CFG.autoPlay && CFG.autoResume && S.player && !S.quizOpen && !maskFound) { if (isPlayerPaused()) tryPlay(); } applyMute(); updateUI(); scanDoc(document, 'top'); if (S.actDoc) scanDoc(S.actDoc, 'activity'); } /* ======================= UI ======================= */ function createUI() { if (document.getElementById('hnu2026-ui')) return; const card = document.createElement('div'); card.id = 'hnu2026-ui'; card.style.cssText = [ 'position:fixed', 'top:64px', 'right:18px', 'z-index:2147483647', 'background:rgba(255,255,255,.94)', 'backdrop-filter:blur(10px)', 'border:1px solid rgba(0,0,0,.10)', 'border-radius:14px', 'padding:10px 12px', 'font:12px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif', 'color:#222', 'box-shadow:0 8px 28px rgba(0,0,0,.16)', 'min-width:250px', 'max-width:330px' ].join(';'); card.innerHTML = '
' + '' + '2026公需课助手' + 'v1.1.1' + '
' + '
初始化…
' + '
' + '' + '' + '' + '' + '' + '' + '
' + ''; document.body.appendChild(card); card.querySelectorAll('button').forEach(b => { b.style.cssText = 'border:1px solid rgba(0,0,0,.14);background:#f3f4f6;border-radius:9px;padding:4px 9px;font-size:11px;cursor:pointer;color:#222;'; b.addEventListener('click', () => { const a = b.getAttribute('data-a'); if (a === 'play') { tryPlay(); log('手动播放'); } else if (a === 'mute') { CFG.mute = !CFG.mute; b.textContent = '静音:' + (CFG.mute ? '开' : '关'); applyMute(); sendPlayerConf(); } else if (a === 'autoresume') { CFG.autoResume = !CFG.autoResume; b.textContent = '防暂停:' + (CFG.autoResume ? '开' : '关'); log(CFG.autoResume ? '防暂停已开启:暂停/平台提示会自动恢复' : '防暂停已关闭:暂停后不再自动恢复'); sendPlayerConf(); } else if (a === 'nextauto') { CFG.autoNext = !CFG.autoNext; b.textContent = '连播:' + (CFG.autoNext ? '开' : '关'); log(CFG.autoNext ? '自动连播已开启' : '自动连播已关闭(本节看完会停住)'); } else if (a === 'next') { S.nextScheduled = false; S.navigated = false; goNext(true); } else if (a === 'log') { const el = document.getElementById('hnu2026-log'); el.style.display = el.style.display === 'none' ? 'block' : 'none'; updateUI(true); } }); }); } function fmt(sec) { sec = Math.max(0, Math.round(sec)); const m = Math.floor(sec / 60), s = sec % 60; return m + ':' + String(s).padStart(2, '0'); } function updateUI(force) { const now = Date.now(); if (!force && now - S.lastLogUI < 900) return; S.lastLogUI = now; const dot = document.getElementById('hnu2026-dot'); const st = document.getElementById('hnu2026-status'); if (!dot || !st) return; const remain = getRemainSec(); const hasPlayer = !!S.player; if (S.manualQuiz) { dot.style.background = '#ef4444'; st.innerHTML = '需要人工作答:非计算题'; } else if (S.quizOpen) { dot.style.background = '#f59e0b'; st.textContent = '正在自动答题…'; } else if (remain !== null && remain <= 0) { dot.style.background = '#10b981'; st.textContent = '本节已完成,准备下一节'; } else if (!hasPlayer) { dot.style.background = '#f59e0b'; st.textContent = '正在连接播放器…'; } else { dot.style.background = isPlayerPaused() ? '#f59e0b' : '#3b82f6'; st.textContent = (isPlayerPaused() ? '已暂停' : '播放中') + ' ' + fmt(S.cur) + (S.dur ? ' / ' + fmt(S.dur) : '') + (remain === null ? '' : ' · 距完成 ' + fmt(remain)); } const logEl = document.getElementById('hnu2026-log'); if (logEl && logEl.style.display !== 'none') { logEl.textContent = S.logs.slice(-40).join('\n'); logEl.scrollTop = logEl.scrollHeight; } } /* ======================= 消息与启动 ======================= */ window.addEventListener('message', e => { const d = e.data; if (!d || d.__hnu2026 !== true) return; if (d.type === 'quiz') { if (d.status === 'open') { S.quizOpen = true; log('播放器内检测到弹题'); } else if (d.status === 'closed') { S.quizOpen = false; S.manualQuiz = false; log('播放器内弹题已关闭'); setTimeout(tryPlay, 1200); } else if (d.status === 'manual') { S.quizOpen = true; S.manualQuiz = true; log('❗ 播放器内不是计算题,需要人工作答'); } } else if (d.type === 'ready') { setTimeout(sendPlayerConf, 500); } else if (d.type === 'playing') { S.playerPaused = !d.playing; if (d.playing === false) { // 播放器被暂停:先把配置同步过去,再在 1.8 秒后兜底恢复 setTimeout(() => resumePlayback('播放器暂停'), 1800); } } else if (d.type === 'time') { S.playerTimeAt = Date.now(); if (d.cur > S.lastCur + 0.3) { S.lastProgressAt = Date.now(); S.lastCur = d.cur; } if (d.cur) S.cur = d.cur; if (d.dur) S.dur = d.dur; } else if (d.type === 'ended') { onEnded('player-frame'); } else if (d.type === 'log') { log(d.text); } }); // 兼容用 window.prompt 弹出的算术验证 try { const nativePrompt = window.prompt; window.prompt = function (msg, def) { const m = extractMath(msg || ''); if (m) { const a = (m.value !== undefined && m.value !== null) ? m.value : evalMath(m.expr); if (a !== null) { log('自动回答 prompt:' + m.expr + ' = ' + a); return String(a); } } return nativePrompt.call(window, msg, def); }; } catch (e) {} function boot() { // 先注册唤醒监听,再 patch 可见性(后者会 stopImmediatePropagation) installWakeListeners(); patchVisibility(window, document); startKeepAlive(); setInterval(tick, CFG.tickMs); const startUI = () => { createUI(); const tid = getTaskId(); log('启动 v1.1.1,任务 ' + (tid || '未知') + ':自动播放/连播/防暂停已开启'); // 顶层 DOM 变化时也扫一下 try { new MutationObserver(() => { if (CFG.autoAnswer) scanDoc(document, 'top'); }) .observe(document.documentElement, { childList: true, subtree: true }); } catch (e) {} }; if (document.body) startUI(); else document.addEventListener('DOMContentLoaded', startUI, { once: true }); // 页面可能在任务间 SPA 切换;切换后立即重连并起播 let lastUrl = location.href; setInterval(() => { if (location.href !== lastUrl) { lastUrl = location.href; log('页面切换,重新连接播放器'); S.player = null; S.playerObj = null; S.iframe = null; S.actDoc = null; S.lastCur = -1; S.cur = 0; S.dur = 0; S.attachAt = 0; S.playerPaused = null; S.maskSig = ''; S.lastMaskAt = 0; S.nextScheduled = false; S.navigated = false; S.quizOpen = false; S.manualQuiz = false; S.quizState = null; setTimeout(() => { attachPlayer(); sendPlayerConf(); if (CFG.autoResume && !checkMasks()) { if (S.player) tryPlay(); postToPlayer({ type: 'resume', reason: 'new-url' }); } }, 800); } }, 1500); } boot(); })();