// ==UserScript== // @name 学习通课程任务助手 // @namespace local.chaoxing.course.helper // @version 1.3.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: 1500, workerTtl: 6500, navigationCooldown: 8000, completionStableTime: 2500, detailPageDelay: 1800, 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*="下一"]' ], 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' ], 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 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)), scanPageEnteredAt: Date.now(), scanExpanded: false, scanNavigationAt: 0, 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, 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, failedAt: 0, playAttemptAt: 0, uiAttemptAt: 0 }; state.media.set(media, info); media.addEventListener('ended', () => { info.completed = true; pushLog(`媒体 ${index + 1} 已完成`); }); } media.playbackRate = state.speed; media.muted = true; return info; } 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; pushLog(`开始媒体 ${index + 1}/${total},${state.speed}x`); } 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(() => { info.failedAt = Date.now(); }); } else { markMediaStarted(info, index, total); } } catch (_) { info.failedAt = now; } } function processMedia() { const mediaList = Array.from(document.querySelectorAll('video, audio')).filter(isVisible); let completed = 0; let playing = 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, playing: false }); return; } if (!permitted && !media.paused) { try { media.pause(); } catch (_) { // Some custom players expose a read-only media facade. } } if (!media.paused) playing += 1; if (permitted && media.paused) attemptMediaStart(media, info, index, mediaList.length); items.push({ index, completed: false, playing: permitted && !media.paused }); }); return { total: mediaList.length, completed, playing, 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 = []; workers.forEach((worker) => { (worker.media.items || []).forEach((item) => { if (!item.completed) candidates.push({ workerId: worker.id, index: item.index }); }); }); const selected = 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 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.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, questionTotal: 0, questionCompleted: 0, questionPending: 0, hasWork: false, busy: false }); if (summary.hasWork) state.seenWork = true; return summary; } 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 (firstVisible(CONFIG.selectors.incomplete, node)) return false; if (/completed|(^|[-_\s])finished($|[-_\s])|jobfinish|icon_completed/i.test(className)) return true; if (/已完成/.test(title)) return true; return Boolean(firstVisible(CONFIG.selectors.completed, node)); } function hasIncompleteMarker(node) { if (!node) return false; if (/unfinished|unfinish/i.test(node.className || '')) return true; if (/未完成/.test(node.getAttribute?.('title') || '')) return true; return Boolean(firstVisible(CONFIG.selectors.incomplete, node)); } function catalogEntries() { const candidates = queryAllInOrder(CONFIG.selectors.catalog).filter(isVisible); const entries = []; candidates.forEach((node) => { const clickable = node.closest('a[href]') || node; if (!entries.includes(clickable) && normalize(clickable.textContent).length > 0) entries.push(clickable); }); return entries; } 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 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; } 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 = queryAllInOrder([ 'a[href*="courseId="]', 'a[href*="courseid="]', 'a[href*="clazzid="]', 'a[href*="/mycourse/"]' ]).filter((link) => isVisible(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( '.courseItem, .course-item, .course_item, .course-card, .Mconright, li, article' ) || 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 = queryAllInOrder(CONFIG.selectors.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) { return scanCatalogEntries() .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 })); } 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), 150); 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 }; 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 expandCatalogForScan() { if (state.scanExpanded) return; state.scanExpanded = true; queryAllInOrder([ '#courseChapter .chapter_unit', '#courseChapter .chapterText', '.chapter_item .chapterText', '.catalog_level .chapterText' ]).filter(isVisible).forEach((node) => { if (!/open|expanded|on/i.test(node.className || '')) clickElement(node); }); } function finishCourseScan() { state.scanSession.status = 'complete'; 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(); pushLog(`扫描完成:${state.todos.length} 个未完成任务点`, 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 processCourseScanner() { if (!isController()) return false; 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 = courses[state.scanSession.index]; if (!course) { finishCourseScan(); return false; } const currentId = courseIdentity(location.href); if (currentId !== course.id && !isCourseDetailPage()) { navigateForScan(course.url); return true; } expandCatalogForScan(); const elapsed = Date.now() - state.scanPageEnteredAt; const entries = scanCatalogEntries(); if (elapsed < 2200 || (!entries.length && elapsed < 9000)) return true; const courseTodos = extractPendingTodos(course); state.todos = state.todos.filter((todo) => todo.courseId !== course.id).concat(courseTodos); saveTodos(); state.scanSession.index += 1; saveScanSession(); state.scanExpanded = false; const next = courses[state.scanSession.index]; if (next) { pushLog(`已扫描 ${state.scanSession.index}/${courses.length}:${course.name}`); navigateForScan(next.url); return true; } finishCourseScan(); return false; } 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) { if (!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 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() || state.scanSession.status === 'scanning') 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 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 scanStatusText() { const session = state.scanSession; if (session.status === 'scanning') { const total = Array.isArray(session.courses) ? session.courses.length : 0; const current = Math.min(Number(session.index || 0) + 1, total); return `正在扫描课程 ${current}/${total}`; } if (session.status === 'requested') return '正在返回课程首页准备扫描'; if (session.status === 'complete') { return `扫描完成 · ${new Date(session.completedAt || Date.now()).toLocaleTimeString()}`; } 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-scan-status').textContent = scanStatusText(); 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 ? '继续队列' : '暂停队列'; queueButton.disabled = state.scanSession.status === 'scanning'; root.querySelector('.cxh-rescan').disabled = state.scanSession.status === 'scanning'; const list = root.querySelector('.cxh-todo-list'); list.replaceChildren(); if (!sorted.length) { const empty = document.createElement('div'); empty.className = 'cxh-empty'; empty.textContent = state.scanSession.status === 'scanning' ? '正在收集未完成任务点' : '当前没有待办任务'; 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') 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 activateNextTodo(); pushLog(state.queuePaused ? '已暂停待办队列' : '已继续待办队列', true); updatePanel(); } function requestManualScan() { if (state.scanSession.status === 'scanning') 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;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 = `
学习通课程助手
`; const progressWindow = document.createElement('section'); progressWindow.id = 'cx-helper-progress-window'; progressWindow.hidden = true; progressWindow.setAttribute('aria-label', '课程进度'); progressWindow.innerHTML = `
课程进度
当前任务
任务点0/0
媒体0/0
题目0/0
待处理题目 0未匹配题目 0
页面与播放器
最近记录
`; const todoWindow = document.createElement('section'); todoWindow.id = 'cx-helper-todo-window'; todoWindow.hidden = true; todoWindow.setAttribute('aria-label', '本地待办列表'); todoWindow.innerHTML = `
本地待办
排队 0 进行中 0 已完成 0
`; document.body.appendChild(panel); document.body.appendChild(progressWindow); document.body.appendChild(todoWindow); panel.querySelector('.cxh-speed').addEventListener('change', (event) => { state.speed = clampSpeed(event.target.value); event.target.value = state.speed; storageApi.set(STORE.speed, state.speed); }); panel.querySelector('.cxh-auto-jump').addEventListener('change', (event) => { state.autoJump = event.target.checked; state.detailJumpAttempted = false; storageApi.set(STORE.autoJump, state.autoJump); }); panel.querySelector('.cxh-toggle').addEventListener('click', toggleEnabled); panel.querySelector('.cxh-open-todos').addEventListener('click', () => toggleTodoWindow()); panel.querySelector('.cxh-open-progress').addEventListener('click', () => toggleProgressWindow()); panel.querySelector('.cxh-import').addEventListener('click', importBank); panel.querySelector('.cxh-export').addEventListener('click', exportUnanswered); progressWindow.querySelector('.cxh-close').addEventListener('click', () => toggleProgressWindow(false)); todoWindow.querySelector('.cxh-todo-close').addEventListener('click', () => toggleTodoWindow(false)); todoWindow.querySelector('.cxh-queue-toggle').addEventListener('click', toggleTodoQueue); todoWindow.querySelector('.cxh-rescan').addEventListener('click', requestManualScan); state.panel = panel; state.progressWindow = progressWindow; state.todoWindow = todoWindow; updatePanel(); } function updatePanel(summary = activeWorkerSummary()) { if (!state.panel) return; state.panel.querySelector('.cxh-toggle').textContent = state.enabled ? '暂停' : '启动'; state.panel.querySelector('.cxh-speed').value = state.speed; state.panel.querySelector('.cxh-auto-jump').checked = state.autoJump; state.panel.querySelector('.cxh-status').textContent = state.lastError ? `异常:${state.lastError}` : state.scanSession.status === 'scanning' || state.scanSession.status === 'requested' ? scanStatusText() : state.lastLog || (state.enabled ? '运行中' : '已暂停'); const course = courseProgress(); const todoPending = state.todos.filter((todo) => todo.status === 'pending').length; const todoRunning = state.todos.filter((todo) => todo.status === 'running').length; state.panel.querySelector('.cxh-progress').textContent = `待办 ${todoRunning}/${todoPending + todoRunning} · 任务 ${course.completed}/${course.total} · 媒体 ${summary.mediaCompleted}/${summary.mediaTotal}`; renderProgressWindow(summary); renderTodoWindow(); } function onMessage(event) { const data = event.data; if (!data || data.type !== MESSAGE_TYPE) return; if (data.kind === 'controller-probe') { if (isController() && event.source && typeof event.source.postMessage === 'function') { event.source.postMessage({ type: MESSAGE_TYPE, kind: 'controller-present' }, '*'); } return; } if (data.kind === 'controller-present') { parentControllerSeen = true; if (!IS_TOP && isController()) deactivateController(); return; } if (data.kind === 'media-permit' && data.permit) { if (Number(data.permit.revision || 0) >= Number(state.mediaPermit.revision || 0)) { state.mediaPermit = data.permit; } broadcastToChildren(data); return; } if (!isController()) { const hops = Number(data.hops || 0); if (hops < 8 && window.parent !== window) { window.parent.postMessage({ ...data, hops: hops + 1 }, '*'); } return; } if (data.kind === 'status' && data.status?.id) { if (Date.now() < state.ignoreWorkerUntil) return; state.workers.set(data.status.id, data.status); selectMediaPermit(); const summary = activeWorkerSummary(); maybeAdvance(summary); updatePanel(summary); } else if (data.kind === 'log' && typeof data.message === 'string') { pushLog(data.message); } } function runCycle() { if (state.running) return; state.running = true; try { if (isController()) { if (!state.panel?.isConnected || !state.progressWindow?.isConnected || !state.todoWindow?.isConnected) createPanel(); syncTaskContext(); } const scanning = isController() ? processCourseScanner() : state.scanSession.status === 'scanning'; if (scanning) { pauseLocalMedia(); publishWorkerStatus({ id: WORKER_ID, url: location.href, framePath: FRAME_PATH, at: Date.now(), media: { total: 0, completed: 0, playing: 0, items: [] }, questions: { total: 0, completed: 0, pending: 0 }, hasWork: false, busy: false }); if (isController()) updatePanel(activeWorkerSummary()); return; } const activeTodo = isController() ? processTodoQueue() : null; if (activeTodo && !todoMatchesLocation(activeTodo)) { pauseLocalMedia(); publishWorkerStatus({ id: WORKER_ID, url: location.href, framePath: FRAME_PATH, at: Date.now(), media: { total: 0, completed: 0, playing: 0, items: [] }, questions: { total: 0, completed: 0, pending: 0 }, hasWork: false, busy: false }); updatePanel(activeWorkerSummary()); return; } if (state.enabled) { const status = buildWorkerStatus(); publishWorkerStatus(status); } else { pauseLocalMedia(); publishWorkerStatus({ id: WORKER_ID, url: location.href, framePath: FRAME_PATH, at: Date.now(), media: { total: 0, completed: 0, playing: 0, items: [] }, questions: { total: 0, completed: 0, pending: 0 }, hasWork: false, busy: false }); } if (isController()) { jumpFromCourseDetail(); selectMediaPermit(); const summary = activeWorkerSummary(); maybeAdvance(summary); updatePanel(summary); } } catch (error) { reportError(error); } finally { state.running = false; } } function boot() { window.addEventListener('message', onMessage); if (IS_TOP) { activateController(); } else if (IS_DIRECT_CHILD) { probeParentController(); window.setTimeout(probeParentController, 250); window.setTimeout(() => { if (!parentControllerSeen) activateController(); }, 700); } bindStoreListeners(); runCycle(); if (!state.timer) state.timer = window.setInterval(runCycle, CONFIG.interval); } function showBootFailure(error) { console.error('[XXT] startup failed', error); if (!document.body || document.querySelector('#cx-helper-boot-error')) return; const notice = document.createElement('div'); notice.id = 'cx-helper-boot-error'; notice.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:2147483647;max-width:320px;padding:12px;background:#7f1d1d;color:#fff;border:1px solid #fecaca;border-radius:6px;font:13px/1.5 Arial,sans-serif;word-break:break-word'; notice.textContent = `学习通课程助手启动异常:${error instanceof Error ? error.message : String(error)}`; document.body.appendChild(notice); } function safeBoot() { try { boot(); } catch (error) { showBootFailure(error); } } if (PAGE_WINDOW.__XXT_ENABLE_TEST_API__) { PAGE_WINDOW.__XXT_TEST_API__ = { discoverCurrentSemesterCourses, extractPendingTodos, isCurrentSemesterCourse, compareFramePaths, activateNextTodo, markRunningTodoComplete, processTodoQueue, todoMatchesLocation }; } if (document.body) safeBoot(); else window.addEventListener('DOMContentLoaded', safeBoot, { once: true }); })();