// ==UserScript==
// @name 易班考试答题助手(新版)
// @namespace http://tampermonkey.net/
// @version 3.1.4
// @description 易班考试自动答题助手 - 支持题目ID、题干文本和混合匹配,保留随机答题兜底。
// @author You
// @match *://exam.yooc.me/group/*/exam/*
// @match *://exam.yooc.me/group/*/exams
// @match *://www.yooc.me/*
// @require https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @connect exambackend.yooc.me
// @connect 38.76.215.191
// @connect *
// ==/UserScript==
(function() {
'use strict';
// 新版题库独立使用 v2 存储键,避免读取旧脚本的题库字段。
const QUESTION_BANK_STORAGE_KEY = 'question_bank_v2';
const SCRIPT_VERSION = '3.1.4';
// 网页版跳转到手机版
var currentUrl = window.location.href;
if (currentUrl.includes('www.yooc.me') && !currentUrl.includes('/mobile/')) {
console.log('[考试助手] 检测到网页版,跳转到手机版');
window.location.href = 'https://www.yooc.me/mobile/dashboard';
return;
}
// 生产环境通过 Caddy 的 /script-api 反向代理访问 script 服务。
var _0xda = 'http://38.76.215.191/script-api/license';
var _0xhb = 1800000;
var _0xt = null;
function _0xfp() {
var cached = GM_getValue('license_fingerprint', '');
if (cached) return cached;
var parts = [];
try { parts.push(navigator.userAgent || ''); } catch(e) {}
try { parts.push(navigator.language || ''); } catch(e) {}
try { parts.push(navigator.platform || ''); } catch(e) {}
try { parts.push(String(navigator.hardwareConcurrency || '')); } catch(e) {}
try { parts.push(screen.width + 'x' + screen.height); } catch(e) {}
try { parts.push(String(screen.colorDepth || '')); } catch(e) {}
try { parts.push(Intl.DateTimeFormat().resolvedOptions().timeZone || ''); } catch(e) {}
try { parts.push(String(navigator.deviceMemory || '')); } catch(e) {}
try {
var canvas = document.createElement('canvas');
var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (gl) {
var ext = gl.getExtension('WEBGL_debug_renderer_info');
if (ext) {
parts.push(gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || '');
parts.push(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || '');
}
}
} catch(e) {}
try {
var c = document.createElement('canvas');
c.width = 200; c.height = 50;
var ctx = c.getContext('2d');
ctx.textBaseline = 'top';
ctx.font = '14px Arial';
ctx.fillStyle = '#f60';
ctx.fillRect(0, 0, 200, 50);
ctx.fillStyle = '#069';
ctx.fillText('fingerprint_test_2024', 2, 15);
parts.push(c.toDataURL());
} catch(e) {}
var raw = parts.join('|||');
var hash = CryptoJS.SHA256(raw).toString(CryptoJS.enc.Hex);
GM_setValue('license_fingerprint', hash);
return hash;
}
function _0xm(mode, reason) {
var old = document.getElementById('license-overlay');
if (old) old.remove();
var overlay = document.createElement('div');
overlay.id = 'license-overlay';
var errorText = '';
if (mode === 'expired') errorText = '授权已过期,请更换授权码。';
else if (mode === 'error') {
var reasonMap = {
'invalid_key': '授权码无效',
'disabled': '授权码已被禁用',
'fingerprint_mismatch': '设备不匹配(已达换绑上限)',
'network': '网络请求失败,请检查网络后重试'
};
errorText = reasonMap[reason] || '验证失败:' + (reason || '未知错误');
}
var title = mode === 'expired' ? '授权已过期' : '考试助手 - 授权验证';
var subtitle = mode === 'expired' ? '你的授权码已过期,请更换新的授权码。' : '请输入授权码激活脚本,获取试用请加QQ群。';
overlay.innerHTML =
'
' +
'
' +
'
' +
'
' +
'
' + title + '
' +
'
' + subtitle + '
' +
'
' +
'
' +
'
' +
(errorText ? '
' + errorText + '
' : '') +
'
' +
'
' +
'
' +
'
' +
'
' +
'
';
document.body.appendChild(overlay);
var input = document.getElementById('license-input');
var btn = document.getElementById('license-submit');
var msg = document.getElementById('license-msg');
var closeBtn = document.getElementById('license-close');
if (closeBtn) closeBtn.addEventListener('click', function() { overlay.remove(); });
input.addEventListener('input', function() {
var v = input.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase().substring(0, 16);
var formatted = '';
for (var i = 0; i < v.length; i++) {
if (i > 0 && i % 4 === 0) formatted += '-';
formatted += v[i];
}
input.value = formatted;
});
input.addEventListener('keydown', function(e) {
if (e.key === 'Enter') btn.click();
});
btn.addEventListener('click', function() {
var key = input.value.trim();
if (key.length !== 19) {
msg.textContent = '请输入完整的授权码';
msg.style.color = '#dc2626';
return;
}
btn.disabled = true;
btn.textContent = '验证中...';
msg.textContent = '';
var fp = _0xfp();
_0xv(key, fp, function(result) {
if (result.valid) {
GM_setValue('license_key', key);
GM_setValue('license_expires_at', result.expires_at);
GM_setValue('license_verified_at', Date.now());
GM_setValue('license_token', result.token || '');
overlay.remove();
_0xsh();
initWithLicense(result.remaining_hours);
} else {
btn.disabled = false;
btn.textContent = '激活';
msg.textContent = (function() {
var m = {
'invalid_key': '授权码无效',
'disabled': '授权码已被禁用',
'expired': '授权码已过期',
'fingerprint_mismatch': '设备不匹配(已达换绑上限)',
'network': '无法连接授权服务器,请检查 Caddy 的 /script-api 路由'
};
return m[result.reason] || '验证失败';
})();
msg.style.color = '#dc2626';
}
});
});
input.focus();
}
function _0xv(key, fingerprint, callback) {
GM_xmlhttpRequest({
method: 'POST',
url: _0xda + '/verify',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ key: key, fingerprint: fingerprint }),
onload: function(resp) {
try {
callback(JSON.parse(resp.responseText));
} catch(e) {
callback({ valid: false, reason: 'network' });
}
},
onerror: function() {
callback({ valid: false, reason: 'network' });
}
});
}
function _0xhc() {
var key = GM_getValue('license_key', '');
var fp = GM_getValue('license_fingerprint', '');
if (!key || !fp) return;
GM_xmlhttpRequest({
method: 'POST',
url: _0xda + '/heartbeat',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ key: key, fingerprint: fp }),
onload: function(resp) {
try {
var result = JSON.parse(resp.responseText);
if (result.valid) {
GM_setValue('license_expires_at', result.expires_at);
GM_setValue('license_verified_at', Date.now());
GM_setValue('license_token', result.token || '');
GM_setValue('license_checksum', result.checksum || '');
_0xups(true, result.remaining_hours);
} else {
_0xups(false, 0);
_0xm('error', result.reason);
}
} catch(e) {}
},
onerror: function() {
console.warn('[考试助手] 心跳请求失败');
}
});
}
function _0xsh() {
if (_0xt) clearInterval(_0xt);
_0xt = setInterval(_0xhc, _0xhb);
}
function _0xfmt(hours) {
if (hours >= 24) return Math.floor(hours / 24) + '天' + (hours % 24) + '小时';
return hours + '小时';
}
function _0xups(active, remainingHours) {
var status = document.querySelector('#hp-status');
if (!status) return;
if (active) {
status.innerHTML = '已激活
剩' + _0xfmt(remainingHours);
status.className = 'hp-status';
var btns = document.querySelectorAll('#helper-panel button');
btns.forEach(function(b) { b.style.pointerEvents = 'auto'; b.style.opacity = '1'; });
} else {
status.textContent = '授权已过期';
status.className = 'hp-status expired';
var btns2 = document.querySelectorAll('#helper-panel button');
btns2.forEach(function(b) { b.style.pointerEvents = 'none'; b.style.opacity = '0.4'; });
}
}
function _0xrun(callback) {
var key = GM_getValue('license_key', '');
if (!key) {
_0xm('enter');
return;
}
var expiresAt = GM_getValue('license_expires_at', '');
var localExpired = false;
if (expiresAt) {
var expireDate = new Date(expiresAt);
if (expireDate <= new Date()) {
localExpired = true;
}
}
var lastVerified = GM_getValue('license_verified_at', 0);
var elapsed = Date.now() - lastVerified;
if (elapsed < _0xhb && expiresAt && !localExpired) {
var remaining = Math.floor((new Date(expiresAt) - new Date()) / 3600000);
callback(remaining);
_0xsh();
return;
}
var remaining = expiresAt ? Math.floor((new Date(expiresAt) - new Date()) / 3600000) : 0;
if (remaining < 0) remaining = 0;
callback(remaining); // 立即创建面板
var fp = _0xfp();
var token = GM_getValue('license_token', '');
function onVerifySuccess(result) {
GM_setValue('license_expires_at', result.expires_at);
GM_setValue('license_verified_at', Date.now());
GM_setValue('license_token', result.token || '');
_0xups(true, result.remaining_hours);
_0xsh();
}
function onVerifyFail(reason) {
if (reason === 'network') {
if (expiresAt && elapsed < 2 * 3600 * 1000) {
_0xsh(); // 继续尝试心跳
} else {
_0xups(false, 0);
_0xm('error', 'network');
}
} else {
_0xups(false, 0);
_0xm('error', reason);
}
}
if (token && !localExpired) {
GM_xmlhttpRequest({
method: 'POST',
url: _0xda + '/heartbeat',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ key: key, fingerprint: fp, token: token }),
onload: function(resp) {
try {
var result = JSON.parse(resp.responseText);
if (result.valid) {
onVerifySuccess(result);
} else {
_0xdv(key, fp, onVerifySuccess, onVerifyFail);
}
} catch(e) {
_0xdv(key, fp, onVerifySuccess, onVerifyFail);
}
},
onerror: function() {
onVerifyFail('network');
}
});
} else {
_0xdv(key, fp, onVerifySuccess, onVerifyFail);
}
}
function _0xdv(key, fp, onSuccess, onFail) {
_0xv(key, fp, function(result) {
if (result.valid) {
onSuccess(result);
} else {
onFail(result.reason);
}
});
}
function initWithLicense(remainingDays) {
console.log('[考试助手] 授权验证通过,剩余 ' + _0xfmt(remainingDays));
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
console.log("脚本开始初始化...");
const userId = getCookie('user_id');
const userToken = getCookie('user_token');
const yibanId = getCookie('yiban_id');
console.log("用户信息:", { userId, userToken, yibanId });
if (!userToken) {
console.warn("未能从Cookie中获取 user_token,部分功能(如API请求)可能受限。");
}
// 同一班级的模拟题与正式考试可能复用题目,默认关闭跨考试题库匹配。
const RELATED_BANK_MATCH_KEY = 'enable_related_bank_matching';
const EXAM_CATALOG_KEY = 'exam_catalog_v2';
const relatedDownloadSession = {};
if (document.readyState === 'complete') {
createControlPanel(remainingDays);
if (window.location.href.match(/group\/\d+\/exams/)) {
injectExamListStats();
}
autoCollectOnReview();
} else {
window.addEventListener('load', function() {
createControlPanel(remainingDays);
if (window.location.href.match(/group\/\d+\/exams/)) {
injectExamListStats();
}
autoCollectOnReview();
});
}
function getCurrentGroupId() {
const match = window.location.href.match(/group\/(\d+)/);
return match ? String(match[1]) : '';
}
function normalizeExamNameForMatch(name) {
const holder = document.createElement('div');
holder.innerHTML = String(name || '');
let value = holder.textContent || holder.innerText || '';
try { value = value.normalize('NFKC'); } catch (e) {}
return value
.replace(/\u00a0/g, ' ')
.replace(/[“”"'‘’《》〈〉()()\[\]【】]/g, '')
.replace(/[::,,。!?!?、;;\-—_]/g, '')
.replace(/\s+/g, '')
.toLowerCase();
}
function buildExamNameCore(name) {
return normalizeExamNameForMatch(name)
.replace(/模拟卷|模拟题|模拟|练习卷|练习题|练习|正式答卷|正式考试|答卷|考试|试卷|测试题|测试|题库|题目/g, '')
.replace(/课程/g, '')
.trim();
}
function scoreExamNameSimilarity(targetName, candidateName) {
const target = buildExamNameCore(targetName);
const candidate = buildExamNameCore(candidateName);
if (!target || !candidate) return 0;
if (target === candidate) return 100;
return target.includes(candidate) || candidate.includes(target) ? 90 : 0;
}
function getStoredExamCatalog() {
try {
const catalog = JSON.parse(localStorage.getItem(EXAM_CATALOG_KEY) || '{}');
return catalog && typeof catalog === 'object' ? catalog : {};
} catch (e) {
return {};
}
}
function rememberExamName(examId, name, groupId) {
if (examId == null || !String(name || '').trim()) return;
const catalog = getStoredExamCatalog();
catalog[String(examId)] = {
examId: String(examId),
name: String(name).trim(),
groupId: String(groupId || getCurrentGroupId() || '')
};
localStorage.setItem(EXAM_CATALOG_KEY, JSON.stringify(catalog));
}
function fetchExamCatalog(callback) {
const groupId = getCurrentGroupId();
const catalog = getStoredExamCatalog();
if (!groupId || !userToken) {
callback(catalog);
return;
}
const url = `https://exambackend.yooc.me/api/exam/list/get?userId=${encodeURIComponent(userId || '')}&token=${encodeURIComponent(userToken)}&yibanId=${encodeURIComponent(yibanId || '')}&groupId=${encodeURIComponent(groupId)}`;
GM_xmlhttpRequest({
method: 'GET',
url: url,
headers: { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' },
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
try {
const payload = JSON.parse(response.responseText);
(Array.isArray(payload.data) ? payload.data : []).forEach(function(item) {
if (item && item.examId != null && item.name) {
catalog[String(item.examId)] = { examId: String(item.examId), name: String(item.name).trim(), groupId: groupId };
}
});
localStorage.setItem(EXAM_CATALOG_KEY, JSON.stringify(catalog));
} catch (e) {
console.warn('[考试助手] 考试目录解析失败,继续使用本地目录。', e);
}
}
callback(catalog);
},
onerror: function() { callback(catalog); }
});
}
function downloadRelatedQuestionBanks(examId, callback) {
const sessionKey = String(examId);
if (relatedDownloadSession[sessionKey]) {
callback();
return;
}
relatedDownloadSession[sessionKey] = true;
fetchExamCatalog(function(catalog) {
const current = catalog[String(examId)];
const candidates = Object.keys(catalog).map(function(id) { return catalog[id]; }).filter(function(item) {
return item.examId === String(examId) || (current && scoreExamNameSimilarity(current.name, item.name) >= 90);
}).slice(0, 6);
const targets = candidates.length ? candidates : [{ examId: String(examId) }];
console.log('[考试助手] 已选择 ' + targets.length + ' 份相关题库进行下载。');
let index = 0;
function next() {
if (index >= targets.length) {
callback();
return;
}
downloadQuestionBank(targets[index++].examId, next);
}
next();
});
}
function isLicenseValid() {
var expiresAt = GM_getValue('license_expires_at', '');
if (!expiresAt) return false;
return new Date(expiresAt).getTime() > Date.now();
}
function checkLicenseWithServer(key, cb) {
GM_xmlhttpRequest({
method: 'POST',
url: _0xda + '/check',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ key: key }),
onload: function(resp) {
try {
var result = JSON.parse(resp.responseText);
cb(result);
} catch(e) {
cb({ valid: true });
}
},
onerror: function() {
cb({ valid: true });
}
});
}
function withLicenseCheck(fn, btnEl) {
return function() {
if (!isLicenseValid()) {
_0xm('expired');
return;
}
var origText = btnEl ? btnEl.textContent : '';
if (btnEl) { btnEl.disabled = true; btnEl.textContent = '验证中...'; }
var key = GM_getValue('license_key', '');
checkLicenseWithServer(key, function(result) {
if (btnEl) { btnEl.disabled = false; btnEl.textContent = origText; }
if (!result.valid) {
GM_deleteValue('license_expires_at');
GM_deleteValue('license_token');
GM_deleteValue('license_verified_at');
_0xm('error', result.reason);
return;
}
fn();
});
};
}
function createControlPanel(remainingDays) {
GM_addStyle(`
#helper-panel {
position: fixed;
top: 50%;
left: 20px;
transform: translateY(-50%);
background-color: #fff;
border: 1px solid #e5e7eb;
border-radius: 10px;
padding: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 9999;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
min-width: 140px;
}
#helper-panel .hp-title {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #333;
text-align: center;
line-height: 1.4;
}
#helper-panel .hp-status {
margin: 0 0 10px 0;
font-size: 11px;
color: #059669;
text-align: center;
}
#helper-panel .hp-status.expired { color: #dc2626; }
#helper-panel button {
display: block;
width: 100%;
padding: 6px 10px;
margin-top: 6px;
border: none;
border-radius: 6px;
background-color: #007bff;
color: white;
font-size: 12px;
cursor: pointer;
transition: background-color 0.2s;
}
#helper-panel button:hover { background-color: #0056b3; }
#helper-panel button:active { background-color: #004a99; }
#hp-update-notify {
position: fixed;
top: calc(50% - 180px);
left: 20px;
background: linear-gradient(135deg, #6366f1, #8b5cf6);
border-radius: 10px;
padding: 10px 14px;
box-shadow: 0 4px 12px rgba(99,102,241,0.3);
z-index: 10000;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
min-width: 140px;
color: #fff;
display: none;
}
#hp-update-notify .hp-un-title {
margin: 0 0 6px;
font-size: 12px;
font-weight: 600;
text-align: center;
line-height: 1.4;
}
#hp-update-notify .hp-un-versions {
font-size: 11px;
text-align: center;
line-height: 1.6;
opacity: 0.95;
margin-bottom: 8px;
}
#hp-update-notify .hp-un-btn {
display: block;
width: 100%;
padding: 6px 10px;
border: none;
border-radius: 6px;
background-color: #fff;
color: #6366f1;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: background-color 0.2s;
}
#hp-update-notify .hp-un-btn:hover { background-color: #f0f0f0; }
#hp-update-notify .hp-un-close {
position: absolute;
top: 6px;
right: 8px;
background: none;
border: none;
color: rgba(255,255,255,0.6);
font-size: 14px;
cursor: pointer;
padding: 0;
line-height: 1;
}
#hp-update-notify .hp-un-close:hover { color: #fff; }
`);
const panel = document.createElement('div');
panel.id = 'helper-panel';
panel.innerHTML = '考试助手
已激活
剩' + _0xfmt(remainingDays) + '
';
const collectButton = document.createElement('button');
collectButton.innerText = '更新题库';
collectButton.addEventListener('click', withLicenseCheck(runReviewMode, collectButton));
panel.appendChild(collectButton);
const examButton = document.createElement('button');
examButton.innerText = '自动答题';
examButton.addEventListener('click', withLicenseCheck(runExamMode, examButton));
panel.appendChild(examButton);
const modeLabel = document.createElement('label');
modeLabel.textContent = '匹配模式';
modeLabel.style.cssText = 'display:block;font-size:11px;color:#555;margin-top:8px;';
const modeSelect = document.createElement('select');
modeSelect.id = 'answer-match-mode';
modeSelect.style.cssText = 'width:100%;padding:4px;font-size:11px;box-sizing:border-box;';
modeSelect.innerHTML =
'' +
'' +
'';
modeSelect.value = getAnswerMatchMode();
modeSelect.addEventListener('change', function() {
GM_setValue('answer_match_mode', modeSelect.value);
console.log('[考试助手] 已切换题库匹配模式:' + modeSelect.value);
});
panel.appendChild(modeLabel);
panel.appendChild(modeSelect);
const relatedBankLabel = document.createElement('label');
relatedBankLabel.style.cssText = 'display:flex;align-items:center;gap:5px;font-size:11px;color:#555;margin-top:8px;cursor:pointer;';
const relatedBankSwitch = document.createElement('input');
relatedBankSwitch.type = 'checkbox';
relatedBankSwitch.checked = GM_getValue(RELATED_BANK_MATCH_KEY, false);
relatedBankSwitch.addEventListener('change', function() {
GM_setValue(RELATED_BANK_MATCH_KEY, relatedBankSwitch.checked);
console.log('[考试助手] 跨考试题库匹配已' + (relatedBankSwitch.checked ? '开启' : '关闭') + '。');
});
relatedBankLabel.appendChild(relatedBankSwitch);
relatedBankLabel.appendChild(document.createTextNode('匹配相近考试题库'));
panel.appendChild(relatedBankLabel);
const importButton = document.createElement('button');
importButton.innerText = '导入题库';
importButton.addEventListener('click', importQuestionBank);
panel.appendChild(importButton);
const forceviewButton = document.createElement('button');
forceviewButton.innerText = '强制看题';
forceviewButton.addEventListener('click', forcevieExam);
panel.appendChild(forceviewButton);
const licenseButton = document.createElement('button');
licenseButton.innerText = '验证卡密';
licenseButton.addEventListener('click', function() { _0xm('enter'); });
panel.appendChild(licenseButton);
document.body.appendChild(panel);
var updateNotify = document.createElement('div');
updateNotify.id = 'hp-update-notify';
updateNotify.innerHTML =
'' +
'有新版本可用
' +
'' +
'';
document.body.appendChild(updateNotify);
var closeNotify = document.getElementById('hp-un-close');
if (closeNotify) closeNotify.addEventListener('click', function() { updateNotify.style.display = 'none'; });
var updateBtn = document.getElementById('hp-un-btn');
if (updateBtn) updateBtn.addEventListener('click', function() {
window.open('http://38.76.215.191/YOOC-Exam-Helper-Online.user.js', '_blank');
});
checkForUpdate();
checkCertStatus();
console.log("操作面板已注入。");
}
function checkForUpdate() {
var currentVersion = SCRIPT_VERSION;
GM_xmlhttpRequest({
method: 'GET',
url: 'http://38.76.215.191/script/version.json?t=' + Date.now(),
onload: function(resp) {
try {
var data = JSON.parse(resp.responseText);
var latestVersion = data.version;
if (latestVersion && latestVersion !== currentVersion) {
var versionsEl = document.getElementById('hp-un-versions');
if (versionsEl) {
versionsEl.innerHTML = '当前版本 v' + currentVersion + '
最新版本 v' + latestVersion;
}
var notify = document.getElementById('hp-update-notify');
if (notify) notify.style.display = 'block';
console.log('[考试助手] 检测到新版本 v' + latestVersion + ',当前版本 v' + currentVersion);
}
} catch(e) {}
},
onerror: function() {}
});
}
function checkCertStatus() {
window.__certOk = false;
GM_xmlhttpRequest({
method: 'HEAD',
url: 'http://38.76.215.191/YOOC-Exam-Helper-Online.user.js',
timeout: 5000,
onload: function(resp) {
window.__certOk = true;
console.log('[考试助手] SSL 证书已信任');
},
onerror: function() {
window.__certOk = false;
console.log('[考试助手] SSL 证书未信任,点击更新将跳转到安装引导页');
},
ontimeout: function() {
window.__certOk = false;
console.log('[考试助手] SSL 连接超时,证书可能未信任');
}
});
}
function injectExamListStats() {
setTimeout(() => {
var root = document.getElementById('root');
if (!root) { console.log('[助手] 未找到 #root'); return; }
var reactKey = Object.keys(root).find(k => k.startsWith('__reactContainer') || k.startsWith('__reactFiber'));
if (!reactKey) { console.log('[助手] 未找到 React fiber key'); return; }
var exams = [];
function walk(fiber, depth) {
if (!fiber || depth > 80) return;
if (fiber.memoizedProps && fiber.memoizedProps.exam) {
var exam = fiber.memoizedProps.exam;
if (!exams.find(function(e) { return e.examId === exam.examId; })) {
exams.push(exam);
}
}
if (fiber.child) walk(fiber.child, depth + 1);
if (fiber.sibling) walk(fiber.sibling, depth + 1);
}
walk(root[reactKey], 0);
console.log('[助手] 找到考试数量:', exams.length);
exams.forEach(function(exam) {
rememberExamName(exam.examId, exam.name, getCurrentGroupId());
fetchQuestionCount(exam);
});
// DOM 方式补全 fiber 遗漏的考试
setTimeout(function() {
injectExamListStatsByDOM();
}, 1000);
}, 2000);
}
function injectExamListStatsByDOM() {
var articles = document.querySelectorAll('article');
articles.forEach(function(article) {
if (article.querySelector('.exam-helper-stats')) return;
var h3 = article.querySelector('h3');
if (!h3) return;
var name = h3.innerText.trim();
if (!name) return;
// 从链接 href 或 innerHTML 中提取 examId
var examId = null;
var links = article.querySelectorAll('a[href*="/exam/"]');
for (var i = 0; i < links.length; i++) {
var m = links[i].href.match(/exam\/(\d+)/);
if (m) { examId = m[1]; break; }
}
if (!examId) {
var examIdMatch = article.innerHTML.match(/exam\/(\d+)/);
if (examIdMatch) examId = examIdMatch[1];
}
if (!examId) return;
rememberExamName(examId, name, getCurrentGroupId());
GM_xmlhttpRequest({
method: "GET",
url: `${SERVER_BASE}/question-bank/count?examId=${examId}`,
onload: function(response) {
var count = 0;
if (response.status >= 200 && response.status < 300) {
try { count = JSON.parse(response.responseText).count || 0; } catch(e) {}
}
var statsEl = document.createElement('span');
statsEl.className = 'exam-helper-stats';
statsEl.style.cssText = 'font-size:12px;color:#4338CA;margin-left:10px;font-weight:normal;';
statsEl.innerHTML = `(题库 ${count} 题)`;
h3.parentElement.appendChild(statsEl);
},
onerror: function() {}
});
});
}
function fetchQuestionCount(exam) {
GM_xmlhttpRequest({
method: "GET",
url: `${SERVER_BASE}/question-bank/count?examId=${exam.examId}`,
onload: function(response) {
let count = 0;
if (response.status >= 200 && response.status < 300) {
try {
const result = JSON.parse(response.responseText);
count = result.count || 0;
} catch(e) {}
}
injectStatsToCard(exam, count);
},
onerror: function() {
injectStatsToCard(exam, 0);
}
});
}
function injectStatsToCard(exam, serverCount) {
const articles = document.querySelectorAll('article');
for (const article of articles) {
if (article.querySelector('.exam-helper-stats')) continue;
const h3 = article.querySelector('h3');
if (h3 && h3.innerText.includes(exam.name)) {
const statsEl = document.createElement('span');
statsEl.className = 'exam-helper-stats';
statsEl.style.cssText = 'font-size:12px;color:#4338CA;margin-left:10px;font-weight:normal;';
statsEl.innerHTML = `(题库 ${serverCount} 题)`;
h3.parentElement.appendChild(statsEl);
break;
}
}
}
// 兼容答案接口的嵌套数组、subjects 字段与直接题目数组三种响应形态。
function extractAnswerSubjects(payload) {
if (!payload) return [];
if (Array.isArray(payload)) {
if (payload.every(function(item) { return item && item.subjectId != null; })) return payload;
return payload.reduce(function(all, item) {
return all.concat(extractAnswerSubjects(item));
}, []);
}
if (Array.isArray(payload.subjects)) return extractAnswerSubjects(payload.subjects);
if (payload.data != null) return extractAnswerSubjects(payload.data);
return payload.subjectId != null ? [payload] : [];
}
function autoCollectOnReview() {
var currentUrl = window.location.href;
var reviewMatch = currentUrl.match(/group\/(\d+)\/exam\/(\d+)\/review\/(\d+)/);
if (!reviewMatch) return;
var examId = reviewMatch[2];
var examuserId = reviewMatch[3];
if (!userToken || !examuserId) return;
console.log('[考试助手] 回顾页检测到,自动收集题库...');
GM_xmlhttpRequest({
method: "GET",
url: `https://exambackend.yooc.me/api/exam/answer/get?examuserId=${examuserId}&token=${userToken}&yibanId=${yibanId}`,
headers: { "Cache-Control": "no-cache", "Pragma": "no-cache" },
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
var data = JSON.parse(response.responseText);
handleApiResponseQuiet(data, examId);
}
}
});
}
function handleApiResponseQuiet(data, examId) {
var oldQuestionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
if (data && data.result === false) return;
if (!oldQuestionBank[examId]) oldQuestionBank[examId] = {};
var question_count = 0;
var subjects = extractAnswerSubjects(data);
if (subjects.length === 0) {
console.warn('[考试助手] 接口响应中没有可用题目 subject。', data);
return;
}
for (var i = 0; i < subjects.length; i++) {
var sub = subjects[i];
var subjectId = String(sub.subjectId);
if (!oldQuestionBank[examId][subjectId]) question_count++;
oldQuestionBank[examId][subjectId] = makeStoredQuestionRecord(examId, subjectId, sub);
}
localStorage.setItem(QUESTION_BANK_STORAGE_KEY, JSON.stringify(oldQuestionBank));
var totalCount = Object.keys(oldQuestionBank[examId]).length;
console.log('[考试助手] 自动收集完成,新增/更新 ' + question_count + ' 题。当前考试题库共 ' + totalCount + ' 题。');
uploadQuestionBank(examId);
var toast = document.createElement('div');
toast.textContent = '题库已自动更新 +' + question_count + ' 题';
toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#059669;color:#fff;padding:10px 20px;border-radius:8px;z-index:99999;font-size:14px;box-shadow:0 4px 12px rgba(0,0,0,0.2);transition:opacity 0.5s;';
document.body.appendChild(toast);
setTimeout(function() { toast.style.opacity = '0'; }, 2000);
setTimeout(function() { toast.remove(); }, 2500);
}
function forcevieExam(){
const currentUrl = window.location.href;
const reviewMatch = currentUrl.match(/group\/(\d+)\/exam\/(\d+)\/review\/(\d+)/);
if (reviewMatch) {
alert("当前已在回顾页,可直接点击「更新题库」收集答案。");
return;
}
const resultMatch = currentUrl.match(/group\/(\d+)\/exam\/(\d+)/);
if (!resultMatch) {
alert("请先打开一场考试的结果页或回顾页,再点击「强制看题」。");
return;
}
const groupId = resultMatch[1];
const examId = resultMatch[2];
console.log("考试ID:", examId);
GM_xmlhttpRequest({
method: "GET",
url: `https://exambackend.yooc.me/api/exam/result/get?userId=${userId}&token=${userToken}&yibanId=${yibanId}&examId=${examId}`,
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const responseData = JSON.parse(response.responseText);
if(responseData.result){
const examuserId = responseData.data.examuserId;
location.href = `https://exam.yooc.me/group/${groupId}/exam/${examId}/review/${examuserId}`
}
else{
alert("未能成功获取 examuserId,可能是还未参加过这场考试。");
}
}
else{
alert("接口请求失败: " + response.status);
console.error("接口请求失败:", response.status, response.statusText, response.responseText);
}
}
})
}
function importQuestionBank() {
importJson(function(error, data) {
if (error) {
console.error("导入题库失败:", error);
alert("导入失败: " + error.message);
return;
}
const oldQuestionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
const mergedQuestionBank = _.merge({}, oldQuestionBank, data);
localStorage.setItem(QUESTION_BANK_STORAGE_KEY, JSON.stringify(mergedQuestionBank));
const message = `题库导入成功!\n导入题库数: ${Object.keys(data).length}\n题库总数: ${Object.keys(mergedQuestionBank).length}`;
console.log(message.replace(/\n/g, ' '));
alert(message);
});
}
const SERVER_BASE = 'http://38.76.215.191/script-api';
function getExamNameForUpload(examId) {
const catalog = getStoredExamCatalog();
const item = catalog[String(examId)];
return item && item.name ? String(item.name).trim() : '';
}
function uploadQuestionBank(examId) {
const questionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
const examData = questionBank[examId];
if (!examData || Object.keys(examData).length === 0) {
console.log("该考试题库为空,跳过上传。");
return;
}
GM_xmlhttpRequest({
method: "POST",
url: `${SERVER_BASE}/question-bank/upload`,
headers: { "Content-Type": "application/json" },
data: JSON.stringify({
examId: examId,
examName: getExamNameForUpload(examId),
questionBank: examData
}),
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const result = JSON.parse(response.responseText);
console.log(`题库上传成功:新增 ${result.added || 0} 题,更新 ${result.updated || 0} 题,当前共 ${result.count || 0} 题。`);
} else {
console.error("题库上传失败:", response.status, response.responseText);
}
},
onerror: function(error) {
console.error("题库上传请求出错:", error);
}
});
}
function downloadQuestionBank(examId, callback) {
GM_xmlhttpRequest({
method: "GET",
url: `${SERVER_BASE}/question-bank/download?examId=${examId}`,
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const result = JSON.parse(response.responseText);
if (result.success && result.questionBank) {
const oldQuestionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
if (!oldQuestionBank[examId]) oldQuestionBank[examId] = {};
_.merge(oldQuestionBank[examId], result.questionBank);
localStorage.setItem(QUESTION_BANK_STORAGE_KEY, JSON.stringify(oldQuestionBank));
console.log(`题库下载成功,已合并。服务器题目数: ${Object.keys(result.questionBank).length},本地该考试题目数: ${Object.keys(oldQuestionBank[examId]).length}`);
} else {
console.log("服务器未找到该考试的题库,将使用本地题库。");
}
} else if (response.status === 404) {
console.log("服务器未找到该考试的题库,将使用本地题库。");
} else {
console.error("题库下载失败:", response.status, response.responseText);
}
if (callback) callback();
},
onerror: function(error) {
console.error("题库下载请求出错:", error);
if (callback) callback();
}
});
}
function importJson(callback) {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.style.display = 'none';
document.body.appendChild(input);
input.addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) {
callback(new Error('未选择文件'));
return;
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
callback(null, data);
} catch (error) {
callback(error);
}
};
reader.onerror = function() {
callback(new Error('文件读取失败'));
};
reader.readAsText(file);
});
input.click();
document.body.removeChild(input);
}
function runExamMode() {
try {
const currentUrl = window.location.href;
if (currentUrl.includes('/review/')) {
runReviewMode();
return;
}
const examIdMatch = currentUrl.match(/exam\/(\d+)/);
const examId = examIdMatch ? examIdMatch[1] : null;
console.log("考试ID:", examId);
if (!examId) {
alert("未能从URL中解析出 examId");
return;
}
console.log("正在从服务器下载题库...");
const downloadBanks = GM_getValue(RELATED_BANK_MATCH_KEY, false) ? downloadRelatedQuestionBanks : function(id, callback) {
downloadQuestionBank(id, callback);
};
downloadBanks(examId, function() {
console.log("题库下载完成,开始自动答题...");
GM_xmlhttpRequest({
method: "GET",
url: `https://exambackend.yooc.me/api/exam/setting/get?examId=${examId}&userId=${userId}&token=${userToken}&yibanId=${yibanId}`,
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const responseData = JSON.parse(response.responseText);
if(responseData.result){
const examuserId = responseData.data.examuserId;
if (Object.hasOwn(localStorage, `exam-paper-${examuserId}`)){
handleApiResponse2write(JSON.parse(localStorage.getItem(`exam-paper-${examuserId}`)).value.paper);
}
else{
GM_xmlhttpRequest({
method: "GET",
url: `https://exambackend.yooc.me/api/exam/paper/get?examuserId=${examuserId}&token=${userToken}&yibanId=${yibanId}`,
headers: { "Cache-Control": "no-cache", "Pragma": "no-cache" },
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const responseData = JSON.parse(response.responseText);
if (responseData.result){
handleApiResponse2write(responseData.data);
} else {
alert("题目获取失败!");
}
} else {
console.error("接口请求失败:", response.status);
}
},
onerror: function(error) { console.error(error); }
});
}
} else {
alert("获取 examuserId 失败");
}
} else {
console.error("接口请求失败:", response.status);
}
},
onerror: function(error) { console.error(error); }
});
});
} catch (error) {
console.error("自动答题脚本出错:", error);
}
}
function runReviewMode() {
try {
const currentUrl = window.location.href;
const examIdMatch = currentUrl.match(/exam\/(\d+)/);
const examId = examIdMatch ? examIdMatch[1] : null;
console.log("考试ID:", examId);
if (!examId) {
console.error("未能从URL中解析出 examId,无法执行操作。");
alert("未能从URL中解析出 examId,无法执行操作。");
return;
}
const examuserIdMatch = currentUrl.match(/review\/(\d+)$/);
const examuserId = examuserIdMatch ? examuserIdMatch[1] : null;
console.log("考试用户ID:", examuserId);
const apiUrl = `https://exambackend.yooc.me/api/exam/answer/get?examuserId=${examuserId}&token=${userToken}&yibanId=${yibanId}`;
if (!apiUrl || !examId) {
console.error("未能构造有效的接口URL,请检查脚本。");
return;
}
console.log("正在请求接口:", apiUrl);
GM_xmlhttpRequest({
method: "GET",
url: apiUrl,
headers: {
"Cache-Control": "no-cache",
"Pragma": "no-cache"
},
onload: function(response) {
if (response.status >= 200 && response.status < 300) {
const responseData = JSON.parse(response.responseText);
handleApiResponse(responseData, examId);
} else {
console.error("接口请求失败:", response.status, response.statusText, response.responseText);
}
},
onerror: function(error) {
console.error("接口请求发生错误:", error);
}
});
} catch (error) {
console.error("收集题库脚本出错:", error);
}
}
function normText(t){
var ta = document.createElement('textarea');
ta.innerHTML = String(t || '');
return ta.value.replace(/ /g,' ').replace(/\t/g,' ').replace(/\s+/g,' ').trim();
}
function normOptionText(t){
return normText(t)
.replace(/^[A-ZA-Z]\s*[..、::]\s*/, '')
.replace(/^[((]\s*[A-ZA-Z]\s*[))]\s*/i, '')
.trim();
}
function cleanOptions(options) {
if (!Array.isArray(options)) return [];
var result = [];
for (var idx = 0; idx < options.length; idx++) {
var opt = options[idx];
var text = typeof opt === 'string' ? opt : (Array.isArray(opt) ? opt[0] : String(opt));
var ta = document.createElement('textarea');
ta.innerHTML = text;
text = ta.value;
var parts = text.split(/\[x\]/);
for (var pi = 0; pi < parts.length; pi++) {
var cleaned = parts[pi].replace(/\t/g, ' ').replace(/\s+/g, ' ').trim();
if (cleaned) result.push([cleaned]);
}
}
return result;
}
// 题库匹配模式:id、text 或 hybrid(ID 优先,文本兜底)。
function getAnswerMatchMode() {
var mode = GM_getValue('answer_match_mode', 'hybrid');
return ['id', 'text', 'hybrid'].indexOf(mode) >= 0 ? mode : 'hybrid';
}
function normalizeMatchText(text) {
var holder = document.createElement('div');
holder.innerHTML = String(text || '');
var value = holder.textContent || holder.innerText || '';
try { value = value.normalize('NFKC'); } catch (e) {}
return value
.replace(/\u00a0/g, ' ')
.replace(/\[x\]/gi, ' {{blank}} ')
.replace(/_{2,}|_{2,}/g, ' {{blank}} ')
.replace(/\s+/g, ' ')
.trim()
.toLowerCase();
}
function normalizeTitleForMatch(text) {
return normalizeMatchText(text)
.replace(/^\s*[一二三四五六七八九十]+\s*[、..)]\s*/, '')
.replace(/^\s*\d+\s*[、..)]\s*/, '')
.replace(/\[\s*\d+(?:\.\d+)?\s*分\s*\]/g, '')
.replace(/\{\{\s*blank(?::\d+)?\s*\}\}/gi, '{{blank}}')
.replace(/\s+/g, ' ')
.trim();
}
function normalizeOptionForMatch(text) {
return normalizeMatchText(text)
.replace(/^[a-zA-Z]\s*[..、::]\s*/, '')
.replace(/^[((]\s*[a-zA-Z]\s*[))]\s*/i, '')
.trim();
}
function getOptionSignature(optionTexts) {
return (optionTexts || []).map(normalizeOptionForMatch).filter(Boolean).sort().join('\u001f');
}
function makeQuestionRecord(examId, subjectId, raw) {
var options = cleanOptions(raw && raw.option).map(function(option) {
var text = Array.isArray(option) ? option[0] : option;
return { textRaw: String(text || ''), textKey: normalizeOptionForMatch(text) };
});
var titleRaw = raw && (raw.title || raw.titleRaw) ? (raw.title || raw.titleRaw) : '';
var titleKey = normalizeTitleForMatch(titleRaw);
var answer = raw && Array.isArray(raw.answer) ? raw.answer : [];
var storedIndices = raw && Array.isArray(raw.answerIndices) ? raw.answerIndices : [];
var storedOptionTexts = raw && Array.isArray(raw.optionTexts) ? raw.optionTexts : [];
var optionTexts = [];
var answerIndices = [];
function resolveAnswerIndex(value) {
var index = Number.parseInt(value, 10);
if (!Number.isInteger(index) && typeof value === 'string') {
var label = value.trim().toUpperCase();
if (/^[A-Z]$/.test(label)) index = label.charCodeAt(0) - 65;
if (!Number.isInteger(index)) {
var textKey = normalizeOptionForMatch(value);
index = options.findIndex(function(option) { return option.textKey === textKey; });
}
}
return Number.isInteger(index) && options[index] ? index : -1;
}
if (answer.length > 0) {
answer.forEach(function(value) {
var index = resolveAnswerIndex(value);
if (index >= 0) {
optionTexts.push(options[index].textKey);
answerIndices.push(index);
}
});
} else {
storedIndices.forEach(function(value) {
var index = resolveAnswerIndex(value);
if (index >= 0) answerIndices.push(index);
});
optionTexts = storedOptionTexts.map(normalizeOptionForMatch).filter(Boolean);
}
if (optionTexts.length === 0 && answerIndices.length > 0) {
optionTexts = answerIndices.map(function(index) { return options[index].textKey; });
}
return {
examId: String(examId),
subjectId: String(subjectId),
titleRaw: String(titleRaw),
titleKey: titleKey,
titleLooseKey: titleKey.replace(/\{\{blank\}\}/g, ' ').replace(/\s+/g, ' ').trim(),
options: options,
optionTexts: optionTexts,
answerTexts: optionTexts.slice(),
answerIndices: answerIndices,
blankValues: answer.length > 0 ? answer.map(function(value) { return String(value == null ? '' : value); }) :
(raw && Array.isArray(raw.blankValues) ? raw.blankValues.map(function(value) { return String(value == null ? '' : value); }) : []),
optionSignature: getOptionSignature(options.map(function(option) { return option.textKey; })),
blankCount: (titleKey.match(/\{\{blank\}\}/g) || []).length,
kind: options.length > 0 ? 'choice' : 'blank'
};
}
function decodeApiAnswer(value) {
if (Array.isArray(value)) return value;
if (value && typeof value === 'object') return value;
if (value == null || value === '') return [];
try {
return JSON.parse(decrypt(String(value), yibanId));
} catch (decryptError) {
try {
return JSON.parse(String(value));
} catch (parseError) {
console.warn('[考试助手] 题目答案解密或解析失败,保留原始值。', decryptError);
return [String(value)];
}
}
}
// 将接口返回的原始题目转换为同时包含 ID、文本和选项索引的题库记录。
function makeStoredQuestionRecord(examId, subjectId, sub) {
var rawRecord = {
title: sub && sub.title && sub.title.length ? sub.title[0] : (sub && sub.title) || '',
option: cleanOptions(sub && sub.option),
answer: decodeApiAnswer(sub && sub.answer),
type: sub && sub.type ? String(sub.type) : '',
points: sub && sub.points != null ? String(sub.points) : '',
inputs: sub && sub.inputs != null ? String(sub.inputs) : ''
};
return Object.assign(rawRecord, makeQuestionRecord(examId, subjectId, rawRecord));
}
function addIndexValue(index, key, value) {
if (!key) return;
if (!index.has(key)) index.set(key, []);
index.get(key).push(value);
}
function buildQuestionTextIndexes(questionBank) {
var composite = new Map();
var title = new Map();
Object.keys(questionBank || {}).forEach(function(examId) {
var examBank = questionBank[examId] || {};
Object.keys(examBank).forEach(function(subjectId) {
var record = makeQuestionRecord(examId, subjectId, examBank[subjectId]);
if (!record.titleKey) return;
var key = record.kind + '|' + record.titleKey + '|' + record.optionSignature + '|' + record.blankCount;
addIndexValue(composite, key, record);
addIndexValue(title, record.kind + '|' + record.titleKey, record);
addIndexValue(title, record.kind + '|loose|' + record.titleLooseKey, record);
});
});
return { composite: composite, title: title };
}
function readCurrentQuestionSnapshot() {
var main = document.getElementsByTagName('main')[0];
var h3 = main ? main.getElementsByTagName('h3')[0] : null;
if (!h3) return null;
var container = h3.parentElement || h3;
var clone = h3.cloneNode(true);
var cloneInputs = clone.querySelectorAll('input, textarea');
for (var ci = 0; ci < cloneInputs.length; ci++) {
cloneInputs[ci].replaceWith(document.createTextNode(' {{blank}} '));
}
var optionList = container.querySelector('ul');
var optionItems = optionList ? Array.prototype.slice.call(optionList.children).filter(function(item) {
return item.tagName && item.tagName.toLowerCase() === 'li';
}) : [];
var inputs = Array.prototype.slice.call(container.querySelectorAll('input.exam-input, input[type=text], input:not([type]), textarea'));
var optionTexts = optionItems.map(function(item) {
var textNode = item.querySelector('.flex-auto') || item.lastElementChild || item;
return normalizeOptionForMatch(textNode.textContent || item.textContent || '');
});
var heading = main.querySelector('h2');
var headingText = heading ? heading.textContent || '' : '';
var kind = inputs.length > 0 && optionItems.length === 0 ? 'blank' : 'choice';
return {
container: container,
h3: h3,
optionItems: optionItems,
optionTexts: optionTexts,
inputs: inputs,
kind: kind,
multiple: /多项|多选/.test(headingText),
titleKey: normalizeTitleForMatch(clone.textContent || ''),
titleLooseKey: normalizeTitleForMatch(clone.textContent || '').replace(/\{\{blank\}\}/g, ' ').replace(/\s+/g, ' ').trim(),
optionSignature: getOptionSignature(optionTexts),
blankCount: inputs.length
};
}
function findQuestionRecord(mode, examId, subjectId, snapshot, questionBank, indexes) {
if (!snapshot) return null;
if (mode !== 'text' && questionBank[examId] && Object.hasOwn(questionBank[examId], subjectId)) {
return { source: 'id', record: makeQuestionRecord(examId, subjectId, questionBank[examId][subjectId]) };
}
if (mode === 'id') return null;
var key = snapshot.kind + '|' + snapshot.titleKey + '|' + snapshot.optionSignature + '|' + snapshot.blankCount;
var candidates = indexes.composite.get(key) || [];
if (candidates.length === 0) {
candidates = indexes.title.get(snapshot.kind + '|' + snapshot.titleKey) || [];
}
if (candidates.length === 0) {
candidates = indexes.title.get(snapshot.kind + '|loose|' + snapshot.titleLooseKey) || [];
}
if (candidates.length > 1) {
var exactSignatureCandidates = candidates.filter(function(item) {
return item.optionSignature === snapshot.optionSignature;
});
if (exactSignatureCandidates.length > 0) {
candidates = exactSignatureCandidates;
} else if (snapshot.kind === 'choice') {
console.warn('[考试助手] 同题干但选项不同,拒绝冒险匹配。');
return null;
}
var currentExamId = String(examId);
candidates = candidates.slice().sort(function(a, b) {
function score(item) {
var value = 0;
if (item.examId === currentExamId) value += 8;
if (item.optionSignature === snapshot.optionSignature) value += 4;
if (item.blankCount === snapshot.blankCount) value += 2;
return value;
}
return score(b) - score(a);
});
}
if (candidates.length > 0) {
if (candidates.length > 1) console.warn('[考试助手] 文本匹配存在多个候选,已按当前考试、选项和空格数排序。');
var record = candidates[0];
return { source: record.examId === String(examId) ? 'text-current-exam' : 'text-cross-exam', record: record };
}
return null;
}
function handleApiResponse2write(data) {
const questionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
const examIdMatch = window.location.href.match(/exam\/(\d+)/);
const examId = examIdMatch ? examIdMatch[1] : null;
const matchMode = getAnswerMatchMode();
const textIndexes = buildQuestionTextIndexes(questionBank);
function findNavButton(name) {
var buttons = Array.prototype.slice.call(document.querySelectorAll('button'));
return buttons.find(function(button) { return (button.textContent || '').trim() === name; }) || null;
}
function getCurrentProgress() {
var items = Array.prototype.slice.call(document.querySelectorAll('li'));
var progress = items.find(function(item) { return /^\s*\d+\s*\/\s*\d+\s*$/.test(item.textContent || ''); });
var match = progress && (progress.textContent || '').match(/(\d+)\s*\/\s*(\d+)/);
return match ? { current: Number(match[1]), total: Number(match[2]) } : null;
}
var progress = getCurrentProgress();
var previous = findNavButton('上一题');
if (!progress || !previous) {
console.error('[考试助手] 未找到可靠的题目进度或上一题按钮,停止自动答题。');
return;
}
for (var back = 1; back < progress.current; back++) previous.click();
function clickRandomOption(optionItems) {
if (!optionItems || optionItems.length === 0) {
console.warn('当前题目未找到可点击选项,跳过随机选择。');
return false;
}
optionItems[Math.floor(Math.random() * optionItems.length)].click();
console.log('[随机答题] 未匹配到题库答案,已随机选择一个选项。');
return true;
}
function setInputValue(input, value) {
var proto = input instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
var setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
setter.call(input, value == null ? '' : String(value));
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
function applyBlankAnswer(snapshot, record) {
var answers = record.blankValues || [];
if (answers.length !== snapshot.inputs.length) {
console.warn('[填空题] 题库答案数量与当前空格数量不一致:', answers.length, snapshot.inputs.length);
return;
}
snapshot.inputs.forEach(function(input, index) {
if (index < answers.length) setInputValue(input, answers[index]);
});
console.log('[填空题] 已按空格顺序填写:', answers.slice(0, snapshot.inputs.length));
}
function applyChoiceAnswer(snapshot, record) {
var desired = new Set();
(record.optionTexts || []).forEach(function(text, answerIndex) {
var targetIndex = snapshot.optionTexts.indexOf(text);
if (targetIndex < 0 && record.answerIndices && Number.isInteger(record.answerIndices[answerIndex])) {
targetIndex = record.answerIndices[answerIndex];
}
if (targetIndex >= 0 && targetIndex < snapshot.optionItems.length) desired.add(targetIndex);
});
if (desired.size === 0) return false;
if (snapshot.multiple) {
snapshot.optionItems.forEach(function(item, index) {
if (item.classList.contains('_c') && !desired.has(index)) item.click();
});
snapshot.optionItems.forEach(function(item, index) {
if (desired.has(index) && !item.classList.contains('_c')) item.click();
});
} else {
var target = Array.from(desired)[0];
if (target != null && !snapshot.optionItems[target].classList.contains('_c')) snapshot.optionItems[target].click();
}
console.log('[选择题] 已按' + (record.source || '题库') + '匹配答案。');
return true;
}
for (let i = 0; i < data.length; i++) {
const sectionId = data[i].sectionId;
const idExamId = examId && questionBank[examId] ? examId : String(sectionId);
for (let j = 0; j < data[i].subjects.length; j++) {
const subjectId = data[i].subjects[j].subjectId.toString();
const snapshot = readCurrentQuestionSnapshot();
if (!snapshot) {
console.warn('[考试助手] 当前题目 DOM 不存在,跳过。');
} else {
var matched = findQuestionRecord(matchMode, idExamId, subjectId, snapshot, questionBank, textIndexes);
if (matched && matched.record.kind === 'blank' && snapshot.kind === 'blank') {
matched.record.source = matched.source;
applyBlankAnswer(snapshot, matched.record);
} else if (matched && matched.record.kind === 'choice' && snapshot.kind === 'choice') {
matched.record.source = matched.source;
if (!applyChoiceAnswer(snapshot, matched.record)) clickRandomOption(snapshot.optionItems);
} else if (snapshot.kind === 'choice') {
clickRandomOption(snapshot.optionItems);
} else {
console.warn('[填空题] 未匹配到答案,保留空白。');
}
}
var next = findNavButton('下一题');
if (next) next.click();
else console.warn('[考试助手] 未找到下一题按钮。');
}
}
}
function handleApiResponse(data, examId) {
const oldQuestionBank = JSON.parse(localStorage.getItem(QUESTION_BANK_STORAGE_KEY) || '{}');
if (data && data.result === false) {
console.log(`题库更新失败!接口返回值异常。`);
alert(`题库更新失败!接口返回值异常。`);
return;
}
if (!oldQuestionBank[examId]) oldQuestionBank[examId] = {};
let question_count = 0;
const subjects = extractAnswerSubjects(data);
if (subjects.length === 0) {
console.log('题库更新失败!接口响应中没有题目。');
alert('题库更新失败!接口响应中没有题目。');
return;
}
for (let i = 0; i < subjects.length; i++) {
const sub = subjects[i];
const subjectId = String(sub.subjectId);
if (!oldQuestionBank[examId][subjectId]) question_count++;
oldQuestionBank[examId][subjectId] = makeStoredQuestionRecord(examId, subjectId, sub);
}
localStorage.setItem(QUESTION_BANK_STORAGE_KEY, JSON.stringify(oldQuestionBank));
const totalCount = Object.keys(oldQuestionBank[examId]).length;
console.log(`题库更新成功!本次新增/更新了 ${question_count} 道题。当前考试题库共 ${totalCount} 题。`);
if (question_count > 0) {
alert(`题库更新成功,新增/更新 ${question_count} 题!`);
} else {
alert("题库已是最新,无需更新。");
}
uploadQuestionBank(examId);
}
function decrypt(_0x1, _0x2) {
var _0x3 = [121,111,111,99,64,97,100,109,105,110];
var _0x4 = [52,50,101,48,55,100,50,102,55,49,57,57,99,51,53,100];
var _0x5 = function(_0x6) {
var _0x7 = '';
for (var _0x8 = 0; _0x8 < _0x6.length; _0x8++) {
_0x7 += String.fromCharCode(_0x6[_0x8] ^ (_0x8 & 3));
}
return _0x7;
};
var _0x9 = _0x3.map(function(c){return String.fromCharCode(c)}).join('') + _0x2;
var _0xa = CryptoJS.MD5(_0x9).toString(CryptoJS.enc.Hex).substr(8, 16);
var _0xb = _0x4.map(function(c){return String.fromCharCode(c)}).join('');
var _0xc = CryptoJS.AES.decrypt(_0x1, CryptoJS.enc.Utf8.parse(_0xa), {
iv: CryptoJS.enc.Utf8.parse(_0xb),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return _0xc.toString(CryptoJS.enc.Utf8);
}
} // end initWithLicense
_0xrun(initWithLicense);
})();