feat: v2.8.0 无头运行器、考试自动交卷、改为退避重试不跳课
新增无头运行能力,解决 Linux 无图形化服务器上无法常驻的问题;同时改掉 "遇到考试课/无进展课就跳过"的策略,改为在同门课上退避重试。 - runner/:自己起无头 Chromium,用 CDP 把构建产物注入页面主世界(等价 @grant none),不装插件、不需要桌面环境或 Xvfb;含浏览器探测与启动参数、 持久化 profile、陈旧 SingletonLock 清理、优雅退出、日志轮转、启动预检 - runner.config.mjs / start-headless.cmd:通用配置 + Windows 一键入口; 凭据只走 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD 环境变量 - src/exam.js:含考试章节的课程自动进考试 → 开始/继续 → 空卷提交 → 确定, 交卷后靠平台记账推进课程;maxExamTries 限制同门课交卷次数,防不记账时死循环 - 去掉跳过与黑名单:没学完就退避重试(30s 起翻倍,最长 5 分钟), 同门课超过 maxCourseRetries 次才停整轮并提示,替代原 maxConsecutiveFailures - 每完成一门都重新拉列表接口取平台实时状态再选下一门,避免用陈旧队列 - 学习进度改存 sessionStorage(yun-xue-tang-run-state-v3),整页跳转/刷新可续; 运行开关不跨会话,浏览器重启后必须显式开跑 - dev/:新增 real-cdp / real-run / real-test / real-e2e 实跑脚本与 check.mjs 统一静态检查(JS 22 + 批处理 2),替代逐文件 node --check - docs/evidence/headless-linux-evidence.txt + 实跑截图,README 补无头部署章节
This commit is contained in:
1 parent
8193326b70
commit
ae117222df
47 files changed
+6198
-837
No files matched your search
+94
-36
@@ -1,27 +1,48 @@
|
||||
// ======== 完成 / 失败 ========
|
||||
// ======== 完成 / 未完成 ========
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { R, S, saveRunState, invalidateShortCatalog, PHASE_IDLE } from './state.js';
|
||||
import { goToList } from './route.js';
|
||||
import { later } from './lifecycle.js';
|
||||
import { truncate } from './utils.js';
|
||||
import { truncate, isGenericCourseTitle, norm } from './utils.js';
|
||||
import { setStatus, updatePanel } from './panel.js';
|
||||
import { courseTitle, pauseAllMedia } from './player.js';
|
||||
import { forgetShortCourse } from './list.js';
|
||||
|
||||
// 取本次要记录的课程名:优先用队列里启动时抓到的真课程名,
|
||||
// 不要在切页瞬间用页面标题(会变成「在线课堂」这类占位文案,
|
||||
// 导致 completedTitles 记错名、下轮又重复进同一门课)。
|
||||
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;
|
||||
}
|
||||
|
||||
// 这门课本轮已试过几次(按标题归一化后的键,同名课程共用一条记录)
|
||||
export function retryCount(title) {
|
||||
const t = norm(title);
|
||||
if (!t) return 0;
|
||||
const rec = (S.courseRetries || {})[t];
|
||||
return rec && rec.n ? rec.n : 0;
|
||||
}
|
||||
|
||||
export function completeCurrent() {
|
||||
const title = S.current ? S.current.title : courseTitle();
|
||||
const title = recordTitle();
|
||||
if (title) {
|
||||
S.done[title] = Date.now();
|
||||
forgetShortCourse(title);
|
||||
S.completedTitles[title] = Date.now();
|
||||
delete S.courseRetries[norm(title)];
|
||||
}
|
||||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||||
S.consecutiveFailures = 0;
|
||||
S.current = null;
|
||||
S.phase = 'idle';
|
||||
S.returning = true;
|
||||
save();
|
||||
S.activeCourse = null;
|
||||
S.coursePhase = PHASE_IDLE;
|
||||
S.awaitingListReturn = true;
|
||||
saveRunState();
|
||||
R.doneLatchKey = '';
|
||||
R.lastSummary = null;
|
||||
R.retryWaitUntil = 0;
|
||||
R.retryTitle = '';
|
||||
// 完成一门就丢掉时长队列:下一轮重新调列表接口拿平台实时状态
|
||||
invalidateShortCatalog();
|
||||
// 平台在完成后会把播放器重置到 0 秒,先暂停,避免又从头播一遍
|
||||
pauseAllMedia();
|
||||
|
||||
@@ -29,9 +50,9 @@ export function completeCurrent() {
|
||||
|
||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : Infinity;
|
||||
if (S.completedThisRun >= limit) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
save();
|
||||
S.batchRunning = false;
|
||||
S.batchFinished = true;
|
||||
saveRunState();
|
||||
setStatus('本次已完成 ' + S.completedThisRun + ' 门,已停止。可重新勾选开始新一轮。');
|
||||
} else {
|
||||
setStatus('课程完成:' + truncate(title, 26) + '(本次 ' + S.completedThisRun + ')');
|
||||
@@ -40,34 +61,71 @@ export function completeCurrent() {
|
||||
later(function () { goToList(true); }, 1200);
|
||||
}
|
||||
|
||||
// 课程没学完(不是「跳过」,是「重试」):
|
||||
// 同一门课最多重试 CFG.maxCourseRetries 次,退避等待后重新进这门课;
|
||||
// 超过次数才停止整轮刷课并明确提示——不会把这门课悄悄拉黑、换下一门。
|
||||
export function failCurrent(reason) {
|
||||
const title = S.current ? S.current.title : courseTitle();
|
||||
if (title) {
|
||||
S.failed[title] = { reason: reason, at: Date.now() };
|
||||
forgetShortCourse(title);
|
||||
}
|
||||
S.current = null;
|
||||
S.phase = 'idle';
|
||||
S.returning = true;
|
||||
S.consecutiveFailures = (S.consecutiveFailures || 0) + 1;
|
||||
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;
|
||||
|
||||
if (S.consecutiveFailures >= CFG.maxConsecutiveFailures) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
setStatus('连续失败 ' + S.consecutiveFailures + ' 门,已暂停:' + reason);
|
||||
save();
|
||||
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;
|
||||
}
|
||||
|
||||
save();
|
||||
setStatus('跳过:' + truncate(title, 24) + '(' + reason + ')');
|
||||
later(function () { goToList(true); }, 1000);
|
||||
// 退避:30 秒起,每次翻倍,最长 5 分钟;整轮连续重试次数越多等得越久,
|
||||
// 避免「进课就失败 → 立刻重进」把页面刷爆。
|
||||
const backoff = Math.min(300000, 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 / 1000) + ' 秒后重试(第 ' +
|
||||
rec.n + '/' + CFG.maxCourseRetries + ' 次):', title, reason);
|
||||
setStatus('未学完:' + truncate(title, 20) + '(' + reason + '),' +
|
||||
Math.round(backoff / 1000) + ' 秒后重试第 ' + rec.n + '/' + CFG.maxCourseRetries + ' 次');
|
||||
updatePanel();
|
||||
// 回列表等退避结束(listTick 会在等待期内不进课,到点后重新挑最短的未完成课)
|
||||
later(function () { goToList(true); }, 1200);
|
||||
}
|
||||
|
||||
// 重试退避是否还在等待期内
|
||||
export function retryWaiting() {
|
||||
return !!(R.retryWaitUntil && Date.now() < R.retryWaitUntil);
|
||||
}
|
||||
|
||||
// 重试等待剩余秒数(面板/日志用)
|
||||
export function retryWaitSeconds() {
|
||||
if (!R.retryWaitUntil) return 0;
|
||||
return Math.max(0, Math.ceil((R.retryWaitUntil - Date.now()) / 1000));
|
||||
}
|
||||
|
||||
export function stopBatch(reason) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
save();
|
||||
setStatus(reason || '批量任务结束');
|
||||
S.batchRunning = false;
|
||||
S.batchFinished = true;
|
||||
saveRunState();
|
||||
setStatus(reason || '列表刷课结束');
|
||||
updatePanel();
|
||||
}
|
||||
+23
-11
@@ -1,26 +1,38 @@
|
||||
// ======== 配置 ========
|
||||
export const CFG = {
|
||||
mute: true, // 静音(自动播放更稳)
|
||||
autoNext: true, // 手动打开课程时,本节结束后自动下一节
|
||||
autoNext: true, // 当前课程自动连播:本节结束后自动下一节
|
||||
tickMs: 2000, // 主循环间隔
|
||||
startClickCooldownMs: 3000, // 「开始学习」重复点击冷却(3 秒内没起播就补点)
|
||||
entryGraceMs: 30000, // 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」
|
||||
stuckMs: 5 * 60 * 1000, // 连续多久没有计时进展就放弃当前课程
|
||||
maxCourses: 10, // 本次最多完成多少门;0 = 不限
|
||||
maxConsecutiveFailures: 5, // 连续失败多少门后自动停止
|
||||
maxCourseRetries: 5, // 同一门课最多重试多少次(不跳过课程,超次数就停下整轮刷课)
|
||||
courseRetryDelayMs: 30000, // 首次重试前的等待;之后每次翻倍,最长 5 分钟
|
||||
alignToFirstIncomplete: true, // 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置
|
||||
preferShortCourses: true, // 批量选课时优先总时长更短的课程(正序)
|
||||
preferShortCourses: true, // 列表刷课时优先总时长更短的课程(正序)
|
||||
maxExamTries: 2, // 同一门课「空卷交卷」的最大次数(平台没记账时避免死循环)
|
||||
examClickCooldownMs: 1500, // 考试页内两次点击的间隔
|
||||
staleCourseMs: 10 * 60 * 1000, // 恢复「当前课程」时允许的最大年龄,更旧的一律丢弃
|
||||
};
|
||||
|
||||
// 版本号:由 build.mjs 从 package.json 注入,不要手改
|
||||
export const VERSION = __YT_VERSION__;
|
||||
export const VERSION = __YUN_XUE_TANG_VERSION__;
|
||||
|
||||
export const LS_ENABLED = 'yt-auto-play-enabled';
|
||||
export const LS_BATCH = 'yt-batch-v2';
|
||||
export const LS_LOGIN = 'yt-login-v1';
|
||||
export const LS_PENDING = 'yt-auto-start-after-login';
|
||||
export const LS_PREFER_SHORT = 'yt-prefer-short';
|
||||
export const SS_SHORT_CATALOG = 'yt-short-catalog-v1';
|
||||
// ---- localStorage:用户偏好(跨会话成立) ----
|
||||
export const LS_ENABLED = 'yun-xue-tang-auto-play-enabled';
|
||||
export const LS_PREFER_SHORT = 'yun-xue-tang-prefer-short';
|
||||
export const LS_TARGET_CATALOG_URL = 'yun-xue-tang-target-catalog-url';
|
||||
export const LS_LOGIN = 'yun-xue-tang-login-v1';
|
||||
export const LS_PENDING = 'yun-xue-tang-auto-start-after-login';
|
||||
|
||||
// ---- sessionStorage:本次进度 + 本次运行状态(换标签页/重启即作废) ----
|
||||
export const SS_RUN_STATE = 'yun-xue-tang-run-state-v3';
|
||||
export const SS_SHORT_CATALOG = 'yun-xue-tang-short-catalog-v1';
|
||||
export const SHORT_CATALOG_TTL = 5 * 60 * 1000;
|
||||
export const PANEL_ID = 'yt-auto-panel';
|
||||
|
||||
// 旧版本把「进度 + 运行意图」整块塞进 localStorage,只用于一次性迁移(迁移后即删除)
|
||||
export const LEGACY_LS_BATCH = 'yun-xue-tang-batch-v2';
|
||||
|
||||
export const PANEL_ID = 'yun-xue-tang-panel';
|
||||
export const TAG = '[云学堂助手]';
|
||||
+81
-16
@@ -1,6 +1,6 @@
|
||||
// ======== 课程页 ========
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { R, S, saveRunState, PHASE_LEARNING } from './state.js';
|
||||
import { goToList, mediaPage } from './route.js';
|
||||
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
|
||||
import { later } from './lifecycle.js';
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
hookAllVideos, findPlayableVideo, ensurePlaying, readSummary, readCountdown,
|
||||
readActiveLessonKey, findNextLessonElement, findNextButton, clickNode,
|
||||
fireClickSequence, lessonClickNodes, syncManualCourse, pauseAllMedia,
|
||||
findPendingExamLesson, lessonItems, isLessonCompleted, lessonActiveLi, clickLesson,
|
||||
} from './player.js';
|
||||
import { examTick, examPhase } from './exam.js';
|
||||
import { completeCurrent, failCurrent } from './complete.js';
|
||||
|
||||
export function courseTick() {
|
||||
R.listWithCurrentSince = 0;
|
||||
if (!S.current) {
|
||||
if (!S.activeCourse) {
|
||||
goToList();
|
||||
return;
|
||||
}
|
||||
@@ -26,10 +28,10 @@ export function courseTick() {
|
||||
|
||||
const isMedia = mediaPage();
|
||||
const urlId = courseIdFromUrl();
|
||||
const curId = S.current.id || '';
|
||||
const curId = S.activeCourse.id || '';
|
||||
const title = courseTitle();
|
||||
const nt = norm(title);
|
||||
const nc = norm(S.current.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;
|
||||
@@ -37,7 +39,7 @@ export function courseTick() {
|
||||
// 在线课堂,旧逻辑会把它当成「课程不一致」在 12 秒后把课退回列表。
|
||||
const idKnown = !!(urlId && curId);
|
||||
const sameCourse = idKnown ? urlId === curId : titleSame;
|
||||
const graceOver = Date.now() - (S.current.startedAt || 0) > CFG.entryGraceMs;
|
||||
const graceOver = Date.now() - (S.activeCourse.startedAt || 0) > CFG.entryGraceMs;
|
||||
if (!sameCourse) {
|
||||
if (graceOver) {
|
||||
console.warn(TAG, '页面课程与队列不一致:队列', nc, curId,
|
||||
@@ -48,9 +50,9 @@ export function courseTick() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (S.phase !== 'learning') {
|
||||
S.phase = 'learning';
|
||||
save();
|
||||
if (S.coursePhase !== PHASE_LEARNING) {
|
||||
S.coursePhase = PHASE_LEARNING;
|
||||
saveRunState();
|
||||
}
|
||||
|
||||
// #/scan 只是进课过渡页:此时页面组件里可能还残留上一门课的汇总,
|
||||
@@ -60,22 +62,30 @@ export function courseTick() {
|
||||
// 1) 防挂机验证(每 10 分钟弹一次,120 秒内不点「继续学习」就停止计时)
|
||||
if (handleAntiIdle()) return;
|
||||
|
||||
// 2) 答题/考试检测
|
||||
// 2) 考试页(说明页 / 答卷页 / 结果页):自动进考试并空卷交卷
|
||||
if (examTick(false)) return;
|
||||
|
||||
// 3) 答题/测验/问卷仍需人工处理
|
||||
if (detectQuiz()) {
|
||||
failCurrent('检测到答题/考试,需要手动处理');
|
||||
failCurrent('检测到答题/测验,需要手动处理');
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) 课程是否包含考试/测验类章节(只需检查一次)
|
||||
// 4) 课程是否包含答题/测验类章节(只需检查一次)
|
||||
if (!R.quizChecked && document.querySelector('.yxtulcdsdk-catalog ul > li .tag-type')) {
|
||||
R.quizChecked = true;
|
||||
if (courseHasQuizLesson()) {
|
||||
failCurrent('课程包含考试/测验章节');
|
||||
failCurrent('课程包含答题/测验章节');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 4) 整门课程是否已完成 / 平台是否刚记录了一节
|
||||
// 5) 有未完成的考试课时且当前不在考试页:先点进考试节(进去后下一轮 examTick 接管)
|
||||
// 汇总已满时不再进考试:个别课程考试节未做但平台已算完成,
|
||||
// 再进考试只会白白多交一次卷。
|
||||
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
|
||||
|
||||
// 6) 整门课程是否已完成 / 平台是否刚记录了一节
|
||||
const summary = readSummary();
|
||||
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
|
||||
if (summary) {
|
||||
@@ -158,7 +168,7 @@ export function courseTick() {
|
||||
if (!localDone) {
|
||||
if (v) {
|
||||
ensurePlaying(v);
|
||||
const want = '学习中:' + truncate(lessonKey || S.current.title, 30);
|
||||
const want = '学习中:' + truncate(lessonKey || S.activeCourse.title, 30);
|
||||
if (statusEl && (statusEl.textContent === '点击开始学习…' ||
|
||||
(isMedia && statusEl.textContent !== want))) {
|
||||
setStatus(want);
|
||||
@@ -300,7 +310,58 @@ export function advanceLesson() {
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 手动课程自动连播 ========
|
||||
// ======== 考试课时 ========
|
||||
// 平台汇总已算完成(个别课考试节没做也判完成)时不再进考试,
|
||||
// 否则只会白白多交一次卷。
|
||||
function isSummaryComplete() {
|
||||
const s = readSummary();
|
||||
return !!(s && s.complete);
|
||||
}
|
||||
|
||||
// 目录里有未完成的考试课时时,先点进考试节。点完后平台会渲染考试说明页,
|
||||
// 下一轮 tick 由 examTick() 接管(开始考试 → 不答题 → 提交 → 确定)。
|
||||
// 顺序上把考试放到最后:还有普通课时没学完就不进考试,
|
||||
// 避免「进考试→交卷→重进课程页」的额外跳转打断正常播放。
|
||||
// 返回 true = 本 tick 已在处理,调用方直接 return。
|
||||
export 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;
|
||||
|
||||
// 已经停在这一节(说明页/答卷页由 examTick 管),不重复点
|
||||
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;
|
||||
}
|
||||
|
||||
// ======== 当前课程自动连播(手动打开的课) ========
|
||||
export function manualCourseTick() {
|
||||
hookAllVideos();
|
||||
if (handleAntiIdle()) return;
|
||||
@@ -314,6 +375,10 @@ export function manualCourseTick() {
|
||||
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;
|
||||
@@ -325,7 +390,7 @@ export function manualCourseTick() {
|
||||
const summary = readSummary();
|
||||
if (summary && summary.complete) {
|
||||
pauseAllMedia();
|
||||
setStatus('课程已完成:' + truncate(S.current ? S.current.title : title, 24));
|
||||
setStatus('课程已完成:' + truncate(S.activeCourse ? S.activeCourse.title : title, 24));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
// ======== 考试:自动进入考试并空卷交卷 ========
|
||||
// 平台的考试章节不是可播放的课时:进课后显示的是「考试说明页」(开始考试 / 继续考试),
|
||||
// 点进去是答卷页(答题卡 + 提交考试),交卷后是结果页(查看答卷详情 / 返回考试说明页)。
|
||||
// 这里的目标只有一个:进入考试后一题不做,直接交卷,让考试章节计入课程进度,
|
||||
// 从而让「含考试章节的课程」也能被刷完,而不是整门课被跳过。
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, saveRunState } from './state.js';
|
||||
import { textOf, isVisible, courseIdFromUrl } from './utils.js';
|
||||
import { later } from './lifecycle.js';
|
||||
import { setStatus } from './panel.js';
|
||||
import { failCurrent, completeCurrent } from './complete.js';
|
||||
import { readSummary } from './player.js';
|
||||
|
||||
// 只认「考试」相关文案:答题/测验/问卷仍按「需要人工处理」跳过
|
||||
const START_RE = /^(开始考试|继续考试|进入考试)$/;
|
||||
const SUBMIT_RE = /^(提交考试|提交试卷|交卷|交卷并退出)$/;
|
||||
// 「交卷」类文案里只有考试独有的几个能用来判定「当前是考试答卷页」;
|
||||
// 「提交试卷」同样会出现在答题/测验页上,不能拿来当考试标志(否则会误抢答题页)。
|
||||
const EXAM_SUBMIT_RE = /^(提交考试|交卷|交卷并退出)$/;
|
||||
const CONFIRM_RE = /^(确定|确认|确定交卷|确认交卷|提交|提交试卷)$/;
|
||||
const RESULT_RE = /^(查看答卷详情|返回考试说明页)$/;
|
||||
|
||||
function visibleAll(sel, root) {
|
||||
let list = [];
|
||||
try {
|
||||
list = [...(root || document).querySelectorAll(sel)];
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
return list.filter(isVisible);
|
||||
}
|
||||
|
||||
// 点击优先级:真正的 button > 按钮类样式 > a > span > 其它。
|
||||
// 站点把点击回调绑在 <button> 上,点到外层 div 不会有任何反应。
|
||||
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;
|
||||
}
|
||||
|
||||
// 有些节点是 svg 包装,没有 click();统一派发鼠标事件序列
|
||||
export 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];
|
||||
}
|
||||
|
||||
// ---- 考试页的三种形态 ----
|
||||
export function examPreviewRoot() {
|
||||
return visibleAll('.yxtulcdsdk-uexam-preview, [class*="uexam-preview"]')[0] || null;
|
||||
}
|
||||
|
||||
export function examPaperRoot() {
|
||||
return visibleAll('[class*="answer-card"], [class*="answerSheet"], [class*="answer-sheet"]')[0] || null;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 'preview' = 考试说明页 | 'paper' = 答卷页 | 'result' = 交卷后的结果页 | '' = 不在考试页
|
||||
export 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 '';
|
||||
}
|
||||
|
||||
// 交卷确认框里的「确定」按钮:只认可见、文案短、且提到交卷/未做的弹层,避免点到隐藏的弹窗模板。
|
||||
// 注意:弹层里文案最短的一层往往是「还有 N 道题未做,是否确认交卷?」的消息体,
|
||||
// 它本身不包含底部按钮,所以按文案长度升序逐个尝试,谁里面有「确定」就用谁。
|
||||
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: btn };
|
||||
}
|
||||
return { shown: true, btn: null };
|
||||
}
|
||||
|
||||
// 手动刷课(自己点开的课)里出错不应该动队列,只停下并提示;
|
||||
// 批量刷课走 failCurrent(重试退避,超过次数才停止整轮)。
|
||||
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);
|
||||
}
|
||||
|
||||
export function examTriedTimes(key) {
|
||||
const m = S.examEmptySubmits || {};
|
||||
return m[key || examCourseKey()] || 0;
|
||||
}
|
||||
|
||||
// 交卷后返回课程页有两种真实情况:
|
||||
// 1) 结果页是课程页里的一个视图,location.href 目标与当前 URL 相同,赋值不会触发任何导航
|
||||
// → 必须 reload,否则会停在结果页无限循环交卷;
|
||||
// 2) 正常的跨路由跳转,href 赋值即可。
|
||||
export 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;
|
||||
// 兜底:SPA 有时只换 hash 不重渲染,1.5 秒后仍在原地址就强制刷新
|
||||
later(function () {
|
||||
if (location.href === cur) {
|
||||
try { location.reload(); } catch (e) { /* ignore */ }
|
||||
}
|
||||
}, 1500);
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 每个 tick 调用。返回 true = 本 tick 已在处理考试页,调用方应直接 return。
|
||||
export 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 < 2000) 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;
|
||||
}
|
||||
+35
-10
@@ -1,22 +1,31 @@
|
||||
// ======== 主循环 ========
|
||||
'use strict';
|
||||
import { CFG, VERSION, TAG } from './config.js';
|
||||
import { R, S, state, save } from './state.js';
|
||||
import { R, S, state, saveRunState, flushRunState, invalidateShortCatalog } from './state.js';
|
||||
import { every, later, onWindow } from './lifecycle.js';
|
||||
import { courseIdFromUrl } from './utils.js';
|
||||
import { route, mediaPage } from './route.js';
|
||||
import { ensurePanel, setStatus } from './panel.js';
|
||||
import { isLoginPage, loginPageTick, doLoginAndStart, fillLoginForm, startBatch, consumePendingStart, setTick } from './login.js';
|
||||
import { isLoginPage, loginPageTick, doLoginAndStart, fillLoginForm, startBatch, consumePendingStart, setTick, loginFields, findLoginVm, checkLoginAgreement, setNativeValue, saveCreds, loadCreds, clearSavedCreds } from './login.js';
|
||||
import {
|
||||
listTick, listVm, shortCatalogKey, courseIdOfCard, ensureShortCatalog,
|
||||
chooseShortCourse, sortCardsByDuration, formatDuration,
|
||||
pendingShortItems, forgetShortCourse,
|
||||
pendingShortItems, scanCards, currentPage, maxPageNumber,
|
||||
startCourse, jumpToPage, nextPage,
|
||||
} from './list.js';
|
||||
import { courseTick, manualCourseTick } from './course.js';
|
||||
import {
|
||||
stopBatch, retryCount, retryWaiting, retryWaitSeconds,
|
||||
completeCurrent, failCurrent,
|
||||
} from './complete.js';
|
||||
import { examTick, examPhase } from './exam.js';
|
||||
import {
|
||||
hookAllVideos, readSummary, readCountdown, lessonItems,
|
||||
findNextLessonElement, clickLesson, alignToFirstIncomplete,
|
||||
isLessonCompleted, findFirstIncompleteLessonElement, dumpCatalog,
|
||||
pauseAllMedia, findPlayableVideo, ensurePlaying, readActiveLessonKey,
|
||||
detectQuiz, courseTitle, findNextButton, clickNode,
|
||||
examLessonElements, findPendingExamLesson,
|
||||
} from './player.js';
|
||||
|
||||
function tick() {
|
||||
@@ -26,8 +35,8 @@ function tick() {
|
||||
if (isLoginPage()) loginPageTick();
|
||||
if (consumePendingStart()) return;
|
||||
|
||||
if (!S.running) {
|
||||
if (route() === 'course' && state.enabled) {
|
||||
if (!S.batchRunning) {
|
||||
if (route() === 'course' && state.autoPlayEnabled) {
|
||||
manualCourseTick();
|
||||
} else {
|
||||
R.manualCourseKey = ''; // 离开课程页后,下次进入同一门课要重新对齐
|
||||
@@ -65,9 +74,11 @@ if (window.top !== window.self) {
|
||||
|
||||
// 调试入口(仅本地使用,可在控制台查看状态)
|
||||
try {
|
||||
Object.defineProperty(window, '__ytAuto', {
|
||||
Object.defineProperty(window, '__yunXueTangAuto', {
|
||||
value: {
|
||||
S, R, state, tick, save, route,
|
||||
S, R, state, tick, save: saveRunState, flush: flushRunState, route,
|
||||
// CFG 暴露给无头运行器:可用 --max / YUN_XUE_TANG_MAX_COURSES 覆盖本次运行的门数上限
|
||||
CFG,
|
||||
mediaPage, courseIdFromUrl,
|
||||
readCountdown, readSummary,
|
||||
isLoginPage, loginPageTick,
|
||||
@@ -82,13 +93,27 @@ try {
|
||||
courseIdOfCard,
|
||||
ensureShortCatalog, chooseShortCourse,
|
||||
sortCardsByDuration, formatDuration,
|
||||
pendingShortItems, forgetShortCourse,
|
||||
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) { /* ignore */ }
|
||||
|
||||
console.log('%c云学堂助手 v' + VERSION + ' 已加载', 'color:#3c9;font-weight:bold');
|
||||
setStatus(S.runFinished
|
||||
// 刷课是否在跑由 sessionStorage 里的本标签页状态决定:
|
||||
// 浏览器重启 / 运行器新建标签页后一定是待机,不会在未登录的页面上谎报「运行中」。
|
||||
setStatus(S.batchFinished
|
||||
? '本次已完成 ' + S.completedThisRun + ' 门(已停止)'
|
||||
: (S.running ? '自动刷课运行中' : '待机'));
|
||||
: (S.batchRunning ? '列表刷课运行中' : '待机'));
|
||||
+5
-5
@@ -48,19 +48,19 @@ export function dispose() {
|
||||
drain(WINDOW_LISTENERS, detachListener);
|
||||
drain(ELEMENT_LISTENERS, detachListener);
|
||||
try {
|
||||
document.querySelectorAll('video[data-yt-hooked]').forEach(function (v) {
|
||||
v.removeAttribute('data-yt-hooked');
|
||||
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.__ytAuto; } catch (e) {}
|
||||
try { if (window.__ytDispose === dispose) delete window.__ytDispose; } catch (e) {}
|
||||
try { delete window.__yunXueTangAuto; } catch (e) {}
|
||||
try { if (window.__yunXueTangDispose === dispose) delete window.__yunXueTangDispose; } catch (e) {}
|
||||
console.log(TAG, '旧实例已释放');
|
||||
}
|
||||
|
||||
try {
|
||||
Object.defineProperty(window, '__ytDispose', {
|
||||
Object.defineProperty(window, '__yunXueTangDispose', {
|
||||
value: dispose, configurable: true, writable: true,
|
||||
});
|
||||
} catch (e) { /* 重复注入时忽略 */ }
|
||||
+104
-53
@@ -1,10 +1,14 @@
|
||||
// ======== 列表页 ========
|
||||
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
|
||||
import { R, S, state, save, resetCourseRuntime } from './state.js';
|
||||
import {
|
||||
R, S, state, saveRunState, setTargetCatalogUrl, resetCourseRuntime, invalidateShortCatalog,
|
||||
PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
|
||||
} from './state.js';
|
||||
import { norm, textOf, truncate } from './utils.js';
|
||||
import { clickNode } from './player.js';
|
||||
import { setStatus, updatePanel } from './panel.js';
|
||||
import { failCurrent, stopBatch } from './complete.js';
|
||||
import { retryWaiting, retryWaitSeconds } from './complete.js';
|
||||
|
||||
export function scanCards() {
|
||||
return [...document.querySelectorAll('li.kng-list-new__item')].map((li, i) => {
|
||||
@@ -95,7 +99,7 @@ export function nextPage() {
|
||||
// 列表卡片本身不显示时长,但列表组件(ul.kng-list-new.__vue__)的 kngListData
|
||||
// 里每门课都带 studyHours(秒)。当前页可据此按时长排序;要进一步跨页优先,
|
||||
// 再用同一套列表接口一次性读取全部课程,按 studyHours 正序排队。
|
||||
// 接口失败时逐级降级:跨页队列 → 当前页时长排序 → 原列表顺序,绝不卡住批量任务。
|
||||
// 接口失败时逐级降级:跨页队列 → 当前页时长排序 → 原列表顺序,绝不卡住刷课任务。
|
||||
|
||||
export function formatDuration(seconds) {
|
||||
const n = Number(seconds);
|
||||
@@ -197,9 +201,12 @@ export function shortCatalogRequest(vm) {
|
||||
return { body: body, headers: headers };
|
||||
}
|
||||
|
||||
// 一次性读取列表接口(limit=6000 可覆盖当前 5000+ 门课程的站点),
|
||||
// 只保留「未学完」的课程,并映射到它所在的页码。
|
||||
async function fetchShortCatalog(vm) {
|
||||
// 刚完成的课程平台记账有延迟,这段窗口内不剔除 done 里的旧记录
|
||||
const DONE_STALE_MS = 10 * 60 * 1000;
|
||||
|
||||
// 一次性读取列表接口(limit=6000 可覆盖当前 5000+ 门课程的站点),
|
||||
// 只保留「未学完」的课程,并映射到它所在的页码。
|
||||
async function fetchShortCatalog(vm) {
|
||||
const key = shortCatalogKey(vm);
|
||||
const q = shortQuery(vm);
|
||||
const req = shortCatalogRequest(vm);
|
||||
@@ -229,18 +236,31 @@ export function shortCatalogRequest(vm) {
|
||||
}
|
||||
|
||||
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;
|
||||
// 平台说这门课还没学完,但本地 done 里有记录:说明本地快照旧了
|
||||
// (例如平台回滚了进度、或之前是在另一目录下学完的同名课)。
|
||||
// 刚完成的那门课平台记账有延迟,所以只剔除超过 DONE_STALE_MS 的旧记录。
|
||||
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: norm(item.title),
|
||||
title: 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;
|
||||
@@ -253,7 +273,7 @@ export function shortCatalogRequest(vm) {
|
||||
|
||||
// 返回 'off' | 'loading' | 'ready' | 'failed'
|
||||
export function ensureShortCatalog() {
|
||||
if (!state.preferShort) return 'off';
|
||||
if (!state.preferShortCourses) return 'off';
|
||||
|
||||
const vm = listVm();
|
||||
if (!vm) {
|
||||
@@ -298,7 +318,7 @@ export function ensureShortCatalog() {
|
||||
setStatus('正在读取课程时长,优先安排短课程…');
|
||||
fetchShortCatalog(vm).then(function (cat) {
|
||||
R.shortCatalogLoading = false;
|
||||
if (!state.preferShort) return;
|
||||
if (!state.preferShortCourses) return;
|
||||
R.shortCatalogFailedAt = 0;
|
||||
R.shortCatalog = cat;
|
||||
writeShortCatalog(cat);
|
||||
@@ -312,7 +332,7 @@ export function ensureShortCatalog() {
|
||||
}).catch(function (e) {
|
||||
R.shortCatalogLoading = false;
|
||||
R.shortCatalogFailedAt = Date.now();
|
||||
if (!state.preferShort) return;
|
||||
if (!state.preferShortCourses) return;
|
||||
console.warn(TAG, '读取课程时长失败,退回当前页时长排序:',
|
||||
e && e.message ? e.message : e);
|
||||
setStatus('未能读取全部课程时长,先按当前页时长排序');
|
||||
@@ -337,12 +357,13 @@ export function pendingShortItems() {
|
||||
if (!cat) return [];
|
||||
return cat.items.filter(function (item) {
|
||||
if (!item || !item.title) return false;
|
||||
if (S.done[item.title] || S.failed[item.title]) return false;
|
||||
// 只排除「本轮已完成」;不再排除任何「失败/跳过」——没过就是重试,不是拉黑
|
||||
if (S.completedTitles[item.title]) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// 列表卡片 -> 课程 id。卡片的打开逻辑按 id 跳转,而播放页 URL 带 kngId:
|
||||
// 列表卡片 -> 课程 id。卡片的打开逻辑按 id 跳转,而播放页 URL 带 kngId:
|
||||
// 有了 id 就能在标题还没刷新时准确判断「进的是不是队列里的这门课」,
|
||||
// 不再因为页面标题短暂是 loading/在线课堂 就误判并退回列表。
|
||||
export function courseIdOfCard(card) {
|
||||
@@ -396,9 +417,15 @@ export function forgetShortCourse(title) {
|
||||
if (R.shortCatalog.items.length !== before) writeShortCatalog(R.shortCatalog);
|
||||
}
|
||||
|
||||
// 时长队列是否可用(可用时页码导航由 chooseShortCourse 独占,listTick 不再恢复页码)
|
||||
export function isShortCatalogActive() {
|
||||
return !!(state.preferShortCourses && R.shortCatalog &&
|
||||
Date.now() - (R.shortCatalog.at || 0) < SHORT_CATALOG_TTL);
|
||||
}
|
||||
|
||||
// 返回 { card } 表示本 tick 可以进入该课程;{ wait: true } 表示正在加载/翻页。
|
||||
export function chooseShortCourse(cards, pending) {
|
||||
if (!state.preferShort) return null;
|
||||
if (!state.preferShortCourses) return null;
|
||||
const status = ensureShortCatalog();
|
||||
|
||||
if (status === 'loading') return { wait: true };
|
||||
@@ -413,7 +440,7 @@ export function chooseShortCourse(cards, pending) {
|
||||
R.shortJumpAt = Date.now();
|
||||
if (jumpToPage(target.page)) {
|
||||
S.listPage = target.page;
|
||||
save();
|
||||
saveRunState();
|
||||
setStatus('优先短课程:转到第 ' + target.page + ' 页(' +
|
||||
formatDuration(target.duration) + ')');
|
||||
return { wait: true };
|
||||
@@ -423,7 +450,7 @@ export function chooseShortCourse(cards, pending) {
|
||||
} else {
|
||||
const card = cardForShortItem(cards, target);
|
||||
if (card) {
|
||||
if (card.status === '已学完' || S.done[card.title] || S.failed[card.title]) {
|
||||
if (card.status === '已学完' || S.completedTitles[card.title]) {
|
||||
// 缓存与实际状态不一致:剔除这一门,下一 tick 继续挑下一门
|
||||
forgetShortCourse(card.title);
|
||||
return { wait: true };
|
||||
@@ -451,6 +478,16 @@ export function chooseShortCourse(cards, pending) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 短课程优先时页码归 chooseShortCourse 管:它知道下一门课在第几页,会直接跳过去。
|
||||
// 只有「没开短课程优先」或「时长队列拿不到(已明确失败)」时,listTick 才去恢复页码。
|
||||
function shouldRestorePage() {
|
||||
if (!state.preferShortCourses) return true;
|
||||
if (isShortCatalogActive()) return false;
|
||||
// 队列还在加载:先别跳,等 chooseShortCourse 一次跳到位
|
||||
if (R.shortCatalogLoading) return false;
|
||||
return !!R.shortCatalogFailedAt;
|
||||
}
|
||||
|
||||
export function listTick() {
|
||||
const cards = scanCards();
|
||||
if (!cards.length) return; // 列表还没渲染
|
||||
@@ -465,22 +502,26 @@ export function listTick() {
|
||||
}
|
||||
if (R.pageChangeAt && Date.now() - R.pageChangeAt < 1500) return;
|
||||
|
||||
if (S.listUrl !== location.href) {
|
||||
S.listUrl = location.href;
|
||||
save();
|
||||
}
|
||||
// 列表 URL 同时是「目标目录」偏好:它决定刷哪个学院的课,
|
||||
// 也是短课程队列的缓存键来源,所以单独存 localStorage。
|
||||
if (S.catalogUrl !== location.href) setTargetCatalogUrl(location.href, { silent: true });
|
||||
|
||||
const page = currentPage();
|
||||
|
||||
// 回到列表后,恢复到课程所在的页码
|
||||
if (S.returning) {
|
||||
// 回到列表后,恢复到课程所在的页码(仅在拿不到时长队列时才需要)
|
||||
if (S.awaitingListReturn && !shouldRestorePage()) {
|
||||
// 页码不需要恢复:直接交给 chooseShortCourse / 当前页继续
|
||||
S.awaitingListReturn = false;
|
||||
R.pageRestoreAttempts = 0;
|
||||
saveRunState();
|
||||
} else if (S.awaitingListReturn) {
|
||||
if (page != null && S.listPage && page !== S.listPage) {
|
||||
R.restoreAttempts++;
|
||||
if (R.restoreAttempts > 12) {
|
||||
R.pageRestoreAttempts++;
|
||||
if (R.pageRestoreAttempts > 12) {
|
||||
console.warn(TAG, '页码恢复失败,改用当前页继续');
|
||||
S.listPage = page || 1;
|
||||
S.returning = false;
|
||||
save();
|
||||
S.awaitingListReturn = false;
|
||||
saveRunState();
|
||||
} else if (S.listPage > page) {
|
||||
// 短课程优先会直接跳到很靠后的页(例如第 307 页),
|
||||
// 不能一页一页 nextPage,否则要翻几百次;优先用页码输入框直跳。
|
||||
@@ -492,36 +533,36 @@ export function listTick() {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
S.returning = false;
|
||||
R.restoreAttempts = 0;
|
||||
save();
|
||||
S.awaitingListReturn = false;
|
||||
R.pageRestoreAttempts = 0;
|
||||
saveRunState();
|
||||
setStatus('回到列表第 ' + (page || 1) + ' 页,继续…');
|
||||
}
|
||||
}
|
||||
|
||||
// 记录当前页
|
||||
if (!S.returning && page != null && page !== S.listPage) {
|
||||
if (!S.awaitingListReturn && page != null && page !== S.listPage) {
|
||||
S.listPage = page;
|
||||
save();
|
||||
saveRunState();
|
||||
}
|
||||
|
||||
// 已在进入课程的过程中:等路由跳转
|
||||
if (S.current && S.phase === 'entering') {
|
||||
const waited = Date.now() - (S.current.startedAt || 0);
|
||||
if (S.activeCourse && S.coursePhase === PHASE_ENTERING) {
|
||||
const waited = Date.now() - (S.activeCourse.startedAt || 0);
|
||||
if (waited > 15000) {
|
||||
failCurrent('未能进入课程页面');
|
||||
return;
|
||||
}
|
||||
// 列表卡片点击偶尔会落在脚本/路由就绪之前(页面毫无反应)。还停在列表时
|
||||
// 最多补点两次,而不是直接把这门课记成失败跳过。
|
||||
// 最多补点两次,而不是提前判这门课未完成。
|
||||
if (waited > 4000 && R.entryRetries < 2 &&
|
||||
Date.now() - R.lastCardClickAt > 4000) {
|
||||
const card = cards.find(function (c) { return c.title === S.current.title; });
|
||||
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.current.title, 22));
|
||||
setStatus('重新进入课程:' + truncate(S.activeCourse.title, 22));
|
||||
try { clickNode(card.li); } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
@@ -529,37 +570,50 @@ export function listTick() {
|
||||
}
|
||||
|
||||
// 从课程页意外回到列表:判断当前课程是已完成还是中断
|
||||
if (S.current && S.phase === 'learning') {
|
||||
if (S.activeCourse && S.coursePhase === PHASE_LEARNING) {
|
||||
if (!R.listWithCurrentSince) R.listWithCurrentSince = Date.now();
|
||||
if (Date.now() - R.listWithCurrentSince < 5000) return;
|
||||
|
||||
const card = cards.find(function (c) { return c.title === S.current.title; });
|
||||
const card = cards.find(function (c) { return c.title === S.activeCourse.title; });
|
||||
if (card && /已学完|已完成|已学习/.test(card.status)) {
|
||||
S.done[S.current.title] = Date.now();
|
||||
forgetShortCourse(S.current.title);
|
||||
S.completedTitles[S.activeCourse.title] = Date.now();
|
||||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||||
}
|
||||
S.current = null;
|
||||
S.phase = 'idle';
|
||||
S.returning = false;
|
||||
S.activeCourse = null;
|
||||
S.coursePhase = PHASE_IDLE;
|
||||
S.awaitingListReturn = false;
|
||||
R.listWithCurrentSince = 0;
|
||||
save();
|
||||
// 回到列表就重新拿平台实时状态(不用本地旧快照选课)
|
||||
invalidateShortCatalog();
|
||||
saveRunState();
|
||||
setStatus('已重置中断的课程状态,继续…');
|
||||
}
|
||||
|
||||
if (S.current) return; // 其他异常情况,等路由
|
||||
if (S.activeCourse) return; // 其他异常情况,等路由
|
||||
|
||||
// 上一门没学完、正在退避等待时不进任何课:到点后直接重进同一门(它仍是最短的未完成课)
|
||||
if (retryWaiting()) {
|
||||
const left = retryWaitSeconds();
|
||||
// 只在秒数变化时刷状态,避免每 tick 都打一行日志
|
||||
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.done[c.title]) return false;
|
||||
if (S.failed[c.title]) return false;
|
||||
if (S.completedTitles[c.title]) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
// 优先短课程:先读时长队列,跨页挑总时长最短的未学完课程;
|
||||
// 接口不可用时 chooseShortCourse 会退回当前页时长排序或原列表顺序。
|
||||
if (state.preferShort) {
|
||||
if (state.preferShortCourses) {
|
||||
const choice = chooseShortCourse(cards, pending);
|
||||
if (choice && choice.wait) return;
|
||||
if (choice && choice.card) {
|
||||
@@ -586,21 +640,18 @@ export function listTick() {
|
||||
|
||||
export function startCourse(card) {
|
||||
const page = currentPage() || S.listPage || 1;
|
||||
S.current = {
|
||||
S.activeCourse = {
|
||||
title: card.title,
|
||||
id: courseIdOfCard(card),
|
||||
status: card.status,
|
||||
startedAt: Date.now(),
|
||||
page: page,
|
||||
duration: card.duration || 0,
|
||||
};
|
||||
S.listPage = page;
|
||||
S.phase = 'entering';
|
||||
S.returning = false;
|
||||
S.coursePhase = PHASE_ENTERING;
|
||||
S.awaitingListReturn = false;
|
||||
R.lastCardClickAt = Date.now();
|
||||
R.shortJumpAt = 0;
|
||||
resetCourseRuntime();
|
||||
save();
|
||||
saveRunState();
|
||||
const durationText = card.duration ? '(' + formatDuration(card.duration) + ')' : '';
|
||||
setStatus('进入课程' + durationText + ':' + truncate(card.title, 28));
|
||||
console.log(TAG, '进入课程', card.title, '状态', card.status,
|
||||
|
||||
+14
-9
@@ -1,6 +1,6 @@
|
||||
// ======== 登录 / 一键刷课 ========
|
||||
import { LS_LOGIN, LS_PENDING } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { R, S, saveRunState, invalidateShortCatalog, PHASE_IDLE } from './state.js';
|
||||
import { route, goToList } from './route.js';
|
||||
import { truncate, isVisible, findVisibleButton } from './utils.js';
|
||||
import { later, onElement } from './lifecycle.js';
|
||||
@@ -139,17 +139,22 @@ export function clearSavedCreds() {
|
||||
}
|
||||
|
||||
export function startBatch() {
|
||||
if (S.runFinished) {
|
||||
if (S.batchFinished) {
|
||||
S.completedThisRun = 0;
|
||||
S.consecutiveFailures = 0;
|
||||
S.runFinished = false;
|
||||
S.batchFinished = false;
|
||||
// 重新开启一轮时清掉重试计数:之前那些课允许重新尝试
|
||||
S.courseRetries = {};
|
||||
R.retryWaitUntil = 0;
|
||||
R.retryTitle = '';
|
||||
}
|
||||
S.running = true;
|
||||
if (!S.current) S.phase = 'idle';
|
||||
save();
|
||||
setStatus('自动刷课已开启');
|
||||
S.batchRunning = true;
|
||||
// 开跑时丢掉旧的时长队列:第一门课也要按平台实时状态挑
|
||||
invalidateShortCatalog();
|
||||
if (!S.activeCourse) S.coursePhase = PHASE_IDLE;
|
||||
saveRunState();
|
||||
setStatus('列表刷课已开启');
|
||||
const r = route();
|
||||
if (r === 'list' || (r === 'course' && S.current)) {
|
||||
if (r === 'list' || (r === 'course' && S.activeCourse)) {
|
||||
tick();
|
||||
} else {
|
||||
goToList();
|
||||
|
||||
+25
-10
@@ -1,8 +1,8 @@
|
||||
// ==UserScript==
|
||||
// @name 云学堂助手
|
||||
// @namespace yun-xue-tang-assistant.local
|
||||
// @version __YT_VERSION__
|
||||
// @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并按列表批量推进课程(单视频/音频课程也支持,学完自动进入下一门,可优先短课程)
|
||||
// @version __YUN_XUE_TANG_VERSION__
|
||||
// @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并在课程列表页逐门自动刷课(单视频/音频课程也支持,含考试章节的课自动空卷交卷,学完自动进入下一门,可优先短课程;不跳过任何课程)
|
||||
// @match *://kfmic.yunxuetang.cn/*
|
||||
// @match *://*.yunxuetang.cn/*
|
||||
// @grant none
|
||||
@@ -13,7 +13,7 @@
|
||||
* 用法:
|
||||
* 1. 浏览器安装 Tampermonkey,新建脚本,粘贴本文件全部内容并保存。
|
||||
* 2. 打开 https://kfmic.yunxuetang.cn/login.html,在右下角面板填账号/密码,
|
||||
* 点「一键登录并刷课」;登录成功后会自动进入课程列表并开始批量学习。
|
||||
* 点「一键登录并刷课」;登录成功后会自动进入课程列表并开始逐门学习。
|
||||
* 3. 也可以手动登录后,在列表页点「一键刷课」。
|
||||
*
|
||||
* 密码保存:
|
||||
@@ -26,23 +26,38 @@
|
||||
* - 同时支持多课时课程(#/course/play)和单视频/音频/课件播放页(#/video/play 等):
|
||||
* 单视频课程会自动点「开始学习」;平台汇总变成「已完成学习」/100%/x=y 时判定整门课
|
||||
* 完成,自动回列表并进入下一门。
|
||||
* - 进入课程(批量或手动打开)都会先对齐到「第一个未学完的课时」,即从第一章第一节起
|
||||
* - 进入课程(列表刷课或自己点开)都会先对齐到「第一个未学完的课时」,即从第一章第一节起
|
||||
* 顺序学习,不沿用平台上次停留的位置(否则前面的课时会被跳过,整门课永远学不完)。
|
||||
* 切换成功与否以目录高亮为准:没切过去会重试并如实提示「未能切换」,不会假装已切换。
|
||||
* - 试跑稳定后,把 config.js 里的 CFG.maxCourses 改成 0 即可不限门数(会持续很久)。
|
||||
* - 平台若有防挂机检测/答题环节,脚本会跳过该课程并在面板提示。
|
||||
* 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」;
|
||||
* 答题/考试、滑块拼图类验证仍会跳过该课程。
|
||||
* - 脚本不跳过任何课程:没有「跳过本课」,也不会把课程拉黑。某门课没学完(例如遇到
|
||||
* 需要人工完成的滑块/拼图验证、答题/测验章节、长时间无计时进展)就退避重试:
|
||||
* 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.__ytDispose(),
|
||||
* - 本文件可直接被 dev/dev-loader.user.js 热注入:脚本暴露 window.__yunXueTangDispose(),
|
||||
* 加载器在注入新版本前会先调用它清理定时器、监听器与面板,因此保存文件后
|
||||
* 约 1 秒内即可生效,无需手动刷新页面。
|
||||
*/
|
||||
+44
-77
@@ -1,9 +1,8 @@
|
||||
// ======== 面板 ========
|
||||
import { CFG, VERSION, LS_ENABLED, LS_PREFER_SHORT, SS_SHORT_CATALOG, PANEL_ID, TAG } from './config.js';
|
||||
import { R, S, state, save } from './state.js';
|
||||
import { R, S, state, saveRunState } from './state.js';
|
||||
import { route } from './route.js';
|
||||
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
|
||||
import { failCurrent } from './complete.js';
|
||||
|
||||
// 会话时长:面板 footer 显示本次脚本会话自加载起已运行多久
|
||||
const SESSION_START_AT = Date.now();
|
||||
@@ -11,7 +10,6 @@ export let statusEl = null;
|
||||
let statsEl = null;
|
||||
let footerEl = null;
|
||||
let cbBatch = null;
|
||||
let btnSkip = null;
|
||||
let labelAuto = null;
|
||||
let labelBatch = null;
|
||||
let labelShort = null;
|
||||
@@ -28,15 +26,6 @@ let btnClearCreds = null;
|
||||
// 面板里两个复选框行共用同一套 label 样式
|
||||
const LABEL_CSS = 'display:flex;align-items:center;gap:6px;cursor:pointer;margin-top:4px;';
|
||||
|
||||
// 「跳过本课」/「清除失败记录」共用一套按钮样式,只有 display 不同
|
||||
function smallBtnCss(display) {
|
||||
return [
|
||||
'display:' + display, 'margin-top:6px', 'padding:2px 8px', 'cursor:pointer',
|
||||
'background:#444', 'color:#eee', 'border:1px solid #666', 'border-radius:4px',
|
||||
'font-size:12px',
|
||||
].join(';');
|
||||
}
|
||||
|
||||
function formatElapsed(ms) {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const h = Math.floor(total / 3600);
|
||||
@@ -52,22 +41,23 @@ export function setStatus(text) {
|
||||
}
|
||||
|
||||
export function updatePanel() {
|
||||
if (cbBatch) cbBatch.checked = S.running;
|
||||
if (cbBatch) cbBatch.checked = S.batchRunning;
|
||||
if (statsEl) {
|
||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : '∞';
|
||||
statsEl.textContent =
|
||||
'本次 ' + S.completedThisRun + '/' + limit +
|
||||
' · 失败 ' + Object.keys(S.failed).length +
|
||||
(R.idlePassed ? ' · 验证 ' + R.idlePassed : '');
|
||||
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()) / 1000) + 's 后重试';
|
||||
}
|
||||
text += (R.idlePassed ? ' · 验证 ' + R.idlePassed : '');
|
||||
statsEl.textContent = text;
|
||||
}
|
||||
if (footerEl) {
|
||||
footerEl.textContent = '会话时长 ' + formatElapsed(Date.now() - SESSION_START_AT);
|
||||
}
|
||||
if (btnSkip) {
|
||||
btnSkip.style.display = S.current && route() === 'course' ? 'block' : 'none';
|
||||
}
|
||||
if (cbAuto) cbAuto.checked = state.enabled;
|
||||
if (cbPreferShort) cbPreferShort.checked = state.preferShort;
|
||||
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
|
||||
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
|
||||
|
||||
const onLogin = isLoginPage();
|
||||
if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none';
|
||||
@@ -77,11 +67,11 @@ export function updatePanel() {
|
||||
if (statsEl) statsEl.style.display = onLogin ? 'none' : 'block';
|
||||
if (btnOne) {
|
||||
// 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」
|
||||
const onCourse = route() === 'course' && !!S.current;
|
||||
const onCourse = route() === 'course' && !!S.activeCourse;
|
||||
btnOne.textContent = onLogin
|
||||
? '一键登录并刷课'
|
||||
: (onCourse && S.running ? '停止刷课' : '一键刷课');
|
||||
btnOne.title = onCourse && S.running ? '停止批量刷课' : '开始 / 继续批量刷课';
|
||||
: (onCourse && S.batchRunning ? '停止刷课' : '一键刷课');
|
||||
btnOne.title = onCourse && S.batchRunning ? '停止列表刷课' : '开始 / 继续列表刷课';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +97,7 @@ export function buildPanel() {
|
||||
titleText.style.cssText = 'font-weight:600;';
|
||||
|
||||
const titleVer = document.createElement('span');
|
||||
titleVer.id = 'yt-version';
|
||||
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;';
|
||||
@@ -117,7 +107,7 @@ export function buildPanel() {
|
||||
|
||||
btnOne = document.createElement('button');
|
||||
btnOne.type = 'button';
|
||||
btnOne.id = 'yt-oneclick';
|
||||
btnOne.id = 'yun-xue-tang-oneclick';
|
||||
btnOne.textContent = '一键刷课';
|
||||
btnOne.style.cssText = [
|
||||
'width:100%', 'margin:2px 0 6px', 'padding:5px 8px', 'cursor:pointer',
|
||||
@@ -130,10 +120,10 @@ export function buildPanel() {
|
||||
return;
|
||||
}
|
||||
// 只有播放页的按钮才是「停止」;列表页/门户页点它一律是开始/继续,避免误停
|
||||
if (route() === 'course' && S.current && S.running) {
|
||||
S.running = false;
|
||||
save();
|
||||
setStatus('自动刷课已暂停');
|
||||
if (route() === 'course' && S.activeCourse && S.batchRunning) {
|
||||
S.batchRunning = false;
|
||||
saveRunState();
|
||||
setStatus('列表刷课已暂停');
|
||||
} else {
|
||||
startBatch();
|
||||
}
|
||||
@@ -141,7 +131,7 @@ export function buildPanel() {
|
||||
});
|
||||
|
||||
loginBox = document.createElement('div');
|
||||
loginBox.id = 'yt-login-box';
|
||||
loginBox.id = 'yun-xue-tang-login-box';
|
||||
loginBox.style.cssText = 'display:none;margin-bottom:6px;';
|
||||
|
||||
const mkInput = function (id, type, ph) {
|
||||
@@ -157,8 +147,8 @@ export function buildPanel() {
|
||||
].join(';');
|
||||
return el;
|
||||
};
|
||||
loginUserEl = mkInput('yt-login-user', 'text', '员工邮箱/账号');
|
||||
loginPassEl = mkInput('yt-login-pass', 'password', '密码');
|
||||
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');
|
||||
@@ -170,9 +160,9 @@ export function buildPanel() {
|
||||
label.appendChild(document.createTextNode(text));
|
||||
return { label: label, cb: cb };
|
||||
};
|
||||
const rem = mkCheck('yt-login-remember', '记住密码');
|
||||
const rem = mkCheck('yun-xue-tang-login-remember', '记住密码');
|
||||
loginRememberEl = rem.cb;
|
||||
const auto = mkCheck('yt-login-auto', '自动登录');
|
||||
const auto = mkCheck('yun-xue-tang-login-auto', '自动登录');
|
||||
loginAutoEl = auto.cb;
|
||||
loginRememberEl.addEventListener('change', function () {
|
||||
if (!loginRememberEl.checked) clearSavedCreds();
|
||||
@@ -211,46 +201,46 @@ export function buildPanel() {
|
||||
labelAuto.style.cssText = 'display:flex;align-items:center;gap:6px;cursor:pointer;';
|
||||
cbAuto = document.createElement('input');
|
||||
cbAuto.type = 'checkbox';
|
||||
cbAuto.id = 'yt-auto-enabled';
|
||||
cbAuto.checked = state.enabled;
|
||||
cbAuto.id = 'yun-xue-tang-auto-enabled';
|
||||
cbAuto.checked = state.autoPlayEnabled;
|
||||
cbAuto.addEventListener('change', function () {
|
||||
state.enabled = cbAuto.checked;
|
||||
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('手动课程自动连播'));
|
||||
labelAuto.appendChild(document.createTextNode('当前课程自动连播'));
|
||||
|
||||
labelBatch = document.createElement('label');
|
||||
labelBatch.style.cssText = LABEL_CSS;
|
||||
cbBatch = document.createElement('input');
|
||||
cbBatch.type = 'checkbox';
|
||||
cbBatch.id = 'yt-batch-enabled';
|
||||
cbBatch.checked = S.running;
|
||||
cbBatch.id = 'yun-xue-tang-batch-enabled';
|
||||
cbBatch.checked = S.batchRunning;
|
||||
cbBatch.addEventListener('change', function () {
|
||||
if (cbBatch.checked) {
|
||||
startBatch();
|
||||
} else {
|
||||
S.running = false;
|
||||
save();
|
||||
setStatus('自动刷课已暂停');
|
||||
S.batchRunning = false;
|
||||
saveRunState();
|
||||
setStatus('列表刷课已暂停');
|
||||
}
|
||||
updatePanel();
|
||||
});
|
||||
labelBatch.appendChild(cbBatch);
|
||||
labelBatch.appendChild(document.createTextNode('自动刷课(批量)'));
|
||||
labelBatch.appendChild(document.createTextNode('课程列表自动刷课'));
|
||||
|
||||
labelShort = document.createElement('label');
|
||||
labelShort.style.cssText = LABEL_CSS;
|
||||
cbPreferShort = document.createElement('input');
|
||||
cbPreferShort.type = 'checkbox';
|
||||
cbPreferShort.id = 'yt-prefer-short';
|
||||
cbPreferShort.checked = state.preferShort;
|
||||
cbPreferShort.id = 'yun-xue-tang-prefer-short';
|
||||
cbPreferShort.checked = state.preferShortCourses;
|
||||
cbPreferShort.title = '按课程总时长从短到长选课';
|
||||
cbPreferShort.addEventListener('change', function () {
|
||||
state.preferShort = cbPreferShort.checked;
|
||||
try { localStorage.setItem(LS_PREFER_SHORT, state.preferShort ? '1' : '0'); } catch (e) {}
|
||||
if (!state.preferShort) {
|
||||
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;
|
||||
@@ -266,41 +256,20 @@ export function buildPanel() {
|
||||
labelShort.appendChild(document.createTextNode('优先短课程(时长正序)'));
|
||||
|
||||
statusEl = document.createElement('div');
|
||||
statusEl.id = 'yt-status';
|
||||
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 = 'yt-stats';
|
||||
statsEl.id = 'yun-xue-tang-stats';
|
||||
statsEl.style.cssText = 'margin-top:2px;color:#aaa;';
|
||||
|
||||
btnSkip = document.createElement('button');
|
||||
btnSkip.type = 'button';
|
||||
btnSkip.textContent = '跳过本课';
|
||||
btnSkip.style.cssText = smallBtnCss('none');
|
||||
btnSkip.addEventListener('click', function () {
|
||||
if (S.current) failCurrent('手动跳过');
|
||||
});
|
||||
|
||||
const clearFail = document.createElement('button');
|
||||
clearFail.type = 'button';
|
||||
clearFail.textContent = '清除失败记录';
|
||||
clearFail.style.cssText = smallBtnCss('inline-block');
|
||||
clearFail.addEventListener('click', function () {
|
||||
S.failed = {};
|
||||
S.consecutiveFailures = 0;
|
||||
S.runFinished = false;
|
||||
save();
|
||||
updatePanel();
|
||||
setStatus('已清除失败记录');
|
||||
});
|
||||
|
||||
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 = 'yt-session-duration';
|
||||
footer.id = 'yun-xue-tang-session-duration';
|
||||
footer.textContent = '会话时长 ' + formatElapsed(0);
|
||||
footer.style.cssText = 'margin-top:4px;color:#8ee6c0;font-size:11px;';
|
||||
footerEl = footer;
|
||||
@@ -313,8 +282,6 @@ export function buildPanel() {
|
||||
box.appendChild(labelShort);
|
||||
box.appendChild(statusEl);
|
||||
box.appendChild(statsEl);
|
||||
box.appendChild(btnSkip);
|
||||
box.appendChild(clearFail);
|
||||
box.appendChild(hint);
|
||||
box.appendChild(footer);
|
||||
document.documentElement.appendChild(box);
|
||||
|
||||
+26
-10
@@ -16,7 +16,7 @@ export function applyMute(v) {
|
||||
|
||||
export function playVideo(v) {
|
||||
if (!v) return;
|
||||
if (state.enabled || S.running) {
|
||||
if (state.autoPlayEnabled || S.batchRunning) {
|
||||
try {
|
||||
const p = v.play();
|
||||
if (p && typeof p.catch === 'function') p.catch(() => {});
|
||||
@@ -26,10 +26,10 @@ export function playVideo(v) {
|
||||
|
||||
export function hookVideo(v) {
|
||||
if (!v) return;
|
||||
if (v.getAttribute && v.getAttribute('data-yt-hooked') === '1') 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-yt-hooked', '1'); } catch (e) {}
|
||||
try { v.setAttribute('data-yun-xue-tang-hooked', '1'); } catch (e) {}
|
||||
|
||||
applyMute(v);
|
||||
|
||||
@@ -70,7 +70,7 @@ export function findPlayableVideo() {
|
||||
export function ensurePlaying(v) {
|
||||
if (!v) return;
|
||||
applyMute(v);
|
||||
if (S.current) {
|
||||
if (S.activeCourse) {
|
||||
try {
|
||||
if (Math.abs(v.playbackRate - 1) > 0.01) v.playbackRate = 1;
|
||||
} catch (e) { /* ignore */ }
|
||||
@@ -360,14 +360,30 @@ export function findNextButton() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 目录里的考试课时(.tag-type 文案为「考试」)。考试不再跳过,而是自动进考试空卷交卷,
|
||||
// 所以单独提供 finder 给课程页调用。
|
||||
export function examLessonElements() {
|
||||
return lessonItems().filter(function (li) {
|
||||
const tag = li.querySelector('.tag-type');
|
||||
return !!tag && /考试/.test(textOf(tag));
|
||||
});
|
||||
}
|
||||
|
||||
// 第一个还没完成的考试课时
|
||||
export function findPendingExamLesson() {
|
||||
return examLessonElements().find(function (li) { return !isLessonCompleted(li); }) || null;
|
||||
}
|
||||
|
||||
// 课程是否包含「答题/测验/问卷」类章节(这类仍需人工,考试已改为自动交卷)
|
||||
export function courseHasQuizLesson() {
|
||||
// 没有标签课时,some() 本身就返回 false,不必先判 length
|
||||
return [...document.querySelectorAll('.yxtulcdsdk-catalog ul > li .tag-type')]
|
||||
.some(function (t) { return /考试|测验|问卷|答题/.test(textOf(t)); });
|
||||
.some(function (t) { return /答题|测验|问卷/.test(textOf(t)); });
|
||||
}
|
||||
|
||||
export function detectQuiz() {
|
||||
const pat = /^(开始答题|继续答题|提交答案|提交试卷|开始考试)$/;
|
||||
// 「开始考试/继续考试」由 exam.js 单独接管(自动空卷交卷),这里只留需要人工的答题类
|
||||
const pat = /^(开始答题|继续答题|提交答案|提交试卷)$/;
|
||||
for (const doc of collectDocuments()) {
|
||||
let els;
|
||||
try {
|
||||
@@ -383,7 +399,7 @@ export function detectQuiz() {
|
||||
for (const d of dialogs) {
|
||||
if (!isVisible(d)) continue;
|
||||
const t = textOf(d);
|
||||
if (/开始考试|提交试卷|开始答题/.test(t)) return true;
|
||||
if (/开始答题|提交试卷/.test(t)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -456,8 +472,8 @@ export function handleAntiIdle() {
|
||||
const btn = findAntiIdleButton(dialog);
|
||||
if (!btn) {
|
||||
if (antiIdleNeedsHuman(dialog)) {
|
||||
setStatus('防挂机验证需要人工完成(滑块/拼图)');
|
||||
failCurrent('防挂机验证需要人工完成');
|
||||
setStatus('防挂机验证需要人工完成(滑块/拼图),本课稍后重试');
|
||||
failCurrent('防挂机验证需要人工完成(滑块/拼图)');
|
||||
} else {
|
||||
setStatus('检测到防挂机验证,未找到「继续学习」按钮');
|
||||
}
|
||||
@@ -571,7 +587,7 @@ export function alignToFirstIncomplete() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 手动模式没有 S.current,用课程标题判断是否换了一门课,换课时重新对齐
|
||||
// 手动模式没有 S.activeCourse,用课程标题判断是否换了一门课,换课时重新对齐
|
||||
export function syncManualCourse() {
|
||||
const key = courseTitle() || location.href;
|
||||
if (R.manualCourseKey === key) return true;
|
||||
|
||||
+7
-4
@@ -1,5 +1,5 @@
|
||||
// ======== 路由 ========
|
||||
import { R, S, save } from './state.js';
|
||||
import { R, S, saveRunState } from './state.js';
|
||||
|
||||
// 平台不同内容类型进入的播放页不同:
|
||||
// 多课时课程 #/course/play?kngId=… 单个视频 #/video/play?kngId=…
|
||||
@@ -20,13 +20,16 @@ export function mediaPage() {
|
||||
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || '');
|
||||
}
|
||||
|
||||
// 回列表页。
|
||||
// catalogUrl 决定「刷的是哪个目录」——它同时也是短课程队列的缓存键来源,
|
||||
// 用错目录会把队列建在另一批课程上,所以这里优先用它而不是裸的 /kng/#/list。
|
||||
export function goToList(force) {
|
||||
if (!force && Date.now() - R.lastGoListAt < 5000) return;
|
||||
R.lastGoListAt = Date.now();
|
||||
const url = S.listUrl || location.origin + '/kng/#/list';
|
||||
const url = S.catalogUrl || location.origin + '/kng/#/list';
|
||||
if (route() === 'list') {
|
||||
S.returning = true;
|
||||
save();
|
||||
S.awaitingListReturn = true;
|
||||
saveRunState();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
+202
-27
@@ -1,47 +1,188 @@
|
||||
// ======== 状态 ========
|
||||
import { CFG, LS_ENABLED, LS_PREFER_SHORT, LS_BATCH } from './config.js';
|
||||
//
|
||||
// 状态分三层,持久化位置按「这条信息跨会话是否还成立」来分:
|
||||
//
|
||||
// 用户偏好(localStorage) —— state / targetCatalogUrl:跨会话、跨标签页都成立
|
||||
// 本次运行状态(sessionStorage)—— S:整页跳转要活,换标签页/重启浏览器即作废
|
||||
// 纯内存(R) —— 运行时计数器、节流时间戳:丢了自愈
|
||||
//
|
||||
// 关键约定:S.batchRunning(是否正在刷课)属于「用户/运行器的授权意图」,
|
||||
// 只活在本标签页内。这样浏览器重启、运行器重建标签页之后都必然是待机状态,
|
||||
// 必须由 runner/session.mjs 或面板显式重新开跑,不会出现「还没登录就开始刷课」。
|
||||
import {
|
||||
CFG, LS_ENABLED, LS_PREFER_SHORT, LS_TARGET_CATALOG_URL,
|
||||
SS_RUN_STATE, SS_SHORT_CATALOG, LEGACY_LS_BATCH,
|
||||
} from './config.js';
|
||||
|
||||
// ======== 用户偏好(localStorage) ========
|
||||
export const state = {
|
||||
enabled: true, // 手动打开的课程:自动连播
|
||||
preferShort: CFG.preferShortCourses, // 批量选课:优先时长短的课程(正序)
|
||||
autoPlayEnabled: true, // 当前课程自动连播(自己点开的课)
|
||||
preferShortCourses: CFG.preferShortCourses, // 列表刷课时优先后时长更短的课程(正序)
|
||||
};
|
||||
try {
|
||||
state.enabled = localStorage.getItem(LS_ENABLED) !== '0';
|
||||
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== '0';
|
||||
} catch (e) { /* ignore */ }
|
||||
try {
|
||||
const v = localStorage.getItem(LS_PREFER_SHORT);
|
||||
if (v === '0' || v === '1') state.preferShort = v === '1';
|
||||
if (v === '0' || v === '1') state.preferShortCourses = v === '1';
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
export function defaultBatch() {
|
||||
// ======== 本次运行状态(sessionStorage) ========
|
||||
export const PHASE_ENTERING = 'entering';
|
||||
export const PHASE_LEARNING = 'learning';
|
||||
export const PHASE_IDLE = 'idle';
|
||||
const VALID_PHASES = new Set([PHASE_IDLE, PHASE_ENTERING, PHASE_LEARNING]);
|
||||
|
||||
export function defaultRunState() {
|
||||
return {
|
||||
running: false,
|
||||
runFinished: false,
|
||||
completedThisRun: 0,
|
||||
consecutiveFailures: 0,
|
||||
listUrl: '',
|
||||
listPage: 1,
|
||||
current: null, // { title, id, status, startedAt, page, duration }
|
||||
returning: false,
|
||||
phase: 'idle', // idle | entering | learning
|
||||
done: {}, // title -> timestamp
|
||||
failed: {}, // title -> { reason, at }
|
||||
// ---- 运行意图 ----
|
||||
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 -> 空卷交卷次数(防死循环)
|
||||
};
|
||||
}
|
||||
|
||||
export let S = defaultBatch();
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_BATCH);
|
||||
if (raw) S = Object.assign(defaultBatch(), JSON.parse(raw));
|
||||
} catch (e) { /* ignore */ }
|
||||
export const S = defaultRunState();
|
||||
|
||||
export function save() {
|
||||
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;
|
||||
|
||||
// ---- 当前课程 ----
|
||||
// learning 阶段:说明是同一标签页内的整页跳转(sessionStorage 跨跳转存活、跨标签页不存活),
|
||||
// 所以「多年前开始学的课」也是真实的,必须接续,不能用时间戳判过期。
|
||||
// entering 阶段:「正在进课」超过 15 秒就会被 failCurrent,若是重启/长时间挂起后
|
||||
// 恢复一个很旧的 startedAt,只会让 course.js 的进课宽限期立刻判过期,把正常加载
|
||||
// 误判成「课程不一致」—— 所以只有这一段才用 staleCourseMs 守门。
|
||||
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;
|
||||
}
|
||||
// 「正在回列表途中」不依赖当前课程:completeCurrent / failCurrent 会先清课程
|
||||
// 再跳回列表,若把它一起丢掉,新页面就不知道需要恢复页码。
|
||||
out.awaitingListReturn = obj.awaitingListReturn === true;
|
||||
|
||||
// ---- 本轮记录 ----
|
||||
out.completedTitles = asMap(obj.completedTitles);
|
||||
out.courseRetries = asMap(obj.courseRetries);
|
||||
out.examEmptySubmits = asMap(obj.examEmptySubmits);
|
||||
return out;
|
||||
}
|
||||
|
||||
// 旧版 localStorage 里的整块状态(yun-xue-tang-batch-v2):只挑「进度」迁移,
|
||||
// 运行意图、当前课程一律不接续。迁移完即删除,避免旧数据一直复活。
|
||||
function migrateLegacy() {
|
||||
let raw = null;
|
||||
try { raw = localStorage.getItem(LEGACY_LS_BATCH); } catch (e) { return; }
|
||||
if (!raw) return;
|
||||
try {
|
||||
localStorage.setItem(LS_BATCH, JSON.stringify(S));
|
||||
const old = JSON.parse(raw);
|
||||
if (old && typeof old === 'object') {
|
||||
const done = asMap(old.done);
|
||||
// 清掉一眼过期的完成记录(超过 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) { /* ignore */ }
|
||||
try { localStorage.removeItem(LEGACY_LS_BATCH); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
(function restore() {
|
||||
let restored = null;
|
||||
try {
|
||||
const raw = sessionStorage.getItem(SS_RUN_STATE);
|
||||
if (raw) restored = restoreFrom(JSON.parse(raw));
|
||||
} catch (e) { /* ignore */ }
|
||||
if (restored) Object.assign(S, restored);
|
||||
// 目标目录是偏好:localStorage 里的值优先,会话里没有就沿用会话内的
|
||||
S.catalogUrl = readTargetCatalogUrl() || S.catalogUrl;
|
||||
migrateLegacy();
|
||||
})();
|
||||
|
||||
// 上次写盘的快照:内容没变就不重复序列化+写入
|
||||
let lastWritten = '';
|
||||
|
||||
export function saveRunState() {
|
||||
try {
|
||||
const text = JSON.stringify(S);
|
||||
if (text === lastWritten) return;
|
||||
lastWritten = text;
|
||||
sessionStorage.setItem(SS_RUN_STATE, text);
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// 运行时状态(不持久化)
|
||||
// 收尾/退出前强制落盘(内容没变也会写,防止 lastWritten 与实际不同步)
|
||||
export function flushRunState() {
|
||||
lastWritten = '';
|
||||
saveRunState();
|
||||
}
|
||||
|
||||
// ======== 目标目录 URL(偏好,localStorage + 会话镜像) ========
|
||||
export function readTargetCatalogUrl() {
|
||||
try { return localStorage.getItem(LS_TARGET_CATALOG_URL) || ''; } catch (e) { return ''; }
|
||||
}
|
||||
|
||||
export 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) { /* ignore */ }
|
||||
if (changed && !(opt && opt.silent)) saveRunState();
|
||||
}
|
||||
|
||||
// ======== 运行时状态(纯内存,不持久化) ========
|
||||
export const R = {
|
||||
hooked: new WeakSet(),
|
||||
lastCardClickAt: 0,
|
||||
@@ -63,6 +204,17 @@ export const R = {
|
||||
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,
|
||||
@@ -74,7 +226,9 @@ export const R = {
|
||||
idleDialogText: '',
|
||||
idleDialogClicks: 0,
|
||||
idleGaveUp: false,
|
||||
restoreAttempts: 0,
|
||||
pageRestoreAttempts: 0,
|
||||
retryWaitUntil: 0, // 重试退避的结束时间(未到点不进课)
|
||||
retryTitle: '', // 正在等待重试的课程名(面板提示用)
|
||||
loginFilled: false,
|
||||
loginSubmittingAt: 0,
|
||||
loginAutoTried: false,
|
||||
@@ -88,8 +242,20 @@ export const R = {
|
||||
shortJumpAt: 0,
|
||||
shortNoVmSince: 0,
|
||||
shortWarnedAt: 0,
|
||||
retryStatusSec: -1, // 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
|
||||
};
|
||||
|
||||
// 丢掉时长队列缓存:下一次选课会重新调列表接口,拿平台实时的
|
||||
// 未学完/已完成状态,而不是用本地旧快照。
|
||||
// 放在 state.js 而不是 list.js,是为了避开 complete.js <-> list.js 的循环引用。
|
||||
export function invalidateShortCatalog() {
|
||||
R.shortCatalog = null;
|
||||
R.shortCatalogLoading = false;
|
||||
R.shortCatalogFailedAt = 0;
|
||||
R.shortNoVmSince = 0;
|
||||
try { sessionStorage.removeItem(SS_SHORT_CATALOG); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
export function resetCourseRuntime() {
|
||||
R.lastLessonKey = '';
|
||||
R.doneLatchKey = '';
|
||||
@@ -100,6 +266,15 @@ export function resetCourseRuntime() {
|
||||
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;
|
||||
// 注意:examLessonAt / examLessonTries 不在这里清。交卷后 backToCourse() 会重进同一门课,
|
||||
// 若清掉冷却就会立即重复点考试节,形成循环。它们在下一次 init() 进入新课时自然重置。
|
||||
R.initialLessonChecked = false;
|
||||
R.phaseSince = 0;
|
||||
R.alignTries = 0;
|
||||
@@ -107,6 +282,6 @@ export function resetCourseRuntime() {
|
||||
R.alignFailed = false;
|
||||
R.manualCourseKey = '';
|
||||
R.lastAdvanceAt = 0;
|
||||
R.restoreAttempts = 0;
|
||||
R.pageRestoreAttempts = 0;
|
||||
R.entryRetries = 0;
|
||||
}
|
||||
@@ -54,6 +54,15 @@ export function courseIdFromUrl() {
|
||||
try { return decodeURIComponent(m[1]); } catch (e) { return m[1]; }
|
||||
}
|
||||
|
||||
// 课程标题的「占位文案」:SPA 切换时页面标题会短暂变成这些通用词。
|
||||
// 用它区分「真的课程名」和「还没加载出来的兜底文案」,避免把兜底文案
|
||||
// 当成课程名写进 done/failed 记录(否则下次会重复进入同一门课)。
|
||||
const GENERIC_TITLE_RE = /^(loading|加载中|在线课堂|云课堂|云学堂|江丰云课堂|课程详情|课程|首页|我的学习)$/i;
|
||||
|
||||
export function isGenericCourseTitle(t) {
|
||||
return !norm(t) || GENERIC_TITLE_RE.test(norm(t));
|
||||
}
|
||||
|
||||
export function collectDocuments(win, out) {
|
||||
win = win || window;
|
||||
out = out || [];
|
||||
|
||||
Reference in new issue
Block a user