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 补无头部署章节
This commit is contained in:
void committed 2026-10-25 23:04:40 +08:00
1 parent 8193326b70
commit ae117222df
47 files changed
+6198 -837

No files matched your search

+82 -3
View File
@@ -13,9 +13,10 @@
| `serve.mjs` | 本地 HTTP 服务,向浏览器提供源码与版本哈希(127.0.0.1:8899) |
| `dev-loader.user.js` | Tampermonkey 里的薄加载器,轮询版本、释放旧实例、注入新实例 |
| `start-dev.cmd` | 双击启动服务 |
| `check.mjs` | `npm run check` 的实现:自动遍历 `runner/`、`dev/` 与顶层文件跑 `node --check`,同时检查 `.cmd` 必须是纯 ASCII + CRLF(cmd.exe 逐字节按代码页读批处理,中文和裸 LF 会让行偏移错位);新增模块不用再手改命令 |
原理:加载器每 1 秒请求 `/version`,发现哈希变化就调用旧实例暴露的
`window.__ytDispose()`(清定时器 / 监听器 / 面板),再把新源码以 `<script>` 形式注入页面主世界。
`window.__yunXueTangDispose()`(清定时器 / 监听器 / 面板),再把新源码以 `<script>` 形式注入页面主世界。
因为脚本依赖页面里的 `__vue__`(登录组件),注入必须发生在主世界,不能走普通沙箱。
## 一次性安装
@@ -32,10 +33,88 @@
- 改完 `src/` 下的模块保存 → `npm run build:watch` 自动重新打包,约 1 秒内页面控制台打印
`[云学堂·热加载] 热更新 → <新哈希>`,面板会重建,视频播放不中断。
- 批量刷课的进度存在 `localStorage`(`yt-batch-v2`),热替换 / 刷新都不会丢。
- 列表刷课的进度存在 `localStorage`(`yun-xue-tang-batch-v2`),热替换 / 刷新都不会丢。
- 改坏了(语法错误):构建失败,加载器会拒绝注入并弹出左下角红条提示,**旧版本继续运行**,修好再保存即可。
- 想完全回到「手动刷新才生效」:把加载器里的 `MODE` 改成 `'reload'`。
## 真机测试
在**真实浏览器 + 真实云学堂页面**上验证脚本,不靠 Node 里的 DOM 桩。
```bash
npm run build # 先出产物
npm run test:real # 有界面 Chrome,能看见面板真实渲染
npm run test:real:headless # 无头模式(CI / 无人值守)
node dev/real-test.mjs --keep # 跑完不关浏览器,便于人工复核
```
三个真机脚本(`real-test` / `real-e2e` / `real-run`)会自动适配当前平台:
没有图形会话时强制 `--headless=new`(即使没传 `--headless`),并补上该平台需要的参数
(Linux:`--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage`;Windows:不弹崩溃恢复气泡),
因此可以原样在无图形化服务器 / 容器 / CI / Windows 后台里跑。平台判断复用
`runner/platform.mjs`,不在这里重复实现。
> 想在生产环境长期无头挂机(持久化登录、掉登录自动重登、崩溃自愈),用 `runner/headless.mjs`,
> 见主 README 的「无头运行(Linux / Windows 服务器)」。
原理:用独立临时用户目录启动 Chrome(不影响日常配置),开 CDP 端口后新建标签页打开
`https://kfmic.yunxuetang.cn/login.html`,把 `yun-xue-tang-assistant.user.js` 注入页面主世界
(等价 Tampermonkey `@grant none`),然后在真实 DOM 上断言:
| 断言 | 说明 |
| --- | --- |
| 面板渲染 | `#yun-xue-tang-panel` 可见、`position:fixed`、距右下各 16px、含密码框与 4 个按钮 |
| 版本号 | `#yun-xue-tang-version` = `v2.7.0`(与 package.json 一致) |
| 页面识别 | 真实登录页 `isLoginPage() === true`、`readSummary/readCountdown` 安全返回 `null` |
| 点击不崩 | 真点「一键登录并刷课」后脚本仍存活、无自身 error 日志 |
| 持久化 | 真实 `localStorage` 可读写 |
| 热替换 | `__yunXueTangDispose()` 后真实 DOM 面板移除、`__yunXueTangAuto` 被删;再注入面板唯一 |
| 路由 | SPA 内改 `location.hash` 后 `route()` 自动跟随,无需重新注入 |
| 整页重定向 | 未登录访问 `#/list` 被站点跳回登录页(新 document),脚本无残留、重注入后正常 |
产物:截图存到 `docs/screenshots/real-chrome-login.png`。
需要 Node 22+(全局 `WebSocket` / `fetch`),无需 puppeteer / playwright。
测试**只读**:不填账号密码、不点登录、不改线上数据。
## 真机登录 / 进课测试(E2E)
带**真实账号**跑完整媒体链路。凭据从环境变量读,不写进代码、不打印明文:
```bash
# 环境变量(已在当前环境配置)
# YUN_XUE_TANG_USR 员工邮箱 / 账号
# YUN_XUE_TANG_PWD 密码
npm run test:e2e # 登录 + 列表;默认只读,不碰学习进度
npm run test:e2e:play # 额外进入最短的未学完课程,采样 25 秒后立即暂停
npm run test:e2e:play -- --seconds 60
node dev/real-e2e.mjs --headless # 无头
node dev/real-e2e.mjs --keep # 跑完不关浏览器
```
覆盖的断言(`--play` 时是 19 项,否则 12 项):
| 阶段 | 断言 |
| --- | --- |
| 登录页 | 脚本注入、识别到账号/密码框、`setNativeValue` 写入真实输入框值一致、隐私政策勾选 |
| 登录 | 真点「一键登录并刷课」后**真正登录成功**(离开登录页);无脚本 error |
| 新 document | 登录是整页跳转,模拟 Tampermonkey 按 `@match` 重新注入后面板恢复 |
| 列表 | 16 张卡片(共 322 页)、`scanCards` 标题/状态解析、Vue 组件 `kngListData` 可读、`studyHours` 时长可用 |
| 进课(`--play`)| 挑**最短的未学完课程**进入(减少对真实进度影响)、`readSummary`/`readCountdown`/`lessonItems` 读到真实数据 |
| 播放(`--play`)| 真实 `<video>` 被接管:`muted=true`、`playbackRate=1`、`paused=false`、`currentTime` 真实推进 |
| 收尾 | 立即 `pauseAllMedia` + `S.batchRunning=false`,`__yunXueTangDispose()` 后面板/API 清理干净 |
行为与安全:
- 不加 `--play` 时会在登录成功后**立即停用列表刷课**(清 `yun-xue-tang-auto-start-after-login`、`S.batchRunning=false`),
避免在真实账号上意外推进课程。
- 加 `--play` 只采样默认 25 秒就暂停并释放,不会把整节课刷完;结束时会打印进度快照(如
`进入前「已完成2/3」→ 采样后「已完成2/3」`)便于核对是否被改动。
- 实测:进课 `2025坚持的力量`(273s 的第 3 节)采样 25 秒,`currentTime` 推进到 63s,进度保持 `2/3` 未变。
> 登录后收集的日志里会出现一条 `填写账号密码后,点「一键登录并刷课」`,这是
> `loginPageTick` 轮询刷新状态文案造成的噪声(发生在点击登录之前),不影响登录结果。
## 常见问题
| 现象 | 处理 |
@@ -44,7 +123,7 @@
| 改完没反应 | 看控制台是否有 `热更新` 日志;确认 `npm run build:watch` 在跑,改的是 `src/` 下的模块 |
| 页面出现两个面板 | 旧完整脚本没停用,去 Tampermonkey 停用它 |
| 端口冲突 | `node dev/serve.mjs 8900`,同时把加载器里的 `SERVER` 常量改成对应端口 |
| 服务没开也想用 | 加载器回退到上次缓存的源码(`GM_getValue('yt-dev-src')`) |
| 服务没开也想用 | 加载器回退到上次缓存的源码(`GM_getValue('yun-xue-tang-dev-src')`) |
## 关闭开发模式
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env node
/**
* 静态检查:对仓库里会直接 `node` 执行的脚本跑 `node --check`,
* 并对批处理文件做两项硬性检查(这两项一旦坏掉就极难排查):
* 1. 必须是纯 ASCII —— cmd.exe 按当前代码页逐字节读批处理,
* 多字节字符(中文)会让行偏移错位,报出 "'鍏?npm' is not recognized" 这种怪错;
* 2. 必须用 CRLF 行尾 —— 只有 LF 时 cmd.exe 会把上一行的尾部当成命令的一部分,
* 同样报出莫名其妙的 "'01' is not recognized"。
*
* 以前 package.json 的 check 脚本是一长串 `node --check a && node --check b && …`,
* 每次新增模块都要手改那行命令(漏了就默默不检查)。现在改为自动遍历目录。
*
* 用法:npm run check
*/
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
/** 要遍历的目录(JS 与 bat 一起收) */
const DIRS = ['runner', 'dev'];
/** 顶层要单独检查的文件(runner.config.mjs 是配置文件,也要求语法正确) */
const FILES = ['build.mjs', 'runner.config.mjs', 'yun-xue-tang-assistant.user.js'];
const TOP_CMD = ['start-headless.cmd'];
const SKIP_DIRS = new Set(['node_modules', '.git', '.run-profile', 'run-logs', '.run-tmp']);
function walk(dir, out = []) {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) {
if (!SKIP_DIRS.has(ent.name)) walk(p, out);
} else if (/\.m?js$|\.cmd$|\.bat$/i.test(ent.name)) {
out.push(p);
}
}
return out;
}
const jsTargets = [];
const cmdTargets = [];
for (const d of DIRS) {
const dir = path.join(ROOT, d);
if (fs.existsSync(dir)) {
for (const f of walk(dir)) {
if (/\.m?js$/.test(f)) jsTargets.push(f);
else cmdTargets.push(f);
}
}
}
for (const f of FILES) {
const p = path.join(ROOT, f);
if (fs.existsSync(p)) jsTargets.push(p);
}
for (const f of TOP_CMD) {
const p = path.join(ROOT, f);
if (fs.existsSync(p)) cmdTargets.push(p);
}
let failed = 0;
// ---- 1. JS 语法 ----
for (const file of jsTargets.sort()) {
const r = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8' });
if (r.status !== 0) {
failed++;
console.error(' FAIL ' + path.relative(ROOT, file));
console.error((r.stderr || '').trim());
}
}
// ---- 2. 批处理文件:纯 ASCII + CRLF ----
for (const file of cmdTargets.sort()) {
const rel = path.relative(ROOT, file);
const buf = fs.readFileSync(file);
const bad = [];
const nonAscii = [];
for (let i = 0; i < buf.length; i++) {
if (buf[i] > 0x7f) nonAscii.push(i);
}
if (nonAscii.length) {
const first = nonAscii[0];
const ctx = buf.slice(Math.max(0, first - 20), first + 20).toString('utf8');
bad.push('含 ' + nonAscii.length + ' 个非 ASCII 字节(首次出现在偏移 ' + first + ',上下文 “' + ctx + '”);'
+ 'cmd.exe 按代码页逐字节读取,中文会让行偏移错位');
}
let lf = 0;
let crlf = 0;
for (let i = 0; i < buf.length; i++) {
if (buf[i] === 0x0a) {
lf++;
if (i > 0 && buf[i - 1] === 0x0d) crlf++;
}
}
if (lf !== crlf) {
bad.push('有 ' + (lf - crlf) + ' 处裸 LF 行尾(共 ' + lf + ' 个 LF / ' + crlf + ' 个 CRLF);'
+ 'cmd.exe 会把上一行尾部当成命令的一部分');
}
if (bad.length) {
failed++;
console.error(' FAIL ' + rel);
for (const b of bad) console.error(' - ' + b);
}
}
const total = jsTargets.length + cmdTargets.length;
if (failed) {
console.error('\n静态检查:' + failed + '/' + total + ' 个文件失败');
process.exit(1);
}
console.log('静态检查:' + total + '/' + total + ' 个文件通过'
+ '(JS ' + jsTargets.length + ' · 批处理 ' + cmdTargets.length + ')');
+9 -9
View File
@@ -31,7 +31,7 @@
const MODE = 'hot'; // 'hot' | 'reload'
const POLL_MS = 1000; // 轮询间隔
const RETRY_MS = 15000; // 服务不可用时的重试间隔
const CACHE_KEY = 'yt-dev-src'; // 最近一次成功拉取的源码
const CACHE_KEY = 'yun-xue-tang-dev-src'; // 最近一次成功拉取的源码
const TAG = '[云学堂·热加载]';
const isTop = (function () {
try { return window.top === window.self; } catch (e) { return true; }
@@ -78,8 +78,8 @@
function disposePrevious() {
try {
if (page && typeof page.__ytDispose === 'function') {
page.__ytDispose();
if (page && typeof page.__yunXueTangDispose === 'function') {
page.__yunXueTangDispose();
return true;
}
} catch (e) {
@@ -91,7 +91,7 @@
function inject(src) {
const el = document.createElement('script');
el.type = 'text/javascript';
el.setAttribute('data-yt-dev-injected', '1');
el.setAttribute('data-yun-xue-tang-dev-injected', '1');
el.textContent = src;
(document.head || document.documentElement).appendChild(el);
el.remove();
@@ -109,11 +109,11 @@
return false;
}
const hadInstance = !!(page && (page.__ytAuto || document.getElementById('yt-auto-panel')));
const hadInstance = !!(page && (page.__yunXueTangAuto || document.getElementById('yun-xue-tang-panel')));
const disposed = disposePrevious();
// 首次注入不存在旧实例,直接注入;之后若旧实例没有 __ytDispose 或指定了 reload 模式,才刷新整页
// 首次注入不存在旧实例,直接注入;之后若旧实例没有 __yunXueTangDispose 或指定了 reload 模式,才刷新整页
if (hadInstance && (MODE === 'reload' || !disposed)) {
console.log(TAG, MODE === 'reload' ? '源码变更,刷新页面' : '旧实例无 __ytDispose,刷新页面');
console.log(TAG, MODE === 'reload' ? '源码变更,刷新页面' : '旧实例无 __yunXueTangDispose,刷新页面');
location.reload();
return false;
}
@@ -123,10 +123,10 @@
GM_setValue(CACHE_KEY, src);
clearBadge();
console.log(TAG, '已注入 ' + src.length + ' 字节源码');
if (isTop && !page.__ytAuto && !document.getElementById('yt-auto-panel')) {
if (isTop && !page.__yunXueTangAuto && !document.getElementById('yun-xue-tang-panel')) {
// 站点 CSP 若禁掉 inline script,退一步用页面主世界的 eval(需要 unsafe-eval)
try { page.eval(src); } catch (e) { /* 两种方式都不行再看下一条 */ }
if (!page.__ytAuto && !document.getElementById('yt-auto-panel')) {
if (!page.__yunXueTangAuto && !document.getElementById('yun-xue-tang-panel')) {
badge('源码已注入但未生效:页面 CSP 可能拦截了注入,请查看控制台');
}
}
+88
View File
@@ -0,0 +1,88 @@
// 极简 CDP 客户端:Node 18+ 原生 WebSocket,无需 puppeteer / playwright。
// 只实现本项目真机测试用到的部分:send / waitEvent / 事件堆积。
// Linux 无图形化服务器 / 容器的浏览器探测与启动参数统一放在 runner/browser.mjs,
// 这里一并转发,避免 dev 测试脚本和 runner 两套逻辑跑偏。
import fs from 'node:fs';
import {
resolveBrowser as _resolveBrowser, safetyArgs as _safetyArgs, hasDisplay,
} from '../runner/browser.mjs';
export { cleanStaleSingleton } from '../runner/browser.mjs';
export async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((res, rej) => {
ws.addEventListener('open', res, { once: true });
ws.addEventListener('error', rej, { once: true });
});
let id = 0;
const pending = new Map();
const events = [];
const waiters = [];
const listeners = [];
ws.addEventListener('message', (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id != null && pending.has(msg.id)) {
const { res, rej } = pending.get(msg.id);
pending.delete(msg.id);
if (msg.error) rej(new Error(msg.error.message));
else res(msg.result);
return;
}
events.push(msg);
for (const fn of listeners) {
try { fn(msg); } catch (e) { /* 忽略订阅者异常 */ }
}
for (let i = waiters.length - 1; i >= 0; i--) {
if (waiters[i].match(msg)) waiters.splice(i, 1)[0].res(msg);
}
});
const send = (method, params = {}) => new Promise((res, rej) => {
const mid = ++id;
pending.set(mid, { res, rej });
ws.send(JSON.stringify({ id: mid, method, params }));
});
const waitEvent = (name, timeoutMs = 30000) => new Promise((res, rej) => {
const timer = setTimeout(() => rej(new Error('等待事件超时: ' + name)), timeoutMs);
waiters.push({
match: (m) => m.method === name,
res: (m) => { clearTimeout(timer); res(m.params); },
});
});
const onEvent = (fn) => { listeners.push(fn); };
return { ws, send, waitEvent, onEvent, events, close: () => { try { ws.close(); } catch (e) {} } };
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function httpJson(url, method = 'GET') {
const r = await fetch(url, { method });
const t = await r.text();
try { return JSON.parse(t); } catch (e) { return t; }
}
// ---- Linux 无图形化服务器 / 容器适配 ----
// 无显示环境:Linux 上没有 DISPLAY / WAYLAND_DISPLAY 就只能无头
// (跑在 Xvfb 下时 Xvfb 会设置 DISPLAY,因此这里只判断变量)
export function forceHeadless() {
return !hasDisplay();
}
// 按环境变量 / 常见安装位置找到真实存在的浏览器;找不到时返回 null
export function findChrome(candidates) {
return _resolveBrowser() || candidates.filter(Boolean).find(function (p) {
try { return fs.statSync(p).isFile(); } catch (e) { return false; }
}) || null;
}
// 必须追加给浏览器的平台安全参数(容器 /dev/shm 小、root 无沙箱)
export function safetyArgs() {
return _safetyArgs();
}
+421
View File
@@ -0,0 +1,421 @@
#!/usr/bin/env node
/**
* 真机端到端测试:真实 Chrome + 真实云学堂账号,跑「登录 → 列表 → 进课 → 播放」全链路。
*
* 账号来源(环境变量,不写进代码、不打印明文):
* YUN_XUE_TANG_USR 员工邮箱 / 账号
* YUN_XUE_TANG_PWD 密码
*
* 用法:
* node dev/real-e2e.mjs 登录 + 列表断言(不动任何课程进度)
* node dev/real-e2e.mjs --play 额外进入最短的一门课,采样播放 N 秒后停止
* node dev/real-e2e.mjs --play --seconds 60
* node dev/real-e2e.mjs --headless 无头模式
* node dev/real-e2e.mjs --keep 跑完不关浏览器(便于人工复核)
* node dev/real-e2e.mjs --shotdir X 截图目录
*
* 安全约束(刻意保守):
* - 只有显式传 --play 才会进入课程页;默认全程只读,不改任何学习进度。
* - --play 默认只采样 25 秒,采完立刻 pause + 释放脚本,不会把整节课刷完。
* - 结束前会打印本轮进度变化(开课前 / 结束后 的 已完成 x/y),便于核对影响。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const SCRIPT_SRC = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
const argv = process.argv.slice(2);
const flag = (n) => argv.includes(n);
const opt = (n, d) => {
const i = argv.indexOf(n);
return i >= 0 && argv[i + 1] ? argv[i + 1] : d;
};
const USR = process.env.YUN_XUE_TANG_USR || '';
const PWD = process.env.YUN_XUE_TANG_PWD || '';
const PLAY = flag('--play');
const SAMPLE_SECONDS = Number(opt('--seconds', 25));
const HEADLESS = flag('--headless') || process.env.YUN_XUE_TANG_HEADLESS === '1';
const KEEP = flag('--keep');
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9334);
const SHOT_DIR = opt('--shotdir', path.join(ROOT, 'docs/screenshots'));
const ORIGIN = 'https://kfmic.yunxuetang.cn';
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const results = [];
const consoleLogs = [];
const log = (...a) => console.log(...a);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (!CHROME) { console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=... 指定'); process.exit(2); }
if (!USR || !PWD) { console.error('缺少环境变量 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD'); process.exit(2); }
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22+,当前 ' + process.version);
process.exit(2);
}
log('[E2E] 账号:' + USR.slice(0, 3) + '***' + USR.slice(-2) + ' 密码:' + '*'.repeat(Math.min(PWD.length, 8)) + '(长度 ' + PWD.length + ')');
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
log('[E2E] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless)' : '(有界面)') + ' 进课采样:' + (PLAY ? SAMPLE_SECONDS + ' 秒' : '否(只读)'));
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-e2e-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--autoplay-policy=no-user-gesture-required',
'--window-size=1360,940',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
try {
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
let version = null;
for (let i = 0; i < 100; i++) {
try { const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`); if (v && v.webSocketDebuggerUrl) { version = v; break; } } catch (e) {}
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 未就绪');
log('[E2E] ' + version.Browser);
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(ORIGIN + '/login.html')}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ type: m.params.entry.level, text: m.params.entry.text });
}
});
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 waitFor = async (exprFn, timeoutMs, label) => {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
try { if (await evalJS(exprFn)) return true; } catch (e) {}
await sleep(500);
}
return false;
};
const shot = async (name) => {
try {
fs.mkdirSync(SHOT_DIR, { recursive: true });
const s = await cdp.send('Page.captureScreenshot', { format: 'png' });
const f = path.join(SHOT_DIR, name);
fs.writeFileSync(f, Buffer.from(s.data, 'base64'));
return path.relative(ROOT, f);
} catch (e) { return '截图失败: ' + e.message; }
};
const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: ORIGIN + '/login.html' });
await loaded;
await sleep(2000);
// ---------- 1. 登录页 + 注入 ----------
await evalJS(SCRIPT_SRC);
await sleep(1000);
const loginInfo = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
return {
url: location.href,
title: document.title,
isLoginPage: a.isLoginPage(),
panel: !!document.getElementById('yun-xue-tang-panel'),
fields: (() => { const f = a.loginFields(); return { user: !!f.user, pwd: !!f.pwd, ph: f.user ? f.user.placeholder : null }; })(),
};
})())`);
check('登录页加载 + 脚本注入', loginInfo.isLoginPage === true && loginInfo.panel === true, loginInfo.url);
check('识别到账号/密码输入框', loginInfo.fields.user && loginInfo.fields.pwd, loginInfo.fields);
// ---------- 2. 填账号密码(走真实的 setNativeValue + Vue 双向绑定) ----------
const filled = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const u = ${JSON.stringify(USR)};
const p = ${JSON.stringify(PWD)};
document.getElementById('yun-xue-tang-login-user').value = u;
document.getElementById('yun-xue-tang-login-pass').value = p;
const okForm = a.fillLoginForm(u, p);
const f = a.loginFields();
return {
okForm,
userValueLen: f.user ? f.user.value.length : -1,
pwdValueLen: f.pwd ? f.pwd.value.length : -1,
userMatched: f.user ? f.user.value === u : false,
pwdMatched: f.pwd ? f.pwd.value === p : false,
panelUser: document.getElementById('yun-xue-tang-login-user').value.length,
};
})())`);
check('账号密码写入真实输入框', filled.okForm === true && filled.userMatched === true && filled.pwdMatched === true,
{ 长度: [filled.userValueLen, filled.pwdValueLen], 一致: [filled.userMatched, filled.pwdMatched] });
const agree = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const before = [...document.querySelectorAll('label')].filter(x => /已阅读并同意|隐私政策/.test(x.innerText||''))
.map(x => { const c = x.querySelector('input[type=checkbox]'); return c ? c.checked : null; });
const ok = a.checkLoginAgreement ? a.checkLoginAgreement() : 'no-api';
const after = [...document.querySelectorAll('label')].filter(x => /已阅读并同意|隐私政策/.test(x.innerText||''))
.map(x => { const c = x.querySelector('input[type=checkbox]'); return c ? c.checked : null; });
return { before, after, ok };
})())`);
check('隐私政策勾选处理正常', agree.ok === true || agree.ok === 'no-api', agree);
// ---------- 3. 点「一键登录并刷课」,等真实登录成功 ----------
// 注意:这个按钮会写 LS_PENDING,登录后自动开启列表刷课(脚本设计行为)。
// 默认(不加 --play)测完登录马上刹住,避免动到真实学习进度。
await evalJS(`(document.getElementById('yun-xue-tang-oneclick').click(), true)`);
const loginOk = await waitFor(`(() => {
if (/\\/login/.test(location.pathname)) return false;
if (!document.body) return false;
if (document.querySelector('input[type=password]')) return false;
return true;
})()`, 45000);
await sleep(2000);
const afterLogin = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const status = (document.getElementById('yun-xue-tang-status') || {}).textContent || '';
const bodyText = document.body ? (document.body.innerText || '').replace(/\\s+/g, ' ').slice(0, 400) : '';
return {
url: location.href, title: document.title, status,
alive: typeof window.__yunXueTangAuto,
isLoginPage: a ? a.isLoginPage() : null,
captcha: /验证码|滑块|安全验证/.test(bodyText),
errText: (bodyText.match(/(用户名密码错误|账号或密码错误|密码错误|账号不存在|登录失败)[^ ]{0,40}/) || [''])[0],
panel: !!document.getElementById('yun-xue-tang-panel'),
};
})())`);
check('真实登录成功(离开登录页)', loginOk === true, afterLogin);
const scriptErrs = () => consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
check('登录流程无脚本 error', scriptErrs().length === 0, scriptErrs().map((e) => e.text.slice(0, 140)));
log(' 截图:' + await shot('e2e-01-after-login.png'));
// 登录是整页跳转(新 document),真实 Tampermonkey 会按 @match 重新注入;
// 这里模拟同样的行为。
if ((await evalJS('typeof window.__yunXueTangAuto')) === 'undefined') {
log('[E2E] 登录后是新 document(' + afterLogin.url + '),重新注入脚本');
await evalJS(SCRIPT_SRC);
await sleep(1200);
}
check('登录后新 document 上脚本已注入', (await evalJS('typeof window.__yunXueTangAuto')) === 'object', await evalJS('document.title || location.pathname'));
if (!PLAY) {
// 立即刹住列表刷课:清 pending 标记 + 关闭 running,防止在真实账号上推进课程
const halted = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
if (a) { a.S.batchRunning = false; a.S.batchFinished = false; a.S.activeCourse = null; a.S.coursePhase = 'idle'; a.save(); }
return { running: a ? a.S.batchRunning : null, current: a ? a.S.activeCourse : null };
})())`);
check('默认只读:登录后立即停用列表刷课', halted.running === false && halted.current === null, halted);
}
// ---------- 4. 列表页断言 ----------
const listNavStarted = Date.now();
await evalJS(`(location.href = 'https://kfmic.yunxuetang.cn/kng/#/list', true)`);
await cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await sleep(2500);
// 换页后可能又是新 document,重新注入
if ((await evalJS('typeof window.__yunXueTangAuto')) === 'undefined') {
log('[E2E] 列表页是新 document,重新注入脚本');
await evalJS(SCRIPT_SRC);
await sleep(1000);
}
if (!PLAY) {
// 新 document 里 S 从 sessionStorage 恢复了 batchRunning=true,再次刹住
await evalJS(`(() => {
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
const a = window.__yunXueTangAuto;
if (a) { a.S.batchRunning = false; a.S.activeCourse = null; a.S.coursePhase = 'idle'; a.save(); }
return true;
})()`);
await sleep(400);
}
const listReady = await waitFor(`!!window.__yunXueTangAuto && document.querySelectorAll('li.kng-list-new__item').length > 0`, 45000);
await sleep(1500);
const listInfo = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto; const cards = a.scanCards();
const vm = (() => {
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
return v || null;
})();
const data = (vm && vm.kngListData) || [];
return {
url: location.href,
route: a.route(),
cards: cards.length,
page: a.currentPage(),
maxPage: a.maxPageNumber(),
first3: cards.slice(0, 3).map((c) => ({ title: c.title.slice(0, 30), status: c.status })),
vmCount: data.length,
vmFirst: data.slice(0, 3).map((d) => ({ title: String(d.title || d.name || '').slice(0, 26), studyHours: d.studyHours, id: String(d.id || d.kngId || '').slice(0, 12) })),
pending: cards.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status)).length,
};
})())`);
check('列表页卡片渲染', listReady === true && listInfo.cards > 0, { 卡片数: listInfo.cards, 页码: listInfo.page + '/' + listInfo.maxPage });
check('scanCards 解析标题与状态', listInfo.first3.every((c) => c.title.length > 0), listInfo.first3);
check('列表 Vue 组件可读(时长来源)', listInfo.vmCount > 0, { 条数: listInfo.vmCount, 样例: listInfo.vmFirst });
const dur = listInfo.vmFirst.filter((d) => Number.isFinite(d.studyHours) && d.studyHours > 0);
check('studyHours 时长可用(短课程优先的数据源)', dur.length > 0, dur);
// ---------- 5. 可选:真实进课 + 采样播放 ----------
let beforeProgress = null;
let playInfo = null;
if (PLAY) {
// 选一门「最短」的未学完课程,尽量减小对真实进度的影响
const pick = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const cards = a.scanCards();
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
const cand = cards
.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status))
.map((c) => ({ c, d: byTitle.get(c.title) }))
.filter((x) => x.d && Number(x.d.studyHours) > 0)
.sort((x, y) => Number(x.d.studyHours) - Number(y.d.studyHours));
if (!cand.length) {
const any = cards.find((c) => c.title && !/已学完|已完成|已学习/.test(c.status));
return any ? { title: any.title, studyHours: null, idx: any.i, fallback: true } : null;
}
return { title: cand[0].c.title, studyHours: Number(cand[0].d.studyHours), idx: cand[0].c.i };
})())`);
check('找到可学的最短课程', !!pick, pick);
if (pick) {
log('[E2E] 选课:' + pick.title + '(' + (pick.studyHours ? Math.round(pick.studyHours / 60) + ' 分钟' : '时长未知') + ')');
// 用脚本自己的 startCourse 走真实进课流程(会写 S.activeCourse 并点卡片)
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
const card = a.scanCards().find((c) => c.i === ${pick.idx});
if (!card) return 'no-card';
a.startCourse(card);
return 'started';
})()`);
const entered = await waitFor(`window.__yunXueTangAuto && window.__yunXueTangAuto.route() === 'course' && /\\/play/.test(location.hash)`, 40000);
await sleep(2500);
const before = await json(`JSON.stringify((() => ({
url: location.hash,
summary: window.__yunXueTangAuto.readSummary(),
countdown: window.__yunXueTangAuto.readCountdown(),
lessons: window.__yunXueTangAuto.lessonItems().length,
active: window.__yunXueTangAuto.lessonItems().length ? (document.querySelector('.yxtulcdsdk-catalog .liactive') || {}).innerText || '' : '',
}))())`);
beforeProgress = before.summary && before.summary.text;
check('进入真实课程播放页', entered === true, before.url);
check('读取到课程汇总/目录', !!before.summary || before.lessons > 0, { 汇总: before.summary && before.summary.text, 目录: before.lessons });
// 触发「开始学习」并观察播放器
const play = await waitFor(`(() => {
const v = document.querySelector('video, audio');
return !!v && v.duration > 0;
})()`, 25000);
const t0 = Date.now();
// 让主循环自己动起来(模拟用户手动打开课程时的自动连播开关)
await evalJS(`(() => { window.__yunXueTangAuto.tick(); return true; })()`);
await sleep(SAMPLE_SECONDS * 1000);
playInfo = await json(`JSON.stringify((() => {
const v = document.querySelector('video, audio');
const a = window.__yunXueTangAuto;
return {
found: !!v,
muted: v ? v.muted : null,
paused: v ? v.paused : null,
rate: v ? v.playbackRate : null,
currentTime: v ? Math.round(v.currentTime) : null,
duration: v ? Math.round(v.duration) : null,
summary: a.readSummary(),
countdown: a.readCountdown(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
elapsedSec: Math.round((Date.now() - ${t0}) / 1000),
};
})())`);
check('播放器被找到并接管(静音 1x)', playInfo.found === true && playInfo.muted === true && playInfo.rate === 1, playInfo);
check('视频真实在播放(时间在走)', playInfo.paused === false && playInfo.currentTime > 0, { 已播到: playInfo.currentTime + 's / ' + playInfo.duration + 's' });
check('采样期间无脚本 error', scriptErrs().length === 0, scriptErrs().map((e) => e.text.slice(0, 140)));
log(' 截图:' + await shot('e2e-02-playing.png'));
// 立刻停手:暂停媒体 + 关闭批量 + dispose
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.S.batchRunning = false;
a.save();
a.pauseAllMedia ? a.pauseAllMedia() : document.querySelectorAll('video, audio').forEach((x) => x.pause());
return true;
})()`);
await sleep(1200);
const stopped = await json(`JSON.stringify((() => {
const v = document.querySelector('video, audio');
return { paused: v ? v.paused : null, running: window.__yunXueTangAuto ? window.__yunXueTangAuto.S.batchRunning : null,
summary: window.__yunXueTangAuto ? window.__yunXueTangAuto.readSummary() : null };
})())`);
check('停止后媒体已暂停', stopped.paused === true && stopped.running === false, stopped);
}
}
// ---------- 6. 释放脚本,确认无残留 ----------
if (PLAY) {
const disposed = await json(`JSON.stringify((() => {
window.__yunXueTangDispose();
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto };
})())`);
check('dispose 后面板与 API 清理干净', disposed.panel === false && disposed.api === 'undefined', disposed);
}
log('\n[E2E] 脚本日志(' + consoleLogs.filter((l) => /云学堂助手/.test(l.text)).length + ' 条脚本相关):');
for (const l of consoleLogs.filter((x) => /云学堂助手/.test(x.text)).slice(-25)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
if (beforeProgress) log('[E2E] 进度快照:进入前「' + beforeProgress + '」→ 采样后「' + (playInfo && playInfo.summary && playInfo.summary.text) + '」');
} catch (e) {
check('E2E 流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 5).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) { await sleep(700); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} }
else log('[E2E] --keep:浏览器保持打开 ' + userDataDir);
}
const failed = results.filter((r) => !r.ok);
log('\n===== E2E 结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);
+467
View File
@@ -0,0 +1,467 @@
#!/usr/bin/env node
/**
* 真机持续运行测试:跨章节 + 跨课程。
*
* 真实 Chrome + 真实账号,让脚本自己跑列表刷课,观察它能否
* 1) 在一门多课时课程里自动从第 N 节切到第 N+1 节(跨章节)
* 2) 一门课完成后回到列表、进下一门课(跨课程)
* 3) 每次整页跳转(新 document)后重新注入并接续运行
* 4) 全程视频持续推进、无脚本 error、没学完的课程按退避重试而不是被跳过
*
* 用法:
* node dev/real-run.mjs --scan 只登录 + 列表,打印所有卡片(只读)
* node dev/real-run.mjs --probe 8 读前 8 门课最短的「未学完」课的目录(不进播放,不动进度)
* node dev/real-run.mjs --max 2 --budget 15 跑批量,最多完成 2 门 / 最多 15 分钟
* node dev/real-run.mjs --title 坚持 --max 2 先把匹配标题的课程跑完,再自动跑下一门
* node dev/real-run.mjs --headless --keep 无头 / 跑完不关浏览器
* node dev/real-run.mjs --out run.json 时间线写到指定文件(默认临时目录)
*
* 注意:这个测试会**真实推进学习进度**(这就是它的目的)。
* 只读的登录/列表测试请看 dev/real-e2e.mjs。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const SCRIPT_SRC = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
const argv = process.argv.slice(2);
const flag = (n) => argv.includes(n);
const opt = (n, d) => {
const i = argv.indexOf(n);
return i >= 0 && argv[i + 1] ? argv[i + 1] : d;
};
const USR = process.env.YUN_XUE_TANG_USR || '';
const PWD = process.env.YUN_XUE_TANG_PWD || '';
const SCAN = flag('--scan');
const PROBE = flag('--probe') ? Number(opt('--probe', 8)) : 0;
const HEADLESS = flag('--headless') || process.env.YUN_XUE_TANG_HEADLESS === '1';
const KEEP = flag('--keep');
const MAX_COURSES = Number(opt('--max', 2));
const BUDGET_MIN = Number(opt('--budget', 15));
const PIN_TITLE = opt('--title', '');
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9335);
const ORIGIN = 'https://kfmic.yunxuetang.cn';
const OUT = opt('--out', path.join(os.tmpdir(), 'yun-xue-tang-run-' + Date.now() + '.json'));
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const results = [];
const consoleLogs = [];
const timeline = [];
const log = (...a) => console.log(...a);
const clock = () => new Date().toISOString().slice(11, 19);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (!CHROME) { console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=... 指定'); process.exit(2); }
if (!USR || !PWD) { console.error('缺少环境变量 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD'); process.exit(2); }
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22+,当前 ' + process.version);
process.exit(2);
}
log('[RUN] 账号:' + USR.slice(0, 3) + '***' + USR.slice(-2));
log('[RUN] 模式:' + (SCAN ? '只读扫描列表' : (PROBE ? '只读探测前 ' + PROBE + ' 门课的目录' : '批量持续运行(最多 ' + MAX_COURSES + ' 门 / ' + BUDGET_MIN + ' 分钟)')) +
(PIN_TITLE ? ' 指定课程:' + PIN_TITLE : ''));
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-run-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
// 后台标签页/最小化时不要把定时器和视频节流,否则「持续运行」测不准
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--autoplay-policy=no-user-gesture-required',
'--window-size=1360,940',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
log('[RUN] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless)' : '(有界面)'));
try {
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
let version = null;
for (let i = 0; i < 100; i++) {
try { const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`); if (v && v.webSocketDebuggerUrl) { version = v; break; } } catch (e) {}
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 未就绪');
log('[RUN] ' + version.Browser);
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(ORIGIN + '/login.html')}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ t: Date.now(), type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ t: Date.now(), type: m.params.entry.level, text: m.params.entry.text });
}
});
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 waitFor = async (exprFn, timeoutMs) => {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
try { if (await evalJS(exprFn)) return true; } catch (e) {}
await sleep(500);
}
return false;
};
// ---------- 整页跳转后自动重新注入(等价 Tampermonkey 按 @match 重注入) ----------
let injections = 0;
let reinjectTimer = null;
const injectIfMissing = async () => {
let t;
try { t = await evalJS('typeof window.__yunXueTangAuto'); } catch (e) { return false; }
if (t === 'object') return false;
try {
await evalJS(SCRIPT_SRC);
injections++;
return true;
} catch (e) { return false; }
};
// 每 1.5 秒兜底检查一次:任何原因导致脚本不在,就补注入(真实环境里由 @match 保证)
const startWatchdog = () => {
if (reinjectTimer) clearInterval(reinjectTimer);
reinjectTimer = setInterval(() => {
injectIfMissing().then((did) => {
if (did) console.log('[RUN] ' + clock() + ' 新 document 已重新注入(第 ' + injections + ' 次)');
}).catch(() => {});
}, 1500);
};
const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: ORIGIN + '/login.html' });
await loaded;
await sleep(2000);
// ---------- 登录 ----------
await evalJS(SCRIPT_SRC);
injections++;
await sleep(1200);
const loginPage = await evalJS(`!!(window.__yunXueTangAuto && window.__yunXueTangAuto.isLoginPage())`);
check('登录页脚本就绪', loginPage === true, await evalJS('location.pathname'));
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.fillLoginForm(${JSON.stringify(USR)}, ${JSON.stringify(PWD)});
try { a.checkLoginAgreement(); } catch (e) {}
return true;
})()`);
await evalJS(`(document.getElementById('yun-xue-tang-oneclick').click(), true)`);
const loginOk = await waitFor(`(() => {
if (/\\/login/.test(location.pathname)) return false;
if (!document.body) return false;
return !document.querySelector('input[type=password]');
})()`, 45000);
check('真实登录成功', loginOk === true, await evalJS('location.pathname'));
// 进列表(新 document)
const loaded2 = cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await evalJS(`(location.href = '${ORIGIN}/kng/#/list', true)`);
await loaded2;
await sleep(2500);
await injectIfMissing();
if (injections === 1) injections++; // 上面那次是列表页注入
await waitFor(`!!window.__yunXueTangAuto && window.__yunXueTangAuto.scanCards().length > 0`, 45000);
await sleep(1500);
// 优先短课程(缩短验证耗时;真机上这是默认勾选行为)
await evalJS(`(() => { try { localStorage.setItem('yun-xue-tang-prefer-short', '1'); } catch (e) {} const a = window.__yunXueTangAuto; if (a) a.state.preferShortCourses = true; return true; })()`);
// ---------- --probe:只读探测目录(关掉自动播放,避免动进度) ----------
if (PROBE) {
// 当前课程自动连播开关关掉:进课后脚本不会自动起播、也不会自动切节
await evalJS(`(() => { localStorage.setItem('yun-xue-tang-auto-play-enabled', '0'); const a = window.__yunXueTangAuto; if (a) a.state.autoPlayEnabled = false; return true; })()`);
const picks = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
return a.scanCards()
.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status))
.map((c) => {
const d = byTitle.get(c.title) || {};
return { i: c.i, title: c.title, studyHours: Number(d.studyHours) || 0, id: String(d.id || '') };
})
.filter((c) => c.studyHours > 0)
.sort((x, y) => x.studyHours - y.studyHours)
.slice(0, ${PROBE});
})())`);
log('\n[RUN] 探测 ' + picks.length + ' 门课(按总时长正序):');
const report = [];
for (const p of picks) {
await evalJS(`(() => {
try { localStorage.setItem('yun-xue-tang-auto-play-enabled', '0'); } catch (e) {}
const a = window.__yunXueTangAuto;
a.state.autoPlayEnabled = false;
const card = a.scanCards().find((c) => c.i === ${p.i});
if (card) a.startCourse(card);
return true;
})()`).catch(() => {});
const ok = await waitFor(`(() => {
const a = window.__yunXueTangAuto;
return !!a && a.route() === 'course' && a.lessonItems().length > 0;
})()`, 25000);
let info = null;
if (ok) {
await sleep(1200);
info = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const items = a.lessonItems();
return {
lessons: items.length,
completed: items.filter((li) => a.isLessonCompleted(li)).length,
quiz: /考试|测验|问卷|答题/.test((document.querySelector('.yxtulcdsdk-catalog') || {}).innerText || ''),
names: items.map((li) => ((li.innerText || '').replace(/\\s+/g, ' ').trim()).slice(0, 22)),
summary: a.readSummary(),
};
})())`);
}
const remaining = info ? info.lessons - info.completed : 0;
log(' ' + (info ? (info.lessons + ' 节/剩 ' + remaining + (info.quiz ? ' [含考试]' : '')) : '进课失败').padEnd(18) +
' ' + String(Math.round(p.studyHours / 60)).padStart(4) + ' 分 ' + p.title.slice(0, 40));
report.push({ ...p, ...(info || {}), remaining });
// 回列表
await evalJS(`(location.href = '${ORIGIN}/kng/#/list', true)`).catch(() => {});
await sleep(2500);
await injectIfMissing();
await waitFor(`!!window.__yunXueTangAuto && window.__yunXueTangAuto.scanCards().length > 0`, 40000);
await sleep(1200);
}
const multi = report.filter((r) => r.remaining >= 2 && !r.quiz);
log('\n[RUN] 适合测「跨章节」的候选(≥2 节未学完且不含考试):');
for (const m of multi) log(' ' + m.remaining + ' 节待学 ' + m.title.slice(0, 40) + ' → ' + m.names.join(' / '));
check('找到可跨章节验证的课程(≥2 节未学完)', multi.length > 0, multi.slice(0, 5).map((m) => ({ title: m.title.slice(0, 30), remaining: m.remaining })));
fs.writeFileSync(path.join(os.tmpdir(), 'yun-xue-tang-probe.json'), JSON.stringify(report, null, 2));
} else if (SCAN) {
const cards = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
return a.scanCards().map((c) => {
const d = byTitle.get(c.title) || {};
return { title: c.title, status: c.status, studyHours: d.studyHours, id: String(d.id || '') };
});
})())`);
log('\n[RUN] 列表卡片(' + cards.length + ' 张):');
for (const c of cards) {
log(' ' + (c.status || '-').padEnd(4) + ' ' +
(c.studyHours ? String(Math.round(c.studyHours / 60)).padStart(5) + ' 分' : ' ? 分') +
' ' + c.title.slice(0, 46));
}
check('列表可读', cards.length > 0, { 卡片数: cards.length });
} else {
// ---------- 启动批量 ----------
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.S.completedThisRun = 0;
a.S.batchFinished = false;
a.startBatch();
return true;
})()`);
await sleep(1500);
// 指定课程:进入列表后抢先开始它(S.batchRunning 先关掉,避免 listTick 抢选别的课)
if (PIN_TITLE) {
const armed = await waitFor(`window.__yunXueTangAuto && window.__yunXueTangAuto.route() === 'list' && window.__yunXueTangAuto.scanCards().length > 0`, 60000);
if (armed) {
const pinned = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
a.S.batchRunning = false; a.save();
const card = a.scanCards().find((c) => c.title.indexOf(${JSON.stringify(PIN_TITLE)}) >= 0);
if (!card) { a.S.batchRunning = true; a.save(); return { ok: false }; }
a.startCourse(card);
a.S.batchRunning = true; a.save();
return { ok: true, title: card.title };
})())`);
check('已指定首门课程并开始', pinned.ok === true, pinned);
} else {
check('已指定首门课程并开始', false, '列表未就绪');
}
}
// ---------- 持续监控 ----------
const startedAt = Date.now();
const deadline = startedAt + BUDGET_MIN * 60 * 1000;
let lastSig = '';
let lastSample = null;
let lastAdvanceAt = Date.now();
let lastCt = 0;
let maxStallMs = 0;
const perCourse = new Map(); // title -> lesson keys seen
const transitions = []; // { t, from, to, course }
let playEvidence = 0; // currentTime 增长次数
const sample = async () => {
try {
return await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
if (!a) return { gone: true, href: location.href };
const v = document.querySelector('video, audio');
const items = a.lessonItems();
return {
href: location.href,
route: a.route(),
phase: a.S.coursePhase,
running: a.S.batchRunning,
runFinished: a.S.batchFinished,
completed: a.S.completedThisRun,
pendingRetries: Object.keys(a.S.courseRetries || {}).length,
cur: a.S.activeCourse ? a.S.activeCourse.title : null,
curId: a.S.activeCourse ? a.S.activeCourse.id : null,
lesson: a.readActiveLessonKey ? a.readActiveLessonKey() : '',
lessonCount: items.length,
summary: a.readSummary(),
countdown: a.readCountdown(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
video: v ? { ct: Math.round(v.currentTime), dur: Math.round(v.duration), paused: v.paused, muted: v.muted, rate: v.playbackRate } : null,
done: Object.keys(a.S.completedTitles || {}).length,
retryTitles: Object.keys(a.S.courseRetries || {}).length,
};
})())`);
} catch (e) {
return null; // 跳转中 DOM 不可用
}
};
log('\n[RUN] 开始持续监控(Ctrl+C 或到点自动结束)…\n');
while (Date.now() < deadline) {
const s = await sample();
if (s && !s.gone) {
lastSample = s;
// 视频推进证据
if (s.video && !s.video.paused && s.video.ct > lastCt) {
playEvidence++;
lastAdvanceAt = Date.now();
lastCt = s.video.ct;
} else if (s.video && s.video.paused && s.video.ct !== lastCt) {
lastCt = s.video.ct;
}
if (Date.now() - lastAdvanceAt > maxStallMs) maxStallMs = Date.now() - lastAdvanceAt;
// 每门课出现过的课时
if (s.cur) {
if (!perCourse.has(s.cur)) perCourse.set(s.cur, []);
const keys = perCourse.get(s.cur);
if (s.lesson && keys[keys.length - 1] !== s.lesson) keys.push(s.lesson);
}
const sig = [s.cur, s.lesson, s.completed, s.phase, s.runFinished].join('|');
if (sig !== lastSig) {
const prev = lastSample && lastSig ? lastSig.split('|') : null;
log('[RUN] ' + clock() + ' ' + (s.cur ? s.cur.slice(0, 26) : '(列表)') +
' ' + (s.phase || '-') + (s.runFinished ? ' [已停止]' : '') +
' 完成 ' + s.completed + ' 待重试 ' + s.pendingRetries +
(s.lesson ? ' 课时:' + s.lesson.slice(0, 30) : '') +
(s.summary ? ' 汇总:' + s.summary.text : '') +
(s.countdown != null ? ' 倒计时 ' + s.countdown + 's' : ''));
if (prev && prev[0] && s.cur && prev[0] === s.cur && prev[1] && s.lesson && prev[1] !== s.lesson) {
transitions.push({ t: Date.now() - startedAt, course: s.cur, from: prev[1], to: s.lesson });
}
timeline.push({ at: Date.now() - startedAt, ...s });
lastSig = sig;
}
if (s.completed >= MAX_COURSES) { log('\n[RUN] 已完成 ' + s.completed + ' 门,达到上限,收尾'); break; }
if (s.runFinished) { log('\n[RUN] 脚本自己停止了:' + s.status); break; }
if (s.runFinished && /重试 .* 次仍未完成/.test(s.status || '')) { log('[RUN] 重试用尽,脚本已停止,收尾'); break; }
}
await sleep(2000);
}
const elapsed = Math.round((Date.now() - startedAt) / 1000);
const errors = consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
const final = (await sample()) || lastSample || {};
check('持续运行未因脚本 exception 中断', errors.length === 0, errors.map((e) => e.text.slice(0, 140)));
check('批处理仍在运行或已按上限结束', final.runFinished !== undefined, { running: final.running, runFinished: final.runFinished });
check('至少完成 2 门课程(跨课程)', (final.completed || 0) >= 2, { 完成: final.completed, 用时秒: elapsed });
check('观察到课时自动切换(跨章节)', transitions.length >= 1, { 切换次数: transitions.length, 明细: transitions.map((x) => x.from.slice(0, 14) + ' → ' + x.to.slice(0, 14)) });
check('视频持续推进(无长时间卡死)', playEvidence >= 3 && maxStallMs < 120000, { 推进采样: playEvidence, 最长停滞秒: Math.round(maxStallMs / 1000) });
check('整页跳转后自动恢复(重新注入)', injections >= 2, { 注入次数: injections });
check('没有课程被永久跳过(重试计数可控)', (final.retryTitles || 0) < 5, { 待重试标题: final.retryTitles });
log('\n[RUN] 每门课观察到的课时:');
for (const [title, keys] of perCourse) {
log(' ' + title.slice(0, 34) + ' → ' + keys.length + ' 节:' + keys.map((k) => k.slice(0, 18)).join(' / '));
}
log('[RUN] 完成后本地已记录 done:' + (final.done || 0) + ' 门;用时 ' + Math.round(elapsed / 60) + ' 分 ' + (elapsed % 60) + ' 秒');
// 收尾:停批量 + 暂停媒体
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
if (a) { a.S.batchRunning = false; a.save(); if (a.pauseAllMedia) a.pauseAllMedia(); }
return true;
})()`).catch(() => {});
await sleep(1000);
const disposed = await json(`JSON.stringify((() => {
try { window.__yunXueTangDispose(); } catch (e) {}
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto };
})())`).catch(() => ({ panel: null, api: 'n/a' }));
check('dispose 后面板与 API 清理干净', disposed.panel === false && disposed.api === 'undefined', disposed);
}
log('\n[RUN] 脚本日志(' + consoleLogs.filter((l) => /云学堂助手/.test(l.text)).length + ' 条):');
for (const l of consoleLogs.filter((x) => /云学堂助手/.test(x.text)).slice(-40)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
} catch (e) {
check('持续运行流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 5).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) { await sleep(700); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} }
else log('[RUN] --keep:浏览器保持打开 ' + userDataDir);
try {
fs.writeFileSync(OUT, JSON.stringify({ timeline, results, logs: consoleLogs.slice(-400) }, null, 2));
log('[RUN] 时间线已写入 ' + OUT);
} catch (e) { /* ignore */ }
}
const failed = results.filter((r) => !r.ok);
log('\n===== RUN 结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);
+325
View File
@@ -0,0 +1,325 @@
#!/usr/bin/env node
/**
* 真机测试:真实 Chrome + 真实 https://kfmic.yunxuetang.cn 页面。
*
* 做法:启动一个独立用户目录的 Chrome(不碰你日常配置),通过 CDP 把打包产物
* yun-xue-tang-assistant.user.js 注入页面主世界——这与 Tampermonkey 在
* @grant none 下的执行环境一致,所以断言的是脚本在真实浏览器 / 真实站点
* DOM 上的行为,而不是 Node 里的 DOM 桩。
*
* 用法:
* node dev/real-test.mjs 有界面浏览器(默认,最接近真机)
* node dev/real-test.mjs --headless 无头模式(CI 用)
* node dev/real-test.mjs --keep 跑完不关浏览器(便于人工肉眼复核)
*
* 环境变量:
* YUN_XUE_TANG_CHROME Chrome/Edge 可执行文件路径
* YUN_XUE_TANG_CDP_PORT 调试端口,默认 9333
* YUN_XUE_TANG_URL 起始页面,默认 https://kfmic.yunxuetang.cn/login.html
* YUN_XUE_TANG_SHOT_DIR 截图目录,默认 docs/screenshots
*
* 需要 Node 22+(用到全局 WebSocket 与 fetch);只做只读探测:
* 不填写账号密码、不点登录、不修改线上数据。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const SCRIPT_FILE = path.join(ROOT, 'yun-xue-tang-assistant.user.js');
const SCRIPT_SRC = fs.readFileSync(SCRIPT_FILE, 'utf8');
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9333);
const START_URL = process.env.YUN_XUE_TANG_URL || 'https://kfmic.yunxuetang.cn/login.html';
const HEADLESS = process.env.YUN_XUE_TANG_HEADLESS === '1' || process.argv.includes('--headless');
const KEEP = process.env.YUN_XUE_TANG_KEEP === '1' || process.argv.includes('--keep');
const SHOT_DIR = process.env.YUN_XUE_TANG_SHOT_DIR || path.join(ROOT, 'docs/screenshots');
const results = [];
const consoleLogs = [];
const log = (...a) => console.log(...a);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22 及以上(依赖全局 WebSocket / fetch),当前 ' + process.version);
process.exit(2);
}
if (!CHROME) {
console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=/path/to/chrome 指定');
process.exit(2);
}
if (!fs.existsSync(SCRIPT_FILE)) {
console.error('缺少构建产物,先运行 npm run build');
process.exit(2);
}
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-chrome-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--window-size=1280,900',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
try {
log('[真机] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless=new)' : '(有界面)'));
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
// ---- 1. 等 CDP 就绪 ----
let version = null;
for (let i = 0; i < 100; i++) {
try {
const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`);
if (v && v.webSocketDebuggerUrl) { version = v; break; }
} catch (e) { /* 还没起来 */ }
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 端口未就绪(' + PORT + ')');
check('真实浏览器进程启动', /^(Chrome|HeadlessChrome|Edg)\//.test(version.Browser || ''), version.Browser);
// ---- 2. 打开真实页面 ----
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(START_URL)}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
await cdp.send('Network.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ type: m.params.entry.level, text: m.params.entry.text });
}
});
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 loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: START_URL });
await loaded;
await sleep(1800);
const page = await json(`JSON.stringify({ url: location.href, title: document.title, host: location.host, ua: navigator.userAgent })`);
log('[真机] 页面:' + page.url);
log('[真机] 标题:' + page.title);
check('落在真实云学堂页面', /(^|\.)yunxuetang\.cn$/.test(page.host), page.host);
check('真实浏览器内核', /Chrome\//.test(page.ua), page.ua.slice(0, 96) + '…');
// ---- 3. 注入(等价 Tampermonkey @grant none 主世界执行)----
check('注入前页面无残留实例', (await evalJS('typeof window.__yunXueTangAuto')) === 'undefined', await evalJS('typeof window.__yunXueTangAuto'));
await evalJS(SCRIPT_SRC);
await sleep(1200);
const loadedLog = consoleLogs.find((l) => /云学堂助手 v[\d.]+ 已加载/.test(l.text));
check('控制台打印加载日志', !!loadedLog, loadedLog && loadedLog.text);
// ---- 4. 面板在真实 DOM 里的渲染 ----
const panel = await json(`JSON.stringify((() => {
const el = document.getElementById('yun-xue-tang-panel');
if (!el) return null;
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return {
version: (document.getElementById('yun-xue-tang-version') || {}).textContent || '',
w: Math.round(r.width), h: Math.round(r.height),
right: Math.round(innerWidth - r.right), bottom: Math.round(innerHeight - r.bottom),
visible: cs.display !== 'none' && cs.visibility !== 'hidden' && Number(cs.opacity) > 0,
position: cs.position, zIndex: cs.zIndex,
buttons: [...el.querySelectorAll('button')].map((b) => b.textContent.trim()),
inputTypes: [...el.querySelectorAll('input')].map((i) => i.type),
text: el.innerText.replace(/\\s+/g, ' ').trim().slice(0, 220),
};
})())`);
check('面板渲染进真实 DOM 且可见', panel && panel.visible && panel.w > 0 && panel.h > 0,
panel && { 宽: panel.w, 高: panel.h, position: panel.position, zIndex: panel.zIndex });
check('面板版本号 v2.7.0', panel && panel.version === 'v2.7.0', panel && panel.version);
check('固定在右下角', panel && panel.right >= 0 && panel.right < 40 && panel.bottom >= 0 && panel.bottom < 40,
panel && { 距右: panel.right, 距下: panel.bottom });
check('面板含按钮与密码框', panel && panel.buttons.length >= 2 && panel.inputTypes.includes('password'),
panel && { 按钮: panel.buttons, 输入框: panel.inputTypes });
// ---- 5. 真实页面上调试入口 / 页面识别 ----
const api = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
if (!a) return null;
return {
keys: Object.keys(a).length,
route: a.route(),
isLoginPage: a.isLoginPage(),
hasDispose: typeof window.__yunXueTangDispose === 'function',
courseId: a.courseIdFromUrl(),
summary: a.readSummary(),
countdown: a.readCountdown(),
};
})())`);
check('window.__yunXueTangAuto 调试入口存在', !!api && api.keys > 20, api && { 导出项: api.keys });
check('真实登录页被正确识别', api && api.isLoginPage === true, api && { route: api.route, isLoginPage: api.isLoginPage });
check('__yunXueTangDispose 可用(热替换前提)', api && api.hasDispose === true, api && api.hasDispose);
check('登录页上 readSummary/readCountdown 安全返回 null',
api && api.summary === null && api.countdown === null, api && { summary: api.summary, countdown: api.countdown });
// ---- 6. 真实点击面板按钮(不填账号,只验证不崩)----
const click = await json(`JSON.stringify((() => {
const panel = document.getElementById('yun-xue-tang-panel');
const btn = document.getElementById('yun-xue-tang-oneclick');
if (!btn) return { error: 'no #yun-xue-tang-oneclick' };
btn.click();
return {
label: btn.textContent.trim(),
panelVisibleAfter: getComputedStyle(panel).display !== 'none',
statusLine: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
panelText: panel.innerText.replace(/\\s+/g, ' ').slice(0, 200),
};
})())`);
await sleep(800);
const afterClick = await json(`JSON.stringify(({
url: location.href,
alive: typeof window.__yunXueTangAuto,
panel: !!document.getElementById('yun-xue-tang-panel'),
}))`);
check('点击「一键登录并刷课」不崩溃', afterClick.alive === 'object' && afterClick.panel === true, { 点击前标签: click.label, ...afterClick });
const scriptErrors = () => consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
check('无脚本自身 error 日志', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140)));
// ---- 7. 真实 localStorage 读写 ----
const ls = await json(`JSON.stringify((() => {
const before = localStorage.getItem('yun-xue-tang-auto-play-enabled');
localStorage.setItem('yun-xue-tang-auto-play-enabled', '0');
const read = localStorage.getItem('yun-xue-tang-auto-play-enabled');
if (before === null) localStorage.removeItem('yun-xue-tang-auto-play-enabled'); else localStorage.setItem('yun-xue-tang-auto-play-enabled', before);
return { read, keys: Object.keys(localStorage).filter((k) => k.indexOf('yun-xue-tang-') === 0) };
})())`);
check('真实 localStorage 可读写', ls.read === '0', ls);
// ---- 8. 真实热替换:dispose → 重新注入 ----
const hot = await json(`JSON.stringify((() => {
window.__yunXueTangDispose();
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto, dispose: typeof window.__yunXueTangDispose };
})())`);
await evalJS(SCRIPT_SRC);
await sleep(900);
const hot2 = await json(`JSON.stringify({
count: document.querySelectorAll('#yun-xue-tang-panel').length,
api: typeof window.__yunXueTangAuto,
version: (document.getElementById('yun-xue-tang-version') || {}).textContent,
timers: 'n/a',
})`);
check('dispose 后真实 DOM 面板被移除', hot.panel === false && hot.api === 'undefined',
hot);
check('重新注入后面板唯一且版本正确', hot2.count === 1 && hot2.api === 'object' && hot2.version === 'v2.7.0', hot2);
// ---- 9. 截图存证 ----
try {
fs.mkdirSync(SHOT_DIR, { recursive: true });
const shot = await cdp.send('Page.captureScreenshot', { format: 'png' });
const file = path.join(SHOT_DIR, 'real-chrome-login.png');
fs.writeFileSync(file, Buffer.from(shot.data, 'base64'));
const size = fs.statSync(file).size;
check('真机截图已保存', size > 5000, path.relative(ROOT, file) + ' (' + size + ' 字节)');
} catch (e) {
check('真机截图已保存', false, e.message);
}
// ---- 10. SPA 内 hash 路由(不换 document):脚本靠 hashchange 自更新,不需要重新注入 ----
const hashNav = await json(`JSON.stringify((() => {
location.hash = '#/list';
return { hash: location.hash, route: window.__yunXueTangAuto.route(), panel: !!document.getElementById('yun-xue-tang-panel') };
})())`);
await sleep(600);
const hashAfter = await json(`JSON.stringify({ hash: location.hash, route: window.__yunXueTangAuto.route(), alive: typeof window.__yunXueTangAuto })`);
check('SPA 内 hash 切换后脚本自动跟随路由', hashAfter.route === 'list' && hashAfter.alive === 'object', { 切前: hashNav, 切后: hashAfter });
// ---- 11. 未登录访问 #/list:站点整页重定向到登录页(新 document)----
// 真实 Tampermonkey 会在新 document 上按 @match 重新注入,这里同样重新注入后再断言。
// 先订阅 load 事件再触发跳转,避免竞态。
const redirected = cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await evalJS(`(() => { window.__yunXueTangDocMarker = 'before-nav'; location.href = 'https://kfmic.yunxuetang.cn/kng/#/list'; return true; })()`);
await redirected;
await sleep(2500);
const afterNav = await json(`JSON.stringify({
url: location.href,
host: location.host,
title: document.title,
newDocument: window.__yunXueTangDocMarker === undefined,
alive: typeof window.__yunXueTangAuto,
})`);
check('未登录访问 #/list 被站点重定向(document 已换新)',
/(^|\.)yunxuetang\.cn$/.test(afterNav.host) && afterNav.newDocument === true, afterNav);
check('新 document 上脚本未残留(重定向后必须重新注入)', afterNav.alive === 'undefined', afterNav.alive);
// 模拟 Tampermonkey 在新 document 上按 @match 自动注入
await evalJS(SCRIPT_SRC);
await sleep(1200);
const reinjected = await json(`JSON.stringify({
url: location.href,
route: window.__yunXueTangAuto ? window.__yunXueTangAuto.route() : 'no-api',
isLoginPage: window.__yunXueTangAuto ? window.__yunXueTangAuto.isLoginPage() : null,
panel: document.querySelectorAll('#yun-xue-tang-panel').length,
version: (document.getElementById('yun-xue-tang-version') || {}).textContent,
bodyScrollable: document.body.scrollHeight > 0,
})`);
check('重定向后重新注入:面板唯一且脚本正常',
reinjected.panel === 1 && reinjected.version === 'v2.7.0' && reinjected.route !== 'no-api', reinjected);
check('列表页导航无脚本报错', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140)));
// ---- 汇总控制台 ----
log('\n[真机] 控制台共 ' + consoleLogs.length + ' 条,最后 15 条:');
for (const l of consoleLogs.slice(-15)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
} catch (e) {
check('真机流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 4).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) {
await sleep(600);
try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {}
} else {
log('[真机] YUN_XUE_TANG_KEEP=1,浏览器保持打开:' + userDataDir);
}
}
const failed = results.filter((r) => !r.ok);
log('\n===== 真机结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);
+3 -3
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
* 云学堂自动刷课 · 本地开发服务器
* 云学堂助手 · 本地开发服务器
*
* 作用:把工作目录里的 yun-xue-tang-assistant.user.js 暴露给浏览器里的
* Tampermonkey 热加载器(dev/dev-loader.user.js)拉取。
@@ -22,7 +22,7 @@ import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..');
const HOST = '127.0.0.1';
const PORT = Number(process.env.YT_DEV_PORT || process.argv[2] || 8899);
const PORT = Number(process.env.YUN_XUE_TANG_DEV_PORT || process.argv[2] || 8899);
const FILES = {
'/src': path.join(ROOT, 'yun-xue-tang-assistant.user.js'),
@@ -59,7 +59,7 @@ function indexHtml() {
<style>body{font:14px/1.7 system-ui,"Microsoft YaHei";max-width:760px;margin:40px auto;padding:0 16px;color:#222}
code{background:#f2f2f4;padding:1px 5px;border-radius:4px}a{color:#2f7d5b}
.ok{color:#2f7d5b;font-weight:600}</style>
<h2>云学堂自动刷课 · 本地开发服务 <span class="ok">运行中</span></h2>
<h2>云学堂助手 · 本地开发服务 <span class="ok">运行中</span></h2>
<p>源码文件:<code>${path.join(ROOT, 'yun-xue-tang-assistant.user.js')}</code></p>
<ul>
<li><a href="/loader.user.js">安装 / 更新热加载器</a>(Tampermonkey 会弹出安装页)</li>
+5 -2
View File
@@ -1,10 +1,13 @@
@echo off
rem NOTE: keep this file PURE ASCII, see start-headless.cmd for why.
rem (cmd.exe parses batch files byte-by-byte with the current code page;
rem multi-byte characters corrupt line offsets.)
chcp 65001 >nul
cd /d "%~dp0.."
title YXT Cruise · 本地开发服务
title YXT Cruise - dev server
where node >nul 2>nul
if errorlevel 1 (
echo 未找到 node.exe,请先安装 Node.js(https://nodejs.org/)
echo [error] node.exe not found. Install Node.js from https://nodejs.org/
pause
exit /b 1
)