// ==UserScript== // @name 学习通课程任务助手 // @namespace local.chaoxing.course.helper // @version 1.6.0 // @description 本地待办任务助手,支持完成识别、媒体故障恢复、单视频顺序执行和本地题库 // @author JXY // @license MIT // @homepage https://scriptcat.org/ // @supportURL https://scriptcat.org/ // @match *://chaoxing.com/* // @match *://*.chaoxing.com/* // @match *://xueyinonline.com/* // @match *://*.xueyinonline.com/* // @grant GM_getValue // @grant GM_setValue // @grant GM_addValueChangeListener // @grant GM_registerMenuCommand // @grant unsafeWindow // @run-at document-idle // ==/UserScript== (function () { 'use strict'; const MESSAGE_TYPE = 'cx-course-helper-worker-v1'; const PAGE_WINDOW = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const IS_TOP = PAGE_WINDOW.top === PAGE_WINDOW; const IS_DIRECT_CHILD = !IS_TOP && PAGE_WINDOW.parent === PAGE_WINDOW.top; const FRAME_PATH = (() => { const path = []; let current = PAGE_WINDOW; try { while (current !== current.top) { const parent = current.parent; let frameIndex = -1; for (let index = 0; index < parent.frames.length; index += 1) { if (parent.frames[index] === current) { frameIndex = index; break; } } path.unshift(frameIndex < 0 ? Number.MAX_SAFE_INTEGER : frameIndex); current = parent; } } catch (_) { path.unshift(Number.MAX_SAFE_INTEGER); } return path; })(); let controllerActive = IS_TOP; let parentControllerSeen = IS_TOP; let controllerMenuRegistered = false; const WORKER_ID = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; const STORE = { enabled: 'cx_helper_enabled', speed: 'cx_helper_speed', autoJump: 'cx_helper_auto_jump', bank: 'cx_helper_bank', unanswered: 'cx_helper_unanswered', logs: 'cx_helper_logs', todos: 'cx_helper_todos', scanSession: 'cx_helper_scan_session', lastAutoScanAt: 'cx_helper_last_auto_scan_at', queuePaused: 'cx_helper_queue_paused' }; const CONFIG = { defaultSpeed: 1, interval: 1000, workerTtl: 6500, mediaStallThreshold: Number(PAGE_WINDOW.__XXT_TEST_MEDIA_STALL_MS__) || 30000, mediaRetryLimit: Number(PAGE_WINDOW.__XXT_TEST_MEDIA_RETRY_LIMIT__) || 3, navigationCooldown: 8000, completionStableTime: 2500, detailPageDelay: 1800, scanCatalogStableTime: 550, scanEmptyTimeout: 4500, scanNavigationDelay: 60, scanRetryLimit: 1, scanRetryDelay: 350, scanExpandBatch: 8, scanExpandMaxClicks: 80, scanLoadMoreMaxClicks: 12, scanLazyLoadSettleTime: 900, selectors: { questions: ['.TiMu', '.questionLi', '.quesItem', '.ans-ques'], optionGroups: [ '.Zy_ulTop > li', '.answerList > li', '.answerOption', '.option-item', 'label:has(input[type="radio"])', 'label:has(input[type="checkbox"])' ], textInputs: ['input[type="text"]', 'textarea'], submit: [ 'button.submitBtn', '.submitBtn', '.answer-submit', 'button[data-action="submit"]', 'button[type="submit"]' ], next: [ 'button.nextChapter', 'a.nextChapter', '.next-btn', 'button[title*="下一节"]', 'a[title*="下一节"]', 'button[aria-label*="下一"]', 'a[aria-label*="下一"]' ], currentCatalog: [ '.posCatalog_select', '.catalog_points .curr', '.chapter_unit .curr', '.catalog_level .curr', '.ncells .curr', '[aria-current="true"]' ], completed: [ '.completed', '.finish', '.finished', '.jobFinish', '.icon_Completed', '.ans-job-finished', '[data-status="completed"]', '[title*="已完成"]' ], incomplete: [ '.jobUnfinish', '.unfinished', '.icon-unfinish', '[data-status="unfinished"]', '[title*="未完成"]' ] } }; const COURSE_TEMPLATES = { 'chaoxing-new': { detect: ['#courseChapter', '.course-card', '.courseItem', '.course-item'], courseLinks: ['.course-card a[href]', '.courseItem a[href]', '.course-item a[href]'], courseCards: ['.course-card', '.courseItem', '.course-item', '.course_item'], catalog: ['#courseChapter .chapter_item a[href]', '#courseChapter [onclick*="chapter"]', '.chapter_item .catalog_name'], expand: ['#courseChapter [aria-expanded="false"]', '#courseChapter .chapter_unit', '#courseChapter .chapterText', '.chapter_item > .chapterText'], loadMore: ['#courseChapter button', '#courseChapter a', '[data-action="load-more"]'] }, 'chaoxing-legacy': { detect: ['.chapter_unit', '.catalog_level', '.ncells', '.Mconright'], courseLinks: ['.Mconright a[href]', 'li a[href*="courseId="]'], courseCards: ['.Mconright', 'li', 'article'], catalog: ['.chapter_unit a[href*="studentstudy"]', '.catalog_level a[href*="studentstudy"]', '.ncells a[href]'], expand: ['.chapter_unit', '.catalog_level [aria-expanded="false"]', '.catalog_level > .chapterText'], loadMore: ['.catalog_level button', '.catalog_level a', '.ncells button', '.ncells a'] }, 'portal-iframe': { detect: [], courseLinks: ['a[href*="courseId="]', 'a[href*="clazzid="]', 'a[href*="/mycourse/"]'], courseCards: ['.course-card', '.courseItem', '.Mconright', 'li', 'article'], catalog: ['#courseChapter .chapter_item a[href]', '.chapter_unit a[href*="studentstudy"]', '.catalog_level a[href*="studentstudy"]', '.ncells a[href]'], expand: ['#courseChapter [aria-expanded="false"]', '#courseChapter .chapterText', '.chapter_unit', '.catalog_level [aria-expanded="false"]'], loadMore: ['#courseChapter button', '#courseChapter a', '.catalog_level button', '.catalog_level a'] }, xueyin: { detect: ['.catalog_points', '.posCatalog_name'], courseLinks: ['a[href*="courseId="]', 'a[href*="clazzid="]', 'a[href*="/mycourse/"]'], courseCards: ['.course-card', '.courseItem', 'li', 'article'], catalog: ['.catalog_points a[href]', '.posCatalog_name', 'a[href*="chapterId"][href*="courseId"]'], expand: ['.catalog_points [aria-expanded="false"]', '.catalog_level [aria-expanded="false"]'], loadMore: ['.catalog_points button', '.catalog_points a', '[data-action="load-more"]'] }, generic: { detect: [], courseLinks: ['a[href*="courseId="]', 'a[href*="courseid="]', 'a[href*="clazzid="]', 'a[href*="/mycourse/"]'], courseCards: ['.courseItem', '.course-item', '.course_item', '.course-card', '.Mconright', 'li', 'article'], catalog: [ '.chapter_unit a[href*="studentstudy"]', '.catalog_level a[href*="studentstudy"]', '.catalog_points a[href]', '.ncells a[href]', '#courseChapter .chapter_item a[href]', '#courseChapter [onclick*="chapter"]', '.chapter_item .catalog_name', 'a[href*="chapterId"][href*="courseId"]', '.posCatalog_name' ], expand: [ '#courseChapter [aria-expanded="false"]', '#courseChapter .chapter_unit', '#courseChapter .chapterText', '.chapter_item > .chapterText', '.catalog_level [aria-expanded="false"]', '.catalog_level > .chapterText', '.catalog_points [aria-expanded="false"]', '[data-action="expand-chapter"]' ], loadMore: [ '#courseChapter button', '#courseChapter a', '.catalog_points button', '.catalog_points a', '.catalog_level button', '.catalog_level a', '[data-action="load-more"]' ] } }; const FALLBACK_PREFIX = 'cx_helper_fallback:'; const storageApi = { get(key, fallback) { try { if (typeof GM_getValue === 'function') return GM_getValue(key, fallback); } catch (error) { console.warn('[XXT] GM_getValue failed, using local storage', error); } try { const raw = localStorage.getItem(`${FALLBACK_PREFIX}${key}`); return raw === null ? fallback : JSON.parse(raw); } catch (_) { return fallback; } }, set(key, value) { try { if (typeof GM_setValue === 'function') { GM_setValue(key, value); return; } } catch (error) { console.warn('[XXT] GM_setValue failed, using local storage', error); } try { localStorage.setItem(`${FALLBACK_PREFIX}${key}`, JSON.stringify(value)); } catch (_) { // Storage can be unavailable in restricted third-party frames. } }, listen(key, callback) { try { if (typeof GM_addValueChangeListener === 'function') { return GM_addValueChangeListener(key, callback); } } catch (error) { console.warn('[XXT] GM_addValueChangeListener failed', error); } return null; }, registerMenu(label, callback) { try { if (typeof GM_registerMenuCommand === 'function') { return GM_registerMenuCommand(label, callback); } } catch (error) { console.warn('[XXT] GM_registerMenuCommand failed', error); } return null; } }; const state = { enabled: toBoolean(storageApi.get(STORE.enabled, true)), speed: clampSpeed(storageApi.get(STORE.speed, CONFIG.defaultSpeed)), autoJump: toBoolean(storageApi.get(STORE.autoJump, true)), bank: loadObject(STORE.bank), bankIndex: new Map(), unanswered: loadObject(STORE.unanswered), todos: loadArray(STORE.todos), scanSession: loadObject(STORE.scanSession), lastAutoScanAt: Number(storageApi.get(STORE.lastAutoScanAt, 0)) || 0, queuePaused: toBoolean(storageApi.get(STORE.queuePaused, false)), scanNavigationAt: 0, scanCatalogSignature: '', scanCatalogStableSince: 0, scanExpansionClicks: 0, scanLoadMoreClicks: 0, scanExpansionActivityAt: 0, scanLastScrollHeight: 0, scanClickedExpanders: new WeakSet(), scanLoadMoreSignatures: new WeakMap(), scanExpansionLimitReached: false, queueNavigationAt: 0, queueFinishedLogged: false, media: new WeakMap(), answeredQuestions: new WeakSet(), submittedQuestions: new WeakSet(), pageSubmitted: false, workers: new Map(), mediaPermit: { workerId: '', index: -1, revision: 0 }, mediaPermitRevision: 0, lastMediaFailureKey: '', panel: null, progressWindow: null, progressOpen: false, todoWindow: null, todoOpen: false, timer: null, running: false, seenWork: false, stableSince: 0, lastNavigation: 0, detailJumpAttempted: false, detailExpandAttempted: false, detailPageEnteredAt: Date.now(), currentTaskKey: '', taskEnteredAt: Date.now(), ignoreWorkerUntil: 0, lastLog: '', lastLogAt: 0, lastError: '' }; function isController() { return controllerActive; } function broadcastToChildren(message) { try { for (let index = 0; index < PAGE_WINDOW.frames.length; index += 1) { PAGE_WINDOW.frames[index].postMessage(message, '*'); } } catch (_) { // Cross-origin frames still accept postMessage when referenced directly. } } function announceController() { if (!isController()) return; broadcastToChildren({ type: MESSAGE_TYPE, kind: 'controller-present' }); } function activateController() { controllerActive = true; parentControllerSeen = true; if (document.body) createPanel(); if (!controllerMenuRegistered) { storageApi.registerMenu('启动/暂停助手', toggleEnabled); storageApi.registerMenu('导入本地题库', importBank); storageApi.registerMenu('导出未匹配题目', exportUnanswered); controllerMenuRegistered = true; } announceController(); } function deactivateController() { if (IS_TOP) return; controllerActive = false; state.panel?.remove(); state.progressWindow?.remove(); state.todoWindow?.remove(); state.panel = null; state.progressWindow = null; state.todoWindow = null; state.progressOpen = false; state.todoOpen = false; state.workers.clear(); } function probeParentController() { if (!IS_DIRECT_CHILD || window.parent === window) return; window.parent.postMessage({ type: MESSAGE_TYPE, kind: 'controller-probe' }, '*'); } rebuildBankIndex(); migrateLegacyUnanswered(); function toBoolean(value) { if (typeof value === 'string') return value === 'true' || value === '1'; return Boolean(value); } function clampSpeed(value) { const number = Number(value); if (!Number.isFinite(number)) return CONFIG.defaultSpeed; return Math.max(0.5, Math.min(16, number)); } function loadObject(key) { const raw = storageApi.get(key, '{}'); try { const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch (_) { return {}; } } function loadArray(key) { const raw = storageApi.get(key, '[]'); try { const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw; return Array.isArray(parsed) ? parsed : []; } catch (_) { return []; } } function saveObject(key, value) { storageApi.set(key, JSON.stringify(value)); } function normalize(value) { return String(value ?? '') .replace(/[\u00a0\r\n\t ]+/g, ' ') .replace(/[“”"'「」『』()()【】\[\]]/g, '') .replace(/^\s*\d+[.、]\s*/, '') .trim() .toLowerCase(); } function rebuildBankIndex() { state.bankIndex = new Map(); Object.entries(state.bank).forEach(([question, answer]) => { if (!question.startsWith('_unanswered:')) { const key = normalize(question); if (key) state.bankIndex.set(key, answer); } }); } function migrateLegacyUnanswered() { let changed = false; Object.keys(state.bank).forEach((key) => { if (!key.startsWith('_unanswered:')) return; const question = key.slice('_unanswered:'.length); if (question && !Object.prototype.hasOwnProperty.call(state.unanswered, question)) { state.unanswered[question] = ''; } delete state.bank[key]; changed = true; }); if (changed) { saveObject(STORE.bank, state.bank); saveObject(STORE.unanswered, state.unanswered); rebuildBankIndex(); } } function isVisible(node) { if (!(node instanceof Element)) return false; const style = getComputedStyle(node); if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false; const rect = node.getBoundingClientRect(); return rect.width > 0 && rect.height > 0; } function queryAllInOrder(selectors, root = document) { if (!selectors.length) return []; try { return Array.from(root.querySelectorAll(selectors.join(','))); } catch (_) { const nodes = []; selectors.forEach((selector) => { try { root.querySelectorAll(selector).forEach((node) => { if (!nodes.includes(node)) nodes.push(node); }); } catch (_) { // Ignore selectors unsupported by an older browser engine. } }); return nodes; } } function firstVisible(selectors, root = document) { return queryAllInOrder(selectors, root).find(isVisible) || null; } function clickElement(node) { if (!(node instanceof Element) || !isVisible(node)) return false; node.scrollIntoView({ block: 'center', behavior: 'auto' }); ['mouseover', 'mousedown', 'mouseup'].forEach((type) => { node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true })); }); node.click(); return true; } function setNativeValue(input, value) { const prototype = input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const descriptor = Object.getOwnPropertyDescriptor(prototype, 'value'); if (descriptor && descriptor.set) descriptor.set.call(input, String(value ?? '')); else input.value = String(value ?? ''); input.dispatchEvent(new Event('input', { bubbles: true })); input.dispatchEvent(new Event('change', { bubbles: true })); } function pushLog(message, force = false) { const now = Date.now(); if (!force && message === state.lastLog && now - state.lastLogAt < 4000) return; state.lastLog = message; state.lastLogAt = now; if (!isController()) { window.parent.postMessage({ type: MESSAGE_TYPE, kind: 'log', message, hops: 0 }, '*'); return; } const line = `${new Date().toLocaleTimeString()} ${message}`; const existing = storageApi.get(STORE.logs, []); const lines = Array.isArray(existing) ? existing : []; storageApi.set(STORE.logs, [line, ...lines].slice(0, 100)); updatePanel(); } function reportError(error) { const message = error instanceof Error ? error.message : String(error); state.lastError = message; pushLog(`运行异常:${message}`, true); } function bindStoreListeners() { storageApi.listen(STORE.enabled, (_name, _old, value) => { state.enabled = toBoolean(value); updatePanel(); }); storageApi.listen(STORE.speed, (_name, _old, value) => { state.speed = clampSpeed(value); updatePanel(); }); storageApi.listen(STORE.autoJump, (_name, _old, value) => { state.autoJump = toBoolean(value); updatePanel(); }); storageApi.listen(STORE.bank, () => { state.bank = loadObject(STORE.bank); rebuildBankIndex(); }); storageApi.listen(STORE.unanswered, () => { state.unanswered = loadObject(STORE.unanswered); }); storageApi.listen(STORE.todos, () => { state.todos = loadArray(STORE.todos); updatePanel(); }); storageApi.listen(STORE.scanSession, () => { state.scanSession = loadObject(STORE.scanSession); updatePanel(); }); storageApi.listen(STORE.queuePaused, (_name, _old, value) => { state.queuePaused = toBoolean(value); updatePanel(); }); } function getQuestionBlocks() { for (const selector of CONFIG.selectors.questions) { const candidates = Array.from(document.querySelectorAll(selector)).filter(isVisible); if (!candidates.length) continue; const blocks = candidates.map((node) => { if (!node.matches('.TiMu')) return node; const ownsAnswerControls = node.querySelector('.Zy_ulTop, .answerList, input, textarea'); return ownsAnswerControls ? node : node.closest('.questionLi, .quesItem, .ans-ques') || node; }); return blocks.filter((node, index) => blocks.indexOf(node) === index && isVisible(node)); } return []; } function getQuestionText(block) { const title = block.querySelector('.Zy_TItle, .quesTitle, .question-title, .mark_name, [data-question-title]'); if (title) return normalize(title.textContent); const clone = block.cloneNode(true); queryAllInOrder(CONFIG.selectors.optionGroups, clone).forEach((node) => node.remove()); queryAllInOrder(CONFIG.selectors.textInputs, clone).forEach((node) => node.remove()); return normalize(clone.textContent).slice(0, 500); } function findAnswer(question) { const key = normalize(question); if (!key) return null; if (state.bankIndex.has(key)) return state.bankIndex.get(key); if (key.length < 6) return null; for (const [candidate, answer] of state.bankIndex.entries()) { if (candidate.length >= 6 && (key.includes(candidate) || candidate.includes(key))) return answer; } return null; } function rememberUnanswered(question) { if (!question || Object.prototype.hasOwnProperty.call(state.unanswered, question)) return; state.unanswered[question] = ''; saveObject(STORE.unanswered, state.unanswered); pushLog(`未匹配题目:${question.slice(0, 36)}`); } function findOptionNodes(block) { for (const selector of CONFIG.selectors.optionGroups) { let nodes = []; try { nodes = Array.from(block.querySelectorAll(selector)).filter(isVisible); } catch (_) { nodes = []; } if (nodes.length) return nodes; } return []; } function optionText(node) { const preferred = node.querySelector('.after, .option-content, .answerText, .clearfix'); const text = normalize((preferred || node).textContent); return text.replace(/^[a-z][.、.]\s*/i, '').trim(); } function optionLetter(node) { const text = normalize(node.textContent); const match = text.match(/^([a-z])[.、.\s]/i); return match ? match[1].toLowerCase() : ''; } function isOptionSelected(node) { const input = node.matches('input') ? node : node.querySelector('input[type="radio"], input[type="checkbox"]'); if (input && input.checked) return true; if (node.getAttribute('aria-checked') === 'true' || node.getAttribute('aria-selected') === 'true') return true; return /(^|\s)(selected|checked|active|on)(\s|$)/i.test(node.className || ''); } function isQuestionCompleted(block) { if (state.submittedQuestions.has(block)) return true; if (block.matches('.completed, .finished, [data-status="completed"]')) return true; return Boolean(firstVisible(['.answerAnalysis', '.analysis', '.Py_answer', '.rightAnswer', '.result-right'], block)); } function answerQuestion(block) { const question = getQuestionText(block); if (isQuestionCompleted(block) || state.answeredQuestions.has(block)) { return { completed: true, pending: false, matched: true }; } const answer = findAnswer(question); if (answer === null || answer === undefined || answer === '') { rememberUnanswered(question); return { completed: false, pending: true, matched: false }; } const answers = (Array.isArray(answer) ? answer : [answer]).map(normalize).filter(Boolean); const options = findOptionNodes(block); let changed = false; let matchedCount = 0; if (options.length) { answers.forEach((wanted) => { const target = wanted.replace(/^[a-z][.、.]\s*/i, '').trim(); const node = options.find((option) => { const text = optionText(option); const letter = optionLetter(option); return Boolean(text) && (text === target || text.startsWith(target) || target.startsWith(text)) || Boolean(letter) && letter === wanted; }); if (!node) return; matchedCount += 1; if (!isOptionSelected(node)) changed = clickElement(node) || changed; }); } else { const inputs = queryAllInOrder(CONFIG.selectors.textInputs, block).filter(isVisible); inputs.forEach((input, index) => { const value = answers[index] ?? answers[0]; if (value !== undefined && normalize(input.value) !== value) { setNativeValue(input, Array.isArray(answer) ? answer[index] ?? answer[0] : answer); changed = true; } }); matchedCount = inputs.length ? Math.min(inputs.length, answers.length || 1) : 0; } const fullyMatched = matchedCount >= answers.length && answers.length > 0; if (!fullyMatched) { rememberUnanswered(question); return { completed: false, pending: true, matched: false }; } const submit = firstVisible(CONFIG.selectors.submit, block); if (submit && !state.submittedQuestions.has(block)) { clickElement(submit); state.submittedQuestions.add(block); } state.answeredQuestions.add(block); if (changed) pushLog(`已填写题目:${question.slice(0, 36)}`); return { completed: true, pending: false, matched: true }; } function processQuestions() { const blocks = getQuestionBlocks(); let completed = 0; let pending = 0; blocks.forEach((block) => { const result = answerQuestion(block); if (result.completed) completed += 1; if (result.pending) pending += 1; }); if (blocks.length && pending === 0 && !state.pageSubmitted) { const pageSubmit = firstVisible(CONFIG.selectors.submit); if (pageSubmit && !blocks.some((block) => block.contains(pageSubmit))) { clickElement(pageSubmit); state.pageSubmitted = true; pushLog('已提交当前页面题目'); } } return { total: blocks.length, completed, pending }; } function mediaCompleted(media) { const info = state.media.get(media); if (info?.completed) return true; const duration = Number(media.duration); const complete = media.ended || (Number.isFinite(duration) && duration > 0 && media.currentTime >= duration - 0.35); if (complete) { state.media.set(media, { ...info, completed: true, started: info?.started || false }); } return complete; } function prepareMedia(media, index) { let info = state.media.get(media); if (!info) { info = { started: false, completed: false, startFailures: 0, playAttemptAt: 0, uiAttemptAt: 0, lastCurrentTime: Number(media.currentTime) || 0, lastProgressAt: Date.now(), stallRetries: 0, failed: false, failureReason: '' }; state.media.set(media, info); media.addEventListener('ended', () => { info.completed = true; pushLog(`媒体 ${index + 1} 已完成`); }); } media.playbackRate = state.speed; media.muted = true; return info; } function updateMediaHealth(media, info, permitted, index) { const now = Date.now(); const currentTime = Number(media.currentTime) || 0; if (currentTime > Number(info.lastCurrentTime || 0) + 0.15) { info.lastCurrentTime = currentTime; info.lastProgressAt = now; return; } if (!info.lastProgressAt) info.lastProgressAt = now; if (!permitted || !info.started || media.paused || info.failed) return; if (now - info.lastProgressAt < CONFIG.mediaStallThreshold) return; info.stallRetries = Number(info.stallRetries || 0) + 1; info.lastProgressAt = now; try { media.pause(); } catch (_) { // The controller still blocks the permit if a custom player refuses pause(). } if (info.stallRetries >= CONFIG.mediaRetryLimit) { info.failed = true; info.failureReason = `媒体 ${index + 1} 播放无进度,已重试 ${info.stallRetries} 次`; pushLog(info.failureReason, true); return; } info.started = false; info.playAttemptAt = 0; info.uiAttemptAt = 0; pushLog(`媒体 ${index + 1} 播放卡住,自动重试 ${info.stallRetries}/${CONFIG.mediaRetryLimit}`, true); } function resetFailedMedia() { document.querySelectorAll('video, audio').forEach((media) => { const info = state.media.get(media); if (!info?.failed) return; info.failed = false; info.failureReason = ''; info.stallRetries = 0; info.startFailures = 0; info.started = false; info.lastCurrentTime = Number(media.currentTime) || 0; info.lastProgressAt = Date.now(); info.playAttemptAt = 0; info.uiAttemptAt = 0; }); } function findMediaPlayButton(media) { const selectors = [ '.vjs-big-play-button', '.vjs-play-control', '.ans-insertvideo-play', '.playButton', '.xgplayer-start', '.dplayer-play-icon', 'button[aria-label*="播放"]', '[title="播放"]' ]; const container = media.closest( '.ans-attach-ct, .video-js, .ans-video, .video-container, .xgplayer, .dplayer' ) || media.parentElement; return firstVisible(selectors, container || document) || firstVisible(selectors, document); } function markMediaStarted(info, index, total) { if (info.started) return; info.started = true; info.startFailures = 0; pushLog(`开始媒体 ${index + 1}/${total},${state.speed}x`); } function recordMediaStartFailure(info, index) { info.startFailures = Number(info.startFailures || 0) + 1; if (info.startFailures < CONFIG.mediaRetryLimit) return; info.failed = true; info.failureReason = `媒体 ${index + 1} 启动失败,已重试 ${info.startFailures} 次`; pushLog(info.failureReason, true); } function attemptMediaStart(media, info, index, total) { const now = Date.now(); if (now - info.uiAttemptAt >= 1200) { info.uiAttemptAt = now; const playButton = findMediaPlayButton(media); if (playButton) clickElement(playButton); } if (now - info.playAttemptAt < 1200) return; info.playAttemptAt = now; try { const result = media.play(); if (result && typeof result.then === 'function') { result.then(() => markMediaStarted(info, index, total)).catch(() => recordMediaStartFailure(info, index)); } else { markMediaStarted(info, index, total); } } catch (_) { recordMediaStartFailure(info, index); } } function processMedia() { const mediaList = Array.from(document.querySelectorAll('video, audio')).filter(isVisible); let completed = 0; const items = []; mediaList.forEach((media, index) => { const info = prepareMedia(media, index); const complete = mediaCompleted(media); const permitted = state.mediaPermit.workerId === WORKER_ID && state.mediaPermit.index === index; if (complete) { completed += 1; items.push({ index, completed: true }); return; } updateMediaHealth(media, info, permitted, index); if (info.failed) { items.push({ index, completed: false, failed: true, failureReason: info.failureReason, retries: info.stallRetries }); return; } if (!permitted && !media.paused) { try { media.pause(); } catch (_) { // Some custom players expose a read-only media facade. } } if (permitted && media.paused) attemptMediaStart(media, info, index, mediaList.length); items.push({ index, completed: false, failed: false }); }); const failedItems = items.filter((item) => item.failed); return { total: mediaList.length, completed, failed: failedItems.length, failureReason: failedItems[0]?.failureReason || '', items }; } function pauseLocalMedia() { document.querySelectorAll('video, audio').forEach((media) => { if (!media.paused) { try { media.pause(); } catch (_) { // Ignore custom player pause failures while the queue is paused. } } }); } function buildWorkerStatus() { const media = processMedia(); const questions = processQuestions(); const hasWork = media.total > 0 || questions.total > 0; return { id: WORKER_ID, url: location.href, framePath: FRAME_PATH, at: Date.now(), media, questions, hasWork, busy: media.completed < media.total || questions.pending > 0 }; } function publishWorkerStatus(status) { if (isController()) { if (Date.now() >= state.ignoreWorkerUntil) state.workers.set(WORKER_ID, status); return; } window.parent.postMessage({ type: MESSAGE_TYPE, kind: 'status', status, hops: 0 }, '*'); } function compareFramePaths(left = [], right = []) { const length = Math.max(left.length, right.length); for (let index = 0; index < length; index += 1) { const a = left[index] ?? -1; const b = right[index] ?? -1; if (a !== b) return a - b; } return 0; } function selectMediaPermit() { if (!isController()) return; const workers = Array.from(state.workers.values()) .sort((a, b) => compareFramePaths(a.framePath, b.framePath)); const candidates = []; let hasFailure = false; workers.forEach((worker) => { (worker.media.items || []).forEach((item) => { if (item.failed) hasFailure = true; else if (!item.completed) candidates.push({ workerId: worker.id, index: item.index }); }); }); const selected = !hasFailure && candidates[0] ? candidates[0] : { workerId: '', index: -1 }; if (selected.workerId === state.mediaPermit.workerId && selected.index === state.mediaPermit.index) return; state.mediaPermitRevision += 1; state.mediaPermit = { workerId: selected.workerId, index: selected.index, revision: state.mediaPermitRevision }; broadcastToChildren({ type: MESSAGE_TYPE, kind: 'media-permit', permit: state.mediaPermit }); } function revokeMediaPermit() { if (!state.mediaPermit.workerId && state.mediaPermit.index === -1) return; state.mediaPermitRevision += 1; state.mediaPermit = { workerId: '', index: -1, revision: state.mediaPermitRevision }; broadcastToChildren({ type: MESSAGE_TYPE, kind: 'media-permit', permit: state.mediaPermit }); } function isScanBlockingStatus(status) { return ['requested', 'scanning', 'paused', 'scan_error'].includes(status); } function disableLegacyScannerState() { if (!isScanBlockingStatus(state.scanSession.status)) return; state.scanSession = { status: 'manual', context: state.scanSession.context || null, sourceUrl: state.scanSession.sourceUrl || '', scannerRemovedAt: Date.now() }; saveScanSession(); revokeMediaPermit(); } function activeWorkerSummary() { const cutoff = Date.now() - CONFIG.workerTtl; for (const [id, worker] of state.workers.entries()) { if (worker.at < cutoff) state.workers.delete(id); } const workers = Array.from(state.workers.values()); const summary = workers.reduce((result, worker) => { result.mediaTotal += worker.media.total; result.mediaCompleted += worker.media.completed; result.mediaFailed += Number(worker.media.failed || 0); if (!result.mediaFailureReason && worker.media.failureReason) { result.mediaFailureReason = worker.media.failureReason; } result.questionTotal += worker.questions.total; result.questionCompleted += worker.questions.completed; result.questionPending += worker.questions.pending; result.hasWork = result.hasWork || worker.hasWork; result.busy = result.busy || worker.busy; return result; }, { mediaTotal: 0, mediaCompleted: 0, mediaFailed: 0, mediaFailureReason: '', questionTotal: 0, questionCompleted: 0, questionPending: 0, hasWork: false, busy: false }); if (summary.hasWork) state.seenWork = true; return summary; } function handleMediaFailure(summary) { if (!isController() || Number(summary.mediaFailed || 0) < 1) return false; const reason = summary.mediaFailureReason || '媒体播放长时间没有进度'; const key = `${state.currentTaskKey}|${reason}`; if (state.lastMediaFailureKey === key && state.queuePaused) return true; state.lastMediaFailureKey = key; state.queuePaused = true; state.enabled = false; storageApi.set(STORE.queuePaused, true); storageApi.set(STORE.enabled, false); pauseLocalMedia(); state.lastError = reason; pushLog(`待办已暂停:${reason}`, true); updatePanel(summary); return true; } function hasCompletionMarker(node) { if (!node) return false; const className = node.className || ''; const title = node.getAttribute?.('title') || ''; if (/unfinished|unfinish/i.test(className) || /未完成/.test(title)) return false; if (CONFIG.selectors.incomplete.some((selector) => node.querySelector?.(selector))) return false; if (/completed|(^|[-_\s])finished($|[-_\s])|jobfinish|icon_completed/i.test(className)) return true; if (/已完成/.test(title)) return true; return CONFIG.selectors.completed.some((selector) => Boolean(node.querySelector?.(selector))); } function hasIncompleteMarker(node) { if (!node) return false; if (/unfinished|unfinish/i.test(node.className || '')) return true; if (/未完成/.test(node.getAttribute?.('title') || '')) return true; return CONFIG.selectors.incomplete.some((selector) => Boolean(node.querySelector?.(selector))); } function catalogEntries() { return scanCatalogEntries().filter((entry) => isVisible(entry.node)).map((entry) => entry.node); } function simpleHash(value) { let hash = 2166136261; const text = String(value || ''); for (let index = 0; index < text.length; index += 1) { hash ^= text.charCodeAt(index); hash = Math.imul(hash, 16777619); } return (hash >>> 0).toString(36); } function currentAcademicYear() { const now = new Date(); const year = now.getFullYear(); const start = now.getMonth() >= 7 ? year : year - 1; return { start, end: start + 1 }; } function currentTermNumber() { const month = new Date().getMonth(); return month >= 7 || month <= 0 ? 1 : 2; } function currentTermKey() { const year = currentAcademicYear(); return `${year.start}-${year.end}-${currentTermNumber()}`; } function detectAccountKey() { try { const url = new URL(location.href); for (const key of ['userId', 'userid', 'uid', 'puid', 'pUid']) { const value = compactText(url.searchParams.get(key)); if (value) return value.slice(0, 120); } } catch (_) { // Continue with DOM account hints. } const node = document.querySelector( '[data-userid], [data-user-id], [data-uid], input[name="userId"], input[name="uid"], meta[name="user-id"]' ); return compactText( node?.getAttribute?.('data-userid') || node?.getAttribute?.('data-user-id') || node?.getAttribute?.('data-uid') || node?.getAttribute?.('value') || node?.getAttribute?.('content') ).slice(0, 120); } function scanPlatformKey(hostname = location.hostname) { const host = normalize(hostname); if (host.includes('xueyinonline')) return 'xueyinonline'; if (host.includes('chaoxing')) return 'chaoxing'; return host; } function activeCourseTemplate() { if (scanPlatformKey() === 'xueyinonline') return { id: 'xueyin', ...COURSE_TEMPLATES.xueyin }; if (FRAME_PATH.length > 0) return { id: 'portal-iframe', ...COURSE_TEMPLATES['portal-iframe'] }; for (const id of ['chaoxing-new', 'chaoxing-legacy']) { const template = COURSE_TEMPLATES[id]; if (template.detect.some((selector) => document.querySelector(selector))) return { id, ...template }; } return { id: 'generic', ...COURSE_TEMPLATES.generic }; } function templateSelectors(kind) { return Array.from(new Set(activeCourseTemplate()[kind] || [])); } function templateNodes(kind) { const template = activeCourseTemplate(); const primary = queryAllInOrder(template[kind] || []); if (primary.length || template.id === 'generic') return primary; return queryAllInOrder(COURSE_TEMPLATES.generic[kind] || []); } function isCourseLink(link) { const rawHref = link?.getAttribute?.('href') || ''; if (!rawHref || /^javascript:/i.test(rawHref)) return false; try { const url = new URL(rawHref, location.href); const hasIdentity = url.searchParams.has('courseId') || url.searchParams.has('courseid') || url.searchParams.has('clazzid') || url.searchParams.has('clazzId'); const knownPath = /\/mycourse\/|studentcourse|studentstudy|coursehome/i.test(url.pathname); return hasIdentity && knownPath; } catch (_) { return false; } } function courseListFingerprint(courses) { return simpleHash((Array.isArray(courses) ? courses : []) .map((course) => `${course.id}|${compactText(course.name)}`) .join('||')); } function buildScanContext(courses) { return { accountKey: detectAccountKey(), termKey: currentTermKey(), platformKey: scanPlatformKey(), courseFingerprint: courseListFingerprint(courses) }; } function scanContextKey(context) { if (!context || typeof context !== 'object') return ''; return simpleHash([ context.accountKey || '', context.termKey || '', context.platformKey || '', context.courseFingerprint || '' ].join('|')); } function scanContextMismatch(context, currentCourses = null) { if (!context || typeof context !== 'object') return ''; if (context.termKey && context.termKey !== currentTermKey()) return '学期已变化'; if (context.platformKey && context.platformKey !== scanPlatformKey()) return '课程平台已变化'; const accountKey = detectAccountKey(); if (context.accountKey && accountKey && context.accountKey !== accountKey) return '登录账号已变化'; if (Array.isArray(currentCourses) && context.courseFingerprint && context.courseFingerprint !== courseListFingerprint(currentCourses)) return '课程列表已变化'; return ''; } function courseIdentity(urlValue) { try { const url = new URL(urlValue, location.href); const courseId = url.searchParams.get('courseId') || url.searchParams.get('courseid') || ''; const clazzId = url.searchParams.get('clazzid') || url.searchParams.get('clazzId') || ''; return courseId || clazzId ? `${courseId}:${clazzId}` : `${url.origin}${url.pathname}`; } catch (_) { return normalize(urlValue); } } function isCurrentSemesterCourse(cardText) { const text = compactText(cardText); if (/已结课|已结束|课程结束|已归档|历史课程|已过期/.test(text)) return false; const year = currentAcademicYear(); const ranges = Array.from(text.matchAll(/(20\d{2})\s*[-—至/]\s*(20\d{2})/g)); if (ranges.length && !ranges.some((match) => Number(match[1]) === year.start && Number(match[2]) === year.end)) { return false; } const firstTerm = /第\s*[一1]\s*学期|秋季|秋学期/.test(text); const secondTerm = /第\s*[二2]\s*学期|春季|春学期/.test(text); if (firstTerm !== secondTerm) { if (firstTerm && currentTermNumber() !== 1) return false; if (secondTerm && currentTermNumber() !== 2) return false; } return true; } function courseNameFromCard(card, link) { const titleNode = card.querySelector( '.course-name, .courseName, .course_name, .name, .Mconright h3, h3, h4, [title]' ); return compactText( titleNode?.getAttribute?.('title') || titleNode?.textContent || link.getAttribute('title') || link.textContent ).slice(0, 160); } function discoverCurrentSemesterCourses() { const links = templateNodes('courseLinks') .filter((link) => isVisible(link) && isCourseLink(link) && !link.closest('#cx-helper-panel, #cx-helper-progress-window, #cx-helper-todo-window')); const courses = []; const seen = new Set(); links.forEach((link) => { const rawHref = link.getAttribute('href') || ''; if (!rawHref || /^javascript:/i.test(rawHref)) return; let url; try { url = new URL(rawHref, location.href).href; } catch (_) { return; } const card = link.closest(templateSelectors('courseCards').join(',')) || link; const cardText = compactText(card.textContent); if (!isCurrentSemesterCourse(cardText)) return; const name = courseNameFromCard(card, link); if (!name) return; const id = courseIdentity(url); if (!id || seen.has(id)) return; seen.add(id); courses.push({ id, name, url, order: courses.length }); }); return courses; } function isCourseHomePage() { const path = location.pathname.toLowerCase(); if (/studentstudy|studentcourse|\/mycourse\/tch|knowledge|chapterstudy/.test(path)) return false; return discoverCurrentSemesterCourses().length > 0; } function scanCatalogEntries() { const candidates = templateNodes('catalog'); const entries = []; candidates.forEach((node) => { const clickable = node.closest('a[href]') || node.querySelector?.('a[href]') || node; const title = compactText(clickable.textContent || node.textContent); if (!title || entries.some((entry) => entry.node === clickable)) return; const href = clickable.getAttribute?.('href') || ''; let url = ''; if (href && !/^javascript:/i.test(href)) { try { url = new URL(href, location.href).href; } catch (_) { url = ''; } } entries.push({ node: clickable, title, url, order: entries.length }); }); return entries; } function inferTaskType(entry) { const text = normalize(`${entry.title} ${entry.node.className || ''} ${entry.url}`); if (/视频|video/.test(text)) return '视频'; if (/音频|audio/.test(text)) return '音频'; if (/测验|作业|考试|quiz|work/.test(text)) return '题目'; if (/文档|阅读|ppt|pdf|document/.test(text)) return '文档'; return '任务点'; } function extractPendingTodos(course, catalog = scanCatalogEntries()) { const contextKey = scanContextKey(state.scanSession.context); return catalog .filter((entry) => hasIncompleteMarker(entry.node) || !hasCompletionMarker(entry.node)) .filter((entry) => entry.url || hasIncompleteMarker(entry.node)) .map((entry, index) => ({ id: `todo-${simpleHash(`${course.id}|${entry.url}|${entry.title}`)}`, courseId: course.id, courseName: course.name, courseOrder: course.order, taskOrder: index, title: entry.title.slice(0, 180), type: inferTaskType(entry), url: entry.url || course.url, status: 'pending', scannedAt: Date.now(), completedAt: 0, contextKey })); } function saveTodos() { storageApi.set(STORE.todos, JSON.stringify(state.todos)); } function saveScanSession() { storageApi.set(STORE.scanSession, JSON.stringify(state.scanSession)); } function navigateForScan(url) { if (!url || Date.now() - state.scanNavigationAt < 1500) return false; state.scanNavigationAt = Date.now(); window.setTimeout(() => location.assign(url), CONFIG.scanNavigationDelay); return true; } function startCourseScan(manual = false) { const courses = discoverCurrentSemesterCourses(); if (!courses.length) return false; state.todos = []; saveTodos(); state.queuePaused = true; storageApi.set(STORE.queuePaused, true); state.scanSession = { id: `scan-${Date.now().toString(36)}`, status: 'scanning', courses, index: 0, sourceUrl: location.href, startedAt: Date.now(), completedAt: 0, manual, autoRun: true, processedCourseIds: [], skippedCourseIds: [], failedCourses: [], courseAttempts: {}, courseStartedAt: { [courses[0].id]: Date.now() }, phase: 'primary', retryQueue: [], retryIndex: 0, schemaVersion: 2, context: buildScanContext(courses) }; saveScanSession(); try { sessionStorage.setItem('cx_helper_auto_scan_started', '1'); } catch (_) { // Session storage is optional; the persisted scan state still prevents duplicate work. } pushLog(`开始扫描 ${courses.length} 门本学期课程`, true); return navigateForScan(courses[0].url); } function shouldStartAutomaticScan() { if (!isCourseHomePage() || state.scanSession.status === 'scanning') return false; try { if (sessionStorage.getItem('cx_helper_auto_scan_started') === '1') return false; } catch (_) { if (Date.now() - state.lastAutoScanAt < 30 * 60 * 1000) return false; } return Date.now() - state.lastAutoScanAt >= 2 * 60 * 1000; } function ensureScanContext() { const session = state.scanSession; if (!session || !['scanning', 'paused', 'scan_error'].includes(session.status)) return true; if (!session.context) { session.schemaVersion = 2; session.context = buildScanContext(session.courses || []); saveScanSession(); return true; } const homeCourses = isCourseHomePage() ? discoverCurrentSemesterCourses() : null; const reason = scanContextMismatch(session.context, homeCourses); if (!reason) return true; const sourceUrl = isCourseHomePage() ? location.href : session.sourceUrl; const manual = session.manual === true; const autoRun = session.autoRun !== false; state.todos = []; saveTodos(); state.queuePaused = true; storageApi.set(STORE.queuePaused, true); state.scanSession = { status: 'requested', sourceUrl, manual, autoRun, contextChangedReason: reason, requestedAt: Date.now() }; saveScanSession(); pushLog(`${reason},正在重新建立扫描`, true); if (homeCourses?.length) startCourseScan(manual); else if (sourceUrl) navigateForScan(sourceUrl); return false; } function looksCollapsed(node) { const aria = node.getAttribute?.('aria-expanded'); if (aria === 'false') return true; if (aria === 'true') return false; const title = compactText(`${node.getAttribute?.('title') || ''} ${node.getAttribute?.('aria-label') || ''}`); if (/展开|显示章节|展开目录/.test(title)) return true; const classText = normalize(`${node.className || ''} ${node.parentElement?.className || ''}`); if (/collapsed|close|closed|fold|shrink/.test(classText)) return true; if (/open|expanded|unfold/.test(classText)) return false; return false; } function scanScrollForLazyContent() { const root = document.scrollingElement || document.documentElement; if (!root) return false; const height = Number(root.scrollHeight || 0); const changed = height > 0 && height !== state.scanLastScrollHeight; state.scanLastScrollHeight = height; if (!changed || height <= Number(root.clientHeight || window.innerHeight || 0)) return false; try { window.scrollTo({ top: height, behavior: 'auto' }); return true; } catch (_) { return false; } } function expandCatalogForScan() { let activity = false; let batch = 0; const expandedContainers = new Set(); const expanders = templateNodes('expand') .filter((node) => isVisible(node) && !state.scanClickedExpanders.has(node) && looksCollapsed(node)); for (const node of expanders) { if (batch >= CONFIG.scanExpandBatch || state.scanExpansionClicks >= CONFIG.scanExpandMaxClicks) { state.scanExpansionLimitReached = true; break; } const container = node.closest?.('.chapter_item, .chapter_unit, .catalog_level, li') || node; if (expandedContainers.has(container)) continue; expandedContainers.add(container); state.scanClickedExpanders.add(node); state.scanExpansionClicks += 1; batch += 1; activity = clickElement(node) || activity; } const loadMoreNodes = templateNodes('loadMore').filter((node) => { if (!isVisible(node)) return false; const href = node.getAttribute?.('href') || ''; if (/courseId=|courseid=|chapterId=|knowledgeId=|studentstudy/i.test(href)) return false; const text = compactText(node.textContent); if (!/^(加载更多|查看更多|更多章节|展开更多|下一页)(章节|课程)?$/.test(text)) return false; const signature = `${text}|${node.getAttribute?.('data-page') || ''}|${state.scanCatalogSignature}`; return state.scanLoadMoreSignatures.get(node) !== signature; }); for (const node of loadMoreNodes) { if (state.scanLoadMoreClicks >= CONFIG.scanLoadMoreMaxClicks) { state.scanExpansionLimitReached = true; break; } const signature = `${compactText(node.textContent)}|${node.getAttribute?.('data-page') || ''}|${state.scanCatalogSignature}`; state.scanLoadMoreSignatures.set(node, signature); state.scanLoadMoreClicks += 1; activity = clickElement(node) || activity; } activity = scanScrollForLazyContent() || activity; if (activity) { state.scanExpansionActivityAt = Date.now(); state.scanCatalogStableSince = Date.now(); } return activity; } function resetScanPageState() { state.scanCatalogSignature = ''; state.scanCatalogStableSince = 0; state.scanNavigationAt = 0; state.scanExpansionClicks = 0; state.scanLoadMoreClicks = 0; state.scanExpansionActivityAt = 0; state.scanLastScrollHeight = 0; state.scanClickedExpanders = new WeakSet(); state.scanLoadMoreSignatures = new WeakMap(); state.scanExpansionLimitReached = false; } function scanAttemptCount(courseId) { const attempts = state.scanSession.courseAttempts; return attempts && Number(attempts[courseId]) > 0 ? Number(attempts[courseId]) : 0; } function setScanAttemptCount(courseId, count) { state.scanSession.courseAttempts = { ...(state.scanSession.courseAttempts || {}), [courseId]: Math.max(0, Number(count) || 0) }; } function currentScanCourse() { const courses = Array.isArray(state.scanSession.courses) ? state.scanSession.courses : []; if (state.scanSession.phase === 'retry') { const retryQueue = Array.isArray(state.scanSession.retryQueue) ? state.scanSession.retryQueue : []; const retryId = retryQueue[Number(state.scanSession.retryIndex || 0)]; return courses.find((course) => course.id === retryId) || null; } return courses[Number(state.scanSession.index || 0)] || null; } function setCourseStartedNow(courseId) { state.scanSession.courseStartedAt = { ...(state.scanSession.courseStartedAt || {}), [courseId]: Date.now() }; } function courseScanElapsed(courseId) { const startedAt = Number(state.scanSession.courseStartedAt?.[courseId] || 0); if (startedAt > 0) return Date.now() - startedAt; setCourseStartedNow(courseId); return 0; } function nextScanCourse() { const courses = Array.isArray(state.scanSession.courses) ? state.scanSession.courses : []; if (state.scanSession.phase === 'retry') { state.scanSession.retryIndex = Number(state.scanSession.retryIndex || 0) + 1; const nextRetryId = (state.scanSession.retryQueue || [])[state.scanSession.retryIndex]; if (!nextRetryId) return null; state.scanSession.index = courses.findIndex((course) => course.id === nextRetryId); return currentScanCourse(); } state.scanSession.index = Number(state.scanSession.index || 0) + 1; if (courses[state.scanSession.index]) return courses[state.scanSession.index]; const retryQueue = Array.isArray(state.scanSession.retryQueue) ? state.scanSession.retryQueue : []; if (!retryQueue.length) return null; state.scanSession.phase = 'retry'; state.scanSession.retryIndex = 0; state.scanSession.index = courses.findIndex((course) => course.id === retryQueue[0]); pushLog(`开始重试 ${retryQueue.length} 门扫描异常课程`, true); return currentScanCourse(); } function advanceCourseScanner() { const next = nextScanCourse(); resetScanPageState(); if (!next) { finishCourseScan(); return false; } setCourseStartedNow(next.id); saveScanSession(); navigateForScan(next.url); return true; } function stopForScanError(course, reason) { const template = activeCourseTemplate(); state.scanSession.status = 'scan_error'; state.scanSession.currentError = { courseId: course.id, courseName: course.name, reason, attempts: scanAttemptCount(course.id), templateId: template.id, occurredAt: Date.now() }; saveScanSession(); revokeMediaPermit(); pauseLocalMedia(); pushLog(`扫描异常:${course.name} · ${reason}`, true); updatePanel(); return true; } function handleCourseScanFailure(course, reason) { const attempts = scanAttemptCount(course.id) + 1; setScanAttemptCount(course.id, attempts); if (state.scanSession.phase !== 'retry' && attempts <= CONFIG.scanRetryLimit) { state.scanSession.retryQueue = Array.from(new Set([ ...(state.scanSession.retryQueue || []), course.id ])); state.scanSession.pendingFailures = { ...(state.scanSession.pendingFailures || {}), [course.id]: { reason, attempts, occurredAt: Date.now() } }; pushLog(`暂存扫描异常,稍后重试:${course.name}`, true); saveScanSession(); return advanceCourseScanner(); } return stopForScanError(course, reason); } function retryFailedCourse() { if (state.scanSession.status !== 'scan_error') return false; const course = currentScanCourse(); if (!course) return false; state.scanSession.status = 'scanning'; state.scanSession.currentError = null; state.scanSession.resumedAt = Date.now(); setCourseStartedNow(course.id); resetScanPageState(); saveScanSession(); pushLog(`重新扫描:${course.name}`, true); window.setTimeout(() => location.assign(course.url), CONFIG.scanRetryDelay); updatePanel(); return true; } function skipFailedCourse() { if (state.scanSession.status !== 'scan_error') return false; const course = currentScanCourse(); if (!course) return false; const failure = state.scanSession.currentError || { courseId: course.id, courseName: course.name, reason: '用户跳过', attempts: scanAttemptCount(course.id), occurredAt: Date.now() }; state.scanSession.failedCourses = [ ...(state.scanSession.failedCourses || []).filter((item) => item.courseId !== course.id), { ...failure, skippedAt: Date.now() } ]; state.scanSession.skippedCourseIds = Array.from(new Set([ ...(state.scanSession.skippedCourseIds || []), course.id ])); state.scanSession.currentError = null; state.scanSession.status = 'scanning'; saveScanSession(); pushLog(`已跳过扫描异常课程:${course.name}`, true); if (state.scanSession.pendingFailures) delete state.scanSession.pendingFailures[course.id]; advanceCourseScanner(); updatePanel(); return true; } function finishCourseScan() { state.scanSession.status = 'complete'; state.scanSession.index = Array.isArray(state.scanSession.courses) ? state.scanSession.courses.length : 0; state.scanSession.completedAt = Date.now(); state.lastAutoScanAt = state.scanSession.completedAt; storageApi.set(STORE.lastAutoScanAt, state.lastAutoScanAt); saveScanSession(); state.todos.sort((a, b) => a.courseOrder - b.courseOrder || a.taskOrder - b.taskOrder); saveTodos(); const failedCount = Array.isArray(state.scanSession.failedCourses) ? state.scanSession.failedCourses.length : 0; pushLog(`扫描完成:${state.todos.length} 个未完成任务点${failedCount ? `,跳过 ${failedCount} 门异常课程` : ''}`, true); const autoRun = state.scanSession.autoRun !== false; state.enabled = autoRun; state.queuePaused = !autoRun; storageApi.set(STORE.enabled, state.enabled); storageApi.set(STORE.queuePaused, state.queuePaused); } function toggleCourseScanPause() { if (state.scanSession.status === 'scanning') { state.scanSession.status = 'paused'; state.scanSession.pausedAt = Date.now(); saveScanSession(); revokeMediaPermit(); pauseLocalMedia(); pushLog(`扫描已暂停,断点 ${Number(state.scanSession.index || 0) + 1}`, true); } else if (state.scanSession.status === 'paused') { state.scanSession.status = 'scanning'; state.scanSession.resumedAt = Date.now(); const course = currentScanCourse(); if (course) setCourseStartedNow(course.id); resetScanPageState(); saveScanSession(); pushLog(`继续扫描第 ${Number(state.scanSession.index || 0) + 1} 门课程`, true); window.setTimeout(runCycle, 0); } else if (state.scanSession.status === 'scan_error') { toggleTodoWindow(true); } updatePanel(); } function scanCatalogSignature(entries) { return entries.map((entry) => [ entry.title, entry.url, hasCompletionMarker(entry.node) ? 'done' : hasIncompleteMarker(entry.node) ? 'pending' : 'unknown' ].join('::')).join('|'); } function processCourseScanner() { // Course-wide scanning was removed because it required full-page navigation. return false; /* legacy scanner retained below only for storage compatibility if (!isController()) return false; if (!ensureScanContext()) return true; if (state.scanSession.status === 'paused') { pauseLocalMedia(); return true; } if (state.scanSession.status === 'scan_error') { pauseLocalMedia(); return true; } if (state.scanSession.status === 'requested') { if (isCourseHomePage()) { startCourseScan(true); } else if (state.scanSession.sourceUrl) { navigateForScan(state.scanSession.sourceUrl); } return true; } if (state.scanSession.status !== 'scanning') { if (shouldStartAutomaticScan()) startCourseScan(false); return state.scanSession.status === 'scanning'; } pauseLocalMedia(); const courses = Array.isArray(state.scanSession.courses) ? state.scanSession.courses : []; const course = currentScanCourse(); if (!course) { finishCourseScan(); return false; } const currentId = courseIdentity(location.href); const elapsed = courseScanElapsed(course.id); if (currentId !== course.id) { if (elapsed >= CONFIG.scanEmptyTimeout) return handleCourseScanFailure(course, '课程页面导航超时'); navigateForScan(course.url); return true; } const template = activeCourseTemplate(); state.scanSession.courseTemplates = { ...(state.scanSession.courseTemplates || {}), [course.id]: template.id }; expandCatalogForScan(); if (state.scanExpansionLimitReached) { return handleCourseScanFailure(course, '课程目录展开次数达到上限,未确认加载完整'); } const entries = scanCatalogEntries(); const signature = scanCatalogSignature(entries); if (signature !== state.scanCatalogSignature) { state.scanCatalogSignature = signature; state.scanCatalogStableSince = Date.now(); if (entries.length) { window.setTimeout(runCycle, CONFIG.scanCatalogStableTime + 60); } } const stableSince = Math.max(state.scanCatalogStableSince, state.scanExpansionActivityAt); const stableWait = state.scanExpansionActivityAt ? CONFIG.scanLazyLoadSettleTime : CONFIG.scanCatalogStableTime; const stable = entries.length > 0 && Date.now() - stableSince >= stableWait; if (!stable) { if (elapsed < CONFIG.scanEmptyTimeout) return true; return handleCourseScanFailure( course, entries.length ? '课程目录持续变化,未确认加载完整' : '课程目录加载超时' ); } const courseTodos = extractPendingTodos(course, entries); state.todos = state.todos.filter((todo) => todo.courseId !== course.id).concat(courseTodos); saveTodos(); state.scanSession.processedCourseIds = Array.from(new Set([ ...(state.scanSession.processedCourseIds || []), course.id ])); if (state.scanSession.pendingFailures) delete state.scanSession.pendingFailures[course.id]; saveScanSession(); const completedCount = state.scanSession.processedCourseIds.length; pushLog(`已扫描 ${completedCount}/${courses.length}:${course.name}`); return advanceCourseScanner(); */ } function currentRunningTodo() { return state.todos.find((todo) => todo.status === 'running') || null; } function nextPendingTodo() { return state.todos .filter((todo) => todo.status === 'pending') .sort((a, b) => a.courseOrder - b.courseOrder || a.taskOrder - b.taskOrder)[0] || null; } function todoMatchesLocation(todo) { if (!todo?.url) return false; try { const target = new URL(todo.url, location.href); const current = new URL(location.href); if (target.href === current.href) return true; const targetCourse = target.searchParams.get('courseId') || target.searchParams.get('courseid'); const currentCourse = current.searchParams.get('courseId') || current.searchParams.get('courseid'); const targetChapter = target.searchParams.get('chapterId') || target.searchParams.get('knowledgeId'); const currentChapter = current.searchParams.get('chapterId') || current.searchParams.get('knowledgeId'); if (targetCourse && currentCourse && targetCourse === currentCourse && targetChapter && currentChapter && targetChapter === currentChapter) { return true; } } catch (_) { // Fall through to title matching for onclick-only task entries. } const currentTitle = normalize(currentTaskTitle()); const todoTitle = normalize(todo.title); return Boolean(todoTitle && currentTitle && (currentTitle.includes(todoTitle) || todoTitle.includes(currentTitle))); } function invalidateTodoContext(reason) { const sourceUrl = state.scanSession.sourceUrl || ''; state.todos = []; saveTodos(); state.queuePaused = true; state.enabled = false; storageApi.set(STORE.queuePaused, true); storageApi.set(STORE.enabled, false); state.scanSession = { ...state.scanSession, status: sourceUrl ? 'requested' : 'context_changed', contextChangedReason: reason, requestedAt: Date.now() }; saveScanSession(); revokeMediaPermit(); pauseLocalMedia(); state.lastError = reason; pushLog(`待办已清空:${reason}`, true); } function validateTodoContext() { if (!state.todos.length) return true; const context = state.scanSession.context; if (!context) { invalidateTodoContext('旧待办缺少账号和学期信息,请重新扫描'); return false; } const homeCourses = isCourseHomePage() ? discoverCurrentSemesterCourses() : null; const reason = scanContextMismatch(context, homeCourses); const expectedKey = scanContextKey(context); const storedMismatch = state.todos.some((todo) => todo.contextKey && todo.contextKey !== expectedKey); if (reason || storedMismatch) { invalidateTodoContext(reason || '待办所属账号或学期与当前环境不一致'); return false; } if (state.todos.some((todo) => !todo.contextKey)) { state.todos = state.todos.map((todo) => ({ ...todo, contextKey: expectedKey })); saveTodos(); } return true; } function navigateForQueue(todo) { if (!todo?.url || Date.now() - state.queueNavigationAt < 2000) return false; state.queueNavigationAt = Date.now(); pushLog(`进入待办:${todo.courseName} / ${todo.title}`); window.setTimeout(() => location.assign(todo.url), 150); return true; } function activateNextTodo() { if (state.queuePaused || !state.enabled) return null; let todo = currentRunningTodo(); if (!todo) { todo = nextPendingTodo(); if (todo) { todo.status = 'running'; todo.startedAt = Date.now(); saveTodos(); } } if (!todo) { if (state.todos.length && !state.queueFinishedLogged) { state.queueFinishedLogged = true; pushLog('本地待办队列已全部完成', true); } return null; } state.queueFinishedLogged = false; if (!todoMatchesLocation(todo)) navigateForQueue(todo); return todo; } function markRunningTodoComplete() { const todo = currentRunningTodo(); if (!todo) return false; todo.status = 'completed'; todo.completedAt = Date.now(); saveTodos(); pushLog(`完成待办:${todo.courseName} / ${todo.title}`, true); state.queueNavigationAt = 0; return true; } function processTodoQueue() { if (!isController() || isScanBlockingStatus(state.scanSession.status)) return null; if (!validateTodoContext()) return null; if (state.queuePaused || !state.enabled) { pauseLocalMedia(); return currentRunningTodo(); } return activateNextTodo(); } function currentCatalogEntry(entries) { const current = firstVisible(CONFIG.selectors.currentCatalog); if (!current) return null; return entries.find((entry) => entry === current || entry.contains(current) || current.contains(entry)) || current; } function currentTaskMarkedComplete() { const current = firstVisible(CONFIG.selectors.currentCatalog); return current ? hasCompletionMarker(current) : false; } function currentTodoMarkedComplete(todo) { if (!todo || !todoMatchesLocation(todo)) return false; if (currentTaskMarkedComplete()) return true; const targetUrl = todo.url || ''; const entry = scanCatalogEntries().find((candidate) => { if (targetUrl && candidate.url === targetUrl) return true; const title = normalize(todo.title); return title && normalize(candidate.title) === title; }); return Boolean(entry && hasCompletionMarker(entry.node)); } function taskKey() { const current = firstVisible(CONFIG.selectors.currentCatalog); if (!current) return ''; const clickable = current.closest('a[href]') || current.querySelector('a[href]') || current; return clickable.getAttribute?.('href') || clickable.getAttribute?.('data-id') || normalize(clickable.textContent); } function resetTaskProgress(ignoreMilliseconds = 0) { state.workers.clear(); state.mediaPermitRevision += 1; state.mediaPermit = { workerId: '', index: -1, revision: state.mediaPermitRevision }; if (isController()) { broadcastToChildren({ type: MESSAGE_TYPE, kind: 'media-permit', permit: state.mediaPermit }); } state.seenWork = false; state.stableSince = 0; state.pageSubmitted = false; state.answeredQuestions = new WeakSet(); state.submittedQuestions = new WeakSet(); state.media = new WeakMap(); state.ignoreWorkerUntil = Date.now() + ignoreMilliseconds; state.taskEnteredAt = Date.now(); } function syncTaskContext() { const key = taskKey(); if (!key) return; if (!state.currentTaskKey) { state.currentTaskKey = key; return; } if (key !== state.currentTaskKey) { state.currentTaskKey = key; resetTaskProgress(500); pushLog(`已切换任务点:${normalize(key).slice(0, 30)}`); } } function isCourseDetailPage() { const path = location.pathname.toLowerCase(); if (/studentstudy|knowledge|chapterstudy/.test(path)) return false; if (/\/mycourse\/(studentcourse|tch)|\/course\/(detail|courseinfo)/.test(path)) return true; return Boolean(document.querySelector('.chapter_unit, .catalog_points, .catalog_level')) && catalogEntries().length > 0; } function jumpFromCourseDetail() { if (!isController() || !state.enabled || !state.autoJump || state.detailJumpAttempted) return false; if (state.scanSession.status === 'complete' && !currentRunningTodo()) return false; if (!isCourseDetailPage() || Date.now() - state.detailPageEnteredAt < CONFIG.detailPageDelay) return false; const entries = catalogEntries(); const target = entries.find(hasIncompleteMarker) || entries.find((entry) => !hasCompletionMarker(entry)); if (!target) { if (!state.detailExpandAttempted) { const expander = firstVisible([ '#courseChapter .chapter_unit', '#courseChapter .chapterText', '.chapter_item .chapterText', '.catalog_level .chapterText' ]); if (expander) { state.detailExpandAttempted = true; state.detailPageEnteredAt = Date.now(); clickElement(expander); pushLog('已展开课程目录,正在查找任务点'); } } return false; } state.detailJumpAttempted = true; resetTaskProgress(1200); state.currentTaskKey = ''; state.lastNavigation = Date.now(); pushLog(`进入任务点:${normalize(target.textContent).slice(0, 30)}`); const clicked = clickElement(target); if (!clicked) state.detailJumpAttempted = false; return clicked; } function goToNextTask() { if (Date.now() - state.lastNavigation < CONFIG.navigationCooldown) return false; const next = firstVisible(CONFIG.selectors.next); if (next && !next.matches(':disabled, [aria-disabled="true"]')) { resetTaskProgress(1200); state.currentTaskKey = ''; state.lastNavigation = Date.now(); pushLog('进入下一个任务点'); return clickElement(next); } const entries = catalogEntries(); const current = currentCatalogEntry(entries); const index = entries.indexOf(current); const following = index >= 0 ? entries.slice(index + 1) : []; const target = following.find(hasIncompleteMarker) || following.find((entry) => !hasCompletionMarker(entry)); if (!target) return false; resetTaskProgress(1200); state.currentTaskKey = ''; state.lastNavigation = Date.now(); pushLog(`按目录进入:${normalize(target.textContent).slice(0, 30)}`); return clickElement(target); } function maybeAdvance(summary) { if (!isController() || !state.enabled || isCourseDetailPage()) return; if (Date.now() - state.taskEnteredAt < 4000) return; const completedWork = state.seenWork && !summary.busy && summary.questionPending === 0 && summary.mediaCompleted >= summary.mediaTotal; const ready = completedWork || (!state.seenWork && currentTaskMarkedComplete()); if (!ready) { state.stableSince = 0; return; } if (!state.stableSince) state.stableSince = Date.now(); if (Date.now() - state.stableSince < CONFIG.completionStableTime) return; if (markRunningTodoComplete()) { state.stableSince = 0; activateNextTodo(); return; } if (state.scanSession.status === 'complete') { state.stableSince = 0; return; } if (goToNextTask()) state.stableSince = 0; } function toggleEnabled() { state.enabled = !state.enabled; state.queuePaused = !state.enabled; resetTaskProgress(state.enabled ? 500 : 0); state.detailJumpAttempted = false; state.detailExpandAttempted = false; state.detailPageEnteredAt = Date.now(); storageApi.set(STORE.enabled, state.enabled); storageApi.set(STORE.queuePaused, state.queuePaused); if (state.scanSession.status === 'scanning') { state.scanSession.autoRun = state.enabled; saveScanSession(); } pushLog(state.enabled ? '已启动自动运行' : '已暂停自动运行', true); updatePanel(); } function importBank() { const raw = prompt('粘贴题库 JSON:{"题目":"答案"},多选题答案使用数组'); if (!raw) return; try { const parsed = JSON.parse(raw); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('顶层必须是 JSON 对象'); state.bank = { ...state.bank, ...parsed }; Object.keys(parsed).forEach((question) => delete state.unanswered[normalize(question)]); saveObject(STORE.bank, state.bank); saveObject(STORE.unanswered, state.unanswered); rebuildBankIndex(); pushLog(`已导入 ${Object.keys(parsed).length} 条题库记录`, true); } catch (error) { alert(`题库 JSON 解析失败:${error.message}`); } } function exportUnanswered() { const payload = JSON.stringify(state.unanswered, null, 2); prompt('复制未匹配题目,补充答案后重新导入:', payload); } function compactText(value) { return String(value || '').replace(/[\r\n\t ]+/g, ' ').trim(); } function currentTaskTitle() { const current = firstVisible(CONFIG.selectors.currentCatalog); const text = compactText(current?.textContent); return text || compactText(document.title) || '当前课程页面'; } function workerLocation(worker) { try { const url = new URL(worker.url); return `${url.hostname}${url.pathname}`; } catch (_) { return compactText(worker.url) || '页面地址未知'; } } function setMeter(root, completed, total) { const percent = total > 0 ? Math.round((completed / total) * 100) : 0; root.querySelector('.cxh-meter-value').textContent = `${completed}/${total}`; root.querySelector('.cxh-meter-fill').style.width = `${Math.max(0, Math.min(100, percent))}%`; } function courseProgress() { const entries = catalogEntries(); return { total: entries.length, completed: entries.filter(hasCompletionMarker).length }; } function renderProgressWindow(summary) { const root = state.progressWindow; if (!root || !state.progressOpen) return; const course = courseProgress(); root.querySelector('.cxh-current-task').textContent = currentTaskTitle(); setMeter(root.querySelector('[data-meter="tasks"]'), course.completed, course.total); setMeter(root.querySelector('[data-meter="media"]'), summary.mediaCompleted, summary.mediaTotal); setMeter(root.querySelector('[data-meter="questions"]'), summary.questionCompleted, summary.questionTotal); root.querySelector('.cxh-pending-value').textContent = String(summary.questionPending); root.querySelector('.cxh-unanswered-value').textContent = String(Object.keys(state.unanswered).length); const workerList = root.querySelector('.cxh-worker-list'); workerList.replaceChildren(); const workers = Array.from(state.workers.values()).sort((a, b) => a.url.localeCompare(b.url)); if (!workers.length) { const empty = document.createElement('div'); empty.className = 'cxh-empty'; empty.textContent = state.enabled ? '等待课程页面或播放器状态' : '启动后显示页面与播放器状态'; workerList.appendChild(empty); } else { workers.forEach((worker, index) => { const row = document.createElement('div'); row.className = 'cxh-worker-row'; const header = document.createElement('div'); header.className = 'cxh-worker-header'; const name = document.createElement('strong'); name.textContent = worker.id === WORKER_ID ? '主页面' : `子页面 ${index + 1}`; const status = document.createElement('span'); status.className = worker.busy ? 'cxh-state is-busy' : worker.hasWork ? 'cxh-state is-ready' : 'cxh-state is-idle'; status.textContent = worker.busy ? '处理中' : worker.hasWork ? '已就绪' : '等待'; header.append(name, status); const location = document.createElement('div'); location.className = 'cxh-worker-location'; location.textContent = workerLocation(worker); location.title = workerLocation(worker); const details = document.createElement('div'); details.className = 'cxh-worker-details'; details.textContent = `媒体 ${worker.media.completed}/${worker.media.total} · 题目 ${worker.questions.completed}/${worker.questions.total} · 待处理 ${worker.questions.pending}`; row.append(header, location, details); workerList.appendChild(row); }); } const logList = root.querySelector('.cxh-log-list'); logList.replaceChildren(); const storedLogs = storageApi.get(STORE.logs, []); const logs = Array.isArray(storedLogs) ? storedLogs.slice(0, 8) : []; if (!logs.length) { const empty = document.createElement('div'); empty.className = 'cxh-empty'; empty.textContent = '暂无运行记录'; logList.appendChild(empty); } else { logs.forEach((line) => { const item = document.createElement('div'); item.className = 'cxh-log-item'; item.textContent = String(line); logList.appendChild(item); }); } root.querySelector('.cxh-updated-at').textContent = `更新于 ${new Date().toLocaleTimeString()}`; } function toggleProgressWindow(force) { if (!state.progressWindow) return; state.progressOpen = typeof force === 'boolean' ? force : !state.progressOpen; if (state.progressOpen && state.todoOpen) toggleTodoWindow(false); state.progressWindow.hidden = !state.progressOpen; state.panel?.querySelector('.cxh-open-progress')?.setAttribute('aria-expanded', String(state.progressOpen)); if (state.progressOpen) renderProgressWindow(activeWorkerSummary()); } function todoStatusText(status) { if (status === 'running') return '进行中'; if (status === 'completed') return '已完成'; return '排队'; } function renderTodoWindow() { const root = state.todoWindow; if (!root || !state.todoOpen) return; const sorted = [...state.todos].sort((a, b) => a.courseOrder - b.courseOrder || a.taskOrder - b.taskOrder ); const counts = sorted.reduce((result, todo) => { result[todo.status] = (result[todo.status] || 0) + 1; return result; }, { pending: 0, running: 0, completed: 0 }); root.querySelector('.cxh-todo-pending').textContent = String(counts.pending || 0); root.querySelector('.cxh-todo-running').textContent = String(counts.running || 0); root.querySelector('.cxh-todo-completed').textContent = String(counts.completed || 0); const queueButton = root.querySelector('.cxh-queue-toggle'); queueButton.textContent = state.queuePaused || !state.enabled ? '继续队列' : '暂停队列'; const list = root.querySelector('.cxh-todo-list'); list.replaceChildren(); if (!sorted.length) { const empty = document.createElement('div'); empty.className = 'cxh-empty'; empty.textContent = '当前没有待办任务'; list.appendChild(empty); return; } const groups = new Map(); sorted.forEach((todo) => { const key = `${todo.courseOrder}:${todo.courseName}`; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(todo); }); groups.forEach((todos, key) => { const group = document.createElement('section'); group.className = 'cxh-todo-course'; const title = document.createElement('div'); title.className = 'cxh-todo-course-title'; title.textContent = key.slice(key.indexOf(':') + 1); group.appendChild(title); todos.forEach((todo) => { const row = document.createElement('div'); row.className = `cxh-todo-item is-${todo.status}`; const content = document.createElement('div'); content.className = 'cxh-todo-content'; const taskTitle = document.createElement('div'); taskTitle.className = 'cxh-todo-title'; taskTitle.textContent = todo.title; const meta = document.createElement('div'); meta.className = 'cxh-todo-meta'; meta.textContent = `${todo.type || '任务点'} · ${todoStatusText(todo.status)}`; content.append(taskTitle, meta); const status = document.createElement('span'); status.className = `cxh-todo-status is-${todo.status}`; status.textContent = todoStatusText(todo.status); const open = document.createElement('button'); open.type = 'button'; open.className = 'cxh-todo-open'; open.textContent = '打开'; open.disabled = !todo.url; open.addEventListener('click', () => { if (todo.url) location.assign(todo.url); }); row.append(content, status, open); group.appendChild(row); }); list.appendChild(group); }); } function toggleTodoWindow(force) { if (!state.todoWindow) return; state.todoOpen = typeof force === 'boolean' ? force : !state.todoOpen; if (state.todoOpen && state.progressOpen) toggleProgressWindow(false); state.todoWindow.hidden = !state.todoOpen; state.panel?.querySelector('.cxh-open-todos')?.setAttribute('aria-expanded', String(state.todoOpen)); if (state.todoOpen) renderTodoWindow(); } function toggleTodoQueue() { if (state.scanSession.status === 'scanning' || state.scanSession.status === 'paused') return; state.queuePaused = !(state.queuePaused || !state.enabled); state.enabled = !state.queuePaused; storageApi.set(STORE.queuePaused, state.queuePaused); storageApi.set(STORE.enabled, state.enabled); if (state.queuePaused) pauseLocalMedia(); else { resetFailedMedia(); broadcastToChildren({ type: MESSAGE_TYPE, kind: 'reset-media-failures' }); state.lastMediaFailureKey = ''; if (/媒体.*(无进度|卡住)/.test(state.lastError)) state.lastError = ''; activateNextTodo(); } pushLog(state.queuePaused ? '已暂停待办队列' : '已继续待办队列', true); updatePanel(); } function requestManualScan() { pushLog('课程自动扫描已移除,请从课程页面手动加入待办', true); return false; /* legacy scan request retained for old stored sessions if (state.scanSession.status === 'scanning' || state.scanSession.status === 'paused') return; if (isCourseHomePage()) { startCourseScan(true); return; } const sourceUrl = state.scanSession.sourceUrl; if (!sourceUrl) { pushLog('请先打开学习通课程首页再重新扫描', true); return; } state.scanSession = { ...state.scanSession, status: 'requested', manual: true }; saveScanSession(); navigateForScan(sourceUrl); */ } function createPanel() { if (!isController() || !document.body) return; if (state.panel?.isConnected && state.progressWindow?.isConnected && state.todoWindow?.isConnected) return; state.panel?.remove(); state.progressWindow?.remove(); state.todoWindow?.remove(); state.panel = null; state.progressWindow = null; state.todoWindow = null; let style = document.querySelector('#cx-helper-style'); if (!style) { style = document.createElement('style'); style.id = 'cx-helper-style'; style.textContent = ` #cx-helper-panel{box-sizing:border-box;position:fixed;z-index:2147483647;right:16px;bottom:16px;width:252px;padding:12px;background:#172033;color:#eef3ff;font:13px/1.5 Arial,sans-serif;border:1px solid #415273;border-radius:8px;box-shadow:0 8px 24px #0006} #cx-helper-panel .cxh-title{font-size:15px;font-weight:700;margin-bottom:5px} #cx-helper-panel .cxh-status{min-height:38px;color:#c6d4ef;margin-bottom:7px;word-break:break-word} #cx-helper-panel .cxh-progress{color:#93a9cf;margin-bottom:8px} #cx-helper-panel .cxh-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px} #cx-helper-panel .cxh-speed{width:66px;background:#0e1523;color:#fff;border:1px solid #526687;border-radius:4px;padding:2px 4px} #cx-helper-panel .cxh-actions{display:flex;gap:5px;flex-wrap:wrap} #cx-helper-panel .cxh-actions button{display:inline-flex;align-items:center;justify-content:center;width:auto;height:32px;min-width:0;min-height:0;margin:0;background:#2d6cdf;color:#fff;border:0;border-radius:4px;padding:5px 8px;font:13px/1 Arial,sans-serif;cursor:pointer} #cx-helper-panel .cxh-actions button:hover{filter:brightness(1.15)} #cx-helper-progress-window{box-sizing:border-box;position:fixed;z-index:2147483646;right:284px;bottom:16px;width:min(440px,calc(100vw - 316px));max-height:min(680px,calc(100vh - 32px));overflow:auto;padding:14px;background:#111827;color:#eef3ff;font:13px/1.5 Arial,sans-serif;border:1px solid #43506a;border-radius:8px;box-shadow:0 12px 30px #0008} #cx-helper-progress-window[hidden]{display:none} #cx-helper-progress-window .cxh-window-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px} #cx-helper-progress-window .cxh-window-title{font-size:16px;font-weight:700} #cx-helper-progress-window .cxh-close{width:30px;height:30px;padding:0;border:0;border-radius:4px;background:#293449;color:#fff;font-size:20px;line-height:30px;cursor:pointer} #cx-helper-progress-window .cxh-task-label,#cx-helper-progress-window .cxh-section-title{color:#94a3b8;font-size:12px;margin-bottom:4px} #cx-helper-progress-window .cxh-current-task{font-weight:700;margin-bottom:12px;overflow-wrap:anywhere} #cx-helper-progress-window .cxh-overview{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:14px} #cx-helper-progress-window .cxh-meter-head{display:flex;justify-content:space-between;margin-bottom:5px} #cx-helper-progress-window .cxh-meter-track{height:7px;background:#2b3548;border-radius:3px;overflow:hidden} #cx-helper-progress-window .cxh-meter-fill{height:100%;width:0;background:#22c55e;transition:width .2s ease} #cx-helper-progress-window [data-meter="tasks"] .cxh-meter-fill{background:#38bdf8} #cx-helper-progress-window [data-meter="questions"] .cxh-meter-fill{background:#f59e0b} #cx-helper-progress-window .cxh-counts{display:flex;gap:18px;margin-bottom:14px;color:#cbd5e1} #cx-helper-progress-window .cxh-counts strong{color:#fff} #cx-helper-progress-window .cxh-section{border-top:1px solid #2c374a;padding-top:11px;margin-top:11px} #cx-helper-progress-window .cxh-worker-row{padding:8px 0;border-bottom:1px solid #222d40} #cx-helper-progress-window .cxh-worker-header{display:flex;align-items:center;justify-content:space-between;gap:8px} #cx-helper-progress-window .cxh-state{font-size:12px;padding:1px 6px;border-radius:4px;background:#334155;color:#dbeafe} #cx-helper-progress-window .cxh-state.is-busy{background:#713f12;color:#fde68a} #cx-helper-progress-window .cxh-state.is-ready{background:#14532d;color:#bbf7d0} #cx-helper-progress-window .cxh-state.is-idle{background:#334155;color:#cbd5e1} #cx-helper-progress-window .cxh-worker-location{color:#94a3b8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} #cx-helper-progress-window .cxh-worker-details{color:#cbd5e1;margin-top:2px} #cx-helper-progress-window .cxh-log-item{padding:4px 0;border-bottom:1px solid #222d40;overflow-wrap:anywhere} #cx-helper-progress-window .cxh-empty{color:#94a3b8;padding:8px 0} #cx-helper-progress-window .cxh-updated-at{color:#64748b;font-size:12px;margin-top:10px;text-align:right} #cx-helper-todo-window{box-sizing:border-box;position:fixed;z-index:2147483646;right:284px;bottom:16px;width:min(520px,calc(100vw - 316px));max-height:min(720px,calc(100vh - 32px));overflow:auto;padding:14px;background:#111827;color:#eef3ff;font:13px/1.5 Arial,sans-serif;border:1px solid #43506a;border-radius:8px;box-shadow:0 12px 30px #0008} #cx-helper-todo-window[hidden]{display:none} #cx-helper-todo-window .cxh-todo-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px} #cx-helper-todo-window .cxh-todo-window-title{font-size:16px;font-weight:700} #cx-helper-todo-window .cxh-todo-close{width:30px;height:30px;padding:0;border:0;border-radius:4px;background:#293449;color:#fff;font-size:20px;line-height:30px;cursor:pointer} #cx-helper-todo-window .cxh-todo-scan-status{color:#94a3b8;margin-bottom:10px} #cx-helper-todo-window .cxh-todo-summary{display:flex;gap:18px;padding:9px 0;border-top:1px solid #2c374a;border-bottom:1px solid #2c374a;color:#cbd5e1} #cx-helper-todo-window .cxh-todo-summary strong{color:#fff} #cx-helper-todo-window .cxh-todo-controls{display:flex;flex-wrap:wrap;gap:7px;margin:10px 0} #cx-helper-todo-window .cxh-todo-controls button,#cx-helper-todo-window .cxh-todo-open{display:inline-flex;align-items:center;justify-content:center;width:auto;height:30px;min-width:0;min-height:0;margin:0;padding:4px 8px;border:0;border-radius:4px;background:#2d6cdf;color:#fff;font:13px/1 Arial,sans-serif;cursor:pointer} #cx-helper-todo-window button:disabled{opacity:.45;cursor:default} #cx-helper-todo-window .cxh-todo-course{margin-top:12px} #cx-helper-todo-window .cxh-todo-course-title{font-weight:700;padding:6px 0;color:#e2e8f0;border-bottom:1px solid #334155} #cx-helper-todo-window .cxh-todo-item{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:8px;padding:9px 0;border-bottom:1px solid #222d40} #cx-helper-todo-window .cxh-todo-item.is-completed{opacity:.65} #cx-helper-todo-window .cxh-todo-title{overflow-wrap:anywhere} #cx-helper-todo-window .cxh-todo-meta{color:#94a3b8;font-size:12px;margin-top:2px} #cx-helper-todo-window .cxh-todo-status{font-size:12px;padding:1px 6px;border-radius:4px;background:#334155;color:#cbd5e1} #cx-helper-todo-window .cxh-todo-status.is-running{background:#713f12;color:#fde68a} #cx-helper-todo-window .cxh-todo-status.is-completed{background:#14532d;color:#bbf7d0} #cx-helper-todo-window .cxh-empty{color:#94a3b8;padding:14px 0} @media(max-width:760px){#cx-helper-progress-window,#cx-helper-todo-window{z-index:2147483647;left:12px;right:12px;top:12px;bottom:12px;width:auto;max-height:none}#cx-helper-progress-window .cxh-overview{grid-template-columns:1fr}#cx-helper-todo-window .cxh-todo-item{grid-template-columns:minmax(0,1fr) auto}#cx-helper-todo-window .cxh-todo-open{grid-column:2}} `; document.documentElement.appendChild(style); } const panel = document.createElement('div'); panel.id = 'cx-helper-panel'; panel.innerHTML = `