// ==UserScript==
// @name 雨课堂刷课助手
// @namespace http://tampermonkey.net/
// @version 3.1.3
// @description 针对雨课堂视频进行自动播放,配置AI自动答题
// @author 风之子
// @license GPL3
// @match *://*.yuketang.cn/*
// @match *://*.gdufemooc.cn/*
// @run-at document-start
// @icon http://yuketang.cn/favicon.ico
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @connect api.openai.com
// @connect api.moonshot.cn
// @connect api.deepseek.com
// @connect dashscope.aliyuncs.com
// @connect api.anthropic.com
// @connect *
// @connect cdn.jsdelivr.net
// @connect unpkg.com
// @require https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
// @require https://unpkg.com/tesseract.js@v2.1.0/dist/tesseract.min.js
// ==/UserScript==
(() => {
'use strict';
let panel; // UI 面板实例后置初始化
// ---- 脚本配置,用户可修改 ----
const Config = {
version: '3.1.3', // 版本号
playbackRate: 2, // 视频播放倍速
pptInterval: 3000, // ppt翻页间隔
storageKeys: { // 使用者勿动
progress: '[雨课堂脚本]刷课进度信息',
ai: 'ykt_ai_conf',
proClassCount: 'pro_lms_classCount',
feature: 'ykt_feature_conf', // 是否开启AI作答/自动评论
rate: 'ykt_rate_conf', // 视频倍速配置:目标倍速与各解锁限制修改点开关
flow: 'ykt_flow_conf', // 刷课流程配置:自动切换任务点/界面、停止后还原修改
pendingAutoStart: 'ykt_pending_auto_start',
userStopped: 'ykt_user_stopped' // 用户已点击停止刷课(持久化,防止重新加载后自动恢复)
}
};
const Utils = {
// 短暂睡眠,等待网页加载
sleep: (ms = 1000) => new Promise(resolve => setTimeout(resolve, ms)),
// 模拟一次带间隔的鼠标点击:按下/抬起/点击错开几十毫秒,降低连续合成动作触发风控的概率
async humanClick(element) {
if (!element) return;
const view = element.ownerDocument?.defaultView || window;
const mouse = type => element.dispatchEvent(new view.MouseEvent(type, { bubbles: true, cancelable: true, view }));
mouse('mousedown');
await this.sleep(40 + Math.random() * 60);
mouse('mouseup');
await this.sleep(40 + Math.random() * 80);
element.click();
},
// 将一个 JSON 字符串解析为 JavaScript 对象
safeJSONParse(value, fallback) {
try {
return JSON.parse(value);
} catch (_) {
return fallback;
}
},
// 每隔一段时间检查某个条件是否满足(通过 checker 函数),如果满足就成功返回;如果超时仍未满足,就失败返回
poll(checker, { interval = 1000, timeout = 20000 } = {}) {
return new Promise(resolve => {
const start = Date.now();
const timer = setInterval(() => {
// 停止刷课后立即中止所有轮询,让流程尽快收尾
if (Session.isStopped()) {
clearInterval(timer);
resolve(false);
return;
}
if (checker()) {
clearInterval(timer);
resolve(true);
return;
}
if (Date.now() - start > timeout) {
clearInterval(timer);
resolve(false);
}
}, interval);
});
},
// 使用UI课程完成度来判别是否完成课程
isProgressDone(text) {
if (!text) return false;
return text.includes('100%') || text.includes('99%') || text.includes('98%') || text.includes('已完成');
},
getCurrentClassroomId() {
const query = new URLSearchParams(location.search);
const queryId = query.get('classroom_id');
if (queryId) return queryId;
const path = location.pathname;
return path.match(/^\/ai-workspace\/lms-graph\/([^/]+)/)?.[1]
|| path.match(/^\/v2\/web\/studentLog\/([^/]+)/)?.[1]
|| path.match(/\/(\d+)\/studycontent$/)?.[1]
|| '';
},
returnUrl() { // 得到课程开始的url
if (location.pathname.includes('/v2/web/studentLog/') || location.pathname.includes('pro/lms/')) {
return location.href
}
return ""
},
isSupportedLearningPage() {
const path = location.pathname;
return path.includes('/ai-workspace/lms-graph/')
|| path.includes('/v2/web/')
|| path.includes('/pro/lms/');
},
waitForMountTarget(timeout = 15000) {
const getTarget = () => document.body || document.documentElement;
const existing = getTarget();
if (existing) return Promise.resolve(existing);
return new Promise(resolve => {
let done = false;
const finish = () => {
if (done) return;
done = true;
observer.disconnect();
clearTimeout(timer);
resolve(getTarget());
};
const observer = new MutationObserver(() => {
if (getTarget()) finish();
});
observer.observe(document, { childList: true, subtree: true });
document.addEventListener('DOMContentLoaded', finish, { once: true });
window.addEventListener('load', finish, { once: true });
const timer = setTimeout(finish, timeout);
});
},
async getDDL() {
const element = document.querySelector('video') || document.querySelector('audio');
const fallback = 180_000;
if (!element) return fallback;
let duration = Number(element.duration);
if (!Number.isFinite(duration) || duration <= 0) {
await new Promise(resolve => element.addEventListener('loadedmetadata', resolve, { once: true }));
duration = Number(element.duration);
}
const elementDurationMs = duration * 1000; // 转为秒
const timeout = Math.max(elementDurationMs * 3, 10_000); // 至少 10 秒(防极短视频);
return timeout;
},
// 关闭雨课堂的挂机/离开检测弹窗,避免遮罩拦截刷课流程
dismissPopups() {
const wrappers = document.querySelectorAll('.el-dialog__wrapper, .el-message-box__wrapper');
for (const wrapper of wrappers) {
const style = getComputedStyle(wrapper);
const rect = wrapper.getBoundingClientRect();
if (style.display === 'none' || style.visibility === 'hidden' || rect.width === 0) continue;
const text = wrapper.innerText || '';
const buttons = [...wrapper.querySelectorAll('button')];
const clickBtn = label => {
const btn = buttons.find(b => (b.innerText || '').trim().includes(label));
if (btn) btn.click();
};
if (text.includes('好好学习') || text.includes('继续观看')) {
clickBtn('继续观看');
} else if (text.includes('报告老师')) {
clickBtn('取消');
}
}
}
};
// ---- 存储工具 ----
const Store = {
getProgress(url) {
const raw = localStorage.getItem(Config.storageKeys.progress);
const all = Utils.safeJSONParse(raw, {}) || { url: { outside: 0, inside: 0 } };
if (!all[url]) {
all[url] = { outside: 0, inside: 0 };
localStorage.setItem(Config.storageKeys.progress, JSON.stringify(all));
}
return { all, current: all[url] };
},
setProgress(url, outside, inside = 0) {
const raw = localStorage.getItem(Config.storageKeys.progress);
const all = Utils.safeJSONParse(raw, {});
all[url] = { outside, inside };
localStorage.setItem(Config.storageKeys.progress, JSON.stringify(all));
},
removeProgress(url) {
const raw = localStorage.getItem(Config.storageKeys.progress);
const all = Utils.safeJSONParse(raw, {});
delete all[url];
localStorage.setItem(Config.storageKeys.progress, JSON.stringify(all));
},
getAIConf() {
const raw = localStorage.getItem(Config.storageKeys.ai);
const saved = Utils.safeJSONParse(raw, {}) || {};
const conf = {
url: saved.url ?? "https://api.deepseek.com/chat/completions",
key: saved.key ?? "sk-xxxxxxx",
model: saved.model ?? "deepseek-chat",
apiFormat: saved.apiFormat ?? "openai", // openai 或 anthropic
authMethod: saved.authMethod ?? "bearer", // bearer 或 x-api-key
};
localStorage.setItem(Config.storageKeys.ai, JSON.stringify(conf));
return conf;
},
setAIConf(conf) {
localStorage.setItem(Config.storageKeys.ai, JSON.stringify(conf));
},
getProClassCount() {
const value = localStorage.getItem(Config.storageKeys.proClassCount);
return value ? Number(value) : 1;
},
setProClassCount(count) {
localStorage.setItem(Config.storageKeys.proClassCount, count);
},
getFeatureConf() {
const raw = localStorage.getItem(Config.storageKeys.feature);
const saved = Utils.safeJSONParse(raw, {}) || {};
const conf = {
autoAI: saved.autoAI ?? false,
autoComment: saved.autoComment ?? false,
useOCR: saved.useOCR ?? true, // 是否启用 OCR 识题(关闭后截图直传多模态模型)
};
localStorage.setItem(Config.storageKeys.feature, JSON.stringify(conf));
return conf;
},
setFeatureConf(conf) {
localStorage.setItem(Config.storageKeys.feature, JSON.stringify(conf));
},
getRateConf() {
const raw = localStorage.getItem(Config.storageKeys.rate);
const saved = Utils.safeJSONParse(raw, {}) || {};
// 目标倍速钳制到 1-16(与倍速迁移说明一致);缺失、非法或非正值回退默认值
const num = Number(saved.targetRate);
const targetRate = Number.isFinite(num) && num > 0 ? Math.min(16, Math.max(1, num)) : Config.playbackRate;
return {
targetRate,
buttonSetEnabled: saved.buttonSetEnabled ?? true,
directSetEnabled: saved.directSetEnabled ?? true,
keepAliveEnabled: saved.keepAliveEnabled ?? true,
ratechangeBlockEnabled: saved.ratechangeBlockEnabled ?? true,
};
},
setRateConf(conf) {
localStorage.setItem(Config.storageKeys.rate, JSON.stringify(conf));
},
getFlowConf() {
const saved = Utils.safeJSONParse(localStorage.getItem(Config.storageKeys.flow), {}) || {};
return {
autoSwitch: saved.autoSwitch ?? true,
restoreOnStop: saved.restoreOnStop ?? true,
};
},
setFlowConf(conf) {
localStorage.setItem(Config.storageKeys.flow, JSON.stringify(conf));
},
getPendingAutoStart() {
const raw = localStorage.getItem(Config.storageKeys.pendingAutoStart);
const saved = Utils.safeJSONParse(raw, null);
if (!saved || !saved.classroomId || !saved.ts) return null;
if (Date.now() - saved.ts > 30 * 60 * 1000) {
localStorage.removeItem(Config.storageKeys.pendingAutoStart);
return null;
}
return saved;
},
setPendingAutoStart(classroomId = '', returnUrl = '') {
if (!classroomId) return;
const prev = this.getPendingAutoStart() || {};
localStorage.setItem(Config.storageKeys.pendingAutoStart, JSON.stringify({
classroomId,
returnUrl: returnUrl || prev.returnUrl || '',
ts: Date.now()
}));
},
clearPendingAutoStart() {
localStorage.removeItem(Config.storageKeys.pendingAutoStart);
},
};
// ---- 刷课会话状态 ----
// 用户点击“停止刷课”后持久化停止标记:重新加载页面(含其它标签页)也不会自动恢复刷课,
// 只有再次点击“开始刷课”才会清除该状态。每次读取持久化值,保证多标签页之间状态一致。
const Session = {
isStopped() {
return localStorage.getItem(Config.storageKeys.userStopped) === '1';
},
begin() {
localStorage.removeItem(Config.storageKeys.userStopped);
},
stop() {
localStorage.setItem(Config.storageKeys.userStopped, '1');
}
};
// ---- UI 面板 ----
function createPanel() {
const iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.top = '40px';
iframe.style.left = '40px';
iframe.style.width = '520px';
iframe.style.height = '340px';
iframe.style.zIndex = '999999';
iframe.style.border = '1px solid #a3a3a3';
iframe.style.borderRadius = '10px';
iframe.style.background = '#fff';
iframe.style.overflow = 'hidden';
iframe.style.boxShadow = '6px 4px 17px 2px #000000';
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('id', 'ykt-helper-iframe');
iframe.setAttribute('allowtransparency', 'true');
const mountTarget = document.body || document.documentElement;
if (!mountTarget) {
throw new Error('面板挂载点不存在');
}
mountTarget.appendChild(iframe);
const doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write(`
展开
- ⭐ 脚本支持:雨课堂所有版本
- 🤖 支持模型:DeepSeek、Kimi(Moonshot)、通义千问、OpenAI、Claude(Anthropic)
- 📢 使用必读:自动答题需先点击[脚本设置]开启并填入API Key
- 🚀 配置完成后,点击[开始刷课]即可启动视频与作业挂机
- 🤝 脚本还有很多不足,欢迎各位一起完善代码
`);
doc.close();
const ui = {
iframe,
doc,
panel: doc.getElementById('panel'),
header: doc.getElementById('header'),
info: doc.getElementById('info'),
btnStart: doc.getElementById('btn-start'),
btnClear: doc.getElementById('btn-clear'),
btnSetting: doc.getElementById('btn-setting'),
btnStop: doc.getElementById('btn-stop'),
btnReload: doc.getElementById('btn-reload'),
settings: doc.getElementById('settings'),
saveSettings: doc.getElementById('save_settings'),
closeSettings: doc.getElementById('close_settings'),
aiUrlInput: doc.getElementById('ai_url'),
aiKeyInput: doc.getElementById('ai_key'),
aiModelInput: doc.getElementById('ai_model'),
aiFormatSelect: doc.getElementById('ai_format'),
authMethodSelect: doc.getElementById('auth_method'),
featureAutoAI: doc.getElementById('feature_auto_ai'),
featureUseOCR: doc.getElementById('feature_use_ocr'),
featureAutoComment: doc.getElementById('feature_auto_comment'),
rateTargetInput: doc.getElementById('rate_target'),
rateButtonSet: doc.getElementById('rate_button_set'),
rateDirectSet: doc.getElementById('rate_direct_set'),
rateKeepAlive: doc.getElementById('rate_keep_alive'),
rateUnlock: doc.getElementById('rate_unlock'),
flowAutoSwitch: doc.getElementById('flow_auto_switch'),
flowRestoreOnStop: doc.getElementById('flow_restore_on_stop'),
minimality: doc.getElementById('minimality'),
question: doc.getElementById('question'),
miniBasic: doc.getElementById('mini-basic')
};
let isDragging = false;
let startX = 0, startY = 0, startLeft = 0, startTop = 0;
const hostWindow = window.parent || window;
const onMove = e => {
if (!isDragging) return;
const deltaX = e.screenX - startX;
const deltaY = e.screenY - startY;
const maxLeft = Math.max(0, hostWindow.innerWidth - iframe.offsetWidth);
const maxTop = Math.max(0, hostWindow.innerHeight - iframe.offsetHeight);
iframe.style.left = Math.min(Math.max(0, startLeft + deltaX), maxLeft) + 'px';
iframe.style.top = Math.min(Math.max(0, startTop + deltaY), maxTop) + 'px';
};
const stopDrag = () => {
if (!isDragging) return;
isDragging = false;
iframe.style.transition = '';
doc.body.style.userSelect = '';
};
ui.header.addEventListener('mousedown', e => {
isDragging = true;
startX = e.screenX;
startY = e.screenY;
startLeft = parseFloat(iframe.style.left) || 0;
startTop = parseFloat(iframe.style.top) || 0;
iframe.style.transition = 'none';
doc.body.style.userSelect = 'none';
e.preventDefault();
});
doc.addEventListener('mousemove', onMove);
hostWindow.addEventListener('mousemove', onMove);
doc.addEventListener('mouseup', stopDrag);
hostWindow.addEventListener('mouseup', stopDrag);
hostWindow.addEventListener('blur', stopDrag);
const normalSize = { width: parseFloat(iframe.style.width), height: parseFloat(iframe.style.height) };
const miniSize = 64;
let isMinimized = false;
const enterMini = () => {
if (isMinimized) return;
isMinimized = true;
ui.panel.style.display = 'none';
ui.miniBasic.classList.add('show');
iframe.style.width = miniSize + 'px';
iframe.style.height = miniSize + 'px';
};
const exitMini = () => {
if (!isMinimized) return;
isMinimized = false;
ui.panel.style.display = '';
ui.miniBasic.classList.remove('show');
iframe.style.width = normalSize.width + 'px';
iframe.style.height = normalSize.height + 'px';
};
ui.minimality.addEventListener('click', enterMini);
ui.miniBasic.addEventListener('click', exitMini);
ui.question.addEventListener('click', () => {
window.parent.alert('作者:niuwh.cn(重构版 by Codex)');
});
// 日志节点上限:长时间刷课时避免面板 DOM 无限增长拖慢渲染
const MAX_LOG_ITEMS = 200;
const appendLog = text => {
const li = doc.createElement('li');
li.innerText = text;
ui.info.appendChild(li);
while (ui.info.childElementCount > MAX_LOG_ITEMS) {
ui.info.firstElementChild.remove();
}
if (ui.info.lastElementChild) ui.info.lastElementChild.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });
};
const log = message => appendLog(message);
const warn = message => appendLog('⚠️警告:' + message);
const error = message => appendLog('🚨报错:' + message);
const defaultAI = { url: 'https://api.deepseek.com/chat/completions', key: 'sk-xxxxxxx', model: 'deepseek-chat', apiFormat: 'openai', authMethod: 'bearer' };
const loadAIConf = () => {
const saved = Store.getAIConf();
ui.aiUrlInput.value = saved.url || defaultAI.url;
ui.aiKeyInput.value = saved.key || defaultAI.key;
ui.aiModelInput.value = saved.model || defaultAI.model;
ui.aiFormatSelect.value = saved.apiFormat || defaultAI.apiFormat;
ui.authMethodSelect.value = saved.authMethod || defaultAI.authMethod;
};
const loadFeatureConf = () => {
const saved = Store.getFeatureConf();
ui.featureAutoAI.checked = saved.autoAI;
ui.featureAutoComment.checked = saved.autoComment;
ui.featureUseOCR.checked = saved.useOCR;
};
const loadRateConf = () => {
const saved = Store.getRateConf();
ui.rateTargetInput.value = saved.targetRate;
ui.rateButtonSet.checked = saved.buttonSetEnabled;
ui.rateDirectSet.checked = saved.directSetEnabled;
ui.rateKeepAlive.checked = saved.keepAliveEnabled;
ui.rateUnlock.checked = saved.ratechangeBlockEnabled;
};
const loadFlowConf = () => {
const saved = Store.getFlowConf();
ui.flowAutoSwitch.checked = saved.autoSwitch;
ui.flowRestoreOnStop.checked = saved.restoreOnStop;
};
loadAIConf();
loadFeatureConf();
loadRateConf();
loadFlowConf();
ui.btnSetting.onclick = () => {
loadAIConf();
loadFeatureConf();
loadRateConf();
loadFlowConf();
ui.settings.style.display = 'block';
};
ui.closeSettings.onclick = () => {
ui.settings.style.display = 'none';
};
ui.saveSettings.onclick = () => {
const conf = {
url: ui.aiUrlInput.value.trim(),
key: ui.aiKeyInput.value.trim(),
model: ui.aiModelInput.value.trim(),
apiFormat: ui.aiFormatSelect.value,
authMethod: ui.authMethodSelect.value
};
Store.setAIConf(conf);
const featureConf = {
autoAI: ui.featureAutoAI.checked,
autoComment: ui.featureAutoComment.checked,
useOCR: ui.featureUseOCR.checked
};
Store.setFeatureConf(featureConf);
const rateConf = {
targetRate: Number(ui.rateTargetInput.value),
buttonSetEnabled: ui.rateButtonSet.checked,
directSetEnabled: ui.rateDirectSet.checked,
keepAliveEnabled: ui.rateKeepAlive.checked,
ratechangeBlockEnabled: ui.rateUnlock.checked
};
Store.setRateConf(rateConf);
const flowConf = {
autoSwitch: ui.flowAutoSwitch.checked,
restoreOnStop: ui.flowRestoreOnStop.checked
};
Store.setFlowConf(flowConf);
// 先还原旧的倍速拦截包装,下次接管媒体时按新开关重新安装
RateUnlock.uninstallAll();
ui.settings.style.display = 'none';
log('✅ 脚本配置已保存');
if (!featureConf.useOCR) {
log('已关闭 OCR:答题时截图将直接发送给多模态模型');
}
};
ui.btnClear.onclick = () => {
Store.removeProgress(window.parent.location.href);
localStorage.removeItem(Config.storageKeys.proClassCount);
Store.clearPendingAutoStart();
log('已清除当前课程的刷课进度缓存');
};
let stopHandler = null;
// 停止刷课:交给外部处理器结束会话并还原对页面/播放器的修改(进度缓存保留)
ui.btnStop.onclick = () => {
if (stopHandler) {
stopHandler();
return;
}
Session.stop();
Store.clearPendingAutoStart();
log('已停止刷课');
};
// 重新加载:刷新页面;刷课进行中会自动续跑,已停止刷课时仅重新加载、不会自动恢复
ui.btnReload.onclick = () => {
if (!Session.isStopped()) {
Store.setPendingAutoStart(Utils.getCurrentClassroomId());
}
log('正在重新加载脚本...');
window.parent.location.reload();
};
let startHandler = null;
let running = false;
const invokeStart = () => {
if (running) {
log('已在刷课中,忽略重复启动');
return;
}
running = true;
log('启动中...');
ui.btnStart.innerText = '刷课中...';
startHandler && startHandler();
};
// 后面赋值给panel
return {
...ui,
log,
warn,
error,
setStartHandler(fn) {
startHandler = fn;
ui.btnStart.onclick = invokeStart;
},
setStopHandler(fn) {
stopHandler = fn;
},
start() {
invokeStart();
},
resetStartButton(text = '开始刷课') {
ui.btnStart.innerText = text;
if (text !== '刷课中...') running = false;
}
};
}
// ---- 倍速解锁:拦截雨课堂 xt 播放器的倍速回写 ----
// xt 播放器的限速器(timeupdate + setInterval 每秒执行)会把倍速强制写回内部记录值(默认 1)。
// 这里不删除页面的监听(内部数据结构不可靠),而是包装媒体元素自身的 playbackRate setter:
// 拦截低于目标倍速的非手动回写(限速定时器/事件回调里的回写),用户手势内的手动调速放行。
const RateUnlock = {
// media -> { hadOwn, origDesc }:元素级 playbackRate 包装的还原记录
// 用 Map 而非 WeakMap:卸载时需要枚举全部已包装元素以还原(记录体积很小,可忽略持有开销)
installedMedia: new Map(),
// 幂等安装:同一元素重复调用不叠加包装;必须先于首次设速调用(设速后限速器就开始回写)
ensure(media) {
media = media || document.querySelector('video') || document.querySelector('audio');
if (!media || !Store.getRateConf().ratechangeBlockEnabled) return false;
if (this.installedMedia.has(media)) return true;
const ownDesc = Object.getOwnPropertyDescriptor(media, 'playbackRate');
const desc = ownDesc || Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'playbackRate');
if (!desc || typeof desc.get !== 'function' || typeof desc.set !== 'function') return false;
let interceptLogged = false;
try {
Object.defineProperty(media, 'playbackRate', {
configurable: true,
enumerable: desc.enumerable,
get() {
return desc.get.call(this);
},
set(value) {
const num = Number(value);
const conf = Store.getRateConf();
// 低于目标倍速的非手动回写(如限速定时器写回 1)一律拦截
if (conf.ratechangeBlockEnabled && conf.targetRate > 1
&& Number.isFinite(num) && num < conf.targetRate
&& !RateUnlock.isUserGesture()) {
if (!interceptLogged) {
interceptLogged = true;
console.log('[倍速] 已拦截页面的倍速回写(解除倍速限制生效)');
}
return;
}
desc.set.call(this, value);
}
});
} catch (e) {
console.warn('[倍速] 倍速回写拦截安装失败:', e);
return false;
}
this.installedMedia.set(media, { hadOwn: !!ownDesc, origDesc: ownDesc || null });
console.log(`[倍速] 倍速回写拦截已启用:低于 ${Store.getRateConf().targetRate}x 的非手动回写将被拦截`);
return true;
},
// 是否处于用户手势中;不支持 userActivation 的浏览器按非手势处理(优先保证拦截生效)
isUserGesture() {
try {
if (navigator.userActivation) return navigator.userActivation.isActive === true;
} catch (_) { /* 忽略环境差异 */ }
return false;
},
// 明确的清理/还原入口:恢复全部被包装的元素(面板保存后按新开关重新安装)
uninstallAll() {
for (const [media, record] of this.installedMedia) {
try {
if (record.hadOwn && record.origDesc) Object.defineProperty(media, 'playbackRate', record.origDesc);
else delete media.playbackRate;
} catch (_) { /* 单个还原失败不影响其余对象 */ }
}
this.installedMedia.clear();
}
};
// ---- 暂停拦截:把 pause 动作替换为空方法 ----
// 雨课堂 xt 播放器在切屏/失焦等场景会调用媒体的 pause() 做惩罚性暂停。
// 不采用“检测到暂停再自动播放”(会与页面的暂停逻辑互相打架),而是包装 pause 方法:
// 刷课进行中直接吞掉暂停动作;停止刷课/视频结束/临近结尾/任务完成时放行真实暂停。
const PauseGuard = {
// media -> { hadOwn, origPause, allowPause }:元素级 pause 包装的还原记录与放行判定
// 用 Map 而非 WeakMap:卸载时需要枚举全部已包装元素以还原(记录体积很小,可忽略持有开销)
installed: new Map(),
// 幂等安装:同一元素重复调用不叠加包装,仅更新放行判定(随任务轮换更新 shouldResume)
install(media, allowPause = () => true) {
if (!media) return false;
const record = this.installed.get(media);
if (record) {
record.allowPause = allowPause;
return true;
}
const hadOwn = Object.prototype.hasOwnProperty.call(media, 'pause');
const origPause = media.pause;
if (typeof origPause !== 'function') return false;
let interceptLogged = false;
try {
media.pause = function () {
const rec = PauseGuard.installed.get(media);
if (!rec || rec.allowPause()) return origPause.apply(this, arguments);
if (!interceptLogged) {
interceptLogged = true;
console.log('[暂停] 已拦截页面的暂停动作(暂停拦截生效)');
}
// 空方法:吞掉本次暂停动作
};
} catch (e) {
console.warn('[暂停] 暂停拦截安装失败:', e);
return false;
}
this.installed.set(media, { hadOwn, origPause, allowPause });
return true;
},
// 还原单个元素被包装的 pause
uninstall(media) {
const record = this.installed.get(media);
if (!record) return;
try {
if (record.hadOwn) media.pause = record.origPause;
else delete media.pause;
} catch (_) { /* 单个还原失败不影响其余对象 */ }
this.installed.delete(media);
},
// 明确的清理/还原入口:恢复全部被包装的元素(停止刷课时还原页面修改)
uninstallAll() {
for (const media of [...this.installed.keys()]) {
this.uninstall(media);
}
}
};
// ---- 页面/播放器修改的还原记录 ----
// 快照脚本首次改动前的原值(媒体倍速/音量/静音、速度按钮 DOM、防切屏包装),
// 停止刷课时一次性还原。用 Map 保证还原时可枚举全部对象(记录仅在页面生命周期内有效)。
const PageRestore = {
mediaStates: new Map(), // media -> { playbackRate, volume, muted, defaultMuted }
nodeStates: new Map(), // node -> { attrs: {name: 原值|null}, text }
screenCheckUndo: null,
snapshotMedia(media) {
if (!media || this.mediaStates.has(media)) return;
this.mediaStates.set(media, {
playbackRate: media.playbackRate,
volume: media.volume,
muted: media.muted,
defaultMuted: media.defaultMuted
});
},
snapshotNode(node, attrs = []) {
if (!node || this.nodeStates.has(node)) return;
const savedAttrs = {};
for (const name of attrs) savedAttrs[name] = node.getAttribute(name);
this.nodeStates.set(node, { attrs: savedAttrs, text: node.innerText });
},
restoreAll() {
// 先卸载倍速/暂停拦截包装,避免还原时被拦截
RateUnlock.uninstallAll();
PauseGuard.uninstallAll();
for (const [media, state] of this.mediaStates) {
try {
media.playbackRate = state.playbackRate;
media.volume = state.volume;
media.muted = state.muted;
media.defaultMuted = state.defaultMuted;
} catch (_) { /* 单个对象还原失败不影响其余对象 */ }
}
this.mediaStates.clear();
for (const [node, state] of this.nodeStates) {
try {
for (const [name, value] of Object.entries(state.attrs)) {
if (value === null) node.removeAttribute(name);
else node.setAttribute(name, value);
}
node.innerText = state.text;
} catch (_) { }
}
this.nodeStates.clear();
if (this.screenCheckUndo) {
this.screenCheckUndo();
this.screenCheckUndo = null;
}
}
};
// ---- 播放器工具 ----
const Player = {
isNearEnd(media, threshold = 1) {
if (!media) return false;
const duration = Number(media.duration || 0);
const currentTime = Number(media.currentTime || 0);
return Number.isFinite(duration) && duration > 1 && currentTime > 0 && duration - currentTime <= threshold;
},
// 接管媒体并设速:autoplay 为 true 时先启动播放并静音(音频/内嵌视频路径)
applySpeed(media, autoplay = false) {
if (Session.isStopped()) return;
const conf = Store.getRateConf();
const target = media || document.querySelector('video') || document.querySelector('audio');
if (!target) return;
// 倍速回写拦截必须先于首次设速安装:设速后限速器就会开始回写
RateUnlock.ensure(target);
// 记录原值,停止刷课时还原
PageRestore.snapshotMedia(target);
if (autoplay) {
target.play();
target.volume = 0;
}
const rate = conf.targetRate;
const rateText = Number(rate).toFixed(2);
const speedBtn = document.querySelector('xt-speedlist xt-button') || document.getElementsByTagName('xt-speedlist')[0]?.firstElementChild?.firstElementChild;
const speedWrap = document.getElementsByTagName('xt-speedbutton')[0];
if (conf.buttonSetEnabled && speedBtn && speedWrap && target.tagName.toLowerCase() === 'video') {
PageRestore.snapshotNode(speedBtn, ['data-speed', 'keyt']);
speedBtn.setAttribute('data-speed', rate);
speedBtn.setAttribute('keyt', rateText);
speedBtn.innerText = `${rateText}X`;
const mousemove = document.createEvent('MouseEvent');
mousemove.initMouseEvent('mousemove', true, true, unsafeWindow, 0, 10, 10, 10, 10, 0, 0, 0, 0, 0, null);
speedWrap.dispatchEvent(mousemove);
speedBtn.click();
} else if (conf.directSetEnabled) {
target.playbackRate = rate;
}
},
mute() {
if (Session.isStopped()) return;
const muteBtn = document.querySelector('#video-box > div > xt-wrap > xt-controls > xt-inner > xt-volumebutton > xt-icon');
if (muteBtn) muteBtn.click();
const video = document.querySelector('video');
if (video) {
PageRestore.snapshotMedia(video);
video.volume = 0;
}
},
// 暂停拦截:刷课期间把 pause 替换为空方法,而非“检测到暂停再自动播放”(后者会与页面暂停互相打架)
// 停止刷课/视频结束/临近结尾/任务完成时放行真实暂停
blockPause(media, shouldResume = () => true) {
if (!media) return () => { };
const allowPause = () => Session.isStopped() || media.ended || this.isNearEnd(media) || !shouldResume();
PauseGuard.install(media, allowPause);
// 启动播放(仅需一次;之后页面的暂停动作直接被拦截,无需反复检测恢复)
let retryTimer = 0;
const startPlay = () => {
if (allowPause()) return;
media.play().catch(e => {
if (allowPause()) return;
console.warn('自动播放失败:', e);
retryTimer = setTimeout(startPlay, 3000);
});
};
startPlay();
return () => {
clearTimeout(retryTimer);
PauseGuard.uninstall(media);
};
},
waitForEnd(media, timeout = 0) {
return new Promise(resolve => {
if (!media) return resolve();
if (media.ended) return resolve();
let timer;
let stopTimer;
const finish = () => {
clearTimeout(timer);
clearInterval(stopTimer);
media.removeEventListener('ended', onEnded);
resolve();
};
const onEnded = () => finish();
media.addEventListener('ended', onEnded, { once: true });
// 停止刷课时提前结束等待,让调用流程尽快收尾
stopTimer = setInterval(() => { if (Session.isStopped()) finish(); }, 500);
if (timeout > 0) {
timer = setTimeout(finish, timeout);
}
});
}
};
// ---- ai-workspace 路由工具 ----
const AiWorkspace = {
normalizeText(text) {
return String(text || '').replace(/\s+/g, ' ').trim();
},
isVisibleElement(element) {
if (!element || element.nodeType !== 1) return false;
const view = element.ownerDocument?.defaultView || window;
const style = view.getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style.display !== 'none'
&& style.visibility !== 'hidden'
&& rect.width > 0
&& rect.height > 0;
},
getRoute() {
const match = location.pathname.match(/^\/ai-workspace\/lms-graph\/([^/]+)\/([^/]+)\/([^/?#]+)/);
if (!match) return null;
const [, classroomId, type, leafId] = match;
const query = new URLSearchParams(location.search);
return {
classroomId,
type,
leafId,
nodeId: query.get('node_id') || ''
};
},
getMedia() {
// 选取可见的 video 或任意 audio 作为接管目标
const candidates = [...document.querySelectorAll('video, audio')].filter(media => {
if (!(media instanceof HTMLMediaElement)) return false;
const rect = media.getBoundingClientRect();
return (rect.width > 0 && rect.height > 0) || media.tagName.toLowerCase() === 'audio';
});
if (!candidates.length) return document.querySelector('video') || document.querySelector('audio');
const score = media => {
const rect = media.getBoundingClientRect();
const area = rect.width * rect.height;
const playingBoost = !media.paused && !media.ended ? 1_000_000 : 0;
const currentBoost = Number(media.currentTime || 0);
return playingBoost + area + currentBoost;
};
return [...candidates].sort((a, b) => score(b) - score(a))[0];
},
isPlayerDone(media, { startTime = 0, minPlayedDelta = 0 } = {}) {
if (!media) return false;
const currentTime = Number(media?.currentTime || 0);
const duration = Number(media?.duration || 0);
const playedDelta = Math.max(0, currentTime - startTime);
if (playedDelta < minPlayedDelta) return false;
if (media?.ended) return true;
if (duration > 1 && currentTime > 0 && duration - currentTime <= 1) return true;
const display = document.querySelector('.xt_video_player_current_time_display')?.innerText?.trim() || '';
const [current, total] = display.split(' / ').map(text => text?.trim());
return Boolean(playedDelta >= minPlayedDelta && current && total && current === total);
},
keepAlive(shouldResume = () => true) {
let lastMedia = null;
const tick = () => {
if (!shouldResume() || Session.isStopped()) return;
const media = this.getMedia();
if (!media) return;
if (lastMedia !== media) {
lastMedia = media;
// 暂停拦截随媒体更换迁移:pause 被替换为空方法,无需“检测到暂停再自动播放”
PauseGuard.install(media, () => Session.isStopped() || media.ended || Player.isNearEnd(media) || !shouldResume());
}
// 记录原值,停止刷课时还原
PageRestore.snapshotMedia(media);
media.muted = true;
media.defaultMuted = true;
media.volume = 0;
// 解锁包装随媒体更换迁移(幂等,重复调用无副作用)
RateUnlock.ensure(media);
// 倍速保活:定时恢复被页面重置的倍速,受“倍速保活”与“直设媒体倍速”双开关控制
const rateConf = Store.getRateConf();
if (rateConf.keepAliveEnabled && rateConf.directSetEnabled) {
media.playbackRate = rateConf.targetRate;
}
};
const timer = setInterval(tick, 500);
document.addEventListener('visibilitychange', tick);
window.addEventListener('focus', tick);
tick();
return () => {
clearInterval(timer);
if (lastMedia) PauseGuard.uninstall(lastMedia);
document.removeEventListener('visibilitychange', tick);
window.removeEventListener('focus', tick);
};
},
getActiveLeafTitle() {
return document.querySelector('.leaf-item.is-active')?.innerText?.replace(/\s+/g, ' ').trim() || '';
},
// 定位作业容器:先查本页,找不到再查同源 iframe
getExerciseContainer() {
const findIn = doc => doc.querySelector('#app .container-body .container-problem')
|| doc.querySelector('#app .container-problem')
|| doc.querySelector('.container-problem')
|| null;
const local = findIn(document);
if (local) return local;
for (const frame of document.querySelectorAll('iframe')) {
try {
const doc = frame.contentDocument;
if (!doc?.body) continue;
if (
doc.querySelector('.container-problem')
|| doc.querySelector('.subject-item')
|| doc.querySelector('.item-body')
) {
return findIn(doc);
}
} catch (_) {
// 跨域 iframe 无法访问,跳过
}
}
return null;
},
getExerciseQuestionTabs(root = this.getExerciseContainer()) {
if (!root) return [];
// 题号列表在作业容器外的侧栏(.problems-aside)里,需要向上找到 .container-body 再查
const scope = root.closest?.('.container-body') || root.closest?.('.problem-box') || root;
const collect = selector => {
const all = [...scope.querySelectorAll(selector)]
.filter((el, index, arr) => arr.indexOf(el) === index && this.isVisibleElement(el));
// 排除包含其它候选的容器节点,避免把整块题目区当成一个“题号”
const tabs = all.filter(el => !all.some(other => other !== el && el.contains(other)));
return tabs.filter(el => {
const text = this.normalizeText(el.innerText);
// 作答后题号文案可能追加“已完成/回答正确”等状态,限制放宽到 40 字
return text && text.length <= 40;
});
};
// 精确选择器优先;命中即返回,避免把题目正文的 .subject-item 误当成题号
const precise = collect('.subject-item.J_order, .problem-index-item, .question-index-item');
if (precise.length) return precise;
return collect('[class*="subject-item"], [class*="problem-index"], [class*="question-index"]');
},
getExerciseQuestionBody(root = this.getExerciseContainer()) {
if (!root) return null;
const itemType = root.querySelector('.item-type');
if (itemType?.parentElement && this.isVisibleElement(itemType.parentElement)) return itemType.parentElement;
const selectors = [
'.item-body',
'.problem-content',
'.question-content',
'.problem-main',
'.problem-body',
'.question-body',
'[class*="problem-content"]',
'[class*="question-content"]',
'[class*="problem-body"]',
'[class*="question-body"]'
];
for (const selector of selectors) {
const match = [...root.querySelectorAll(selector)].find(el => this.isVisibleElement(el));
if (match) return match;
}
return root;
},
// 已作答判定:只看明确的“已提交”禁用态与状态文本。
// 不再用裸 button[disabled] 兜底——未选选项时被禁用的“提交”按钮会把整道题误判成已完成
isExerciseAnswered(root = this.getExerciseContainer()) {
if (!root) return false;
const disabled = root.querySelector('.el-button.el-button--info.is-disabled.is-plain');
if (disabled && this.isVisibleElement(disabled)) return true;
// 已提交/已作答的按钮文案也算完成,比裸 button[disabled] 精确,不受“未选选项时提交按钮禁用”影响
const buttons = [...root.querySelectorAll('button, .el-button')];
const answeredBtn = buttons.find(el => /已提交|已作答|已完成/.test(this.normalizeText(el.innerText || '')));
if (answeredBtn) return true;
// 通用兜底:提交按钮被禁用且已有选项被勾选,说明本题已提交(未选选项时提交按钮即使禁用也不误判)
const checked = root.querySelector('input[type="radio"]:checked, input[type="checkbox"]:checked, .el-radio.is-checked, .el-checkbox.is-checked, [role="radio"][aria-checked="true"], [role="checkbox"][aria-checked="true"]');
const disabledSubmit = buttons.find(el => /提交|保存/.test(this.normalizeText(el.innerText || ''))
&& (el.disabled || /is-disabled/.test(el.className || '')));
if (checked && disabledSubmit) return true;
const statusSelectors = [
'.result',
'.status',
'.answer-status',
'[class*="result"]',
'[class*="status"]'
];
for (const selector of statusSelectors) {
const statusNode = [...root.querySelectorAll(selector)]
.find(el => this.isVisibleElement(el) && /已完成|已作答|已提交|回答正确|回答错误/.test(this.normalizeText(el.innerText)));
if (statusNode) return true;
}
return false;
},
// 选项元素:题干内按优先级定位一次,选项计数与点选复用同一批元素,避免重复扫描 DOM
getExerciseOptions(root = this.getExerciseContainer()) {
if (!root) return [];
const listContainer = root.querySelector('.list-inline.list-unstyled-radio')
|| root.querySelector('.list-unstyled.list-unstyled-radio')
|| root.querySelector('.list-unstyled')
|| root.querySelector('ul.list')
|| root.querySelector('[class*="option-list"]')
|| root.querySelector('[class*="answer-list"]')
|| root.querySelector('ul')
|| root.querySelector('[role="radiogroup"]');
if (!listContainer) return [];
return [...listContainer.querySelectorAll('li, .option-item, .answer-item, [class*="option-item"], [class*="answer-item"]')];
},
// 题目指纹:题干全文。用全文而不是前缀,避免共用同一段材料的题目前缀相同导致切题判断失效;
// 同时剔除“已提交/回答正确/正确答案:A”这类作答状态文案,避免它们被误判成切换了题目
getExerciseFingerprint(root = this.getExerciseContainer()) {
const questionRoot = this.getExerciseQuestionBody(root);
const text = this.normalizeText(questionRoot?.innerText || '');
return text
.replace(/已提交|已作答|已完成|回答正确|回答错误/g, '')
.replace(/(?:正确答案|你的答案)[::]?\s*[A-Fa-f、,,\s]*/g, '')
.trim();
},
// 提交后的二次确认弹窗:仅在弹窗文本包含“提交”时点确定,避免误点其它弹窗
confirmSubmitDialog(root = this.getExerciseContainer()) {
const docs = [document];
const ownerDoc = root?.ownerDocument;
if (ownerDoc && ownerDoc !== document) docs.push(ownerDoc);
for (const doc of docs) {
const boxes = doc.querySelectorAll('.el-message-box__wrapper, .el-dialog__wrapper');
for (const box of boxes) {
if (!this.isVisibleElement(box)) continue;
if (!this.normalizeText(box.innerText || '').includes('提交')) continue;
const confirmBtn = [...box.querySelectorAll('button')]
.find(btn => this.isVisibleElement(btn) && /^(确定|确认|提交|好的)/.test(this.normalizeText(btn.innerText || '')));
if (confirmBtn) {
confirmBtn.click();
return true;
}
}
}
return false;
}
};
// ---- 防切屏 ----
function preventScreenCheck() {
const win = unsafeWindow;
// 幂等安装:重复调用不再叠加包装,并登记还原入口(停止刷课时恢复页面原行为)
if (PageRestore.screenCheckUndo) return;
const blackList = new Set(['visibilitychange', 'blur', 'pagehide']);
const origWinAdd = win.addEventListener;
const origDocAdd = document.addEventListener;
win._addEventListener = origWinAdd;
win.addEventListener = (...args) => blackList.has(args[0]) ? undefined : win._addEventListener(...args);
document._addEventListener = origDocAdd;
document.addEventListener = (...args) => blackList.has(args[0]) ? undefined : document._addEventListener(...args);
// 属性遮蔽声明为可配置,便于停止刷课时删除还原
Object.defineProperties(document, {
hidden: { value: false, configurable: true },
visibilityState: { value: 'visible', configurable: true },
hasFocus: { value: () => true, configurable: true },
onvisibilitychange: { get: () => undefined, set: () => { }, configurable: true },
onblur: { get: () => undefined, set: () => { }, configurable: true }
});
Object.defineProperties(win, {
onblur: { get: () => undefined, set: () => { }, configurable: true },
onpagehide: { get: () => undefined, set: () => { }, configurable: true }
});
PageRestore.screenCheckUndo = () => {
try {
win.addEventListener = origWinAdd;
delete win._addEventListener;
} catch (_) { /* 尽力还原 */ }
try {
document.addEventListener = origDocAdd;
delete document._addEventListener;
} catch (_) { }
for (const key of ['hidden', 'visibilityState', 'hasFocus', 'onvisibilitychange', 'onblur']) {
try { delete document[key]; } catch (_) { }
}
for (const key of ['onblur', 'onpagehide']) {
try { delete win[key]; } catch (_) { }
}
};
}
// ---- OCR & AI ----
const Solver = {
// 解析答题模式:OCR 开启走 OCR 识别(原行为),关闭即认为模型支持图片输入,截图直传
resolveAnswerMode() {
return Store.getFeatureConf().useOCR ? 'ocr' : 'vision';
},
// 两条路径共用的截图逻辑:按元素尺寸动态选缩放(最长边不超过 maxSide)。
// 固定 2 倍渲染整块题目 DOM 会在长题目上产生巨大的 canvas,造成明显卡顿
async capture(element, maxSide = 1600) {
panel.log('正在截图...');
const rect = element.getBoundingClientRect();
const longest = Math.max(rect.width, rect.height, 1);
const scale = Math.min(2, Math.max(1, maxSide / longest));
return html2canvas(element, {
useCORS: true,
logging: false,
scale,
backgroundColor: '#ffffff'
});
},
// OCR worker 复用:Tesseract.recognize 每次调用都会新建 worker 并重新初始化语言包,
// 连续作答时反复初始化 wasm 非常耗 CPU;这里惰性创建一次并复用
ocrWorker: null,
ocrWorkerPromise: null,
ensureOcrWorker() {
if (this.ocrWorker) return Promise.resolve(this.ocrWorker);
if (this.ocrWorkerPromise) return this.ocrWorkerPromise;
if (typeof Tesseract === 'undefined' || typeof Tesseract.createWorker !== 'function') {
return Promise.resolve(null);
}
const logger = m => {
if (m.status === 'downloading tesseract lang') {
console.log(`正在下载语言包 ${(m.progress * 100).toFixed(0)}%`);
}
};
this.ocrWorkerPromise = (async () => {
const worker = Tesseract.createWorker({ logger });
await worker.load();
await worker.loadLanguage('chi_sim');
await worker.initialize('chi_sim');
this.ocrWorker = worker;
return worker;
})().catch(err => {
console.error('OCR worker 初始化失败,回退到单次识别:', err);
this.ocrWorkerPromise = null;
return null;
});
return this.ocrWorkerPromise;
},
resetOcrWorker() {
const worker = this.ocrWorker;
this.ocrWorker = null;
this.ocrWorkerPromise = null;
if (!worker) return;
try {
worker.terminate();
} catch (_) { }
},
async recognize(element) {
if (!element) return '无元素';
try {
const canvas = await this.capture(element);
const worker = await this.ensureOcrWorker();
panel.log(worker ? '正在 OCR 识别...' : '正在 OCR 识别 (首轮较慢)...');
const result = worker
? await worker.recognize(canvas)
: await Tesseract.recognize(canvas, 'chi_sim', {
logger: m => {
if (m.status === 'downloading tesseract lang') {
console.log(`正在下载语言包 ${(m.progress * 100).toFixed(0)}%`);
}
}
});
return String(result?.data?.text || '').replace(/\s+/g, ' ').trim();
} catch (err) {
console.error('OCR error:', err);
// worker 可能已崩溃:丢弃它,下次重新创建
this.resetOcrWorker();
panel.log(`OCR 失败: ${err.message || '网络错误'}`);
return 'OCR识别出错';
}
},
// 截图直传路径:把截图压缩成模型可接受的 JPEG 图片负载
toImagePayload(canvas) {
const MAX_SIDE = 1568; // 限制最长边,避免 base64 请求体过大
let target = canvas;
const maxSide = Math.max(canvas.width, canvas.height);
if (maxSide > MAX_SIDE) {
const ratio = MAX_SIDE / maxSide;
const scaled = document.createElement('canvas');
scaled.width = Math.round(canvas.width * ratio);
scaled.height = Math.round(canvas.height * ratio);
scaled.getContext('2d').drawImage(canvas, 0, 0, scaled.width, scaled.height);
target = scaled;
}
const dataUrl = target.toDataURL('image/jpeg', 0.85);
return { base64: dataUrl.split(',')[1], mediaType: 'image/jpeg', dataUrl };
},
// 按模式准备题目输入:vision 返回图片负载,ocr 返回 OCR 文本;失败或过短返回 null
async prepareQuestion(element, mode = 'ocr') {
if (!element) return null;
if (mode === 'vision') {
try {
// 与 toImagePayload 的最长边限制保持一致,避免先渲染大图再缩小
const canvas = await this.capture(element, 1568);
return this.toImagePayload(canvas);
} catch (err) {
console.error('Screenshot error:', err);
panel.log(`截图失败: ${err.message || '网络错误'}`);
return null;
}
}
const text = await this.recognize(element);
return (text && text !== 'OCR识别出错' && text.length > 5) ? text : null;
},
// OCR 文本路径提示词
buildTextPrompt(ocrText, optionCount) {
const maxChar = String.fromCharCode(65 + optionCount - 1);
const rangeStr = optionCount ? `A-${maxChar}` : 'A-D';
return `
你是专业做题助手,请分析 OCR 文本,判断题型后给出答案。
强约束:
1) 本题只有 ${optionCount || '若干'} 个选项,范围 ${rangeStr}
2) 忽略 OCR 错误的选项字母,按出现顺序映射 A/B/C/D...
3) 输出格式必须包含“正确答案:”前缀,例如 正确答案:A 或 正确答案:ABD 或 正确答案:对/错
题目内容:
${ocrText}
`;
},
// 截图直传路径提示词
buildVisionPrompt(optionCount) {
const maxChar = String.fromCharCode(65 + optionCount - 1);
const rangeStr = optionCount ? `A-${maxChar}` : 'A-D';
return `
你是专业做题助手,请直接分析题目截图,判断题型后给出答案。
强约束:
1) 本题只有 ${optionCount || '若干'} 个选项,范围 ${rangeStr}
2) 以截图中选项出现顺序为准,映射 A/B/C/D...
3) 输出格式必须包含“正确答案:”前缀,例如 正确答案:A 或 正确答案:ABD 或 正确答案:对/错
`;
},
async askAI(question, optionCount = 0) {
const saved = Store.getAIConf();
const API_URL = saved.url;
const API_KEY = saved.key;
const MODEL_NAME = saved.model;
const API_FORMAT = saved.apiFormat || 'openai';
const AUTH_METHOD = saved.authMethod || 'bearer';
// question 为对象时走截图直传(多模态),为字符串时走 OCR 文本,两条路径并列
const isImage = !!question && typeof question === 'object';
return new Promise((resolve, reject) => {
if (!API_KEY || API_KEY.includes('sk-xxxx')) {
const msg = '⚠️ 请在 [AI配置] 中填写有效的 API Key';
panel.log(msg);
reject(msg);
return;
}
const prompt = isImage ? this.buildVisionPrompt(optionCount) : this.buildTextPrompt(question, optionCount);
const systemPrompt = isImage
? "你是一个只输出答案的助手。请根据题目截图作答,判断题输出'对'或'错',选择题输出字母。"
: "你是一个只输出答案的助手。判断题输出'对'或'错',选择题输出字母。";
// 图片路径用多模态 content 数组承载截图,文本路径保持纯文本
const userContent = isImage
? [
{ type: 'text', text: prompt },
API_FORMAT === 'anthropic'
? { type: 'image', source: { type: 'base64', media_type: question.mediaType, data: question.base64 } }
: { type: 'image_url', image_url: { url: question.dataUrl } }
]
: prompt;
// 构建认证 header
const authHeader = AUTH_METHOD === 'x-api-key'
? { 'x-api-key': API_KEY }
: { 'Authorization': `Bearer ${API_KEY}` };
if (API_FORMAT === 'anthropic') {
// Anthropic API 格式
const headers = {
'Content-Type': 'application/json',
...authHeader
};
// 只有原生 Anthropic API 才需要 anthropic-version,代理通常不需要
if (API_URL.includes('api.anthropic.com')) {
headers['anthropic-version'] = '2023-06-01';
}
const requestBody = {
model: MODEL_NAME,
max_tokens: 1024,
system: systemPrompt,
messages: [
{ role: 'user', content: userContent }
]
};
// 调试日志
console.log('[AI请求] URL:', API_URL);
console.log('[AI请求] Headers:', headers);
console.log('[AI请求] Body:', requestBody);
panel.log(`请求 ${API_URL}...`);
GM_xmlhttpRequest({
method: 'POST',
url: API_URL,
headers,
data: JSON.stringify(requestBody),
timeout: 120000, // 120秒,思考模型需要更长响应时间
onload: res => {
console.log('[AI响应] Status:', res.status);
console.log('[AI响应] Response:', res.responseText);
if (res.status === 200) {
try {
const json = JSON.parse(res.responseText);
// Anthropic 返回格式: content[0].text
const answerText = json.content?.[0]?.text || json.choices?.[0]?.message?.content;
resolve(answerText);
} catch (e) {
reject('JSON 解析失败');
}
} else {
const err = `请求失败: HTTP ${res.status} - ${res.responseText}`;
panel.log(err);
reject(err);
}
},
onerror: () => reject('网络错误'),
ontimeout: () => reject('请求超时')
});
} else {
// OpenAI API 格式(默认)
GM_xmlhttpRequest({
method: 'POST',
url: API_URL,
headers: {
'Content-Type': 'application/json',
...authHeader
},
data: JSON.stringify({
model: MODEL_NAME,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userContent }
],
temperature: 0.1
}),
timeout: 120000, // 120秒,思考模型需要更长响应时间
onload: res => {
if (res.status === 200) {
try {
const json = JSON.parse(res.responseText);
const answerText = json.choices[0].message.content;
resolve(answerText);
} catch (e) {
reject('JSON 解析失败');
}
} else {
const err = `请求失败: HTTP ${res.status}`;
panel.log(err);
reject(err);
}
},
onerror: () => reject('网络错误'),
ontimeout: () => reject('请求超时')
});
}
});
},
// 返回 { selected, submitted, fingerprint }:
// selected 是否点选了选项,submitted 是否点到可用的提交按钮,
// fingerprint 为“选完选项、点击提交之前”的题目指纹,供调用方判断页面是否自动切题
async autoSelectAndSubmit(aiResponse, itemBodyElement, options = null) {
const responseText = String(aiResponse || '');
// 兼容“正确答案:A”“正确答案是 A”“答案:A、B”等常见写法
const match = responseText.match(/(?:正确|参考)?答案(?:[::]|为|是)?\s*([A-Fa-f]+(?:[\s,,、]*[A-Fa-f]+)*|[对错]|正确|错误)/);
if (!match) {
panel.log('⚠️ 未提取到有效选项,请人工检查');
return { selected: false, submitted: false, fingerprint: '' };
}
let answerRaw = match[1].replace(/[\s,,、]/g, '').trim();
const map = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5 };
let targetIndices = [];
if (answerRaw === '对' || answerRaw === '正确') {
targetIndices = [0];
} else if (answerRaw === '错' || answerRaw === '错误') {
targetIndices = [1];
} else {
for (const char of answerRaw.toUpperCase()) {
if (map[char] !== undefined) targetIndices.push(map[char]);
}
}
if (!targetIndices.length) {
return { selected: false, submitted: false, fingerprint: '' };
}
panel.log(`✅ AI 建议选:${answerRaw}`);
const optionEls = options?.length ? options : AiWorkspace.getExerciseOptions(itemBodyElement);
if (!optionEls.length) {
panel.log('⚠️ 未找到选项容器');
return { selected: false, submitted: false, fingerprint: '' };
}
// 选项最终状态:先清理多选里残留的草稿选项,再逐个确保目标项被勾选。
// 站点会恢复草稿勾选态但不写答案,此时点击已勾选项不触发 change,需要补发 change 事件
const ownerDoc = itemBodyElement.ownerDocument || document;
const ViewEvent = ownerDoc.defaultView?.Event || Event;
const clickableOf = option => option.querySelector('label.el-radio') ||
option.querySelector('label.el-checkbox') ||
option.querySelector('.el-radio__label') ||
option.querySelector('.el-checkbox__label') ||
option.querySelector('[role="radio"]') ||
option.querySelector('[role="checkbox"]') ||
option.querySelector('input') ||
option;
const inputOf = option => option.querySelector('input[type="radio"], input[type="checkbox"]');
const isCheckedOption = option => {
const input = inputOf(option);
if (input) return input.checked;
const label = option.querySelector('label.el-radio, label.el-checkbox');
if (label) return /is-checked/.test(label.className || '');
return /is-checked/.test(option.className || '');
};
const applyOption = async (option, checked) => {
await Utils.humanClick(clickableOf(option));
await Utils.sleep(180 + Math.random() * 160);
const input = inputOf(option);
if (!input) return;
if (input.checked !== checked) input.checked = checked;
input.dispatchEvent(new ViewEvent('change', { bubbles: true }));
await Utils.sleep(80 + Math.random() * 80);
};
// 作答前停顿,避免“截图→点选项→提交”连成一条直线
await Utils.sleep(250 + Math.random() * 350);
const isMultiChoice = optionEls.some(option => option.querySelector('input[type="checkbox"], label.el-checkbox'));
if (isMultiChoice) {
for (let i = 0; i < optionEls.length; i++) {
if (!targetIndices.includes(i) && isCheckedOption(optionEls[i])) {
await applyOption(optionEls[i], false);
}
}
}
for (const idx of targetIndices) {
const option = optionEls[idx];
if (option) await applyOption(option, true);
}
const isDisabled = btn => btn.disabled || /is-disabled|is-loading/.test(btn.className || '');
const submitBtn = (() => {
const ownerDocument = itemBodyElement.ownerDocument || document;
const roots = [itemBodyElement.parentElement, itemBodyElement, ownerDocument].filter(Boolean);
const matchText = text => /提交|保存|确认|确定|提交答案/.test(text);
for (const root of roots) {
const local = root.querySelectorAll('button, .el-button, [role="button"]');
for (const btn of local) {
if (btn.offsetParent !== null && !isDisabled(btn) && matchText(btn.innerText || '')) return btn;
}
}
const global = ownerDocument.querySelectorAll('.el-button.el-button--primary.el-button--medium');
for (const btn of global) {
if (matchText(btn.innerText || '') && btn.offsetParent !== null && !isDisabled(btn)) return btn;
}
return null;
})();
// 提交前再停顿,和选项点击错开;停顿后再取指纹,把勾选后的异步文案变化一并算入基准
await Utils.sleep(400 + Math.random() * 400);
const fingerprint = AiWorkspace.getExerciseFingerprint();
if (!submitBtn) {
panel.log('⚠️ 未找到可用的提交按钮,请手动提交');
return { selected: true, submitted: false, fingerprint };
}
panel.log('正在提交...');
await Utils.humanClick(submitBtn);
return { selected: true, submitted: true, fingerprint };
}
};
// ---- 流程开关:自动切换下一个任务点/切换界面 ----
// 关闭后当前任务点完成(或失败)时不再点击下一个任务点、不再跳转其它页面,
// 提示后停在原地并清除跨页自动续跑标记,避免切换页面后抓取失败的连环报错
function haltIfNoAutoSwitch(context) {
if (Store.getFlowConf().autoSwitch) return false;
panel.log(`${context}:已关闭“自动切换任务点/界面”,停留当前页面;请手动切换后点击[开始刷课]继续`);
Store.clearPendingAutoStart();
panel.resetStartButton('开始刷课');
return true;
}
// ---- v2 逻辑 ----
class V2Runner {
constructor() {
this.baseUrl = location.href;
const { current } = Store.getProgress(this.baseUrl);
this.outside = current.outside;
this.inside = current.inside;
this.shouldStop = false;
}
updateProgress(outside, inside = 0) {
this.outside = outside;
this.inside = inside;
Store.setProgress(this.baseUrl, outside, inside);
}
async waitForExternalHandoff(timeout = 1200) {
await Utils.sleep(timeout);
if (document.visibilityState === 'hidden' || !document.hasFocus()) {
this.shouldStop = true;
panel.log('已交给新页面继续,返回目录页后会自动续跑');
return true;
}
return false;
}
checkCompletionStatus(statusBox, statusText) {
// 1. 检查明确的完成状态文本
if (statusText.includes('已完成') || statusText.includes('已读')) {
return true;
}
// 2. 检查明确的未完成状态文本
if (statusText.includes('未开始') || statusText.includes('未读') || statusText.includes('进行中')) {
return false;
}
// 3. 检查学习进度数字比例
const progressMatch = statusText.match(/(\d+)\/(\d+)/);
if (progressMatch) {
const [, current, total] = progressMatch;
const currentNum = parseInt(current, 10);
const totalNum = parseInt(total, 10);
// 根据数字进度判断:相等且大于0表示已完成
return currentNum === totalNum && totalNum > 0;
}
// 默认返回false(未完成)
return false;
}
async run() {
panel.log(`检测到已播放到第 ${this.outside} 集,继续刷课...`);
// 在课件页恢复时直接续播当前内容,不重新走列表流程
if (location.pathname.includes('/studentCards/')) {
const videoBox = document.querySelector('.video-box');
const boxText = videoBox?.innerText || '';
if ((videoBox || document.querySelector('video')) && !boxText.includes('已完成')) {
panel.log('检测到当前课件页,直接续播当前内容');
await this.waitCoursewareVideo();
if (haltIfNoAutoSwitch('当前课件内容播放完成')) return;
history.back();
await Utils.sleep(1000);
}
}
while (!Session.isStopped()) {
await this.autoSlide();
const list = document.querySelector('.logs-list')?.childNodes;
if (!list || !list.length) {
// 可能停留在课件页:跳回目录页继续,避免无限重试
const pending = Store.getPendingAutoStart();
const returnUrl = pending?.returnUrl
|| (pending?.classroomId ? `/v2/web/studentLog/${pending.classroomId}` : '');
if (returnUrl && !location.pathname.includes('/studentLog/')) {
if (haltIfNoAutoSwitch('当前页面无课程列表')) return;
panel.log('当前页面无课程列表,返回目录页继续');
location.href = returnUrl;
return;
}
panel.log('未找到课程列表,稍后重试');
await Utils.sleep(2000);
continue;
}
console.log(`当前集数:${this.outside}/全部集数${list.length}`);
if (this.outside >= list.length) {
panel.log('课程刷完啦 🎉');
panel.resetStartButton('刷完啦~');
Store.removeProgress(this.baseUrl);
Store.clearPendingAutoStart();
break;
}
const course = list[this.outside]?.querySelector('.content-box')?.querySelector('section');
if (!course) {
panel.log('未找到当前课程节点,跳过');
this.updateProgress(this.outside + 1, 0);
continue;
}
const type = course.querySelector('.tag')?.querySelector('use')?.getAttribute('xlink:href') || 'piliang';
const title = course.querySelector('h2')?.innerText?.trim() || `第${this.outside + 1}项`;
// 预检查完成状态
const statusBox = course.querySelector('.statistics-box .aside');
const statusText = statusBox?.innerText || '';
// 判断是否已完成
let isCompleted = this.checkCompletionStatus(statusBox, statusText);
if (isCompleted) {
panel.log(`✅ ${title} 已完成,跳过`);
this.updateProgress(this.outside + 1, 0);
continue;
}
panel.log(`刷课状态:第 ${this.outside + 1}/${list.length} 个,类型 ${type},标题:${title}`);
if (type.includes('shipin')) {
await this.handleVideo(course);
} else if (type.includes('piliang')) {
await this.handleBatch(course, list);
} else if (type.includes('ketang')) {
await this.handleClassroom(course);
} else if (type.includes('kejian')) {
await this.handleCourseware(course);
} else if (type.includes('kaoshi')) {
panel.log('考试区域脚本会被屏蔽,已跳过');
this.updateProgress(this.outside + 1, 0);
} else {
panel.log('非视频/批量/课件/考试,已跳过');
this.updateProgress(this.outside + 1, 0);
}
if (this.shouldStop || Session.isStopped()) return;
}
}
async autoSlide() {
const frequency = Math.floor((this.outside + 1) / 20) + 1;
for (let i = 0; i < frequency; i++) {
// 下滑到最底部,触发课程加载
const container = document.querySelector('.viewContainer');
if (container) container.scrollTop = container.scrollHeight;
await Utils.sleep(800);
}
}
async handleVideo(course) {
course.click();
if (await this.waitForExternalHandoff(1500)) return;
await Utils.sleep(3000);
const progressNode = document.querySelector('.progress-wrap')?.querySelector('.text');
const title = document.querySelector('.title')?.innerText || '视频';
const isDeadline = document.querySelector('.box')?.innerText.includes('已过考核截止时间');
if (isDeadline) panel.log(`${title} 已过截止,进度不再增加,将直接跳过`);
Player.applySpeed();
Player.mute();
const stopObserve = Player.blockPause(document.querySelector('video'));
await Utils.poll(() => {
Utils.dismissPopups();
return isDeadline || Utils.isProgressDone(progressNode?.innerHTML);
}, { interval: 5000, timeout: await Utils.getDDL() });
stopObserve();
if (Session.isStopped()) return;
this.updateProgress(this.outside + 1, 0);
if (haltIfNoAutoSwitch('当前视频播放完成')) {
this.shouldStop = true;
return;
}
history.back();
await Utils.sleep(1200);
}
async handleBatch(course, list) {
const expandBtn = course.querySelector('.sub-info')?.querySelector('.gray')?.querySelector('span');
if (!expandBtn) {
panel.log('未找到批量展开按钮,跳过');
this.updateProgress(this.outside + 1, 0);
return;
}
expandBtn.click();
await Utils.sleep(1200);
const activities = list[this.outside]?.querySelector('.leaf_list__wrap')?.querySelectorAll('.activity__wrap') || [];
let idx = this.inside;
panel.log(`进入批量区,内部进度 ${idx}/${activities.length}`);
while (idx < activities.length) {
const item = activities[idx];
if (!item) break;
const tagText = item.querySelector('.tag')?.innerText || '';
const tagHref = item.querySelector('.tag')?.querySelector('use')?.getAttribute('xlink:href') || '';
const title = item.querySelector('h2')?.innerText || `第${idx + 1}项`;
// 检查当前项目的完成状态
const statusBox = item.querySelector('.statistics-box .aside');
const statusText = statusBox?.innerText || '';
const isCompleted = this.checkCompletionStatus(statusBox, statusText);
if (isCompleted) {
panel.log(`✅ ${title} 已完成,跳过`);
idx++;
this.updateProgress(this.outside, idx);
continue;
}
if (tagText === '音频') {
idx = await this.playMediaItem(item, title, idx, true);
} else if (tagHref.includes('shipin')) {
idx = await this.playMediaItem(item, title, idx);
} else if (tagHref.includes('tuwen') || tagHref.includes('taolun')) {
idx = await this.autoCommentItem(item, tagHref.includes('tuwen') ? '图文' : '讨论', idx);
} else if (tagHref.includes('zuoye')) {
idx = await this.handleHomework(item, idx);
} else {
panel.log(`类型未知,已跳过:${title}`);
idx++;
this.updateProgress(this.outside, idx);
}
if (this.shouldStop || Session.isStopped()) return;
}
this.updateProgress(this.outside + 1, 0);
await Utils.sleep(1000);
}
// 批量区媒体条目:打开并等待播放进度完成,audio 区分音频/视频的接管方式
async playMediaItem(item, title, idx, audio = false) {
panel.log(`开始播放${audio ? '音频' : '视频'}:${title}`);
item.click();
if (await this.waitForExternalHandoff()) return idx;
await Utils.sleep(2500);
let stopPause = () => { };
if (audio) {
Player.applySpeed(document.querySelector('audio'), true);
} else {
Player.applySpeed();
Player.mute();
stopPause = Player.blockPause(document.querySelector('video'));
}
const progressNode = document.querySelector('.progress-wrap')?.querySelector('.text');
await Utils.poll(() => {
Utils.dismissPopups();
return Utils.isProgressDone(progressNode?.innerHTML);
}, { interval: 3000, timeout: await Utils.getDDL() });
stopPause();
if (Session.isStopped()) return idx;
panel.log(`${title} 播放完成`);
idx++;
this.updateProgress(this.outside, idx);
if (haltIfNoAutoSwitch(`${title} 播放完成`)) {
this.shouldStop = true;
return idx;
}
history.back();
await Utils.sleep(1500);
return idx;
}
async autoCommentItem(item, typeText, idx) {
panel.log(`开始处理${typeText}:${item.querySelector('h2')?.innerText || ''}`);
item.click();
await Utils.sleep(1200);
// 检查是否开启自动评论功能
const featureFlags = Store.getFeatureConf();
if (!featureFlags.autoComment) {
panel.log(`${typeText}已查看,但未开启自动回复功能`);
idx++;
this.updateProgress(this.outside, idx);
if (haltIfNoAutoSwitch(`${typeText}已查看`)) {
this.shouldStop = true;
return idx;
}
history.back();
await Utils.sleep(1000);
return idx;
}
// 开启了自动评论功能,执行评论逻辑
window.scrollTo(0, document.body.scrollHeight);
await Utils.sleep(800);
window.scrollTo(0, 0);
const commentSelectors = ['#new_discuss .new_discuss_list .cont_detail', '.new_discuss_list dd .cont_detail', '.cont_detail.word-break'];
let firstComment = '';
for (let retry = 0; retry < 30 && !firstComment; retry++) {
for (const sel of commentSelectors) {
const list = document.querySelectorAll(sel);
for (const node of list) {
if (node?.innerText?.trim()) {
firstComment = node.innerText.trim();
break;
}
}
if (firstComment) break;
}
if (!firstComment) await Utils.sleep(500);
}
if (!firstComment) {
panel.log('未找到评论内容,跳过该项');
} else {
const input = document.querySelector('.el-textarea__inner');
if (input) {
input.value = firstComment;
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
await Utils.sleep(800);
const sendBtn = document.querySelector('.el-button.submitComment') ||
document.querySelector('.publish_discuss .postBtn button') ||
document.querySelector('.el-button--primary');
if (sendBtn && !sendBtn.disabled && !sendBtn.classList.contains('is-disabled')) {
sendBtn.click();
panel.log(`已在${typeText}区发表评论`);
} else {
panel.log('发送按钮不可用或不存在');
}
} else {
panel.log('未找到评论输入框,跳过');
}
}
idx++;
this.updateProgress(this.outside, idx);
if (haltIfNoAutoSwitch(`${typeText}已处理`)) {
this.shouldStop = true;
return idx;
}
history.back();
await Utils.sleep(1000);
return idx;
}
async handleHomework(item, idx) {
const featureFlags = Store.getFeatureConf();
if (!featureFlags.autoAI) {
panel.log('已关闭AI自动答题,跳过该项');
idx++;
this.updateProgress(this.outside, idx);
return idx;
}
const mode = Solver.resolveAnswerMode();
panel.log(mode === 'vision' ? '进入作业,启动 截图直传 + AI' : '进入作业,启动 OCR + AI');
item.click();
await Utils.sleep(1500);
let i = 0;
const maxRetry = 3; // 最大重试次数
while (true) {
const items = document.querySelectorAll('.subject-item.J_order');
if (i >= items.length) {
panel.log(`所有题目处理完毕,共 ${items.length} 题,准备交卷`);
break;
}
const listItem = items[i];
listItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
listItem.click();
await Utils.sleep(1800);
const disabled = document.querySelectorAll('.el-button.el-button--info.is-disabled.is-plain');
if (disabled.length > 0) {
panel.log(`第 ${i + 1} 题已完成,跳过...`);
i++;
continue;
}
const targetEl = document.querySelector('.item-type')?.parentElement || document.querySelector('.item-body');
let optionCount = 0;
const listContainer = targetEl?.querySelector('.list-inline.list-unstyled-radio') ||
targetEl?.querySelector('.list-unstyled.list-unstyled-radio') ||
targetEl?.querySelector('ul.list');
if (listContainer) optionCount = listContainer.querySelectorAll('li').length;
const questionInput = await Solver.prepareQuestion(targetEl, mode);
if (questionInput) {
let retryCount = 0;
let success = false;
while (retryCount < maxRetry && !success) {
try {
if (retryCount > 0) {
panel.log(`🔄 第 ${i + 1} 题重试 ${retryCount}/${maxRetry}...`);
}
panel.log('🤖 请求 AI 获取答案...');
const aiText = await Solver.askAI(questionInput, optionCount);
const result = await Solver.autoSelectAndSubmit(aiText, targetEl);
if (!result.selected) throw new Error('未提取到有效答案');
success = true;
} catch (err) {
retryCount++;
panel.log(`AI 答题失败:${err}`);
if (retryCount < maxRetry) {
panel.log(`等待 5 秒后重试...`);
await Utils.sleep(5000);
} else {
panel.log(`⚠️ 第 ${i + 1} 题重试 ${maxRetry} 次后仍失败,跳过`);
}
}
}
}
await Utils.sleep(1500);
i++;
}
idx++;
this.updateProgress(this.outside, idx);
if (haltIfNoAutoSwitch('当前作业处理完成')) {
this.shouldStop = true;
return idx;
}
history.back();
await Utils.sleep(1200);
return idx;
}
async handleClassroom(course) {
panel.log('进入课堂模式...');
course.click();
await Utils.sleep(5000);
const iframe = document.querySelector('iframe.lesson-report-mobile');
if (!iframe || !iframe.contentDocument) {
panel.log('未找到课堂 iframe,跳过');
this.updateProgress(this.outside + 1, 0);
return;
}
const video = iframe.contentDocument.querySelector('video');
const audio = iframe.contentDocument.querySelector('audio');
if (video) {
Player.applySpeed(video, true);
await Player.waitForEnd(video);
}
if (!Session.isStopped() && audio) {
Player.applySpeed(audio, true);
await Player.waitForEnd(audio);
}
if (Session.isStopped()) return;
this.updateProgress(this.outside + 1, 0);
if (haltIfNoAutoSwitch('当前课堂内容播放完成')) {
this.shouldStop = true;
return;
}
history.go(-1);
await Utils.sleep(1200);
}
// 等待课件视频播放完毕;播放器被关闭(弹窗关闭/元素销毁)时自动重新打开
async waitCoursewareVideo() {
const deadline = await Utils.getDDL();
const start = Date.now();
let boundVideo = null;
let stopObserve = () => { };
let reopenAttempts = 0;
try {
while (Date.now() - start < deadline && !Session.isStopped()) {
Utils.dismissPopups();
const video = document.querySelector('video');
const display = document.querySelector('.xt_video_player_current_time_display');
if (!video) {
// 播放器被关闭或视频元素被销毁,重新打开视频框
const videoBox = document.querySelector('.video-box');
if (videoBox && !videoBox.innerText.includes('已完成')) {
panel.log('播放器被关闭,正在重新打开');
videoBox.click();
boundVideo = null;
}
reopenAttempts++;
if (reopenAttempts >= 4) {
panel.log('播放器恢复失败,刷新页面重试');
location.reload();
return false;
}
await Utils.sleep(2000);
continue;
}
reopenAttempts = 0;
if (!display) {
// 播放器加载中,等待渲染
await Utils.sleep(800);
continue;
}
if (video !== boundVideo) {
stopObserve();
Player.applySpeed();
Player.mute();
boundVideo = video;
stopObserve = Player.blockPause(video);
}
const times = display.innerText || '';
const [nowTime, totalTime] = times.split(' / ');
if (nowTime && totalTime && nowTime === totalTime) return true;
await Utils.sleep(800);
}
return false;
} finally {
stopObserve();
}
}
async handleCourseware(course) {
const tableData = course.parentNode?.parentNode?.parentNode?.__vue__?.tableData;
const deadlinePassed = (tableData?.deadline || tableData?.end) ? (tableData.deadline < Date.now() || tableData.end < Date.now()) : false;
if (deadlinePassed) {
panel.log(`${course.querySelector('h2')?.innerText || '课件'} 已结课,跳过`);
this.updateProgress(this.outside + 1, 0);
return;
}
course.click();
await Utils.sleep(3000);
// 检测"查看课件"按钮(课件概况页专用)
const checkBtn = document.querySelector('.ppt_img_box .check') || document.querySelector('p.check');
if (checkBtn && checkBtn.innerText?.trim() === '查看课件') {
panel.log('检测到"查看课件"按钮,正在点击...');
checkBtn.click();
await Utils.sleep(2000);
}
const classType = document.querySelector('.el-card__header')?.innerText || '';
const className = document.querySelector('.dialog-header')?.firstElementChild?.innerText || '课件';
if (classType.includes('PPT')) {
const slides = document.querySelector('.swiper-wrapper')?.children || [];
panel.log(`开始播放 PPT:${className}`);
for (let i = 0; i < slides.length; i++) {
if (Session.isStopped()) return;
slides[i].click();
panel.log(`${className}:第 ${i + 1} 张`);
await Utils.sleep(Config.pptInterval);
}
await Utils.sleep(Config.pptInterval);
const videoBoxes = document.querySelectorAll('.video-box');
if (videoBoxes?.length) {
panel.log('PPT 中有视频,继续播放');
for (let i = 0; i < videoBoxes.length; i++) {
if (Session.isStopped()) return;
if (videoBoxes[i].innerText === '已完成') {
panel.log(`第 ${i + 1} 个视频已完成,跳过`);
continue;
}
videoBoxes[i].click();
await Utils.sleep(2000);
await this.waitCoursewareVideo();
}
}
panel.log(`${className} 已播放完毕`);
} else {
const videoBox = document.querySelector('.video-box');
if (videoBox) {
videoBox.click();
await Utils.sleep(1800);
await this.waitCoursewareVideo();
panel.log(`${className} 视频播放完毕`);
}
}
if (Session.isStopped()) return;
this.updateProgress(this.outside + 1, 0);
if (haltIfNoAutoSwitch('当前课件播放完成')) {
this.shouldStop = true;
return;
}
history.back();
await Utils.sleep(1000);
}
}
// ---- pro/lms 旧版(仅做转发) ----
class ProOldRunner {
run() {
panel.log('准备打开新标签页...');
const leafDetail = document.querySelectorAll('.leaf-detail');
let classCount = Store.getProClassCount() - 1;
while (leafDetail[classCount] && !leafDetail[classCount].firstChild.querySelector('i').className.includes('shipin')) {
classCount++;
Store.setProClassCount(classCount + 1);
panel.log('课程不属于视频,已跳过');
}
leafDetail[classCount]?.click();
}
}
// ---- pro/lms 新版(主要逻辑) ----
class ProNewRunner {
async run() {
preventScreenCheck();
let classCount = Store.getProClassCount();
while (!Session.isStopped()) {
panel.log(`准备播放第 ${classCount} 集...`);
await Utils.sleep(2000);
const className = document.querySelector('.header-bar')?.firstElementChild?.innerText || '';
const classType = document.querySelector('.header-bar')?.firstElementChild?.firstElementChild?.getAttribute('class') || '';
const classStatus = document.querySelector('#app > div.app_index-wrapper > div.wrap > div.viewContainer.heightAbsolutely > div > div > div > div > section.title')?.lastElementChild?.innerText || '';
if (classType.includes('tuwen') && !classStatus.includes('已读')) {
panel.log(`正在阅读:${className}`);
await Utils.sleep(2000);
} else if (classType.includes('taolun')) {
panel.log(`讨论区暂不自动发帖,${className}`);
await Utils.sleep(2000);
} else if (classType.includes('shipin') && !classStatus.includes('100%')) {
panel.log(`2s 后开始播放:${className}`);
await Utils.sleep(2000);
let statusTimer;
let videoTimer;
try {
statusTimer = setInterval(() => {
const status = document.querySelector('#app > div.app_index-wrapper > div.wrap > div.viewContainer.heightAbsolutely > div > div > div > div > section.title')?.lastElementChild?.innerText || '';
if (status.includes('100%') || status.includes('99%') || status.includes('98%') || status.includes('已完成')) {
panel.log(`${className} 播放完毕`);
clearInterval(statusTimer);
statusTimer = null;
}
}, 200);
const videoWaitStart = Date.now();
videoTimer = setInterval(() => {
if (Session.isStopped()) return;
const video = document.querySelector('video');
if (video) {
setTimeout(() => {
if (Session.isStopped()) return;
Player.applySpeed();
Player.mute();
Player.blockPause(video); // 不接管清理:暂停拦截随页面持续生效,跨集数不中断
}, 2000);
clearInterval(videoTimer);
videoTimer = null;
} else if (Date.now() - videoWaitStart > 20000) {
location.reload();
}
}, 5000);
await Utils.sleep(8000);
await Utils.poll(() => {
const status = document.querySelector('#app > div.app_index-wrapper > div.wrap > div.viewContainer.heightAbsolutely > div > div > div > div > section.title')?.lastElementChild?.innerText || '';
return status.includes('100%') || status.includes('99%') || status.includes('98%') || status.includes('已完成');
}, { interval: 1000, timeout: await Utils.getDDL() });
} finally {
if (statusTimer) clearInterval(statusTimer);
if (videoTimer) clearInterval(videoTimer);
}
} else if (classType.includes('zuoye')) {
panel.log(`进入作业:${className}(暂无自动答题)`);
await Utils.sleep(2000);
} else if (classType.includes('kaoshi')) {
panel.log(`进入考试:${className}(不会自动答题)`);
await Utils.sleep(2000);
} else if (classType.includes('ketang')) {
panel.log(`进入课堂:${className}(暂无自动功能)`);
await Utils.sleep(2000);
} else {
panel.log(`已看过:${className}`);
await Utils.sleep(2000);
}
if (Session.isStopped()) return;
panel.log(`第 ${classCount} 集播放完毕`);
classCount++;
Store.setProClassCount(classCount);
const nextBtn = document.querySelector('.btn-next');
if (nextBtn) {
if (haltIfNoAutoSwitch(`第 ${classCount - 1} 集播放完毕`)) break;
const event1 = new Event('mousemove', { bubbles: true });
event1.clientX = 9999;
event1.clientY = 9999;
nextBtn.dispatchEvent(event1);
nextBtn.dispatchEvent(new Event('click'));
} else {
localStorage.removeItem(Config.storageKeys.proClassCount);
panel.log('课程播放完毕 🎉');
Store.clearPendingAutoStart();
panel.resetStartButton('开始刷课');
break;
}
}
}
}
// ---- ai-workspace 新版学习空间 ----
class AiWorkspaceRunner {
// 获取要跳转回去的目标地址
getReturnUrl() {
const pending = Store.getPendingAutoStart();
const route = AiWorkspace.getRoute();
if (!pending || !route) return '';
if (pending.classroomId !== route.classroomId) return '';
console.log(`returnUrl:${pending.returnUrl}`)
return pending.returnUrl || '';
}
async autoSelect() {
if (Session.isStopped()) return;
// 进入ai - workspace的方式有两种:可以处理两种不同的逻辑,增加兼容性
const returnUrl = this.getReturnUrl()
// 1. 从传统的 v2 - pro / lms 的目录新开标签页进入(开始刷课)的
if (returnUrl) {
await this.returnToSource(returnUrl)
} else {
// 2. 直接从ai - workspac页面进入(开始刷课)的
panel.log("检测到是从ai - workspac页面点击开始刷课");
this.source = document.querySelectorAll('.nav-item-leaf-box'); // ai-workspace 课程列表
this.activateIndex = Array.from(this.source).findIndex(el => el.firstChild.classList.contains("is-active")) // 现在正在刷第几个(从0开始)
await this.handleNext(this.activateIndex + 1)
}
}
async returnToSource(returnUrl) {
panel.log('媒体播放完成,返回课程目录页继续匹配');
await Utils.sleep(1200);
// 取回打开本页的课程目录窗口(跨域 opener 不可用)
let sourceWindow = null;
try {
if (window.opener && !window.opener.closed && window.opener.location.origin === location.origin) {
sourceWindow = window.opener;
}
} catch (_) { }
if (sourceWindow) {
try {
sourceWindow.location.href = returnUrl;
sourceWindow.focus();
window.close();
return true;
} catch (e) {
console.error("跳转父窗口异常", e);
}
}
// if (location.href !== returnUrl) {
// location.href = returnUrl;
// } else {
// history.back();
// }
// return true;
}
async handleMedia(route) {
const title = AiWorkspace.getActiveLeafTitle() || `${route.type} ${route.leafId}`;
panel.log(`开始播放:${title}`);
const ready = await Utils.poll(() => Boolean(AiWorkspace.getMedia()), { interval: 500, timeout: 20000 });
if (Session.isStopped()) return false;
let media = AiWorkspace.getMedia();
if (!ready || !media) {
panel.log('未找到视频/音频元素,停止当前轮次');
return false;
}
const playbackState = { completed: false };
const shouldResume = () => !playbackState.completed;
let stopObserve = () => { };
if (media.tagName.toLowerCase() === 'video') {
Player.applySpeed(media);
Player.mute();
stopObserve = Player.blockPause(media, shouldResume);
} else {
Player.applySpeed(media, true);
}
const stopKeepAlive = AiWorkspace.keepAlive(shouldResume);
const rateConf = Store.getRateConf();
panel.log(`已接管播放器:${media.tagName.toLowerCase()},目标倍速 ${rateConf.targetRate}x,静音开启;按钮设速:${rateConf.buttonSetEnabled ? '开' : '关'} 直设倍速:${rateConf.directSetEnabled ? '开' : '关'} 倍速保活:${rateConf.keepAliveEnabled ? '开' : '关'} 回写拦截:${rateConf.ratechangeBlockEnabled ? '开' : '关'}`);
try {
let startTime = Number(media.currentTime || 0);
const started = await Utils.poll(() => {
const currentMedia = AiWorkspace.getMedia();
if (currentMedia) media = currentMedia;
if (!media) return false;
const currentTime = Number(media.currentTime || 0);
return currentTime > startTime + 0.5 || (!media.paused && media.readyState >= 2 && currentTime > startTime + 0.2);
}, { interval: 500, timeout: 15000 });
if (!started) {
if (!Session.isStopped()) panel.log('未确认到视频实际开始播放,停止当前轮次');
return false;
}
startTime = Number(media.currentTime || 0);
let resolveEnded;
const endedPromise = new Promise(resolve => {
resolveEnded = resolve;
});
const onEnded = () => {
playbackState.completed = true;
resolveEnded(true);
};
media.addEventListener('ended', onEnded);
const done = await Promise.race([
endedPromise,
Utils.poll(() => {
if (playbackState.completed) return true;
const currentMedia = AiWorkspace.getMedia();
if (currentMedia) media = currentMedia;
if (AiWorkspace.isPlayerDone(media, { startTime, minPlayedDelta: 3 })) {
playbackState.completed = true;
return true;
}
return false;
}, { interval: 1000, timeout: await Utils.getDDL() })
]);
media.removeEventListener('ended', onEnded);
playbackState.completed = true;
if (!done) {
if (!Session.isStopped()) panel.log('等待播放完成超时,停止当前轮次');
return false;
}
} finally {
stopObserve();
stopKeepAlive();
}
panel.log(`${title} 播放完成`);
return true;
}
// 提交后等待页面自动切到下一题并完成渲染:期间不点击任何切题按钮,避免重复切题触发风控
async waitNextQuestion(previousFingerprint, timeout = 15000) {
if (!previousFingerprint) return false;
let last = '';
return Utils.poll(() => {
AiWorkspace.confirmSubmitDialog();
const container = AiWorkspace.getExerciseContainer();
if (!container) {
last = '';
return false;
}
const fingerprint = AiWorkspace.getExerciseFingerprint(container);
if (!fingerprint || fingerprint === previousFingerprint) {
last = '';
return false;
}
// 连续两次读数一致才认为新题已渲染完成,避免在题目还在切换时开始作答
const ready = fingerprint === last;
last = fingerprint;
return ready;
}, { interval: 500, timeout });
}
// 当前题已完成(例如中途开始刷课停在已答题)才单击一次下一个未作答题号;
// 正常提交后不调用这里,避免页面自动跳题后又多点一次
async openNextUnansweredTab(previousFingerprint) {
if (Session.isStopped()) return false;
const container = AiWorkspace.getExerciseContainer();
const tabs = AiWorkspace.getExerciseQuestionTabs(container);
if (!tabs.length) return false;
const isAnsweredTab = tab => /primary/.test(tab.className) || Boolean(tab.querySelector('.icon-status.success'));
const activeIndex = tabs.findIndex(tab => /active|current|selected|is-active/.test(tab.className));
const ordered = activeIndex >= 0
? [...tabs.slice(activeIndex + 1), ...tabs.slice(0, activeIndex)]
: tabs;
const pending = ordered.find(tab => !isAnsweredTab(tab));
if (!pending) return false;
panel.log('当前题目已完成,切换到下一道未作答题目');
await Utils.sleep(300 + Math.random() * 300);
await Utils.humanClick(pending);
return this.waitNextQuestion(previousFingerprint, 15000);
}
async solveExerciseQuestion(root, label = '', { fingerprint = '', cache = null } = {}) {
let questionRoot = AiWorkspace.getExerciseQuestionBody(root);
if (!questionRoot) {
panel.log('未找到题目容器,停止当前轮次');
return { ok: false, submitted: false, skipped: false, aiFailed: false, fingerprint };
}
if (AiWorkspace.isExerciseAnswered(questionRoot.closest?.('.container-problem') || root)) {
panel.log(`${label || '当前题目'} 已完成,跳过`);
return { ok: true, submitted: false, skipped: true, aiFailed: false, fingerprint };
}
// 选项只定位一次:选项数量、点选都复用同一批元素
let options = AiWorkspace.getExerciseOptions(questionRoot);
if (!options.length) {
// 刚切到新题时选项可能仍在渲染,短暂等待后重新取样,避免把渲染中的题目当成“无选项”跳过
await Utils.poll(() => {
const latestRoot = AiWorkspace.getExerciseContainer() || root;
return AiWorkspace.getExerciseOptions(AiWorkspace.getExerciseQuestionBody(latestRoot)).length > 0;
}, { interval: 300, timeout: 2000 });
if (Session.isStopped()) {
return { ok: false, submitted: false, skipped: false, aiFailed: false, fingerprint };
}
const latestRoot = AiWorkspace.getExerciseContainer() || root;
questionRoot = AiWorkspace.getExerciseQuestionBody(latestRoot) || questionRoot;
options = AiWorkspace.getExerciseOptions(questionRoot);
}
if (!options.length) {
panel.log(`${label || '当前题目'} 未找到选项,跳过`);
return { ok: false, submitted: false, skipped: true, aiFailed: false, fingerprint };
}
const cacheKey = AiWorkspace.normalizeText(questionRoot.innerText || '') || fingerprint;
let aiText = cache?.get(cacheKey) || '';
if (aiText) {
panel.log(`${label || '当前题目'} 命中答案缓存,跳过 AI 请求`);
} else {
const mode = Solver.resolveAnswerMode();
const questionInput = await Solver.prepareQuestion(questionRoot, mode);
if (!questionInput) {
panel.log(`${label || '当前题目'} ${mode === 'vision' ? '截图失败' : 'OCR 结果过短'},跳过`);
return { ok: false, submitted: false, skipped: true, aiFailed: false, fingerprint };
}
const maxRetry = 3;
for (let retryCount = 0; retryCount < maxRetry && !aiText; retryCount++) {
try {
if (retryCount > 0) panel.log(`${label || '当前题目'} 重试 ${retryCount}/${maxRetry - 1}`);
panel.log('🤖 请求 AI 获取答案...');
aiText = await Solver.askAI(questionInput, options.length);
} catch (err) {
panel.log(`AI 答题失败:${err}`);
if (retryCount < maxRetry - 1) await Utils.sleep(3000);
}
}
if (!aiText) {
panel.log(`⚠️ ${label || '当前题目'} 未获取到答案,跳过`);
return { ok: false, submitted: false, skipped: false, aiFailed: true, fingerprint };
}
cache?.set(cacheKey, aiText);
}
if (Session.isStopped()) {
return { ok: false, submitted: false, skipped: false, aiFailed: false, fingerprint };
}
const result = await Solver.autoSelectAndSubmit(aiText, questionRoot, options);
if (!result.selected) {
// 无法把答案映射到选项:清掉缓存,避免下次仍用同一份无效答案
cache?.delete(cacheKey);
panel.log(`⚠️ ${label || '当前题目'} 未能匹配选项,跳过`);
return { ok: false, submitted: false, skipped: false, aiFailed: true, fingerprint };
}
return {
ok: true,
submitted: result.submitted,
skipped: false,
aiFailed: false,
fingerprint: result.fingerprint || fingerprint
};
}
async handleExercise(route) {
const featureFlags = Store.getFeatureConf();
if (!featureFlags.autoAI) {
panel.log('已关闭 AI 自动答题,作业将直接跳过');
return true;
}
// 未配置有效 Key 时直接跳过,避免每题都截图/OCR 后才发现请求必然失败
const aiConf = Store.getAIConf();
if (!aiConf.key || aiConf.key.includes('sk-xxxx')) {
panel.log('⚠️ 未配置有效的 API Key,本次作业跳过自动作答');
return true;
}
const ready = await Utils.poll(() => Boolean(AiWorkspace.getExerciseContainer()), { interval: 500, timeout: 20000 });
if (Session.isStopped()) return true;
if (!ready) {
panel.log('未找到作业容器,停止当前轮次');
return false;
}
panel.log(`开始处理作业:${AiWorkspace.getActiveLeafTitle() || route.leafId}`);
// 本次作业内的答案缓存:页面回退或重新进入同一题时不再重复请求 AI
const answerCache = new Map();
const processed = new Set();
const maxQuestions = 100; // 防御题号不变化的异常页面导致无限作答
let currentIndex = 0;
for (let i = 0; i < maxQuestions; i++) {
if (Session.isStopped()) return true;
const currentRoot = AiWorkspace.getExerciseContainer();
if (!currentRoot) break;
const fingerprint = AiWorkspace.getExerciseFingerprint(currentRoot);
if (!fingerprint) break;
if (processed.has(fingerprint)) {
panel.log('题目内容未再变化,作业处理结束');
break;
}
const tabs = AiWorkspace.getExerciseQuestionTabs(currentRoot);
if (i === 0 && tabs.length) panel.log(`检测到题目索引 ${tabs.length} 个`);
const activeIndex = tabs.findIndex(tab => /active|current|selected|is-active/.test(tab.className));
if (activeIndex >= 0) currentIndex = activeIndex;
const activeTab = tabs[currentIndex];
const label = AiWorkspace.normalizeText(activeTab?.innerText || '') || `第 ${currentIndex + 1} 题`;
const result = await this.solveExerciseQuestion(currentRoot, label, { fingerprint, cache: answerCache });
if (Session.isStopped()) return true;
processed.add(fingerprint);
const baseline = result.fingerprint || fingerprint;
if (result.submitted) {
// 站点提交成功后会自动切到下一题:这里只等待新题加载完成,不再点任何切题按钮
if (await this.waitNextQuestion(baseline, 15000)) {
panel.log('页面已自动切换到下一题');
if (activeIndex < 0 && tabs.length) currentIndex += 1;
continue;
}
if (Session.isStopped()) return true;
panel.log('提交后未检测到页面自动切题,已停止继续作答以避免重复切题');
break;
}
if (result.skipped) {
// 当前题已完成或不是可作答题型:单击一次下一道未作答题号继续
if (await this.openNextUnansweredTab(baseline)) {
if (activeIndex < 0 && tabs.length) currentIndex += 1;
continue;
}
panel.log('没有可继续作答的题目,作业处理结束');
break;
}
panel.log('本题未提交成功,已停止继续作答以避免重复切题');
break;
}
return true;
}
// 直接在ai-workspace页面处理课程的逻辑
async handleNext(count) {
if (Session.isStopped()) return;
if (count >= this.source.length) {
panel.log('课程刷完啦 🎉');
panel.resetStartButton('刷完啦~');
Store.clearPendingAutoStart();
return;
}
this.source[count].firstChild.click();
await Utils.sleep(2000);
await this.run(false)
}
async run(preventScreenCheckSwitch = true) {
// 仅开启一次防切屏
if (preventScreenCheckSwitch) preventScreenCheck();
const route = AiWorkspace.getRoute();
if (!route) {
panel.log('当前页面已离开 ai-workspace/lms-graph');
return;
}
if (!route.leafId) {
panel.log('未能识别当前知识点');
return;
}
let ok = false;
if (route.type === 'video' || route.type === 'audio') {
ok = await this.handleMedia(route);
} else if (route.type === 'exercise') {
ok = await this.handleExercise(route);
} else {
panel.log(`当前类型为 ${route.type},当前暂不自动处理此类型,自动跳过`);
await Utils.sleep(2000);
ok = true;
}
if (Session.isStopped()) return;
if (!ok) panel.warn(Store.getFlowConf().autoSwitch ? '(该视频可能已经刷完了),即将跳过开始下一个' : '(该视频可能已经刷完了)');
// 继续下一个任务点/界面;关闭自动切换时停留当前页面,避免切换后抓取失败
if (haltIfNoAutoSwitch(ok ? '当前任务点处理完成' : '当前任务点处理结束')) return;
await this.autoSelect()
}
}
// ---- 路由 ----
// 停止刷课:结束当前会话、还原对页面/播放器的修改,并持久化停止状态(重新加载也不会自动恢复)
function stopBrushing() {
Session.stop();
Store.clearPendingAutoStart();
const restoreOnStop = Store.getFlowConf().restoreOnStop;
if (restoreOnStop) PageRestore.restoreAll();
// 释放复用的 OCR worker,避免停止后仍占用 wasm 线程与内存
Solver.resetOcrWorker();
panel.resetStartButton('开始刷课');
panel.log(restoreOnStop
? '已停止刷课:对页面/播放器的修改已还原;重新加载后不会自动恢复,点击[开始刷课]可重新启动'
: '已停止刷课:已按设置保留对页面/播放器的修改(倍速/静音等);重新加载后不会自动恢复,点击[开始刷课]可重新启动');
}
function start() {
// 显式开始刷课:清除“用户已停止”状态,之后的跨页面跳转才允许自动续跑
Session.begin();
// ---- ai-workspace获取课程根目录信息并保存(处理完一个课程重定向到根目录) ----
const classroomId = Utils.getCurrentClassroomId();
const returnUrl = Utils.returnUrl()
Store.setPendingAutoStart(classroomId, returnUrl);
const aiRoute = AiWorkspace.getRoute();
if (aiRoute) {
panel.log(`正在匹配处理逻辑:ai-workspace/lms-graph/${aiRoute.type}`);
new AiWorkspaceRunner().run();
return;
}
// ---- ai-workspace end
const url = location.host;
const path = location.pathname.split('/');
const matchURL = `${url}${path[0]}/${path[1]}/${path[2]}`;
panel.log(`正在匹配处理逻辑:${matchURL}`);
if (matchURL.includes('yuketang.cn/v2/web') || matchURL.includes('gdufemooc.cn/v2/web')) {
new V2Runner().run();
} else if (matchURL.includes('yuketang.cn/pro/lms') || matchURL.includes('gdufemooc.cn/pro/lms')) {
if (document.querySelector('.btn-next')) {
new ProNewRunner().run();
} else {
new ProOldRunner().run();
}
} else {
panel.resetStartButton('开始刷课');
panel.log('当前页面非刷课页面,应匹配 */v2/web/*、*/pro/lms/* 或 */ai-workspace/lms-graph/*');
}
}
// ---- 启动 ----
async function boot() {
// 主要是规避firefox会创建多个iframe的问题
if (window.top !== window.self) return;
await Utils.waitForMountTarget();
try {
panel = createPanel();
panel.log(`雨课堂刷课助手 v${Config.version} 已加载`);
panel.setStartHandler(start);
panel.setStopHandler(stopBrushing);
const pendingAutoStart = Store.getPendingAutoStart();
const currentClassroomId = Utils.getCurrentClassroomId();
if (
pendingAutoStart
&& !Session.isStopped()
&& Utils.isSupportedLearningPage()
&& currentClassroomId
&& pendingAutoStart.classroomId === currentClassroomId
) {
panel.log(`检测到跨页面跳转,自动恢复刷课:课堂 ${currentClassroomId}`);
setTimeout(() => panel.start(), 1200);
}
} catch (err) {
console.error('面板初始化失败:', err);
}
}
boot();
})();