Files
yun-xue-tang-assistant/runner/page.mjs
T
void ae117222df feat: v2.8.0 无头运行器、考试自动交卷、改为退避重试不跳课
新增无头运行能力,解决 Linux 无图形化服务器上无法常驻的问题;同时改掉
"遇到考试课/无进展课就跳过"的策略,改为在同门课上退避重试。

- runner/:自己起无头 Chromium,用 CDP 把构建产物注入页面主世界(等价
  @grant none),不装插件、不需要桌面环境或 Xvfb;含浏览器探测与启动参数、
  持久化 profile、陈旧 SingletonLock 清理、优雅退出、日志轮转、启动预检
- runner.config.mjs / start-headless.cmd:通用配置 + Windows 一键入口;
  凭据只走 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD 环境变量
- src/exam.js:含考试章节的课程自动进考试 → 开始/继续 → 空卷提交 → 确定,
  交卷后靠平台记账推进课程;maxExamTries 限制同门课交卷次数,防不记账时死循环
- 去掉跳过与黑名单:没学完就退避重试(30s 起翻倍,最长 5 分钟),
  同门课超过 maxCourseRetries 次才停整轮并提示,替代原 maxConsecutiveFailures
- 每完成一门都重新拉列表接口取平台实时状态再选下一门,避免用陈旧队列
- 学习进度改存 sessionStorage(yun-xue-tang-run-state-v3),整页跳转/刷新可续;
  运行开关不跨会话,浏览器重启后必须显式开跑
- dev/:新增 real-cdp / real-run / real-test / real-e2e 实跑脚本与 check.mjs
  统一静态检查(JS 22 + 批处理 2),替代逐文件 node --check
- docs/evidence/headless-linux-evidence.txt + 实跑截图,README 补无头部署章节
2026-10-25 23:04:40 +08:00

150 lines
6.0 KiB
JavaScript

