Fix desktop quiz submission and keep runs enabled until cancelled
This commit is contained in:
+121
-64
@@ -1,7 +1,7 @@
|
||||
// ==UserScript==
|
||||
// @name 学员中心 · 2倍速学习助手
|
||||
// @namespace local.icampus.study
|
||||
// @version 1.2.0
|
||||
// @version 1.3.0
|
||||
// @description 支持切换标签页继续2倍速播放与保存进度,自动测验及错题重试。
|
||||
// @match https://icampus.yunyinsh.com/course/*
|
||||
// @run-at document-start
|
||||
@@ -28,13 +28,14 @@
|
||||
function bodyJSON(body) {
|
||||
try { return typeof body === 'string' && body.length < 65536 ? JSON.parse(body) : null; } catch { return null; }
|
||||
}
|
||||
function courseDone(c) { return !!c && (c.status === 'COMPLETED' || !!c.completedAt); }
|
||||
function examPerfect(c) { return !!c && Number(c.examScorePercent)===100 && (c.examPassed===true || c.examPassed==='true'); }
|
||||
function courseDone(c) { return !!c && (c.status === 'COMPLETED' || !!c.completedAt) && (!c.examRequired || examPerfect(c)); }
|
||||
function videoPlan(detail) {
|
||||
if (!detail?.course || !Array.isArray(detail.resources)) return {kind: 'wait'};
|
||||
const resources = [...detail.resources].sort((a, b) => a.sortNo - b.sortNo);
|
||||
const next = resources.find(r => r.completed !== true);
|
||||
if (next) return {kind: next.type === 'VIDEO' ? 'video' : 'manual', resource: next};
|
||||
if (detail.course.examRequired && detail.course.examPassed !== true) return {kind: 'quiz'};
|
||||
if (detail.course.examRequired && !examPerfect(detail.course)) return {kind: 'quiz'};
|
||||
return {kind: 'finish'};
|
||||
}
|
||||
function resolveCards(cards, courses) {
|
||||
@@ -91,7 +92,7 @@
|
||||
return m ? {kind:'card', paperId:m[1]} : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
const core = {normalize, route, endpoint, bodyJSON, courseDone, videoPlan, resolveCards, leaseAvailable,
|
||||
const core = {normalize, route, endpoint, bodyJSON, courseDone, examPerfect, videoPlan, resolveCards, leaseAvailable,
|
||||
questionKey, selectionKey, chooseAnswer, learnCard, quizEndpoint};
|
||||
if (typeof module === 'object' && module.exports && typeof window === 'undefined') { module.exports = core; return; }
|
||||
if (window.top !== window.self || document.getElementById('icampus-study-helper')) return;
|
||||
@@ -101,6 +102,9 @@
|
||||
const SNAPSHOT_KEY = 'icampus.study.v1.lastExam';
|
||||
const RESUME_KEY = 'icampus.study.v1.recovery';
|
||||
const BACKGROUND_KEY = 'icampus.study.v1.background';
|
||||
const INTENT_KEY = 'icampus.study.v1.enabled';
|
||||
let armed = false;
|
||||
let waiting = null;
|
||||
let backgroundEnabled = true;
|
||||
try { backgroundEnabled = localStorage.getItem(BACKGROUND_KEY) !== 'off'; } catch {}
|
||||
let foregroundGraceUntil = 0;
|
||||
@@ -173,14 +177,30 @@
|
||||
render(); return; // Let the website restart its normal timer on return.
|
||||
}
|
||||
if(!running || !backgroundEnabled || !route(location.hash).id) return;
|
||||
if(!holdLease()) { stop('其他学习页接管了助手,本页已暂停。'); return; }
|
||||
if(!holdLease()) { park('其他学习页接管了助手,本页已暂停。'); return; }
|
||||
// The course component's hidden handler stops its heartbeat timer.
|
||||
// Keep the existing timer alive; leave true visibility and all requests unchanged.
|
||||
event.stopImmediatePropagation();
|
||||
log('已切到后台,继续正常播放并等待平台保存。'); render();
|
||||
}
|
||||
document.addEventListener('visibilitychange',onVisibilityChange,true);
|
||||
function stop(message = '已暂停;点击开始可继续。') {
|
||||
function workSignature() {
|
||||
const root=document.querySelector('.course-quiz');
|
||||
return JSON.stringify([location.hash,root?.textContent,
|
||||
[...(root?.querySelectorAll('.quiz-option.is-selected') || [])].map(b=>b.textContent),
|
||||
[...(root?.querySelectorAll('input, textarea') || [])].map(b=>b.value),
|
||||
document.querySelector('.course-head__top')?.textContent,
|
||||
currentVideo()?.paused,currentVideo()?.readyState,
|
||||
[...document.querySelectorAll('article.course-row')].map(b=>b.textContent)]);
|
||||
}
|
||||
function persistIntent() {
|
||||
try {
|
||||
if(armed) sessionStorage.setItem(INTENT_KEY,JSON.stringify({enabled:true,mode:mode?.value || 'all',
|
||||
quizOnly,autoQuiz:autoQuiz?.checked!==false,used:[...recoveryUsed]}));
|
||||
else sessionStorage.removeItem(INTENT_KEY);
|
||||
} catch { /* Run remains active in this page if session storage is unavailable. */ }
|
||||
}
|
||||
function park(message = '等待页面恢复。', {passive=false}={}) {
|
||||
running = false; ++runNumber;
|
||||
const video = active?.video;
|
||||
active = null;
|
||||
@@ -188,7 +208,12 @@
|
||||
try { sessionStorage.removeItem(RESUME_KEY); } catch {}
|
||||
if (video && !video.paused) video.pause();
|
||||
restoreVisibilityHandling();
|
||||
releaseLease(); show(message);
|
||||
waiting=armed?{message,passive,signature:workSignature(),nextAt:Date.now()+15000}:null;
|
||||
releaseLease(); show(armed?`已启动 · 等待处理:${message}`:message);
|
||||
}
|
||||
function stop() {
|
||||
armed=false; waiting=null; persistIntent();
|
||||
park('已人工取消自动运行。');
|
||||
}
|
||||
function safeCourse(c) {
|
||||
if (!c || typeof c.id !== 'string') return null;
|
||||
@@ -198,10 +223,10 @@
|
||||
if (!meta) return;
|
||||
if (meta.kind) return receiveQuiz(meta, response, httpStatus);
|
||||
const relevant = meta.id === route(location.hash).id || meta.id === 'packages';
|
||||
if (relevant && running && (httpStatus === 401 || httpStatus === 403)) return stop('登录状态失效或无权限,请重新登录后刷新。');
|
||||
if (relevant && running && (httpStatus === 401 || httpStatus === 403)) return park('登录状态失效或无权限,请重新登录后刷新。');
|
||||
if (!response || typeof response !== 'object' || response.bizCode === undefined) return;
|
||||
if (response.bizCode !== 0) {
|
||||
if (running && relevant) stop(`平台未接受操作(${response.bizCode}):${response.message || '请查看页面提示'}`);
|
||||
if (running && relevant) park(`平台未接受操作(${response.bizCode}):${response.message || '请查看页面提示'}`);
|
||||
return;
|
||||
}
|
||||
const data = response.data;
|
||||
@@ -289,7 +314,7 @@
|
||||
localStorage.setItem(BANK_KEY, JSON.stringify(bank));
|
||||
if (lastExam) localStorage.setItem(SNAPSHOT_KEY, JSON.stringify(lastExam));
|
||||
return true;
|
||||
} catch { if (running) stop('答案记忆保存失败,请检查浏览器本地存储空间。'); return false; }
|
||||
} catch { if (running) park('答案记忆保存失败,请检查浏览器本地存储空间。'); return false; }
|
||||
}
|
||||
function savedAnswersMatch(snapshot, body) {
|
||||
if (!Array.isArray(body?.answers) || body.answers.length !== snapshot.questions.length) return false;
|
||||
@@ -309,7 +334,7 @@
|
||||
exams.get(id)?.examId === meta.examId;
|
||||
if (!relevant) return;
|
||||
if (httpStatus === 401 || httpStatus === 403 || (response?.bizCode !== undefined && response.bizCode !== 0)) {
|
||||
if (running) stop(`测验操作失败:${response?.message || '登录状态或权限异常'}`); return;
|
||||
if (running) park(`测验操作失败:${response?.message || '登录状态或权限异常'}`); return;
|
||||
}
|
||||
if (response?.bizCode !== 0) return;
|
||||
const data = response.data;
|
||||
@@ -365,10 +390,10 @@
|
||||
}
|
||||
function quizWait(message, timeout = 25000) {
|
||||
show(message);
|
||||
if (Date.now() - quiz.since > waitLimit(timeout)) stop('测验页面未在预期时间内响应。已保留答案记忆,请检查网页后继续。');
|
||||
if (Date.now() - quiz.since > waitLimit(timeout)) park('测验页面未在预期时间内响应。已保留答案记忆,请检查网页后继续。');
|
||||
}
|
||||
function tickQuiz(id) {
|
||||
if (autoQuiz && !autoQuiz.checked && !quizOnly) return stop('自动测验已关闭,请开启后继续。');
|
||||
if (autoQuiz && !autoQuiz.checked && !quizOnly) return park('自动测验已关闭,请开启后继续。');
|
||||
if (!quiz || quiz.courseId !== id) quiz = {courseId:id,phase:'idle',since:Date.now(),round:0};
|
||||
const root = document.querySelector('.course-quiz');
|
||||
if (!root) return quizWait('等待课程测验区域加载…');
|
||||
@@ -379,17 +404,23 @@
|
||||
const course = details.get(id)?.course;
|
||||
if (course) course.examPassed = true;
|
||||
const percent = result.querySelector('.quiz-result__score strong')?.textContent.trim();
|
||||
log(`测验已合格(${percent || '平台确认'})。`);
|
||||
if (quizOnly) return stop(`测验已合格(${percent || '平台确认'}),答案已按可用反馈保存。`);
|
||||
quiz = null; return;
|
||||
const score=percent && /^\d+(\.\d+)?%$/.test(percent) ? Number(percent.replace('%','')) : course?.examScorePercent;
|
||||
if(course && score!==undefined) course.examScorePercent=score;
|
||||
if(Number(score)===100) {
|
||||
log('测验已达到100%,允许继续。');
|
||||
if(quizOnly) return park('本门测验已达到100%,保持已启动,等待后续操作。',{passive:true});
|
||||
quiz=null; return;
|
||||
}
|
||||
// A lower platform pass mark does not satisfy the user's 100% gate.
|
||||
if(!quizButton(root,'重新测验')) return park(`当前正确率${score ?? '未知'}%,等待重考入口;达到100%前不切换视频或课程。`);
|
||||
}
|
||||
if (quiz.phase === 'opening' || quiz.phase === 'retrying') return quizWait('正在打开测验…');
|
||||
const exam = exams.get(id);
|
||||
if (exam?.canRetry === false || exam?.attemptsExhausted || root.querySelector('.quiz-result__exhausted'))
|
||||
return stop('平台答题次数已用完,已保留答案记忆。');
|
||||
return park('平台答题次数已用完,已保留答案记忆。');
|
||||
const retry = quizButton(root, '重新测验');
|
||||
if (!retry) return stop('本次未合格,但页面没有可用的重新测验按钮。');
|
||||
if (++quiz.round > 256) return stop('本轮重试达到256次,已暂停,请检查是否存在无法判断的题目。');
|
||||
if (!retry) return park('等待重新测验入口出现后继续重考。');
|
||||
++quiz.round;
|
||||
quiz.phase='retrying'; quiz.since=Date.now(); quiz.plan=null;
|
||||
retry.click(); show('未合格,读取上次逐题反馈后重新作答…'); return;
|
||||
}
|
||||
@@ -418,7 +449,7 @@
|
||||
const option=questions.find(q=>q.id===pending.id)?.options.find(o=>o.key===pending.key);
|
||||
if (option?.selected===pending.want) quiz.lastClick=null;
|
||||
else {
|
||||
if(Date.now()-pending.at>waitLimit(8000)) stop('选项点击后没有生效,已暂停,请检查页面。');
|
||||
if(Date.now()-pending.at>waitLimit(8000)) park('选项点击后没有生效,已暂停,请检查页面。');
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -426,24 +457,24 @@
|
||||
const planned = [];
|
||||
for (const q of questions) {
|
||||
if (q.unsupported || !q.title || !q.id || q.options.some(o => !o.key))
|
||||
return stop('本卷包含图片、材料题、填空或问答题,需要手动作答;已保留其他答案记忆。');
|
||||
return park('本卷包含图片、材料题、填空或问答题,需要手动作答;已保留其他答案记忆。');
|
||||
const key = questionKey(q);
|
||||
const seed = VERIFIED_ANSWERS.find(a => normalize(a.question) === normalize(q.title));
|
||||
if (!bank[key] && seed && q.type === 'single' && q.options.some(o => normalize(o.text) === normalize(seed.answerText)))
|
||||
bank[key] = {correct:[normalize(seed.answerText)],wrong:[]};
|
||||
const choice = chooseAnswer(q, bank[key]);
|
||||
if (!choice) return stop('某题的可用选项已全部尝试,或选项无法唯一识别,请人工核对。');
|
||||
if (!choice) return park('某题的可用选项已全部尝试,或选项无法唯一识别,请人工核对。');
|
||||
planned.push(pureQuestion(q, choice));
|
||||
}
|
||||
const signature = qs => JSON.stringify(qs.map(q => [questionKey(q),selectionKey(q.chosen)]).sort());
|
||||
if (lastExam?.courseId === id && lastExam.submitted && signature(lastExam.questions) === signature(planned))
|
||||
return stop('未取得能改变答案的逐题反馈,已暂停,避免反复提交同一份答案。');
|
||||
return park('未取得能改变答案的逐题反馈,已暂停,避免反复提交同一份答案。');
|
||||
quiz.plan = planned; quiz.phase='answering'; quiz.since=Date.now();
|
||||
show(`自动作答:共 ${questions.length} 题,优先使用已确认答案。`);
|
||||
}
|
||||
for (const planned of quiz.plan) {
|
||||
const q = questions.find(q => q.id === planned.id);
|
||||
if (!q || questionKey(q) !== questionKey(planned)) return stop('作答过程中题目发生变化,已暂停。');
|
||||
if (!q || questionKey(q) !== questionKey(planned)) return park('作答过程中题目发生变化,已暂停。');
|
||||
for (const option of q.options) {
|
||||
const want = planned.chosen.includes(normalize(option.text));
|
||||
if (q.type === 'single' ? want && !option.selected : want !== option.selected) {
|
||||
@@ -452,9 +483,10 @@
|
||||
}
|
||||
}
|
||||
if (selectionKey(q.options.filter(o => o.selected).map(o => o.text)) !== selectionKey(planned.chosen))
|
||||
return stop('页面选项状态与计划不一致,已暂停。');
|
||||
return park('页面选项状态与计划不一致,已暂停。');
|
||||
}
|
||||
const submit = root.querySelector('button.quiz-footer__submit');
|
||||
// Desktop uses the side answer-card button; the mobile footer is hidden there.
|
||||
const submit = quizButton(root,'交卷');
|
||||
if (!visible(submit) || submit.disabled) return quizWait('等待交卷按钮可用…');
|
||||
lastExam = {courseId:id,examId:exam.examId,paperId:exam.paperId,questions:quiz.plan,
|
||||
answersSaved:false,submitted:false};
|
||||
@@ -464,7 +496,7 @@
|
||||
|
||||
function goBack(forVerification) {
|
||||
const back = document.querySelector('.van-nav-bar__left');
|
||||
if (!back) return stop('找不到返回列表按钮,请手动返回课程列表后继续。');
|
||||
if (!back) return park('找不到返回列表按钮,请手动返回课程列表后继续。');
|
||||
if (forVerification) verifyAfterBack = route(location.hash).id;
|
||||
mustObservePackagesAfter = Date.now();
|
||||
navigatingUntil = Date.now() + 20000;
|
||||
@@ -475,24 +507,24 @@
|
||||
}
|
||||
function tickList() {
|
||||
if (!packagesAt || packagesAt < mustObservePackagesAfter) {
|
||||
if (Date.now() - routeSince > waitLimit(25000)) stop('未收到新的课程列表数据,请刷新页面后开始。');
|
||||
if (Date.now() - routeSince > waitLimit(25000)) park('未收到新的课程列表数据,请刷新页面,助手会自动接续。');
|
||||
return;
|
||||
}
|
||||
if (verifyAfterBack) {
|
||||
const previous = courses.find(c => c.id === verifyAfterBack);
|
||||
if (!courseDone(previous)) return stop('视频已播完,但平台尚未确认整门课程完成。请查看课程状态后继续。');
|
||||
if (!courseDone(previous)) return park('视频已播完,但平台尚未确认整门课程完成。请查看课程状态后继续。');
|
||||
log('平台已确认上一门课程完成。'); verifyAfterBack = null;
|
||||
}
|
||||
const cards = [...document.querySelectorAll('article.course-row')].filter(visible)
|
||||
.map(el => ({el, title: el.querySelector('.course-row__title')?.textContent}));
|
||||
if (!cards.length) {
|
||||
if (Date.now() - routeSince > waitLimit(25000)) stop('没有找到课程列表,请检查是否已登录。');
|
||||
if (Date.now() - routeSince > waitLimit(25000)) park('没有找到课程列表,请检查是否已登录。');
|
||||
return;
|
||||
}
|
||||
const mapped = resolveCards(cards, courses);
|
||||
if (mapped.some(x => !x.course)) return stop('课程名称重复或列表结构发生变化,请进入具体课程后选择“仅当前课程”。');
|
||||
if (mapped.some(x => !x.course)) return park('课程名称重复或列表结构发生变化,请进入具体课程后选择“仅当前课程”。');
|
||||
const next = mapped.find(x => !courseDone(x.course));
|
||||
if (!next) return stop('当前显示的课程均已由平台确认完成。');
|
||||
if (!next) return park('当前显示的课程均已由平台确认完成。');
|
||||
expectedCourse = next.course.id;
|
||||
details.delete(expectedCourse);
|
||||
navigatingUntil = Date.now() + 20000;
|
||||
@@ -502,12 +534,13 @@
|
||||
}
|
||||
function recoverMedia(id, resourceId, reason) {
|
||||
const key = `${id}/${resourceId}`;
|
||||
if (recoveryUsed.has(key)) return stop(`${reason},自动恢复一次后仍失败,请检查网络并手动刷新。`);
|
||||
if (recoveryUsed.has(key)) return park(`${reason},自动恢复一次后仍失败,请检查网络并手动刷新。`);
|
||||
recoveryUsed.add(key);
|
||||
persistIntent();
|
||||
try {
|
||||
sessionStorage.setItem(RESUME_KEY, JSON.stringify({hash:location.hash, expires:Date.now()+120000,
|
||||
mode:mode.value, autoQuiz:autoQuiz?.checked !== false, used:[...recoveryUsed]}));
|
||||
} catch { return stop(`${reason},无法保存恢复状态,请手动刷新后继续。`); }
|
||||
} catch { return park(`${reason},无法保存恢复状态,请手动刷新后继续。`); }
|
||||
// The website tears down its old session and fetches fresh media on reload.
|
||||
// Only this explicit recovery reload resumes; ordinary refreshes stay paused.
|
||||
running=false; ++runNumber;
|
||||
@@ -540,14 +573,20 @@
|
||||
return Date.now()-load.settledAt>=1000;
|
||||
}
|
||||
async function tickCourse(id) {
|
||||
if (expectedCourse && expectedCourse !== id) return stop('打开的课程与选定课程不一致,已暂停。');
|
||||
if (expectedCourse && expectedCourse !== id) return park('打开的课程与选定课程不一致,已暂停。');
|
||||
expectedCourse = null;
|
||||
const detail = details.get(id);
|
||||
if (!detail) {
|
||||
if (Date.now() - routeSince > waitLimit(20000)) stop('未捕获课程详情。安装后请刷新学习页,再点击开始。');
|
||||
if (Date.now() - routeSince > waitLimit(20000)) park('未捕获课程详情,请刷新学习页,助手会自动接续。');
|
||||
return;
|
||||
}
|
||||
const plan = videoPlan(detail);
|
||||
if(detail.course.examRequired && !examPerfect(detail.course)) {
|
||||
const gatedVideo=active?.video || currentVideo();
|
||||
if(gatedVideo && !gatedVideo.paused) gatedVideo.pause();
|
||||
active=null;
|
||||
return tickQuiz(id);
|
||||
}
|
||||
// 正在播放的资源自然结束后再切换,即便平台提前返回 completed。
|
||||
if (active && active.courseId === id && !active.video.ended) return monitor();
|
||||
if (active?.video.ended) {
|
||||
@@ -555,27 +594,27 @@
|
||||
active.endedAt ||= Date.now();
|
||||
if (resource?.completed !== true) {
|
||||
show('视频已结束,等待平台确认保存…');
|
||||
if (Date.now() - active.endedAt > waitLimit(25000)) stop('平台尚未确认视频完成,请返回列表核对后再继续。');
|
||||
if (Date.now() - active.endedAt > waitLimit(25000)) park('平台尚未确认视频完成,请返回列表核对后再继续。');
|
||||
return;
|
||||
}
|
||||
log('平台已确认本段视频完成。'); active = null;
|
||||
}
|
||||
if (plan.kind === 'manual') return stop('下一项不是视频,请在页面中完成该学习资源后继续。');
|
||||
if (plan.kind === 'manual') return park('下一项不是视频,请在页面中完成该学习资源后继续。');
|
||||
if (plan.kind === 'quiz' || quiz?.courseId === id) return tickQuiz(id);
|
||||
if (plan.kind === 'finish') {
|
||||
if (mode.value === 'current') return stop('本门视频及测验条件已满足;请返回列表核对最终完成状态。');
|
||||
if (mode.value === 'current') return park('本门视频及测验条件已满足;请返回列表核对最终完成状态。');
|
||||
return goBack(true);
|
||||
}
|
||||
if (plan.kind !== 'video') return;
|
||||
const resource = plan.resource;
|
||||
const buttons = [...document.querySelectorAll('button.resource-item')];
|
||||
const matches = buttons.filter(b => normalize(b.querySelector('.resource-item__title')?.textContent) === normalize(resource.name));
|
||||
if (matches.length !== 1) return stop('未能唯一识别下一段视频,请手动选择后检查页面。');
|
||||
if (matches.length !== 1) return park('未能唯一识别下一段视频,请手动选择后检查页面。');
|
||||
const button = matches[0];
|
||||
if (!button.classList.contains('is-active')) {
|
||||
if (button.disabled || resource.playable === false) return stop('下一段视频尚未解锁,请按平台提示完成前置学习。');
|
||||
if (button.disabled || resource.playable === false) return park('下一段视频尚未解锁,请按平台提示完成前置学习。');
|
||||
if (resourceSwitch?.id === resource.id) {
|
||||
if (Date.now() - resourceSwitch.at > waitLimit(20000)) stop('切换视频没有成功,请手动选择该视频后继续。');
|
||||
if (Date.now() - resourceSwitch.at > waitLimit(20000)) park('切换视频没有成功,请手动选择该视频后继续。');
|
||||
return;
|
||||
}
|
||||
resourceSwitch = {id: resource.id, at: Date.now(),previousVideo:currentVideo(),previousSrc:currentVideo()?.currentSrc};
|
||||
@@ -594,7 +633,7 @@
|
||||
mediaLoad=null;
|
||||
lastNetworkAt = Date.now();
|
||||
video.playbackRate = 2;
|
||||
if (Math.abs(video.playbackRate - 2) > 0.01) return stop('播放器未接受2倍速,请检查页面倍速设置。');
|
||||
if (Math.abs(video.playbackRate - 2) > 0.01) return park('播放器未接受2倍速,请检查页面倍速设置。');
|
||||
attemptPlay(active,run);
|
||||
if(running) show(`正在启动2倍速播放:${resource.name}`);
|
||||
}
|
||||
@@ -604,7 +643,7 @@
|
||||
const failed=error => {
|
||||
if(!running || run!==runNumber || active!==a) return;
|
||||
a.playPending=false;
|
||||
if(error?.name==='NotAllowedError') return stop('浏览器阻止自动播放,请手动点击网页“点击播放”,然后点助手继续。');
|
||||
if(error?.name==='NotAllowedError') return park('浏览器阻止自动播放,请手动点击网页“点击播放”,助手会自动接续。');
|
||||
if(error?.name!=='AbortError') recoverMedia(a.courseId,a.id,'播放启动失败');
|
||||
// AbortError commonly means the website is replacing the media source.
|
||||
};
|
||||
@@ -617,7 +656,7 @@
|
||||
const a = active, v = a.video;
|
||||
const resource=details.get(a.courseId)?.resources.find(r=>r.id===a.id);
|
||||
const selected=document.querySelector('button.resource-item.is-active .resource-item__title');
|
||||
if(selected && normalize(selected.textContent)!==normalize(resource?.name)) return stop('视频已被手动切换,点击开始可继续。');
|
||||
if(selected && normalize(selected.textContent)!==normalize(resource?.name)) return park('视频已被手动切换,等待页面稳定后继续。');
|
||||
if (!v.isConnected || currentVideo() !== v || v.currentSrc !== a.src) {
|
||||
active=null; mediaLoad=null; show('播放器正在重建,等待新视频就绪…'); return;
|
||||
}
|
||||
@@ -630,35 +669,44 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (Math.abs(v.playbackRate - 2) > 0.01) return stop('播放器改变了倍速,已暂停;请检查是否仍有诊断脚本在运行。');
|
||||
if (v.paused && !v.ended) return stop('视频已暂停;点击助手开始可继续。');
|
||||
if (Math.abs(v.playbackRate - 2) > 0.01) return park('播放器改变了倍速,已暂停;请检查是否仍有诊断脚本在运行。');
|
||||
if (v.paused && !v.ended) return park('视频已手动暂停;点击视频播放可继续,或点人工取消关闭助手。',{passive:true});
|
||||
if (v.currentTime > a.lastPosition + 0.1) { a.progressedAt = Date.now(); a.lastPosition = v.currentTime; }
|
||||
if (Date.now() - a.progressedAt > waitLimit(60000)) return recoverMedia(a.courseId,a.id,'视频长时间没有推进');
|
||||
const saveTimeout=waitLimit(75000);
|
||||
if (Date.now()>foregroundGraceUntil && Date.now()-lastNetworkAt>saveTimeout)
|
||||
return stop(`超过${saveTimeout/1000}秒未收到平台保存确认,已暂停,避免继续播放却未计入进度。`);
|
||||
return park(`超过${saveTimeout/1000}秒未收到平台保存确认,已暂停,避免继续播放却未计入进度。`);
|
||||
}
|
||||
async function tick() {
|
||||
if (!running || busy) return;
|
||||
if(busy || !armed) return;
|
||||
if(!running) {
|
||||
if(!waiting) return;
|
||||
const changed=waiting.signature!==workSignature();
|
||||
if(!changed && (waiting.passive || Date.now()<waiting.nextAt)) return;
|
||||
if(!holdLease()) { waiting.nextAt=Date.now()+15000; return; }
|
||||
waiting=null;running=true;routeSince=Date.now();mediaLoad=null;
|
||||
if(quiz) quiz.since=Date.now();
|
||||
show('已启动 · 自动检查并继续…');
|
||||
}
|
||||
busy = true;
|
||||
try {
|
||||
if (!holdLease()) return stop('另一个学习页正在使用助手,或浏览器禁止本地存储。');
|
||||
if (!holdLease()) return park('另一个学习页正在使用助手,或浏览器禁止本地存储。');
|
||||
if (Date.now() - startAt < 600) return;
|
||||
if (location.hash !== lastHash) {
|
||||
const destination=route(location.hash);
|
||||
const expected=courseNavigationPending && (expectedCourse ? destination.id===expectedCourse : destination.list);
|
||||
lastHash = location.hash; routeSince = Date.now(); active = null; navigatingUntil = 0;
|
||||
courseNavigationPending = false; resourceSwitch = null;
|
||||
if (!expected) return stop('页面已被手动切换;点击开始可继续。');
|
||||
if (!expected) { quiz=null; expectedCourse=null; show('已启动 · 页面已切换,继续检查当前课程。'); }
|
||||
}
|
||||
if (navigatingUntil > Date.now()) return;
|
||||
if (courseNavigationPending) return stop('课程页面跳转没有成功,请手动打开课程后继续。');
|
||||
if (courseNavigationPending) return park('课程页面跳转没有成功,请手动打开课程后继续。');
|
||||
const here = route(location.hash);
|
||||
if (here.list) tickList();
|
||||
else if (here.id) { if (quizOnly) tickQuiz(here.id); else await tickCourse(here.id); }
|
||||
else stop('请打开“我的课程”列表或课程学习页。');
|
||||
else park('请打开“我的课程”列表或课程学习页。');
|
||||
render();
|
||||
} catch { stop('页面结构或播放操作出现异常,请刷新页面后重试。'); }
|
||||
} catch { park('页面结构或播放操作出现异常,请刷新页面后重试。'); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
function render() {
|
||||
@@ -669,11 +717,12 @@
|
||||
panel.querySelector('[data-progress]').textContent = v
|
||||
? `实际 ${v.playbackRate.toFixed(1)}倍 · ${Math.floor(v.currentTime / 60)}:${String(Math.floor(v.currentTime % 60)).padStart(2, '0')} / ${Math.floor(v.duration / 60)}:${String(Math.floor(v.duration % 60)).padStart(2, '0')}\n平台进度 ${course?.progressPercent ?? '待确认'}% · ${active.saved ? '已收到保存确认' : '等待保存确认'}`
|
||||
: '以平台保存结果为准;电脑需保持唤醒。';
|
||||
panel.querySelector('[data-start]').disabled = running;
|
||||
panel.querySelector('[data-quiz-only]').disabled = running;
|
||||
panel.querySelector('[data-start]').disabled = armed;
|
||||
panel.querySelector('[data-start]').textContent = armed ? (running?'已启动 · 运行中':'已启动 · 等待恢复') : '开始';
|
||||
panel.querySelector('[data-quiz-only]').disabled = armed;
|
||||
panel.querySelector('[data-background-state]').textContent = backgroundEnabled
|
||||
? `${isHidden()?'后台':'前台'} · 切标签页继续播放已开启` : '后台模式已关闭';
|
||||
mode.disabled = running;
|
||||
mode.disabled = armed;
|
||||
}
|
||||
function mount() {
|
||||
if (!document.body) return;
|
||||
@@ -681,14 +730,14 @@
|
||||
host.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:2147483646';
|
||||
panel = host.attachShadow({mode: 'open'});
|
||||
panel.innerHTML = `<style>:host{font:14px/1.6 system-ui;color:#eaf0fa}section{width:290px;background:#17243a;border:1px solid #6883a6;border-radius:12px;padding:15px;box-shadow:0 5px 24px #0005}strong{font-size:16px}p{margin:9px 0;white-space:pre-line}small{color:#b7c7df}button,select{font:inherit;border-radius:6px;border:1px solid #7186a5;padding:5px 9px;margin:3px 5px 3px 0}button{cursor:pointer;background:#dbeaff;color:#123}button:disabled{opacity:.5;cursor:default}select{width:100%;background:#fff;color:#123}[data-status]{min-height:45px}details{margin-top:8px}pre{white-space:pre-wrap;max-height:160px;overflow:auto;font-size:12px}</style>
|
||||
<section><strong>2倍速学习助手 · 1.2.0</strong><p data-status></p><small data-progress></small>
|
||||
<section><strong>2倍速学习助手 · 1.3.0</strong><p data-status></p><small data-progress></small>
|
||||
<select aria-label="播放范围"><option value="all">按列表顺序继续课程</option><option value="current">仅当前课程</option></select>
|
||||
<div><button data-start>开始 / 继续</button><button data-stop>暂停</button></div>
|
||||
<label><input type="checkbox" data-quiz checked> 视频完成后自动做测验</label>
|
||||
<div><button data-start>开始</button><button data-stop>人工取消</button></div>
|
||||
<label><input type="checkbox" data-quiz checked> 自动测验,达到100%才继续</label>
|
||||
<div><label><input type="checkbox" data-background> 切标签页继续播放</label></div>
|
||||
<small data-background-state></small>
|
||||
<div><button data-quiz-only>只做本门测验</button></div>
|
||||
<small>错题根据平台反馈重试;合格后平台可能不允许重考。</small>
|
||||
<small>启动后持续运行与等待;只有人工取消才关闭。测验100%后继续视频。</small>
|
||||
<details><summary>运行记录</summary><pre></pre><button data-copy>更新记录</button></details></section>`;
|
||||
mode = panel.querySelector('select');
|
||||
autoQuiz = panel.querySelector('[data-quiz]');
|
||||
@@ -697,11 +746,12 @@
|
||||
backgroundToggle.onchange=()=>setBackgroundEnabled(backgroundToggle.checked);
|
||||
function beginRun(only, resume) {
|
||||
if (only && !route(location.hash).id) return show('请先进入需要作答的课程学习页。');
|
||||
if (!holdLease()) return show('另一个学习页正在运行助手,或本地存储不可用。请先暂停另一个页面。');
|
||||
if (only) currentVideo()?.pause();
|
||||
quizOnly=only; quiz=null;
|
||||
mediaLoad=null; recoveryUsed=new Set(resume?.used || []);
|
||||
running = true; ++runNumber; active = null; expectedCourse = null; verifyAfterBack = null;
|
||||
armed=true; waiting=null; persistIntent();
|
||||
if(!holdLease()) return park('另一个学习页正在运行,等待其释放控制权。');
|
||||
startAt = routeSince = Date.now(); lastHash = location.hash; navigatingUntil = 0;
|
||||
courseNavigationPending = false; resourceSwitch = null;
|
||||
show('已开始,正在核对课程与平台数据…'); void tick();
|
||||
@@ -709,6 +759,7 @@
|
||||
panel.querySelector('[data-start]').onclick = () => beginRun(false);
|
||||
panel.querySelector('[data-quiz-only]').onclick = () => beginRun(true);
|
||||
panel.querySelector('[data-stop]').onclick = () => stop();
|
||||
autoQuiz.onchange=()=>{persistIntent();if(waiting)waiting.nextAt=0;};
|
||||
panel.querySelector('[data-copy]').onclick = () => { panel.querySelector('pre').textContent = logs.map(x => `${x.time} ${x.message}`).join('\n'); };
|
||||
document.body.append(host); render();
|
||||
try {
|
||||
@@ -717,10 +768,16 @@
|
||||
if(resume?.hash===location.hash && resume.expires>Date.now() && Array.isArray(resume.used) && resume.used.length<=100) {
|
||||
mode.value=resume.mode==='current'?'current':'all'; autoQuiz.checked=resume.autoQuiz!==false;
|
||||
beginRun(false,resume);
|
||||
} else {
|
||||
const intent=JSON.parse(sessionStorage.getItem(INTENT_KEY) || 'null');
|
||||
if(intent?.enabled && Array.isArray(intent.used)) {
|
||||
mode.value=intent.mode==='current'?'current':'all';autoQuiz.checked=intent.autoQuiz!==false;
|
||||
beginRun(!!intent.quizOnly,intent);
|
||||
}
|
||||
}
|
||||
} catch { /* Ordinary reload or invalid checkpoint: wait for the user. */ }
|
||||
} catch { /* Invalid stored settings: wait for an explicit start. */ }
|
||||
}
|
||||
window.addEventListener('storage', e => { if (e.key === LEASE_KEY && running && readLease()?.owner !== owner) stop('其他学习页接管了助手,本页已暂停。'); });
|
||||
window.addEventListener('storage', e => { if (e.key === LEASE_KEY && running && readLease()?.owner !== owner) park('其他学习页接管了助手,本页已暂停。'); });
|
||||
window.addEventListener('pagehide', () => { running = false; releaseLease(); });
|
||||
if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount, {once: true});
|
||||
setInterval(() => { void tick(); }, 1000);
|
||||
|
||||
Reference in New Issue
Block a user