// ==UserScript== // @name 头歌助手 // @namespace edu-helper.local // @version 0.6.1 // @author 如风 // @description 头歌实训纯接口自动化:扫描 → 队列 → 逐关答题,全程不跳页 // @match https://www.educoder.net/* // @match https://educoder.net/* // @run-at document-idle // @noframes // @grant GM_xmlhttpRequest // @connect data.educoder.net // ==/UserScript== /* * 分层结构(自下而上,单向依赖): * Crypto 签名用 MD5 * Session 身份:Cookie / 会话 / zzud * Http 带签名的单次请求,统一错误码 * Api 平台接口(课程、作业、关卡、提交) * Model 接口数据 → 领域对象(题型、题目、通过判定) * Scanner 发现:课程 → 作业 → 关卡链 * Solver 单关执行:答题 → 等结果 * Runner 队列调度(唯一的状态机) * View 渲染(只读 state,不发起请求) */ (() => { 'use strict'; if (document.querySelector('tg-answer-assistant')) return; const VERSION = '0.6.1'; const API = 'https://data.educoder.net/api'; const AK = 'e9dd5b4322f9f7d83d009de9bfa100c3'; const SK = '2e3da06ae26ba9f76a5d8d355746f2fe'; const POLL_MS = 1500; // 等评分轮询间隔 const PASS_TIMEOUT = 25000; // 单关等通过上限 const STEP_MS = 300; // 关卡之间间隔 const ERROR_TEXT = { 401: '登录已过期', '-102': '签名被拒绝', '-2': '平台繁忙', '-1': '参数错误', 404: '关卡不存在', }; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const norm = value => String(value ?? '').normalize('NFKC').replace(/\s+/g, ' ').trim(); const splitPaths = raw => String(raw ?? '').split(/[;;]/).map(part => part.trim()).filter(Boolean); /* ============================================================ * Crypto —— 签名用 MD5(浏览器没有内置实现) * ========================================================== */ const Crypto = (() => { function md5Ascii(text) { const bytes = new Uint8Array(Math.ceil((text.length + 9) / 64) * 64); for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i); bytes[text.length] = 128; const view = new DataView(bytes.buffer); view.setUint32(bytes.length - 8, text.length * 8, true); const state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; const shifts = [[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]]; for (let offset = 0; offset < bytes.length; offset += 64) { let [a, b, c, d] = state; for (let i = 0; i < 64; i++) { const round = i >>> 4; const f = [(b & c) | (~b & d), (d & b) | (~d & c), b ^ c ^ d, c ^ (b | ~d)][round]; const word = [i, 5 * i + 1, 3 * i + 5, 7 * i][round] % 16; const k = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); const sum = (a + f + k + view.getUint32(offset + word * 4, true)) | 0; const shift = shifts[round][i % 4]; [a, b, c, d] = [d, (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0, b, c]; } [a, b, c, d].forEach((x, i) => { state[i] = (state[i] + x) | 0; }); } return state.flatMap(x => [0, 8, 16, 24].map(n => ((x >>> n) & 255).toString(16).padStart(2, '0'))).join(''); } const b64 = text => btoa(text); return { sign(method) { const time = Date.now(); const payload = `method=${method}&ak=${AK}&sk=${SK}&time=${time}`; return [time, md5Ascii(b64(payload))]; }, }; })(); /* ============================================================ * Session —— 身份 * ========================================================== */ const Session = { read(name) { const hit = document.cookie.split(';').map(x => x.trim()).find(x => x.startsWith(name + '=')); return hit ? hit.slice(name.length + 1) : ''; }, value() { return this.read('_educoder_session'); }, autologin() { return this.read('autologin_trustie'); }, cookieHeader() { const parts = []; if (this.autologin()) parts.push(`autologin_trustie=${this.autologin()}`); if (this.value()) parts.push(`_educoder_session=${this.value()}`); return parts.join('; '); }, zzud() { return new URL(location.href).searchParams.get('zzud') || sessionStorage.getItem('tg.zzud') || localStorage.getItem('tg.zzud') || ''; }, }; /* ============================================================ * Http —— 单次请求 + 统一错误 * ========================================================== */ const Http = { call(method, path, body) { const [time, signature] = Crypto.sign(method); const headers = { 'X-EDU-Type': 'pc', 'X-EDU-Timestamp': String(time), 'X-EDU-Signature': signature, 'Pc-Authorization': Session.value() || 'null', 'Accept': 'application/json', }; const cookie = Session.cookieHeader(); if (cookie) headers.Cookie = cookie; let data; if (body !== undefined) { data = JSON.stringify(body); headers['Content-Type'] = 'application/json; charset=utf-8'; } return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method, url: API + path, headers, data, timeout: 20000, responseType: 'json', onerror: () => reject(new Error('网络错误')), ontimeout: () => reject(new Error('请求超时')), onload: res => { const payload = res.response; if (res.status !== 200 || !payload || typeof payload !== 'object') { reject(new Error(`请求失败 HTTP ${res.status}`)); return; } const code = payload.status; if (ERROR_TEXT[code] !== undefined) { const error = new Error(ERROR_TEXT[code]); error.code = code; reject(error); return; } resolve(payload); }, }); }); }, get(path) { return this.call('GET', path); }, post(path, body) { return this.call('POST', path, body); }, }; /* ============================================================ * Api —— 平台接口 * ========================================================== */ const Api = { courses() { const query = `page=1&limit=100&order=mine&search=&zzud=${encodeURIComponent(Session.zzud())}`; return Http.get(`/courses.json?${query}`).then(data => data.courses || []); }, homeworks(courseId) { const query = `limit=100&status=0&id=${encodeURIComponent(courseId)}&type=4&order=0&zzud=${encodeURIComponent(Session.zzud())}`; return Http.get(`/courses/${encodeURIComponent(courseId)}/homework_commons.json?${query}`) .then(data => data.homeworks || []); }, entryGame(shixunId, homeworkId) { const query = `homework_common_id=${homeworkId}&zzud=${encodeURIComponent(Session.zzud())}`; return Http.get(`/shixuns/${encodeURIComponent(shixunId)}/shixun_exec.json?${query}`) .then(data => (data.game_identifier ? String(data.game_identifier) : '')); }, detail(gameId, homeworkId) { const query = `homework_common_id=${homeworkId}&zzud=${encodeURIComponent(Session.zzud())}`; return Http.get(`/tasks/${encodeURIComponent(gameId)}.json?${query}`); }, choose(gameId, homeworkId, body) { const query = `zzud=${encodeURIComponent(Session.zzud())}`; return Http.post(`/tasks/${encodeURIComponent(gameId)}/choose_build.json?${query}`, body); }, }; /* ============================================================ * Model —— 接口数据 → 领域对象 * ========================================================== */ const Model = { /** 只有这两种数字才是错误,顶层 status 成功时是字符串 "required"。 */ isError(body) { return body && typeof body === 'object' && ERROR_TEXT[body.status] !== undefined; }, /** @returns {{title,passed,kind,questions,paths,graphics,raw}} */ read(detail) { const challenge = detail.challenge || {}; const game = detail.game || {}; const env = (detail.shixun_environments || [])[0] || {}; // 单选/多选不做区分:一律「选出全部正确项」,答案就是字母拼接("A" / "ACD")。 // category 仅用于界面提示,2 = 多选,1 = 单选。 const questions = (detail.chooses || []).map(item => ({ position: Number(item.position) || 0, title: norm(item.subject), multi: Number(item.category) === 2, options: (item.challenge_question || []) .slice() .sort((a, b) => Number(a.position) - Number(b.position)) .map((option, index) => ({ letter: String.fromCharCode(65 + index), text: norm(option.option_name) })), })).filter(item => item.options.length); const paths = splitPaths(challenge.path); const graphics = env.tab_type === 3 || /StarUML|VNC|Logisim/i.test(String(detail.mirror_name || '')); const kind = questions.length ? (paths.length ? 'mixed' : 'choice') : (paths.length ? 'code' : 'empty'); return { title: norm(challenge.subject) || '(未命名关卡)', body: String(challenge.task_pass ?? ''), challengeId: challenge.id, passed: game.status === 2, kind, questions, paths, graphics, env, raw: detail, }; }, }; /* ============================================================ * 路由 —— 从 URL 取上下文 * ========================================================== */ const Route = { path() { return location.pathname.replace(/\/$/, ''); }, parts() { return location.pathname.split('/').filter(Boolean); }, /** 班级作业列表页 /classrooms/{课程标识}/... */ courseId() { const hit = location.pathname.match(/^\/classrooms\/([^/]+)/); return hit ? hit[1] : ''; }, isTask(path = this.path()) { return /^\/tasks\/[^/]+\/[^/]+\/[^/]+\/?$/.test(path); }, /** 作业详情页 /classrooms/{课程}/shixun_homework/{作业}/... → 只处理这一份。 */ homeworkId() { const hit = location.pathname.match(/\/shixun_homework\/(\d+)/); return hit ? Number(hit[1]) : 0; }, taskUrl(courseId, homeworkId, gameId) { return `${location.origin}/tasks/${encodeURIComponent(courseId)}/${homeworkId}/${encodeURIComponent(gameId)}`; }, keyOf(url = location.href) { const parts = new URL(url).pathname.split('/').filter(Boolean); if (parts[0] !== 'tasks' || parts.length < 3) throw new Error('不是关卡地址'); const homeworkId = new URL(url).searchParams.get('homework_common_id') || parts[2]; return { gameId: parts[3] || parts[parts.length - 1], homeworkId, courseId: parts[1] }; }, }; /* ============================================================ * Scanner —— 发现课程 / 作业 / 关卡链 * ========================================================== */ const Scanner = { /** 还有关卡没做完的作业。 */ open(works) { return works.filter(work => { const total = Number(work.challenge_count) || 0; const done = Number(work.finished_challenge_count) || 0; return total > 0 && done < total; }); }, /** 入口关卡是链尾,沿 prev_game 回溯到链头。 */ async chain(work, courseId) { const entry = await Api.entryGame(work.shixun_identifier, work.homework_id); if (!entry) return []; const chain = []; let cursor = String(entry); while (cursor && cursor !== 'null' && !chain.includes(cursor)) { chain.push(cursor); let detail; try { detail = await Api.detail(cursor, work.homework_id); } catch { break; } cursor = detail?.prev_game ? String(detail.prev_game) : ''; } return chain.reverse().map(gameId => ({ gameId, homeworkId: work.homework_id, courseId, url: Route.taskUrl(courseId, work.homework_id, gameId), })); }, /** 当前页面能覆盖到的作业:班级页 → 本课程;关卡页 → 该作业。 */ async homeworkList(courseId) { // 停在某份作业的详情页时,只处理这一份,且不受「是否已完成」限制。 const pinned = Route.homeworkId(); if (pinned) { const works = await Api.homeworks(courseId || Route.keyOf().courseId); return works.filter(work => Number(work.homework_id) === pinned); } if (courseId) return this.open(await Api.homeworks(courseId)); if (!Route.isTask()) throw new Error('请先打开班级作业列表页、作业详情页或任意关卡'); const key = Route.keyOf(); const works = await Api.homeworks(key.courseId); const one = works.find(work => Number(work.homework_id) === Number(key.homeworkId)); return one ? [one] : []; }, async courseName(courseId) { if (!courseId) return ''; try { const courses = await Api.courses(); const hit = courses.find(course => course.identifier === courseId); return hit ? norm(hit.name) : courseId; } catch { return courseId; } }, }; /* ============================================================ * Solver —— 单关执行 * ========================================================== */ const Solver = { /** 平台在提交响应里回吐标准答案,所以先发占位答案再正答。 */ async probe(detail, key, count) { const body = { answer: Array(count).fill('A'), challenge_id: detail.challenge.id, subject_id: null, question_id: null, competition_entry_id: null, smart_plan_page_item_bank_id: null, }; const probe = await Api.choose(key.gameId, key.homeworkId, body); const served = new Map((probe.test_sets || []) .map(item => [Number(item.position), item.standard_answer])); const answers = (detail.chooses || []) .slice() .sort((a, b) => Number(a.position) - Number(b.position)) .map(item => served.get(Number(item.position))); if (answers.length !== count || answers.some(answer => typeof answer !== 'string' || !/^[A-Z]+$/.test(answer))) { throw new Error('平台未返回完整答案'); } return answers; }, async submitChoice(detail, key, count) { const answers = await this.probe(detail, key, count); const result = await Api.choose(key.gameId, key.homeworkId, { answer: answers, challenge_id: detail.challenge.id, subject_id: null, question_id: null, competition_entry_id: null, smart_plan_page_item_bank_id: null, }); return { answers, result }; }, async waitPassed(key, timeout = PASS_TIMEOUT) { const deadline = Date.now() + timeout; while (Date.now() < deadline) { await sleep(POLL_MS); let detail; try { detail = await Api.detail(key.gameId, key.homeworkId); } catch { continue; } if (detail?.game?.status === 2) return true; } return false; }, }; /* ============================================================ * Runner —— 唯一的状态机 * ========================================================== */ const State = { phase: 'idle', // idle | scanning | countdown | running | paused | done token: 0, course: { id: '', name: '' }, jobs: [], // {id, name, total, passed, status} queue: [], // {gameId, homeworkId, courseId, url} cursor: null, // 当前项 results: { passed: [], skipped: [], failed: [] }, logs: [], }; /* 配置独立存放,View 与 Runner 各自读取,互不依赖。 */ const Prefs = { data: { delay: 1, auto: false }, load() { try { const saved = JSON.parse(localStorage.getItem('tg.prefs.v6') || '{}'); if (saved.delay) this.data.delay = Number(saved.delay) || 1; if (typeof saved.auto === 'boolean') this.data.auto = saved.auto; } catch { /* 用默认值 */ } }, save() { localStorage.setItem('tg.prefs.v6', JSON.stringify(this.data)); }, }; const Runner = { /** 正在推进(不包含暂停)。 */ active() { return ['countdown', 'running'].includes(State.phase); }, /** 占用中:可用于控制「停止」按钮。 */ busy() { return ['countdown', 'running', 'paused'].includes(State.phase); }, log(message, tone = 'blue') { State.logs.push([new Date().toLocaleTimeString('zh-CN', { hour12: false }), message, tone]); State.logs = State.logs.slice(-40); View.render(); }, jobOf(homeworkId) { return State.jobs.find(job => String(job.id) === String(homeworkId)) || null; }, markJob(homeworkId, passed) { const job = this.jobOf(homeworkId); if (!job) return; if (passed) job.passed = Math.min(job.total, job.passed + 1); if (job.passed >= job.total) job.status = 'done'; }, /** 扫描:只读,不提交。 */ async scan() { const courseId = Route.courseId() || (Route.isTask() ? Route.keyOf().courseId : ''); State.course = { id: courseId, name: await Scanner.courseName(courseId) }; const pinned = Route.homeworkId(); State.jobs = (await Scanner.homeworkList(courseId)).map(work => ({ id: work.homework_id, name: norm(work.name), shixun: work.shixun_identifier, // 指定作业时以总关卡数为分母,逐关判定会在处理时补齐; // 课程级扫描时只算真正没做完的部分。 total: pinned ? Number(work.challenge_count) || 0 : Number(work.challenge_count) - Number(work.finished_challenge_count), passed: 0, status: 'pending', })); View.render(); const total = State.jobs.reduce((sum, job) => sum + job.total, 0); this.log(State.jobs.length ? `发现 ${State.jobs.length} 份作业,共 ${total} 关待处理` : '没有待处理的作业', State.jobs.length ? 'green' : 'amber'); return State.jobs; }, /** 构建队列:逐份作业取关卡链。 */ async build() { const queue = []; for (const job of State.jobs) { if (State.phase === 'paused') break; try { const items = await Scanner.chain({ ...job, homework_id: job.id, shixun_identifier: job.shixun }, State.course.id); this.log(`· ${job.name} ${items.length} 关`); queue.push(...items); } catch (error) { this.log(`· ${job.name} 读取失败:${error.message}`, 'amber'); } } return queue; }, async start(auto = false) { if (this.active()) return; if (State.phase === 'paused') { State.phase = 'running'; this.log('继续处理队列'); this.run(State.token); return; } State.phase = 'scanning'; View.render(); try { await this.scan(); if (!State.jobs.length) { State.phase = 'idle'; View.render(); return; } this.log('正在读取关卡列表…'); State.queue = await this.build(); } catch (error) { State.phase = 'paused'; this.log(`初始化失败:${error.message}`, 'amber'); View.render(); return; } if (!State.queue.length) { State.phase = 'idle'; this.log('没有可处理的关卡', 'amber'); View.render(); return; } this.log(`队列共 ${State.queue.length} 关,开始后台处理`, 'green'); State.phase = 'countdown'; View.render(); const token = ++State.token; setTimeout(() => { if (token !== State.token) return; State.phase = 'running'; this.run(token); }, Math.max(1, Prefs.data.delay) * 1000); }, /** 队列循环:全程接口,不跳页。 */ async run(token) { while (State.queue.length) { if (token !== State.token) return; const item = State.queue.shift(); State.cursor = item; View.render(); let outcome; try { outcome = await this.handle(item, token); } catch (error) { if (token !== State.token) return; outcome = { status: 'failed', reason: error.message }; if (error.code === 401) { State.phase = 'paused'; this.log(error.message, 'amber'); View.render(); return; } } if (token !== State.token) return; this.record(item, outcome); View.render(); await sleep(STEP_MS); } if (token !== State.token) return; State.phase = 'done'; State.cursor = null; this.log('全部关卡处理结束', 'green'); View.render(); }, record(item, outcome) { if (outcome.status === 'passed') { State.results.passed.push(item); this.markJob(item.homeworkId, true); this.log(`✓ ${outcome.title || item.gameId} 已通过`, 'green'); } else if (outcome.status === 'skipped') { State.results.skipped.push({ ...item, reason: outcome.reason }); this.log(`⏭ ${outcome.title || item.gameId} ${outcome.reason}`, 'amber'); } else { State.results.failed.push({ ...item, reason: outcome.reason }); this.log(`✕ ${outcome.title || item.gameId} ${outcome.reason}`, 'red'); } }, /** 单关:读 → 判 → 答 → 等。 */ async handle(item, token) { let detail; try { detail = await Api.detail(item.gameId, item.homeworkId); } catch (error) { return { status: 'skipped', reason: `详情不可读(${error.message})` }; } const model = Model.read(detail); if (State.cursor === item) item.title = model.title; // 让界面显示真实关卡名 View.render(); if (model.passed) return { status: 'passed', title: model.title }; // 有题目就答,与 tab_type 无关:图形化环境里的选择题同样走 choose_build 接口。 if (!model.questions.length) { if (model.graphics) return { status: 'skipped', title: model.title, reason: '图形化环境需人工' }; if (model.kind === 'code') return { status: 'skipped', title: model.title, reason: '代码题暂不处理' }; return { status: 'skipped', title: model.title, reason: '没有可提交的题目' }; } if (token !== State.token) return { status: 'skipped', reason: '已中断' }; const key = { gameId: item.gameId, homeworkId: item.homeworkId }; const count = model.questions.length; const multi = model.questions.filter(question => question.multi).length; this.log(`→ ${model.title} ${count} 题${multi ? `(多选 ${multi})` : ''}`, 'blue'); const { result } = await Solver.submitChoice(detail, key, count); const correct = result?.choose_correct_num; const total = result?.challenge_chooses_count; this.log(` 已提交 ${correct ?? '?'}/${total ?? count}`); if (token !== State.token) return { status: 'skipped', reason: '已中断' }; const passed = await Solver.waitPassed(key); return passed ? { status: 'passed', title: model.title } : { status: 'failed', title: model.title, reason: `评测未通过(${correct ?? '?'}/${total ?? count})` }; }, pause() { if (!this.active()) return; State.token += 1; State.phase = 'paused'; this.log('已暂停', 'amber'); View.render(); }, stop() { State.token += 1; State.phase = 'done'; this.log('已停止', 'amber'); View.render(); }, reset() { State.token += 1; State.phase = 'idle'; State.jobs = []; State.queue = []; State.cursor = null; State.results = { passed: [], skipped: [], failed: [] }; View.render(); }, }; /* ============================================================ * View —— 只读渲染 * ========================================================== */ const View = { host: null, ui: null, $: null, get prefs() { return Prefs.data; }, build() { const host = document.createElement('tg-answer-assistant'); document.body.append(host); const ui = host.attachShadow({ mode: 'open' }); ui.innerHTML = `
`; this.host = host; this.ui = ui; this.$ = id => ui.getElementById(id); this.bind(); this.restore(); }, field(text, cls) { const span = document.createElement('span'); if (cls) span.className = cls; span.textContent = text; return span; }, toast(message, tone = 'blue') { const el = this.$('toast'); el.textContent = message; el.className = 'toast ' + tone; el.hidden = false; clearTimeout(this.timer); this.timer = setTimeout(() => { el.hidden = true; }, 2200); }, render() { const $ = this.$; const totals = State.jobs.reduce((acc, job) => { acc.total += job.total; acc.passed += job.passed; return acc; }, { total: 0, passed: 0 }); const done = State.results.passed.length; const total = State.queue.length + done + State.results.skipped.length + State.results.failed.length; const terminal = State.phase === 'done'; const active = Runner.active(); const busy = Runner.busy(); const planned = totals.total || total; $('pillCount').textContent = `${done}/${Math.max(planned, 1)}`; $('status').textContent = { idle: '待开始', scanning: '扫描中', countdown: '即将开始', running: '运行中', paused: '已暂停', done: '已完成' }[State.phase] || ''; $('course').textContent = State.course.name || '未进入课程'; $('current').textContent = State.cursor ? `${this.jobName(State.cursor.homeworkId)} · ${this.titleOf(State.cursor)}` : (State.phase === 'idle' ? '点「开始作答」扫描题目' : '准备中'); $('metric').textContent = `已通过 ${done} 跳过 ${State.results.skipped.length} 未通过 ${State.results.failed.length}`; $('bar').max = Math.max(1, planned); $('bar').value = done; const rows = State.jobs.map(job => { const row = document.createElement('div'); row.className = 'row'; const here = State.cursor && String(State.cursor.homeworkId) === String(job.id); const fin = job.status === 'done'; row.append( this.field(fin ? '✓' : here ? '▶' : '·', fin ? 'green' : here ? 'blue' : 'muted'), this.field(job.name, here ? 'blue' : ''), this.field(`${job.passed}/${job.total}`, 'muted'), this.field(fin ? '已通过' : here ? '进行中' : '待处理', fin ? 'green' : here ? 'blue' : 'muted'), ); return row; }); $('rows').replaceChildren(...(rows.length ? rows : [this.field(State.phase === 'scanning' ? '正在扫描…' : '尚未扫描', 'muted')])); $('logs').replaceChildren(...State.logs.slice(-6).map(([time, message, tone]) => { const row = document.createElement('div'); row.className = 'log'; row.append(this.field(time, 'muted'), this.field(message, tone)); return row; })); $('start').textContent = State.phase === 'paused' ? '继续' : active ? '暂停' : '开始作答'; $('stop').hidden = !busy; $('gear').hidden = active; $('summary').hidden = !terminal; $('work').hidden = terminal || !$('settings').hidden; if (terminal) { $('settings').hidden = true; $('totals').textContent = `通过 ${done} 关 跳过 ${State.results.skipped.length} 关 未通过 ${State.results.failed.length} 关`; $('resultBar').max = Math.max(1, total); $('resultBar').value = done; $('rate').textContent = total ? `通过率 ${(done / total * 100).toFixed(1)}%` : '暂无统计'; $('passedList').textContent = State.results.passed.map(item => this.titleOf(item)).join('、') || '无'; $('skippedList').textContent = this.grouped(State.results.skipped); $('failedList').textContent = this.grouped(State.results.failed); $('ended').textContent = `${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 处理结束`; } if (active) { if (this.originalTitle === null) this.originalTitle = document.title; document.title = `[${done}/${Math.max(total, 1)}] ${this.originalTitle}`; } else if (this.originalTitle !== null) { document.title = this.originalTitle; this.originalTitle = null; } }, /** 按原因归并,避免几十条同名项铺满面板。 */ grouped(items) { if (!items.length) return '无'; const map = new Map(); for (const item of items) { const reason = item.reason || '未标注'; if (!map.has(reason)) map.set(reason, []); map.get(reason).push(this.titleOf(item)); } return [...map].map(([reason, names]) => `${reason}(${names.length} 关)\n${names.slice(0, 4).join('、')}${names.length > 4 ? ' 等' : ''}` ).join('\n'); }, jobName(homeworkId) { const job = State.jobs.find(item => String(item.id) === String(homeworkId)); return job ? job.name : `作业 ${homeworkId}`; }, titleOf(item) { return item.title || this.jobName(item.homeworkId); }, restore() { Prefs.load(); this.$('delay').value = String(Prefs.data.delay); this.$('auto').checked = Prefs.data.auto; }, persist() { Prefs.save(); }, bind() { const $ = this.$; $('pill').onclick = () => { $('panel').hidden = false; $('pill').hidden = true; this.render(); if (State.phase === 'idle') { Runner.scan().catch(error => Runner.log(`扫描失败:${error.message}`, 'amber')); } }; $('hide').onclick = () => { $('panel').hidden = true; $('pill').hidden = false; }; $('close').onclick = $('hide').onclick; $('start').onclick = () => { if (Runner.active()) { Runner.pause(); return; } Runner.start().catch(error => Runner.log(error.message, 'amber')); }; $('stop').onclick = () => Runner.stop(); $('again').onclick = () => { Runner.reset(); $('summary').hidden = true; $('work').hidden = false; }; $('retry').onclick = () => { const items = State.results.failed.slice(); if (!items.length) { this.toast('没有未通过的关卡', 'amber'); return; } State.results.failed = []; State.queue = items.map(item => ({ ...item })); $('summary').hidden = true; $('work').hidden = false; State.phase = 'running'; this.render(); Runner.run(++State.token); }; $('gear').onclick = () => { const open = $('settings').hidden; $('settings').hidden = !open; $('work').hidden = open; $('gear').textContent = open ? '返回' : '设置'; }; $('save').onclick = () => { this.prefs.delay = Number($('delay').value) || 1; this.prefs.auto = $('auto').checked; this.persist(); $('gear').click(); this.toast('设置已保存', 'green'); }; }, /** 页面切换只更新界面;自动开始由这里决定。 */ tick() { const path = Route.path(); if (path !== this.lastPath) { this.lastPath = path; this.render(); } if (State.phase !== 'idle' || !this.prefs.auto) return; if (this.seen === path) return; const usable = Route.isTask(path) || !!Route.courseId() || /^\/tasks\//.test(path); if (!usable || !this.$('settings').hidden) return; this.seen = path; Runner.start(true).catch(error => Runner.log(error.message, 'amber')); }, }; /* ============================================================ * 启动 * ========================================================== */ function boot() { View.build(); View.lastPath = Route.path(); View.render(); View.tick(); setInterval(() => View.tick(), 900); } if (document.body) boot(); else document.addEventListener('DOMContentLoaded', boot, { once: true }); })();