// ==UserScript==
// @name 多平台网课助手 · 专业版
// @namespace qkhelper-pro
// @version 4.0.2
// @description 多平台网课自动答题与刷课助手:本地题库 → 在线题库 → 必应搜索 → 自有 AI 四级链路;基础功能免费,部分增强功能需付费会员激活,答题数据只存本机。
// @connect aiyouxi.byethost3.com
// @match *://*.chaoxing.com/*
// @match *://*.zhihuishu.com/*
// @match *://*.icve.com/*
// @match *://*.ouchn.cn/*
// @match *://*.ouchn.edu.cn/*
// @match *://*.ulearning.cn/*
// @match *://*.qingshuxuetang.com/*
// @match *://*.icourse163.org/*
// @match *://*.xuetangx.com/*
// @match *://*.unipus.cn/*
// @match *://*.kaoshixing.com/*
// @match *://*.168wangxiao.com/*
// @match *://*.webtrn.cn/*
// @match *://*.zjooc.cn/*
// @match *://*.wencaischool.net/*
// @match *://*.yxbyun.com/*
// @match *://*.youkexuetang.cn/*
// @match *://*.xjtudlc.com/*
// @match *://*.hnzkw.org/*
// @match *://*.ls365.com/*
// @match *://*.ls365.net/*
// @match *://*.bossyun.com/*
// @match *://*.zk211.com/*
// @match *://*.jijiaool.com/*
// @match *://*.zygbxxpt.com/*
// @match *://*.icve.com.cn/*
// @match *://*.courshare.cn/*
// @match *://*.jsnu.edu.cn/*
// @match *://*.moodle.qwbx.ouchn.cn/*
// @match *://*.bjou.edu.cn/*
// @match *://*.hnqtyq.cn/*
// @match *://*.ougd.cn/*
// @run-at document-end
// @grant GM_getValue
// @grant GM_info
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @antifeature membership
// @connect api.tikuhai.com
// @connect cx.icodef.com
// @connect tk.enncy.cn
// @connect api.muketool.com
// @connect api.deepseek.com
// @connect api.siliconflow.cn
// @connect api.minimaxi.com
// @connect open.bigmodel.cn
// @connect dashscope.aliyuncs.com
// @connect api.moonshot.cn
// @connect api.openai.com
// @connect cn.bing.com
// @connect www.bing.com
// @noframes
// @license All Rights Reserved
// ==/UserScript==
//
// ⚠️ 免责声明
// 本脚本仅供个人学习辅助与浏览器自动化技术研究使用。自动化答题/刷课可能违反所在平台
// 的服务条款,部分平台会监测异常学习行为。请勿用于正式考试、替考或任何需要本人真实
// 完成的教学环节;请自行评估风险,使用产生的一切后果由使用者自行承担。
(function () {
'use strict';
/* ==================== AI 平台预设(官网 / Key / 文档 / 接口 / 现役模型) ====================
2026-11 实测:7 个平台的 OpenAI 兼容 chat/completions 端点做无 Key 探活,
除 api.openai.com(国内网络需代理)外均返回标准 401 认证错误 => 端点与请求格式有效。
MiniMax 只有 api.minimaxi.com 可用,api.minimax.cn / api.minimax.io 的 /v1 路径实测 404。
模型名会换代,所以一律给「推荐 + 备选」,最终以「📋 拉取模型列表」的真实结果为准。
★ GM_xmlhttpRequest 的跨域目标必须在元数据 @connect 里声明,否则请求会被
脚本管理器静默拦掉。上面 7 个预设域名已显式声明;@connect * 用于放行用户
自己填写的 OpenAI 兼容中转域名。脚本管理器安装/更新时会提示扩大跨域权限,
请确认后再授权。自有 API Key 只保存在本机,不会上传。 */
const AI_PROVIDERS = {
deepseek: {
label: 'DeepSeek(官方直连 · 推荐)',
site: 'https://platform.deepseek.com/',
keyUrl: 'https://platform.deepseek.com/api_keys',
docs: 'https://api-docs.deepseek.com/',
url: 'https://api.deepseek.com/v1/chat/completions',
model: 'deepseek-v4-flash',
alt: ['deepseek-flash', 'deepseek-v4-pro'],
note: '官方已于 2026-07-24 停用 deepseek-chat / deepseek-reasoner,现役为 V4 系列;国内可直连。/v1 与不带 /v1 两种路径都兼容。'
},
siliconflow: {
label: '硅基流动 SiliconFlow',
site: 'https://cloud.siliconflow.cn/',
keyUrl: 'https://cloud.siliconflow.cn/account/ak',
docs: 'https://docs.siliconflow.cn/',
url: 'https://api.siliconflow.cn/v1/chat/completions',
model: 'deepseek-ai/DeepSeek-V4-Flash',
alt: ['Pro/deepseek-ai/DeepSeek-V4', 'Qwen/Qwen3-8B'],
note: '注册实名后送额度。模型 ID 必须带组织前缀且区分大小写,请从「模型广场」完整复制,或点下方「拉取模型列表」。'
},
minimax: {
label: 'MiniMax',
site: 'https://platform.minimaxi.com/',
keyUrl: 'https://platform.minimaxi.com/',
docs: 'https://platform.minimaxi.com/document',
url: 'https://api.minimaxi.com/v1/chat/completions',
model: 'MiniMax-M3',
alt: ['MiniMax-M2.1', 'abab6.5s-chat'],
note: '实测 api.minimaxi.com 可用;另两个常见域名 api.minimax.cn / api.minimax.io 的 /v1/chat/completions 返回 404。Key 在控制台「账户管理 → 接口密钥」创建。'
},
zhipu: {
label: '智谱 AI(GLM)',
site: 'https://bigmodel.cn/',
keyUrl: 'https://bigmodel.cn/usercenter/apikeys',
docs: 'https://docs.bigmodel.cn/',
url: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
model: 'glm-4.7-flash',
alt: ['glm-4.7', 'glm-5'],
note: 'GLM-4.7-Flash 便宜且默认非思考模式,答题最省事;GLM-5 系列部分为纯思考模型,可能只返回思维链导致本题空答案。'
},
qwen: {
label: '通义千问(阿里云百炼)',
site: 'https://bailian.console.aliyun.com/',
keyUrl: 'https://bailian.console.aliyun.com/#/api-key',
docs: 'https://help.aliyun.com/zh/model-studio/',
url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
model: 'qwen3.8-flash',
alt: ['qwen3.7-plus', 'qwen-plus'],
note: '必须走 compatible-mode 路径才是 OpenAI 兼容格式;北京地域的 Key 不能用于国际地域,反之亦然。'
},
kimi: {
label: 'Kimi(月之暗面)',
site: 'https://platform.moonshot.cn/',
keyUrl: 'https://platform.moonshot.cn/console/api-keys',
docs: 'https://platform.moonshot.cn/docs/',
url: 'https://api.moonshot.cn/v1/chat/completions',
model: 'kimi-k2.6',
alt: ['moonshot-v1-8k', 'kimi-k2.7'],
note: '国内账号用 api.moonshot.cn,海外账号需改成 api.moonshot.ai(选「自定义」填)。部分新模型强制思考,可能只返回思维链。'
},
openai: {
label: 'OpenAI 官方',
site: 'https://platform.openai.com/',
keyUrl: 'https://platform.openai.com/api-keys',
docs: 'https://platform.openai.com/docs/api-reference/chat',
url: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-5.4-mini',
alt: ['gpt-5-mini', 'gpt-4o-mini'],
note: '本机网络实测无法直连(需自备代理)。GPT-5 系列要求 max_completion_tokens 且不支持 temperature,脚本已自动适配;连不上时请改用国内平台或自建中转。'
},
custom: {
label: '其他 / 自定义(OpenAI 兼容)',
site: '', keyUrl: '', docs: '', url: '', model: '', alt: [],
note: '填任意 OpenAI 兼容中转地址(须以 /chat/completions 结尾)。首次请求会弹出 Tampermonkey 跨域授权,务必点「允许」,否则请求会被静默拦截;也可把域名加进脚本头部 @connect 永久放行。'
}
};
// 由接口地址反查平台,用于老用户没存 aiProvider 时自动回显
function detectProvider(url) {
const u = String(url || '').toLowerCase();
const hosts = {
deepseek: 'api.deepseek.com', siliconflow: 'api.siliconflow.cn',
minimax: 'api.minimaxi.com', zhipu: 'open.bigmodel.cn',
qwen: 'dashscope.aliyuncs.com', kimi: 'api.moonshot.cn', openai: 'api.openai.com'
};
for (const k of Object.keys(hosts)) if (u.indexOf(hosts[k]) >= 0) return k;
return 'custom';
}
function providerOptions(sel) {
return Object.keys(AI_PROVIDERS).map((k) =>
'').join('');
}
// 选中平台后把「官网 / 创建 Key / 接口文档 / 接口地址 / 推荐模型 / 备选 / 注意事项」直接摆给用户
function providerInfoHtml(key) {
const p = AI_PROVIDERS[key] || AI_PROVIDERS.custom;
const link = (url, text) => url
? '' + escapeHtml(text) + ' ↗'
: '自定义平台,请自行填写';
return '
📡 ' + escapeHtml(p.label) + ' · 对接信息
' +
'官网' + link(p.site, '打开官网') + '
' +
'API Key' + link(p.keyUrl, '创建 / 查看 Key') + '
' +
'接口文档' + link(p.docs, '查看文档') + '
' +
'接口地址' + escapeHtml(p.url || '自行填写') + '
' +
'推荐模型' + escapeHtml(p.model || '自行填写') + '
' +
(p.alt && p.alt.length ? '备选模型' + escapeHtml(p.alt.join(' / ')) + '
' : '') +
'' + escapeHtml(p.note || '') + '
';
}
/* ==================== 配置 ==================== */
const DEFAULT_CONFIG = {
speed: 2, // 视频倍速(默认 2x 最快;1 = 原速最安全,2x 检测风险最高,自行权衡)
autoVideo: true, // 自动处理视频任务
autoAudio: true, // 自动处理音频任务
autoWork: true, // 自动做章节测验
autoSubmit: true, // 正确率达标自动提交测验
autoJump: true, // 本章完成后自动切下一章
muted: true, // 视频静音播放(默认开);取消勾选 = 有声播放
answerIntervalMin: 2, // 每题最小间隔(秒)——拟人「读题思考」时间,0 秒答题是官方风控重点特征,不建议改回 0
answerIntervalMax: 5, // 每题最大间隔(秒)
submitDelayMin: 4, // 提交前最小延迟(秒)——拟人「检查试卷」时间
submitDelayMax: 9, // 提交前最大延迟(秒)
minAccuracy: 0.6, // 最低作答覆盖率(写进提交域的题数/总题数),低于则暂存不提交
quizDelayMin: 0, // 弹题作答前等待(秒,0=最快)
quizDelayMax: 0,
dailyLimitMinutes: 0, // 每日刷课时长上限(分钟),0 = 不限
deliberateErrorRate: 0, // 故意答错率 0~0.2(0=不故意错)
aiEnabled: false, // 启用 AI 答题(需填 key;面板填了 Key 会自动勾上)
aiKey: '', // 个人 API Key:点面板 ⚙ 填写(各平台官网创建,只存本机)
aiProvider: 'deepseek', // 当前选中的 AI 平台(面板回显/官网展示用)
aiUrl: 'https://api.deepseek.com/v1/chat/completions',
aiModel: 'deepseek-v4-flash',
// 零配置(不填 AI Key)即可完整搜题:本地题库 → 在线免费题库 → 必应搜索。
// AI 只是增强项,不是使用前提。答题数据只存本机,不上传题目与答案;
// 唯一的服务器请求是用户自建卡密系统的激活 / 状态查询。
useTiku: true, // 在线免费题库(面板可关;关掉则跳过这一级)
useWebSearch: true, // 必应实时搜索兜底(免费;本地/在线题库/AI 都无结果时使用)
authUrl: 'https://aiyouxi.byethost3.com/qkauth/api.php', // 用户自建卡密 API(可改)
cardKey: '', // 用户自建卡密,只存本机
overwrite: false, // 覆盖重答:开启后已作答过的弹题/测验也会清掉旧答案重新作答
failTolerance: 3, // AI 失败容忍次数:连续失败 N 次才进入 10 分钟冷却(自定义失败容忍策略)
quizRandomFallback: true, // 弹题随机兜底:未搜到答案时随机点一个选项,避免卡住视频
autoLearnResult: true, // 结果页自动纠错:判错的答案从题库剔除,判对/公布的正确答案写入并锁定
// v4.0.0 填空题专项(四项都是真实生效的开关,关掉即跳过对应能力)
aiBlankStructured: true, // 填空让 AI 按 JSON 结构化输出并自动解析多种分隔格式
aiFirstForText: true, // 填空/简答:AI 答案优先于在线题库(空数不匹配的题库答案不抢先采用)
blankPayloadStrict: true, // 填空写完必须回读提交真值域,写不进去就按「写入失败」拦提交
blankSearchFallback: true, // 必应搜索兜底对填空/简答也生效(从摘要抽取答案片段)
// v4.0.0 多平台通用模式(不接任何第三方收费接口)
genericMode: true, // 非学习通平台自动启用通用刷课/答题探测
genericSubmit: false, // 通用模式默认只填不交,考试场景请手动提交;确认安全后可开
};
/* 反检测增强:抹掉浏览器自动化痕迹(navigator.webdriver 是最常见的挂机检测点),
配合脚本里已有的随机延迟/拟人化答题间隔一起降低被风控的概率 */
try {
Object.defineProperty(navigator, 'webdriver', { get: () => false, configurable: true });
} catch (e) { /* ignore */ }
// 配置数值统一走这里,避免 `parseFloat(v) || 默认值` 把用户填的 0 悄悄改成默认值
function cfgNum(raw, fallback, min, max) {
const n = parseFloat(raw);
const v = Number.isFinite(n) ? n : fallback;
return Math.min(max, Math.max(min, v));
}
// 提交判定(纯函数,便于回归测试)。
// okCount = 真正写进提交域的题数;noAnswer = 题库/AI/搜索都没结果而主动留空的题数;
// failed = 有答案却没写进提交域的题数(真故障,一律拦住防白卷)。
// v4.0.0 起门槛从「答案来源可信度均值」改为「作答覆盖率 = okCount/total」:
// 用户用自有 AI(可信度 0.7)把 10 题全答对了,旧算法算 70% < 90% 永不提交;
// 作答覆盖率衡量的正是用户设阈值时想控的东西 —— 有多少题真的写上了答案。
// 答案对不对脚本交卷前读不到,「正确率」本就是测算值;failed>0 仍一律拦住防白卷。
// confidence 参数保留仅为兼容旧调用签名,不再参与判定。
function shouldSubmit(okCount, total, confidence, noAnswer, failed) {
const handled = okCount + Number(noAnswer || 0);
const coverage = total > 0 ? okCount / total : 0;
return !!(CONFIG.autoSubmit && total > 0 && okCount > 0
&& handled === total && Number(failed || 0) === 0
&& coverage >= CONFIG.minAccuracy);
}
function loadConfig() {
try {
const saved = (typeof GM_getValue !== 'undefined')
? GM_getValue('cxConfig', null)
: JSON.parse(localStorage.getItem('cxConfig') || 'null');
if (saved && typeof saved === 'object') {
const cfg = Object.assign({}, DEFAULT_CONFIG, saved);
// 迁移:老版本拟人延迟默认为 0(答题太快易被风控),自动升级为拟人间隔
if (Number(cfg.answerIntervalMin) === 0 && Number(cfg.answerIntervalMax) === 0) {
cfg.answerIntervalMin = DEFAULT_CONFIG.answerIntervalMin;
cfg.answerIntervalMax = DEFAULT_CONFIG.answerIntervalMax;
cfg.submitDelayMin = DEFAULT_CONFIG.submitDelayMin;
cfg.submitDelayMax = DEFAULT_CONFIG.submitDelayMax;
saveConfig(cfg);
}
return cfg;
}
} catch (e) { /* ignore */ }
return Object.assign({}, DEFAULT_CONFIG);
}
function saveConfig(cfg) {
try {
if (typeof GM_setValue !== 'undefined') GM_setValue('cxConfig', cfg);
else localStorage.setItem('cxConfig', JSON.stringify(cfg));
} catch (e) { /* ignore */ }
}
let CONFIG = loadConfig();
// 一次性迁移(v1.0.6):旧存储的 240 分钟上限 / 1x 倍速 强制升级为新默认(0 不限 + 2x)
try {
const MIG = 'cxMigV105';
const done = (typeof GM_getValue !== 'undefined') ? GM_getValue(MIG, false) : localStorage.getItem(MIG);
if (!done) {
CONFIG.dailyLimitMinutes = 0;
CONFIG.speed = 2;
saveConfig(CONFIG);
if (typeof GM_setValue !== 'undefined') GM_setValue(MIG, true);
else localStorage.setItem(MIG, '1');
}
} catch (e) { /* ignore */ }
if (CONFIG.speed > 2) { CONFIG.speed = 2; } // 倍速上限 2x
// 一次性迁移(v1.0.11-local):deepseek-reasoner 已于 2026-07 停用,自动换现役模型;清除废弃的 reportUrl
try {
const MIG2 = 'cxMigV110';
const done2 = (typeof GM_getValue !== 'undefined') ? GM_getValue(MIG2, false) : localStorage.getItem(MIG2);
if (!done2) {
if (CONFIG.aiModel === 'deepseek-reasoner' || CONFIG.aiModel === 'deepseek-chat') {
CONFIG.aiModel = 'deepseek-v4-flash';
}
delete CONFIG.reportUrl;
saveConfig(CONFIG);
if (typeof GM_setValue !== 'undefined') GM_setValue(MIG2, true);
else localStorage.setItem(MIG2, '1');
}
} catch (e) { /* ignore */ }
// 一次性迁移(v4.0.0):老配置没有 aiProvider,按接口地址反查补全,面板才能正确回显官网信息
try {
const MIG3 = 'cxMigV258';
const done3 = (typeof GM_getValue !== 'undefined') ? GM_getValue(MIG3, false) : localStorage.getItem(MIG3);
if (!done3) {
if (!CONFIG.aiProvider) CONFIG.aiProvider = detectProvider(CONFIG.aiUrl);
if (CONFIG.aiModel === 'deepseek-reasoner' || CONFIG.aiModel === 'deepseek-chat') {
CONFIG.aiModel = 'deepseek-v4-flash';
}
saveConfig(CONFIG);
if (typeof GM_setValue !== 'undefined') GM_setValue(MIG3, true);
else localStorage.setItem(MIG3, '1');
}
} catch (e) { /* ignore */ }
// 一次性迁移(v4.0.0):老版本 useTiku 默认 false,而且配置面板里根本没有这个开关,
// 所以老用户存储里的 false 全是「脚本默认值」而非主动关闭。升级后自动打开在线题库,
// 不填 AI Key 也能走完 本地题库 → 在线题库 → 必应搜索 三级链路。
// 迁移只跑一次,之后用户在面板里主动关掉就会被尊重。
try {
const MIG4 = 'cxMigV261';
const done4 = (typeof GM_getValue !== 'undefined') ? GM_getValue(MIG4, false) : localStorage.getItem(MIG4);
if (!done4) {
if (CONFIG.useTiku === false) CONFIG.useTiku = true;
saveConfig(CONFIG);
if (typeof GM_setValue !== 'undefined') GM_setValue(MIG4, true);
else localStorage.setItem(MIG4, '1');
}
} catch (e) { /* ignore */ }
// 一次性迁移(v4.0.0):填空题四项开关是新增能力,老配置里没有这些键时补成默认开启。
// 只在「键确实不存在」时写入,用户之后主动关掉的值一律尊重。
try {
const MIG5 = 'cxMigV263';
const done5 = (typeof GM_getValue !== 'undefined') ? GM_getValue(MIG5, false) : localStorage.getItem(MIG5);
if (!done5) {
for (const k of ['aiBlankStructured', 'aiFirstForText', 'blankPayloadStrict', 'blankSearchFallback']) {
if (typeof CONFIG[k] !== 'boolean') CONFIG[k] = DEFAULT_CONFIG[k];
}
saveConfig(CONFIG);
if (typeof GM_setValue !== 'undefined') GM_setValue(MIG5, true);
else localStorage.setItem(MIG5, '1');
}
} catch (e) { /* ignore */ }
/* 题目收集器:做过的题(题干+选项+答案)自动积累,导出后交给 AI 整理成考前手册 */
let COLLECTED = [];
try {
COLLECTED = (typeof GM_getValue !== 'undefined')
? GM_getValue('cxQuestions', [])
: JSON.parse(localStorage.getItem('cxQuestions') || '[]');
if (!Array.isArray(COLLECTED)) COLLECTED = [];
// 清洗:历史上思维链泄漏会把整段推理文字当答案存入库(填空题答案不会超过 60 字),
// 启动时把这类污染记录剔除,防止每次都「查到」垃圾答案
const n0 = COLLECTED.length;
COLLECTED = COLLECTED.filter((it) => !(String(it.t) === '2' && String(it.a || '').length > 60));
if (COLLECTED.length !== n0 && typeof GM_setValue !== 'undefined') GM_setValue('cxQuestions', COLLECTED);
else if (COLLECTED.length !== n0) localStorage.setItem('cxQuestions', JSON.stringify(COLLECTED));
} catch (e) { COLLECTED = []; }
function recordQuestion(q, answer, confidence) {
try {
// 排除法推出的候选只是「还没被判错的选项」,未经平台判对,绝不入库
if (LAST_ANSWER_META && LAST_ANSWER_META.noBank) return;
// AI / 必应来源同样收录。只要「确实写进提交域且答案经过净化」就入本地题库,
// 低可信来源原样带上 conf / src,由结果页判分纠错负责把错的改对或下架。
// 仍然拒绝:noBank 推断、随机兜底(调用方不传)、conf<=0 的未知来源。
const conf = Number(confidence == null ? 1 : confidence);
if (!Number.isFinite(conf) || conf <= 0) return;
const cleanAns = sanitizeAnswers(answer || [], q.type);
if (!cleanAns.length) return;
const key = normQ(q.question);
if (!key) return;
const origin = (LAST_ANSWER_META && LAST_ANSWER_META.source) || 'unknown';
const rec = { q: q.question, t: String(q.type), o: (q.options || []).join('§'), a: cleanAns.join('|'), c: conf, src: 'auto', by: origin };
const at = COLLECTED.findIndex((it) => normQ(it.q) === key);
if (at >= 0) {
// 手动导入 / 结果页判分确认过的答案不许自动收录改写
if (COLLECTED[at].src === 'import' || COLLECTED[at].src === 'verified') return;
const old = Number(COLLECTED[at].c == null ? 1 : COLLECTED[at].c);
if (Number.isFinite(old) && old > conf) return; // 不拿低可信答案覆盖高可信答案
COLLECTED[at] = rec;
} else {
COLLECTED.push(rec);
if (COLLECTED.length > 20000) COLLECTED = COLLECTED.slice(-20000);
}
if (typeof GM_setValue !== 'undefined') GM_setValue('cxQuestions', COLLECTED);
else localStorage.setItem('cxQuestions', JSON.stringify(COLLECTED));
} catch (e) { /* ignore */ }
}
/* ===== 错答案排除表:结果页判错 → 记住「这个答案不对」→ 下次避开 =====
只登记平台客观判错的答案;拟人模式故意答错的题会被打标记跳过,不污染排除表。
单选/判断可在排除后推出唯一剩余候选,但那只是答题候选,未经平台判对绝不写进题库。 */
const EXCLUDE_KEY = 'cxExclusions';
const DELIB_KEY = 'cxDeliberateWrong';
const STORE_TTL = 30 * 24 * 3600 * 1000;
let EXCLUSIONS = {};
let DELIBERATE = {};
function readStore(key) {
try {
const raw = (typeof GM_getValue !== 'undefined') ? GM_getValue(key, '{}') : (localStorage.getItem(key) || '{}');
const o = (typeof raw === 'string') ? JSON.parse(raw) : raw;
return (o && typeof o === 'object' && !Array.isArray(o)) ? o : {};
} catch (e) { return {}; }
}
function writeStore(key, obj) {
try {
if (typeof GM_setValue !== 'undefined') GM_setValue(key, obj);
else localStorage.setItem(key, JSON.stringify(obj));
} catch (e) { /* ignore */ }
}
(function pruneStores() {
const now = Date.now();
EXCLUSIONS = readStore(EXCLUDE_KEY);
DELIBERATE = readStore(DELIB_KEY);
let dirty = false;
for (const k of Object.keys(EXCLUSIONS)) {
if (!EXCLUSIONS[k] || !Array.isArray(EXCLUSIONS[k].bad) || now - (EXCLUSIONS[k].ts || 0) > STORE_TTL) {
delete EXCLUSIONS[k]; dirty = true;
}
}
for (const k of Object.keys(DELIBERATE)) {
if (now - (DELIBERATE[k] || 0) > 24 * 3600 * 1000) { delete DELIBERATE[k]; dirty = true; }
}
if (dirty) { writeStore(EXCLUDE_KEY, EXCLUSIONS); writeStore(DELIB_KEY, DELIBERATE); }
})();
function markDeliberateWrong(q) {
const k = normQ(q && q.question);
if (!k) return;
DELIBERATE[k] = Date.now();
writeStore(DELIB_KEY, DELIBERATE);
}
function isDeliberate(stem) {
const k = normQ(stem);
return !!(DELIBERATE[k] && Date.now() - DELIBERATE[k] < 24 * 3600 * 1000);
}
// bad 由调用处按题型拼好:单选/判断=单个值;多选=字母组合;填空/简答=整份答案文本
function addExclusion(stem, type, bad, optCount) {
const k = normQ(stem);
if (!k || !bad || !bad.length) return;
const rec = EXCLUSIONS[k] || { t: String(type), bad: [], opts: 0 };
rec.t = String(type);
if (optCount) rec.opts = Number(optCount) || 0;
const set = new Set(rec.bad.map((x) => String(x).toUpperCase()));
bad.forEach((x) => set.add(String(x).toUpperCase()));
rec.bad = Array.from(set).slice(0, 12);
rec.ts = Date.now();
EXCLUSIONS[k] = rec;
writeStore(EXCLUDE_KEY, EXCLUSIONS);
}
function clearExclusion(stem) {
const k = normQ(stem);
if (k && EXCLUSIONS[k]) { delete EXCLUSIONS[k]; writeStore(EXCLUDE_KEY, EXCLUSIONS); }
}
function exclusionFor(q) {
const k = normQ(q && q.question);
const rec = k ? EXCLUSIONS[k] : null;
return (rec && Array.isArray(rec.bad) && rec.bad.length) ? rec : null;
}
function filterExcluded(q, ans) {
const rec = exclusionFor(q);
if (!rec || !ans || !ans.length) return ans || [];
const t = String(q.type);
const bad = new Set(rec.bad.map((x) => String(x).toUpperCase()));
if (t === '0' || t === '3') return ans.filter((a) => !bad.has(String(a).toUpperCase()));
const combo = (t === '1' ? ans.slice().sort().join('') : ans.join('|')).toUpperCase();
return bad.has(combo) ? [] : ans;
}
// 只有「排除到只剩唯一候选」才敢推断;多选/填空绝不瞎猜,继续交给 AI/搜索
function deduceAnswer(q) {
const rec = exclusionFor(q);
if (!rec) return [];
const t = String(q.type);
const bad = new Set(rec.bad.map((x) => String(x).toUpperCase()));
if (t === '3') {
if (bad.has('正确') && !bad.has('错误')) return ['错误'];
if (bad.has('错误') && !bad.has('正确')) return ['正确'];
return [];
}
if (t === '0') {
const n = (q.options && q.options.length) || rec.opts || 0;
if (!n || n > 8) return [];
const all = Array.from({ length: n }, (_, i) => String.fromCharCode(65 + i));
const left = all.filter((x) => !bad.has(x));
return left.length === 1 ? [left[0]] : [];
}
return [];
}
/* ===== 结果页自动纠错(让题库只留正确答案) =====
交卷后平台结果页会给出「我的答案 / 正确答案 / 对错 / 得分」。这是脚本唯一能
客观判定答案对错的来源。以前脚本从不读它,所以一条错答案进了本地题库就会被
永远优先命中(本地题库优先级最高),再也没机会被纠正 —— 越刷越错。
规则(全部带保护,绝不误删):
① 平台公布正确答案 → 写成 verified,直接覆盖旧错答案(含手动导入的错答案)
② 判对且「我的答案」有效 → 把我的答案写成 verified 锁定
③ 判错且「我的答案」非空且 == 题库里存的那条 → 删掉这条错答案,下次重新查 AI/在线题库
④ 白卷(我的答案空) → 不删!那可能是提交域没写进去,不是答案本身错
不少课程结果页不公布正确答案,只给对错+得分,所以 ③ 是主要纠错路径。 */
// 门控必须严格:只有明确出现「对错/正确答案/得分」标记才允许动题库(误删不可逆)
const RESULT_GATE_SEL = '.marking_dui, .marking_cuo, .correctAnswer, .correctAnswerBx, .rightAnswerContent, .right_answer, .newAnswerScore';
const RESULT_Q_SEL = '.TiMu, .questionLi, .mark_item';
const RESULT_CORRECT_SEL = '.correctAnswer .answerCon, .correctAnswerBx .correctAnswer, .rightAnswerContent, .mark_key .answerCon, .mark_key, .right_answer, .correctAnswer';
const RESULT_MY_SEL = '.myAnswer .answerCon, .myAnswer, .mark_answer, .answerCon';
function persistBank() {
try {
if (typeof GM_setValue !== 'undefined') GM_setValue('cxQuestions', COLLECTED);
else localStorage.setItem('cxQuestions', JSON.stringify(COLLECTED));
} catch (e) { /* ignore */ }
}
function resultStem(root) {
const el = root.querySelector('.Zy_TItle, .mark_name, .questionTitle, .q-title, .stem, .title');
const s = decodeText(el ? String(el.textContent || '') : String(root.textContent || '').slice(0, 140));
return s.replace(/^\s*\d+\s*[.、).]?\s*/, '')
.replace(/【(单选题|多选题|判断题|填空题|简答题|论述题)】/g, '')
.replace(/^\s*(单选题|多选题|判断题|填空题)\s*[::]\s*/, '')
.replace(/\s+/g, ' ').trim();
}
function resultType(root, stem) {
try {
const ti = root.querySelector('input[name^=answertype], input[id^=answertype]');
if (ti && String(ti.value || '')) return String(ti.value);
} catch (e) { /* ignore */ }
// 用题目原文判断题型:resultStem 会剥掉【判断题】标记,不能拿它判
const raw = String(root.textContent || '').slice(0, 60);
if (/多选/.test(raw)) return '1';
if (/判断/.test(raw)) return '3';
if (/填空/.test(raw)) return '2';
return '0';
}
function resultAnsText(root, sel) {
const el = root.querySelector(sel);
if (!el) return '';
return decodeText(String(el.textContent || '').replace(/\s+/g, ' ').trim());
}
// 结果页答案文本 → 合法答案数组。严格按题型校验,宁可不学也不写脏数据。
function normalizeResultAnswer(raw, type) {
let s = String(raw || '').replace(/\s+/g, ' ').trim();
s = s.replace(/^(正确答案|我的答案|参考答案|答案)\s*[::]\s*/i, '').trim();
s = s.replace(/\s*\(.*$/, '').trim(); // 去掉 "(推断正确)" 之类的附注
// 结果页可能沿用加密字体:私用区码点说明这段字还没解码,绝不入库,否则会存一串乱码
if (!s || hasPrivateUse(s)) return [];
if (s.length > 500) return [];
const t = String(type);
if (t === '3') {
if (/^(正确|对|√|true|T|是)$/i.test(s)) return ['正确'];
if (/^(错误|错|×|false|F|否)$/i.test(s)) return ['错误'];
return [];
}
if (t === '0' || t === '1') {
// 只认「纯字母 + 分隔符」,防止从选项正文/解析里抓到零散字母
if (!/^[A-Ha-h\s,,、;;|/]+$/.test(s)) return [];
const letters = (s.match(/[A-Ha-h]/g) || []).map((x) => x.toUpperCase());
if (!letters.length) return [];
return t === '0' ? [letters[0]] : [...new Set(letters)];
}
// v4.0.0 结果页公布的填空题正确答案常用「、」「;」「1. 2.」分隔,
// 旧版按整串存成一个空,下次答题就永远对不上空数。
if (t === '2') return sanitizeAnswers(splitTextAnswers(s, '2', 1), t);
return sanitizeAnswers([s], t);
}
function bankIndexOf(stem) {
const key = normQ(stem);
if (!key || key.length < 4) return -1;
const exact = COLLECTED.findIndex((it) => normQ(it.q) === key);
if (exact >= 0) return exact;
return COLLECTED.findIndex((it) => {
const n = normQ(it.q);
return n.length >= 8 && (n.includes(key) || key.includes(n));
});
}
function bankAnsSet(a) { return String(a || '').split(/[|,,、;;\s]+/).filter(Boolean).map((x) => x.toUpperCase()).sort().join(''); }
function upsertVerified(stem, type, ans) {
clearExclusion(stem); // 平台已确认正确答案,该题的错答案排除记录作废
const at = bankIndexOf(stem);
const rec = { q: stem, t: String(type), o: at >= 0 ? (COLLECTED[at].o || '') : '',
a: ans.join('|'), c: 1.5, src: 'verified' };
if (at >= 0) {
const old = COLLECTED[at];
// 已是同一份已验证答案 → 幂等,不再重复写/重复打日志
if (old.src === 'verified' && bankAnsSet(old.a) === bankAnsSet(ans.join('|'))) return false;
COLLECTED[at] = rec;
} else {
COLLECTED.push(rec);
if (COLLECTED.length > 20000) COLLECTED = COLLECTED.slice(-20000);
}
return true;
}
// 结果页选项文本优先复用本地题库里那份,拿不到再从 DOM 粗提(仅供后端分类/校验)
function resultOptionsText(root, stem) {
const at = bankIndexOf(stem);
if (at >= 0 && COLLECTED[at].o) return COLLECTED[at].o;
try {
const nodes = Array.from(root.querySelectorAll('li, .option'));
const txt = nodes.map((n) => String(n.textContent || '').replace(/\s+/g, ' ').trim())
.filter((x) => x && x.length < 200);
return txt.slice(0, 8).join('§');
} catch (e) { return ''; }
}
// 判错的答案怎么记:单值题记单个字母/判断值;多选题记整个组合;填空记整份文本
function badAnswersOf(t, mine) {
if (t === '0' || t === '3') return mine.slice(0, 1);
if (t === '1') return [mine.slice().sort().join('').toUpperCase()];
return [mine.join('|')];
}
function learnFromResult(doc) {
const out = { learned: 0, removed: 0, skipped: 0, events: [] };
try {
if (!doc || !doc.querySelector) return out;
// 没有判分/答案标记 = 不是结果页,绝不动题库
if (!doc.querySelector(RESULT_GATE_SEL)) return out;
const roots = Array.from(doc.querySelectorAll(RESULT_Q_SEL));
for (const r of roots) {
const stem = resultStem(r);
if (stem.length < 4) { out.skipped++; continue; }
const t = String(resultType(r, stem));
const o = resultOptionsText(r, stem);
const optCount = o ? o.split('§').filter(Boolean).length : 0;
const published = normalizeResultAnswer(resultAnsText(r, RESULT_CORRECT_SEL), t);
const mine = normalizeResultAnswer(resultAnsText(r, RESULT_MY_SEL), t);
const dui = !!r.querySelector('.marking_dui');
const cuo = !!r.querySelector('.marking_cuo');
const scoreEl = r.querySelector('.newAnswerScore .scoreNum, .mark_score .scoreNum, .scoreNum');
const scored = scoreEl ? parseFloat(String(scoreEl.textContent || '').replace(/[^\d.]/g, '')) : NaN;
// ① 平台公布了正确答案 → 覆盖(优先级最高,手动导入的旧答案也纠正)
if (published.length) {
if (upsertVerified(stem, t, published)) out.learned++;
out.events.push({ q: stem, t, o, a: published.join('|'), verdict: 'published' });
continue;
}
// ② 判对(对勾或得分>0)且我的答案有效 → 锁进题库
if ((dui || (Number.isFinite(scored) && scored > 0)) && mine.length) {
if (upsertVerified(stem, t, mine)) out.learned++;
out.events.push({ q: stem, t, o, a: mine.join('|'), verdict: 'correct' });
continue;
}
// ③ 判错:记下这个错答案(下次避开/单选可推剩余选项),本地同值答案剔除
if (cuo && mine.length) {
if (isDeliberate(stem)) { out.skipped++; continue; } // 拟人故意答错不算真实判错
addExclusion(stem, t, badAnswersOf(t, mine), optCount);
const at = bankIndexOf(stem);
if (at >= 0 && COLLECTED[at].src !== 'verified'
&& bankAnsSet(COLLECTED[at].a) === bankAnsSet(mine.join('|'))) {
COLLECTED.splice(at, 1);
out.removed++;
} else out.skipped++;
out.events.push({ q: stem, t, o, a: mine.join('|'), verdict: 'wrong' });
continue;
}
out.skipped++; // 白卷 / 只有得分无结论:不动题库
}
if (out.learned || out.removed) persistBank();
} catch (e) { /* ignore */ }
return out;
}
function exportQuestions() {
if (!COLLECTED.length) { log('📋 还没有收集到题目(做完学习检测/弹题后自动收集)', 'warn'); return; }
const data = JSON.stringify(COLLECTED);
const done = () => log(`📋 已导出 ${COLLECTED.length} 道题,全选复制发给 AI 助手`, 'ok');
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(data).then(done).catch(() => { showExportBox(data); });
} else showExportBox(data);
} catch (e) { showExportBox(data); }
}
function showExportBox(data) {
const ta = document.createElement('textarea');
ta.id = 'cxExportBox';
ta.value = data;
document.body.appendChild(ta);
ta.focus(); ta.select();
ta.addEventListener('blur', () => { try { ta.remove(); } catch (e) {} });
log('📋 题目数据已生成在左下角文本框,全选(Ctrl+A)复制后发给 AI 助手', 'ok');
}
/* ==================== 工具函数 ==================== */
// 暂停感知等待:挂机暂停期间所有等待挂起(任务冻结在当前步骤,不会继续跑),
// 点「开始」恢复后从原处继续——切章/答题/翻页全部感知暂停状态
const sleep = async (s) => {
let left = Math.max(0, s * 1000);
while (left > 0) {
if (PAUSED) { await new Promise((r) => setTimeout(r, 300)); continue; }
const step = Math.min(250, left);
await new Promise((r) => setTimeout(r, step));
left -= step;
}
};
const randomSleep = (min, max) => sleep(Math.floor(Math.random() * (max - min + 1)) + min);
const waitResume = async () => { while (PAUSED) await new Promise((r) => setTimeout(r, 300)); };
function waitElementLoaded(win, selector, timeoutMs = 60000) {
return new Promise((resolve, reject) => {
const start = Date.now();
const timer = setInterval(() => {
try {
if (win.document.querySelector(selector)) { clearInterval(timer); resolve(); return; }
} catch (e) { /* iframe 未就绪 */ }
if (Date.now() - start > timeoutMs) { clearInterval(timer); reject(new Error('等待元素超时: ' + selector)); }
}, 200);
});
}
function waitIframeLoaded(iframe, timeoutMs = 60000) {
return new Promise((resolve, reject) => {
const start = Date.now();
const timer = setInterval(() => {
try {
if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') { clearInterval(timer); resolve(); return; }
} catch (e) { /* ignore */ }
if (Date.now() - start > timeoutMs) { clearInterval(timer); reject(new Error('iframe 加载超时')); }
}, 200);
});
}
// HTML 转纯文本(保留 img/sub/sup/br)
function clean(html) {
if (html == null) return '';
return String(html)
.replace(/<((?!img|sub|sup|br)[^>]+)>/g, '')
.replace(/ /g, ' ')
.replace(/\s+/g, ' ')
.replace(/
/gi, '\n')
.trim();
}
// 去题型前缀【单选题】和分值后缀(2.0分)
const cl = (str) => String(str).replace(/^【.*?】\s*/, '').replace(/\s*(\d+(\.\d+)?分)$/, '');
// 跨域请求:油猴环境用 GM_xmlhttpRequest,普通环境降级 fetch
function cxFetch(url, { method = 'GET', data = null, headers = {}, timeout = 10000 } = {}) {
return new Promise((resolve, reject) => {
if (typeof GM_xmlhttpRequest !== 'undefined') {
GM_xmlhttpRequest({
method, url, data, headers, timeout,
onload: (res) => resolve(res.responseText),
onerror: (err) => reject(err),
ontimeout: () => reject(new Error('timeout'))
});
} else {
fetch(url, { method, headers, body: data }).then((r) => r.text()).then(resolve).catch(reject);
}
});
}
// 平台识别:用于多平台路由分发与题库分类。
function platformName() {
try {
const h = location.hostname;
if (h.includes('chaoxing') || h.includes('xueyitong') || h.includes('xuexitong')) return 'chaoxing';
if (h.includes('zhihuishu') || h.includes('studyvideoh5') || h.includes('shengda')) return 'zhihuishu';
if (h.includes('icourse163')) return 'icourse163';
if (h.includes('xuetangx')) return 'xuetangx';
if (h.includes('unipus')) return 'unipus';
// v4.0.0 通用平台:只做识别与题库分类,具体作答/刷课由通用适配层按 DOM 探测完成
const GENERIC_HOST_MAP = [
['icve', ['icve.com', 'zjicve']],
['ouchn', ['ouchn.cn', 'ouchn.edu.cn']],
['ulearning', ['ulearning.cn']],
['qingshu', ['qingshuxuetang.com']],
['kaoshixing', ['kaoshixing.com']],
['wangxiao168', ['168wangxiao.com']],
['webtrn', ['webtrn.cn']],
['zjooc', ['zjooc.cn']],
['wencai', ['wencaischool.net']],
['yxbyun', ['yxbyun.com']],
['youke', ['youkexuetang.cn']],
['xjtudlc', ['xjtudlc.com']],
['hnzkw', ['hnzkw.org']],
['ls365', ['ls365.com', 'ls365.net']],
['bossyun', ['bossyun.com']],
['zk211', ['zk211.com']],
['jijiaool', ['jijiaool.com']],
['zygbxxpt', ['zygbxxpt.com']],
['courshare', ['courshare.cn']],
['jsnu', ['jsnu.edu.cn']],
['bjou', ['bjou.edu.cn']],
['hnqtyq', ['hnqtyq.cn']],
['ougd', ['ougd.cn']]
];
for (const [name, keys] of GENERIC_HOST_MAP) {
if (keys.some((k) => h.includes(k))) return name;
}
return 'other';
} catch (e) { return 'other'; }
}
/* ==================== 会员激活 / 授权校验 ====================
只做授权验证:激活 / 查询状态。不上传题目、答案或 API Key。
卡密系统独立部署在 /qkauth/,表前缀 qka_,与其他程序完全隔离。 */
function gmGet(k, d) {
try { return (typeof GM_getValue !== 'undefined') ? GM_getValue(k, d) : (localStorage.getItem(k) || d); }
catch (e) { return d; }
}
function gmSet(k, v) {
try { if (typeof GM_setValue !== 'undefined') GM_setValue(k, v); else localStorage.setItem(k, v); } catch (e) { /* ignore */ }
}
function authMachineId() {
let id = gmGet('cxMachineId', '');
if (!id) {
id = 'M' + Math.random().toString(36).slice(2, 10).toUpperCase() + Date.now().toString(36).slice(-4).toUpperCase();
gmSet('cxMachineId', id);
}
return id;
}
let AUTH = { ok: false, active: false, type: '', expireAt: '', left: 0, limit: 0, used: 0 };
function authRequest(action, cardKey) {
const url = String(CONFIG.authUrl || '').replace(/\/+$/, '');
if (!url) return Promise.resolve({ ok: false, message: '未配置服务器地址' });
const payload = JSON.stringify({
action: action,
cardKey: cardKey || CONFIG.cardKey || '',
clientId: authMachineId(),
platform: (typeof platformName === 'function') ? platformName() : 'other'
});
return cxFetch(url, {
method: 'POST', data: payload, timeout: 12000,
headers: { 'Content-Type': 'application/json' }
}).then((txt) => JSON.parse(txt));
}
function authMsg(text, bad) {
const el = document.getElementById('authMsg');
if (el) { el.textContent = text; el.className = 'cx-auth-msg' + (bad ? ' bad' : ''); }
if (text) log(text, bad ? 'warn' : 'ok');
}
function authRender(r) {
AUTH = r || {};
const badge = document.getElementById('cxVipBadge');
const state = document.getElementById('authState');
const detail = document.getElementById('authDetail');
const bar = document.getElementById('authBar');
const active = !!(r && r.ok && r.active);
if (badge) {
badge.textContent = active ? 'VIP ✓' : '免费版';
badge.className = 'cx-vip' + (active ? ' on' : '');
}
if (state) {
state.textContent = active ? (r.type === 'forever' ? '永久会员 · 已激活' :
(r.type === 'count' ? '次数卡 · 使用中' : '天数卡 · 使用中')) : '未激活';
state.className = 'auth-state' + (active ? ' on' : '');
}
if (detail) {
if (!active) detail.textContent = (r && r.message) ? r.message : '输入卡密即可激活会员标识;免费功能无需卡密';
else if (r.type === 'count') detail.textContent = '剩余 ' + r.left + ' / 共 ' + r.limit + ' 次';
else if (r.type === 'day') detail.textContent = '有效期至 ' + String(r.expireAt || '').slice(0, 16);
else detail.textContent = '永久有效 · 已绑定本机';
}
if (bar) {
let pct = 0;
if (active && r.type === 'count' && r.limit > 0) pct = Math.max(0, Math.min(100, Math.round(r.left / r.limit * 100)));
else if (active && r.type === 'day') pct = 100;
else if (active) pct = 100;
bar.style.width = pct + '%';
}
const mi = document.getElementById('authMachine');
if (mi && !mi.value) mi.value = authMachineId();
}
async function activateCard(key) {
try {
const r = await authRequest('activate', key);
authRender(r);
authMsg(r && r.ok ? '✅ ' + r.message : '❌ ' + ((r && r.message) || '激活失败'), !(r && r.ok));
return r;
} catch (e) {
authMsg('❌ 无法连接卡密服务器:' + (e.message || e) + '(检查地址与跨域授权)', true);
return { ok: false, message: String(e && e.message || e) };
}
}
async function queryCardStatus(silent) {
if (!CONFIG.cardKey) { if (!silent) authMsg('请先输入卡密', true); return; }
if (!silent) authMsg('正在查询卡密状态...');
try {
const r = await authRequest('query');
authRender(r);
if (!silent) authMsg((r && r.ok) ? ((r.active ? '✅ ' : '⚠ ') + r.message) : '❌ ' + ((r && r.message) || '查询失败'), !(r && r.ok && r.active));
} catch (e) {
if (!silent) authMsg('❌ 查询失败:' + (e.message || e), true);
}
}
/* ==================== 日志面板 ==================== */
let logPanel = null;
let logLines = [];
function setStatus(text) {
const el = document.getElementById('cxStatus');
if (el) el.textContent = text;
// 状态文字右侧按钮:工作中(未暂停)→ 停止;待机/已暂停 → 开始
const btn = document.getElementById('cxRunBtn');
if (btn) btn.textContent = (text === '工作中' && !PAUSED) ? '⏸' : '▶';
}
// 日志转义:DOM 诊断片段含 HTML 标签,必须转义后再显示,否则被面板当真标签吞掉
function escapeHtml(s) {
return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
// 日志正文一律转义,避免 DOM 诊断片段被当成真标签渲染
function renderLogLines(lines) {
const ic = { ok: '✓', warn: '!', err: '×', info: '·' };
return lines.map((l) => '' +
(ic[l.level] || '·') + '' + escapeHtml(l.line) + '
').join('');
}
function log(msg, level = 'info', opts) {
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
const line = `[${time}] ${msg}`;
const color = level === 'ok' ? '#7ee787' : level === 'warn' ? '#f0b72f' : level === 'err' ? '#f85149' : '#58a6ff';
console.log(`%c[全平台助手] ${line}`, `color:${color}`);
if (logPanel) {
logLines.push({ line, level });
if (logLines.length > 60) logLines.shift();
const logsEl = document.getElementById('cxLogs');
if (logsEl) {
logsEl.innerHTML = renderLogLines(logLines);
logsEl.scrollTop = logsEl.scrollHeight;
}
}
}
// ===== 本地状态仅保存在浏览器,不向任何地址推送 =====
function scriptVersion() {
try { if (typeof GM_info !== 'undefined' && GM_info.script && GM_info.script.version) return GM_info.script.version; } catch (e) { /* ignore */ }
return 'unknown';
}
let PAUSED = false;
function togglePause() {
PAUSED = !PAUSED;
setStatus(PAUSED ? '已暂停' : '工作中');
log(PAUSED ? '⏸ 已暂停挂机(答题全部冻结在当前步骤,点「开始」继续)' : '▶ 已恢复挂机(任务从暂停处继续)', PAUSED ? 'warn' : 'ok');
}
/* ==================== 单一面板:状态 + 配置一体化 ==================== */
function cxSwitchTab(name) {
const p = document.getElementById('cxPanel');
if (!p) return;
p.querySelectorAll('#cxTabs button').forEach((b) => b.classList.toggle('on', b.dataset.tab === name));
p.querySelectorAll('.cx-page').forEach((x) => x.classList.toggle('on', x.dataset.page === name));
if (name === 'auth') queryCardStatus(true);
}
function showConfigUI() {
const p = document.getElementById('cxPanel');
if (!p) { initPanel(); return; }
p.classList.remove('cx-min');
cxSwitchTab('answer');
}
function initPanel() {
if (logPanel) return;
logPanel = document.createElement('div');
logPanel.id = 'cxPanel';
const fld = (label, inner, hint) => '' + inner +
(hint ? '
' + hint + '
' : '') + '
';
const check = (id, text, on) => '';
const currentProvider = AI_PROVIDERS[CONFIG.aiProvider] ? CONFIG.aiProvider : detectProvider(CONFIG.aiUrl);
logPanel.innerHTML = [
'',
'✦全平台助手',
'体验版',
'待机',
'',
'',
'
',
'',
'',
'',
'',
'',
'',
'',
'',
'
',
'',
''
].join('');
const st = document.createElement('style');
st.textContent = `
#cxPanel{--bg:#0b111b;--bg2:#131f2e;--panel:rgba(13,20,32,.985);--line:#263a50;--ink:#e4eef7;--soft:#849aae;--acc:#2dd4bf;--acc2:#a78bfa;--ok:#34d399;--err:#fb7185;--shadow:0 28px 80px rgba(0,0,0,.65);position:fixed;right:18px;bottom:18px;width:480px;max-height:86vh;background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:16px;box-shadow:var(--shadow);backdrop-filter:blur(18px);font:13px/1.65 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif;display:flex;flex-direction:column;overflow:hidden;z-index:2147483647}
#cxPanel *{box-sizing:border-box}#cxPanel.cx-min{width:330px}
#cxPanel.cx-min #cxTabs,#cxPanel.cx-min #cxScroll,#cxPanel.cx-min #cxFoot{display:none}
#cxTitle{padding:11px 13px;display:flex;align-items:center;gap:7px;background:linear-gradient(100deg,#14283a,#101a28);border-bottom:1px solid var(--line);cursor:move;user-select:none;min-width:0}
.cx-logo{color:var(--acc);font-size:17px;text-shadow:0 0 12px rgba(45,212,191,.65)}
#cxTitleText{font-weight:700;white-space:nowrap}
.cx-vip{font-size:10px;padding:2px 8px;border-radius:999px;background:#1c2b3d;color:var(--soft);border:1px solid var(--line);white-space:nowrap}
.cx-vip.on{background:linear-gradient(135deg,#134e4a,#0f766e);color:#99f6e4;border-color:#14b8a6;box-shadow:0 0 14px rgba(45,212,191,.3)}
#cxStatus{margin-left:auto;font-size:11px;padding:2px 9px;border-radius:999px;background:#12283a;color:#7dd3fc;white-space:nowrap}
#cxTitle button{cursor:pointer;color:var(--ink);background:#172536;border:1px solid var(--line);border-radius:8px;min-width:28px;height:26px;font-size:13px}
#cxTitle button:hover{background:#1d3448;border-color:var(--acc);color:var(--acc)}
#cxTabs{display:flex;gap:2px;padding:7px 8px 0;background:var(--bg2);border-bottom:1px solid var(--line)}
#cxTabs button{flex:1;background:transparent;border:1px solid transparent;border-bottom:0;color:var(--soft);padding:8px 1px;border-radius:9px 9px 0 0;cursor:pointer;font-size:11px;white-space:nowrap}
#cxTabs button:hover{color:var(--ink);background:#1a2c3e}
#cxTabs button.on{background:var(--panel);border-color:var(--line);color:var(--acc);font-weight:700;box-shadow:inset 0 2px 0 var(--acc)}
#cxScroll{overflow-y:auto;padding:12px 14px;flex:1;scrollbar-width:thin;scrollbar-color:#2b465c transparent}
.cx-page{display:none}.cx-page.on{display:block}
.cx-card{background:rgba(19,31,46,.75);border:1px solid var(--line);border-radius:12px;padding:12px 13px;margin-bottom:11px}
.cx-card-t{font-size:12px;font-weight:700;color:var(--acc2);margin-bottom:9px}
.cx-field{margin:9px 0}.cx-field>label{display:block;font-size:12px;color:#b9cad9;margin-bottom:5px}
.cx-field input,.cx-field select,.cx-field textarea,.cx-auth-card input{width:100%;background:#0a111b;border:1px solid #2a3f55;border-radius:9px;color:var(--ink);padding:8px 10px;font-size:13px;outline:none}
.cx-field input:focus,.cx-field select:focus,.cx-field textarea:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(45,212,191,.12)}
.cx-field textarea{resize:vertical;font:12px/1.5 ui-monospace,Consolas,monospace}
.cx-hint{font-size:11px;color:var(--soft);margin-top:5px;line-height:1.6}
.cx-checks{display:grid;grid-template-columns:1fr 1fr;gap:4px 10px;margin:8px 0}
.cx-check{display:flex;align-items:center;gap:8px;cursor:pointer;font-size:12px;padding:3px 0}
.cx-check input{width:15px;height:15px;accent-color:var(--acc);flex:0 0 auto}
.cx-inline{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.cx-inline input{flex:1;min-width:0;width:auto}
.cx-row{display:flex;gap:9px}.cx-row>div{flex:1;min-width:0}
.cx-btn{background:linear-gradient(135deg,#14b8a6,#0ea5e9);color:#04201c;border:0;border-radius:9px;padding:8px 16px;font-size:13px;font-weight:700;cursor:pointer;white-space:nowrap}
.cx-btn.ghost{background:#182a3c;color:#a5e9dd;border:1px solid #2c4a5e}
.cx-btn.sm{padding:6px 11px;font-size:12px}
#cxFoot{padding:10px 14px;display:flex;justify-content:space-between;align-items:center;gap:10px;background:var(--bg2);border-top:1px solid var(--line)}
#cxFoot span{font-size:11px;color:var(--soft)}
#cxDash{display:flex;gap:1px;background:var(--line);border-radius:9px;overflow:hidden}
.cx-stat{flex:1;background:var(--bg2);padding:9px 6px;text-align:center;min-width:0}
.cx-stat b{display:block;font-size:13px;color:var(--acc);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.cx-stat span{font-size:10px;color:var(--soft)}
#cxLogs{padding:6px 9px;overflow-y:auto;max-height:220px;background:#0a111b;border:1px solid var(--line);border-radius:9px;scrollbar-width:thin;scrollbar-color:#2b465c transparent}
.cx-log{color:#9fb3c6;margin:3px 0;font-size:11.5px;word-break:break-all}
.cx-log-i{display:inline-block;width:14px;color:var(--soft)}
.cx-log.ok{color:#6ee7b7}.cx-log.ok .cx-log-i{color:var(--ok)}
.cx-log.warn{color:#fcd34d}.cx-log.warn .cx-log-i{color:#fbbf24}
.cx-log.err{color:#fda4af}.cx-log.err .cx-log-i{color:var(--err)}
.cx-auth-card{position:relative;background:linear-gradient(135deg,#132c3a,#1b1b3a);border:1px solid #2b4c60;border-radius:13px;padding:14px;margin-bottom:11px;overflow:hidden}
.cx-auth-card:after{content:"";position:absolute;right:-30px;top:-40px;width:120px;height:120px;border-radius:50%;background:radial-gradient(circle,rgba(45,212,191,.18),transparent 70%)}
.cx-auth-icon{font-size:24px;float:left;margin-right:11px}
.auth-state{display:block;font-size:16px;color:#e2e8f0}.auth-state.on{color:#5eead4}
#authDetail{font-size:11.5px;color:#9fb6c6}
.cx-auth-bar{height:5px;background:#0b111b;border-radius:99px;margin-top:12px;overflow:hidden;clear:both}
.cx-auth-bar i{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--acc),var(--acc2));transition:width .5s}
.cx-auth-msg{font-size:12px;color:var(--ok);margin-top:8px;min-height:18px}.cx-auth-msg.bad{color:var(--err)}
.cx-pay{display:flex;gap:12px;justify-content:center;margin:12px 0}
.cx-pay>div{display:flex;flex-direction:column;align-items:center;gap:5px;font-size:11px;color:#9fb6c6}
.cx-pay img{width:132px;height:132px;object-fit:contain;background:#fff;border-radius:8px;padding:5px;border:1px solid #2c4055}
.cx-group{display:block;text-align:center;background:#132b3a;border:1px solid #2c5a6b;color:#7dd3fc;border-radius:9px;padding:9px;text-decoration:none;font-size:12px;font-weight:600}
.cx-group:hover{border-color:var(--acc);color:#a5f3fc}
.cx-pinfo{margin-top:7px;background:#0b111b;border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-size:11px;line-height:1.7;color:#a9c0d0}
.cx-pinfo a{color:var(--acc);text-decoration:underline}.cx-pinfo code{color:#93c5fd}
.cx-test{font-size:11px;color:var(--soft);word-break:break-all}
.cx-p{font-size:12px;color:#b6c8d6;margin:7px 0;line-height:1.75}
.cx-p b{color:#7ee7d5}
`;
document.head.appendChild(st);
document.body.appendChild(logPanel);
log('✦ 全平台助手 v' + scriptVersion() + ' 已加载(专业版)');
// 收起 / 展开
document.getElementById('cxClose').addEventListener('click', () => {
logPanel.classList.toggle('cx-min');
document.getElementById('cxClose').textContent = logPanel.classList.contains('cx-min') ? '▴' : '▾';
});
// 标签切换
logPanel.querySelectorAll('#cxTabs button').forEach((b) => b.addEventListener('click', () => cxSwitchTab(b.dataset.tab)));
// 运行 / 暂停
document.getElementById('cxRunBtn').addEventListener('click', togglePause);
// 拖拽
const titleEl = document.getElementById('cxTitle');
titleEl.addEventListener('mousedown', (e) => {
if (e.target.closest('button')) return;
e.preventDefault();
const rect = logPanel.getBoundingClientRect();
const sx = e.clientX, sy = e.clientY;
logPanel.style.left = rect.left + 'px'; logPanel.style.top = rect.top + 'px';
logPanel.style.right = 'auto'; logPanel.style.bottom = 'auto';
const onMove = (ev) => { logPanel.style.left = (rect.left + ev.clientX - sx) + 'px'; logPanel.style.top = (rect.top + ev.clientY - sy) + 'px'; };
const onUp = () => { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onUp); };
document.addEventListener('mousemove', onMove); document.addEventListener('mouseup', onUp);
});
// ===== 配置事件 =====
const renderProviderInfo = (k) => { const box = document.getElementById('cfgProviderInfo'); if (box) box.innerHTML = providerInfoHtml(k); };
renderProviderInfo(currentProvider);
document.getElementById('cfgProvider').addEventListener('change', (e) => {
const k = e.target.value, p = AI_PROVIDERS[k] || AI_PROVIDERS.custom;
document.getElementById('cfgAIUrl').value = p.url;
document.getElementById('cfgAIModel').value = p.model;
renderProviderInfo(k);
document.getElementById('cfgTestResult').textContent = '已切换平台,请重新测试连接';
});
document.getElementById('cfgFetchModels').addEventListener('click', async () => {
const base = document.getElementById('cfgAIUrl').value.trim();
const key = document.getElementById('cfgAIKey').value.trim();
const btn = document.getElementById('cfgFetchModels');
if (!base || !key) { document.getElementById('cfgTestResult').textContent = '请先填接口地址与 API Key'; return; }
btn.disabled = true; btn.textContent = '拉取中...';
try {
const obj = JSON.parse(await cxFetch(modelsEndpointFor(base), { method: 'GET', headers: { 'Authorization': 'Bearer ' + key }, timeout: 15000 }));
const list = (obj.data || obj.models || []).map((m) => (m && (m.id || m.model || m.name)) || (typeof m === 'string' ? m : '')).filter(Boolean);
document.getElementById('cxModelList').innerHTML = list.map((id) => '').join('');
document.getElementById('cfgTestResult').textContent = list.length ? ('✅ 已拉取 ' + list.length + ' 个模型,点输入框选择') : '该平台未返回模型列表';
} catch (e) { document.getElementById('cfgTestResult').textContent = '拉取失败:检查 Key / 跨域授权'; }
btn.disabled = false; btn.textContent = '拉取列表';
});
document.getElementById('cfgTestAI').addEventListener('click', async () => {
const box = document.getElementById('cfgTestResult');
const url = document.getElementById('cfgAIUrl').value.trim();
const key = document.getElementById('cfgAIKey').value.trim();
const model = document.getElementById('cfgAIModel').value.trim();
const providerKey = document.getElementById('cfgProvider').value;
if (!url || !key || !model) { box.textContent = '❌ 接口地址 / Key / 模型名三项都要填'; return; }
box.textContent = '⏳ 正在测试...';
const r = await testAIConnection(url, key, model, providerKey);
box.textContent = (r.ok ? '✅ ' : '❌ ') + r.message;
if (r.ok) {
CONFIG.aiUrl = url; CONFIG.aiKey = key; CONFIG.aiModel = r.model || model;
CONFIG.aiProvider = providerKey; CONFIG.aiEnabled = true;
document.getElementById('cfgAI').checked = true;
if (r.model && r.model !== model) document.getElementById('cfgAIModel').value = r.model;
saveConfig(CONFIG); resetAIChannel();
log('✅ AI 连接测试通过,已自动保存并启用', 'ok');
}
});
document.getElementById('authActivate').addEventListener('click', () => {
const key = document.getElementById('cfgCard').value.replace(/\s+/g, '').toUpperCase();
if (!key) { authMsg('请先输入激活码', true); return; }
CONFIG.cardKey = key; saveConfig(CONFIG);
activateCard(key);
});
document.getElementById('authQuery').addEventListener('click', () => queryCardStatus(false));
document.getElementById('authCopy').addEventListener('click', () => {
const v = authMachineId();
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(v).then(() => authMsg('机器码已复制:' + v)).catch(() => authMsg('机器码:' + v));
else authMsg('机器码:' + v);
});
document.getElementById('cfgExport').addEventListener('click', exportQuestions);
document.getElementById('cfgPurgeAuto').addEventListener('click', () => {
const auto = COLLECTED.filter((it) => it.src !== 'import' && it.src !== 'verified').length;
if (!auto) { log('没有自动收录的记录,无需清理', 'info'); return; }
if (!confirm('将清除 ' + auto + ' 条脚本自动收录的答案(手动导入和判分确认的保留)。\n建议先备份。确定继续?')) return;
COLLECTED = COLLECTED.filter((it) => it.src === 'import' || it.src === 'verified');
try { if (typeof GM_setValue !== 'undefined') GM_setValue('cxQuestions', COLLECTED); else localStorage.setItem('cxQuestions', JSON.stringify(COLLECTED)); } catch (e) { /* ignore */ }
log('🧹 已清除 ' + auto + ' 条自动收录记录', 'ok');
});
document.getElementById('cfgImport').addEventListener('click', () => {
const ta = document.getElementById('cfgImportData');
const raw = (ta.value || '').trim();
if (!raw) { log('请先粘贴题库 JSON', 'warn'); return; }
try {
const arr = JSON.parse(raw);
if (!Array.isArray(arr)) throw new Error('不是 JSON 数组');
let added = 0, replaced = 0, skipped = 0;
for (const it of arr) {
const question = String(it.q || it.question || '').trim();
let a = (it.a != null) ? it.a : (it.answer != null ? it.answer : it.answers);
if (Array.isArray(a)) a = a.join('|');
a = String(a || '').trim();
if (!question || !a) { skipped++; continue; }
const rec = { q: question, t: String(it.t != null ? it.t : (it.type != null ? it.type : '')), o: String(it.o || ''), a: a, c: 1, src: 'import' };
const k = normQ(question);
const at = COLLECTED.findIndex((x) => normQ(x.q) === k);
if (at >= 0) { COLLECTED[at] = rec; replaced++; } else { COLLECTED.push(rec); added++; }
}
try { if (typeof GM_setValue !== 'undefined') GM_setValue('cxQuestions', COLLECTED); else localStorage.setItem('cxQuestions', JSON.stringify(COLLECTED)); } catch (e) { /* ignore */ }
log('📥 导入完成:新增 ' + added + ' / 替换 ' + replaced + ' / 跳过 ' + skipped, 'ok');
ta.value = '';
} catch (e) { log('导入失败:' + (e.message || e), 'err'); }
});
document.getElementById('cfgSave').addEventListener('click', () => {
const providerKey = document.getElementById('cfgProvider').value;
const preset = AI_PROVIDERS[providerKey] || AI_PROVIDERS.custom;
CONFIG.speed = cfgNum(document.getElementById('cfgSpeed').value, 1, 1, 2);
CONFIG.aiEnabled = document.getElementById('cfgAI').checked;
CONFIG.aiKey = document.getElementById('cfgAIKey').value.trim();
CONFIG.aiProvider = providerKey;
CONFIG.aiModel = document.getElementById('cfgAIModel').value.trim() || preset.model || 'deepseek-v4-flash';
CONFIG.aiUrl = document.getElementById('cfgAIUrl').value.trim() || preset.url || 'https://api.deepseek.com/v1/chat/completions';
if (CONFIG.aiKey && !CONFIG.aiEnabled) { CONFIG.aiEnabled = true; document.getElementById('cfgAI').checked = true; log('🔑 已填 Key,自动勾选启用 AI 答题', 'ok'); }
CONFIG.deliberateErrorRate = cfgNum(document.getElementById('cfgErrRate').value, 0, 0, 20) / 100;
CONFIG.dailyLimitMinutes = cfgNum(document.getElementById('cfgDaily').value, 0, 0, 1440);
CONFIG.autoSubmit = document.getElementById('cfgSubmit').checked;
CONFIG.autoJump = document.getElementById('cfgJump').checked;
CONFIG.useWebSearch = document.getElementById('cfgWeb').checked;
CONFIG.useTiku = document.getElementById('cfgTiku').checked;
CONFIG.aiBlankStructured = document.getElementById('cfgAIBlankStruct').checked;
CONFIG.aiFirstForText = document.getElementById('cfgAIFirstText').checked;
CONFIG.blankPayloadStrict = document.getElementById('cfgBlankPayload').checked;
CONFIG.blankSearchFallback = document.getElementById('cfgBlankSearch').checked;
CONFIG.minAccuracy = cfgNum(document.getElementById('cfgMinAcc').value, 60, 0, 100) / 100;
CONFIG.cardKey = document.getElementById('cfgCard').value.replace(/\s+/g, '').toUpperCase();
CONFIG.overwrite = document.getElementById('cfgOverwrite').checked;
CONFIG.quizRandomFallback = document.getElementById('cfgQFb').checked;
CONFIG.muted = document.getElementById('cfgMuted').checked;
CONFIG.autoLearnResult = document.getElementById('cfgLearnResult').checked;
CONFIG.genericMode = document.getElementById('cfgGenericMode').checked;
CONFIG.genericSubmit = document.getElementById('cfgGenericSubmit').checked;
CONFIG.failTolerance = Math.round(cfgNum(document.getElementById('cfgFailTol').value, 3, 1, 10));
saveConfig(CONFIG); resetAIChannel();
log('💾 配置已保存(AI ' + (CONFIG.aiEnabled ? '开' : '关') + ' · 题库 ' + (CONFIG.useTiku ? '开' : '关') + ' · 搜索 ' + (CONFIG.useWebSearch ? '开' : '关') + ' · 通用 ' + (CONFIG.genericMode ? '开' : '关') + ')', 'ok');
if (!CONFIG.useTiku && !CONFIG.useWebSearch && !CONFIG.aiEnabled) log('⚠ 在线题库、搜索与 AI 都已关闭,可能大量留空', 'warn');
if (CONFIG.cardKey) activateCard(CONFIG.cardKey);
});
if (logLines.length === 0) {
logLines.push({ line: '💡 打开课程页面自动开始答题;切换上方标签查看设置', level: 'info' });
logLines.push({ line: '🔑 会员激活码为可选增强,免费链路无需激活码即可使用', level: 'info' });
}
const initLogs = document.getElementById('cxLogs');
if (initLogs) initLogs.innerHTML = renderLogLines(logLines);
try {
document.getElementById('cxStatCount').textContent = String((typeof COLLECTED !== 'undefined' && COLLECTED.length) || 0);
document.getElementById('cxStatAi').textContent = (CONFIG.aiEnabled && CONFIG.aiKey) ? (CONFIG.aiProvider || 'AI 已启用') : '未启用';
} catch (e) { /* ignore */ }
authRender({ ok: false, active: false, message: '' });
if (CONFIG.cardKey) setTimeout(() => { queryCardStatus(true); }, 400);
}
/* ==================== 答案通道 ==================== */
// 免费题库站公开协议适配(公开题库无需 token 即可查询)
async function channelTikuHai(q) {
try {
const res = JSON.parse(await cxFetch('https://api.tikuhai.com/search', {
method: 'POST', timeout: 8000,
data: JSON.stringify({ question: q.question, type: q.type }),
headers: { 'Content-Type': 'application/json' }
}));
// 2026-11 实测该站已转付费:code=-1 时 msg 是整段「购买后可查看」的 HTML。
// 旧版直接 split('#') 把这段 HTML 当答案返回,虽然多数会被 filterAnswers 拦下,
// 但仍会白跑一次请求、部分题型还可能漏进脏文本,这里直接判为无答案。
const msg = String(res.msg || '');
if (/(付费|购买|充值|会员|解锁|订单)/.test(msg)) return { form: '题库海', answer: [] };
if (res.code === -1) return { form: '题库海', answer: msg.split('#') };
const a = (res.data && res.data.answer) || msg || '';
return { form: '题库海', answer: String(a).split('#') };
} catch (e) { return { form: '题库海', answer: [] }; }
}
async function channelYizhi(q) {
try {
// 不再伪造 X-Forwarded-For/X-Real-IP 绕过限流(易触发风控且不规范),按原始请求发送
const res = JSON.parse(await cxFetch('https://cx.icodef.com/wyn-nb?v=4', {
method: 'POST', timeout: 8000,
data: JSON.stringify({ question: q.question }),
headers: { 'Content-Type': 'application/json' }
}));
if (res.code !== 1) return { form: '一之题库', answer: [] };
let data = String(res.data || '').replace(/javascript:void\(0\);/g, '').replace(/\n/g, '').trim();
if (/(叛逆|公众号|李恒雅|一之)/.test(data)) return { form: '一之题库', answer: [] };
return { form: '一之题库', answer: data.split('#') };
} catch (e) { return { form: '一之题库', answer: [] }; }
}
async function channelYanxi(q) {
try {
// 官方协议是 GET + query 参数(POST + JSON 会直接 404/参数丢失),已修正
const res = JSON.parse(await cxFetch('https://tk.enncy.cn/query?title=' + encodeURIComponent(q.question), {
method: 'GET', timeout: 8000,
headers: {}
}));
if (res.code !== 1) return { form: '言溪题库', answer: [] };
return { form: '言溪题库', answer: String(res.data.answer || '').split('#') };
} catch (e) { return { form: '言溪题库', answer: [] }; }
}
async function channelMuketool(q) {
try {
const res = JSON.parse(await cxFetch('https://api.muketool.com/cx/v2/query', {
method: 'POST', timeout: 8000,
data: JSON.stringify({ question: q.question, type: parseInt(q.type, 10) || 0 }),
headers: { 'Content-Type': 'application/json' }
}));
if (res.code !== 1) return { form: '木课工具', answer: [] };
return { form: '木课工具', answer: String(res.data || '').split('#') };
} catch (e) { return { form: '木课工具', answer: [] }; }
}
/* 本地自建题库(零成本、零延迟、优先级最高):
数据源 = 脚本自动积累的做过的题 + ⚙ 里手动导入的题库 JSON */
/* ===== v4.0.0 填空题基础设施:题干指纹 / 空位数 / 多格式答案拆分 =====
填空题题干含 ____、( )、题号、分值,各题库按完整题干精确匹配必然查不到;
AI 又常把多个空写成 1. X 2. Y / 第N空:X / 顿号分隔 / JSON。这里统一收敛。 */
function isTextType(t) { return /^(2|4|5|6|7|9)$/.test(String(t == null ? '' : t)); }
// 只用于「题库检索/匹配」的稳定题干指纹;AI 与页面显示仍用原始明文,绝不回写 DOM
function stemKey(s) {
return String(s || '')
.replace(/^【[^】]*】\s*/, '')
.replace(/^\s*(单选题|多选题|判断题|填空题|简答题|论述题|名词解释)\s*[::]?\s*/, '')
.replace(/^\s*\d{1,3}\s*[..、))]\s*/, '')
.replace(/[((]\s*\d+(\.\d+)?\s*分\s*[))]\s*$/, '')
.replace(/[_\uFF3F\u2014\-\s]{2,}/g, '')
.replace(/[((]\s*[))]/g, '')
.replace(/[\[\]【】□■]/g, '')
.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '')
.toLowerCase();
}
function cleanBlankText(x) {
return String(x == null ? '' : x)
.replace(/^["'“”‘’\s]+|["'“”‘’\s]+$/g, '')
.replace(/^第\s*[一二三四五六七八九十\d]+\s*空\s*[::]?\s*/, '')
.replace(/^(答案|正确答案)\s*[::]\s*/i, '')
.replace(/[。;;]+$/g, '')
.trim();
}
function cleanBlanks(arr, want) {
const out = [];
for (const raw of (arr || [])) {
const a = cleanBlankText(raw);
if (!a) continue;
if (a.length > 60 && REASONING_RE.test(a)) continue; // 长推理整段丢弃,短答案不误伤
if (/^https?:|www\./i.test(a)) continue;
out.push(a);
}
// 只有一段却需要多空:保留这一份「综合答案」,交给填写器处理,不伪造、不按估计空数截断
return out.slice(0, 10);
}
function splitTextAnswers(raw, type, expected) {
const want = Math.max(1, Number(expected) || 1);
let s = String(raw == null ? '' : raw).trim();
if (!s) return [];
if (String(type) !== '2') return [s]; // 简答/论述:整段保留,绝不按标点拆
// ① 结构化 JSON(兼容 ```json 围栏)
s = s.replace(/^```[a-z]*\s*/i, '').replace(/```\s*$/, '').trim();
const jm = s.match(/\{[\s\S]*?"blanks"\s*:\s*\[[\s\S]*?\][\s\S]*?\}/);
if (jm) {
try {
const o = JSON.parse(jm[0]);
if (o && Array.isArray(o.blanks)) {
const arr = o.blanks.map((x) => cleanBlankText(x)).filter(Boolean);
if (arr.length) return cleanBlanks(arr, want);
}
} catch (e) { /* 不是合法 JSON,继续按文本拆 */ }
}
s = s.replace(/^(答案|正确答案|参考答案|填空答案|最终答案)\s*[::]?\s*/i, '').trim();
// ② 编号 / 第N空 → 统一换成换行
s = s.replace(/第\s*[一二三四五六七八九十\d]+\s*空\s*[::]?\s*/g, '\n')
.replace(/[((]\s*\d{1,2}\s*[))]\s*[::]?\s*/g, '\n')
.replace(/(^|[\s|])\d{1,2}\s*[..、))]\s*/g, '$1\n');
// ③ 主分隔符:竖线 / 井号 / 换行
let parts = s.split(/[||#\n\r]+/).map(cleanBlankText).filter(Boolean);
// ④ 数量对不上且明确需要多空时,再试中文分号/顿号(不拆英文逗号,避免把「1,2」拆坏)
if (want > 1 && parts.length !== want) {
const more = s.split(/[;;、]+/).map(cleanBlankText).filter(Boolean);
if (more.length === want) parts = more;
}
if (parts.length === 1 && want > 1 && /[;;、]/.test(parts[0])) {
parts = parts[0].split(/[;;、]+/).map(cleanBlankText).filter(Boolean);
}
return cleanBlanks(parts, want);
}
function blankCountOf(root, q) {
let n = 0;
try { n = collectBlankInputs(root).length; } catch (e) { n = 0; }
if (!n) {
const s = String((q && (q.question || q.rawQuestion)) || '');
const under = (s.match(/[_\uFF3F]{2,}/g) || []).length;
const paren = (s.match(/[((]\s*[))]/g) || []).length;
const sq = (s.match(/\[\s*\]|【\s*】/g) || []).length;
n = under + paren + sq;
}
return Math.min(10, Math.max(1, Number(n) || 1));
}
function normQ(s) { return String(s || '').replace(/\s+/g, '').toLowerCase(); }
function channelLocal(q) {
try {
// 题干同时用「原文指纹」和「去空位符指纹」匹配:
// 填空题的 ____ /( )/题号/分值在不同页面写法不一,只比原文永远查不到。
const keys = [normQ(q.question), normQ(q.rawQuestion), stemKey(q.question), stemKey(q.rawQuestion)]
.filter((k, i, a) => k && a.indexOf(k) === i);
if (!keys.length || keys[0].length < 4) return { form: '本地题库', answer: [] };
let hit = null, bestC = -1;
for (const it of COLLECTED) {
if (!it.a) continue; // 跳过没答案的历史记录
const n = normQ(it.q);
const ns = stemKey(it.q);
const matched = keys.some((key) =>
n === key || ns === key ||
(key.length >= 8 && (n.includes(key) || key.includes(n) || ns.includes(key) || key.includes(ns))));
if (matched) {
const c = Number(it.c == null ? 1 : it.c);
if (Number.isFinite(c) && c > bestC) { hit = it; bestC = c; }
}
}
if (hit) {
const ans = String(hit.a).split('|').filter(Boolean);
if (ans.length) return { form: '本地题库', answer: ans, confidence: bestC,
verified: hit.src === 'verified' || hit.src === 'import' };
}
} catch (e) { /* ignore */ }
return { form: '本地题库', answer: [], confidence: 0 };
}
/* 必应实时搜索兜底(免费):把题干拿到必应搜,从结果摘要里按「选项文本命中」推断答案。
启发式,准确率有限;不用百度是因为百度反爬严(验证码/乱码壳页),必应摘要可直接解析 */
async function channelWebSearch(q) {
try {
const url = 'https://cn.bing.com/search?q=' + encodeURIComponent(q.question.slice(0, 80) + ' 答案');
const html = await cxFetch(url, { method: 'GET', headers: {}, timeout: 12000 });
const text = String(html)
.replace(/