新增无头运行能力,解决 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 补无头部署章节
3048 lines
102 KiB
JavaScript
3048 lines
102 KiB
JavaScript
// ==UserScript==
|
||
// @name 云学堂助手
|
||
// @namespace yun-xue-tang-assistant.local
|
||
// @version 2.8.0
|
||
// @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并在课程列表页逐门自动刷课(单视频/音频课程也支持,含考试章节的课自动空卷交卷,学完自动进入下一门,可优先短课程;不跳过任何课程)
|
||
// @match *://kfmic.yunxuetang.cn/*
|
||
// @match *://*.yunxuetang.cn/*
|
||
// @grant none
|
||
// @run-at document-idle
|
||
// ==/UserScript==
|
||
|
||
/*
|
||
* 用法:
|
||
* 1. 浏览器安装 Tampermonkey,新建脚本,粘贴本文件全部内容并保存。
|
||
* 2. 打开 https://kfmic.yunxuetang.cn/login.html,在右下角面板填账号/密码,
|
||
* 点「一键登录并刷课」;登录成功后会自动进入课程列表并开始逐门学习。
|
||
* 3. 也可以手动登录后,在列表页点「一键刷课」。
|
||
*
|
||
* 密码保存:
|
||
* - 只有勾选「记住密码」才会写入本机 localStorage,使用 base64 混淆(不是加密,
|
||
* 本机其他脚本仍可读取)。公用电脑请不要勾选。
|
||
* - 不勾选时密码只用于本次登录,不会落盘。
|
||
*
|
||
* 重要说明:
|
||
* - 平台按“真实播放时长”计时,快进、倍速都不省时间,脚本只做自动播放和自动切节。
|
||
* - 同时支持多课时课程(#/course/play)和单视频/音频/课件播放页(#/video/play 等):
|
||
* 单视频课程会自动点「开始学习」;平台汇总变成「已完成学习」/100%/x=y 时判定整门课
|
||
* 完成,自动回列表并进入下一门。
|
||
* - 进入课程(列表刷课或自己点开)都会先对齐到「第一个未学完的课时」,即从第一章第一节起
|
||
* 顺序学习,不沿用平台上次停留的位置(否则前面的课时会被跳过,整门课永远学不完)。
|
||
* 切换成功与否以目录高亮为准:没切过去会重试并如实提示「未能切换」,不会假装已切换。
|
||
* - 试跑稳定后,把 config.js 里的 CFG.maxCourses 改成 0 即可不限门数(会持续很久)。
|
||
* - 脚本不跳过任何课程:没有「跳过本课」,也不会把课程拉黑。某门课没学完(例如遇到
|
||
* 需要人工完成的滑块/拼图验证、答题/测验章节、长时间无计时进展)就退避重试:
|
||
* 30 秒起每次翻倍、最长 5 分钟,同一门课最多重试 CFG.maxCourseRetries 次,
|
||
* 超过才停下整轮刷课并在面板写明原因,等人工处理后点「一键刷课」接着跑。
|
||
* - 选课每次都动态查询:每完成一门课都重新调列表接口,拿平台实时的已完成/未完成状态,
|
||
* 再按总时长从短到长挑下一门,不使用本地缓存的旧快照。
|
||
* - 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」。
|
||
* - 考试章节支持:自动进入考试、不答题直接交卷(空白交卷)。交卷后平台会把考试节点
|
||
* 计入课程进度,含考试章节的课程也能学完。
|
||
* 同一门课最多交卷 CFG.maxExamTries 次,超过仍没计入进度就按普通未完成退避重试。
|
||
* - 验证码/滑块需要手动完成,脚本不会绕过。
|
||
* - 课程/单位如有相关规定,请自行确认风险。
|
||
*
|
||
* 短课程优先:
|
||
* - 面板勾选「优先短课程(时长正序)」后,列表刷课会先读课程列表接口里的总时长,
|
||
* 按「未学完课程的总时长从短到长」选课,而不是按列表顺序。接口不可用时会自动
|
||
* 退回为「当前页按时长正序」,再不行就按原来的列表顺序,不会卡住刷课任务。
|
||
*
|
||
* 无头运行(Linux 服务器 / Windows 无人值守):
|
||
* - 不装 Tampermonkey 也能跑:仓库里的 runner/headless.mjs 会自己起一个无头 Chromium,
|
||
* 用 CDP 把本文件注入页面主世界(等价 @grant none),并用固定 profile 持久化登录。
|
||
* npm run build && npm run headless:check && npm run headless(凭据读环境变量)。
|
||
* Windows 上也可以直接双击 start-headless.cmd。
|
||
* - 需要在无头环境里调试本文件时,可以把 window.__yunXueTangAuto 当成调试入口,
|
||
* 用 runtime.evaluate 直接调 tick()/startBatch()/readSummary() 等,不必开界面。
|
||
*
|
||
* 开发热加载:
|
||
* - 本文件可直接被 dev/dev-loader.user.js 热注入:脚本暴露 window.__yunXueTangDispose(),
|
||
* 加载器在注入新版本前会先调用它清理定时器、监听器与面板,因此保存文件后
|
||
* 约 1 秒内即可生效,无需手动刷新页面。
|
||
*/
|
||
|
||
"use strict";
|
||
(() => {
|
||
// src/config.js
|
||
var CFG = {
|
||
mute: true,
|
||
// 静音(自动播放更稳)
|
||
autoNext: true,
|
||
// 当前课程自动连播:本节结束后自动下一节
|
||
tickMs: 2e3,
|
||
// 主循环间隔
|
||
startClickCooldownMs: 3e3,
|
||
// 「开始学习」重复点击冷却(3 秒内没起播就补点)
|
||
entryGraceMs: 3e4,
|
||
// 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」
|
||
stuckMs: 5 * 60 * 1e3,
|
||
// 连续多久没有计时进展就放弃当前课程
|
||
maxCourses: 10,
|
||
// 本次最多完成多少门;0 = 不限
|
||
maxCourseRetries: 5,
|
||
// 同一门课最多重试多少次(不跳过课程,超次数就停下整轮刷课)
|
||
courseRetryDelayMs: 3e4,
|
||
// 首次重试前的等待;之后每次翻倍,最长 5 分钟
|
||
alignToFirstIncomplete: true,
|
||
// 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置
|
||
preferShortCourses: true,
|
||
// 列表刷课时优先总时长更短的课程(正序)
|
||
maxExamTries: 2,
|
||
// 同一门课「空卷交卷」的最大次数(平台没记账时避免死循环)
|
||
examClickCooldownMs: 1500,
|
||
// 考试页内两次点击的间隔
|
||
staleCourseMs: 10 * 60 * 1e3
|
||
// 恢复「当前课程」时允许的最大年龄,更旧的一律丢弃
|
||
};
|
||
var VERSION = "2.8.0";
|
||
var LS_ENABLED = "yun-xue-tang-auto-play-enabled";
|
||
var LS_PREFER_SHORT = "yun-xue-tang-prefer-short";
|
||
var LS_TARGET_CATALOG_URL = "yun-xue-tang-target-catalog-url";
|
||
var LS_LOGIN = "yun-xue-tang-login-v1";
|
||
var LS_PENDING = "yun-xue-tang-auto-start-after-login";
|
||
var SS_RUN_STATE = "yun-xue-tang-run-state-v3";
|
||
var SS_SHORT_CATALOG = "yun-xue-tang-short-catalog-v1";
|
||
var SHORT_CATALOG_TTL = 5 * 60 * 1e3;
|
||
var LEGACY_LS_BATCH = "yun-xue-tang-batch-v2";
|
||
var PANEL_ID = "yun-xue-tang-panel";
|
||
var TAG = "[云学堂助手]";
|
||
|
||
// src/state.js
|
||
var state = {
|
||
autoPlayEnabled: true,
|
||
// 当前课程自动连播(自己点开的课)
|
||
preferShortCourses: CFG.preferShortCourses
|
||
// 列表刷课时优先后时长更短的课程(正序)
|
||
};
|
||
try {
|
||
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== "0";
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
const v = localStorage.getItem(LS_PREFER_SHORT);
|
||
if (v === "0" || v === "1") state.preferShortCourses = v === "1";
|
||
} catch (e) {
|
||
}
|
||
var PHASE_ENTERING = "entering";
|
||
var PHASE_LEARNING = "learning";
|
||
var PHASE_IDLE = "idle";
|
||
var VALID_PHASES = /* @__PURE__ */ new Set([PHASE_IDLE, PHASE_ENTERING, PHASE_LEARNING]);
|
||
function defaultRunState() {
|
||
return {
|
||
// ---- 运行意图 ----
|
||
batchRunning: false,
|
||
// 列表刷课是否在跑(只在本标签页内有效)
|
||
batchFinished: false,
|
||
// 本轮已停止(达上限 / 重试用尽 / 无课可学)
|
||
completedThisRun: 0,
|
||
// 本轮已完成门数
|
||
// ---- 选课范围 ----
|
||
// 目标目录 URL:决定「刷哪个学院/目录」的课,也是短课程队列的缓存键来源。
|
||
// 值同时镜像到 localStorage(LS_TARGET_CATALOG_URL),所以跨会话仍然有效。
|
||
catalogUrl: "",
|
||
// 例:https://kfmic.yunxuetang.cn/kng/#/list?cid=…
|
||
listPage: 1,
|
||
// 列表页码(短课程队列不可用时是唯一的页码来源)
|
||
// ---- 当前课程 ----
|
||
activeCourse: null,
|
||
// { title, id, startedAt }
|
||
coursePhase: PHASE_IDLE,
|
||
// idle | entering | learning
|
||
awaitingListReturn: false,
|
||
// 刚学完/失败,正在回列表途中
|
||
// ---- 本轮记录 ----
|
||
completedTitles: {},
|
||
// 课程名 -> 完成时间戳(防平台记账延迟时重进同一门)
|
||
courseRetries: {},
|
||
// 课程名 -> { n, reason, at }(未完成重试次数)
|
||
examEmptySubmits: {}
|
||
// 课程 id -> 空卷交卷次数(防死循环)
|
||
};
|
||
}
|
||
var S = defaultRunState();
|
||
function asMap(v) {
|
||
return v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
||
}
|
||
function restoreFrom(obj) {
|
||
if (!obj || typeof obj !== "object") return null;
|
||
const out = defaultRunState();
|
||
out.batchRunning = obj.batchRunning === true;
|
||
out.batchFinished = obj.batchFinished === true;
|
||
const done = Number(obj.completedThisRun);
|
||
out.completedThisRun = Number.isFinite(done) && done >= 0 ? Math.floor(done) : 0;
|
||
out.catalogUrl = typeof obj.catalogUrl === "string" ? obj.catalogUrl : "";
|
||
const page = Number(obj.listPage);
|
||
out.listPage = Number.isFinite(page) && page >= 1 ? Math.floor(page) : 1;
|
||
const cur = obj.activeCourse;
|
||
const startedAt = cur && Number(cur.startedAt);
|
||
const visiblePhase = VALID_PHASES.has(obj.coursePhase) ? obj.coursePhase : PHASE_ENTERING;
|
||
if (cur && cur.title && Number.isFinite(startedAt)) {
|
||
const stale = Date.now() - startedAt > CFG.staleCourseMs;
|
||
const keep = visiblePhase === PHASE_LEARNING || !stale;
|
||
out.activeCourse = keep ? { title: String(cur.title), id: String(cur.id || ""), startedAt } : null;
|
||
out.coursePhase = keep ? visiblePhase : PHASE_IDLE;
|
||
} else {
|
||
out.activeCourse = null;
|
||
out.coursePhase = PHASE_IDLE;
|
||
}
|
||
out.awaitingListReturn = obj.awaitingListReturn === true;
|
||
out.completedTitles = asMap(obj.completedTitles);
|
||
out.courseRetries = asMap(obj.courseRetries);
|
||
out.examEmptySubmits = asMap(obj.examEmptySubmits);
|
||
return out;
|
||
}
|
||
function migrateLegacy() {
|
||
let raw = null;
|
||
try {
|
||
raw = localStorage.getItem(LEGACY_LS_BATCH);
|
||
} catch (e) {
|
||
return;
|
||
}
|
||
if (!raw) return;
|
||
try {
|
||
const old = JSON.parse(raw);
|
||
if (old && typeof old === "object") {
|
||
const done = asMap(old.done);
|
||
for (const k of Object.keys(done)) {
|
||
const at = Number(done[k]);
|
||
if (!Number.isFinite(at) || Date.now() - at > CFG.staleCourseMs) delete done[k];
|
||
}
|
||
S.completedTitles = done;
|
||
S.courseRetries = asMap(old.retries);
|
||
S.examEmptySubmits = asMap(old.examTried);
|
||
const page = Number(old.listPage);
|
||
if (Number.isFinite(page) && page >= 1) S.listPage = Math.floor(page);
|
||
const url = typeof old.listUrl === "string" ? old.listUrl : "";
|
||
if (url) setTargetCatalogUrl(url, { silent: true });
|
||
}
|
||
console.log("[云学堂助手] 已迁移旧版本进度记录(不再恢复旧的运行状态)");
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
localStorage.removeItem(LEGACY_LS_BATCH);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
(function restore() {
|
||
let restored = null;
|
||
try {
|
||
const raw = sessionStorage.getItem(SS_RUN_STATE);
|
||
if (raw) restored = restoreFrom(JSON.parse(raw));
|
||
} catch (e) {
|
||
}
|
||
if (restored) Object.assign(S, restored);
|
||
S.catalogUrl = readTargetCatalogUrl() || S.catalogUrl;
|
||
migrateLegacy();
|
||
})();
|
||
var lastWritten = "";
|
||
function saveRunState() {
|
||
try {
|
||
const text = JSON.stringify(S);
|
||
if (text === lastWritten) return;
|
||
lastWritten = text;
|
||
sessionStorage.setItem(SS_RUN_STATE, text);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function flushRunState() {
|
||
lastWritten = "";
|
||
saveRunState();
|
||
}
|
||
function readTargetCatalogUrl() {
|
||
try {
|
||
return localStorage.getItem(LS_TARGET_CATALOG_URL) || "";
|
||
} catch (e) {
|
||
return "";
|
||
}
|
||
}
|
||
function setTargetCatalogUrl(url, opt) {
|
||
const next = String(url || "");
|
||
if (!next) return;
|
||
const changed = S.catalogUrl !== next;
|
||
S.catalogUrl = next;
|
||
try {
|
||
localStorage.setItem(LS_TARGET_CATALOG_URL, next);
|
||
} catch (e) {
|
||
}
|
||
if (changed && !(opt && opt.silent)) saveRunState();
|
||
}
|
||
var R = {
|
||
hooked: /* @__PURE__ */ new WeakSet(),
|
||
lastCardClickAt: 0,
|
||
entryRetries: 0,
|
||
// 点卡片后仍停在列表时,重试进入课程的次数
|
||
lastPageJumpAt: 0,
|
||
pageChangeAt: 0,
|
||
pageChangeSig: "",
|
||
listWithCurrentSince: 0,
|
||
lastGoListAt: 0,
|
||
lastStartClickAt: 0,
|
||
lastAdvanceAt: 0,
|
||
manualAdvanceAt: 0,
|
||
lastLessonKey: "",
|
||
doneLatchKey: "",
|
||
// 本节已播完(倒计时归零/video.ended),防止平台把视频拉回开头重播
|
||
lastSummary: null,
|
||
lastCountdown: null,
|
||
lastProgressAt: Date.now(),
|
||
waitStart: 0,
|
||
waitSummaryX: -1,
|
||
waitLessonKey: "",
|
||
quizChecked: false,
|
||
// 考试(空卷交卷)自动处理状态
|
||
examPhase: "",
|
||
// '' | preview | paper | result
|
||
examActionAt: 0,
|
||
// 上次考试页内点击时间
|
||
examStarts: 0,
|
||
// 本形态点了多少次「开始考试」
|
||
examSubmits: 0,
|
||
// 本形态点了多少次「提交考试」
|
||
examConfirms: 0,
|
||
// 本形态点了多少次交卷确认「确定」
|
||
examPaperAt: 0,
|
||
// 进入答卷页的时间(等题目渲染)
|
||
examLeaving: false,
|
||
// 已交卷,正在返回课程页
|
||
examLessonAt: 0,
|
||
// 上次点「考试节」的时间(防抖)
|
||
examLessonTries: 0,
|
||
// 本次进考试节已点次数
|
||
examLessonKey: "",
|
||
// examLessonTries 所属课程(换课重置,同课重进保留)
|
||
initialLessonChecked: false,
|
||
phaseSince: 0,
|
||
alignTries: 0,
|
||
alignStable: 0,
|
||
alignFailed: false,
|
||
manualCourseKey: "",
|
||
lastIdleClickAt: 0,
|
||
idlePassed: 0,
|
||
idleDialogText: "",
|
||
idleDialogClicks: 0,
|
||
idleGaveUp: false,
|
||
pageRestoreAttempts: 0,
|
||
retryWaitUntil: 0,
|
||
// 重试退避的结束时间(未到点不进课)
|
||
retryTitle: "",
|
||
// 正在等待重试的课程名(面板提示用)
|
||
loginFilled: false,
|
||
loginSubmittingAt: 0,
|
||
loginAutoTried: false,
|
||
loginBoundUser: null,
|
||
loginBoundPwd: null,
|
||
// 短课程优先:课程时长队列(只在当前标签页会话内缓存)
|
||
shortCatalog: null,
|
||
shortCatalogLoading: false,
|
||
shortCatalogFailedAt: 0,
|
||
shortFetchStartedAt: 0,
|
||
shortJumpAt: 0,
|
||
shortNoVmSince: 0,
|
||
shortWarnedAt: 0,
|
||
retryStatusSec: -1
|
||
// 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
|
||
};
|
||
function invalidateShortCatalog() {
|
||
R.shortCatalog = null;
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = 0;
|
||
R.shortNoVmSince = 0;
|
||
try {
|
||
sessionStorage.removeItem(SS_SHORT_CATALOG);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function resetCourseRuntime() {
|
||
R.lastLessonKey = "";
|
||
R.doneLatchKey = "";
|
||
R.lastSummary = null;
|
||
R.lastCountdown = null;
|
||
R.lastProgressAt = Date.now();
|
||
R.waitStart = 0;
|
||
R.waitSummaryX = -1;
|
||
R.waitLessonKey = "";
|
||
R.quizChecked = false;
|
||
R.examPhase = "";
|
||
R.examActionAt = 0;
|
||
R.examStarts = 0;
|
||
R.examSubmits = 0;
|
||
R.examConfirms = 0;
|
||
R.examPaperAt = 0;
|
||
R.examLeaving = false;
|
||
R.initialLessonChecked = false;
|
||
R.phaseSince = 0;
|
||
R.alignTries = 0;
|
||
R.alignStable = 0;
|
||
R.alignFailed = false;
|
||
R.manualCourseKey = "";
|
||
R.lastAdvanceAt = 0;
|
||
R.pageRestoreAttempts = 0;
|
||
R.entryRetries = 0;
|
||
}
|
||
|
||
// src/lifecycle.js
|
||
var TIMERS = [];
|
||
var DELAYS = [];
|
||
var WINDOW_LISTENERS = [];
|
||
var ELEMENT_LISTENERS = [];
|
||
function every(fn, ms) {
|
||
const id = setInterval(fn, ms);
|
||
TIMERS.push(id);
|
||
return id;
|
||
}
|
||
function later(fn, ms) {
|
||
const id = setTimeout(function() {
|
||
const i = DELAYS.indexOf(id);
|
||
if (i >= 0) DELAYS.splice(i, 1);
|
||
try {
|
||
fn();
|
||
} catch (e) {
|
||
console.error(TAG, e);
|
||
}
|
||
}, ms);
|
||
DELAYS.push(id);
|
||
return id;
|
||
}
|
||
function onWindow(target, type, fn) {
|
||
target.addEventListener(type, fn);
|
||
WINDOW_LISTENERS.push([target, type, fn]);
|
||
}
|
||
function onElement(el, type, fn) {
|
||
el.addEventListener(type, fn);
|
||
ELEMENT_LISTENERS.push([el, type, fn]);
|
||
}
|
||
function detachListener(x) {
|
||
x[0].removeEventListener(x[1], x[2]);
|
||
}
|
||
function drain(arr, fn) {
|
||
arr.splice(0).forEach(function(x) {
|
||
try {
|
||
fn(x);
|
||
} catch (e) {
|
||
}
|
||
});
|
||
}
|
||
function dispose() {
|
||
drain(TIMERS, clearInterval);
|
||
drain(DELAYS, clearTimeout);
|
||
drain(WINDOW_LISTENERS, detachListener);
|
||
drain(ELEMENT_LISTENERS, detachListener);
|
||
try {
|
||
document.querySelectorAll("video[data-yun-xue-tang-hooked]").forEach(function(v) {
|
||
v.removeAttribute("data-yun-xue-tang-hooked");
|
||
});
|
||
} catch (e) {
|
||
}
|
||
const panel = document.getElementById(PANEL_ID);
|
||
if (panel && panel.parentNode) panel.parentNode.removeChild(panel);
|
||
try {
|
||
delete window.__yunXueTangAuto;
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
if (window.__yunXueTangDispose === dispose) delete window.__yunXueTangDispose;
|
||
} catch (e) {
|
||
}
|
||
console.log(TAG, "旧实例已释放");
|
||
}
|
||
try {
|
||
Object.defineProperty(window, "__yunXueTangDispose", {
|
||
value: dispose,
|
||
configurable: true,
|
||
writable: true
|
||
});
|
||
} catch (e) {
|
||
}
|
||
|
||
// src/utils.js
|
||
var norm = (s) => String(s || "").replace(/\s/g, "");
|
||
var truncate = (s, n) => s.length > n ? s.slice(0, n) + "…" : s;
|
||
function textOf(el) {
|
||
try {
|
||
return norm(el.innerText || el.textContent || "");
|
||
} catch (e) {
|
||
return "";
|
||
}
|
||
}
|
||
function isVisible(el) {
|
||
try {
|
||
const win = el.ownerDocument && el.ownerDocument.defaultView || window;
|
||
const r = el.getBoundingClientRect();
|
||
if (r.width === 0 || r.height === 0) return false;
|
||
const cs = win.getComputedStyle(el);
|
||
return cs.display !== "none" && cs.visibility !== "hidden" && Number(cs.opacity) > 0;
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
function findVisibleButton(re) {
|
||
const els = document.querySelectorAll('button, [role="button"], a');
|
||
for (const el of els) {
|
||
if (re.test(textOf(el)) && isVisible(el)) return el;
|
||
}
|
||
return null;
|
||
}
|
||
function findVisibleClickable(re) {
|
||
const btn = findVisibleButton(re);
|
||
if (btn && !btn.disabled) return btn;
|
||
const els = document.querySelectorAll("div, span");
|
||
for (const el of els) {
|
||
if (el.children.length > 0) continue;
|
||
if (!isVisible(el) || !re.test(textOf(el))) continue;
|
||
if (el.closest && el.closest("button[disabled]")) continue;
|
||
return el;
|
||
}
|
||
return null;
|
||
}
|
||
function courseIdFromUrl() {
|
||
const m = String(location.hash || "").match(/[?&]kngId=([^&]+)/);
|
||
if (!m) return "";
|
||
try {
|
||
return decodeURIComponent(m[1]);
|
||
} catch (e) {
|
||
return m[1];
|
||
}
|
||
}
|
||
var GENERIC_TITLE_RE = /^(loading|加载中|在线课堂|云课堂|云学堂|江丰云课堂|课程详情|课程|首页|我的学习)$/i;
|
||
function isGenericCourseTitle(t) {
|
||
return !norm(t) || GENERIC_TITLE_RE.test(norm(t));
|
||
}
|
||
function collectDocuments(win, out) {
|
||
win = win || window;
|
||
out = out || [];
|
||
try {
|
||
if (win.document) out.push(win.document);
|
||
} catch (e) {
|
||
}
|
||
try {
|
||
for (let i = 0; i < win.frames.length; i++) {
|
||
collectDocuments(win.frames[i], out);
|
||
}
|
||
} catch (e) {
|
||
}
|
||
return out;
|
||
}
|
||
|
||
// src/route.js
|
||
function route() {
|
||
const h = location.hash || "";
|
||
if (h.indexOf("#/list") === 0) return "list";
|
||
if (h.indexOf("#/scan") === 0) return "course";
|
||
if (/^#\/[a-z0-9_-]+\/play(?:[?/]|$)/i.test(h)) return "course";
|
||
return "other";
|
||
}
|
||
function mediaPage() {
|
||
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || "");
|
||
}
|
||
function goToList(force) {
|
||
if (!force && Date.now() - R.lastGoListAt < 5e3) return;
|
||
R.lastGoListAt = Date.now();
|
||
const url = S.catalogUrl || location.origin + "/kng/#/list";
|
||
if (route() === "list") {
|
||
S.awaitingListReturn = true;
|
||
saveRunState();
|
||
return;
|
||
}
|
||
try {
|
||
location.href = url;
|
||
} catch (e) {
|
||
location.hash = "#/list";
|
||
}
|
||
}
|
||
|
||
// src/login.js
|
||
var tick = function() {
|
||
};
|
||
function setTick(fn) {
|
||
tick = fn;
|
||
}
|
||
function clearPending() {
|
||
try {
|
||
localStorage.removeItem(LS_PENDING);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function isLoginPage() {
|
||
if (/\/login(\.html)?($|[?#])/i.test(location.pathname + location.search)) return true;
|
||
if (/^#\/login/i.test(location.hash)) return true;
|
||
return !!document.querySelector('input[type="password"]') && /登录/.test(document.title);
|
||
}
|
||
function loginFields() {
|
||
const pwd = [...document.querySelectorAll('input[type="password"]')].find(isVisible) || null;
|
||
const all = [...document.querySelectorAll("input")].filter(isVisible);
|
||
let user = all.find(function(el) {
|
||
return /员工邮箱|账号|用户名|邮箱|手机号/.test(el.placeholder || "");
|
||
}) || null;
|
||
if (!user && pwd) {
|
||
const pi = all.indexOf(pwd);
|
||
for (let i = pi - 1; i >= 0; i--) {
|
||
const el = all[i];
|
||
if (el.type === "text" || el.type === "email" || !el.type) {
|
||
user = el;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return { user, pwd };
|
||
}
|
||
function setNativeValue(el, value) {
|
||
if (!el) return false;
|
||
try {
|
||
const proto = el.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
||
const setter = Object.getOwnPropertyDescriptor(proto, "value").set;
|
||
setter.call(el, value);
|
||
} catch (e) {
|
||
el.value = value;
|
||
}
|
||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||
el.dispatchEvent(new Event("change", { bubbles: true }));
|
||
el.dispatchEvent(new Event("blur", { bubbles: true }));
|
||
return true;
|
||
}
|
||
function findLoginVm() {
|
||
const btn = findVisibleButton(/^登录$/);
|
||
let vm = btn && btn.__vue__;
|
||
while (vm && vm.$options.name !== "Login") vm = vm.$parent;
|
||
if (vm) return vm;
|
||
for (const el of document.querySelectorAll("#app, #app *")) {
|
||
const v = el.__vue__;
|
||
if (v && v.pwdLoginForm) return v;
|
||
}
|
||
return null;
|
||
}
|
||
function fillLoginForm(user, pass) {
|
||
const f = loginFields();
|
||
if (!f.user || !f.pwd) return false;
|
||
setNativeValue(f.user, user);
|
||
setNativeValue(f.pwd, pass);
|
||
const vm = findLoginVm();
|
||
if (vm && vm.pwdLoginForm) {
|
||
vm.pwdLoginForm.userName = user;
|
||
vm.pwdLoginForm.password = pass;
|
||
}
|
||
return true;
|
||
}
|
||
function checkLoginAgreement() {
|
||
const labels = [...document.querySelectorAll("label")].filter(function(l) {
|
||
return /已阅读并同意|隐私政策/.test(l.innerText || "") && isVisible(l);
|
||
});
|
||
if (!labels.length) return true;
|
||
for (const label of labels) {
|
||
const cb = label.querySelector('input[type="checkbox"]');
|
||
if (!cb) continue;
|
||
if (!cb.checked) {
|
||
try {
|
||
label.click();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
if (!cb.checked) {
|
||
try {
|
||
cb.click();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
if (cb.checked) return true;
|
||
}
|
||
return false;
|
||
}
|
||
function b64enc(s) {
|
||
const bytes = new TextEncoder().encode(String(s));
|
||
let bin = "";
|
||
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
||
return btoa(bin);
|
||
}
|
||
function b64dec(s) {
|
||
const bin = atob(String(s));
|
||
const bytes = new Uint8Array(bin.length);
|
||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||
return new TextDecoder().decode(bytes);
|
||
}
|
||
function saveCreds(user, pass, remember, auto) {
|
||
try {
|
||
if (!remember) {
|
||
localStorage.removeItem(LS_LOGIN);
|
||
return;
|
||
}
|
||
localStorage.setItem(LS_LOGIN, b64enc(JSON.stringify({ u: user, p: pass, auto: !!auto })));
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function loadCreds() {
|
||
try {
|
||
const raw = localStorage.getItem(LS_LOGIN);
|
||
if (!raw) return null;
|
||
const obj = JSON.parse(b64dec(raw));
|
||
if (!obj || !obj.u || !obj.p) return null;
|
||
return { u: String(obj.u), p: String(obj.p), auto: !!obj.auto };
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
function clearSavedCreds() {
|
||
try {
|
||
localStorage.removeItem(LS_LOGIN);
|
||
} catch (e) {
|
||
}
|
||
if (loginRememberEl) loginRememberEl.checked = false;
|
||
}
|
||
function startBatch() {
|
||
if (S.batchFinished) {
|
||
S.completedThisRun = 0;
|
||
S.batchFinished = false;
|
||
S.courseRetries = {};
|
||
R.retryWaitUntil = 0;
|
||
R.retryTitle = "";
|
||
}
|
||
S.batchRunning = true;
|
||
invalidateShortCatalog();
|
||
if (!S.activeCourse) S.coursePhase = PHASE_IDLE;
|
||
saveRunState();
|
||
setStatus("列表刷课已开启");
|
||
const r = route();
|
||
if (r === "list" || r === "course" && S.activeCourse) {
|
||
tick();
|
||
} else {
|
||
goToList();
|
||
}
|
||
updatePanel();
|
||
}
|
||
function consumePendingStart() {
|
||
let ts = 0;
|
||
try {
|
||
ts = Number(localStorage.getItem(LS_PENDING) || 0);
|
||
} catch (e) {
|
||
}
|
||
if (!ts) return false;
|
||
if (Date.now() - ts > 5 * 60 * 1e3) {
|
||
clearPending();
|
||
return false;
|
||
}
|
||
if (isLoginPage()) return false;
|
||
clearPending();
|
||
startBatch();
|
||
return true;
|
||
}
|
||
function watchLoginResult() {
|
||
if (!isLoginPage()) return;
|
||
const vm = findLoginVm();
|
||
if (vm && vm.captchaVisible) {
|
||
setStatus("需要手动完成验证码/滑块,完成后会自动继续");
|
||
return;
|
||
}
|
||
if (vm && typeof vm.pwd_tips === "string" && vm.pwd_tips.trim()) {
|
||
clearPending();
|
||
R.loginSubmittingAt = 0;
|
||
setStatus("登录失败:" + truncate(vm.pwd_tips.trim(), 50));
|
||
return;
|
||
}
|
||
const txt = document.body.innerText || "";
|
||
const err = txt.match(/(用户名密码错误[^\n]{0,60}|账号或密码错误[^\n]{0,60}|密码错误[^\n]{0,60}|账号不存在[^\n]{0,60}|登录失败[^\n]{0,60})/);
|
||
if (err) {
|
||
clearPending();
|
||
R.loginSubmittingAt = 0;
|
||
setStatus("登录失败:" + truncate(err[0], 50));
|
||
return;
|
||
}
|
||
if (/验证码|安全验证|滑块/.test(txt) && R.loginSubmittingAt) {
|
||
setStatus("需要手动完成验证码/滑块,完成后会自动继续");
|
||
return;
|
||
}
|
||
if (R.loginSubmittingAt && Date.now() - R.loginSubmittingAt > 12e3) {
|
||
R.loginSubmittingAt = 0;
|
||
setStatus("尚未登录成功:请检查账号密码,或手动完成验证");
|
||
}
|
||
}
|
||
function doLoginAndStart() {
|
||
const f = loginFields();
|
||
const user = (loginUserEl ? loginUserEl.value.trim() : "") || (f.user ? String(f.user.value || "").trim() : "");
|
||
const pass = (loginPassEl ? loginPassEl.value : "") || (f.pwd ? String(f.pwd.value || "") : "");
|
||
if (!user || !pass) {
|
||
setStatus("请先填写账号和密码");
|
||
return;
|
||
}
|
||
if (loginUserEl) loginUserEl.value = user;
|
||
if (loginPassEl) loginPassEl.value = pass;
|
||
const remember = !!(loginRememberEl && loginRememberEl.checked);
|
||
const auto = !!(loginAutoEl && loginAutoEl.checked);
|
||
saveCreds(user, pass, remember, auto);
|
||
fillLoginForm(user, pass);
|
||
if (!checkLoginAgreement()) {
|
||
setStatus("请先勾选《隐私政策》");
|
||
return;
|
||
}
|
||
try {
|
||
localStorage.setItem(LS_PENDING, String(Date.now()));
|
||
} catch (e) {
|
||
}
|
||
R.loginSubmittingAt = Date.now();
|
||
R.loginAutoTried = true;
|
||
setStatus("正在登录…");
|
||
const vm = findLoginVm();
|
||
if (vm) {
|
||
try {
|
||
if (vm.pwdLoginForm) {
|
||
vm.pwdLoginForm.userName = user;
|
||
vm.pwdLoginForm.password = pass;
|
||
}
|
||
try {
|
||
vm.agreeSecretProtocol = true;
|
||
} catch (e) {
|
||
}
|
||
const p = vm.handleLogin();
|
||
if (p && typeof p.catch === "function") {
|
||
p.catch(function(e) {
|
||
setStatus("登录异常:" + (e && e.message ? e.message : e));
|
||
});
|
||
}
|
||
} catch (e) {
|
||
setStatus("登录异常:" + (e && e.message ? e.message : e));
|
||
}
|
||
} else {
|
||
const btn = findVisibleButton(/^登录$/);
|
||
if (btn) {
|
||
try {
|
||
btn.click();
|
||
} catch (e) {
|
||
}
|
||
} else {
|
||
setStatus("未找到登录按钮,请手动点击");
|
||
}
|
||
}
|
||
later(watchLoginResult, 2500);
|
||
}
|
||
function loginPageTick() {
|
||
if (!isLoginPage()) return;
|
||
const f = loginFields();
|
||
if (f.user && f.pwd && (R.loginBoundUser !== f.user || R.loginBoundPwd !== f.pwd)) {
|
||
R.loginBoundUser = f.user;
|
||
R.loginBoundPwd = f.pwd;
|
||
const sync = function() {
|
||
if (loginUserEl) loginUserEl.value = f.user.value;
|
||
if (loginPassEl) loginPassEl.value = f.pwd.value;
|
||
};
|
||
onElement(f.user, "input", sync);
|
||
onElement(f.pwd, "input", sync);
|
||
}
|
||
if (!R.loginFilled) {
|
||
if (f.user && f.pwd) {
|
||
R.loginFilled = true;
|
||
const creds = loadCreds();
|
||
if (creds) {
|
||
fillLoginForm(creds.u, creds.p);
|
||
if (loginUserEl) loginUserEl.value = creds.u;
|
||
if (loginPassEl) loginPassEl.value = creds.p;
|
||
if (loginRememberEl) loginRememberEl.checked = true;
|
||
if (loginAutoEl) loginAutoEl.checked = !!creds.auto;
|
||
setStatus("已填充保存的账号,可点「一键登录并刷课」");
|
||
if (creds.auto && !R.loginAutoTried) {
|
||
R.loginAutoTried = true;
|
||
later(function() {
|
||
doLoginAndStart();
|
||
}, 800);
|
||
}
|
||
} else {
|
||
setStatus("填写账号密码后,点「一键登录并刷课」");
|
||
}
|
||
}
|
||
}
|
||
if (R.loginSubmittingAt) watchLoginResult();
|
||
}
|
||
|
||
// src/panel.js
|
||
var SESSION_START_AT = Date.now();
|
||
var statusEl = null;
|
||
var statsEl = null;
|
||
var footerEl = null;
|
||
var cbBatch = null;
|
||
var labelAuto = null;
|
||
var labelBatch = null;
|
||
var labelShort = null;
|
||
var cbPreferShort = null;
|
||
var cbAuto = null;
|
||
var loginBox = null;
|
||
var loginUserEl = null;
|
||
var loginPassEl = null;
|
||
var loginRememberEl = null;
|
||
var loginAutoEl = null;
|
||
var btnOne = null;
|
||
var btnClearCreds = null;
|
||
var LABEL_CSS = "display:flex;align-items:center;gap:6px;cursor:pointer;margin-top:4px;";
|
||
function formatElapsed(ms) {
|
||
const total = Math.max(0, Math.floor(ms / 1e3));
|
||
const h = Math.floor(total / 3600);
|
||
const m = Math.floor(total % 3600 / 60);
|
||
const s = total % 60;
|
||
const p = function(n) {
|
||
return n < 10 ? "0" + n : "" + n;
|
||
};
|
||
return h > 0 ? h + ":" + p(m) + ":" + p(s) : m + ":" + p(s);
|
||
}
|
||
function setStatus(text) {
|
||
console.log(TAG, text);
|
||
if (statusEl) statusEl.textContent = text;
|
||
}
|
||
function updatePanel() {
|
||
if (cbBatch) cbBatch.checked = S.batchRunning;
|
||
if (statsEl) {
|
||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : "∞";
|
||
let text = "本次 " + S.completedThisRun + "/" + limit;
|
||
const retryTitles = Object.keys(S.courseRetries || {}).length;
|
||
if (retryTitles) text += " · 待重试 " + retryTitles;
|
||
if (R.retryWaitUntil && Date.now() < R.retryWaitUntil) {
|
||
text += " · " + Math.ceil((R.retryWaitUntil - Date.now()) / 1e3) + "s 后重试";
|
||
}
|
||
text += R.idlePassed ? " · 验证 " + R.idlePassed : "";
|
||
statsEl.textContent = text;
|
||
}
|
||
if (footerEl) {
|
||
footerEl.textContent = "会话时长 " + formatElapsed(Date.now() - SESSION_START_AT);
|
||
}
|
||
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
|
||
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
|
||
const onLogin = isLoginPage();
|
||
if (loginBox) loginBox.style.display = onLogin ? "block" : "none";
|
||
if (labelAuto) labelAuto.style.display = onLogin ? "none" : "flex";
|
||
if (labelBatch) labelBatch.style.display = onLogin ? "none" : "flex";
|
||
if (labelShort) labelShort.style.display = onLogin ? "none" : "flex";
|
||
if (statsEl) statsEl.style.display = onLogin ? "none" : "block";
|
||
if (btnOne) {
|
||
const onCourse = route() === "course" && !!S.activeCourse;
|
||
btnOne.textContent = onLogin ? "一键登录并刷课" : onCourse && S.batchRunning ? "停止刷课" : "一键刷课";
|
||
btnOne.title = onCourse && S.batchRunning ? "停止列表刷课" : "开始 / 继续列表刷课";
|
||
}
|
||
}
|
||
function buildPanel() {
|
||
if (window.top !== window.self) return;
|
||
if (document.getElementById(PANEL_ID)) return;
|
||
const box = document.createElement("div");
|
||
box.id = PANEL_ID;
|
||
box.style.cssText = [
|
||
"position:fixed",
|
||
"right:16px",
|
||
"bottom:16px",
|
||
"z-index:2147483647",
|
||
"background:rgba(24,24,28,.88)",
|
||
"color:#eee",
|
||
"padding:10px 12px",
|
||
"border-radius:8px",
|
||
"box-shadow:0 4px 16px rgba(0,0,0,.35)",
|
||
'font:12px/1.5 system-ui,-apple-system,"Microsoft YaHei",sans-serif',
|
||
"user-select:none",
|
||
"max-width:280px",
|
||
"min-width:220px"
|
||
].join(";");
|
||
const title = document.createElement("div");
|
||
title.style.cssText = "display:flex;align-items:baseline;gap:6px;margin-bottom:6px;";
|
||
const titleText = document.createElement("span");
|
||
titleText.textContent = "云学堂助手";
|
||
titleText.style.cssText = "font-weight:600;";
|
||
const titleVer = document.createElement("span");
|
||
titleVer.id = "yun-xue-tang-version";
|
||
titleVer.textContent = "v" + VERSION;
|
||
titleVer.title = "脚本版本 v" + VERSION;
|
||
titleVer.style.cssText = "font-weight:400;font-size:10px;color:#8ee6c0;opacity:.85;";
|
||
title.appendChild(titleText);
|
||
title.appendChild(titleVer);
|
||
btnOne = document.createElement("button");
|
||
btnOne.type = "button";
|
||
btnOne.id = "yun-xue-tang-oneclick";
|
||
btnOne.textContent = "一键刷课";
|
||
btnOne.style.cssText = [
|
||
"width:100%",
|
||
"margin:2px 0 6px",
|
||
"padding:5px 8px",
|
||
"cursor:pointer",
|
||
"background:#2f7d5b",
|
||
"color:#fff",
|
||
"border:1px solid #3a9a70",
|
||
"border-radius:5px",
|
||
"font-size:12px",
|
||
"font-weight:600"
|
||
].join(";");
|
||
btnOne.addEventListener("click", function() {
|
||
if (isLoginPage()) {
|
||
doLoginAndStart();
|
||
return;
|
||
}
|
||
if (route() === "course" && S.activeCourse && S.batchRunning) {
|
||
S.batchRunning = false;
|
||
saveRunState();
|
||
setStatus("列表刷课已暂停");
|
||
} else {
|
||
startBatch();
|
||
}
|
||
updatePanel();
|
||
});
|
||
loginBox = document.createElement("div");
|
||
loginBox.id = "yun-xue-tang-login-box";
|
||
loginBox.style.cssText = "display:none;margin-bottom:6px;";
|
||
const mkInput = function(id, type, ph) {
|
||
const el = document.createElement("input");
|
||
el.id = id;
|
||
el.type = type;
|
||
el.placeholder = ph;
|
||
el.autocomplete = type === "password" ? "off" : "username";
|
||
el.style.cssText = [
|
||
"width:100%",
|
||
"box-sizing:border-box",
|
||
"margin:0 0 4px",
|
||
"padding:4px 6px",
|
||
"background:#2a2a30",
|
||
"color:#eee",
|
||
"border:1px solid #555",
|
||
"border-radius:4px",
|
||
"font-size:12px",
|
||
"user-select:text"
|
||
].join(";");
|
||
return el;
|
||
};
|
||
loginUserEl = mkInput("yun-xue-tang-login-user", "text", "员工邮箱/账号");
|
||
loginPassEl = mkInput("yun-xue-tang-login-pass", "password", "密码");
|
||
const mkCheck = function(id, text) {
|
||
const label = document.createElement("label");
|
||
label.style.cssText = "display:inline-flex;align-items:center;gap:4px;cursor:pointer;margin-right:10px;";
|
||
const cb = document.createElement("input");
|
||
cb.type = "checkbox";
|
||
cb.id = id;
|
||
label.appendChild(cb);
|
||
label.appendChild(document.createTextNode(text));
|
||
return { label, cb };
|
||
};
|
||
const rem = mkCheck("yun-xue-tang-login-remember", "记住密码");
|
||
loginRememberEl = rem.cb;
|
||
const auto = mkCheck("yun-xue-tang-login-auto", "自动登录");
|
||
loginAutoEl = auto.cb;
|
||
loginRememberEl.addEventListener("change", function() {
|
||
if (!loginRememberEl.checked) clearSavedCreds();
|
||
});
|
||
const remRow = document.createElement("div");
|
||
remRow.style.cssText = "margin:2px 0 4px;font-size:11px;color:#bbb;";
|
||
remRow.appendChild(rem.label);
|
||
remRow.appendChild(auto.label);
|
||
btnClearCreds = document.createElement("button");
|
||
btnClearCreds.type = "button";
|
||
btnClearCreds.textContent = "清除密码";
|
||
btnClearCreds.style.cssText = [
|
||
"padding:1px 6px",
|
||
"cursor:pointer",
|
||
"background:#444",
|
||
"color:#eee",
|
||
"border:1px solid #666",
|
||
"border-radius:4px",
|
||
"font-size:10px"
|
||
].join(";");
|
||
btnClearCreds.addEventListener("click", function() {
|
||
clearSavedCreds();
|
||
if (loginPassEl) loginPassEl.value = "";
|
||
if (loginUserEl) loginUserEl.value = "";
|
||
setStatus("已清除保存的密码");
|
||
});
|
||
const loginHint = document.createElement("div");
|
||
loginHint.textContent = "密码仅存本机(base64 混淆,非加密),公用电脑请勿勾选记住";
|
||
loginHint.style.cssText = "color:#d9a441;font-size:10px;line-height:1.35;margin-top:2px;";
|
||
loginBox.appendChild(loginUserEl);
|
||
loginBox.appendChild(loginPassEl);
|
||
loginBox.appendChild(remRow);
|
||
loginBox.appendChild(btnClearCreds);
|
||
loginBox.appendChild(loginHint);
|
||
labelAuto = document.createElement("label");
|
||
labelAuto.style.cssText = "display:flex;align-items:center;gap:6px;cursor:pointer;";
|
||
cbAuto = document.createElement("input");
|
||
cbAuto.type = "checkbox";
|
||
cbAuto.id = "yun-xue-tang-auto-enabled";
|
||
cbAuto.checked = state.autoPlayEnabled;
|
||
cbAuto.addEventListener("change", function() {
|
||
state.autoPlayEnabled = cbAuto.checked;
|
||
try {
|
||
localStorage.setItem(LS_ENABLED, cbAuto.checked ? "1" : "0");
|
||
} catch (e) {
|
||
}
|
||
setStatus(cbAuto.checked ? "自动连播已开启" : "自动连播已关闭");
|
||
});
|
||
labelAuto.appendChild(cbAuto);
|
||
labelAuto.appendChild(document.createTextNode("当前课程自动连播"));
|
||
labelBatch = document.createElement("label");
|
||
labelBatch.style.cssText = LABEL_CSS;
|
||
cbBatch = document.createElement("input");
|
||
cbBatch.type = "checkbox";
|
||
cbBatch.id = "yun-xue-tang-batch-enabled";
|
||
cbBatch.checked = S.batchRunning;
|
||
cbBatch.addEventListener("change", function() {
|
||
if (cbBatch.checked) {
|
||
startBatch();
|
||
} else {
|
||
S.batchRunning = false;
|
||
saveRunState();
|
||
setStatus("列表刷课已暂停");
|
||
}
|
||
updatePanel();
|
||
});
|
||
labelBatch.appendChild(cbBatch);
|
||
labelBatch.appendChild(document.createTextNode("课程列表自动刷课"));
|
||
labelShort = document.createElement("label");
|
||
labelShort.style.cssText = LABEL_CSS;
|
||
cbPreferShort = document.createElement("input");
|
||
cbPreferShort.type = "checkbox";
|
||
cbPreferShort.id = "yun-xue-tang-prefer-short";
|
||
cbPreferShort.checked = state.preferShortCourses;
|
||
cbPreferShort.title = "按课程总时长从短到长选课";
|
||
cbPreferShort.addEventListener("change", function() {
|
||
state.preferShortCourses = cbPreferShort.checked;
|
||
try {
|
||
localStorage.setItem(LS_PREFER_SHORT, state.preferShortCourses ? "1" : "0");
|
||
} catch (e) {
|
||
}
|
||
if (!state.preferShortCourses) {
|
||
R.shortCatalog = null;
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = 0;
|
||
try {
|
||
sessionStorage.removeItem(SS_SHORT_CATALOG);
|
||
} catch (e) {
|
||
}
|
||
setStatus("已关闭短课程优先,按列表顺序选课");
|
||
} else {
|
||
R.shortCatalogFailedAt = 0;
|
||
setStatus("已开启短课程优先:时长正序");
|
||
}
|
||
updatePanel();
|
||
});
|
||
labelShort.appendChild(cbPreferShort);
|
||
labelShort.appendChild(document.createTextNode("优先短课程(时长正序)"));
|
||
statusEl = document.createElement("div");
|
||
statusEl.id = "yun-xue-tang-status";
|
||
statusEl.textContent = "待机";
|
||
statusEl.style.cssText = "margin-top:6px;color:#8ee6c0;word-break:break-all;";
|
||
statsEl = document.createElement("div");
|
||
statsEl.id = "yun-xue-tang-stats";
|
||
statsEl.style.cssText = "margin-top:2px;color:#aaa;";
|
||
const hint = document.createElement("div");
|
||
hint.textContent = "真实播放计时 · 保持窗口可见";
|
||
hint.style.cssText = "margin-top:6px;color:#777;font-size:11px;";
|
||
const footer = document.createElement("div");
|
||
footer.id = "yun-xue-tang-session-duration";
|
||
footer.textContent = "会话时长 " + formatElapsed(0);
|
||
footer.style.cssText = "margin-top:4px;color:#8ee6c0;font-size:11px;";
|
||
footerEl = footer;
|
||
box.appendChild(title);
|
||
box.appendChild(loginBox);
|
||
box.appendChild(btnOne);
|
||
box.appendChild(labelAuto);
|
||
box.appendChild(labelBatch);
|
||
box.appendChild(labelShort);
|
||
box.appendChild(statusEl);
|
||
box.appendChild(statsEl);
|
||
box.appendChild(hint);
|
||
box.appendChild(footer);
|
||
document.documentElement.appendChild(box);
|
||
}
|
||
function ensurePanel() {
|
||
if (window.top !== window.self) return;
|
||
if (!document.getElementById(PANEL_ID)) buildPanel();
|
||
updatePanel();
|
||
}
|
||
|
||
// src/complete.js
|
||
function recordTitle() {
|
||
const queued = S.activeCourse ? S.activeCourse.title : "";
|
||
if (queued && !isGenericCourseTitle(queued)) return queued;
|
||
const page = courseTitle();
|
||
if (page && !isGenericCourseTitle(page)) return page;
|
||
return queued || page;
|
||
}
|
||
function retryCount(title) {
|
||
const t = norm(title);
|
||
if (!t) return 0;
|
||
const rec = (S.courseRetries || {})[t];
|
||
return rec && rec.n ? rec.n : 0;
|
||
}
|
||
function completeCurrent() {
|
||
const title = recordTitle();
|
||
if (title) {
|
||
S.completedTitles[title] = Date.now();
|
||
delete S.courseRetries[norm(title)];
|
||
}
|
||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||
S.activeCourse = null;
|
||
S.coursePhase = PHASE_IDLE;
|
||
S.awaitingListReturn = true;
|
||
saveRunState();
|
||
R.doneLatchKey = "";
|
||
R.lastSummary = null;
|
||
R.retryWaitUntil = 0;
|
||
R.retryTitle = "";
|
||
invalidateShortCatalog();
|
||
pauseAllMedia();
|
||
console.log(TAG, "课程完成:", title, "第", S.completedThisRun, "门,返回列表选下一门");
|
||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : Infinity;
|
||
if (S.completedThisRun >= limit) {
|
||
S.batchRunning = false;
|
||
S.batchFinished = true;
|
||
saveRunState();
|
||
setStatus("本次已完成 " + S.completedThisRun + " 门,已停止。可重新勾选开始新一轮。");
|
||
} else {
|
||
setStatus("课程完成:" + truncate(title, 26) + "(本次 " + S.completedThisRun + ")");
|
||
}
|
||
later(function() {
|
||
goToList(true);
|
||
}, 1200);
|
||
}
|
||
function failCurrent(reason) {
|
||
const title = recordTitle();
|
||
const key = norm(title);
|
||
const rec = key ? S.courseRetries[key] || { n: 0 } : { n: 0 };
|
||
rec.n = (rec.n || 0) + 1;
|
||
rec.reason = reason;
|
||
rec.at = Date.now();
|
||
if (key) S.courseRetries[key] = rec;
|
||
S.activeCourse = null;
|
||
S.coursePhase = PHASE_IDLE;
|
||
S.awaitingListReturn = false;
|
||
if (rec.n > CFG.maxCourseRetries) {
|
||
S.batchRunning = false;
|
||
S.batchFinished = true;
|
||
R.retryWaitUntil = 0;
|
||
R.retryTitle = "";
|
||
saveRunState();
|
||
setStatus("「" + truncate(title || "当前课程", 22) + "」重试 " + CFG.maxCourseRetries + " 次仍未完成,已停止刷课:" + reason);
|
||
console.warn(TAG, "重试用尽,停止刷课:", title, reason);
|
||
pauseAllMedia();
|
||
updatePanel();
|
||
return;
|
||
}
|
||
const backoff = Math.min(3e5, CFG.courseRetryDelayMs * Math.pow(2, Math.min(rec.n - 1, 4)));
|
||
R.retryWaitUntil = Date.now() + backoff;
|
||
R.retryTitle = title;
|
||
R.retryStatusSec = -1;
|
||
invalidateShortCatalog();
|
||
S.awaitingListReturn = true;
|
||
saveRunState();
|
||
console.warn(TAG, "课程未完成," + Math.round(backoff / 1e3) + " 秒后重试(第 " + rec.n + "/" + CFG.maxCourseRetries + " 次):", title, reason);
|
||
setStatus("未学完:" + truncate(title, 20) + "(" + reason + ")," + Math.round(backoff / 1e3) + " 秒后重试第 " + rec.n + "/" + CFG.maxCourseRetries + " 次");
|
||
updatePanel();
|
||
later(function() {
|
||
goToList(true);
|
||
}, 1200);
|
||
}
|
||
function retryWaiting() {
|
||
return !!(R.retryWaitUntil && Date.now() < R.retryWaitUntil);
|
||
}
|
||
function retryWaitSeconds() {
|
||
if (!R.retryWaitUntil) return 0;
|
||
return Math.max(0, Math.ceil((R.retryWaitUntil - Date.now()) / 1e3));
|
||
}
|
||
function stopBatch(reason) {
|
||
S.batchRunning = false;
|
||
S.batchFinished = true;
|
||
saveRunState();
|
||
setStatus(reason || "列表刷课结束");
|
||
updatePanel();
|
||
}
|
||
|
||
// src/player.js
|
||
function applyMute(v) {
|
||
if (!CFG.mute) return;
|
||
try {
|
||
if (!v.muted) v.muted = true;
|
||
v.defaultMuted = true;
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function playVideo(v) {
|
||
if (!v) return;
|
||
if (state.autoPlayEnabled || S.batchRunning) {
|
||
try {
|
||
const p = v.play();
|
||
if (p && typeof p.catch === "function") p.catch(() => {
|
||
});
|
||
} catch (e) {
|
||
}
|
||
}
|
||
}
|
||
function hookVideo(v) {
|
||
if (!v) return;
|
||
if (v.getAttribute && v.getAttribute("data-yun-xue-tang-hooked") === "1") return;
|
||
if (R.hooked.has(v)) return;
|
||
R.hooked.add(v);
|
||
try {
|
||
v.setAttribute("data-yun-xue-tang-hooked", "1");
|
||
} catch (e) {
|
||
}
|
||
applyMute(v);
|
||
onElement(v, "play", function() {
|
||
applyMute(v);
|
||
R.lastProgressAt = Date.now();
|
||
});
|
||
onElement(v, "ended", function() {
|
||
R.lastProgressAt = Date.now();
|
||
});
|
||
onElement(v, "timeupdate", function() {
|
||
R.lastProgressAt = Date.now();
|
||
});
|
||
}
|
||
function hookAllVideos() {
|
||
for (const doc of collectDocuments()) {
|
||
let vids;
|
||
try {
|
||
vids = doc.querySelectorAll("video, audio");
|
||
} catch (e) {
|
||
continue;
|
||
}
|
||
for (const v of vids) hookVideo(v);
|
||
}
|
||
}
|
||
function findPlayableVideo() {
|
||
const vids = [...document.querySelectorAll("video, audio")].filter(function(v) {
|
||
return v.duration > 0 || v.currentSrc;
|
||
});
|
||
return vids.find(function(v) {
|
||
return !v.paused;
|
||
}) || vids.find(function(v) {
|
||
return isVisible(v) && v.duration > 0;
|
||
}) || vids.find(function(v) {
|
||
return v.duration > 0;
|
||
}) || vids[0] || null;
|
||
}
|
||
function ensurePlaying(v) {
|
||
if (!v) return;
|
||
applyMute(v);
|
||
if (S.activeCourse) {
|
||
try {
|
||
if (Math.abs(v.playbackRate - 1) > 0.01) v.playbackRate = 1;
|
||
} catch (e) {
|
||
}
|
||
}
|
||
if (!v.paused) return;
|
||
if (v.ended) return;
|
||
playVideo(v);
|
||
}
|
||
function readSummary() {
|
||
const el = document.querySelector('[class*="course-summary"]');
|
||
if (!el) return null;
|
||
const t = textOf(el);
|
||
const m = t.match(/已完成(\d+)\/(\d+)/);
|
||
if (m) {
|
||
const x = Number(m[1]);
|
||
const y = Number(m[2]);
|
||
return {
|
||
x,
|
||
y,
|
||
percent: y > 0 ? Math.round(x / y * 100) : 0,
|
||
complete: y > 0 && x >= y,
|
||
kind: "ratio",
|
||
text: t
|
||
};
|
||
}
|
||
const pct = t.match(/已完成(\d+)%/);
|
||
if (pct) {
|
||
const x = Number(pct[1]);
|
||
return { x, y: 100, percent: x, complete: x >= 100, kind: "percent", text: t };
|
||
}
|
||
if (/已完成学习|学习完成|已完成本课程|已学完/.test(t)) {
|
||
return { x: 100, y: 100, percent: 100, complete: true, kind: "done", text: t };
|
||
}
|
||
const bar = el.querySelector('[role="progressbar"]');
|
||
if (bar) {
|
||
const now = Number(bar.getAttribute("aria-valuenow"));
|
||
const max = Number(bar.getAttribute("aria-valuemax")) || 100;
|
||
if (Number.isFinite(now)) {
|
||
return {
|
||
x: now,
|
||
y: max,
|
||
percent: Math.round(now / max * 100),
|
||
complete: now >= max,
|
||
kind: "percent",
|
||
text: t
|
||
};
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
function readCountdown() {
|
||
const el = document.querySelector(".yxtulcdsdk-course-player__countdown");
|
||
if (!el) return null;
|
||
const t = textOf(el);
|
||
const m = t.match(/还需(?:(\d+)小时)?(?:(\d+)分钟)?(?:(\d+)秒)?/);
|
||
if (m && (m[1] || m[2] || m[3])) {
|
||
return Number(m[1] || 0) * 3600 + Number(m[2] || 0) * 60 + Number(m[3] || 0);
|
||
}
|
||
if (/已完成|学习完成|已学完/.test(t)) return 0;
|
||
return null;
|
||
}
|
||
function readActiveLessonKey() {
|
||
const active = document.querySelector(".yxtulcdsdk-catalog .liactive");
|
||
if (!active) return "";
|
||
const li = active.closest("li");
|
||
return norm(li ? li.innerText : active.innerText);
|
||
}
|
||
function lessonItems() {
|
||
return [...document.querySelectorAll(".yxtulcdsdk-catalog ul > li")].filter(function(li) {
|
||
return !li.querySelector("ul");
|
||
});
|
||
}
|
||
function findNextLessonElement() {
|
||
const activeLi = lessonActiveLi();
|
||
if (!activeLi) return null;
|
||
const lis = lessonItems();
|
||
const idx = lis.indexOf(activeLi);
|
||
if (idx < 0 || idx + 1 >= lis.length) return null;
|
||
return lis[idx + 1];
|
||
}
|
||
function isLessonCompleted(li) {
|
||
try {
|
||
const text = textOf(li);
|
||
if (/已学完|已完成/.test(text)) return true;
|
||
const hint = [
|
||
li.getAttribute("aria-label") || "",
|
||
li.getAttribute("title") || "",
|
||
String(li.className || "")
|
||
].join(" ");
|
||
if (/已学完|已完成|finished|completed|is-done/i.test(hint)) return true;
|
||
const ds = [...li.querySelectorAll("svg path")].map(function(p) {
|
||
return String(p.getAttribute("d") || "");
|
||
});
|
||
return ds.some(function(d) {
|
||
return d.replace(/,/g, " ").indexOf("M10 2.75") >= 0;
|
||
});
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
function findFirstIncompleteLessonElement() {
|
||
for (const li of lessonItems()) {
|
||
if (!isLessonCompleted(li)) return li;
|
||
}
|
||
return null;
|
||
}
|
||
function pauseAllMedia() {
|
||
try {
|
||
document.querySelectorAll("video, audio").forEach(function(x) {
|
||
try {
|
||
x.pause();
|
||
} catch (e) {
|
||
}
|
||
});
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function lessonActiveLi() {
|
||
const el = document.querySelector(".yxtulcdsdk-catalog .liactive");
|
||
return el ? el.closest("li") : null;
|
||
}
|
||
function layoutAvailable() {
|
||
try {
|
||
const r = document.body.getBoundingClientRect();
|
||
return r.width > 0 && r.height > 0;
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
function dumpCatalog() {
|
||
return lessonItems().map(function(li, i) {
|
||
return {
|
||
i: i + 1,
|
||
text: truncate(textOf(li), 36),
|
||
active: li.classList.contains("liactive") || !!li.querySelector(".liactive"),
|
||
done: isLessonCompleted(li),
|
||
cls: String(li.className || "").slice(0, 48)
|
||
};
|
||
});
|
||
}
|
||
function fireMouse(el, type) {
|
||
try {
|
||
el.dispatchEvent(new MouseEvent(type, {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
view: window,
|
||
button: 0
|
||
}));
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function firePointer(el, type) {
|
||
try {
|
||
el.dispatchEvent(new PointerEvent(type, {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
pointerId: 1,
|
||
pointerType: "mouse",
|
||
isPrimary: true
|
||
}));
|
||
} catch (e) {
|
||
fireMouse(el, type.replace("pointer", "mouse"));
|
||
}
|
||
}
|
||
function clickNode(el) {
|
||
if (!el) return false;
|
||
try {
|
||
if (typeof el.click === "function") {
|
||
el.click();
|
||
return true;
|
||
}
|
||
} catch (e) {
|
||
}
|
||
fireMouse(el, "click");
|
||
return true;
|
||
}
|
||
function fireClickSequence(el) {
|
||
if (!el) return;
|
||
firePointer(el, "pointerdown");
|
||
fireMouse(el, "mousedown");
|
||
firePointer(el, "pointerup");
|
||
fireMouse(el, "mouseup");
|
||
clickNode(el);
|
||
}
|
||
function lessonClickNodes(li) {
|
||
const title = li.querySelector(".item") || li.querySelector(".yxtf-tooltip") || li.querySelector("span");
|
||
const row = li.querySelector('[class*="flex-space-between"]') || li.querySelector("div");
|
||
const svg = li.querySelector("svg");
|
||
return [title, row, li, svg].filter(Boolean);
|
||
}
|
||
function clickLesson(li, attempt) {
|
||
if (!li) return;
|
||
const nodes = lessonClickNodes(li);
|
||
if (!nodes.length) return;
|
||
const title = nodes[0];
|
||
const row = nodes[1] && nodes[1] !== li ? nodes[1] : null;
|
||
const svg = li.querySelector("svg");
|
||
if (attempt <= 2) {
|
||
clickNode(title);
|
||
if (attempt === 2 && row) clickNode(row);
|
||
return;
|
||
}
|
||
if (attempt >= 4) {
|
||
const startBtn = [...li.querySelectorAll('button, [role="button"], span, div')].find(function(el) {
|
||
return el.children.length <= 1 && /^(开始学习|继续学习)$/.test(textOf(el));
|
||
});
|
||
if (startBtn) clickNode(startBtn);
|
||
}
|
||
fireClickSequence(title);
|
||
const targets = [title, row, li, svg].filter(Boolean);
|
||
const target = targets[(attempt - 3) % targets.length];
|
||
if (target && target !== title) fireClickSequence(target);
|
||
}
|
||
function confirmLessonDialog() {
|
||
const pat = /^(确定|确认|是|切换|确定切换|继续切换|继续学习|继续观看|知道了)$/;
|
||
const boxes = [...document.querySelectorAll(
|
||
'.yxt-dialog__wrapper, [class*="dialog"], [class*="modal"], [role="dialog"]'
|
||
)].filter(isVisible);
|
||
let buttons = [];
|
||
for (const box of boxes) {
|
||
buttons = buttons.concat([...box.querySelectorAll('button, [role="button"]')]);
|
||
}
|
||
if (!buttons.length) {
|
||
buttons = [...document.querySelectorAll('button, [role="button"]')];
|
||
}
|
||
for (const el of buttons) {
|
||
if (!isVisible(el)) continue;
|
||
if (pat.test(textOf(el))) {
|
||
clickNode(el);
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
function findNextButton() {
|
||
const els = [...document.querySelectorAll(
|
||
'[class*="kng-operate"] div, [class*="kng-operate"] span, [class*="kng-operate"] button'
|
||
)];
|
||
for (const el of els) {
|
||
if (textOf(el) === "下一个" && isVisible(el)) return el;
|
||
}
|
||
const generic = [...document.querySelectorAll("div, span, button, a")];
|
||
for (const el of generic) {
|
||
if (el.children.length <= 1 && textOf(el) === "下一个" && isVisible(el)) return el;
|
||
}
|
||
return null;
|
||
}
|
||
function examLessonElements() {
|
||
return lessonItems().filter(function(li) {
|
||
const tag = li.querySelector(".tag-type");
|
||
return !!tag && /考试/.test(textOf(tag));
|
||
});
|
||
}
|
||
function findPendingExamLesson() {
|
||
return examLessonElements().find(function(li) {
|
||
return !isLessonCompleted(li);
|
||
}) || null;
|
||
}
|
||
function courseHasQuizLesson() {
|
||
return [...document.querySelectorAll(".yxtulcdsdk-catalog ul > li .tag-type")].some(function(t) {
|
||
return /答题|测验|问卷/.test(textOf(t));
|
||
});
|
||
}
|
||
function detectQuiz() {
|
||
const pat = /^(开始答题|继续答题|提交答案|提交试卷)$/;
|
||
for (const doc of collectDocuments()) {
|
||
let els;
|
||
try {
|
||
els = doc.querySelectorAll('button, [role="button"], a');
|
||
} catch (e) {
|
||
continue;
|
||
}
|
||
for (const el of els) {
|
||
if (pat.test(textOf(el)) && isVisible(el)) return true;
|
||
}
|
||
}
|
||
const dialogs = [...document.querySelectorAll('.yxt-dialog__wrapper, [class*="dialog"]')];
|
||
for (const d of dialogs) {
|
||
if (!isVisible(d)) continue;
|
||
const t = textOf(d);
|
||
if (/开始答题|提交试卷/.test(t)) return true;
|
||
}
|
||
return false;
|
||
}
|
||
function findAntiIdleDialog() {
|
||
const pat = /防挂机|不要走开|学习将被停止|请点击.?继续学习/;
|
||
let best = null;
|
||
let bestLen = Infinity;
|
||
for (const doc of collectDocuments()) {
|
||
let cands;
|
||
try {
|
||
cands = doc.querySelectorAll('[class*="dialog"], [class*="modal"], [role="dialog"]');
|
||
} catch (e) {
|
||
continue;
|
||
}
|
||
for (const el of cands) {
|
||
if (!isVisible(el)) continue;
|
||
const t = textOf(el);
|
||
if (t.length > 400) continue;
|
||
if (!pat.test(t)) continue;
|
||
if (t.length < bestLen) {
|
||
best = el;
|
||
bestLen = t.length;
|
||
}
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
function findAntiIdleButton(dialog) {
|
||
if (!dialog) return null;
|
||
const want = /^(继续学习|我知道了|继续观看)$/;
|
||
const pick = function(sel) {
|
||
return [...dialog.querySelectorAll(sel)].find(function(el2) {
|
||
return want.test(textOf(el2)) && isVisible(el2);
|
||
}) || null;
|
||
};
|
||
const el = pick("button") || pick('[role="button"]') || pick("a") || pick("div") || pick("span");
|
||
if (!el) return findVisibleButton(/^(继续学习)$/);
|
||
if (el.tagName !== "BUTTON") {
|
||
const inner = el.querySelector("button");
|
||
if (inner) return inner;
|
||
}
|
||
return el;
|
||
}
|
||
function antiIdleNeedsHuman(dialog) {
|
||
if (!dialog) return false;
|
||
try {
|
||
const cands = dialog.querySelectorAll(
|
||
'input[type="range"], [class*="slider"], [class*="captcha"], [class*="drag-verify"], [class*="verify-slider"]'
|
||
);
|
||
for (const el of cands) if (isVisible(el)) return true;
|
||
return false;
|
||
} catch (e) {
|
||
return false;
|
||
}
|
||
}
|
||
function handleAntiIdle() {
|
||
const dialog = findAntiIdleDialog();
|
||
if (!dialog) return false;
|
||
const btn = findAntiIdleButton(dialog);
|
||
if (!btn) {
|
||
if (antiIdleNeedsHuman(dialog)) {
|
||
setStatus("防挂机验证需要人工完成(滑块/拼图),本课稍后重试");
|
||
failCurrent("防挂机验证需要人工完成(滑块/拼图)");
|
||
} else {
|
||
setStatus("检测到防挂机验证,未找到「继续学习」按钮");
|
||
}
|
||
return true;
|
||
}
|
||
if (Date.now() - R.lastIdleClickAt < 2500) return true;
|
||
const dialogText = truncate(textOf(dialog), 40);
|
||
const sameDialog = R.idleDialogText === dialogText;
|
||
if (sameDialog && R.idleDialogClicks >= 10) {
|
||
if (!R.idleGaveUp) {
|
||
R.idleGaveUp = true;
|
||
console.warn(
|
||
TAG,
|
||
"防挂机验证弹层点了 10 次仍未关闭,停止点击,等待人工处理",
|
||
String(dialog.outerHTML || "").slice(0, 800)
|
||
);
|
||
setStatus("防挂机验证未能通过,等待人工处理");
|
||
}
|
||
return true;
|
||
}
|
||
R.idleDialogText = dialogText;
|
||
R.idleDialogClicks = sameDialog ? R.idleDialogClicks + 1 : 1;
|
||
R.idleGaveUp = false;
|
||
R.lastIdleClickAt = Date.now();
|
||
R.idlePassed++;
|
||
try {
|
||
btn.click();
|
||
} catch (e) {
|
||
}
|
||
console.log(TAG, "防挂机验证:已点击「继续学习」(第", R.idlePassed, "次)");
|
||
setStatus("已通过防挂机验证(第 " + R.idlePassed + " 次)");
|
||
updatePanel();
|
||
return true;
|
||
}
|
||
function courseTitle() {
|
||
return String(document.title || "").replace(/\s*-\s*[^-]*(云课堂|云学堂)\s*$/, "").trim();
|
||
}
|
||
function alignToFirstIncomplete() {
|
||
if (!CFG.alignToFirstIncomplete || R.initialLessonChecked) return false;
|
||
const lis = lessonItems();
|
||
if (!lis.length) return false;
|
||
if (!R.phaseSince) R.phaseSince = Date.now();
|
||
if (Date.now() - R.phaseSince < 1500) return true;
|
||
const activeLi = lessonActiveLi();
|
||
const activeIdx = activeLi ? lis.indexOf(activeLi) : -1;
|
||
const targetLi = findFirstIncompleteLessonElement();
|
||
const targetIdx = targetLi ? lis.indexOf(targetLi) : -1;
|
||
if (targetIdx < 0) {
|
||
R.initialLessonChecked = true;
|
||
return false;
|
||
}
|
||
if (targetIdx === activeIdx) {
|
||
R.alignStable++;
|
||
if (R.alignStable < 2) return true;
|
||
R.initialLessonChecked = true;
|
||
R.lastLessonKey = readActiveLessonKey();
|
||
console.log(TAG, "起点已对齐:第", targetIdx + 1, "节", truncate(textOf(targetLi), 24));
|
||
setStatus("从第 " + (targetIdx + 1) + " 节开始:" + truncate(textOf(targetLi), 18));
|
||
return false;
|
||
}
|
||
R.alignStable = 0;
|
||
if (R.alignTries >= 8) {
|
||
R.initialLessonChecked = true;
|
||
R.alignFailed = true;
|
||
setStatus("未能切换到第 " + (targetIdx + 1) + " 节,按当前位置继续");
|
||
console.warn(TAG, "起点对齐失败:点击课时后平台未切换,目录快照:", dumpCatalog());
|
||
return false;
|
||
}
|
||
R.alignTries++;
|
||
if (layoutAvailable() && !isVisible(targetLi)) {
|
||
let ul = targetLi.parentElement;
|
||
while (ul && ul.tagName !== "UL") ul = ul.parentElement;
|
||
const collapsed = ul && getComputedStyle(ul).display === "none";
|
||
const chapterLi = ul && ul.parentElement ? ul.parentElement.closest("li") : null;
|
||
if (collapsed && chapterLi && R.alignTries <= 3) {
|
||
setStatus("展开章节:" + truncate(textOf(chapterLi), 20));
|
||
clickNode(chapterLi.querySelector(".hand") || chapterLi);
|
||
return true;
|
||
}
|
||
}
|
||
if (R.alignTries > 1 && confirmLessonDialog()) {
|
||
setStatus("已确认切换提示,继续…");
|
||
return true;
|
||
}
|
||
console.log(
|
||
TAG,
|
||
"对齐起点:第",
|
||
activeIdx >= 0 ? activeIdx + 1 : "?",
|
||
"节 → 第",
|
||
targetIdx + 1,
|
||
"节",
|
||
"(第 " + R.alignTries + " 次)"
|
||
);
|
||
setStatus("正在切换到第 " + (targetIdx + 1) + " 节…" + (R.alignTries > 1 ? "(第 " + R.alignTries + " 次)" : ""));
|
||
clickLesson(targetLi, R.alignTries);
|
||
return true;
|
||
}
|
||
function syncManualCourse() {
|
||
const key = courseTitle() || location.href;
|
||
if (R.manualCourseKey === key) return true;
|
||
R.manualCourseKey = key;
|
||
R.initialLessonChecked = false;
|
||
R.phaseSince = 0;
|
||
R.alignTries = 0;
|
||
R.alignStable = 0;
|
||
R.alignFailed = false;
|
||
R.lastLessonKey = "";
|
||
R.doneLatchKey = "";
|
||
R.waitStart = 0;
|
||
return true;
|
||
}
|
||
|
||
// src/list.js
|
||
function scanCards() {
|
||
return [...document.querySelectorAll("li.kng-list-new__item")].map((li, i) => {
|
||
const titleEl = li.querySelector(".yxtf-tooltip");
|
||
const tags = [...li.querySelectorAll(".kng-list-new__tag")].map(textOf);
|
||
const status = tags.find((t) => /已学完|学习中|未开始|未学习|已完成/.test(t)) || tags.find((t) => t !== "课程") || "";
|
||
return {
|
||
li,
|
||
i,
|
||
title: norm(titleEl ? titleEl.innerText : ""),
|
||
status,
|
||
tags
|
||
};
|
||
});
|
||
}
|
||
function currentPage() {
|
||
const el = document.querySelector(".yxtf-pager .number.active");
|
||
if (!el) return null;
|
||
const n = Number(textOf(el));
|
||
return Number.isFinite(n) ? n : null;
|
||
}
|
||
function maxPageNumber() {
|
||
const nums = [...document.querySelectorAll(".yxtf-pager .number")].map((e) => Number(textOf(e))).filter((n) => Number.isFinite(n) && n > 0);
|
||
return nums.length ? Math.max.apply(null, nums) : null;
|
||
}
|
||
function cardsSignature(cards) {
|
||
cards = cards || scanCards();
|
||
if (!cards.length) return "";
|
||
return cards.length + "|" + cards[0].title + "|" + cards[cards.length - 1].title;
|
||
}
|
||
function jumpToPage(target) {
|
||
if (!target) return false;
|
||
if (Date.now() - R.lastPageJumpAt < 3e3) return false;
|
||
R.lastPageJumpAt = Date.now();
|
||
R.pageChangeAt = Date.now();
|
||
R.pageChangeSig = cardsSignature();
|
||
const input = document.querySelector(
|
||
'.yxtf-pagination__editor input, .yxtf-pagination input[type="number"]'
|
||
);
|
||
if (input) {
|
||
try {
|
||
const setter = Object.getOwnPropertyDescriptor(
|
||
window.HTMLInputElement.prototype,
|
||
"value"
|
||
).set;
|
||
setter.call(input, String(target));
|
||
} catch (e) {
|
||
input.value = String(target);
|
||
}
|
||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||
input.dispatchEvent(new KeyboardEvent("keydown", {
|
||
key: "Enter",
|
||
code: "Enter",
|
||
keyCode: 13,
|
||
which: 13,
|
||
bubbles: true
|
||
}));
|
||
console.log(TAG, "跳转到第", target, "页");
|
||
return true;
|
||
}
|
||
const btn = [...document.querySelectorAll(".yxtf-pager .number")].find((e) => Number(textOf(e)) === target);
|
||
if (btn) {
|
||
btn.click();
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
function nextPage() {
|
||
if (Date.now() - R.lastPageJumpAt < 3e3) return;
|
||
R.lastPageJumpAt = Date.now();
|
||
R.pageChangeAt = Date.now();
|
||
R.pageChangeSig = cardsSignature();
|
||
const btn = document.querySelector(".yxtf-pagination .btn-next");
|
||
if (btn && !btn.disabled) {
|
||
btn.click();
|
||
console.log(TAG, "翻到下一页");
|
||
}
|
||
}
|
||
function formatDuration(seconds) {
|
||
const n = Number(seconds);
|
||
if (!Number.isFinite(n) || n <= 0) return "时长未知";
|
||
const minutes = Math.max(1, Math.round(n / 60));
|
||
if (minutes < 60) return minutes + " 分钟";
|
||
const h = Math.floor(minutes / 60);
|
||
const m = minutes % 60;
|
||
return h + " 小时" + (m ? " " + m + " 分钟" : "");
|
||
}
|
||
function listData(vm) {
|
||
return vm && vm.kngListData || [];
|
||
}
|
||
function listVm() {
|
||
const ul = document.querySelector("ul.kng-list-new");
|
||
let vm = ul && ul.__vue__;
|
||
while (vm && !Array.isArray(vm.kngListData)) vm = vm.$parent;
|
||
return vm && Array.isArray(vm.kngListData) ? vm : null;
|
||
}
|
||
function shortQuery(vm) {
|
||
return {
|
||
pageSize: Number(vm && vm.pageSize) || 16,
|
||
orderBy: vm && vm.sortColumn || "createTime",
|
||
orderType: vm && vm.sortType || "desc"
|
||
};
|
||
}
|
||
function shortCatalogKey(vm) {
|
||
const q = shortQuery(vm);
|
||
const key = {
|
||
collegeId: vm && vm.collegeId || "",
|
||
catalogId: vm && vm.currentCatalogId || "",
|
||
title: vm && vm.searchKey || "",
|
||
type: vm && vm.kngType != null ? vm.kngType : "",
|
||
allTag: vm && vm.tagIds && vm.tagIds.length ? 0 : 1,
|
||
tagIds: vm && vm.tagIds || [],
|
||
orderBy: q.orderBy,
|
||
orderType: q.orderType,
|
||
pageSize: q.pageSize
|
||
};
|
||
return JSON.stringify(key);
|
||
}
|
||
function readShortCatalog(key) {
|
||
try {
|
||
const raw = sessionStorage.getItem(SS_SHORT_CATALOG);
|
||
if (!raw) return null;
|
||
const obj = JSON.parse(raw);
|
||
if (!obj || obj.key !== key || !Array.isArray(obj.items)) return null;
|
||
if (Date.now() - (obj.at || 0) > SHORT_CATALOG_TTL) return null;
|
||
return obj;
|
||
} catch (e) {
|
||
return null;
|
||
}
|
||
}
|
||
function writeShortCatalog(cat) {
|
||
if (!cat) return;
|
||
try {
|
||
sessionStorage.setItem(SS_SHORT_CATALOG, JSON.stringify(cat));
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function shortApiBase() {
|
||
try {
|
||
const hit = performance.getEntriesByType("resource").map(function(e) {
|
||
return e.name;
|
||
}).find(function(u) {
|
||
return /\/kng\/knowledge\/pagelist/.test(u);
|
||
});
|
||
if (hit) return new URL(hit).origin + "/kng/knowledge/pagelist";
|
||
} catch (e) {
|
||
}
|
||
return "https://api-phx-tc.yunxuetang.cn/kng/knowledge/pagelist";
|
||
}
|
||
function shortCatalogRequest(vm) {
|
||
const orgId = vm && vm.collegeId || localStorage.getItem("orgId") || "";
|
||
const token = localStorage.getItem("token") || "";
|
||
if (!token) throw new Error("未找到登录 token,可能尚未登录或登录已过期");
|
||
const body = JSON.stringify({
|
||
collegeId: orgId,
|
||
catalogId: vm && vm.currentCatalogId || "",
|
||
title: vm && vm.searchKey || "",
|
||
type: vm && vm.kngType != null ? vm.kngType : "",
|
||
allTag: vm && vm.tagIds && vm.tagIds.length ? 0 : 1,
|
||
tagIds: vm && vm.tagIds || []
|
||
});
|
||
const headers = {
|
||
"content-type": "application/json;charset=UTF-8",
|
||
accept: "application/json, text/plain, */*",
|
||
token,
|
||
"yxt-orgdomain": location.hostname,
|
||
source: "501"
|
||
};
|
||
return { body, headers };
|
||
}
|
||
var DONE_STALE_MS = 10 * 60 * 1e3;
|
||
async function fetchShortCatalog(vm) {
|
||
const key = shortCatalogKey(vm);
|
||
const q = shortQuery(vm);
|
||
const req = shortCatalogRequest(vm);
|
||
const api = shortApiBase();
|
||
const datas = [];
|
||
let offset = 0;
|
||
let total = Infinity;
|
||
let requests = 0;
|
||
while (offset < total && requests < 20) {
|
||
const limit = Number.isFinite(total) ? Math.min(6e3, total - offset) : 6e3;
|
||
if (limit <= 0) break;
|
||
const url = api + "?limit=" + limit + "&offset=" + offset + "&orderType=" + encodeURIComponent(q.orderType) + "&orderBy=" + encodeURIComponent(q.orderBy);
|
||
const res = await fetch(url, { method: "POST", headers: req.headers, body: req.body });
|
||
if (!res.ok) throw new Error("列表接口 HTTP " + res.status);
|
||
const json = await res.json();
|
||
const list = json && json.datas;
|
||
if (!Array.isArray(list)) throw new Error("列表接口返回格式异常");
|
||
if (!list.length) break;
|
||
datas.push.apply(datas, list);
|
||
total = Number(json.paging && json.paging.count);
|
||
if (!Number.isFinite(total)) total = datas.length;
|
||
offset += list.length;
|
||
requests++;
|
||
}
|
||
const items = [];
|
||
let pruned = 0;
|
||
datas.forEach(function(item, index) {
|
||
if (!item || !item.title) return;
|
||
const title = norm(item.title);
|
||
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) return;
|
||
if (S.completedTitles[title] && Date.now() - Number(S.completedTitles[title]) > DONE_STALE_MS) {
|
||
delete S.completedTitles[title];
|
||
pruned++;
|
||
}
|
||
const seconds = Number(item.studyHours);
|
||
items.push({
|
||
id: item.id ? String(item.id) : "",
|
||
title,
|
||
duration: Number.isFinite(seconds) && seconds > 0 ? seconds : 0,
|
||
status: item.status,
|
||
page: Math.floor(index / q.pageSize) + 1
|
||
});
|
||
});
|
||
if (pruned) {
|
||
saveRunState();
|
||
console.log(TAG, "平台显示未学完,已重新纳入队列的旧记录:", pruned, "门");
|
||
}
|
||
items.sort(function(a, b) {
|
||
const da = a.duration > 0 ? a.duration : Number.MAX_SAFE_INTEGER;
|
||
const db = b.duration > 0 ? b.duration : Number.MAX_SAFE_INTEGER;
|
||
return da === db ? a.page - b.page : da - db;
|
||
});
|
||
return { key, at: Date.now(), pageSize: q.pageSize, total: datas.length, items };
|
||
}
|
||
function ensureShortCatalog() {
|
||
if (!state.preferShortCourses) return "off";
|
||
const vm = listVm();
|
||
if (!vm) {
|
||
if (!R.shortNoVmSince) R.shortNoVmSince = Date.now();
|
||
if (Date.now() - R.shortNoVmSince > 5e3) {
|
||
R.shortCatalogFailedAt = Date.now();
|
||
if (Date.now() - (R.shortWarnedAt || 0) > 1e4) {
|
||
R.shortWarnedAt = Date.now();
|
||
console.warn(TAG, "未找到课程列表组件,退回当前页时长排序");
|
||
setStatus("未读取到课程列表数据,先按当前页时长排序");
|
||
}
|
||
return "failed";
|
||
}
|
||
return "loading";
|
||
}
|
||
R.shortNoVmSince = 0;
|
||
const key = shortCatalogKey(vm);
|
||
if (R.shortCatalog && R.shortCatalog.key === key && Date.now() - (R.shortCatalog.at || 0) < SHORT_CATALOG_TTL) {
|
||
return "ready";
|
||
}
|
||
if (R.shortCatalogLoading) {
|
||
if (Date.now() - R.shortFetchStartedAt > 2e4) {
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
return "failed";
|
||
}
|
||
return "loading";
|
||
}
|
||
if (R.shortCatalogFailedAt && Date.now() - R.shortCatalogFailedAt < 3e4) return "failed";
|
||
const cached = readShortCatalog(key);
|
||
if (cached) {
|
||
R.shortCatalog = cached;
|
||
return "ready";
|
||
}
|
||
R.shortCatalogLoading = true;
|
||
R.shortFetchStartedAt = Date.now();
|
||
setStatus("正在读取课程时长,优先安排短课程…");
|
||
fetchShortCatalog(vm).then(function(cat) {
|
||
R.shortCatalogLoading = false;
|
||
if (!state.preferShortCourses) return;
|
||
R.shortCatalogFailedAt = 0;
|
||
R.shortCatalog = cat;
|
||
writeShortCatalog(cat);
|
||
const shortest = cat.items[0];
|
||
console.log(
|
||
TAG,
|
||
"短课程队列已就绪:待学",
|
||
cat.items.length,
|
||
"门;最短",
|
||
shortest ? formatDuration(shortest.duration) : "无"
|
||
);
|
||
setStatus(shortest ? "优先短课程:共 " + cat.items.length + " 门待学,最短 " + formatDuration(shortest.duration) : "时长队列为空,按当前页继续");
|
||
updatePanel();
|
||
}).catch(function(e) {
|
||
R.shortCatalogLoading = false;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
if (!state.preferShortCourses) return;
|
||
console.warn(
|
||
TAG,
|
||
"读取课程时长失败,退回当前页时长排序:",
|
||
e && e.message ? e.message : e
|
||
);
|
||
setStatus("未能读取全部课程时长,先按当前页时长排序");
|
||
updatePanel();
|
||
});
|
||
return "loading";
|
||
}
|
||
function shortFallback(reason) {
|
||
R.shortCatalog = null;
|
||
R.shortCatalogFailedAt = Date.now();
|
||
try {
|
||
sessionStorage.removeItem(SS_SHORT_CATALOG);
|
||
} catch (e) {
|
||
}
|
||
if (Date.now() - (R.shortWarnedAt || 0) > 1e4) {
|
||
R.shortWarnedAt = Date.now();
|
||
console.warn(TAG, "短课程优先暂不可用,退回当前页时长排序:", reason);
|
||
setStatus("短课程优先暂不可用,先按当前页时长排序");
|
||
}
|
||
}
|
||
function pendingShortItems() {
|
||
const cat = R.shortCatalog;
|
||
if (!cat) return [];
|
||
return cat.items.filter(function(item) {
|
||
if (!item || !item.title) return false;
|
||
if (S.completedTitles[item.title]) return false;
|
||
return true;
|
||
});
|
||
}
|
||
function courseIdOfCard(card) {
|
||
if (!card) return "";
|
||
const vm = listVm();
|
||
const data = listData(vm);
|
||
const byIndex = data[card.i];
|
||
const t = norm(card.title);
|
||
if (byIndex && String(byIndex.id || "") && norm(byIndex.title) === t) {
|
||
return String(byIndex.id);
|
||
}
|
||
const hit = data.find(function(x) {
|
||
return x && norm(x.title) === t;
|
||
});
|
||
return hit && hit.id ? String(hit.id) : "";
|
||
}
|
||
function durationOfCard(card, vm) {
|
||
if (!card) return 0;
|
||
const data = listData(vm);
|
||
const hit = data.find(function(item) {
|
||
return norm(item.title) === card.title;
|
||
});
|
||
const n = hit ? Number(hit.studyHours) : 0;
|
||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||
}
|
||
function cardForShortItem(cards, item) {
|
||
if (!item) return null;
|
||
if (item.id) {
|
||
const vm = listVm();
|
||
const data = listData(vm);
|
||
const index = data.findIndex(function(x) {
|
||
return x && String(x.id) === item.id;
|
||
});
|
||
if (index >= 0 && cards[index] && cards[index].title === item.title) return cards[index];
|
||
}
|
||
return cards.find(function(c) {
|
||
return c.title === item.title;
|
||
}) || null;
|
||
}
|
||
function sortCardsByDuration(cards, vm) {
|
||
vm = vm || listVm();
|
||
return cards.slice().sort(function(a, b) {
|
||
const da = durationOfCard(a, vm) || Number.MAX_SAFE_INTEGER;
|
||
const db = durationOfCard(b, vm) || Number.MAX_SAFE_INTEGER;
|
||
return da - db;
|
||
});
|
||
}
|
||
function forgetShortCourse(title) {
|
||
const t = norm(title);
|
||
if (!t || !R.shortCatalog || !Array.isArray(R.shortCatalog.items)) return;
|
||
const before = R.shortCatalog.items.length;
|
||
R.shortCatalog.items = R.shortCatalog.items.filter(function(item) {
|
||
return item.title !== t;
|
||
});
|
||
if (R.shortCatalog.items.length !== before) writeShortCatalog(R.shortCatalog);
|
||
}
|
||
function isShortCatalogActive() {
|
||
return !!(state.preferShortCourses && R.shortCatalog && Date.now() - (R.shortCatalog.at || 0) < SHORT_CATALOG_TTL);
|
||
}
|
||
function chooseShortCourse(cards, pending) {
|
||
if (!state.preferShortCourses) return null;
|
||
const status = ensureShortCatalog();
|
||
if (status === "loading") return { wait: true };
|
||
if (status === "ready") {
|
||
const items = pendingShortItems();
|
||
if (items.length) {
|
||
const target = items[0];
|
||
const page = currentPage() || S.listPage || 1;
|
||
if (target.page && target.page !== page) {
|
||
if (Date.now() - R.shortJumpAt < 6e3) return { wait: true };
|
||
R.shortJumpAt = Date.now();
|
||
if (jumpToPage(target.page)) {
|
||
S.listPage = target.page;
|
||
saveRunState();
|
||
setStatus("优先短课程:转到第 " + target.page + " 页(" + formatDuration(target.duration) + ")");
|
||
return { wait: true };
|
||
}
|
||
if (Date.now() - R.lastPageJumpAt < 3500) return { wait: true };
|
||
shortFallback("无法跳转到第 " + target.page + " 页");
|
||
} else {
|
||
const card = cardForShortItem(cards, target);
|
||
if (card) {
|
||
if (card.status === "已学完" || S.completedTitles[card.title]) {
|
||
forgetShortCourse(card.title);
|
||
return { wait: true };
|
||
}
|
||
card.duration = target.duration;
|
||
R.shortJumpAt = 0;
|
||
return { card };
|
||
}
|
||
if (Date.now() - R.shortJumpAt < 8e3) return { wait: true };
|
||
shortFallback("目标课程不在第 " + target.page + " 页");
|
||
}
|
||
}
|
||
}
|
||
if (pending && pending.length) {
|
||
const vm = listVm();
|
||
const sorted = sortCardsByDuration(pending, vm);
|
||
if (sorted.length) {
|
||
sorted[0].duration = durationOfCard(sorted[0], vm);
|
||
return { card: sorted[0] };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
function shouldRestorePage() {
|
||
if (!state.preferShortCourses) return true;
|
||
if (isShortCatalogActive()) return false;
|
||
if (R.shortCatalogLoading) return false;
|
||
return !!R.shortCatalogFailedAt;
|
||
}
|
||
function listTick() {
|
||
const cards = scanCards();
|
||
if (!cards.length) return;
|
||
if (R.pageChangeSig) {
|
||
if (cardsSignature(cards) === R.pageChangeSig && Date.now() - R.pageChangeAt < 1e4) {
|
||
return;
|
||
}
|
||
R.pageChangeSig = "";
|
||
}
|
||
if (R.pageChangeAt && Date.now() - R.pageChangeAt < 1500) return;
|
||
if (S.catalogUrl !== location.href) setTargetCatalogUrl(location.href, { silent: true });
|
||
const page = currentPage();
|
||
if (S.awaitingListReturn && !shouldRestorePage()) {
|
||
S.awaitingListReturn = false;
|
||
R.pageRestoreAttempts = 0;
|
||
saveRunState();
|
||
} else if (S.awaitingListReturn) {
|
||
if (page != null && S.listPage && page !== S.listPage) {
|
||
R.pageRestoreAttempts++;
|
||
if (R.pageRestoreAttempts > 12) {
|
||
console.warn(TAG, "页码恢复失败,改用当前页继续");
|
||
S.listPage = page || 1;
|
||
S.awaitingListReturn = false;
|
||
saveRunState();
|
||
} else if (S.listPage > page) {
|
||
if (jumpToPage(S.listPage)) return;
|
||
nextPage();
|
||
return;
|
||
} else {
|
||
jumpToPage(S.listPage);
|
||
return;
|
||
}
|
||
} else {
|
||
S.awaitingListReturn = false;
|
||
R.pageRestoreAttempts = 0;
|
||
saveRunState();
|
||
setStatus("回到列表第 " + (page || 1) + " 页,继续…");
|
||
}
|
||
}
|
||
if (!S.awaitingListReturn && page != null && page !== S.listPage) {
|
||
S.listPage = page;
|
||
saveRunState();
|
||
}
|
||
if (S.activeCourse && S.coursePhase === PHASE_ENTERING) {
|
||
const waited = Date.now() - (S.activeCourse.startedAt || 0);
|
||
if (waited > 15e3) {
|
||
failCurrent("未能进入课程页面");
|
||
return;
|
||
}
|
||
if (waited > 4e3 && R.entryRetries < 2 && Date.now() - R.lastCardClickAt > 4e3) {
|
||
const card = cards.find(function(c) {
|
||
return c.title === S.activeCourse.title;
|
||
});
|
||
if (card) {
|
||
R.entryRetries++;
|
||
R.lastCardClickAt = Date.now();
|
||
console.log(TAG, "进入课程超时,重试点击卡片(第", R.entryRetries, "次)");
|
||
setStatus("重新进入课程:" + truncate(S.activeCourse.title, 22));
|
||
try {
|
||
clickNode(card.li);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
if (S.activeCourse && S.coursePhase === PHASE_LEARNING) {
|
||
if (!R.listWithCurrentSince) R.listWithCurrentSince = Date.now();
|
||
if (Date.now() - R.listWithCurrentSince < 5e3) return;
|
||
const card = cards.find(function(c) {
|
||
return c.title === S.activeCourse.title;
|
||
});
|
||
if (card && /已学完|已完成|已学习/.test(card.status)) {
|
||
S.completedTitles[S.activeCourse.title] = Date.now();
|
||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||
}
|
||
S.activeCourse = null;
|
||
S.coursePhase = PHASE_IDLE;
|
||
S.awaitingListReturn = false;
|
||
R.listWithCurrentSince = 0;
|
||
invalidateShortCatalog();
|
||
saveRunState();
|
||
setStatus("已重置中断的课程状态,继续…");
|
||
}
|
||
if (S.activeCourse) return;
|
||
if (retryWaiting()) {
|
||
const left = retryWaitSeconds();
|
||
if (R.retryStatusSec !== left) {
|
||
R.retryStatusSec = left;
|
||
setStatus("等待重试:" + truncate(R.retryTitle || "上一门课", 20) + "(" + left + " 秒后)");
|
||
}
|
||
return;
|
||
}
|
||
R.retryStatusSec = -1;
|
||
const pending = cards.filter((c) => {
|
||
if (!c.title) return false;
|
||
if (/已学完|已完成|已学习/.test(c.status)) return false;
|
||
if (S.completedTitles[c.title]) return false;
|
||
return true;
|
||
});
|
||
if (state.preferShortCourses) {
|
||
const choice = chooseShortCourse(cards, pending);
|
||
if (choice && choice.wait) return;
|
||
if (choice && choice.card) {
|
||
if (Date.now() - R.lastCardClickAt < 5e3) return;
|
||
startCourse(choice.card);
|
||
return;
|
||
}
|
||
}
|
||
if (pending.length) {
|
||
if (Date.now() - R.lastCardClickAt < 5e3) return;
|
||
startCourse(pending[0]);
|
||
return;
|
||
}
|
||
const max = maxPageNumber();
|
||
if (page != null && max && page < max) {
|
||
nextPage();
|
||
return;
|
||
}
|
||
stopBatch("所有页面的未学完课程都已处理完毕");
|
||
}
|
||
function startCourse(card) {
|
||
const page = currentPage() || S.listPage || 1;
|
||
S.activeCourse = {
|
||
title: card.title,
|
||
id: courseIdOfCard(card),
|
||
startedAt: Date.now()
|
||
};
|
||
S.listPage = page;
|
||
S.coursePhase = PHASE_ENTERING;
|
||
S.awaitingListReturn = false;
|
||
R.lastCardClickAt = Date.now();
|
||
R.shortJumpAt = 0;
|
||
resetCourseRuntime();
|
||
saveRunState();
|
||
const durationText = card.duration ? "(" + formatDuration(card.duration) + ")" : "";
|
||
setStatus("进入课程" + durationText + ":" + truncate(card.title, 28));
|
||
console.log(
|
||
TAG,
|
||
"进入课程",
|
||
card.title,
|
||
"状态",
|
||
card.status,
|
||
card.duration ? "时长 " + formatDuration(card.duration) : ""
|
||
);
|
||
try {
|
||
card.li.click();
|
||
} catch (e) {
|
||
console.error(TAG, e);
|
||
failCurrent("课程卡片点击失败");
|
||
}
|
||
}
|
||
|
||
// src/exam.js
|
||
var START_RE = /^(开始考试|继续考试|进入考试)$/;
|
||
var SUBMIT_RE = /^(提交考试|提交试卷|交卷|交卷并退出)$/;
|
||
var EXAM_SUBMIT_RE = /^(提交考试|交卷|交卷并退出)$/;
|
||
var CONFIRM_RE = /^(确定|确认|确定交卷|确认交卷|提交|提交试卷)$/;
|
||
var RESULT_RE = /^(查看答卷详情|返回考试说明页)$/;
|
||
function visibleAll(sel, root) {
|
||
let list = [];
|
||
try {
|
||
list = [...(root || document).querySelectorAll(sel)];
|
||
} catch (e) {
|
||
return [];
|
||
}
|
||
return list.filter(isVisible);
|
||
}
|
||
function rankOf(el) {
|
||
const tag = el.tagName;
|
||
if (tag === "BUTTON" || tag === "INPUT") return 0;
|
||
if (/yxtf?-button|btn/i.test(String(el.className || ""))) return 1;
|
||
if (tag === "A") return 2;
|
||
if (tag === "SPAN") return 3;
|
||
return 4;
|
||
}
|
||
function examClick(el) {
|
||
if (!el) return false;
|
||
try {
|
||
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: window }));
|
||
el.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, view: window }));
|
||
el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, view: window }));
|
||
return true;
|
||
} catch (e) {
|
||
try {
|
||
el.click();
|
||
return true;
|
||
} catch (e2) {
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
function findClickableByText(re, root) {
|
||
const cands = visibleAll('button, [role="button"], a, span, div', root);
|
||
const hit = cands.filter(function(el) {
|
||
const t = textOf(el);
|
||
return !!t && t.length <= 12 && re.test(t);
|
||
});
|
||
if (!hit.length) return null;
|
||
hit.sort(function(a, b) {
|
||
const d = rankOf(a) - rankOf(b);
|
||
if (d) return d;
|
||
return textOf(a).length - textOf(b).length;
|
||
});
|
||
return hit[0];
|
||
}
|
||
function examPreviewRoot() {
|
||
return visibleAll('.yxtulcdsdk-uexam-preview, [class*="uexam-preview"]')[0] || null;
|
||
}
|
||
function examPaperRoot() {
|
||
return visibleAll('[class*="answer-card"], [class*="answerSheet"], [class*="answer-sheet"]')[0] || null;
|
||
}
|
||
function examResultRoot() {
|
||
const btns = visibleAll('button, [role="button"], a');
|
||
for (const b of btns) {
|
||
const t = textOf(b);
|
||
if (t && t.length <= 12 && RESULT_RE.test(t)) return b;
|
||
}
|
||
return null;
|
||
}
|
||
function examPhase() {
|
||
if (examResultRoot()) return "result";
|
||
if (examPaperRoot()) return "paper";
|
||
if (examPreviewRoot()) return "preview";
|
||
if (findClickableByText(EXAM_SUBMIT_RE)) return "paper";
|
||
if (R.examPhase === "preview" && findClickableByText(SUBMIT_RE)) return "paper";
|
||
if (findClickableByText(START_RE)) return "preview";
|
||
return "";
|
||
}
|
||
function confirmState() {
|
||
const boxes = visibleAll('.yxtf-dialog__wrapper, .yxt-dialog__wrapper, [class*="dialog"], [class*="modal"], [role="dialog"]');
|
||
const cands = boxes.filter(function(b) {
|
||
const t = textOf(b);
|
||
return !!t && t.length <= 300 && /交卷|未做|确认提交|是否确认/.test(t);
|
||
});
|
||
if (!cands.length) return { shown: false, btn: null };
|
||
cands.sort(function(a, b) {
|
||
return textOf(a).length - textOf(b).length;
|
||
});
|
||
for (const b of cands) {
|
||
const btn = findClickableByText(CONFIRM_RE, b);
|
||
if (btn) return { shown: true, btn };
|
||
}
|
||
return { shown: true, btn: null };
|
||
}
|
||
function examAbort(reason, manual) {
|
||
if (manual) {
|
||
setStatus("考试:" + reason);
|
||
return true;
|
||
}
|
||
failCurrent(reason);
|
||
return true;
|
||
}
|
||
function examCourseKey() {
|
||
return S.activeCourse && S.activeCourse.id || courseIdFromUrl() || location.pathname + location.hash;
|
||
}
|
||
function examTriedTimes(key) {
|
||
const m = S.examEmptySubmits || {};
|
||
return m[key || examCourseKey()] || 0;
|
||
}
|
||
function backToCourse() {
|
||
const id = S.activeCourse && S.activeCourse.id || courseIdFromUrl() || "";
|
||
const target = id ? location.origin + "/kng/#/course/play?kngId=" + encodeURIComponent(id) : "";
|
||
R.initialLessonChecked = false;
|
||
R.alignTries = 0;
|
||
R.alignStable = 0;
|
||
R.alignFailed = false;
|
||
R.phaseSince = 0;
|
||
R.lastLessonKey = "";
|
||
R.doneLatchKey = "";
|
||
R.waitStart = 0;
|
||
R.lastCountdown = null;
|
||
R.lastSummary = null;
|
||
R.examLeaving = false;
|
||
try {
|
||
const cur = location.href;
|
||
if (!target || cur === target) {
|
||
location.reload();
|
||
return;
|
||
}
|
||
location.href = target;
|
||
later(function() {
|
||
if (location.href === cur) {
|
||
try {
|
||
location.reload();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
}, 1500);
|
||
} catch (e) {
|
||
}
|
||
}
|
||
function finishExam() {
|
||
if (R.examLeaving) return;
|
||
R.examLeaving = true;
|
||
const key = examCourseKey();
|
||
if (!S.examEmptySubmits) S.examEmptySubmits = {};
|
||
S.examEmptySubmits[key] = examTriedTimes(key) + 1;
|
||
saveRunState();
|
||
const times = S.examEmptySubmits[key];
|
||
console.log(TAG, "考试已空卷交卷(第", times, "次),返回课程页继续学习");
|
||
const s = readSummary();
|
||
if (s && s.complete) {
|
||
setStatus("考试已交卷(未答题),课程已完成");
|
||
later(completeCurrent, 1500);
|
||
return;
|
||
}
|
||
if (times >= Math.max(1, CFG.maxExamTries)) {
|
||
examAbort("已空卷交卷 " + times + " 次,仍未计入课程进度,请手动处理", false);
|
||
return;
|
||
}
|
||
setStatus("考试已交卷(未答题),返回课程继续…");
|
||
later(backToCourse, 1800);
|
||
}
|
||
function examTick(manual) {
|
||
const now = Date.now();
|
||
const phase = examPhase();
|
||
if (!phase) {
|
||
if (R.examPhase) {
|
||
R.examPhase = "";
|
||
R.examPaperAt = 0;
|
||
R.examSubmits = 0;
|
||
R.examConfirms = 0;
|
||
R.examStarts = 0;
|
||
R.examActionAt = 0;
|
||
}
|
||
return false;
|
||
}
|
||
if (R.examPhase !== phase) {
|
||
R.examPhase = phase;
|
||
R.examActionAt = 0;
|
||
R.examSubmits = 0;
|
||
R.examConfirms = 0;
|
||
R.examStarts = 0;
|
||
R.examPaperAt = 0;
|
||
if (phase === "preview") {
|
||
console.log(TAG, "检测到考试章节:进入考试后不答题,直接交卷");
|
||
setStatus("检测到考试:进入考试后直接交卷…");
|
||
}
|
||
}
|
||
if (phase === "result") {
|
||
finishExam();
|
||
return true;
|
||
}
|
||
const key = examCourseKey();
|
||
if (examTriedTimes(key) >= Math.max(1, CFG.maxExamTries)) {
|
||
return examAbort("已空卷交卷 " + examTriedTimes(key) + " 次,仍未计入课程进度,请手动处理", manual);
|
||
}
|
||
if (now - R.examActionAt < CFG.examClickCooldownMs) return true;
|
||
if (phase === "preview") {
|
||
const root = examPreviewRoot();
|
||
const btn = findClickableByText(START_RE, root) || findClickableByText(START_RE);
|
||
if (!btn) {
|
||
setStatus("考试:未找到「开始考试」按钮,等待页面渲染…");
|
||
return true;
|
||
}
|
||
R.examActionAt = now;
|
||
R.examStarts++;
|
||
if (R.examStarts > Math.max(3, CFG.maxExamTries + 3)) {
|
||
return examAbort("点击「开始考试」多次仍不进答卷页", manual);
|
||
}
|
||
setStatus(R.examStarts > 1 ? "考试:再次点击「" + textOf(btn) + "」…(第 " + R.examStarts + " 次)" : "考试:进入考试(不答题,随后直接交卷)");
|
||
examClick(btn);
|
||
return true;
|
||
}
|
||
if (!R.examPaperAt) R.examPaperAt = now;
|
||
if (now - R.examPaperAt < 2e3) return true;
|
||
const cs = confirmState();
|
||
if (cs.shown) {
|
||
if (!cs.btn) {
|
||
setStatus("考试:交卷确认框里没找到「确定」按钮");
|
||
return true;
|
||
}
|
||
R.examActionAt = now;
|
||
R.examConfirms++;
|
||
if (R.examConfirms > 6) {
|
||
return examAbort("交卷确认框点了多次仍未交卷", manual);
|
||
}
|
||
setStatus("考试:不答题,确认交卷…");
|
||
examClick(cs.btn);
|
||
return true;
|
||
}
|
||
const sub = findClickableByText(SUBMIT_RE);
|
||
if (!sub) {
|
||
setStatus("考试:等待「提交考试」按钮…");
|
||
return true;
|
||
}
|
||
if (R.examSubmits >= 6) {
|
||
return examAbort("「提交考试」点了多次仍无结果", manual);
|
||
}
|
||
R.examActionAt = now;
|
||
R.examSubmits++;
|
||
setStatus("考试:不答题,直接交卷…");
|
||
examClick(sub);
|
||
return true;
|
||
}
|
||
|
||
// src/course.js
|
||
function courseTick() {
|
||
R.listWithCurrentSince = 0;
|
||
if (!S.activeCourse) {
|
||
goToList();
|
||
return;
|
||
}
|
||
hookAllVideos();
|
||
const isMedia = mediaPage();
|
||
const urlId = courseIdFromUrl();
|
||
const curId = S.activeCourse.id || "";
|
||
const title = courseTitle();
|
||
const nt = norm(title);
|
||
const nc = norm(S.activeCourse.title);
|
||
const genericTitle = !nt || /^(loading|加载中|在线课堂|江丰云课堂|云课堂|课程详情|课程)$/.test(nt);
|
||
const titleSame = genericTitle || !nc || nt === nc || nt.indexOf(nc) >= 0 || nc.indexOf(nt) >= 0;
|
||
const idKnown = !!(urlId && curId);
|
||
const sameCourse = idKnown ? urlId === curId : titleSame;
|
||
const graceOver = Date.now() - (S.activeCourse.startedAt || 0) > CFG.entryGraceMs;
|
||
if (!sameCourse) {
|
||
if (graceOver) {
|
||
console.warn(
|
||
TAG,
|
||
"页面课程与队列不一致:队列",
|
||
nc,
|
||
curId,
|
||
"页面",
|
||
nt,
|
||
urlId,
|
||
location.href
|
||
);
|
||
failCurrent("页面课程与队列不一致");
|
||
return;
|
||
}
|
||
return;
|
||
}
|
||
if (S.coursePhase !== PHASE_LEARNING) {
|
||
S.coursePhase = PHASE_LEARNING;
|
||
saveRunState();
|
||
}
|
||
if ((location.hash || "").indexOf("#/scan") === 0) return;
|
||
if (handleAntiIdle()) return;
|
||
if (examTick(false)) return;
|
||
if (detectQuiz()) {
|
||
failCurrent("检测到答题/测验,需要手动处理");
|
||
return;
|
||
}
|
||
if (!R.quizChecked && document.querySelector(".yxtulcdsdk-catalog ul > li .tag-type")) {
|
||
R.quizChecked = true;
|
||
if (courseHasQuizLesson()) {
|
||
failCurrent("课程包含答题/测验章节");
|
||
return;
|
||
}
|
||
}
|
||
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
|
||
const summary = readSummary();
|
||
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
|
||
if (summary) {
|
||
if (summary.complete) {
|
||
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
|
||
R.lastSummary = summary;
|
||
if (confirmed) {
|
||
completeCurrent();
|
||
return;
|
||
}
|
||
setStatus("课程已完成,确认中…");
|
||
return;
|
||
}
|
||
if (R.lastSummary && summary.x > R.lastSummary.x) {
|
||
R.lastProgressAt = Date.now();
|
||
const prevKey = R.lastLessonKey;
|
||
const curKey = readActiveLessonKey();
|
||
R.lastSummary = summary;
|
||
if (!isMedia && summary.kind !== "percent" && (!prevKey || curKey === prevKey)) {
|
||
setStatus("本节已记录,切换下一节…");
|
||
advanceLesson();
|
||
return;
|
||
}
|
||
setStatus(summary.kind === "percent" ? "学习进度:" + summary.x + "%" : "进度更新:" + summary.x + "/" + summary.y);
|
||
return;
|
||
}
|
||
R.lastSummary = summary;
|
||
}
|
||
if (!isMedia && alignToFirstIncomplete()) return;
|
||
const cd = readCountdown();
|
||
if (cd != null) {
|
||
if (R.lastCountdown == null || cd < R.lastCountdown) {
|
||
R.lastProgressAt = Date.now();
|
||
}
|
||
R.lastCountdown = cd;
|
||
}
|
||
const lessonKey = readActiveLessonKey();
|
||
if (lessonKey && lessonKey !== R.lastLessonKey) {
|
||
R.lastLessonKey = lessonKey;
|
||
R.doneLatchKey = "";
|
||
R.waitStart = 0;
|
||
R.waitSummaryX = -1;
|
||
R.waitLessonKey = "";
|
||
R.lastProgressAt = Date.now();
|
||
setStatus("学习中:" + truncate(lessonKey, 28) + (R.alignFailed ? "(起点未对齐)" : ""));
|
||
}
|
||
const v = findPlayableVideo();
|
||
const latchKey = isMedia ? "media" : lessonKey || "";
|
||
const cdDone = cd != null && cd <= 0;
|
||
const ended = !!(v && v.ended);
|
||
if (latchKey && R.doneLatchKey && R.doneLatchKey !== latchKey) R.doneLatchKey = "";
|
||
if (latchKey && (cdDone || ended && (cd == null || cd <= 3))) {
|
||
R.doneLatchKey = latchKey;
|
||
}
|
||
const localDone = ended || cdDone || !!latchKey && R.doneLatchKey === latchKey;
|
||
if (!localDone) {
|
||
if (v) {
|
||
ensurePlaying(v);
|
||
const want = "学习中:" + truncate(lessonKey || S.activeCourse.title, 30);
|
||
if (statusEl && (statusEl.textContent === "点击开始学习…" || isMedia && statusEl.textContent !== want)) {
|
||
setStatus(want);
|
||
}
|
||
} else {
|
||
const startBtn = findVisibleClickable(/^(开始学习|继续学习|继续观看)$/);
|
||
if (startBtn && Date.now() - R.lastStartClickAt > CFG.startClickCooldownMs) {
|
||
R.lastStartClickAt = Date.now();
|
||
setStatus("点击开始学习…");
|
||
console.log(TAG, "点击开始学习", textOf(startBtn) || startBtn.tagName);
|
||
try {
|
||
startBtn.click();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if (!localDone) {
|
||
R.waitStart = 0;
|
||
} else if (!R.waitStart) {
|
||
R.waitStart = Date.now();
|
||
R.waitSummaryX = prevSummaryX;
|
||
R.waitLessonKey = lessonKey;
|
||
setStatus(isMedia ? "课程已播完,等待平台记录…" : "本节结束,等待平台记录…");
|
||
}
|
||
if (R.waitStart) {
|
||
const newKey = readActiveLessonKey();
|
||
const s2 = readSummary();
|
||
if (s2 && s2.complete) {
|
||
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
|
||
R.lastSummary = s2;
|
||
if (!confirmed) {
|
||
setStatus("课程已完成,确认中…");
|
||
return;
|
||
}
|
||
R.waitStart = 0;
|
||
R.lastProgressAt = Date.now();
|
||
completeCurrent();
|
||
return;
|
||
}
|
||
if (!isMedia && R.waitLessonKey && newKey && newKey !== R.waitLessonKey) {
|
||
R.waitStart = 0;
|
||
R.lastLessonKey = newKey;
|
||
R.doneLatchKey = "";
|
||
R.lastProgressAt = Date.now();
|
||
setStatus("已自动进入下一节");
|
||
return;
|
||
}
|
||
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
|
||
R.waitStart = 0;
|
||
R.lastProgressAt = Date.now();
|
||
if (s2.complete) {
|
||
completeCurrent();
|
||
} else {
|
||
advanceLesson();
|
||
}
|
||
return;
|
||
}
|
||
if (Date.now() - R.waitStart > 3e4) {
|
||
if (isMedia) {
|
||
R.waitStart = Date.now();
|
||
setStatus("课程已播完,等待平台完成记录…");
|
||
} else {
|
||
R.waitStart = 0;
|
||
setStatus("平台未更新进度,尝试下一节…");
|
||
advanceLesson();
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
if (Date.now() - R.lastProgressAt > CFG.stuckMs) {
|
||
failCurrent("长时间没有计时进展");
|
||
}
|
||
}
|
||
function switchLesson(li) {
|
||
if (!li) return;
|
||
const want = norm(textOf(li));
|
||
const nodes = lessonClickNodes(li);
|
||
const svg = li.querySelector("svg");
|
||
const steps = [
|
||
{ at: 0, run: function() {
|
||
clickNode(nodes[0]);
|
||
} },
|
||
{ at: 500, run: function() {
|
||
if (nodes[1]) clickNode(nodes[1]);
|
||
} },
|
||
{ at: 1e3, run: function() {
|
||
fireClickSequence(li);
|
||
} },
|
||
{ at: 1500, run: function() {
|
||
if (svg) fireClickSequence(svg);
|
||
} }
|
||
];
|
||
for (const step of steps) {
|
||
if (!step.at) {
|
||
step.run();
|
||
continue;
|
||
}
|
||
later(function() {
|
||
if (want && readActiveLessonKey() === want) return;
|
||
step.run();
|
||
}, step.at);
|
||
}
|
||
}
|
||
function advanceLesson() {
|
||
if (Date.now() - R.lastAdvanceAt < 5e3) return;
|
||
R.lastAdvanceAt = Date.now();
|
||
R.lastCountdown = null;
|
||
R.lastLessonKey = "";
|
||
R.doneLatchKey = "";
|
||
R.waitStart = 0;
|
||
const next = findNextLessonElement();
|
||
if (next) {
|
||
setStatus("进入下一节");
|
||
switchLesson(next);
|
||
return;
|
||
}
|
||
const btn = findNextButton();
|
||
if (btn) {
|
||
setStatus("进入下一节");
|
||
clickNode(btn);
|
||
return;
|
||
}
|
||
const s = readSummary();
|
||
if (s && s.complete) {
|
||
completeCurrent();
|
||
} else {
|
||
setStatus("没有找到下一节,等待课程完成…");
|
||
}
|
||
}
|
||
function isSummaryComplete() {
|
||
const s = readSummary();
|
||
return !!(s && s.complete);
|
||
}
|
||
function enterPendingExamLesson() {
|
||
const li = findPendingExamLesson();
|
||
if (!li) return false;
|
||
const courseKey = S.activeCourse && S.activeCourse.id || courseIdFromUrl() || "";
|
||
if (R.examLessonKey !== courseKey) {
|
||
R.examLessonKey = courseKey;
|
||
R.examLessonTries = 0;
|
||
R.examLessonAt = 0;
|
||
}
|
||
const pendingNormal = lessonItems().some(function(item) {
|
||
const tag = item.querySelector(".tag-type");
|
||
const isExam = !!tag && /考试/.test(textOf(tag));
|
||
return !isExam && !isLessonCompleted(item);
|
||
});
|
||
if (pendingNormal) return false;
|
||
if (Date.now() - R.examLessonAt < CFG.examClickCooldownMs * 2) return true;
|
||
const activeLi = lessonActiveLi();
|
||
if (activeLi && activeLi === li && examPhase()) return false;
|
||
if (R.examLessonTries >= 10) {
|
||
failCurrent("点击考试章节多次后仍未进入考试页");
|
||
return true;
|
||
}
|
||
R.examLessonAt = Date.now();
|
||
R.examLessonTries++;
|
||
setStatus("进入考试章节:" + truncate(textOf(li), 20) + (R.examLessonTries > 1 ? "(第 " + R.examLessonTries + " 次)" : ""));
|
||
clickLesson(li, R.examLessonTries);
|
||
return true;
|
||
}
|
||
function manualCourseTick() {
|
||
hookAllVideos();
|
||
if (handleAntiIdle()) return;
|
||
const title = courseTitle();
|
||
if (!title || /^(loading|加载中)/i.test(title)) return;
|
||
syncManualCourse();
|
||
if (!mediaPage() && alignToFirstIncomplete()) return;
|
||
if (examTick(true)) return;
|
||
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
|
||
const lessonKey = readActiveLessonKey();
|
||
if (lessonKey && lessonKey !== R.lastLessonKey) {
|
||
R.lastLessonKey = lessonKey;
|
||
R.doneLatchKey = "";
|
||
setStatus("学习中:" + truncate(lessonKey, 28));
|
||
}
|
||
const summary = readSummary();
|
||
if (summary && summary.complete) {
|
||
pauseAllMedia();
|
||
setStatus("课程已完成:" + truncate(S.activeCourse ? S.activeCourse.title : title, 24));
|
||
return;
|
||
}
|
||
const v = findPlayableVideo();
|
||
if (!v) {
|
||
if (!mediaPage()) return;
|
||
const startBtn = findVisibleClickable(/^(开始学习|继续学习|继续观看)$/);
|
||
if (startBtn && Date.now() - R.lastStartClickAt > CFG.startClickCooldownMs) {
|
||
R.lastStartClickAt = Date.now();
|
||
setStatus("点击开始学习…");
|
||
try {
|
||
startBtn.click();
|
||
} catch (e) {
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
const cd = readCountdown();
|
||
if (cd != null) {
|
||
if (R.lastCountdown == null || cd < R.lastCountdown) R.lastProgressAt = Date.now();
|
||
R.lastCountdown = cd;
|
||
}
|
||
if (v.ended || cd != null && cd <= 0) R.doneLatchKey = "manual";
|
||
const localDone = v.ended || cd != null && cd <= 0 || R.doneLatchKey === "manual";
|
||
if (localDone) {
|
||
if (CFG.autoNext && Date.now() - R.manualAdvanceAt > 6e3) {
|
||
R.manualAdvanceAt = Date.now();
|
||
const next = findNextLessonElement();
|
||
if (next) {
|
||
switchLesson(next);
|
||
} else {
|
||
const btn = findNextButton();
|
||
if (btn) clickNode(btn);
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
ensurePlaying(v);
|
||
}
|
||
|
||
// src/index.js
|
||
function tick2() {
|
||
try {
|
||
if (window.top !== window.self) return;
|
||
ensurePanel();
|
||
if (isLoginPage()) loginPageTick();
|
||
if (consumePendingStart()) return;
|
||
if (!S.batchRunning) {
|
||
if (route() === "course" && state.autoPlayEnabled) {
|
||
manualCourseTick();
|
||
} else {
|
||
R.manualCourseKey = "";
|
||
}
|
||
return;
|
||
}
|
||
const r = route();
|
||
if (r === "list") {
|
||
listTick();
|
||
} else if (r === "course") {
|
||
courseTick();
|
||
}
|
||
} catch (e) {
|
||
console.error(TAG, e);
|
||
}
|
||
}
|
||
setTick(tick2);
|
||
if (window.top !== window.self) {
|
||
every(function() {
|
||
try {
|
||
hookAllVideos();
|
||
} catch (e) {
|
||
}
|
||
}, CFG.tickMs);
|
||
} else {
|
||
ensurePanel();
|
||
hookAllVideos();
|
||
every(tick2, CFG.tickMs);
|
||
onWindow(window, "hashchange", function() {
|
||
later(tick2, 300);
|
||
});
|
||
}
|
||
try {
|
||
Object.defineProperty(window, "__yunXueTangAuto", {
|
||
value: {
|
||
S,
|
||
R,
|
||
state,
|
||
tick: tick2,
|
||
save: saveRunState,
|
||
flush: flushRunState,
|
||
route,
|
||
// CFG 暴露给无头运行器:可用 --max / YUN_XUE_TANG_MAX_COURSES 覆盖本次运行的门数上限
|
||
CFG,
|
||
mediaPage,
|
||
courseIdFromUrl,
|
||
readCountdown,
|
||
readSummary,
|
||
isLoginPage,
|
||
loginPageTick,
|
||
doLoginAndStart,
|
||
fillLoginForm,
|
||
startBatch,
|
||
consumePendingStart,
|
||
findNextLessonElement,
|
||
lessonItems,
|
||
dumpCatalog,
|
||
clickLesson,
|
||
alignToFirstIncomplete,
|
||
isLessonCompleted,
|
||
findFirstIncompleteLessonElement,
|
||
listVm,
|
||
shortCatalogKey,
|
||
courseIdOfCard,
|
||
ensureShortCatalog,
|
||
chooseShortCourse,
|
||
sortCardsByDuration,
|
||
formatDuration,
|
||
pendingShortItems,
|
||
invalidateShortCatalog,
|
||
retryCount,
|
||
retryWaiting,
|
||
retryWaitSeconds,
|
||
completeCurrent,
|
||
failCurrent,
|
||
// 以下供开发/真机测试驱动内部路径使用:
|
||
scanCards,
|
||
currentPage,
|
||
maxPageNumber,
|
||
startCourse,
|
||
jumpToPage,
|
||
nextPage,
|
||
listTick,
|
||
courseTick,
|
||
manualCourseTick,
|
||
loginFields,
|
||
findLoginVm,
|
||
checkLoginAgreement,
|
||
setNativeValue,
|
||
saveCreds,
|
||
loadCreds,
|
||
clearSavedCreds,
|
||
pauseAllMedia,
|
||
findPlayableVideo,
|
||
ensurePlaying,
|
||
readActiveLessonKey,
|
||
detectQuiz,
|
||
courseTitle,
|
||
findNextButton,
|
||
clickNode,
|
||
stopBatch,
|
||
// 考试:调试/真机验证用
|
||
examTick,
|
||
examPhase,
|
||
examLessonElements,
|
||
findPendingExamLesson
|
||
},
|
||
configurable: true
|
||
});
|
||
} catch (e) {
|
||
}
|
||
console.log("%c云学堂助手 v" + VERSION + " 已加载", "color:#3c9;font-weight:bold");
|
||
setStatus(S.batchFinished ? "本次已完成 " + S.completedThisRun + " 门(已停止)" : S.batchRunning ? "列表刷课运行中" : "待机");
|
||
})();
|