// 页面侧接口:所有「注入后要调用的 JS 表达式」集中在这里,外加把 CDP 的求值包成
// 好用的 page 对象。改脚本内部 API 时只需要动这一个文件。
//
// page.evalJS(expr) 求值并返回值(异常会抛出)
// page.json(expr) 求值并把返回的 JSON 字符串解析成对象
// page.tryEval(expr) 求值但吞掉异常,返回 undefined(页面正在跳转时用)
import { sleep } from './cdp.mjs';
/**
* @param {object} cdp cdp.mjs 的客户端
*/
export function createPage(cdp) {
const evalJS = async (expr) => {
const r = await cdp.send('Runtime.evaluate', {
expression: expr, returnByValue: true, awaitPromise: true, userGesture: true,
});
if (r.exceptionDetails) {
const d = r.exceptionDetails;
throw new Error((d.exception && d.exception.description) || d.text);
}
return r.result.value;
};
const json = async (expr) => JSON.parse(await evalJS(expr));
const tryEval = async (expr) => {
try { return await evalJS(expr); } catch (e) { return undefined; }
};
return { evalJS, json, tryEval };
}
/** 环境自检:脚本是否注入、面板是否渲染、视频编解码能力、中文字体 */
export const EXPR_SELF_CHECK = `JSON.stringify((function () {
var a = window.__yunXueTangAuto;
var probe = document.createElement('video');
var codecs = {
h264: probe.canPlayType('video/mp4; codecs="avc1.42E01E"') || '',
aac: probe.canPlayType('audio/mp4; codecs="mp4a.40.2"') || '',
vp9: probe.canPlayType('video/webm; codecs="vp9"') || '',
};
return {
url: location.href,
ua: navigator.userAgent,
api: typeof a,
version: (document.getElementById('yun-xue-tang-version') || {}).textContent || '',
panels: document.querySelectorAll('#yun-xue-tang-panel').length,
panelVisible: (function () {
var el = document.getElementById('yun-xue-tang-panel');
if (!el) return false;
var r = el.getBoundingClientRect();
return r.width > 0 && r.height > 0;
})(),
isLoginPage: a ? a.isLoginPage() : null,
route: a ? a.route() : null,
codecs: codecs,
fonts: (function () {
// 中文字体缺失不影响逻辑(靠 DOM 文本匹配),仅影响截图观感
var c = document.createElement('canvas').getContext('2d');
if (!c) return 'n/a';
c.font = '16px sans-serif';
var w = c.measureText('云学堂助手').width;
var w2 = c.measureText('abcd').width;
return w > 0 && w2 > 0 ? 'ok' : 'unknown';
})(),
};
})())`;
/** 看护循环:判断是否需要注入 / 是否在登录页 / 当前 --max 生效值 */
export const EXPR_WATCH = `JSON.stringify({
href: location.href,
ready: typeof window.__yunXueTangAuto === 'object',
onLogin: !!(window.__yunXueTangAuto && window.__yunXueTangAuto.isLoginPage()),
hasPwd: !!document.querySelector('input[type=password]'),
bodyLen: (document.body && document.body.innerText || '').length,
maxCourses: (window.__yunXueTangAuto && window.__yunXueTangAuto.CFG) ? window.__yunXueTangAuto.CFG.maxCourses : null,
})`;
/** 主监控快照:课程、课时、进度、倒计时、视频状态 */
export const EXPR_SNAPSHOT = `JSON.stringify((function () {
var a = window.__yunXueTangAuto;
if (!a) return { noApi: true, href: location.href };
var v = document.querySelector('video, audio');
var items = [];
try { items = a.lessonItems(); } catch (e) {}
return {
href: location.href,
route: a.route(),
running: a.S.batchRunning,
runFinished: a.S.batchFinished,
phase: a.S.coursePhase,
completed: a.S.completedThisRun,
pendingRetries: Object.keys(a.S.courseRetries || {}).length,
course: a.S.activeCourse ? a.S.activeCourse.title : null,
lesson: (a.readActiveLessonKey ? a.readActiveLessonKey() : ''),
lessons: items.length,
summary: a.readSummary(),
countdown: a.readCountdown(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
doneCount: Object.keys(a.S.completedTitles || {}).length,
retryCount: Object.keys(a.S.courseRetries || {}).length,
retryWait: (a.retryWaitSeconds ? a.retryWaitSeconds() : 0),
retryTitle: a.R.retryTitle || '',
video: v ? {
t: Math.round(v.currentTime), d: Math.round(v.duration || 0),
paused: v.paused, err: v.error ? v.error.code : 0, src: v.currentSrc ? 1 : 0,
} : null,
};
})())`;
/** 会话结尾的累计统计 */
export const EXPR_FINAL_STATS = `JSON.stringify((function () {
var a = window.__yunXueTangAuto;
if (!a) return {};
return {
completed: a.S.completedThisRun,
doneCount: Object.keys(a.S.completedTitles || {}).length,
retryCount: Object.keys(a.S.courseRetries || {}).length,
};
})())`;
/** 收尾:暂停媒体、停批量、存进度(浏览器关掉前调用) */
export const EXPR_PAUSE_AND_SAVE = `(function () {
var a = window.__yunXueTangAuto;
if (a) { try { a.pauseAllMedia(); a.S.batchRunning = false; a.save(); } catch (e) {} }
return true;
})()`;
/** 把 maxCourses 同步到页面(0 = 不限,必须一并推送) */
export const exprSetMaxCourses = (max) =>
`(function(){ var a = window.__yunXueTangAuto; if (a && a.CFG) a.CFG.maxCourses = ${Number(max)}; return true; })()`;
/** 启动 / 接续批量刷课,同时同步「优先短课程」偏好 */
export const exprStartBatch = (preferShort) => `(function () {
var a = window.__yunXueTangAuto;
try { localStorage.setItem('yun-xue-tang-prefer-short', '${preferShort ? '1' : '0'}'); } catch (e) {}
a.state.preferShortCourses = ${preferShort ? 'true' : 'false'};
a.startBatch();
return true;
})()`;
/** 登录页:填账号密码、勾协议、点登录并接着刷课 */
export const exprAutoLogin = (usr, pwd) => `(function () {
var a = window.__yunXueTangAuto;
if (!a) return 'no-api';
var ok = a.fillLoginForm(${JSON.stringify(usr)}, ${JSON.stringify(pwd)});
try { a.checkLoginAgreement(); } catch (e) {}
a.doLoginAndStart();
return ok ? 'filled' : 'no-fields';
})()`;
export { sleep };