refactor: 拆分 src/ 模块并接入 esbuild 构建
把单文件脚本拆成 src/ 下 13 个 ES 模块,用 esbuild 打回同名 .user.js, 产物文件名不变,dev/ 热加载链路无需改动。 - build.mjs:esbuild 打包(--watch / --minify),版本号只从 package.json 读取,同时替换 meta.js 的 @version 与 config.js 的 VERSION - 统一版本号来源,消除 package.json / meta.js / config.js 三处手写 - 补回 'use strict'(esbuild IIFE 默认不带,属真实行为回归) - 清理重复实现:pauseAllMedia、listData、shortQuery、drain、clearPending、 cbAuto 模块级引用、共用 cssText - 去掉搬代码时残留的 IIFE 缩进、死字段、二次兜底默认值、过期注释 - README / dev/README 同步构建流程与目录结构 行为无变化,仅 src/config.js 的 CFG 改成构建期注入版本号。
This commit is contained in:
1 parent
8200bfa0c5
commit
8193326b70
19 files changed
+4884
-1671
No files matched your search
@@ -0,0 +1,73 @@
|
||||
// ======== 完成 / 失败 ========
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { goToList } from './route.js';
|
||||
import { later } from './lifecycle.js';
|
||||
import { truncate } from './utils.js';
|
||||
import { setStatus, updatePanel } from './panel.js';
|
||||
import { courseTitle, pauseAllMedia } from './player.js';
|
||||
import { forgetShortCourse } from './list.js';
|
||||
|
||||
export function completeCurrent() {
|
||||
const title = S.current ? S.current.title : courseTitle();
|
||||
if (title) {
|
||||
S.done[title] = Date.now();
|
||||
forgetShortCourse(title);
|
||||
}
|
||||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||||
S.consecutiveFailures = 0;
|
||||
S.current = null;
|
||||
S.phase = 'idle';
|
||||
S.returning = true;
|
||||
save();
|
||||
R.doneLatchKey = '';
|
||||
R.lastSummary = null;
|
||||
// 平台在完成后会把播放器重置到 0 秒,先暂停,避免又从头播一遍
|
||||
pauseAllMedia();
|
||||
|
||||
console.log(TAG, '课程完成:', title, '第', S.completedThisRun, '门,返回列表选下一门');
|
||||
|
||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : Infinity;
|
||||
if (S.completedThisRun >= limit) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
save();
|
||||
setStatus('本次已完成 ' + S.completedThisRun + ' 门,已停止。可重新勾选开始新一轮。');
|
||||
} else {
|
||||
setStatus('课程完成:' + truncate(title, 26) + '(本次 ' + S.completedThisRun + ')');
|
||||
}
|
||||
// 完成后的返回列表不能被 5 秒节流吞掉
|
||||
later(function () { goToList(true); }, 1200);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (S.consecutiveFailures >= CFG.maxConsecutiveFailures) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
setStatus('连续失败 ' + S.consecutiveFailures + ' 门,已暂停:' + reason);
|
||||
save();
|
||||
return;
|
||||
}
|
||||
|
||||
save();
|
||||
setStatus('跳过:' + truncate(title, 24) + '(' + reason + ')');
|
||||
later(function () { goToList(true); }, 1000);
|
||||
}
|
||||
|
||||
export function stopBatch(reason) {
|
||||
S.running = false;
|
||||
S.runFinished = true;
|
||||
save();
|
||||
setStatus(reason || '批量任务结束');
|
||||
updatePanel();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// ======== 配置 ========
|
||||
export const CFG = {
|
||||
mute: true, // 静音(自动播放更稳)
|
||||
autoNext: true, // 手动打开课程时,本节结束后自动下一节
|
||||
tickMs: 2000, // 主循环间隔
|
||||
startClickCooldownMs: 3000, // 「开始学习」重复点击冷却(3 秒内没起播就补点)
|
||||
entryGraceMs: 30000, // 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」
|
||||
stuckMs: 5 * 60 * 1000, // 连续多久没有计时进展就放弃当前课程
|
||||
maxCourses: 10, // 本次最多完成多少门;0 = 不限
|
||||
maxConsecutiveFailures: 5, // 连续失败多少门后自动停止
|
||||
alignToFirstIncomplete: true, // 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置
|
||||
preferShortCourses: true, // 批量选课时优先总时长更短的课程(正序)
|
||||
};
|
||||
|
||||
// 版本号:由 build.mjs 从 package.json 注入,不要手改
|
||||
export const VERSION = __YT_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';
|
||||
export const SHORT_CATALOG_TTL = 5 * 60 * 1000;
|
||||
export const PANEL_ID = 'yt-auto-panel';
|
||||
export const TAG = '[云学堂助手]';
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
// ======== 课程页 ========
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { goToList, mediaPage } from './route.js';
|
||||
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
|
||||
import { later } from './lifecycle.js';
|
||||
import { setStatus, statusEl } from './panel.js';
|
||||
import {
|
||||
alignToFirstIncomplete, courseHasQuizLesson, detectQuiz, handleAntiIdle, courseTitle,
|
||||
hookAllVideos, findPlayableVideo, ensurePlaying, readSummary, readCountdown,
|
||||
readActiveLessonKey, findNextLessonElement, findNextButton, clickNode,
|
||||
fireClickSequence, lessonClickNodes, syncManualCourse, pauseAllMedia,
|
||||
} from './player.js';
|
||||
import { completeCurrent, failCurrent } from './complete.js';
|
||||
|
||||
export function courseTick() {
|
||||
R.listWithCurrentSince = 0;
|
||||
if (!S.current) {
|
||||
goToList();
|
||||
return;
|
||||
}
|
||||
|
||||
// 播放器可能是点「开始学习」后才创建的;每轮顺带接管一次,
|
||||
// 新视频一出现就静音并挂上 play/ended/timeupdate 监听。
|
||||
hookAllVideos();
|
||||
|
||||
const isMedia = mediaPage();
|
||||
const urlId = courseIdFromUrl();
|
||||
const curId = S.current.id || '';
|
||||
const title = courseTitle();
|
||||
const nt = norm(title);
|
||||
const nc = norm(S.current.title);
|
||||
const genericTitle = !nt || /^(loading|加载中|在线课堂|江丰云课堂|云课堂|课程详情|课程)$/.test(nt);
|
||||
const titleSame = genericTitle || !nc || nt === nc ||
|
||||
nt.indexOf(nc) >= 0 || nc.indexOf(nt) >= 0;
|
||||
// 有了 URL 里的 kngId 就以 id 为准:标题在 SPA 切页时经常短暂是 loading/
|
||||
// 在线课堂,旧逻辑会把它当成「课程不一致」在 12 秒后把课退回列表。
|
||||
const idKnown = !!(urlId && curId);
|
||||
const sameCourse = idKnown ? urlId === curId : titleSame;
|
||||
const graceOver = Date.now() - (S.current.startedAt || 0) > CFG.entryGraceMs;
|
||||
if (!sameCourse) {
|
||||
if (graceOver) {
|
||||
console.warn(TAG, '页面课程与队列不一致:队列', nc, curId,
|
||||
'页面', nt, urlId, location.href);
|
||||
failCurrent('页面课程与队列不一致');
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (S.phase !== 'learning') {
|
||||
S.phase = 'learning';
|
||||
save();
|
||||
}
|
||||
|
||||
// #/scan 只是进课过渡页:此时页面组件里可能还残留上一门课的汇总,
|
||||
// 等路由切到真正的播放页再判断,避免把旧课程的「已完成学习」当成新课程完成。
|
||||
if ((location.hash || '').indexOf('#/scan') === 0) return;
|
||||
|
||||
// 1) 防挂机验证(每 10 分钟弹一次,120 秒内不点「继续学习」就停止计时)
|
||||
if (handleAntiIdle()) return;
|
||||
|
||||
// 2) 答题/考试检测
|
||||
if (detectQuiz()) {
|
||||
failCurrent('检测到答题/考试,需要手动处理');
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) 课程是否包含考试/测验类章节(只需检查一次)
|
||||
if (!R.quizChecked && document.querySelector('.yxtulcdsdk-catalog ul > li .tag-type')) {
|
||||
R.quizChecked = true;
|
||||
if (courseHasQuizLesson()) {
|
||||
failCurrent('课程包含考试/测验章节');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 4) 整门课程是否已完成 / 平台是否刚记录了一节
|
||||
const summary = readSummary();
|
||||
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
|
||||
if (summary) {
|
||||
// 三种完成文案统一走这里:x/y 满、百分比 100%、「已完成学习」。
|
||||
// 页面切换瞬间可能读到上一门课的残留文案,连续两次读到才确认。
|
||||
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;
|
||||
}
|
||||
|
||||
// 5) 对齐起点:进入课程后统一从「第一个未学完的课时」开始(即第一章第一节起顺序学),
|
||||
// 不沿用平台上次停留的位置。否则前面的课时会被跳过,整门课永远学不完。
|
||||
// 单视频/音频页没有目录,不走这一步。
|
||||
if (!isMedia && alignToFirstIncomplete()) return;
|
||||
|
||||
// 6) 计时与当前章节
|
||||
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 ? '(起点未对齐)' : ''));
|
||||
}
|
||||
|
||||
// 7) 本节是否已在本地结束(必须先判断,避免把已结束的视频重新拉回开头)
|
||||
const v = findPlayableVideo();
|
||||
// 视频 ended 是本节结束的主信号;倒计时文案在切节后可能变成下一节的时长。
|
||||
// doneLatchKey 用来记住「这节已经播完」:平台在完成后会把播放器重置到 0 秒,
|
||||
// video.ended 变回 false、倒计时也消失,若只看即时状态就会把视频从头重播。
|
||||
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);
|
||||
|
||||
// 8) 播放器
|
||||
if (!localDone) {
|
||||
if (v) {
|
||||
ensurePlaying(v);
|
||||
const want = '学习中:' + truncate(lessonKey || S.current.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) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 9) 标记等待平台记录
|
||||
if (!localDone) {
|
||||
R.waitStart = 0;
|
||||
} else if (!R.waitStart) {
|
||||
R.waitStart = Date.now();
|
||||
R.waitSummaryX = prevSummaryX;
|
||||
R.waitLessonKey = lessonKey;
|
||||
setStatus(isMedia ? '课程已播完,等待平台记录…' : '本节结束,等待平台记录…');
|
||||
}
|
||||
|
||||
// 10) 等待平台记录本节完成
|
||||
if (R.waitStart) {
|
||||
const newKey = readActiveLessonKey();
|
||||
const s2 = readSummary();
|
||||
|
||||
// 整门课已完成(含「已完成学习」/百分比 100%)
|
||||
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 > 30000) {
|
||||
if (isMedia) {
|
||||
// 单视频/音频:平台记账有延迟,继续等,不能把已播完的视频再拉回 0 秒
|
||||
R.waitStart = Date.now();
|
||||
setStatus('课程已播完,等待平台完成记录…');
|
||||
} else {
|
||||
R.waitStart = 0;
|
||||
setStatus('平台未更新进度,尝试下一节…');
|
||||
advanceLesson();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 11) 长时间无进展 → 放弃
|
||||
if (Date.now() - R.lastProgressAt > CFG.stuckMs) {
|
||||
failCurrent('长时间没有计时进展');
|
||||
}
|
||||
}
|
||||
|
||||
// 自动切下一节:先点标题(事件会冒泡到行容器 / li 上的句柄),
|
||||
// 平台没反应时再依次补点行容器、li、状态图标;每一步都先确认目标课时还没
|
||||
// 变成当前课时,避免平台自己已经切过去之后又被点回来。
|
||||
export 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: 1000, 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);
|
||||
}
|
||||
}
|
||||
|
||||
export function advanceLesson() {
|
||||
if (Date.now() - R.lastAdvanceAt < 5000) 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('没有找到下一节,等待课程完成…');
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 手动课程自动连播 ========
|
||||
export function manualCourseTick() {
|
||||
hookAllVideos();
|
||||
if (handleAntiIdle()) return;
|
||||
|
||||
// 课程标题就绪前不做任何判断,避免在旧课程的目录上点来点去
|
||||
const title = courseTitle();
|
||||
if (!title || /^(loading|加载中)/i.test(title)) return;
|
||||
|
||||
// 手动进入课程时同样先对齐到「第一个未学完的课时」;每门课只对齐一次,
|
||||
// 之后用户自己点别的课时不会被拉回来
|
||||
syncManualCourse();
|
||||
if (!mediaPage() && alignToFirstIncomplete()) return;
|
||||
|
||||
const lessonKey = readActiveLessonKey();
|
||||
if (lessonKey && lessonKey !== R.lastLessonKey) {
|
||||
R.lastLessonKey = lessonKey;
|
||||
R.doneLatchKey = '';
|
||||
setStatus('学习中:' + truncate(lessonKey, 28));
|
||||
}
|
||||
|
||||
// 整门课已完成(平台汇总会变成「已完成学习」/100%):停在这里,别再重播
|
||||
const summary = readSummary();
|
||||
if (summary && summary.complete) {
|
||||
pauseAllMedia();
|
||||
setStatus('课程已完成:' + truncate(S.current ? S.current.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 > 6000) {
|
||||
R.manualAdvanceAt = Date.now();
|
||||
const next = findNextLessonElement();
|
||||
if (next) {
|
||||
switchLesson(next);
|
||||
} else {
|
||||
const btn = findNextButton();
|
||||
if (btn) clickNode(btn);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ensurePlaying(v);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// ======== 主循环 ========
|
||||
'use strict';
|
||||
import { CFG, VERSION, TAG } from './config.js';
|
||||
import { R, S, state, save } 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 {
|
||||
listTick, listVm, shortCatalogKey, courseIdOfCard, ensureShortCatalog,
|
||||
chooseShortCourse, sortCardsByDuration, formatDuration,
|
||||
pendingShortItems, forgetShortCourse,
|
||||
} from './list.js';
|
||||
import { courseTick, manualCourseTick } from './course.js';
|
||||
import {
|
||||
hookAllVideos, readSummary, readCountdown, lessonItems,
|
||||
findNextLessonElement, clickLesson, alignToFirstIncomplete,
|
||||
isLessonCompleted, findFirstIncompleteLessonElement, dumpCatalog,
|
||||
} from './player.js';
|
||||
|
||||
function tick() {
|
||||
try {
|
||||
if (window.top !== window.self) return;
|
||||
ensurePanel();
|
||||
if (isLoginPage()) loginPageTick();
|
||||
if (consumePendingStart()) return;
|
||||
|
||||
if (!S.running) {
|
||||
if (route() === 'course' && state.enabled) {
|
||||
manualCourseTick();
|
||||
} else {
|
||||
R.manualCourseKey = ''; // 离开课程页后,下次进入同一门课要重新对齐
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const r = route();
|
||||
if (r === 'list') {
|
||||
listTick();
|
||||
} else if (r === 'course') {
|
||||
courseTick();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(TAG, e);
|
||||
}
|
||||
}
|
||||
|
||||
// 把主循环回填给 login.startBatch(它在点击「一键刷课」后需要立即 tick 一次)
|
||||
setTick(tick);
|
||||
|
||||
// iframe 内只负责接管视频
|
||||
if (window.top !== window.self) {
|
||||
every(function () {
|
||||
try { hookAllVideos(); } catch (e) {}
|
||||
}, CFG.tickMs);
|
||||
} else {
|
||||
ensurePanel();
|
||||
hookAllVideos();
|
||||
every(tick, CFG.tickMs);
|
||||
onWindow(window, 'hashchange', function () {
|
||||
later(tick, 300);
|
||||
});
|
||||
}
|
||||
|
||||
// 调试入口(仅本地使用,可在控制台查看状态)
|
||||
try {
|
||||
Object.defineProperty(window, '__ytAuto', {
|
||||
value: {
|
||||
S, R, state, tick, save, route,
|
||||
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, forgetShortCourse,
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
console.log('%c云学堂助手 v' + VERSION + ' 已加载', 'color:#3c9;font-weight:bold');
|
||||
setStatus(S.runFinished
|
||||
? '本次已完成 ' + S.completedThisRun + ' 门(已停止)'
|
||||
: (S.running ? '自动刷课运行中' : '待机'));
|
||||
@@ -0,0 +1,66 @@
|
||||
// ======== 生命周期(支持热替换:新版本注入前先 dispose 旧实例) ========
|
||||
import { PANEL_ID, TAG } from './config.js';
|
||||
|
||||
export const TIMERS = []; // setInterval id
|
||||
export const DELAYS = []; // setTimeout id
|
||||
export const WINDOW_LISTENERS = [];// [target, type, fn]
|
||||
export const ELEMENT_LISTENERS = [];// [el, type, fn]
|
||||
|
||||
export function every(fn, ms) {
|
||||
const id = setInterval(fn, ms);
|
||||
TIMERS.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function onWindow(target, type, fn) {
|
||||
target.addEventListener(type, fn);
|
||||
WINDOW_LISTENERS.push([target, type, fn]);
|
||||
}
|
||||
|
||||
export function onElement(el, type, fn) {
|
||||
el.addEventListener(type, fn);
|
||||
ELEMENT_LISTENERS.push([el, type, fn]);
|
||||
}
|
||||
|
||||
// 登记表里的一项:[target, 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) {} });
|
||||
}
|
||||
|
||||
export function dispose() {
|
||||
drain(TIMERS, clearInterval);
|
||||
drain(DELAYS, clearTimeout);
|
||||
drain(WINDOW_LISTENERS, detachListener);
|
||||
drain(ELEMENT_LISTENERS, detachListener);
|
||||
try {
|
||||
document.querySelectorAll('video[data-yt-hooked]').forEach(function (v) {
|
||||
v.removeAttribute('data-yt-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) {}
|
||||
console.log(TAG, '旧实例已释放');
|
||||
}
|
||||
|
||||
try {
|
||||
Object.defineProperty(window, '__ytDispose', {
|
||||
value: dispose, configurable: true, writable: true,
|
||||
});
|
||||
} catch (e) { /* 重复注入时忽略 */ }
|
||||
+614
@@ -0,0 +1,614 @@
|
||||
// ======== 列表页 ========
|
||||
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
|
||||
import { R, S, state, save, resetCourseRuntime } 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';
|
||||
|
||||
export 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: li,
|
||||
i: i,
|
||||
title: norm(titleEl ? titleEl.innerText : ''),
|
||||
status: status,
|
||||
tags: tags,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function cardsSignature(cards) {
|
||||
cards = cards || scanCards();
|
||||
if (!cards.length) return '';
|
||||
return cards.length + '|' + cards[0].title + '|' + cards[cards.length - 1].title;
|
||||
}
|
||||
|
||||
export function jumpToPage(target) {
|
||||
if (!target) return false;
|
||||
if (Date.now() - R.lastPageJumpAt < 3000) 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;
|
||||
}
|
||||
|
||||
export function nextPage() {
|
||||
if (Date.now() - R.lastPageJumpAt < 3000) 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, '翻到下一页');
|
||||
}
|
||||
}
|
||||
|
||||
// ======== 短课程优先(时长正序) ========
|
||||
// 列表卡片本身不显示时长,但列表组件(ul.kng-list-new.__vue__)的 kngListData
|
||||
// 里每门课都带 studyHours(秒)。当前页可据此按时长排序;要进一步跨页优先,
|
||||
// 再用同一套列表接口一次性读取全部课程,按 studyHours 正序排队。
|
||||
// 接口失败时逐级降级:跨页队列 → 当前页时长排序 → 原列表顺序,绝不卡住批量任务。
|
||||
|
||||
export 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) || [];
|
||||
}
|
||||
|
||||
// 列表页组件:优先取直接挂载 kngListData 的父组件
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 列表接口的分页/排序参数:缓存 key 与实际请求共用同一份默认值,避免两处飘移
|
||||
function shortQuery(vm) {
|
||||
return {
|
||||
pageSize: Number(vm && vm.pageSize) || 16,
|
||||
orderBy: (vm && vm.sortColumn) || 'createTime',
|
||||
orderType: (vm && vm.sortType) || 'desc',
|
||||
};
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeShortCatalog(cat) {
|
||||
if (!cat) return;
|
||||
try {
|
||||
sessionStorage.setItem(SS_SHORT_CATALOG, JSON.stringify(cat));
|
||||
} catch (e) { /* 容量不足时只保留内存队列 */ }
|
||||
}
|
||||
|
||||
export 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';
|
||||
}
|
||||
|
||||
export 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: token,
|
||||
'yxt-orgdomain': location.hostname,
|
||||
source: '501',
|
||||
};
|
||||
return { body: body, headers: headers };
|
||||
}
|
||||
|
||||
// 一次性读取列表接口(limit=6000 可覆盖当前 5000+ 门课程的站点),
|
||||
// 只保留「未学完」的课程,并映射到它所在的页码。
|
||||
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(6000, total - offset) : 6000;
|
||||
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 = [];
|
||||
datas.forEach(function (item, index) {
|
||||
if (!item || !item.title) return;
|
||||
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) return;
|
||||
const seconds = Number(item.studyHours);
|
||||
items.push({
|
||||
id: item.id ? String(item.id) : '',
|
||||
title: norm(item.title),
|
||||
duration: Number.isFinite(seconds) && seconds > 0 ? seconds : 0,
|
||||
status: item.status,
|
||||
page: Math.floor(index / q.pageSize) + 1,
|
||||
});
|
||||
});
|
||||
// 时长未知的排最后;相同时按原来的列表顺序(页码)
|
||||
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: key, at: Date.now(), pageSize: q.pageSize, total: datas.length, items: items };
|
||||
}
|
||||
|
||||
// 返回 'off' | 'loading' | 'ready' | 'failed'
|
||||
export function ensureShortCatalog() {
|
||||
if (!state.preferShort) return 'off';
|
||||
|
||||
const vm = listVm();
|
||||
if (!vm) {
|
||||
if (!R.shortNoVmSince) R.shortNoVmSince = Date.now();
|
||||
if (Date.now() - R.shortNoVmSince > 5000) {
|
||||
R.shortCatalogFailedAt = Date.now();
|
||||
if (Date.now() - (R.shortWarnedAt || 0) > 10000) {
|
||||
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 > 20000) {
|
||||
R.shortCatalogLoading = false;
|
||||
R.shortCatalogFailedAt = Date.now();
|
||||
return 'failed';
|
||||
}
|
||||
return 'loading';
|
||||
}
|
||||
if (R.shortCatalogFailedAt && Date.now() - R.shortCatalogFailedAt < 30000) 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.preferShort) 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.preferShort) return;
|
||||
console.warn(TAG, '读取课程时长失败,退回当前页时长排序:',
|
||||
e && e.message ? e.message : e);
|
||||
setStatus('未能读取全部课程时长,先按当前页时长排序');
|
||||
updatePanel();
|
||||
});
|
||||
return 'loading';
|
||||
}
|
||||
|
||||
export function shortFallback(reason) {
|
||||
R.shortCatalog = null;
|
||||
R.shortCatalogFailedAt = Date.now();
|
||||
try { sessionStorage.removeItem(SS_SHORT_CATALOG); } catch (e) { /* ignore */ }
|
||||
if (Date.now() - (R.shortWarnedAt || 0) > 10000) {
|
||||
R.shortWarnedAt = Date.now();
|
||||
console.warn(TAG, '短课程优先暂不可用,退回当前页时长排序:', reason);
|
||||
setStatus('短课程优先暂不可用,先按当前页时长排序');
|
||||
}
|
||||
}
|
||||
|
||||
export function pendingShortItems() {
|
||||
const cat = R.shortCatalog;
|
||||
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;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// 列表卡片 -> 课程 id。卡片的打开逻辑按 id 跳转,而播放页 URL 带 kngId:
|
||||
// 有了 id 就能在标题还没刷新时准确判断「进的是不是队列里的这门课」,
|
||||
// 不再因为页面标题短暂是 loading/在线课堂 就误判并退回列表。
|
||||
export 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) : '';
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 优先用课程 id 匹配卡片,避免同名课程(平台上确实有)点错;
|
||||
// id 不可用时再退回标题匹配。
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
});
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
// 返回 { card } 表示本 tick 可以进入该课程;{ wait: true } 表示正在加载/翻页。
|
||||
export function chooseShortCourse(cards, pending) {
|
||||
if (!state.preferShort) 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 < 6000) return { wait: true };
|
||||
R.shortJumpAt = Date.now();
|
||||
if (jumpToPage(target.page)) {
|
||||
S.listPage = target.page;
|
||||
save();
|
||||
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.done[card.title] || S.failed[card.title]) {
|
||||
// 缓存与实际状态不一致:剔除这一门,下一 tick 继续挑下一门
|
||||
forgetShortCourse(card.title);
|
||||
return { wait: true };
|
||||
}
|
||||
card.duration = target.duration;
|
||||
R.shortJumpAt = 0;
|
||||
return { card: card };
|
||||
}
|
||||
// 刚翻到目标页时卡片可能还没渲染完
|
||||
if (Date.now() - R.shortJumpAt < 8000) 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;
|
||||
}
|
||||
|
||||
export function listTick() {
|
||||
const cards = scanCards();
|
||||
if (!cards.length) return; // 列表还没渲染
|
||||
|
||||
// 等待翻页后的新卡片,避免用旧卡片做判断
|
||||
if (R.pageChangeSig) {
|
||||
if (cardsSignature(cards) === R.pageChangeSig &&
|
||||
Date.now() - R.pageChangeAt < 10000) {
|
||||
return;
|
||||
}
|
||||
R.pageChangeSig = '';
|
||||
}
|
||||
if (R.pageChangeAt && Date.now() - R.pageChangeAt < 1500) return;
|
||||
|
||||
if (S.listUrl !== location.href) {
|
||||
S.listUrl = location.href;
|
||||
save();
|
||||
}
|
||||
|
||||
const page = currentPage();
|
||||
|
||||
// 回到列表后,恢复到课程所在的页码
|
||||
if (S.returning) {
|
||||
if (page != null && S.listPage && page !== S.listPage) {
|
||||
R.restoreAttempts++;
|
||||
if (R.restoreAttempts > 12) {
|
||||
console.warn(TAG, '页码恢复失败,改用当前页继续');
|
||||
S.listPage = page || 1;
|
||||
S.returning = false;
|
||||
save();
|
||||
} else if (S.listPage > page) {
|
||||
// 短课程优先会直接跳到很靠后的页(例如第 307 页),
|
||||
// 不能一页一页 nextPage,否则要翻几百次;优先用页码输入框直跳。
|
||||
if (jumpToPage(S.listPage)) return;
|
||||
nextPage();
|
||||
return;
|
||||
} else {
|
||||
jumpToPage(S.listPage);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
S.returning = false;
|
||||
R.restoreAttempts = 0;
|
||||
save();
|
||||
setStatus('回到列表第 ' + (page || 1) + ' 页,继续…');
|
||||
}
|
||||
}
|
||||
|
||||
// 记录当前页
|
||||
if (!S.returning && page != null && page !== S.listPage) {
|
||||
S.listPage = page;
|
||||
save();
|
||||
}
|
||||
|
||||
// 已在进入课程的过程中:等路由跳转
|
||||
if (S.current && S.phase === 'entering') {
|
||||
const waited = Date.now() - (S.current.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; });
|
||||
if (card) {
|
||||
R.entryRetries++;
|
||||
R.lastCardClickAt = Date.now();
|
||||
console.log(TAG, '进入课程超时,重试点击卡片(第', R.entryRetries, '次)');
|
||||
setStatus('重新进入课程:' + truncate(S.current.title, 22));
|
||||
try { clickNode(card.li); } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 从课程页意外回到列表:判断当前课程是已完成还是中断
|
||||
if (S.current && S.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; });
|
||||
if (card && /已学完|已完成|已学习/.test(card.status)) {
|
||||
S.done[S.current.title] = Date.now();
|
||||
forgetShortCourse(S.current.title);
|
||||
S.completedThisRun = (S.completedThisRun || 0) + 1;
|
||||
}
|
||||
S.current = null;
|
||||
S.phase = 'idle';
|
||||
S.returning = false;
|
||||
R.listWithCurrentSince = 0;
|
||||
save();
|
||||
setStatus('已重置中断的课程状态,继续…');
|
||||
}
|
||||
|
||||
if (S.current) return; // 其他异常情况,等路由
|
||||
|
||||
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;
|
||||
return true;
|
||||
});
|
||||
|
||||
// 优先短课程:先读时长队列,跨页挑总时长最短的未学完课程;
|
||||
// 接口不可用时 chooseShortCourse 会退回当前页时长排序或原列表顺序。
|
||||
if (state.preferShort) {
|
||||
const choice = chooseShortCourse(cards, pending);
|
||||
if (choice && choice.wait) return;
|
||||
if (choice && choice.card) {
|
||||
if (Date.now() - R.lastCardClickAt < 5000) return;
|
||||
startCourse(choice.card);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (pending.length) {
|
||||
if (Date.now() - R.lastCardClickAt < 5000) return;
|
||||
startCourse(pending[0]);
|
||||
return;
|
||||
}
|
||||
|
||||
const max = maxPageNumber();
|
||||
if (page != null && max && page < max) {
|
||||
nextPage();
|
||||
return;
|
||||
}
|
||||
|
||||
stopBatch('所有页面的未学完课程都已处理完毕');
|
||||
}
|
||||
|
||||
export function startCourse(card) {
|
||||
const page = currentPage() || S.listPage || 1;
|
||||
S.current = {
|
||||
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;
|
||||
R.lastCardClickAt = Date.now();
|
||||
R.shortJumpAt = 0;
|
||||
resetCourseRuntime();
|
||||
save();
|
||||
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('课程卡片点击失败');
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
// ======== 登录 / 一键刷课 ========
|
||||
import { LS_LOGIN, LS_PENDING } from './config.js';
|
||||
import { R, S, save } from './state.js';
|
||||
import { route, goToList } from './route.js';
|
||||
import { truncate, isVisible, findVisibleButton } from './utils.js';
|
||||
import { later, onElement } from './lifecycle.js';
|
||||
import { setStatus, updatePanel, loginUserEl, loginPassEl, loginRememberEl, loginAutoEl } from './panel.js';
|
||||
|
||||
// startBatch 内部会调用 tick()(主循环),tick 定义在 index.js;
|
||||
// 用可变绑定 + setter 在 index.js 装配阶段回填,避免 login -> index 的循环导入。
|
||||
let tick = function () {};
|
||||
export function setTick(fn) { tick = fn; }
|
||||
|
||||
// 「登录后自动开始刷课」的一次性标记,用完/失效就清掉
|
||||
function clearPending() {
|
||||
try { localStorage.removeItem(LS_PENDING); } catch (e) {}
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
export 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: user, pwd: pwd };
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
export 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) { /* ignore */ }
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSavedCreds() {
|
||||
try { localStorage.removeItem(LS_LOGIN); } catch (e) {}
|
||||
if (loginRememberEl) loginRememberEl.checked = false;
|
||||
}
|
||||
|
||||
export function startBatch() {
|
||||
if (S.runFinished) {
|
||||
S.completedThisRun = 0;
|
||||
S.consecutiveFailures = 0;
|
||||
S.runFinished = false;
|
||||
}
|
||||
S.running = true;
|
||||
if (!S.current) S.phase = 'idle';
|
||||
save();
|
||||
setStatus('自动刷课已开启');
|
||||
const r = route();
|
||||
if (r === 'list' || (r === 'course' && S.current)) {
|
||||
tick();
|
||||
} else {
|
||||
goToList();
|
||||
}
|
||||
updatePanel();
|
||||
}
|
||||
|
||||
export 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 * 1000) {
|
||||
clearPending();
|
||||
return false;
|
||||
}
|
||||
if (isLoginPage()) return false;
|
||||
clearPending();
|
||||
startBatch();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function watchLoginResult() {
|
||||
if (!isLoginPage()) return;
|
||||
const vm = findLoginVm();
|
||||
if (vm && vm.captchaVisible) {
|
||||
setStatus('需要手动完成验证码/滑块,完成后会自动继续');
|
||||
return; // 保留 pending,手动完成登录后仍会自动开始
|
||||
}
|
||||
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; // 保留 pending,手动完成登录后仍会自动开始
|
||||
}
|
||||
if (R.loginSubmittingAt && Date.now() - R.loginSubmittingAt > 12000) {
|
||||
R.loginSubmittingAt = 0;
|
||||
setStatus('尚未登录成功:请检查账号密码,或手动完成验证');
|
||||
}
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
|
||||
export 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();
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
// ==UserScript==
|
||||
// @name 云学堂助手
|
||||
// @namespace yun-xue-tang-assistant.local
|
||||
// @version __YT_VERSION__
|
||||
// @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 即可不限门数(会持续很久)。
|
||||
* - 平台若有防挂机检测/答题环节,脚本会跳过该课程并在面板提示。
|
||||
* 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」;
|
||||
* 答题/考试、滑块拼图类验证仍会跳过该课程。
|
||||
* - 验证码/滑块需要手动完成,脚本不会绕过。
|
||||
* - 课程/单位如有相关规定,请自行确认风险。
|
||||
*
|
||||
* 短课程优先:
|
||||
* - 面板勾选「优先短课程(时长正序)」后,批量刷课会先读课程列表接口里的总时长,
|
||||
* 按「未学完课程的总时长从短到长」选课,而不是按列表顺序。接口不可用时会自动
|
||||
* 退回为「当前页按时长正序」,再不行就按原来的列表顺序,不会卡住批量任务。
|
||||
*
|
||||
* 开发热加载:
|
||||
* - 本文件可直接被 dev/dev-loader.user.js 热注入:脚本暴露 window.__ytDispose(),
|
||||
* 加载器在注入新版本前会先调用它清理定时器、监听器与面板,因此保存文件后
|
||||
* 约 1 秒内即可生效,无需手动刷新页面。
|
||||
*/
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
// ======== 面板 ========
|
||||
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 { route } from './route.js';
|
||||
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
|
||||
import { failCurrent } from './complete.js';
|
||||
|
||||
// 会话时长:面板 footer 显示本次脚本会话自加载起已运行多久
|
||||
const SESSION_START_AT = Date.now();
|
||||
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;
|
||||
let cbPreferShort = null;
|
||||
let cbAuto = null;
|
||||
let loginBox = null;
|
||||
export let loginUserEl = null;
|
||||
export let loginPassEl = null;
|
||||
export let loginRememberEl = null;
|
||||
export let loginAutoEl = null;
|
||||
let btnOne = null;
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
export function setStatus(text) {
|
||||
console.log(TAG, text);
|
||||
if (statusEl) statusEl.textContent = text;
|
||||
}
|
||||
|
||||
export function updatePanel() {
|
||||
if (cbBatch) cbBatch.checked = S.running;
|
||||
if (statsEl) {
|
||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : '∞';
|
||||
statsEl.textContent =
|
||||
'本次 ' + S.completedThisRun + '/' + limit +
|
||||
' · 失败 ' + Object.keys(S.failed).length +
|
||||
(R.idlePassed ? ' · 验证 ' + R.idlePassed : '');
|
||||
}
|
||||
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;
|
||||
|
||||
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.current;
|
||||
btnOne.textContent = onLogin
|
||||
? '一键登录并刷课'
|
||||
: (onCourse && S.running ? '停止刷课' : '一键刷课');
|
||||
btnOne.title = onCourse && S.running ? '停止批量刷课' : '开始 / 继续批量刷课';
|
||||
}
|
||||
}
|
||||
|
||||
export 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 = 'yt-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 = 'yt-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.current && S.running) {
|
||||
S.running = false;
|
||||
save();
|
||||
setStatus('自动刷课已暂停');
|
||||
} else {
|
||||
startBatch();
|
||||
}
|
||||
updatePanel();
|
||||
});
|
||||
|
||||
loginBox = document.createElement('div');
|
||||
loginBox.id = 'yt-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('yt-login-user', 'text', '员工邮箱/账号');
|
||||
loginPassEl = mkInput('yt-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: label, cb: cb };
|
||||
};
|
||||
const rem = mkCheck('yt-login-remember', '记住密码');
|
||||
loginRememberEl = rem.cb;
|
||||
const auto = mkCheck('yt-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 = 'yt-auto-enabled';
|
||||
cbAuto.checked = state.enabled;
|
||||
cbAuto.addEventListener('change', function () {
|
||||
state.enabled = 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 = 'yt-batch-enabled';
|
||||
cbBatch.checked = S.running;
|
||||
cbBatch.addEventListener('change', function () {
|
||||
if (cbBatch.checked) {
|
||||
startBatch();
|
||||
} else {
|
||||
S.running = false;
|
||||
save();
|
||||
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 = 'yt-prefer-short';
|
||||
cbPreferShort.checked = state.preferShort;
|
||||
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) {
|
||||
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 = 'yt-status';
|
||||
statusEl.textContent = '待机';
|
||||
statusEl.style.cssText = 'margin-top:6px;color:#8ee6c0;word-break:break-all;';
|
||||
|
||||
statsEl = document.createElement('div');
|
||||
statsEl.id = 'yt-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.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(btnSkip);
|
||||
box.appendChild(clearFail);
|
||||
box.appendChild(hint);
|
||||
box.appendChild(footer);
|
||||
document.documentElement.appendChild(box);
|
||||
}
|
||||
|
||||
export function ensurePanel() {
|
||||
if (window.top !== window.self) return;
|
||||
if (!document.getElementById(PANEL_ID)) buildPanel();
|
||||
updatePanel();
|
||||
}
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
// ======== 播放器 ========
|
||||
import { CFG, TAG } from './config.js';
|
||||
import { R, S, state } from './state.js';
|
||||
import { norm, textOf, truncate, isVisible, findVisibleButton, collectDocuments } from './utils.js';
|
||||
import { onElement } from './lifecycle.js';
|
||||
import { setStatus, updatePanel } from './panel.js';
|
||||
import { failCurrent } from './complete.js';
|
||||
|
||||
export function applyMute(v) {
|
||||
if (!CFG.mute) return;
|
||||
try {
|
||||
if (!v.muted) v.muted = true;
|
||||
v.defaultMuted = true;
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
export function playVideo(v) {
|
||||
if (!v) return;
|
||||
if (state.enabled || S.running) {
|
||||
try {
|
||||
const p = v.play();
|
||||
if (p && typeof p.catch === 'function') p.catch(() => {});
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
export function hookVideo(v) {
|
||||
if (!v) return;
|
||||
if (v.getAttribute && v.getAttribute('data-yt-hooked') === '1') return;
|
||||
if (R.hooked.has(v)) return;
|
||||
R.hooked.add(v);
|
||||
try { v.setAttribute('data-yt-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();
|
||||
});
|
||||
}
|
||||
|
||||
export 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);
|
||||
}
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function ensurePlaying(v) {
|
||||
if (!v) return;
|
||||
applyMute(v);
|
||||
if (S.current) {
|
||||
try {
|
||||
if (Math.abs(v.playbackRate - 1) > 0.01) v.playbackRate = 1;
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
if (!v.paused) return;
|
||||
// 已播完就交给「进度/切节」逻辑处理。
|
||||
// 平台在切到下一节后会自动挂出「还需 5分钟…」,那是下一节的时长,
|
||||
// 不能据此把已结束的视频拉回开头重播。
|
||||
if (v.ended) return;
|
||||
playVideo(v);
|
||||
}
|
||||
|
||||
// 平台完成状态有三种真实文案:
|
||||
// 多课时课程:已完成 2/3
|
||||
// 单视频/音频:已完成 0% -> 已完成 67%
|
||||
// 全部学完: 已完成学习 (此时进度条和倒计时都会消失)
|
||||
// 旧实现只认 x/y,课程真正学完后汇总变成「已完成学习」→ 永远不判完成,
|
||||
// 结果就是停在课程页、不回列表、也不进入下一门。
|
||||
export 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: x, y: 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: 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;
|
||||
}
|
||||
|
||||
export function readCountdown() {
|
||||
const el = document.querySelector('.yxtulcdsdk-course-player__countdown');
|
||||
if (!el) return null;
|
||||
const t = textOf(el);
|
||||
// 平台文案可能是「还需 2小时 7分钟 59秒」,也可能只剩「还需 5分钟」
|
||||
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;
|
||||
}
|
||||
|
||||
export function readActiveLessonKey() {
|
||||
const active = document.querySelector('.yxtulcdsdk-catalog .liactive');
|
||||
if (!active) return '';
|
||||
const li = active.closest('li');
|
||||
return norm(li ? li.innerText : active.innerText);
|
||||
}
|
||||
|
||||
// 目录里「章」节点也带 .hand 且包含子 ul;只取真正的课时 li
|
||||
export function lessonItems() {
|
||||
return [...document.querySelectorAll('.yxtulcdsdk-catalog ul > li')]
|
||||
.filter(function (li) { return !li.querySelector('ul'); });
|
||||
}
|
||||
|
||||
export 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;
|
||||
// 返回 li 本身:真正的点击目标由 clickLesson 选择。以前返回内部 .hand,
|
||||
// 在真实目录里那是 <svg>,没有 click(),next.click() 会抛异常 → 切节失效。
|
||||
return lis[idx + 1];
|
||||
}
|
||||
|
||||
export function isLessonCompleted(li) {
|
||||
try {
|
||||
// 1) 状态文案:目录里的标签可能在标题前(「已学完 第1节」),也可能在标题后,
|
||||
// 不能只认结尾,否则一个都识别不出来 → 每次都退回第一节
|
||||
const text = textOf(li);
|
||||
if (/已学完|已完成/.test(text)) return true;
|
||||
|
||||
// 2) 语义属性/类名(平台改版时比 svg 路径稳定)
|
||||
const hint = [
|
||||
li.getAttribute('aria-label') || '',
|
||||
li.getAttribute('title') || '',
|
||||
String(li.className || ''),
|
||||
].join(' ');
|
||||
if (/已学完|已完成|finished|completed|is-done/i.test(hint)) return true;
|
||||
|
||||
// 3) 完成态图标:平台用一个起点 M10 2.75 的实心圆 + 对勾
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
export function findFirstIncompleteLessonElement() {
|
||||
for (const li of lessonItems()) {
|
||||
if (!isLessonCompleted(li)) return li;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 暂停页面上所有媒体:平台会在课程完成后把播放器重置到 0 秒,不暂停就会又从头播一遍。
|
||||
// 逐个元素 try,单个元素 busy/已卸下时不影响其余视频。
|
||||
export function pauseAllMedia() {
|
||||
try {
|
||||
document.querySelectorAll('video, audio').forEach(function (x) {
|
||||
try { x.pause(); } catch (e) {}
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// ---- 课时切换(对齐起点 / 纠偏时使用,带多种点击方式与校验) ----
|
||||
export function lessonActiveLi() {
|
||||
const el = document.querySelector('.yxtulcdsdk-catalog .liactive');
|
||||
return el ? el.closest('li') : null;
|
||||
}
|
||||
|
||||
// 浏览器里有布局信息;jsdom 之类的无布局环境下返回 false,避免误判“隐藏”
|
||||
export function layoutAvailable() {
|
||||
try {
|
||||
const r = document.body.getBoundingClientRect();
|
||||
return r.width > 0 && r.height > 0;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 目录诊断快照:起点纠正失败时打到控制台,便于定位平台为什么不响应点击
|
||||
export 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),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function fireMouse(el, type) {
|
||||
try {
|
||||
el.dispatchEvent(new MouseEvent(type, {
|
||||
bubbles: true, cancelable: true, view: window, button: 0,
|
||||
}));
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
export 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')); }
|
||||
}
|
||||
|
||||
// 目录里的展开箭头、课时状态图标都是 <svg>,而 SVGSVGElement 并没有
|
||||
// HTMLElement 的 click() 方法:直接 el.click() 会抛 TypeError 并被静默吞掉,
|
||||
// 等于“点了但什么都没发生”。任何节点都统一走这里,必要时派发鼠标事件。
|
||||
export function clickNode(el) {
|
||||
if (!el) return false;
|
||||
try {
|
||||
if (typeof el.click === 'function') {
|
||||
el.click();
|
||||
return true;
|
||||
}
|
||||
} catch (e) { /* 落到下面的事件派发 */ }
|
||||
fireMouse(el, 'click');
|
||||
return true;
|
||||
}
|
||||
|
||||
// 有些点击逻辑挂在 mousedown/pointerup 上,补一整套鼠标事件序列
|
||||
export function fireClickSequence(el) {
|
||||
if (!el) return;
|
||||
firePointer(el, 'pointerdown');
|
||||
fireMouse(el, 'mousedown');
|
||||
firePointer(el, 'pointerup');
|
||||
fireMouse(el, 'mouseup');
|
||||
clickNode(el);
|
||||
}
|
||||
|
||||
// 课时的点击句柄可能挂在标题 span、行容器、li 或右侧状态图标任意一层,
|
||||
// 这里按「由内向外」返回候选节点:点最内层标题时事件会依次冒泡到行容器和 li,
|
||||
// 能覆盖这三种常见写法;状态图标(svg)放最后作兜底。
|
||||
export 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);
|
||||
}
|
||||
|
||||
// 点击第 attempt 次切换课时,逐次换目标与事件方式:
|
||||
// 1) 标题 span 2) 标题 + 行容器 3) 完整鼠标序列(标题) 4) 行容器 + 课时自带按钮
|
||||
// 5) li 6) 状态图标 …… 避免前两次点偏后就直接放弃
|
||||
export 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);
|
||||
}
|
||||
|
||||
// 平台切课时可能弹「确认切换/退出当前学习」,自动点掉。
|
||||
// 先只在弹层里找,避免误点页面上的其它同名按钮。
|
||||
export 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;
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function courseHasQuizLesson() {
|
||||
// 没有标签课时,some() 本身就返回 false,不必先判 length
|
||||
return [...document.querySelectorAll('.yxtulcdsdk-catalog ul > li .tag-type')]
|
||||
.some(function (t) { return /考试|测验|问卷|答题/.test(textOf(t)); });
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 防挂机验证:平台每 10 分钟(kngConf/cheat.maxMin)弹一次,
|
||||
// 文案「已触发防挂机验证,请点击“继续学习”,否则学习将被停止」,120 秒内不点就停止计时。
|
||||
export function findAntiIdleDialog() {
|
||||
const pat = /防挂机|不要走开|学习将被停止|请点击.?继续学习/;
|
||||
let best = null;
|
||||
let bestLen = Infinity;
|
||||
for (const doc of collectDocuments()) {
|
||||
let cands;
|
||||
try {
|
||||
// 只认 dialog/modal,别把 [class*="popup"] 之类的外层容器算进来:
|
||||
// 平台会把 <body class="yxt-popup-parent--hidden"> 整个页面套进去,误判成弹窗。
|
||||
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;
|
||||
// 取文案最短的那层(即最内层弹窗),避免选到大 wrapper
|
||||
if (t.length < bestLen) { best = el; bestLen = t.length; }
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function findAntiIdleButton(dialog) {
|
||||
if (!dialog) return null;
|
||||
const want = /^(继续学习|我知道了|继续观看)$/;
|
||||
const pick = function (sel) {
|
||||
return [...dialog.querySelectorAll(sel)].find(function (el) {
|
||||
return want.test(textOf(el)) && isVisible(el);
|
||||
}) || null;
|
||||
};
|
||||
// 必须优先点真正的 <button>:平台的点击回调绑在 button 上,
|
||||
// 点文案相同的外层 div(如 <div class="mt24">)不会有任何反应。
|
||||
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;
|
||||
}
|
||||
|
||||
// 弹层里是滑块/拼图时脚本过不了,需要人工
|
||||
export 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;
|
||||
}
|
||||
}
|
||||
|
||||
export function handleAntiIdle() {
|
||||
const dialog = findAntiIdleDialog();
|
||||
if (!dialog) return false;
|
||||
|
||||
// 先找按钮:只要弹窗里有「继续学习」就直接点,不要因为页面里别处有 canvas 就误判成滑块
|
||||
const btn = findAntiIdleButton(dialog);
|
||||
if (!btn) {
|
||||
if (antiIdleNeedsHuman(dialog)) {
|
||||
setStatus('防挂机验证需要人工完成(滑块/拼图)');
|
||||
failCurrent('防挂机验证需要人工完成');
|
||||
} else {
|
||||
setStatus('检测到防挂机验证,未找到「继续学习」按钮');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (Date.now() - R.lastIdleClickAt < 2500) return true;
|
||||
|
||||
// 同一个弹层最多点 10 次,防止平台异常不关闭时无限点击
|
||||
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) { /* ignore */ }
|
||||
console.log(TAG, '防挂机验证:已点击「继续学习」(第', R.idlePassed, '次)');
|
||||
setStatus('已通过防挂机验证(第 ' + R.idlePassed + ' 次)');
|
||||
updatePanel();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function courseTitle() {
|
||||
return String(document.title || '')
|
||||
.replace(/\s*-\s*[^-]*(云课堂|云学堂)\s*$/, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
// 对齐起点:把当前课时切到「第一个未学完的课时」。
|
||||
// 返回 true = 本 tick 已处理(正在切换 / 等待确认),调用方应直接 return;
|
||||
// 返回 false = 无需对齐或已对齐,可以继续播放逻辑。
|
||||
// 成功与否以目录高亮为准(连续两个 tick 都在目标课时才算数),
|
||||
// 避免面板声称已切换、实际仍停在平台上次的位置。
|
||||
export 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) {
|
||||
// 所有课时都已完成,整门课是否结束交给 summary 判断
|
||||
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++;
|
||||
|
||||
// 章节折叠时子课时不可点,先展开所属章节。
|
||||
// 展开箭头通常是 <svg>,必须用 clickNode 派发事件(svg 没有 click() 方法)。
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 切课时平台可能弹确认框,先点掉(第 1 次不查,避免误点页面上的其他「确定」)
|
||||
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;
|
||||
}
|
||||
|
||||
// 手动模式没有 S.current,用课程标题判断是否换了一门课,换课时重新对齐
|
||||
export 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;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// ======== 路由 ========
|
||||
import { R, S, save } from './state.js';
|
||||
|
||||
// 平台不同内容类型进入的播放页不同:
|
||||
// 多课时课程 #/course/play?kngId=… 单个视频 #/video/play?kngId=…
|
||||
// 单个音频 #/audio/play?kngId=… 单个课件 #/ppt/play?kngId=…
|
||||
// 以前只认 #/course/play,其它类型整页逻辑都不会跑(不自动播放、也不判完成)。
|
||||
// #/scan 是点开课程后的过渡页,也按课程页处理。
|
||||
export 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';
|
||||
}
|
||||
|
||||
// 单媒体播放页(没有多课时目录):完成判定看进度百分比/「已完成学习」,
|
||||
// 不需要找下一节。
|
||||
export function mediaPage() {
|
||||
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || '');
|
||||
}
|
||||
|
||||
export function goToList(force) {
|
||||
if (!force && Date.now() - R.lastGoListAt < 5000) return;
|
||||
R.lastGoListAt = Date.now();
|
||||
const url = S.listUrl || location.origin + '/kng/#/list';
|
||||
if (route() === 'list') {
|
||||
S.returning = true;
|
||||
save();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
location.href = url;
|
||||
} catch (e) {
|
||||
location.hash = '#/list';
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
// ======== 状态 ========
|
||||
import { CFG, LS_ENABLED, LS_PREFER_SHORT, LS_BATCH } from './config.js';
|
||||
|
||||
export const state = {
|
||||
enabled: true, // 手动打开的课程:自动连播
|
||||
preferShort: CFG.preferShortCourses, // 批量选课:优先时长短的课程(正序)
|
||||
};
|
||||
try {
|
||||
state.enabled = 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';
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
export function defaultBatch() {
|
||||
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 }
|
||||
};
|
||||
}
|
||||
|
||||
export let S = defaultBatch();
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_BATCH);
|
||||
if (raw) S = Object.assign(defaultBatch(), JSON.parse(raw));
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
export function save() {
|
||||
try {
|
||||
localStorage.setItem(LS_BATCH, JSON.stringify(S));
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// 运行时状态(不持久化)
|
||||
export const R = {
|
||||
hooked: 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,
|
||||
initialLessonChecked: false,
|
||||
phaseSince: 0,
|
||||
alignTries: 0,
|
||||
alignStable: 0,
|
||||
alignFailed: false,
|
||||
manualCourseKey: '',
|
||||
lastIdleClickAt: 0,
|
||||
idlePassed: 0,
|
||||
idleDialogText: '',
|
||||
idleDialogClicks: 0,
|
||||
idleGaveUp: false,
|
||||
restoreAttempts: 0,
|
||||
loginFilled: false,
|
||||
loginSubmittingAt: 0,
|
||||
loginAutoTried: false,
|
||||
loginBoundUser: null,
|
||||
loginBoundPwd: null,
|
||||
// 短课程优先:课程时长队列(只在当前标签页会话内缓存)
|
||||
shortCatalog: null,
|
||||
shortCatalogLoading: false,
|
||||
shortCatalogFailedAt: 0,
|
||||
shortFetchStartedAt: 0,
|
||||
shortJumpAt: 0,
|
||||
shortNoVmSince: 0,
|
||||
shortWarnedAt: 0,
|
||||
};
|
||||
|
||||
export 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.initialLessonChecked = false;
|
||||
R.phaseSince = 0;
|
||||
R.alignTries = 0;
|
||||
R.alignStable = 0;
|
||||
R.alignFailed = false;
|
||||
R.manualCourseKey = '';
|
||||
R.lastAdvanceAt = 0;
|
||||
R.restoreAttempts = 0;
|
||||
R.entryRetries = 0;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// ======== 基础工具 ========
|
||||
export const norm = (s) => String(s || '').replace(/\s/g, '');
|
||||
export const truncate = (s, n) => (s.length > n ? s.slice(0, n) + '…' : s);
|
||||
|
||||
export function textOf(el) {
|
||||
try {
|
||||
return norm(el.innerText || el.textContent || '');
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 平台的「开始学习/继续学习」多数是 <button>,但个别页面把点击句柄放在
|
||||
// 文案 span 或外层 div 上。按由外到内找不到时,再找最内层的纯文字节点,
|
||||
// 点击会冒泡到真正的句柄。只认可见且没有兄弟文字干扰的最内层节点。
|
||||
export 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;
|
||||
}
|
||||
|
||||
// 从播放页 URL 里取课程 id:进课过渡页(#/scan)和真正的播放页
|
||||
// (#/course/play、#/video/play…)都带 kngId。
|
||||
export function courseIdFromUrl() {
|
||||
const m = String(location.hash || '').match(/[?&]kngId=([^&]+)/);
|
||||
if (!m) return '';
|
||||
try { return decodeURIComponent(m[1]); } catch (e) { return m[1]; }
|
||||
}
|
||||
|
||||
export 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;
|
||||
}
|
||||
Reference in new issue
Block a user