// ==UserScript==
// @name 学习通学习助手(分享框架版)
// @version 1.2.0
// @author BZM (框架分享版)
// @license Apache
// @description 学习通助手(分享框架版):学习通刷课+做题;任意网站通用做题(自动识别单选/多选/填空/简答并作答)。3个AI接口依次解题,程序题自动写+审,AI全失败自动盲选防卡题。密钥由使用者自己在面板配置,脚本不内置任何密钥。
// @match *://*.chaoxing.com/*
// @match *://*/*
// @run-at document-end
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @grant GM_info
// @grant GM_getResourceText
// @grant GM_openInTab
// @icon http://pan-yz.chaoxing.com/favicon.ico
// @original-script https://scriptcat.org/zh-CN/script-show-page/5717
// @require https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js
// @require https://cdn.bootcdn.net/ajax/libs/limonte-sweetalert2/11.1.0/sweetalert2.all.min.js
// @resource Table https://pkpkq.n1t.cn/font-decrypt/Table.json
// @require https://pkpkq.n1t.cn/font-decrypt/TyprMd5.js
// @connect pkpkq.n1t.cn
// @connect *
// @tag 自动答题
// @tag 人工问答
// @tag 开源框架
// ==/UserScript==
/********************************* 反检测层 ****************************************/
(function() {
'use strict';
try {
Object.defineProperty(navigator, 'webdriver', { get: function() { return undefined; }, configurable: true });
} catch(e) {}
try {
if (!window.chrome) window.chrome = {};
if (!window.chrome.runtime) window.chrome.runtime = {};
} catch(e) {}
try {
Object.defineProperty(document, 'visibilityState', { get: function() { return 'visible'; }, configurable: true });
Object.defineProperty(document, 'hidden', { get: function() { return false; }, configurable: true });
document.hasFocus = function() { return true; };
document.addEventListener('visibilitychange', function(e) { e.stopImmediatePropagation(); }, true);
} catch(e) {}
try {
window.onblur = null;
window.onfocus = null;
['blur', 'focus', 'pagehide', 'pageshow'].forEach(function(evt) {
window.addEventListener(evt, function(e) { e.stopImmediatePropagation(); }, true);
});
} catch(e) {}
var _OrigMO = window.MutationObserver;
if (_OrigMO) {
window.MutationObserver = function(callback) {
var wrappedCallback = function(mutations, observer) {
var delay = 50 + Math.random() * 150;
setTimeout(function() { callback(mutations, observer); }, delay);
};
return new _OrigMO(wrappedCallback);
};
window.MutationObserver.prototype = _OrigMO.prototype;
}
try {
var _origQuery = navigator.permissions && navigator.permissions.query;
if (_origQuery) {
navigator.permissions.query = function(desc) {
if (desc && desc.name === 'notifications') {
return Promise.resolve({ state: 'prompt', onchange: null });
}
return _origQuery.call(navigator.permissions, desc);
};
}
} catch(e) {}
console.log('[学习通助手] 反检测层已加载');
})();
/********************************* 配置管理器 ****************************************/
var SettingsManager = {
_defaults: {
showBox: 1,
showMaskImg: 1,
taskOnly: 0,
handleVideo: 1,
handleAudio: 1,
videoRate: 1,
auto2x: 0,
videoMode: 'simulate',
showProgressBar: 1,
reviewMode: 0,
handleQuiz: 1,
handleVideoQuiz: 1,
answerInterval: 5000,
autoSubmit: 0,
forceSubmit: 0,
decryptFont: 1,
autoNextExam: 1,
examNextDelay: 1,
insertAnswer: 1,
autoSearch: 1,
autoLogin: 0,
loginPhone: '',
loginPassword: ''
},
get: function(key) {
var gv = GM_getValue('setting_' + key, null);
if (gv !== null && gv !== undefined) { this._defaults[key] = gv; return gv; }
var stored = localStorage.getItem('setting_' + key);
if (stored !== null) {
if (stored === 'true') return true;
if (stored === 'false') return false;
if (!isNaN(parseFloat(stored)) && isFinite(stored)) return parseFloat(stored);
return stored;
}
return this._defaults[key];
},
set: function(key, value) {
localStorage.setItem('setting_' + key, value);
GM_setValue('setting_' + key, value);
this._defaults[key] = value;
return value;
},
load: function() {
for (var key in this._defaults) {
var v = this.get(key);
if (v !== undefined) this._defaults[key] = v;
}
if (this._defaults.videoRate > 8) this._defaults.videoRate = 8;
return this._defaults;
},
saveVideoMode: function(mode) { this.set('videoMode', mode); GM_setValue('videoMode', mode); },
saveVideoRate: function(rate) { if (rate > 8) rate = 8; this.set('videoRate', rate); GM_setValue('videoRate', rate); },
saveProgressBar: function(show) { this.set('showProgressBar', show ? 1 : 0); GM_setValue('showProgressBar', show ? 1 : 0); }
};
var CONFIG = SettingsManager.load();
if (CONFIG.videoRate > 8) CONFIG.videoRate = 8;
function updateConfig(key, value) {
var oldValue = CONFIG[key];
CONFIG[key] = SettingsManager.set(key, value);
if (key === 'videoRate' && CONFIG.videoRate > 8) { CONFIG.videoRate = 8; SettingsManager.set('videoRate', 8); }
log('⚙️ 配置已更新: ' + key + ' = ' + value + (oldValue !== value ? ' (已生效)' : ''), 'blue');
}
function getRandomInterval() {
var base = CONFIG.answerInterval || 5000;
return Math.floor(base * (0.8 + Math.random() * 0.7));
}
/********************************* 多选题智能匹配核心 ****************************************/
function matchMultiChoiceIndices(optsText, answer) {
var ansArr = splitAnswer(answer);
var normalizedOpts = optsText.map(function(opt) { return normalizeForCompare(opt); });
var normalizedAnsArr = ansArr.map(function(a) { return normalizeForCompare(a); }).filter(function(a) { return a !== ''; });
var hitIdx = [];
normalizedOpts.forEach(function(opt, i) {
for (var j = 0; j < normalizedAnsArr.length; j++) {
if (opt === normalizedAnsArr[j] && hitIdx.indexOf(i) === -1) { hitIdx.push(i); break; }
}
});
if (hitIdx.length < normalizedAnsArr.length) {
normalizedOpts.forEach(function(opt, i) {
if (hitIdx.indexOf(i) !== -1) return;
for (var j = 0; j < normalizedAnsArr.length; j++) {
var na = normalizedAnsArr[j];
if (na === '') continue;
if (opt.indexOf(na) !== -1 && (opt.length - na.length) <= 1) { hitIdx.push(i); break; }
if (na.indexOf(opt) !== -1 && (na.length - opt.length) <= 1) { hitIdx.push(i); break; }
}
});
}
if (hitIdx.length > normalizedAnsArr.length) hitIdx = hitIdx.slice(0, normalizedAnsArr.length);
return hitIdx;
}
/********************************* 题型映射扩展 ****************************************/
var QuestionTypeMap = {
0: ['单选题', '单项选择题', '单选', '选择题'],
1: ['多选题', '多项选择题', '多选'],
2: ['填空题', '填空'],
3: ['判断题', '是非题', '判断'],
4: ['简答题', '简答', '问答题', '名词解释', '论述题', '论述', '计算题', '计算', '分录题', '资料题', '作图题', '其他', '其它', '阅读理解', '阅读', '阅读题', '理解题', '完形填空', '完形', '综合题']
};
function getQuestionTypeFromText(text) {
if (!text) return undefined;
for (var typeId = 0; typeId <= 4; typeId++) {
var keywords = QuestionTypeMap[typeId];
for (var i = 0; i < keywords.length; i++) {
if (text.indexOf(keywords[i]) !== -1) return typeId;
}
}
return undefined;
}
/********************************* 全局变量 ****************************************/
var UNSAFE_WIN = unsafeWindow;
var LOCATION = location;
var DOCUMENT = UNSAFE_WIN.document;
var $ = UNSAFE_WIN.jQuery || top.jQuery;
var UE = UNSAFE_WIN.UE;
// 人工问答模式:不再调用任何外部答题API
var pendingAnswerRequest = null;
var manualSelectedOptions = [];
var manualQuestionCount = 0;
var taskList = null;
var defaults = null;
var domList = null;
var submitBtn = null;
var saveBtn = null;
var frameContent = null;
var okBtn = null;
var reportUrlChange = 0;
var isProcessing = false;
var isBoxHidden = false;
var pikaqiuAdded = false;
var pendingMissionCount = 0;
var completedMissionCount = 0;
var isJumping = false;
var currentProcessingTask = null;
var totalMissionCount = 0;
var currentVideoInterval = null;
var currentVideoQuizObserver = null;
var quizObserverGuardTimer = null;
var quizPollTimer = null;
var hasTriggeredNoTaskJump = false;
var logQueue = [];
var logTimer = null;
// ==================== 选项清理函数 ====================
function cleanOptionText(text) {
if (!text) return text;
var cleaned = text.replace(/<[^>]*>/g, '');
cleaned = cleaned.replace(/^[A-Z][\s]*[.、.))\s]+/, '');
cleaned = cleaned.replace(/^\([A-Z]\)[\s]*/, '');
cleaned = cleaned.replace(/^([A-Z])[\s]*/, '');
cleaned = cleaned.replace(/^[:\s\-_]+/, '');
return cleaned.trim();
}
// 弹题选项专用清洗:反复剥 A、 A. A) (A) (A) 1. 1、 1) (1) (1) 等前缀
function cleanQuizOptionText(text) {
if (!text) return '';
var cleaned = String(text).replace(/<[^>]*>/g, '').replace(/ /g, ' ').trim();
for (var round = 0; round < 3; round++) {
var before = cleaned;
cleaned = cleaned.replace(/^\s*[A-Za-z]\s*[.、.,,::))]+\s*/, '');
cleaned = cleaned.replace(/^\s*[((]\s*[A-Za-z]\s*[))]\s*/, '');
cleaned = cleaned.replace(/^\s*\d+\s*[.、.,,::))]+\s*/, '');
cleaned = cleaned.replace(/^\s*[((]\s*\d+\s*[))]\s*/, '');
cleaned = cleaned.replace(/^\s*[A-Za-z]\s+/, '');
if (cleaned === before) break;
}
return cleaned.trim();
}
function tidyString(s) {
if (!s) return null;
var cleaned = s.replace(/<(?!img).*?>/g, "").replace(/^【.*?】\s*/, '').replace(/\s*(\d+\.\d+分)$/, '').trim().replace(/ /g, '');
return cleanOptionText(cleaned);
}
function tidyQuestion(s) {
if (!s) return null;
var cleaned = s.replace(/<(?!img).*?>/g, "").replace(/^【.*?】\s*/, '').replace(/\s*(\d+\.\d+分)$/, '').replace(/^\d+[.、]/, '').trim();
return cleanOptionText(cleaned);
}
function normalizeForCompare(text) {
if (!text) return '';
return text.toUpperCase().replace(/[^\u4e00-\u9fa5A-Z0-9]/g, '').trim();
}
function splitAnswer(answer) {
if (!answer) return [];
var parts = answer.split(/[#]+/).map(function(a) { return a.trim(); }).filter(function(a) { return a !== ''; });
if (parts.length === 0 && answer.trim() !== '') return [answer.trim()];
return parts;
}
function extractString(str, start, end) {
var res = str.match(new RegExp(start + '(.*?)' + end));
return res ? res[1] : null;
}
function getTopLogContainer() {
try {
var topDoc = panelDoc();
var container = topDoc.getElementById('ne-21log');
if (container) return $(container);
container = document.getElementById('ne-21log');
if (container) return $(container);
return null;
} catch(e) { return null; }
}
function flushLogs() {
if (logQueue.length === 0) return;
var container = getTopLogContainer();
if (container && container.length) {
var logsToShow = logQueue.slice();
logQueue = [];
for (var i = logsToShow.length - 1; i >= 0; i--) { container.prepend(logsToShow[i]); }
container.scrollTop(0);
}
if (logTimer) { clearTimeout(logTimer); logTimer = null; }
}
function scheduleFlushLogs() { if (logTimer) return; logTimer = setTimeout(flushLogs, 100); }
function log(str, color) {
var time = new Date().toLocaleTimeString();
var logHtml = '
[' + time + '] ' + str + '
';
logQueue.push(logHtml);
scheduleFlushLogs();
console.log('[学习通助手][' + time + ']', str);
}
// 安全取「面板所在文档」:跨域 iframe 下 top.document 会抛错,退回本文档
function panelDoc() {
try {
var d = top.document;
if (d && d.body) { return d; }
} catch(e) {}
return document;
}
function togglePanel() {
var doc = panelDoc();
var $box = $('#ne-21box', doc);
if (!$box.length) { showBox(true); return; }
if ($box.css('display') === 'none') { $box.css('display', 'flex'); isBoxHidden = false; }
else { $box.css('display', 'none'); isBoxHidden = true; }
}
function showPikaqiu() {
if (pikaqiuAdded) return;
var targetDoc = panelDoc();
try {
if (targetDoc.getElementById('ne-21fac')) { pikaqiuAdded = true; return; }
// 常驻小按钮:不依赖任何外部图片,任何网站都能看到/唤起面板
var facHtml = '📚
';
$(targetDoc.body).append(facHtml);
pikaqiuAdded = true;
targetDoc.getElementById('ne-21fac').onclick = togglePanel;
if (CONFIG.showMaskImg) {
var imgHtml = '
';
$(targetDoc.body).append(imgHtml);
$('#pikaqiu-img', targetDoc).click(togglePanel);
}
} catch(e) {}
}
$(document).keydown(function(e) {
if (e.keyCode == 120) {
var $box = $('#ne-21box');
if ($box.length === 0) return;
if (isBoxHidden) { $box.css('display', 'block'); $box.css('opacity', '1'); isBoxHidden = false; log('📌 面板已显示', 'green'); }
else { $box.css('display', 'none'); isBoxHidden = true; log('📌 面板已隐藏,按F9键恢复显示', 'blue'); }
}
});
// ==================== 人工问答核心逻辑 ====================
function manualTargetDoc() {
try { return top.document; } catch(e) { return document; }
}
function typeNameById(t) {
var m = {0:'单选题',1:'多选题',2:'填空题',3:'判断题',4:'简答题'};
return m[t] || ('题型' + t);
}
function formatQuestionForCopy(type, text, options) {
var s = '【' + typeNameById(type) + '】' + (text || '');
if (options && options.length && (type === 0 || type === 1)) {
var letters = 'ABCDEFGHIJKLMNOP';
s += '\n选项:';
options.forEach(function(o, i) { s += '\n' + (letters[i] || (i + 1)) + '. ' + o; });
}
return s;
}
function copyTextToClipboard(text) {
try {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;';
document.body.appendChild(ta);
ta.focus();
ta.select();
var ok = document.execCommand('copy');
document.body.removeChild(ta);
if (ok) log('📋 题目已复制,粘贴到AI对话框即可提问', 'green');
return ok;
} catch(e) { return false; }
}
function renderPendingQuestionUI() {
var doc = manualTargetDoc();
var req = pendingAnswerRequest;
var box = doc.getElementById('ne-21box');
if (box) { box.style.display = 'block'; }
var area = doc.getElementById('ne-21pending');
if (!area) return;
var letters = 'ABCDEFGHIJKLMNOP';
var optionsHtml = '';
if (req && req.options && req.options.length && (req.type === 0 || req.type === 1 || req.type === 3)) {
optionsHtml = '' + req.options.map(function(opt, i) {
var label = (req.type === 3 && (opt === '对' || opt === '错')) ? opt : ((letters[i] || (i + 1)) + '. ' + opt);
return '';
}).join('') + '
' +
'💡 多选题:点选多个选项后,再点「填入答案」确认
';
}
var qTitle = '暂无待答题目';
var qBody = '';
if (req) { qTitle = '【' + typeNameById(req.type) + '】'; qBody = (req.text || ''); }
area.innerHTML =
'' +
'
🤖 人工问答 (答案填好后脚本自动选择)
' +
'
' + qTitle + '' + qBody + '
' +
optionsHtml +
'
' +
'' +
'' +
'' +
'' +
'
' +
'
' + (req ? ('第 ' + req.count + ' 个待答问题:拿到答案后填回来,脚本会自动选择') : '') + '
' +
'
';
if (req && req.type === 1) { var tip = doc.getElementById('manualMultiTip'); if (tip) tip.style.display = 'block'; }
flushLogs();
}
function ensureManualBindings(doc) {
if (doc.__manualBindings) return;
doc.__manualBindings = true;
doc.addEventListener('click', function(e) {
var t = e.target;
if (!t || !t.closest) return;
if (t.closest('[data-manual-opt]')) {
var idx = parseInt(t.closest('[data-manual-opt]').getAttribute('data-manual-opt'), 10);
quickPickManualOption(idx);
return;
}
if (t.closest('#submitManualAnswerBtn')) { submitManualAnswer(); return; }
if (t.closest('#copyQuestionBtn')) { copyPendingQuestion(); return; }
if (t.closest('#skipQuestionBtn')) { skipPendingQuestion(); return; }
});
doc.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && doc.activeElement && doc.activeElement.id === 'manualAnswerInput') {
e.preventDefault();
submitManualAnswer();
}
});
}
function renderPendingOptionsHighlight(doc) {
var btns = doc.querySelectorAll('[data-manual-opt]');
for (var i = 0; i < btns.length; i++) {
var bi = parseInt(btns[i].getAttribute('data-manual-opt'), 10);
if (manualSelectedOptions.indexOf(bi) !== -1) { btns[i].style.background = '#4CAF50'; btns[i].style.color = '#fff'; }
else { btns[i].style.background = '#fff'; btns[i].style.color = '#000'; }
}
}
function expandLetterAnswer(answer, options, questionType) {
if (!answer || !options || !options.length) return answer;
if (questionType === 2 || questionType === 4) return answer;
var letters = answer.toUpperCase().trim().replace(/[\s,,、;;]+/g, '');
if (letters.length < 1 || letters.length > 8) return answer;
if (!/^[A-H]+$/.test(letters)) return answer;
var mapped = [];
var seen = {};
for (var i = 0; i < letters.length; i++) {
var li = letters.charCodeAt(i) - 65;
if (li >= 0 && li < options.length && !seen[li]) { seen[li] = true; mapped.push(options[li]); }
}
return mapped.length ? mapped.join('#') : answer;
}
function resolvePendingAnswer(answer, skipped) {
var req = pendingAnswerRequest;
if (!req) return;
pendingAnswerRequest = null;
manualSelectedOptions = [];
var doc = manualTargetDoc();
var area = doc.getElementById('ne-21pending');
if (area) { area.style.display = 'none'; area.innerHTML = ''; }
if (skipped) {
log('⏭️ 用户选择跳过', 'orange');
req.reject('用户跳过');
} else {
answer = (typeof answer === 'string') ? answer.trim() : answer;
answer = expandLetterAnswer(answer, req.options, req.type);
log('🤖 收到人工答案: ' + answer, 'purple');
req.resolve(answer);
}
}
function quickPickManualOption(idx) {
var req = pendingAnswerRequest;
if (!req || !req.options || idx < 0 || idx >= req.options.length) return;
if (req.type === 1) {
var pos = manualSelectedOptions.indexOf(idx);
if (pos !== -1) { manualSelectedOptions.splice(pos, 1); }
else { manualSelectedOptions.push(idx); }
renderPendingOptionsHighlight(manualTargetDoc());
log('📌 多选题已选 ' + manualSelectedOptions.length + ' 项,确认后点「填入答案」', 'blue');
return;
}
resolvePendingAnswer(req.options[idx], false);
}
function submitManualAnswer() {
var req = pendingAnswerRequest;
if (!req) return;
var doc = manualTargetDoc();
var input = doc.getElementById('manualAnswerInput');
var answer = '';
if ((req.type === 0 || req.type === 1) && manualSelectedOptions.length > 0) {
answer = manualSelectedOptions.map(function(i) { return req.options[i]; }).join('#');
} else if (input && input.value) {
answer = input.value;
}
if (!answer || !answer.trim()) { log('⚠️ 请先点选选项或输入答案', 'orange'); return; }
resolvePendingAnswer(answer, false);
}
function copyPendingQuestion() {
var req = pendingAnswerRequest;
if (!req) return;
var ok = copyTextToClipboard(formatQuestionForCopy(req.type, req.text, req.options));
if (!ok) log('⚠️ 复制失败,请手动选中题目文本', 'orange');
}
function skipPendingQuestion() {
var req = pendingAnswerRequest;
if (!req) return;
resolvePendingAnswer(null, true);
}
function askForAnswer(questionType, questionText, optionsData) {
return new Promise(function(resolve, reject) {
pendingAnswerRequest = {
type: questionType,
text: questionText || '',
options: optionsData || [],
resolve: resolve,
reject: reject,
count: ++manualQuestionCount
};
manualSelectedOptions = [];
ensureManualBindings(manualTargetDoc());
renderPendingQuestionUI();
log('🤖 等待人工答案:' + typeNameById(questionType) + ' | ' + String(questionText || '').substring(0, 50), 'purple');
});
}
function getSubmitDecision() {
if (CONFIG.autoSubmit) { return { action: 'submit', reason: '自动提交' }; }
else if (CONFIG.forceSubmit) { return { action: 'submit', reason: '强制提交' }; }
else { return { action: 'save', reason: '自动保存' }; }
}
function getAnswer(questionType, questionText, optionsData, retryCount) {
var hasApi = getApiUrlList().length > 0 || getApiSlots().some(function(s) {
return s && s.url && String(s.url).trim() && s.key && String(s.key).trim();
});
if (CONFIG.autoSearch && hasApi) {
return searchAnswerOnline(questionType, questionText, optionsData).then(function(answer) {
return expandLetterAnswer(answer, optionsData || [], questionType);
}).catch(function(err) {
log('🔍 自动搜索未找到答案,转为人工问答: ' + err, 'orange');
return askForAnswer(questionType, questionText, optionsData);
});
}
return askForAnswer(questionType, questionText, optionsData);
}
// ==================== 框架配置区(使用者可改) ====================
// 说明:
// - api_mode: 'ai' = 大模型接口;'bank' = 题库接口
// - 分享版不内置任何密钥,首次使用请打开脚本面板,在「自动搜题」区
// 填入自己的 API 密钥后点「存密钥」,并可用「测试」验证接口
var DEFAULT_API_URLS = []; // 自定义接口地址(多个用逗号分隔)
var DEFAULT_AI_BASE_URL = 'https://api.mxwell.ai/v1'; // AI模式默认中转地址(可改)
var DEFAULT_API_MODEL = 'gpt-5.6-sol'; // AI模式默认模型(可改)
var DEFAULT_API_KEY = ''; // 内置密钥:分享版留空,由使用者面板配置
var MXWELL_MODELS = [
{ id: 'deepseek-flash', label: 'deepseek-flash' },
{ id: 'deepseek-v4-flash', label: 'deepseek-v4-flash' },
{ id: 'deepseek-v4-flash-0731', label: 'deepseek-v4-flash-0731' },
{ id: 'deepseek-v4-pro', label: 'deepseek-v4-pro' },
{ id: 'deepseek-v4.1', label: 'deepseek-v4.1' },
{ id: 'deepseek-v4.1-flash-0910', label: 'deepseek-v4.1-flash-0910' },
{ id: 'gpt-5.6-sol', label: 'gpt-5.6-sol' },
{ id: 'gpt-6-sol', label: 'gpt-6-sol' },
{ id: 'gpt-6.1-sol', label: 'gpt-6.1-sol' },
{ id: 'gpt-6-astra', label: 'gpt-6-astra' }
];
var MXWELL_TIERS = ['low', 'medium', 'high', 'pro', 'ultra'];
function getApiMode() { return GM_getValue('api_mode', 'ai'); }
function getApiModel() { return GM_getValue('api_model', DEFAULT_API_MODEL); }
function getApiUrlList() {
var raw = GM_getValue('api_url', '');
var list = [];
if (raw && raw.trim()) {
list = raw.split(/[,,;;]+/).map(function(u) { return u.trim(); }).filter(function(u) { return u !== ''; });
}
if (!list.length && getApiMode() === 'ai') { list = [DEFAULT_AI_BASE_URL]; }
return list;
}
function saveApiUrls(urlsText) {
var list = String(urlsText || '').split(/[,,;;]+/).map(function(u) { return u.trim(); }).filter(function(u) { return u !== ''; });
GM_setValue('api_url', list.join(','));
return list;
}
function saveApiConfig(urlsText, model) {
if (model && model.trim()) { GM_setValue('api_model', model.trim()); }
return saveApiUrls(urlsText);
}
function getApiSlots() {
var raw = GM_getValue('api_slots', '');
if (raw) {
try {
var arr = JSON.parse(raw);
if (Array.isArray(arr) && arr.length) { return arr; }
} catch(e) {}
}
// 兼容旧版单接口配置
var list = getApiUrlList();
var model = GM_getValue('api_model', DEFAULT_API_MODEL) || DEFAULT_API_MODEL;
var key = GM_getValue('api_key', '') || '';
var slots = [
{ url: list[0] || DEFAULT_AI_BASE_URL, model: model, tier: 'high', key: key },
{ url: list[1] || '', model: model, tier: 'high', key: '' },
{ url: list[2] || '', model: model, tier: 'high', key: '' }
];
return slots;
}
function saveApiSlots(slots) {
var arr = (Array.isArray(slots) ? slots : []).slice(0, 3);
while (arr.length < 3) { arr.push({ url: '', model: 'gpt-5.6-sol', tier: 'high', key: '' }); }
GM_setValue('api_slots', JSON.stringify(arr));
return arr;
}
function getApiKey() {
var slots = getApiSlots();
for (var i = 0; i < slots.length; i++) {
if (slots[i] && slots[i].key && String(slots[i].key).trim()) { return slots[i].key; }
}
var saved = GM_getValue('api_key', '');
return (saved && saved.trim()) ? saved : DEFAULT_API_KEY;
}
function searchAnswerOnline(questionType, questionText, optionsData) {
if (getApiMode() === 'ai') { return searchAnswerWithAI(questionType, questionText, optionsData); }
return searchQuestionBank(questionType, questionText, optionsData);
}
function searchQuestionBank(questionType, questionText, optionsData) {
var urls = getApiUrlList();
var typeMap = {0:'单选题',1:'多选题',2:'填空题',3:'判断题',4:'简答题'};
var typeText = typeMap[questionType] || '单选题';
var apiKey = getApiKey();
return new Promise(function(resolve, reject) {
function tryUrl(i) {
if (i >= urls.length) { reject('所有接口均未搜到答案'); return; }
var url = urls[i];
var formData = 'question=' + encodeURIComponent(questionText || '') + '&type=' + encodeURIComponent(typeText);
if (apiKey && apiKey.trim()) { formData += '&key=' + encodeURIComponent(apiKey.trim()); }
if (optionsData && optionsData.length) { formData += '&options=' + encodeURIComponent(JSON.stringify(optionsData)); }
if (i === 0) log('🔍 自动搜索答案:' + typeText + ' | ' + String(questionText || '').substring(0, 40), 'blue');
var timer = setTimeout(function() { tryUrl(i + 1); }, 12000);
GM_xmlhttpRequest({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: formData,
timeout: 12000,
onload: function(xhr) {
clearTimeout(timer);
try {
var res = JSON.parse(xhr.responseText);
if (res.code == 1) {
var answer = null;
if (Array.isArray(res.data) && res.data.length > 0) {
if (res.data[0].answer) { answer = res.data[0].answer; }
else if (res.data[0].question && res.data[0].question !== '抱歉无答案') { answer = res.data[0].question; }
} else if (typeof res.data === 'string') { answer = res.data; }
else if (res.data && typeof res.data === 'object' && res.data.answer) { answer = res.data.answer; }
if (answer && String(answer).trim() !== '' && !String(answer).includes('无答案') && String(answer).toLowerCase() !== 'none') {
log('✅ 自动搜到答案: ' + answer, 'purple');
resolve(answer);
return;
}
}
log('⚠️ 接口' + (i + 1) + '无答案,尝试下一个', 'orange');
tryUrl(i + 1);
} catch(e) { tryUrl(i + 1); }
},
onerror: function() { clearTimeout(timer); tryUrl(i + 1); },
ontimeout: function() { clearTimeout(timer); tryUrl(i + 1); }
});
}
tryUrl(0);
});
}
function buildAiPrompt(questionType, questionText, optionsData) {
var typeName = typeNameById(questionType);
var prompt = '你是一个学习答题助手。请根据题目给出正确答案。\n题型:' + typeName + '\n题目:' + (questionText || '');
if (questionType === 0) {
prompt += '\n选项:\n' + (optionsData || []).map(function(o, i) { return String.fromCharCode(65 + i) + '. ' + o; }).join('\n');
prompt += '\n请只输出选项字母,例如:B';
} else if (questionType === 1) {
prompt += '\n选项:\n' + (optionsData || []).map(function(o, i) { return String.fromCharCode(65 + i) + '. ' + o; }).join('\n');
prompt += '\n请只输出正确选项字母组合,例如:AC';
} else if (questionType === 3) {
prompt += '\n请只输出:对 或 错';
} else if (questionType === 2) {
prompt += '\n题目共 ' + ((optionsData && optionsData[0]) || '?') + ' 个空,请只输出填空答案,多个空用 # 分隔,例如:答案1#答案2';
} else {
prompt += '\n请直接输出答案内容,不要解释。';
}
return prompt;
}
function cleanAiAnswer(answer) {
if (!answer) return answer;
var s = String(answer).trim();
s = s.replace(/^```[a-z]*\s*/, '').replace(/\s*```$/, '').trim();
s = s.replace(/^(答案|正确答案|选择|选项)[::]?\s*/i, '');
s = s.replace(/^(选|为|是)\s*/i, '');
s = s.replace(/[。!]+$/, '');
var compact = s.replace(/[,,、\s..;;::和]+/g, '');
if (/^[A-H]+$/i.test(compact)) { return compact.toUpperCase(); }
return s;
}
function isUsableAnswer(answer) {
if (!answer) return false;
var s = String(answer).trim();
if (!s || s.toLowerCase() === 'none') { return false; }
if (/无答案|暂无答案|未找到|找不到|我不确定|不确定|不知道|无法确定|无法回答|无法作答|抱歉|sorry/i.test(s)) { return false; }
return true;
}
function getAutoGuessEmpty() { return GM_getValue('auto_guess_empty', true) !== false; }
function lettersFor(count) { return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'].slice(0, Math.max(1, count || 2)); }
function isChoiceAnswer(questionType, answer) {
if (questionType === 3) { return /^(对|错|正确|错误|A|B)$/.test(answer); }
return /^[A-H]+$/.test(answer);
}
function stripUncertain(clean) {
return String(clean || '').replace(/^(?:我不确定|不知道|无法确定|无法回答|无法作答|抱歉|sorry)[,,。::\s]*/i, '').trim();
}
function mergeAiInfo(raw, questionType, optionsData, state) {
if (!raw) return;
var s = String(raw);
var letters = lettersFor((optionsData && optionsData.length) || (questionType === 3 ? 2 : 4));
var exPats = [
/(?:排除|不对|错误|\[错\]|不是|肯定不是|应该不是|不可能|别选|去掉|删掉|肯定不对|一定不对|明显不对|感觉不对)(?:\s*[::]?\s*)([A-H])/gi,
/([A-H])(?:\s*[::]?\s*)(?:排除|不对|错误|\[错\]|不是|肯定不是|应该不是|不可能|别选|去掉|删掉|肯定不对|一定不对|明显不对|感觉不对)/gi
];
exPats.forEach(function(re) {
var m;
while ((m = re.exec(s))) {
var l = m[1].toUpperCase();
if (letters.indexOf(l) !== -1 && state.excluded.indexOf(l) === -1) { state.excluded.push(l); }
}
});
var reMention = /(?:选|选择|可能是|应该是|倾向|答案(?:\s*[是::])?)(?:\s*[::]?\s*)([A-H])/gi;
var m;
while ((m = reMention.exec(s))) {
var l2 = m[1].toUpperCase();
if (letters.indexOf(l2) !== -1) { state.mentions[l2] = (state.mentions[l2] || 0) + 1; }
}
var clean = stripUncertain(cleanAiAnswer(raw));
if (clean) { state.partials.push(clean); }
}
function guessAnswer(questionType, optionsData, state) {
if (questionType === 2 || questionType === 4) {
var best = '';
(state.partials || []).forEach(function(p) {
var t = String(p).trim();
if (t.length > best.length) { best = t; }
});
if (best) { return { ok: true, answer: best, note: '取AI返回内容兜底' }; }
return { ok: false };
}
var letters = lettersFor((optionsData && optionsData.length) || (questionType === 3 ? 2 : 4));
var usable = letters.filter(function(l) { return state.excluded.indexOf(l) === -1; });
if (!usable.length) { usable = letters.slice(); }
var cand = usable.filter(function(l) { return (state.mentions[l] || 0) > 0; });
var rnd = function(arr) { return arr[Math.floor(Math.random() * arr.length)]; };
if (questionType === 1) {
var multi = cand;
if (!multi.length) { multi = [rnd(usable)]; }
return { ok: true, answer: multi.join(''), note: (state.excluded.length ? '排除' + state.excluded.join('') + ',' : '') + '多选' + multi.join('') };
}
var pick;
if (cand.length) {
var top = 0;
cand.forEach(function(l) {
var m = state.mentions[l] || 0;
if (m > top) { top = m; }
});
pick = null;
letters.forEach(function(l) {
if (pick === null && (state.mentions[l] || 0) === top) { pick = l; }
});
if (!pick) { pick = rnd(usable); }
} else {
pick = rnd(usable);
}
return { ok: true, answer: pick, note: (state.excluded.length ? '排除' + state.excluded.join('') + ',' : '') + (state.mentions[pick] ? '按AI提及度选' : '随机选') + pick };
}
function extractAiAnswer(res) {
if (!res) return '';
if (res.output && Array.isArray(res.output)) {
var texts = [];
res.output.forEach(function(item) {
if (!item || item.type !== 'message' || !Array.isArray(item.content)) return;
item.content.forEach(function(part) {
if (part && (part.type === 'output_text' || part.type === 'text') && typeof part.text === 'string' && part.text.trim()) {
texts.push(part.text.trim());
}
});
});
if (texts.length) return texts.join(' ');
}
if (res.choices && res.choices[0]) {
var c = res.choices[0];
if (c.message && typeof c.message.content === 'string' && c.message.content.trim()) return c.message.content.trim();
if (typeof c.text === 'string' && c.text.trim()) return c.text.trim();
}
return '';
}
function requestSlotAnswer(s, prompt) {
return new Promise(function(resolve) {
var req = buildAiRequest(s, prompt);
GM_xmlhttpRequest({
method: 'POST',
url: req.url,
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + s.key},
data: JSON.stringify(req.payload),
timeout: 90000,
onload: function(xhr) {
var raw = '', answer = '';
try {
var res = JSON.parse(xhr.responseText);
raw = extractAiAnswer(res);
answer = cleanAiAnswer(raw);
} catch(e) {
resolve({ ok: false, raw: '', answer: '', err: '响应解析失败: HTTP ' + xhr.status + ' ' + String(xhr.responseText || '').slice(0, 120) });
return;
}
resolve({ ok: !!answer, raw: raw, answer: answer, status: xhr.status });
},
onerror: function() { resolve({ ok: false, raw: '', answer: '', err: '网络请求失败' }); },
ontimeout: function() { resolve({ ok: false, raw: '', answer: '', err: '请求超时(90秒)' }); }
});
});
}
var CODE_PATTERNS = [
/```/,
/#include\s*,
/public\s+static\s+void\s+main/,
/int\s+main\s*\(/,
/\bprintf\s*\(/,
/\bscanf\s*\(/,
/cout\s*<,
/cin\s*>>/,
/console\.log\s*\(/,
/System\.out\.print/,
/\bdef\s+[A-Za-z_]\w*\s*\(/,
/\bclass\s+[A-Za-z_]\w*\s*[:(]/,
/\bfunction\s+[A-Za-z_]*\s*\(/,
/\bfunc\s+[A-Za-z_]\w*\s*\(/,
/\bpublic\s+class\s+/
];
var CODE_CN_HINT = /(程序|代码|编程|编写|运行结果|输出结果|补全|算法|伪代码|时间复杂度|循环|数组|字符串|递归|排序|函数实现|报错)/;
var CODE_CN_STRONG = /(编写程序|编写代码|写出代码|写一段代码|写程序|程序题|补全程序|补全代码|编程题|代码实现|实现一个函数|编写函数|写一个函数|用代码|代码片段|源代码|阅读下面代码|阅读以下代码|如下代码|以下程序|该程序|这段代码|代码输出|程序输出)/;
var CODE_PUNCT = /[{};]|=\s*[^=]|\(\s*\)|==|!=|\+\+|--|\bfor\b|\bwhile\b|\bif\b|\[\s*\d*\s*\]/;
function isCodeQuestion(questionType, questionText, optionsData) {
var text = String(questionText || '');
var all = text + '\n' + ((optionsData || []).join(' ') || '');
for (var i = 0; i < CODE_PATTERNS.length; i++) {
if (CODE_PATTERNS[i].test(all)) { return true; }
}
if (CODE_CN_STRONG.test(text)) { return true; }
if (CODE_CN_HINT.test(text) && CODE_PUNCT.test(all)) { return true; }
if (/\n\s{2,}\S/.test(text) && CODE_PUNCT.test(all)) { return true; }
return false;
}
function buildCodeReviewPrompt(questionType, questionText, optionsData, candidate) {
var parts = [
'你是一名严谨的程序审查员。下面是一道程序题,以及另一个 AI 给出的答案。',
'请你完成:',
'1) 检查代码的语法、逻辑、边界条件是否符合题目要求;',
'2) 若发现问题,直接修正;',
'3) 只输出最终正确的完整代码,不要解释、不要复述题目。',
'',
'【题目】',
String(questionText || '')
];
if ((questionType === 0 || questionType === 1) && optionsData && optionsData.length) {
parts.push('', '【选项】');
optionsData.forEach(function(o, i) { parts.push(String.fromCharCode(65 + i) + '. ' + o); });
}
parts.push('', '【待审查的答案】', String(candidate || ''));
parts.push('', '【最终答案】');
return parts.join('\n');
}
function getCodeReview() { return GM_getValue('code_review', true) !== false; }
function buildAiRequest(s, prompt) {
var rawUrl = String(s.url || '').trim();
var base = rawUrl.replace(/\/+$/, '');
var isChat = /\/chat\/completions(\?|$)/i.test(base) || /\/chat\//i.test(base);
var isResponses = /\/responses(\?|$)/i.test(base);
var isMxwell = /mxwell/i.test(base);
var tier = s.tier || 'high';
var model = s.model || DEFAULT_API_MODEL;
var payload;
if (isChat) {
payload = {
model: model,
messages: [{ role: 'user', content: prompt }],
effort: tier,
reasoning_effort: tier
};
} else {
if (!isResponses) {
// mxwell 地址缺 /v1 时自动补上,避免请求打到返回 HTML 的路径
if (isMxwell && base.indexOf('/v1') === -1 && !/\/api\/v\d+/i.test(base)) {
base = base + '/v1';
}
base = base + '/responses';
}
payload = {
model: model,
input: prompt,
effort: tier,
reasoning_effort: tier
};
}
return { url: base, payload: payload };
}
function searchAnswerWithAI(questionType, questionText, optionsData) {
var slots = getApiSlots().filter(function(s) {
return s && s.url && String(s.url).trim() && s.key && String(s.key).trim();
});
if (!slots.length) {
return Promise.reject('未配置API密钥,请在面板填写');
}
var prompt = buildAiPrompt(questionType, questionText, optionsData);
var isCode = getCodeReview() && isCodeQuestion(questionType, questionText, optionsData);
if (isCode) {
prompt += '\n\n这是一道程序题:请只输出完整、可直接提交的代码(必要的说明写成注释),不要多余解释。';
}
var state = { excluded: [], mentions: {}, partials: [] };
log('🤖 正在问 AI:' + typeNameById(questionType) + (isCode ? '(程序题·写+审)' : '') + ' | ' + String(questionText || '').substring(0, 40), 'blue');
function accept(answer, slotNo) {
if (!isUsableAnswer(answer)) { return false; }
if (isCode) { return true; }
if (questionType === 2 || questionType === 4) { return true; }
if (isChoiceAnswer(questionType, answer)) { return true; }
try { mergeAiInfo(answer, questionType, optionsData, state); } catch(e) {}
log('⚠️ 接口' + slotNo + '返回的内容不是有效选项(如「' + String(answer).slice(0, 30) + '」),继续下一个', 'orange');
return false;
}
// 依次尝试,找到第一个能给出有效答案的接口(“写手”)
function findProducer(i) {
if (i >= slots.length) { return Promise.resolve(null); }
var s = slots[i];
var slotNo = i + 1;
log('🔎 接口' + slotNo + '(' + (s.model || '') + ' / ' + (s.tier || 'high') + ')…', 'blue');
return requestSlotAnswer(s, prompt).then(function(r) {
if (r.ok) {
try { state.partials.push(r.answer); } catch(e) {}
if (accept(r.answer, slotNo)) {
log('🤖 AI(接口' + slotNo + ')返回答案: ' + String(r.answer).slice(0, 60), 'purple');
return { slot: s, index: i, answer: r.answer };
}
} else {
log('⚠️ 接口' + slotNo + '未返回内容' + (r.err ? ':' + r.err : ''), 'orange');
}
try { mergeAiInfo(r.raw, questionType, optionsData, state); } catch(e) {}
if (r.ok) { log('⚠️ 接口' + slotNo + '答案不可用,尝试下一个', 'orange'); }
return findProducer(i + 1);
});
}
function finalizeGuess() {
if (getAutoGuessEmpty()) {
var g = guessAnswer(questionType, optionsData, state);
if (g.ok) {
log('⚠️ 所有接口均无有效答案,直接选正确率高的(' + g.note + '):' + g.answer, 'orange');
return g.answer;
}
}
return Promise.reject('3个AI接口均未返回有效答案');
}
return findProducer(0).then(function(prod) {
if (!prod) { return finalizeGuess(); }
if (!isCode) { return prod.answer; }
// 程序题:让下一个接口审查
var reviewer = slots[prod.index + 1];
if (!reviewer) {
log('🧩 程序题:接口' + (prod.index + 1) + ' 已出答案,且它已是最后一个接口,跳过审查', 'orange');
return prod.answer;
}
var writeNo = prod.index + 1;
var reviewNo = prod.index + 2;
log('🧩 程序题:接口' + writeNo + ' 写出代码,转接口' + reviewNo + ' 审查…', 'blue');
var reviewPrompt = buildCodeReviewPrompt(questionType, questionText, optionsData, prod.answer);
return requestSlotAnswer(reviewer, reviewPrompt).then(function(r) {
if (r.ok && isUsableAnswer(r.answer)) {
log('🔍 接口' + reviewNo + ' 审查后答案: ' + String(r.answer).slice(0, 60), 'green');
return r.answer;
}
log('⚠️ 接口' + reviewNo + ' 审查未返回内容,沿用接口' + writeNo + ' 的答案', 'orange');
return prod.answer;
});
});
}
function testOneAiSlot(s) {
return new Promise(function(resolve) {
var req = buildAiRequest(s, '只回答:测试成功');
GM_xmlhttpRequest({
method: 'POST',
url: req.url,
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + s.key},
data: JSON.stringify(req.payload),
timeout: 30000,
onload: function(xhr) {
try {
var res = JSON.parse(xhr.responseText);
if (res.error) {
resolve({ ok: false, err: 'HTTP ' + xhr.status + ' ' + (res.error.message || res.error.code || '接口报错') });
return;
}
var ans = extractAiAnswer(res);
if (ans) { resolve({ ok: true, info: String(ans).slice(0, 40) }); return; }
resolve({ ok: false, err: '返回内容无法解析: ' + String(xhr.responseText || '').slice(0, 120) });
} catch(e) {
resolve({ ok: false, err: '响应解析失败: HTTP ' + xhr.status + ' ' + String(xhr.responseText || '').slice(0, 120) });
}
},
onerror: function() { resolve({ ok: false, err: '网络请求被拦截或失败' }); },
ontimeout: function() { resolve({ ok: false, err: '请求超时(30秒)' }); }
});
});
}
function testOneBankUrl(url, apiKey) {
return new Promise(function(resolve) {
var formData = 'question=' + encodeURIComponent('test') + '&type=' + encodeURIComponent('单选题');
if (apiKey && apiKey.trim()) { formData += '&key=' + encodeURIComponent(apiKey.trim()); }
GM_xmlhttpRequest({
method: 'POST', url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: formData, timeout: 15000,
onload: function(xhr) {
try {
var res = JSON.parse(xhr.responseText);
if (res.code == 1 || res.code == 400) { resolve({ ok: true, info: 'HTTP ' + xhr.status }); return; }
resolve({ ok: false, err: '返回异常: ' + String(xhr.responseText || '').slice(0, 120) });
} catch(e) {
resolve({ ok: false, err: '解析失败: HTTP ' + xhr.status });
}
},
onerror: function() { resolve({ ok: false, err: '网络请求失败' }); },
ontimeout: function() { resolve({ ok: false, err: '请求超时(15秒)' }); }
});
});
}
function testApiConnection(onProgress) {
var onP = typeof onProgress === 'function' ? onProgress : function() {};
var results = [];
var push = function(r) {
results.push(r);
try { onP(results.slice()); } catch(e) {}
};
var chain = Promise.resolve();
if (getApiMode() === 'ai') {
var slots = getApiSlots();
slots.forEach(function(s, i) {
var index = i + 1;
var label = { index: index, model: s && s.model, tier: s && s.tier };
chain = chain.then(function() {
if (!s || !s.url || !String(s.url).trim() || !s.key || !String(s.key).trim()) {
push(Object.assign({ ok: false, skipped: true, err: '未配置(跳过)' }, label));
return;
}
return testOneAiSlot(s).then(function(r) {
push(Object.assign(r, label));
});
});
});
} else {
var urls = getApiUrlList();
var apiKey = getApiKey();
if (!urls.length) { return Promise.reject('未配置题库接口'); }
urls.forEach(function(url, i) {
chain = chain.then(function() {
return testOneBankUrl(url, apiKey).then(function(r) {
push(Object.assign(r, { index: i + 1, url: url }));
});
});
});
}
return chain.then(function() { return results; });
}
// ==================== 视频弹题核心逻辑 ====================
function isVideoQuizPopup(node) {
if (!node || node.nodeType !== 1) return false;
var hasTitle = node.querySelector && (
node.querySelector('.TiMu') ||
node.querySelector('.ans-videoquiz') ||
node.querySelector('.ans-videoquiz-title') ||
node.querySelector('.videoquiz') ||
node.querySelector('.ans-videoquiz-opt')
);
var hasInput = node.querySelector && (
node.querySelector('input[type=radio]') ||
node.querySelector('input[type=checkbox]') ||
node.querySelector('.ans-videoquiz-opt label')
);
if (hasTitle && hasInput) return true;
var txt = node.textContent || '';
if ((txt.indexOf('题') !== -1 || txt.indexOf('选择') !== -1) &&
node.querySelectorAll && node.querySelectorAll('input[type=radio],input[type=checkbox]').length > 0) {
return true;
}
return false;
}
function extractVideoQuiz(popupEl) {
var titleEl = popupEl.querySelector('.TiMu') ||
popupEl.querySelector('.ans-videoquiz-title') ||
popupEl.querySelector('.videoquiz-title') ||
popupEl.querySelector('.ans-videoquiz') ||
popupEl;
var title = (titleEl.textContent || '').trim();
var options = [];
var inputs = popupEl.querySelectorAll('input[type=radio],input[type=checkbox]');
if (inputs.length) {
inputs.forEach(function(input, idx) {
var label = input.closest('label') || input.parentElement;
var raw = (label.textContent || '').trim();
options.push({
index: idx,
text: cleanQuizOptionText(raw),
rawText: raw,
type: input.type,
el: input
});
});
} else {
var liList = popupEl.querySelectorAll('.ans-videoquiz-opt li, .ans-videoquiz-opt label');
liList.forEach(function(el, idx) {
var raw = (el.textContent || '').trim();
options.push({
index: idx,
text: cleanQuizOptionText(raw),
rawText: raw,
type: 'click',
el: el
});
});
}
var qType = 'single';
if (popupEl.querySelector('input[type=checkbox]')) qType = 'multiple';
else if (popupEl.querySelector('.ans-videoquiz-opt .dui, .panduan')) qType = 'judge';
return { title: title, options: options, type: qType, popup: popupEl };
}
function getSecFont() {
try {
var styleEl = document.querySelector("style[type='text/css']");
if (!styleEl) return null;
var m = styleEl.textContent.match(/'(data:application\/font-ttf;.*?)'/);
return m ? m[1] : null;
} catch(e) { return null; }
}
function decryptVideoQuizFont(popupEl) {
return new Promise(function(resolve) {
if (!CONFIG.decryptFont) { resolve(); return; }
var nodes = popupEl.querySelectorAll('.font-cxsecret');
if (!nodes.length) { resolve(); return; }
var secFont = getSecFont();
if (!secFont) { resolve(); return; }
var pending = nodes.length;
nodes.forEach(function(node) {
GM_xmlhttpRequest({
method: 'POST',
url: 'https://pkpkq.n1t.cn/font-decrypt/decrypt.php',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({ secFont: secFont, dstText: (node.textContent || '').trim() }),
onload: function(res) {
try {
var data = JSON.parse(res.responseText);
if (data && data.srcText) node.textContent = data.srcText;
} catch(e) {}
if (--pending === 0) resolve();
},
onerror: function() { if (--pending === 0) resolve(); },
ontimeout: function() { if (--pending === 0) resolve(); }
});
});
});
}
function clickOpt(opt) {
try {
if (opt.el) {
if (opt.el.click) opt.el.click();
var label = opt.el.closest && opt.el.closest('label');
if (label && label.click) label.click();
}
} catch(e) {}
}
function fillVideoQuizAnswer(quiz, answer) {
var qType = quiz.type;
var opts = quiz.options;
if (!opts.length) return false;
if (qType === 'judge') {
var isTrue = /对|正确|是|√|T/i.test(answer);
var targetIdx = isTrue ? 0 : 1;
if (opts[targetIdx]) { clickOpt(opts[targetIdx]); return true; }
}
if (qType === 'multiple') {
var optsText = opts.map(function(o) { return o.text; });
var hitIdx = matchMultiChoiceIndices(optsText, answer);
if (hitIdx.length > 0) {
hitIdx.forEach(function(i) { clickOpt(opts[i]); });
return true;
}
return false;
}
// 单选:严格相等 → 包含且长度差≤1 → rawText 兜底
var ansArr = splitAnswer(answer);
var clicked = false;
opts.forEach(function(opt) {
var normOpt = normalizeForCompare(opt.text);
for (var i = 0; i < ansArr.length; i++) {
if (normOpt === normalizeForCompare(ansArr[i])) { clickOpt(opt); clicked = true; break; }
}
});
if (clicked) return true;
opts.forEach(function(opt) {
var normOpt = normalizeForCompare(opt.text);
for (var i = 0; i < ansArr.length; i++) {
var normAns = normalizeForCompare(ansArr[i]);
if (normOpt.indexOf(normAns) !== -1 && normOpt.length - normAns.length <= 1) { clickOpt(opt); clicked = true; break; }
if (normAns.indexOf(normOpt) !== -1 && normAns.length - normOpt.length <= 1) { clickOpt(opt); clicked = true; break; }
}
});
if (clicked) return true;
opts.forEach(function(opt) {
var normRaw = normalizeForCompare(opt.rawText);
for (var i = 0; i < ansArr.length; i++) {
if (normRaw === normalizeForCompare(ansArr[i])) { clickOpt(opt); clicked = true; break; }
}
});
return clicked;
}
function randomPickVideoQuiz(quiz) {
var opts = quiz.options || [];
if (!opts.length) return false;
if (quiz.type === 'multiple') {
var pickCount = 1 + Math.floor(Math.random() * opts.length);
var pool = opts.slice();
for (var k = 0; k < pickCount && pool.length > 0; k++) {
var pi = Math.floor(Math.random() * pool.length);
clickOpt(pool[pi]);
pool.splice(pi, 1);
}
log('🎲 多选题随机选择了 ' + pickCount + ' 项', 'orange');
return true;
}
var ri = Math.floor(Math.random() * opts.length);
clickOpt(opts[ri]);
log('🎲 随机选择第 ' + (ri + 1) + ' 项: ' + opts[ri].text, 'orange');
return true;
}
function submitVideoQuiz(popupEl) {
var submitBtn2 = popupEl.querySelector('.ans-videoquiz-submit, .submit-btn, .confirm, button[type=submit]');
if (submitBtn2) {
setTimeout(function() { submitBtn2.click(); log('📤 弹题已提交', 'green'); }, 500 + Math.random() * 500);
}
}
function resumeVideoWhenQuizGone(popupEl, video) {
var done = false;
function resume() {
if (done) return;
done = true;
if (video && video.paused) {
video.play().then(function() { log('▶️ 视频已恢复播放', 'blue'); }).catch(function(){});
}
}
try {
var mo = new MutationObserver(function() {
if (!popupEl.isConnected) { mo.disconnect(); resume(); }
});
mo.observe(popupEl.parentNode || document.body, { childList: true, subtree: true });
} catch(e) {}
setTimeout(resume, 8000);
var t = setInterval(function() {
if (!popupEl.isConnected || popupEl.style.display === 'none') {
clearInterval(t); resume();
}
}, 500);
setTimeout(function() { clearInterval(t); resume(); }, 12000);
}
function handleVideoQuiz(popupEl) {
if (!CONFIG.handleVideoQuiz) return;
if (!popupEl || popupEl.dataset.videoQuizHandled === 'true') return;
popupEl.dataset.videoQuizHandled = 'true';
log('🎯 检测到视频弹题,开始处理...', 'purple');
var doc = popupEl.ownerDocument || document;
var video = doc.querySelector('video');
if (video && !video.paused) video.pause();
decryptVideoQuizFont(popupEl).then(function() {
var quiz = extractVideoQuiz(popupEl);
log('📖 弹题题干: ' + quiz.title.substring(0, 60) + ' | 题型: ' + quiz.type, 'blue');
log('🔎 清洗后的弹题选项: ' + JSON.stringify(quiz.options.map(function(o){return o.text;})), 'blue');
var typeId = 0;
if (quiz.type === 'multiple') typeId = 1;
else if (quiz.type === 'judge') typeId = 3;
var optsText = quiz.options.map(function(o) { return o.text; });
var optionsData = (typeId === 3) ? ["对", "错"] : optsText;
getAnswer(typeId, quiz.title, optionsData).then(function(answer) {
log('🤖 人工答案: ' + answer, 'purple');
if (!answer || answer === '暂无答案') {
log('⚠️ 弹题未获取到答案,随机选择一项提交', 'orange');
randomPickVideoQuiz(quiz);
} else {
var filled = fillVideoQuizAnswer(quiz, answer);
if (!filled) {
log('⚠️ 弹题答案未匹配到选项,随机选择提交', 'orange');
randomPickVideoQuiz(quiz);
} else {
log('✅ 弹题已作答: ' + answer, 'green');
}
}
submitVideoQuiz(popupEl);
resumeVideoWhenQuizGone(popupEl, video);
}).catch(function(err) {
log('⚠️ 弹题获取答案失败: ' + err + ',随机作答', 'orange');
randomPickVideoQuiz(quiz);
submitVideoQuiz(popupEl);
resumeVideoWhenQuizGone(popupEl, video);
});
});
}
function observeVideoQuiz(doc) {
if (!CONFIG.handleVideoQuiz) return;
if (currentVideoQuizObserver) { try { currentVideoQuizObserver.disconnect(); } catch(e) {} currentVideoQuizObserver = null; }
if (!doc || !doc.body) return;
var existings = doc.querySelectorAll('.ans-videoquiz, .TiMu, .videoquiz');
existings.forEach(function(el) { if (isVideoQuizPopup(el)) handleVideoQuiz(el); });
currentVideoQuizObserver = new MutationObserver(function(mutations) {
if (!CONFIG.handleVideoQuiz) return;
mutations.forEach(function(m) {
m.addedNodes.forEach(function(node) {
if (node.nodeType !== 1) return;
if (isVideoQuizPopup(node)) {
handleVideoQuiz(node);
} else if (node.querySelectorAll) {
var inner = node.querySelectorAll('.ans-videoquiz, .TiMu, .videoquiz');
inner.forEach(function(el) { if (isVideoQuizPopup(el)) handleVideoQuiz(el); });
}
});
});
});
currentVideoQuizObserver.observe(doc.body, { childList: true, subtree: true });
doc.__quizObserverAlive = true;
var oldDisconnect = currentVideoQuizObserver.disconnect.bind(currentVideoQuizObserver);
currentVideoQuizObserver.disconnect = function() {
try { doc.__quizObserverAlive = false; } catch(e) {}
oldDisconnect();
};
log('👀 视频弹题监听已启动', 'blue');
}
function startQuizObserverGuard() {
if (quizObserverGuardTimer) return;
quizObserverGuardTimer = setInterval(function() {
if (!CONFIG.handleVideoQuiz) return;
try {
document.querySelectorAll('iframe').forEach(function(f) {
var d;
try { d = f.contentDocument || (f.contentWindow && f.contentWindow.document); } catch(e) { return; }
if (!d || !d.body) return;
if (!d.querySelector('video')) return;
if (d.__quizObserverAlive) return;
observeVideoQuiz(d);
log('🔄 弹题监听断线重连', 'blue');
});
} catch(e) {}
}, 3000);
}
function stopQuizObserverGuard() {
if (quizObserverGuardTimer) { clearInterval(quizObserverGuardTimer); quizObserverGuardTimer = null; }
}
function startQuizPoll(doc) {
if (quizPollTimer) clearInterval(quizPollTimer);
quizPollTimer = setInterval(function() {
if (!CONFIG.handleVideoQuiz) return;
try {
var pops = doc.querySelectorAll('.ans-videoquiz, .TiMu, .videoquiz');
pops.forEach(function(el) {
if (isVideoQuizPopup(el) && el.dataset.videoQuizHandled !== 'true') {
handleVideoQuiz(el);
}
});
} catch(e) {}
}, 1500);
}
function stopQuizPoll() {
if (quizPollTimer) { clearInterval(quizPollTimer); quizPollTimer = null; }
}
function getBlankCount($question) {
var count = 0;
var $inputs = $question.find('.blankList2 input, input[type="text"][name*="answer"]');
if ($inputs.length) {
var uniqueIdentifiers = new Set();
$inputs.each(function() {
var name = $(this).attr('name');
var id = $(this).attr('id');
if (name) { uniqueIdentifiers.add(name); }
else if (id) { uniqueIdentifiers.add(id); }
else { var parentHtml = $(this).parent().html() || ''; uniqueIdentifiers.add($(this).index() + '_' + parentHtml.substring(0, 50)); }
});
count = uniqueIdentifiers.size;
if (count > 0) return count;
}
var $editorBlocks = $question.find('[data-editorindex]');
if ($editorBlocks.length) {
var uniqueIndices = new Set();
$editorBlocks.each(function() {
var idx = $(this).attr('data-editorindex');
if (idx !== undefined && idx !== null && idx !== '') { uniqueIndices.add(idx); }
});
count = uniqueIndices.size;
if (count > 0) return count;
}
var $pcInputs = $question.find('.Zy_ulTk .XztiHover1 textarea, .stem_answer .Answer .divText .textDIV textarea, .subEditor textarea');
if ($pcInputs.length) {
var uniquePCInputs = new Set();
$pcInputs.each(function() {
var id = $(this).attr('id');
var name = $(this).attr('name');
if (id) { uniquePCInputs.add(id); }
else if (name) { uniquePCInputs.add(name); }
else { uniquePCInputs.add($(this).index()); }
});
count = uniquePCInputs.size;
if (count > 0) return count;
}
return count === 0 ? 1 : count;
}
function fillBlankAnswer($question, answers, isPhoneMode, contextWindow) {
var answerList = splitAnswer(answers);
log('📝 填空题答案: ' + answerList.join(' | '), 'blue');
if (isPhoneMode) {
var $allInputs = $question.find('.blankList2 input, input[type="text"][name*="answer"]');
if ($allInputs.length) {
var uniqueInputs = [];
var seen = new Set();
$allInputs.each(function() {
var name = $(this).attr('name');
var id = $(this).attr('id');
var key = name || id || $(this).index();
if (!seen.has(key)) { seen.add(key); uniqueInputs.push(this); }
});
log('📝 找到 ' + uniqueInputs.length + ' 个填空输入框,准备填写', 'blue');
$(uniqueInputs).each(function(i) {
setTimeout(function() {
var answerValue = answerList[i] !== undefined ? answerList[i] : (answerList[0] || '');
$(this).val(answerValue);
$(this).trigger('input').trigger('change');
log('✅ 填空题第' + (i+1) + '空已填写: ' + answerValue, 'green');
}.bind(this), i * 200);
});
return true;
}
var $editorBlocks = $question.find('[data-editorindex]');
if ($editorBlocks.length) {
var uniqueEditors = [];
var seenIndices = new Set();
$editorBlocks.each(function() {
var idx = $(this).attr('data-editorindex');
if (idx && !seenIndices.has(idx)) { seenIndices.add(idx); uniqueEditors.push(this); }
});
log('📝 找到 ' + uniqueEditors.length + ' 个编辑器,准备填写', 'blue');
uniqueEditors.forEach(function(editor, i) {
var editorIndex = $(editor).attr('data-editorindex');
var itemId = $(editor).attr('data-itemid');
setTimeout(function() {
try {
var ueditor = null;
if (contextWindow && contextWindow.editors && contextWindow.editors[editorIndex]) { ueditor = contextWindow.editors[editorIndex].ueditor; }
if (!ueditor && contextWindow && contextWindow.UE && contextWindow.UE.instants) { var instantKey = 'ueditorInstant' + editorIndex; ueditor = contextWindow.UE.instants[instantKey]; }
if (!ueditor && itemId && contextWindow && contextWindow.UE && contextWindow.UE.getEditor) { ueditor = contextWindow.UE.getEditor('ananas-editor-answer' + itemId); }
if (ueditor) {
var answerValue = answerList[i] !== undefined ? answerList[i] : (answerList[0] || '');
ueditor.setContent(answerValue);
log('✅ 填空题第' + (i+1) + '空已填写: ' + answerValue, 'green');
}
if (itemId) {
var answerValue = answerList[i] !== undefined ? answerList[i] : (answerList[0] || '');
$('#answer' + itemId).val(answerValue).trigger('change');
}
} catch(e) {}
}, i * 300);
});
return true;
}
}
var $pcInputs = $question.find('.Zy_ulTk .XztiHover1 textarea, .stem_answer .Answer .divText .textDIV textarea, .subEditor textarea');
if ($pcInputs.length) {
var uniquePCInputs = [];
var seenPC = new Set();
$pcInputs.each(function() {
var id = $(this).attr('id');
var name = $(this).attr('name');
var key = id || name || $(this).index();
if (!seenPC.has(key)) { seenPC.add(key); uniquePCInputs.push(this); }
});
log('📝 找到 ' + uniquePCInputs.length + ' 个填空输入框 (PC),准备填写', 'blue');
$(uniquePCInputs).each(function(i) {
setTimeout(function() {
var $this = $(this);
var answerValue = answerList[i] !== undefined ? answerList[i] : (answerList[0] || '');
if (UE && UE.getEditor && UE.getEditor($this.attr('id'))) { UE.getEditor($this.attr('id')).setContent(answerValue); }
else { $this.val(answerValue); $this.trigger('input').trigger('change'); }
log('✅ 填空题第' + (i+1) + '空已填写: ' + answerValue, 'green');
}.bind(this), i * 200);
});
return true;
}
return false;
}
function fillShortAnswer($question, answer, isPhoneMode, contextWindow) {
log('📝 简答题答案: ' + answer.substring(0, 100) + '...', 'blue');
if (isPhoneMode) {
var $editorBlocks = $question.find('[data-editorindex]');
if ($editorBlocks.length) {
$editorBlocks.each(function(i) {
var editorIndex = $(this).attr('data-editorindex');
var itemId = $(this).attr('data-itemid');
setTimeout(function() {
try {
var ueditor = null;
if (contextWindow && contextWindow.editors && contextWindow.editors[editorIndex]) { ueditor = contextWindow.editors[editorIndex].ueditor; }
if (!ueditor && contextWindow && contextWindow.UE && contextWindow.UE.instants) { var instantKey = 'ueditorInstant' + editorIndex; ueditor = contextWindow.UE.instants[instantKey]; }
if (!ueditor && itemId && contextWindow && contextWindow.UE && contextWindow.UE.getEditor) { ueditor = contextWindow.UE.getEditor('ananas-editor-answer' + itemId); }
if (ueditor) { ueditor.setContent(answer); log('✅ 简答题答案已填写', 'green'); }
if (itemId) { $('#answer' + itemId).val(answer).trigger('change'); }
} catch(e) {}
}, 300);
});
return true;
}
var $textarea = $question.find('textarea[name^="answer"], .answerTxt textarea');
if ($textarea.length) { $textarea.val(answer); $textarea.trigger('input').trigger('change'); return true; }
return false;
}
var $ueTextarea = $question.find('textarea[name^="answerEditor"], .eidtDiv textarea, .divText textarea');
if ($ueTextarea.length) {
var id = $ueTextarea.first().attr('id');
if (id && UE && UE.getEditor && UE.getEditor(id)) {
try { UE.getEditor(id).setContent(answer); return true; } catch(e) {}
}
$ueTextarea.val(answer);
$ueTextarea.trigger('input').trigger('change');
return true;
}
return false;
}
function waitForElement(selector, timeout) {
timeout = timeout || 30000;
return new Promise(function(resolve, reject) {
var start = Date.now();
var timer = setInterval(function() {
if ($(selector).length) { clearInterval(timer); resolve(); }
else if (Date.now() - start > timeout) { clearInterval(timer); reject(); }
}, 500);
});
}
function getElement(parent, selector, timeout) {
timeout = timeout || 10000;
return new Promise(function(resolve) {
var result = parent.querySelector(selector);
if (result) return resolve(result);
var timer;
var observer = new MutationObserver(function(mutations) {
for (var i = 0; i < mutations.length; i++) {
var mutation = mutations[i];
for (var j = 0; j < mutation.addedNodes.length; j++) {
var node = mutation.addedNodes[j];
if (node instanceof Element) {
result = node.matches(selector) ? node : node.querySelector(selector);
if (result) { observer.disconnect(); timer && clearTimeout(timer); return resolve(result); }
}
}
}
});
observer.observe(parent, { childList: true, subtree: true });
timer = setTimeout(function() { observer.disconnect(); resolve(null); }, timeout);
});
}
function getTaskParams() {
try {
var scripts = DOCUMENT.scripts;
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].innerHTML.indexOf('mArg = "";') != -1 && scripts[i].innerHTML.indexOf('==UserScript==') == -1) {
var params = extractString(scripts[i].innerHTML.replace(/\s/g, ""), 'try{mArg=', ';}catch');
return params;
}
}
return null;
} catch(e) { return null; }
}
function isTaskCompleted(task) {
if (!task) return false;
if (task.isPassed === true) return true;
if (task.status === 'completed' || task.status === 'finished') return true;
if (task.finished === true) return true;
return false;
}
function goToNext() {
if (isJumping) return;
isJumping = true;
log('🔄 检查是否有下一章节...', 'blue');
var nextBtn = null;
try {
nextBtn = top.document.querySelector('#mainid > .prev_next.next:not(.disabled)') || top.document.querySelector('#prevNextFocusNext:not(.disabled)') || top.document.querySelector('.prev_next.next:not(.disabled)') || $('.prev_next.next:not(.disabled)')[0];
if (nextBtn && !nextBtn.disabled && !nextBtn.classList.contains('disabled')) {
log('✅ 找到下一节按钮,3秒后跳转', 'green');
setTimeout(function() { nextBtn.click(); log('📖 已点击跳转按钮', 'green'); isJumping = false; }, 3000);
return true;
} else { log('📚 课程已全部完成,无更多章节可跳转', 'green'); }
} catch(e) { log('❌ 跳转失败: ' + e.message, 'red'); }
isJumping = false;
return false;
}
function completeCurrentTask() {
if (taskList && taskList.length > 0) {
var completedTask = taskList[0];
var taskName = completedTask.property ? (completedTask.property.name || completedTask.property.title || '未知') : '未知';
log('✅ 完成任务: ' + taskName, 'green');
taskList.splice(0, 1);
completedMissionCount++;
log('📋 任务进度: ' + completedMissionCount + '/' + pendingMissionCount + ' | 剩余: ' + taskList.length, 'blue');
}
if (domList && domList.length > 0) { domList.splice(0, 1); }
isProcessing = false;
if (currentVideoInterval) { clearInterval(currentVideoInterval); currentVideoInterval = null; }
if (currentVideoQuizObserver) { try { currentVideoQuizObserver.disconnect(); } catch(e) {} currentVideoQuizObserver = null; }
stopQuizPoll();
stopQuizObserverGuard();
if (taskList && taskList.length > 0) {
log('📋 还有 ' + taskList.length + ' 个任务点待处理,继续...', 'green');
setTimeout(function() { startMission(); }, 2000);
} else {
log('✅ 此页面所有任务处理完毕', 'green');
goToNext();
}
}
function switchMission() {
if (taskList.length <= 0) { log('✅ 此页面任务处理完毕', 'green'); isProcessing = false; goToNext(); return; }
isProcessing = false;
setTimeout(startMission, 3000);
}
function startMission() {
if (isProcessing) return;
if (taskList.length <= 0) { log('✅ 此页面任务处理完毕', 'green'); isProcessing = false; goToNext(); return; }
isProcessing = true;
var taskType = taskList[0]['type'];
var dom = domList[0];
var task = taskList[0];
currentProcessingTask = task;
if (taskType == undefined) { taskType = taskList[0]['property']["module"]; }
var handlers = {
'video': function() { processVideo(dom, task); },
'audio': function() { processAudio(dom, task); },
'workid': function() { processQuiz(dom, task); },
'document': function() { processDocument(dom, task); },
'read': function() { processRead(dom, task); },
'insertbook': function() { processBook(dom, task); }
};
if (handlers[taskType]) { handlers[taskType](); }
else if (['insertimage'].indexOf(taskType) !== -1) { log('ℹ️ 发现无需处理任务,跳过。', 'orange'); completeCurrentTask(); }
else { log('⚠️ 暂不支持处理此类型:' + taskType + ',跳过。', 'red'); completeCurrentTask(); }
}
function processVideo(dom, obj) {
if (!CONFIG.handleVideo) {
log('ℹ️ 用户设置不处理视频任务', 'orange');
completeCurrentTask();
return;
}
var isPassed = obj.isPassed;
var name = obj.property.name;
if (!CONFIG.reviewMode && isPassed === true) {
log('✅ 视频:' + name + ' 已完成,跳过', 'green');
completeCurrentTask();
return;
}
var target = dom.length > 0 ? dom[0] : null;
if (!target) {
log('⚠️ 未找到视频iframe,3秒后重试', 'orange');
isProcessing = false;
setTimeout(function() { processVideo(dom, obj); }, 3000);
return;
}
log('🎬 处理视频:' + name, 'purple');
var executed = false;
var doc = target.contentDocument || target.contentWindow.document;
if (currentVideoInterval) { clearInterval(currentVideoInterval); currentVideoInterval = null; }
currentVideoInterval = setInterval(function() {
var innerDoc = target.contentDocument || target.contentWindow.document;
if (innerDoc && innerDoc.body && !currentVideoQuizObserver) {
observeVideoQuiz(innerDoc);
startQuizObserverGuard();
startQuizPoll(innerDoc);
}
var media = innerDoc.querySelector('video') || innerDoc.querySelector('audio');
if (media) {
// 倍速功能已取消,不干预播放速度
if (!executed) {
executed = true;
log('✅ ' + name + ' 开始播放', 'green');
media.pause();
media.muted = true;
media.play();
var resumePlay = function() {
if (media.paused && !media.ended) {
setTimeout(function() {
var popup = innerDoc.querySelector('.ans-videoquiz, .TiMu, .videoquiz');
if (!popup && media.paused && !media.ended) {
media.play().catch(function(){});
log('🔄 ' + name + ' 恢复播放', 'blue');
}
}, 500);
}
};
media.addEventListener('pause', resumePlay);
var onVideoEnd = function() {
log('✅ ' + name + ' 播放完成', 'green');
media.removeEventListener('pause', resumePlay);
media.removeEventListener('ended', onVideoEnd);
if (currentVideoInterval) { clearInterval(currentVideoInterval); currentVideoInterval = null; }
if (currentVideoQuizObserver) { try { currentVideoQuizObserver.disconnect(); } catch(e) {} currentVideoQuizObserver = null; }
stopQuizPoll();
stopQuizObserverGuard();
completeCurrentTask();
};
media.addEventListener('ended', onVideoEnd);
if (media.ended) { onVideoEnd(); }
} else if (media.ended) {
if (currentVideoInterval) { clearInterval(currentVideoInterval); currentVideoInterval = null; }
if (currentVideoQuizObserver) { try { currentVideoQuizObserver.disconnect(); } catch(e) {} currentVideoQuizObserver = null; }
stopQuizPoll();
stopQuizObserverGuard();
completeCurrentTask();
} else if (media.paused) {
// 主动保活:任何原因暂停(含平台检测),无弹题时自动续播
var popup = innerDoc.querySelector('.ans-videoquiz, .TiMu, .videoquiz');
if (!popup) { media.play().catch(function(){}); }
}
}
}, 1500);
}
function processAudio(dom, obj) {
if (!CONFIG.handleAudio) {
log('ℹ️ 用户设置不处理音频任务', 'orange');
completeCurrentTask();
return;
}
var isPassed = obj.isPassed;
var name = obj.property.name;
if (!CONFIG.reviewMode && isPassed === true) {
log('✅ 音频:' + name + ' 已完成,跳过', 'green');
completeCurrentTask();
return;
}
log('🎵 处理音频:' + name + ',等待5秒后完成', 'purple');
setTimeout(function() { completeCurrentTask(); }, 5000);
}
function processBook(dom, obj) {
var jobId = obj['property']['jobid'];
var name = obj['property']['bookname'];
var jtoken = obj['jtoken'];
var knowledgeId = defaults['knowledgeid'];
var courseId = defaults['courseid'];
var clazzId = defaults['clazzId'];
if (isTaskCompleted(obj)) {
log('✅ 读书:' + name + ' 已完成,跳过', 'green');
completeCurrentTask();
return;
}
$.ajax({
url: LOCATION.protocol + "//" + LOCATION.host + '/ananas/job?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + Date.now(),
method: 'GET',
success: function(res) { log('📚 读书:' + name + (res.msg || '完成'), 'green'); completeCurrentTask(); },
error: function() {
log('❌ 读书:' + name + ' 处理失败,3秒后重试', 'red');
isProcessing = false;
setTimeout(function() { processBook(dom, obj); }, 3000);
}
});
}
function processDocument(dom, obj) {
var jobId = obj['property']['jobid'];
var name = obj['property']['name'];
var jtoken = obj['jtoken'];
var knowledgeId = defaults['knowledgeid'];
var courseId = defaults['courseid'];
var clazzId = defaults['clazzId'];
if (isTaskCompleted(obj)) {
log('✅ 文档:' + name + ' 已完成,跳过', 'green');
completeCurrentTask();
return;
}
$.ajax({
url: LOCATION.protocol + "//" + LOCATION.host + '/ananas/job/document?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + Date.now(),
method: 'GET',
success: function(res) { log('📄 文档:' + name + (res.msg || '完成'), 'green'); completeCurrentTask(); },
error: function() {
log('❌ 文档:' + name + ' 处理失败,3秒后重试', 'red');
isProcessing = false;
setTimeout(function() { processDocument(dom, obj); }, 3000);
}
});
}
function processRead(dom, obj) {
var jobId = obj['property']['jobid'];
var name = obj['property']['title'];
var jtoken = obj['jtoken'];
var knowledgeId = defaults['knowledgeid'];
var courseId = defaults['courseid'];
var clazzId = defaults['clazzId'];
if (isTaskCompleted(obj)) {
log('✅ 阅读:' + name + ' 已完成,跳过', 'green');
completeCurrentTask();
return;
}
$.ajax({
url: LOCATION.protocol + '//' + LOCATION.host + '/ananas/job/readv2?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + Date.now(),
method: 'GET',
success: function(res) { log('📖 阅读:' + name + (res.msg || '完成'), 'green'); completeCurrentTask(); },
error: function() {
log('❌ 阅读:' + name + ' 处理失败,3秒后重试', 'red');
isProcessing = false;
setTimeout(function() { processRead(dom, obj); }, 3000);
}
});
}
function processQuiz(dom, obj) {
if (!CONFIG.handleQuiz) {
log('ℹ️ 用户设置不自动处理测验', 'orange');
completeCurrentTask();
return;
}
var isDo = true;
if (CONFIG.taskOnly && obj['jobid'] == undefined) { isDo = false; }
if (isDo) {
if (obj['jobid'] !== undefined) {
var phoneWeb = LOCATION.protocol + '//' + LOCATION.host + '/work/phone/work?workId=' + obj['jobid'].replace('work-', '') + '&courseId=' + defaults['courseid'] + '&clazzId=' + defaults['clazzId'] + '&knowledgeId=' + defaults['knowledgeid'] + '&jobId=' + obj['jobid'] + '&enc=' + obj['enc'];
log('📝 准备处理测验', 'purple');
setTimeout(function() { startPhoneQuiz(0, dom, phoneWeb, obj); }, 3000);
} else {
setTimeout(function() { startPCQuiz(0, dom, obj); }, 3000);
}
} else {
log('ℹ️ 用户设置只处理属于任务点的任务', 'orange');
completeCurrentTask();
}
}
function startPhoneQuiz(index, doms, phoneWeb, taskObj) {
if (index == doms.length) { log('✅ 此页面全部测验已处理完毕', 'green'); completeCurrentTask(); return; }
getElement($(doms[index]).contents()[0], 'iframe').then(function(iframe) {
if (!iframe) { setTimeout(function() { startPhoneQuiz(index, doms, phoneWeb, taskObj); }, 5000); return; }
var workIframe = $(iframe);
var workStatus = workIframe.contents().find('.newTestCon .newTestTitle .testTit_status').text().trim();
if (!workStatus) { domList.splice(0, 1); isProcessing = false; setTimeout(switchMission, 2000); return; }
if (workStatus.indexOf("待做") != -1 || workStatus.indexOf("待完成") != -1 || workStatus.indexOf("未达到及格线") != -1) {
workIframe.attr('src', phoneWeb);
getElement($(doms[index]).contents()[0], 'iframe[src="' + phoneWeb + '"]').then(function() {
setTimeout(function() { doPhoneQuiz(workIframe.contents(), taskObj); }, 3000);
});
} else if (workStatus.indexOf('待批阅') != -1) {
taskList.splice(0, 1); domList.splice(0, 1);
log('⚠️ 测验待批阅,跳过', 'red');
completeCurrentTask();
} else if (workStatus.indexOf('已完成') != -1 || workStatus.indexOf('已交') != -1) {
log('✅ 测验已完成,跳过', 'green');
completeCurrentTask();
} else {
taskList.splice(0, 1); domList.splice(0, 1);
log('⚠️ 未知状态,跳过', 'red');
completeCurrentTask();
}
});
}
function doPhoneQuiz($dom, taskObj) {
var $cy = $dom.find('.Wrappadding form');
submitBtn = $cy.find('.zquestions .zsubmit .btn-ok-bottom');
okBtn = $dom.find('#okBtn');
saveBtn = $cy.find('.zquestions .zsubmit .btn-save');
var questionList = $cy.find('.zquestions .Py-mian1');
processPhoneQuestions(0, questionList, taskObj);
}
function processPhoneQuestions(index, questionList, taskObj) {
if (index == questionList.length) {
var decision = getSubmitDecision();
if (decision.action === 'submit') {
log('✅ 测验处理完成,准备' + decision.reason + '。', 'green');
setTimeout(function() {
submitBtn.click();
setTimeout(function() { okBtn.click(); log('✅ 提交成功', 'green'); completeCurrentTask(); }, 3000);
}, 5000);
} else {
log('💾 ' + decision.reason + ',自动保存', 'green');
setTimeout(function() {
saveBtn.click();
setTimeout(function() { log('✅ 保存成功', 'green'); completeCurrentTask(); }, 3000);
}, 5000);
}
return;
}
var contextWindow = questionList[index] ? (questionList[index].ownerDocument.defaultView || unsafeWindow) : unsafeWindow;
var $question = $(questionList[index]);
var questionHtml = $question.find('.Py-m1-title').html() || $question.html() || '';
var typeName = '';
var bracketMatch = questionHtml.match(/\[(.*?)\]/);
var _hash = atob('YW13eGI=');
if (bracketMatch && bracketMatch[1]) { typeName = bracketMatch[1]; }
if (!typeName) { var chineseMatch = questionHtml.match(/(单选题|多选题|填空题|判断题|简答题)/); if (chineseMatch) { typeName = chineseMatch[1]; } }
var typeMap = { '单选题': 0, '多选题': 1, '填空题': 2, '判断题': 3, '简答题': 4 };
var questionType = typeMap[typeName];
if (questionType === undefined) { questionType = getQuestionTypeFromText(questionHtml); }
if (questionType === undefined) {
if ($question.find('.answerList.singleChoice li').length) questionType = 0;
else if ($question.find('.answerList.multiChoice li').length) questionType = 1;
else if ($question.find('.blankList2 input').length) questionType = 2;
else if ($question.find('.answerList.panduan li').length) questionType = 3;
else if ($question.find('textarea').length) questionType = 4;
}
if (questionType === undefined) {
log('⚠️ 第' + (index + 1) + '题无法识别题型,跳过', 'orange');
setTimeout(function() { processPhoneQuestions(index + 1, questionList, taskObj); }, getRandomInterval());
return;
}
var cleanedQuestion = tidyQuestion(questionHtml);
cleanedQuestion = cleanedQuestion.replace(/\[.*?\]/, '').trim();
cleanedQuestion = cleanedQuestion.replace(/^\d+[.、]?\s*/, '');
var checkAnswered = function() {
if (questionType == 0 || questionType == 1) {
var $opts = questionType == 0 ? $question.find('.answerList.singleChoice li') : $question.find('.answerList.multiChoice li');
for (var i = 0; i < $opts.length; i++) { if ($($opts[i]).attr('aria-label')) return true; }
} else if (questionType == 2) {
var $inputs = $question.find('.blankList2 input');
if ($inputs.length && $inputs.first().val() && $inputs.first().val().trim() !== '') return true;
var $editorBlocks = $question.find('[data-editorindex]');
if ($editorBlocks.length) {
var hasContent = false;
$editorBlocks.each(function() { var itemId = $(this).attr('data-itemid'); if (itemId && $('#answer' + itemId).val() && $('#answer' + itemId).val().trim() !== '') { hasContent = true; } });
if (hasContent) return true;
}
} else if (questionType == 3) {
var $pd = $question.find('.answerList.panduan li');
for (var i = 0; i < $pd.length; i++) { if ($($pd[i]).attr('aria-label')) return true; }
} else if (questionType == 4) {
var $ta = $question.find('textarea[name^="answer"]');
if ($ta.length && $ta.first().val() && $ta.first().val().trim() !== '') return true;
var $editorBlocks = $question.find('[data-editorindex]');
if ($editorBlocks.length) {
var hasContent = false;
$editorBlocks.each(function() { var itemId = $(this).attr('data-itemid'); if (itemId && $('#answer' + itemId).val() && $('#answer' + itemId).val().trim() !== '') { hasContent = true; } });
if (hasContent) return true;
}
}
return false;
};
if (checkAnswered()) {
log('📌 第' + (index + 1) + '题已作答,跳过', 'green');
setTimeout(function() { processPhoneQuestions(index + 1, questionList, taskObj); }, 30);
return;
}
var $opts = [];
var optsText = [];
var optionsData = [];
var pureQuestion = cleanedQuestion;
if (questionType == 0 || questionType == 1) {
$opts = questionType == 0 ? $question.find('.answerList.singleChoice li') : $question.find('.answerList.multiChoice li');
$opts.each(function() {
var rawText = tidyString($(this).html());
rawText = rawText.replace(/^[A-Z][\s]*[.、.))\s]+/, '');
rawText = rawText.replace(/^\([A-Z]\)[\s]*/, '');
rawText = rawText.replace(/^([A-Z])[\s]*/, '');
optsText.push(rawText);
});
optionsData = optsText;
} else if (questionType == 2) {
var blankCount = getBlankCount($question);
optionsData = [blankCount.toString()];
log('📝 填空题传入空数量: ' + blankCount, 'blue');
} else if (questionType == 3) {
optionsData = ["对", "错"];
} else if (questionType == 4) {
optionsData = ["1"];
}
getAnswer(questionType, pureQuestion, optionsData).then(function(answer) {
if (answer == '暂无答案' || !answer) {
log('⚠️ 第' + (index + 1) + '题无法获取答案,跳过', 'red');
setTimeout(function() { processPhoneQuestions(index + 1, questionList, taskObj); }, getRandomInterval());
return;
}
if (CONFIG.insertAnswer) { $question.find('.Py-m1-title').html($question.find('.Py-m1-title').html() + '📖 ' + answer + '
'); }
if (questionType == 0) {
var normalizedOpts = optsText.map(function(opt) { return normalizeForCompare(opt); });
var normalizedAnswer = normalizeForCompare(answer);
var idx = normalizedOpts.findIndex(function(t) { return t === normalizedAnswer; });
if (idx === -1) { idx = normalizedOpts.findIndex(function(t) { return t.indexOf(normalizedAnswer) !== -1 || normalizedAnswer.indexOf(t) !== -1; }); }
if (idx != -1) { $question.find('.answerList.singleChoice li').eq(idx).click(); log('✅ 单选题已选: ' + optsText[idx], 'green'); }
else { log('⚠️ 未找到匹配选项: ' + answer, 'orange'); }
} else if (questionType == 1) {
var hitIdx = matchMultiChoiceIndices(optsText, answer);
if (hitIdx.length > 0) {
hitIdx.forEach(function(i, k) {
setTimeout(function() { $($opts[i]).click(); }, 300 * (k + 1));
});
log('✅ 多选题已选 ' + hitIdx.length + ' 项: ' + hitIdx.map(function(i){return optsText[i];}).join(' | '), 'green');
} else {
log('⚠️ 多选题未匹配到任何选项,答案: ' + answer, 'orange');
}
} else if (questionType == 2) {
fillBlankAnswer($question, answer, true, contextWindow);
} else if (questionType == 3) {
var trueKeywords = '正确|是|对|√|T|ri';
var $pd = $question.find('.answerList.panduan li');
if (answer && answer.trim() !== '' && (trueKeywords.indexOf(answer) != -1 || trueKeywords.toLowerCase().indexOf(answer.toLowerCase()) != -1)) {
$pd.each(function(i, t) { if ($(t).attr('val-param') == 'true') { $(t).click(); log('✅ 判断题自动选择: 正确 (接口返回: ' + answer + ')', 'green'); } });
} else {
$pd.each(function(i, t) { if ($(t).attr('val-param') == 'false') { $(t).click(); log('✅ 判断题自动选择: 错误 (接口返回: ' + answer + ')', 'green'); } });
}
} else if (questionType == 4) {
fillShortAnswer($question, answer, true, contextWindow);
}
log('✅ 第' + (index + 1) + '题自动答题成功', 'green');
setTimeout(function() { processPhoneQuestions(index + 1, questionList, taskObj); }, getRandomInterval());
}).catch(function(err) {
log('⚠️ 第' + (index + 1) + '题获取答案失败: ' + err, 'orange');
setTimeout(function() { processPhoneQuestions(index + 1, questionList, taskObj); }, getRandomInterval());
});
}
function startPCQuiz(index, doms, taskObj) {
if (index == doms.length) { log('✅ 此页面全部测验已处理完毕', 'green'); completeCurrentTask(); return; }
getElement($(doms[index]).contents()[0], 'iframe').then(function(iframe) {
if (!iframe) { setTimeout(function() { startPCQuiz(index, doms, taskObj); }, 5000); return; }
var workIframe = $(iframe);
var workStatus = workIframe.contents().find(".newTestCon .newTestTitle .testTit_status").text().trim();
if (!workStatus) { domList.splice(0, 1); isProcessing = false; setTimeout(switchMission, 2000); return; }
if (workStatus.indexOf("待做") != -1 || workStatus.indexOf("待完成") != -1) {
log('📝 准备处理测验', 'purple');
setTimeout(function() { doPCQuiz(index, doms, iframe, taskObj); }, 5000);
} else if (workStatus.indexOf('待批阅') != -1) {
taskList.splice(0, 1); domList.splice(0, 1);
log('⚠️ 测验待批阅,跳过', 'red');
completeCurrentTask();
} else if (workStatus.indexOf('已完成') != -1 || workStatus.indexOf('已交') != -1) {
log('✅ 测验已完成,跳过', 'green');
completeCurrentTask();
} else {
taskList.splice(0, 1); domList.splice(0, 1);
log('⚠️ 未知状态,跳过', 'red');
completeCurrentTask();
}
});
}
function doPCQuiz(index, doms, dom, taskObj) {
frameContent = $(dom).contents();
var $cyHtml = frameContent.find('.CeYan');
var questionList = $cyHtml.find('.TiMu');
submitBtn = frameContent.find(".ZY_sub").find(".btnSubmit");
saveBtn = frameContent.find(".ZY_sub").find(".btnSave");
processPCQuestions(index, doms, 0, questionList, taskObj);
}
function processPCQuestions(index, doms, qIndex, questionList, taskObj) {
if (qIndex == questionList.length) {
var decision = getSubmitDecision();
if (decision.action === 'submit') {
log('✅ 测验处理完成,准备' + decision.reason + '。', 'green');
setTimeout(function() {
submitBtn.click();
setTimeout(function() { frameContent.find('#confirmSubWin > div > div > a.bluebtn').click(); log('✅ 提交成功', 'green'); completeCurrentTask(); }, 3000);
}, 5000);
} else {
log('💾 ' + decision.reason + ',自动保存', 'green');
setTimeout(function() {
saveBtn.click();
setTimeout(function() { log('✅ 保存成功', 'green'); completeCurrentTask(); }, 3000);
}, 5000);
}
return;
}
var $question = $(questionList[qIndex]);
var questionHtml = $question.find('.Zy_TItle.clearfix > div').html() || $question.html() || '';
var typeName = '';
var bracketMatch = questionHtml.match(/【(.*?)】/);
if (bracketMatch && bracketMatch[1]) { typeName = bracketMatch[1]; }
if (!typeName) { var chineseMatch = questionHtml.match(/(单选题|多选题|填空题|判断题|简答题)/); if (chineseMatch) { typeName = chineseMatch[1]; } }
var typeMap = { '单选题': 0, '多选题': 1, '填空题': 2, '判断题': 3, '简答题': 4 };
var questionType = typeMap[typeName];
if (questionType === undefined) { questionType = getQuestionTypeFromText(questionHtml); }
if (questionType === undefined) {
if ($question.find('.Zy_ulTop li').length) { questionType = $question.find('input[type="checkbox"]').length ? 1 : 0; }
else if ($question.find('.Zy_ulTk .XztiHover1').length) { questionType = 2; }
else { questionType = 4; }
}
var cleanedQuestion = tidyQuestion(questionHtml);
cleanedQuestion = cleanedQuestion.replace(/【.*?】/, '').trim();
cleanedQuestion = cleanedQuestion.replace(/^\d+[.、]?\s*/, '');
var $opts = [];
var optsText = [];
var optionsData = [];
var pureQuestion = cleanedQuestion;
if (questionType == 0 || questionType == 1) {
$opts = $question.find('.Zy_ulTop li a');
$opts.each(function() {
var rawText = tidyString($(this).html());
rawText = rawText.replace(/^[A-Z][\s]*[.、.))\s]+/, '');
rawText = rawText.replace(/^\([A-Z]\)[\s]*/, '');
rawText = rawText.replace(/^([A-Z])[\s]*/, '');
optsText.push(rawText);
});
optionsData = optsText;
} else if (questionType == 2) {
var blankCount = getBlankCount($question);
optionsData = [blankCount.toString()];
} else if (questionType == 3) {
optionsData = ["对", "错"];
} else if (questionType == 4) {
optionsData = ["1"];
}
getAnswer(questionType, pureQuestion, optionsData).then(function(answer) {
if (answer && answer != '暂无答案') {
if (CONFIG.insertAnswer) { $question.find('.Zy_TItle.clearfix > div').html($question.find('.Zy_TItle.clearfix > div').html() + '📖 ' + answer + '
'); }
if (questionType == 0) {
var normalizedOpts = optsText.map(function(opt) { return normalizeForCompare(opt); });
var normalizedAnswer = normalizeForCompare(answer);
var idx = normalizedOpts.findIndex(function(t) { return t === normalizedAnswer; });
if (idx === -1) { idx = normalizedOpts.findIndex(function(t) { return t.indexOf(normalizedAnswer) !== -1 || normalizedAnswer.indexOf(t) !== -1; }); }
if (idx != -1) { $($opts[idx]).parent().click(); log('✅ PC单选题已选: ' + optsText[idx], 'green'); }
else { log('⚠️ 未找到匹配选项: ' + answer, 'orange'); }
} else if (questionType == 1) {
var hitIdx = matchMultiChoiceIndices(optsText, answer);
if (hitIdx.length > 0) {
hitIdx.forEach(function(i, k) {
setTimeout(function() { $($opts[i]).parent().click(); }, 300 * (k + 1));
});
log('✅ PC多选题已选 ' + hitIdx.length + ' 项: ' + hitIdx.map(function(i){return optsText[i];}).join(' | '), 'green');
} else {
log('⚠️ PC多选题未匹配到任何选项,答案: ' + answer, 'orange');
}
} else if (questionType == 2) {
fillBlankAnswer($question, answer, false, null);
} else if (questionType == 3) {
var trueKeywords = '正确|是|对|√|T|ri';
var $pdContainer = $question.find('.Zy_ulTop li');
if ($pdContainer.length === 0) { $pdContainer = $question.find('.stem_answer .answer_p').parent(); }
if (answer && answer.trim() !== '' && (trueKeywords.indexOf(answer) != -1 || trueKeywords.toLowerCase().indexOf(answer.toLowerCase()) != -1)) {
var clicked = false;
$pdContainer.each(function(i, t) {
var $opt = $(t).find('a, .answer_p');
if ($opt.length === 0) $opt = $(t);
var valAttr = $(t).find('span').attr('val-param') || $(t).attr('val-param');
if (valAttr == 'true') { $(t).click(); clicked = true; log('✅ PC判断题自动选择: 正确 (接口返回: ' + answer + ')', 'green'); }
});
if (!clicked && $pdContainer.length > 0) { $($pdContainer[0]).click(); log('✅ PC判断题自动选择: 正确(默认第一个) (接口返回: ' + answer + ')', 'green'); }
} else {
var clicked = false;
$pdContainer.each(function(i, t) {
var valAttr = $(t).find('span').attr('val-param') || $(t).attr('val-param');
if (valAttr == 'false') { $(t).click(); clicked = true; log('✅ PC判断题自动选择: 错误 (接口返回: ' + answer + ')', 'green'); }
});
if (!clicked && $pdContainer.length > 1) { $($pdContainer[1]).click(); log('✅ PC判断题自动选择: 错误(默认第二个) (接口返回: ' + answer + ')', 'green'); }
else if (!clicked && $pdContainer.length === 1) { $($pdContainer[0]).click(); log('✅ PC判断题自动选择: 错误(唯一选项) (接口返回: ' + answer + ')', 'green'); }
}
} else if (questionType == 4) {
fillShortAnswer($question, answer, false, null);
}
log('✅ PC第' + (qIndex + 1) + '题自动答题成功', 'green');
} else {
log('⚠️ PC第' + (qIndex + 1) + '题无法获取答案', 'orange');
}
setTimeout(function() { processPCQuestions(index, doms, qIndex + 1, questionList, taskObj); }, getRandomInterval());
}).catch(function() {
setTimeout(function() { processPCQuestions(index, doms, qIndex + 1, questionList, taskObj); }, getRandomInterval());
});
}
function processHomework() {
log('📝 开始处理作业', 'green');
var $homeworkTable = $('.mark_table').find('form');
var questionList = $homeworkTable.find('.questionLi');
doHomework(0, questionList);
}
function doHomework(index, questionList) {
if (index == questionList.length) { log('✅ 作业题目已全部完成', 'green'); return; }
var $question = $(questionList[index]);
var typeName = $question.attr('typename');
var typeMap = { '单选题': 0, '多选题': 1, '填空题': 2, '判断题': 3, '简答题': 4 };
var questionType = typeMap[typeName];
var questionFull = $question.find('.mark_name').html() || '';
var cleanedQuestion = tidyQuestion(questionFull);
cleanedQuestion = cleanedQuestion.replace(/^[(].*?[)]/, '').trim();
cleanedQuestion = cleanedQuestion.replace(/^\d+[.、]?\s*/, '');
if (questionType === undefined) { questionType = getQuestionTypeFromText(questionFull); }
if (questionType === undefined) {
var answerTmpArr = $question.find('.stem_answer').find('.answer_p');
if (answerTmpArr && answerTmpArr.length > 0) { questionType = $question.find('input[type="checkbox"]').length ? 1 : 0; }
else if ($question.find('.stem_answer').find('.divText textarea').length) { questionType = 4; }
}
if (questionType === undefined) {
log('⚠️ 作业第' + (index + 1) + '题无法识别题型,跳过', 'orange');
setTimeout(function() { doHomework(index + 1, questionList); }, getRandomInterval());
return;
}
var checkAnswered = function() {
if (questionType == 0 || questionType == 1) {
var $opts = $question.find('.stem_answer .answer_p');
for (var i = 0; i < $opts.length; i++) { if ($($opts[i]).parent().find('span').attr('class') && $($opts[i]).parent().find('span').attr('class').indexOf('check_answer') != -1) { return true; } }
} else if (questionType == 2) {
var $inputs = $question.find('.stem_answer .Answer .divText .textDIV textarea');
if ($inputs.length && $inputs.val() && $inputs.val().trim() !== '') return true;
} else if (questionType == 3) {
var $opts = $question.find('.stem_answer .answer_p');
for (var i = 0; i < $opts.length; i++) { if ($($opts[i]).parent().find('span').attr('class') && $($opts[i]).parent().find('span').attr('class').indexOf('check_answer') != -1) { return true; } }
} else if (questionType == 4) {
var $ta = $question.find('.stem_answer .eidtDiv textarea');
if ($ta.length && $ta.val() && $ta.val().trim() !== '') return true;
}
return false;
};
if (checkAnswered()) {
log('📌 作业第' + (index + 1) + '题已作答,跳过', 'green');
setTimeout(function() { doHomework(index + 1, questionList); }, 30);
return;
}
var $opts = [];
var optsText = [];
var optionsData = [];
var pureQuestion = cleanedQuestion;
if (questionType == 0 || questionType == 1) {
$opts = $question.find('.stem_answer .answer_p');
$opts.each(function() {
var rawText = tidyString($(this).html());
rawText = rawText.replace(/^[A-Z][\s]*[.、.))\s]+/, '');
rawText = rawText.replace(/^\([A-Z]\)[\s]*/, '');
rawText = rawText.replace(/^([A-Z])[\s]*/, '');
optsText.push(rawText);
});
optionsData = optsText;
} else if (questionType == 2) {
var blankCount = getBlankCount($question);
optionsData = [blankCount.toString()];
} else if (questionType == 3) {
optionsData = ["对", "错"];
} else if (questionType == 4) {
optionsData = ["1"];
}
getAnswer(questionType, pureQuestion, optionsData).then(function(answer) {
if (answer && answer != '暂无答案') {
if (CONFIG.insertAnswer) { $question.find('.mark_name').html($question.find('.mark_name').html() + '📖 ' + answer + '
'); }
if (questionType == 0) {
var normalizedOpts = optsText.map(function(opt) { return normalizeForCompare(opt); });
var normalizedAnswer = normalizeForCompare(answer);
var idx = normalizedOpts.findIndex(function(t) { return t === normalizedAnswer; });
if (idx === -1) { idx = normalizedOpts.findIndex(function(t) { return t.indexOf(normalizedAnswer) !== -1 || normalizedAnswer.indexOf(t) !== -1; }); }
if (idx != -1) { $($opts[idx]).parent().click(); log('✅ 作业单选题已选: ' + optsText[idx], 'green'); }
else { log('⚠️ 未找到匹配选项: ' + answer, 'orange'); }
} else if (questionType == 1) {
var hitIdx = matchMultiChoiceIndices(optsText, answer);
if (hitIdx.length > 0) {
hitIdx.forEach(function(i, k) {
setTimeout(function() { $($opts[i]).parent().click(); }, 300 * (k + 1));
});
log('✅ 作业多选题已选 ' + hitIdx.length + ' 项: ' + hitIdx.map(function(i){return optsText[i];}).join(' | '), 'green');
} else {
log('⚠️ 作业多选题未匹配到任何选项,答案: ' + answer, 'orange');
}
} else if (questionType == 2) {
fillBlankAnswer($question, answer, false, null);
} else if (questionType == 3) {
var trueKeywords = '正确|是|对|√|T|ri';
var $pdContainer = $question.find('.stem_answer .answer_p').parent();
if (answer && answer.trim() !== '' && (trueKeywords.indexOf(answer) != -1 || trueKeywords.toLowerCase().indexOf(answer.toLowerCase()) != -1)) {
if ($pdContainer.length > 0) { $($pdContainer[0]).click(); log('✅ 作业判断题自动选择: 正确 (接口返回: ' + answer + ')', 'green'); }
} else {
if ($pdContainer.length > 1) { $($pdContainer[1]).click(); log('✅ 作业判断题自动选择: 错误 (接口返回: ' + answer + ')', 'green'); }
else if ($pdContainer.length === 1) { $($pdContainer[0]).click(); log('✅ 作业判断题自动选择: 错误(唯一选项) (接口返回: ' + answer + ')', 'green'); }
}
} else if (questionType == 4) {
fillShortAnswer($question, answer, false, null);
}
log('✅ 作业第' + (index + 1) + '题自动答题成功', 'green');
} else {
log('⚠️ 作业第' + (index + 1) + '题无法获取答案', 'orange');
}
setTimeout(function() { doHomework(index + 1, questionList); }, getRandomInterval());
}).catch(function() {
setTimeout(function() { doHomework(index + 1, questionList); }, getRandomInterval());
});
}
function processExam() {
var $examTable = $('.mark_table').find('.whiteDiv');
var questionFull = tidyString($examTable.find('h3.mark_name').html().trim());
var typeName = questionFull.match(/[(](.*?),.*?分[)]|$/)[1];
var typeMap = { '单选题': 0, '多选题': 1, '填空题': 2, '判断题': 3, '简答题': 4 };
var questionType = typeMap[typeName];
var cleanedQuestion = tidyQuestion(questionFull.replace(/[(].*?分[)]/, '').replace(/^\s*/, ''));
cleanedQuestion = cleanedQuestion.replace(/^\d+[.、]?\s*/, '');
var $answerDom = $examTable.find('#submitTest').find('.stem_answer');
if (questionType === undefined) { questionType = getQuestionTypeFromText(questionFull); }
if (questionType === undefined) {
var $opts = $answerDom.find('.clearfix.answerBg .fl.answer_p');
if ($opts.length) { questionType = $answerDom.find('input[type="checkbox"]').length ? 1 : 0; }
else if ($answerDom.find('.Answer .divText .subEditor textarea').length) { questionType = 4; }
}
if (questionType === undefined) {
log('⚠️ 考试题目无法识别题型,跳过', 'orange');
goToNextExam();
return;
}
var checkAnswered = function() {
if (questionType == 0 || questionType == 1) {
var $opts = $answerDom.find('.clearfix.answerBg .fl.answer_p');
for (var i = 0; i < $opts.length; i++) { if ($($opts[i]).parent().find('span').attr('class') && $($opts[i]).parent().find('span').attr('class').indexOf('check_answer') != -1) { return true; } }
} else if (questionType == 2) {
var $inputs = $answerDom.find('.Answer .divText .subEditor textarea');
if ($inputs.length && $inputs.val() && $inputs.val().trim() !== '') return true;
} else if (questionType == 4) {
var $ta = $answerDom.find('.subEditor textarea');
if ($ta.length && $ta.val() && $ta.val().trim() !== '') return true;
}
return false;
};
if (checkAnswered()) {
log('📌 考试此题已作答,跳过', 'green');
goToNextExam();
return;
}
var $opts = [];
var optsText = [];
var optionsData = [];
var pureQuestion = cleanedQuestion;
if (questionType == 0 || questionType == 1) {
$opts = $answerDom.find('.clearfix.answerBg .fl.answer_p');
$opts.each(function() {
var rawText = tidyString($(this).html());
rawText = rawText.replace(/^[A-Z][\s]*[.、.))\s]+/, '');
rawText = rawText.replace(/^\([A-Z]\)[\s]*/, '');
rawText = rawText.replace(/^([A-Z])[\s]*/, '');
optsText.push(rawText);
});
optionsData = optsText;
} else if (questionType == 2) {
var blankCount = getBlankCount($answerDom);
optionsData = [blankCount.toString()];
} else if (questionType == 4) {
optionsData = ["1"];
} else if (questionType == 3) {
optionsData = ["对", "错"];
}
getAnswer(questionType, pureQuestion, optionsData).then(function(answer) {
if (answer && answer != '暂无答案') {
if (CONFIG.insertAnswer) { $examTable.find('h3.mark_name').html($examTable.find('h3.mark_name').html() + '📖 ' + answer + ''); }
if (questionType == 0) {
var normalizedOpts = optsText.map(function(opt) { return normalizeForCompare(opt); });
var normalizedAnswer = normalizeForCompare(answer);
var idx = normalizedOpts.findIndex(function(t) { return t === normalizedAnswer; });
if (idx === -1) { idx = normalizedOpts.findIndex(function(t) { return t.indexOf(normalizedAnswer) !== -1 || normalizedAnswer.indexOf(t) !== -1; }); }
if (idx != -1) { $($opts[idx]).parent().click(); log('✅ 考试单选题已选: ' + optsText[idx], 'green'); }
else { log('⚠️ 未找到匹配选项: ' + answer, 'orange'); }
} else if (questionType == 1) {
var hitIdx = matchMultiChoiceIndices(optsText, answer);
if (hitIdx.length > 0) {
hitIdx.forEach(function(i, k) {
setTimeout(function() { $($opts[i]).parent().click(); }, 300 * (k + 1));
});
log('✅ 考试多选题已选 ' + hitIdx.length + ' 项: ' + hitIdx.map(function(i){return optsText[i];}).join(' | '), 'green');
} else {
log('⚠️ 考试多选题未匹配到任何选项,答案: ' + answer, 'orange');
}
} else if (questionType == 2) {
fillBlankAnswer($answerDom, answer, false, null);
} else if (questionType == 3) {
var trueKeywords = '正确|是|对|√|T|ri';
var $pdContainer = $answerDom.find('.clearfix.answerBg .fl.answer_p').parent();
if (answer && answer.trim() !== '' && (trueKeywords.indexOf(answer) != -1 || trueKeywords.toLowerCase().indexOf(answer.toLowerCase()) != -1)) {
if ($pdContainer.length > 0) { $($pdContainer[0]).click(); log('✅ 考试判断题自动选择: 正确 (接口返回: ' + answer + ')', 'green'); }
} else {
if ($pdContainer.length > 1) { $($pdContainer[1]).click(); log('✅ 考试判断题自动选择: 错误 (接口返回: ' + answer + ')', 'green'); }
else if ($pdContainer.length === 1) { $($pdContainer[0]).click(); log('✅ 考试判断题自动选择: 错误(唯一选项) (接口返回: ' + answer + ')', 'green'); }
}
} else if (questionType == 4) {
fillShortAnswer($answerDom, answer, false, null);
}
log('✅ 考试自动答题成功', 'green');
} else {
log('⚠️ 考试无法获取答案', 'orange');
}
setTimeout(function() { goToNextExam(); }, getRandomInterval());
}).catch(function() {
setTimeout(function() { goToNextExam(); }, getRandomInterval());
});
}
function goToNextExam() {
if (CONFIG.autoNextExam) {
var $nextBtn = $('.mark_table .whiteDiv .nextDiv a.jb_btn');
var delay = CONFIG.examNextDelay ? 2000 + (Math.floor(Math.random() * 5 + 1) * 1000) : 2000;
setTimeout(function() { $nextBtn.click(); }, delay);
log('⏭️ ' + (delay/1000) + '秒后自动跳转下一题', 'blue');
}
}
function decryptFont() {
var TyprInstance = null;
var md5Instance = null;
if (typeof unsafeWindow !== 'undefined' && unsafeWindow.Typr) { TyprInstance = unsafeWindow.Typr; }
else if (typeof window !== 'undefined' && window.Typr) { TyprInstance = window.Typr; }
else if (typeof Typr !== 'undefined') { TyprInstance = Typr; }
if (typeof unsafeWindow !== 'undefined' && unsafeWindow.md5) { md5Instance = unsafeWindow.md5; }
else if (typeof window !== 'undefined' && window.md5) { md5Instance = window.md5; }
else if (typeof md5 !== 'undefined') { md5Instance = md5; }
if (!TyprInstance || !md5Instance || !TyprInstance.U) { setTimeout(function() { decryptFont(); }, 1000); return; }
var $tip = $('style:contains(font-cxsecret)');
if (!$tip.length) return;
try {
var styleText = $tip.text();
var fontBase64 = null;
var match1 = styleText.match(/base64,([\w\W]+?)'/);
if (match1 && match1[1]) fontBase64 = match1[1];
if (!fontBase64) {
var match2 = styleText.match(/url\("data:application\/font-woff;charset=utf-8;base64,([\w\W]+?)"\)/);
if (match2 && match2[1]) fontBase64 = match2[1];
}
if (!fontBase64) {
var match3 = styleText.match(/url\('data:application\/font-woff;charset=utf-8;base64,([\w\W]+?)'\)/);
if (match3 && match3[1]) fontBase64 = match3[1];
}
if (!fontBase64) return;
var fontUint8Array = base64ToUint8Array(fontBase64);
var parsedFont = TyprInstance.parse(fontUint8Array);
if (!parsedFont || parsedFont.length === 0) return;
var font = parsedFont[0];
var tableJson = GM_getResourceText('Table');
if (!tableJson) return;
var table;
try { table = JSON.parse(tableJson); } catch(e) { return; }
var $secretElements = $('.font-cxsecret');
if ($secretElements.length === 0) return;
var existingChars = new Set();
$secretElements.each(function() {
var html = $(this).html();
if (html) { for (var j = 0; j < html.length; j++) { existingChars.add(html.charCodeAt(j)); } }
});
if (existingChars.size === 0) return;
var match = {};
var charCodes = Array.from(existingChars);
log('🔓 发现 ' + charCodes.length + ' 个加密字符,开始解密...', 'blue');
for (var idx = 0; idx < charCodes.length; idx++) {
var i = charCodes[idx];
var glyph = TyprInstance.U.codeToGlyph(font, i);
if (!glyph) continue;
var path = TyprInstance.U.glyphToPath(font, glyph);
if (!path) continue;
var pathStr = JSON.stringify(path);
var hash = md5Instance(pathStr);
if (!hash) continue;
var hashKey = hash.slice(24);
var realChar = table[hashKey];
if (realChar !== undefined && realChar !== null && realChar !== 0) { match[i] = realChar; }
}
var matchCount = Object.keys(match).length;
if (matchCount === 0) return;
$secretElements.each(function() {
var $el = $(this);
var html = $el.html();
if (!html) return;
for (var code in match) {
var encryptedChar = String.fromCharCode(parseInt(code));
var realChar = String.fromCharCode(match[code]);
var escapedChar = encryptedChar.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
var regex = new RegExp(escapedChar, 'g');
html = html.replace(regex, realChar);
}
if ($el.html() !== html) { $el.html(html); $el.removeClass('font-cxsecret'); }
});
log('✅ 字体解密完成!已还原 ' + matchCount + ' 个字符', 'green');
} catch(e) { log('❌ 字体解密失败: ' + e.message, 'red'); }
}
function base64ToUint8Array(base64) {
var data = window.atob(base64);
var buf = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) buf[i] = data.charCodeAt(i);
return buf;
}
function getSettingsPanelHTML() {
function aiSlotRowHTML(i) {
var s = (getApiSlots()[i] || {});
var hasCustom = !MXWELL_MODELS.some(function(m) { return m.id === s.model; });
var sel = '';
MXWELL_MODELS.forEach(function(m) {
sel += '';
});
sel += '';
var tierIdx = MXWELL_TIERS.indexOf(s.tier);
if (tierIdx < 0) { tierIdx = 2; }
return '';
}
return '' +
'
' +
'
📚 学习通助手 v1.2.1 (按住拖动 · 右下角缩放)
' +
'[F9隐藏]' +
'' +
'
' +
'
' +
'
' +
'
' +
'
🤖 AI 自动搜题
' +
'
' +
'' +
'' +
'' +
'
' +
'
' +
'
3 个接口按 1→2→3 依次尝试,出答案即停;全失败直接选正确率高的。
' +
'
' + aiSlotRowHTML(0) + aiSlotRowHTML(1) + aiSlotRowHTML(2) + '
' +
'
' +
'' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
🧩 通用做题(任意网站)
' +
'
非学习通页面用这里:自动识别本页题目(单选/多选/填空/简答)并作答。
' +
'
' +
'
' +
'' +
'' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
' +
'
';
}
function speedNum(text) {
var s = String(text || '').replace(/倍速/g, '').replace(/x/gi, '').replace(/\s+/g, '').replace(/[^0-9.]/g, '');
var n = parseFloat(s);
return isFinite(n) && n > 0 ? n : 0;
}
function findSpeedOptions(doc) {
var list = [];
var seen = {};
var selectors = [
'#speedBox li', '#speedList li', '.speedBox li', '[class*="speedBox"] li',
'[class*="speedlist"] li', '.vjs-menu-content li', '.vjs-playback-rate-menu li',
'[data-speed]'
];
selectors.forEach(function(sel) {
var els = [];
try { els = doc.querySelectorAll(sel); } catch(e) {}
for (var i = 0; i < els.length; i++) {
var el = els[i];
var ds = el.getAttribute && el.getAttribute('data-speed');
var num = ds ? parseFloat(ds) : speedNum(el.textContent);
if (!isFinite(num) || num <= 0) continue;
var key = Math.round(num * 100);
if (seen[key]) continue;
seen[key] = true;
list.push({ num: num, el: el });
}
});
return list;
}
function nativeClick(el) {
if (!el) return;
try { el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); } catch(e) {}
try { el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true })); } catch(e) {}
try { el.click(); } catch(e) {}
try { el.dispatchEvent(new MouseEvent('click', { bubbles: true })); } catch(e) {}
}
function applyNativeSpeed(doc, media, force) {
var want;
if (CONFIG.auto2x === false || CONFIG.auto2x === 0) {
want = 1;
} else {
var opts = findSpeedOptions(doc);
want = opts.some(function(o) { return Math.abs(o.num - 2) < 0.05; }) ? 2 : (opts.length ? 1 : 2);
}
var current = 0;
try { current = media ? media.playbackRate : 0; } catch(e) {}
if (!force && Math.abs(current - want) < 0.05) { return want; }
var target = null;
findSpeedOptions(doc).forEach(function(o) {
if (Math.abs(o.num - want) < 0.05) { target = o; }
});
if (target) {
var menuBtn = null;
try {
menuBtn = doc.querySelector('.vjs-playback-rate, .vjs-menu-button, .speedBox, [class*="speedBox"]') ||
(media && media.closest ? media.closest('.vjs-control-bar') : null);
} catch(e) {}
if (menuBtn && target.el !== menuBtn) {
nativeClick(menuBtn);
setTimeout(function() { nativeClick(target.el); }, 120);
} else {
nativeClick(target.el);
}
setTimeout(function() {
try {
if (media && Math.abs(media.playbackRate - want) > 0.05) { media.playbackRate = want; }
} catch(e) {}
}, 400);
} else {
try {
if (media) { media.defaultPlaybackRate = want; media.playbackRate = want; }
} catch(e) {}
}
return want;
}
function applyVideoRateToAll() {
if (!CONFIG.auto2x) { return; }
function walk(doc, depth) {
if (!doc || depth > 4) return;
try {
var medias = doc.querySelectorAll('video, audio');
for (var m = 0; m < medias.length; m++) {
var media = medias[m];
if (!media.__smartRateGuard) {
media.__smartRateGuard = true;
var apply = function() { applyNativeSpeed(doc, media, false); };
media.addEventListener('play', apply);
media.addEventListener('ratechange', apply);
media.addEventListener('loadedmetadata', apply);
}
applyNativeSpeed(doc, media, false);
}
var frames = doc.querySelectorAll('iframe');
for (var i = 0; i < frames.length; i++) {
var f = frames[i];
var fd = f.contentDocument || (f.contentWindow && f.contentWindow.document);
if (fd) walk(fd, depth + 1);
}
} catch(e) {}
}
try { walk(document, 0); } catch(e) {}
}
function startVideoRateWatchdog() {
if (window.__rateWatchdogStarted) return;
window.__rateWatchdogStarted = true;
setInterval(function() { applyVideoRateToAll(); }, 2000);
}
// 面板右下角拖拽缩放(尺寸存 GM 值,下次打开保持)
function bindPanelResize(targetDoc, $box, boxEl) {
var grip = targetDoc.getElementById('ne-21resize');
if (!grip || !boxEl) { return; }
var resizing = false, rsX = 0, rsY = 0, rsW = 0, rsH = 0;
grip.addEventListener('mousedown', function(e) {
resizing = true;
var rect = boxEl.getBoundingClientRect();
rsX = e.clientX; rsY = e.clientY;
rsW = rect.width; rsH = rect.height;
if (boxEl.style.right !== 'auto') {
$box.css({ left: rect.left + 'px', top: rect.top + 'px', right: 'auto' });
}
e.preventDefault();
e.stopPropagation();
});
$(targetDoc).off('mousemove.panelResize mouseup.panelResize')
.on('mousemove.panelResize', function(e) {
if (!resizing) return;
var vw = $(targetDoc).width(), vh = $(targetDoc).height();
var w = rsW + (e.clientX - rsX);
var h = rsH + (e.clientY - rsY);
w = Math.max(300, Math.min(vw - 16, w));
h = Math.max(200, Math.min(vh - 16, h));
$box.css({ width: w + 'px', height: h + 'px' });
})
.on('mouseup.panelResize', function() {
if (!resizing) return;
resizing = false;
var rect = boxEl.getBoundingClientRect();
GM_setValue('panel_width', Math.round(rect.width));
GM_setValue('panel_height', Math.round(rect.height));
log('🖼️ 面板尺寸已保存: ' + Math.round(rect.width) + '×' + Math.round(rect.height), 'blue');
});
}
function bindSettingUI(targetDoc) {
var $box = $('#ne-21box', targetDoc);
var boxEl = $box[0];
if (boxEl) {
var savedLeft = GM_getValue('panel_left', null);
var savedTop = GM_getValue('panel_top', null);
var savedW = GM_getValue('panel_width', null);
var savedH = GM_getValue('panel_height', null);
if (savedW) { $box.css('width', Math.round(parseFloat(savedW)) + 'px'); }
if (savedH) { $box.css('height', Math.round(parseFloat(savedH)) + 'px'); }
if (savedLeft !== null && savedTop !== null) {
var vw = $(targetDoc).width();
var vh = $(targetDoc).height();
var maxLeft = Math.max(0, vw - boxEl.offsetWidth);
var maxTop = Math.max(0, vh - boxEl.offsetHeight);
savedLeft = Math.max(0, Math.min(maxLeft, savedLeft));
savedTop = Math.max(0, Math.min(maxTop, savedTop));
$box.css({ left: savedLeft + 'px', top: savedTop + 'px', right: 'auto' });
}
var $handle = $('#ne-21drag-handle', targetDoc);
var dragging = false, startX = 0, startY = 0, origLeft = 0, origTop = 0;
$handle.off('mousedown.panelDrag').on('mousedown.panelDrag', function(e) {
if ($(e.target).is('span, button, input, a')) return;
dragging = true;
var rect = boxEl.getBoundingClientRect();
origLeft = rect.left; origTop = rect.top;
startX = e.clientX; startY = e.clientY;
$box.css({ left: origLeft + 'px', top: origTop + 'px', right: 'auto' });
e.preventDefault();
});
$(targetDoc).off('mousemove.panelDrag mouseup.panelDrag')
.on('mousemove.panelDrag', function(e) {
if (!dragging) return;
var dx = e.clientX - startX, dy = e.clientY - startY;
var newLeft = origLeft + dx, newTop = origTop + dy;
var vw = $(targetDoc).width(), vh = $(targetDoc).height();
newLeft = Math.max(0, Math.min(vw - boxEl.offsetWidth, newLeft));
newTop = Math.max(0, Math.min(vh - boxEl.offsetHeight, newTop));
$box.css({ left: newLeft + 'px', top: newTop + 'px' });
})
.on('mouseup.panelDrag', function() {
if (!dragging) return;
dragging = false;
var rect = boxEl.getBoundingClientRect();
GM_setValue('panel_left', Math.round(rect.left));
GM_setValue('panel_top', Math.round(rect.top));
});
bindPanelResize(targetDoc, $box, boxEl);
}
$('#ne-21close', targetDoc).off('click').on('click', function() {
$('#ne-21box', targetDoc).css('display', 'none');
isBoxHidden = true;
});
var moreBtn = targetDoc.getElementById('moreSettingsBtn');
var moreSet = targetDoc.getElementById('moreSettings');
var visible = false;
if (moreBtn) {
moreBtn.onclick = function() {
moreSet.style.display = visible ? 'none' : 'block';
moreBtn.textContent = visible ? '⚙️ 更多设置' : '✖️ 关闭设置';
visible = !visible;
};
}
ensureManualBindings(targetDoc);
var apiModeSel = targetDoc.getElementById('apiModeSel');
var aiArea = targetDoc.getElementById('aiSlotsArea');
var bankArea = targetDoc.getElementById('bankArea');
function updateApiModeUI() {
if (!apiModeSel) return;
var isAi = apiModeSel.value === 'ai';
if (aiArea) { aiArea.style.display = isAi ? '' : 'none'; }
if (bankArea) { bankArea.style.display = isAi ? 'none' : ''; }
GM_setValue('api_mode', isAi ? 'ai' : 'bank');
}
if (apiModeSel) { apiModeSel.onchange = updateApiModeUI; }
updateApiModeUI();
var apiUrlInput = targetDoc.getElementById('apiUrlInput');
if (apiUrlInput && !apiUrlInput.value) { apiUrlInput.value = getApiUrlList().join(','); }
function slotFromInputs(i) {
var sel = targetDoc.getElementById('apiModelSel' + i);
var custom = targetDoc.getElementById('apiModelCustom' + i);
var model = sel && sel.value === '__custom'
? (custom ? String(custom.value).trim() : '')
: (sel ? sel.value : '');
if (!model) { model = DEFAULT_API_MODEL; }
var tierEl = targetDoc.getElementById('apiTier' + i);
var tier = tierEl ? (MXWELL_TIERS[parseInt(tierEl.value, 10)] || 'high') : 'high';
var urlEl = targetDoc.getElementById('apiUrl' + i);
var keyEl = targetDoc.getElementById('apiKey' + i);
var old = (getApiSlots()[i - 1] || {});
var key = old.key || '';
if (keyEl && String(keyEl.value).trim()) { key = String(keyEl.value).trim(); }
return { url: urlEl ? String(urlEl.value).trim() : '', model: model, tier: tier, key: key };
}
function fillSlotInputs(i) {
var s = (getApiSlots()[i - 1] || {});
var sel = targetDoc.getElementById('apiModelSel' + i);
var custom = targetDoc.getElementById('apiModelCustom' + i);
var hasCustom = !MXWELL_MODELS.some(function(m) { return m.id === s.model; });
if (sel) { sel.value = hasCustom ? '__custom' : (s.model || 'gpt-5.6-sol'); }
if (custom) {
custom.style.display = hasCustom ? '' : 'none';
custom.value = hasCustom ? (s.model || '') : '';
}
var tierIdx = MXWELL_TIERS.indexOf(s.tier);
if (tierIdx < 0) { tierIdx = 2; }
var tierEl = targetDoc.getElementById('apiTier' + i);
if (tierEl) { tierEl.value = tierIdx; }
var lbl = targetDoc.getElementById('apiTierLabel' + i);
if (lbl) { lbl.textContent = MXWELL_TIERS[tierIdx]; }
var keyEl = targetDoc.getElementById('apiKey' + i);
if (keyEl) { keyEl.placeholder = s.key ? '已设置' : '密钥'; }
}
[1, 2, 3].forEach(function(i) {
var sel = targetDoc.getElementById('apiModelSel' + i);
if (sel) {
sel.onchange = function() {
var c = targetDoc.getElementById('apiModelCustom' + i);
if (c) { c.style.display = this.value === '__custom' ? '' : 'none'; }
};
}
var tier = targetDoc.getElementById('apiTier' + i);
if (tier) {
tier.oninput = function() {
var lbl = targetDoc.getElementById('apiTierLabel' + i);
if (lbl) { lbl.textContent = MXWELL_TIERS[parseInt(this.value, 10)] || 'high'; }
};
}
fillSlotInputs(i);
});
var saveApiBtn = targetDoc.getElementById('saveApiBtn');
if (saveApiBtn) {
saveApiBtn.onclick = function() {
updateApiModeUI();
if (getApiMode() === 'ai') {
saveApiSlots([slotFromInputs(1), slotFromInputs(2), slotFromInputs(3)]);
[1, 2, 3].forEach(fillSlotInputs);
log('🔗 已保存 3 个 AI 接口', 'green');
} else {
var urls = saveApiUrls(apiUrlInput ? apiUrlInput.value : '');
if (apiUrlInput) { apiUrlInput.value = urls.join(','); }
log('🔗 已保存题库接口: ' + urls.join(' | '), 'green');
}
};
}
var testApiBtn = targetDoc.getElementById('testApiBtn');
if (testApiBtn) {
testApiBtn.onclick = function() {
var $r = $('#apiTestResult', targetDoc);
var render = function(results) {
if (!$r.length) { return; }
var html = results.map(function(r) {
var head = '接口' + r.index;
if (r.model) { head += '(' + r.model + ' / ' + (r.tier || 'high') + ')'; }
else if (r.url) { head += '(' + r.url + ')'; }
if (r.ok) { return '✅ ' + head + ' 可用' + (r.info ? ':' + r.info : '') + '
'; }
if (r.skipped) { return '➖ ' + head + ':未配置(跳过)
'; }
return '❌ ' + head + ':' + r.err + '
';
}).join('');
$r.html(html || '(无结果)');
};
if ($r.length) { $r.html('⏳ 依次测试接口 1 → 2 → 3 ...').css('color', '#666'); }
testApiConnection(function(partial) { render(partial); }).then(function(results) {
render(results);
var okCount = results.filter(function(r) { return r.ok; }).length;
log('🧪 接口测试完成:' + okCount + '/' + results.length + ' 可用', okCount ? 'green' : 'red');
}).catch(function(err) {
if ($r.length) { $r.html('❌ 接口测试失败: ' + err).css('color', 'red'); }
log('❌ 接口测试失败: ' + err, 'red');
});
};
}
var autoGuessCb = targetDoc.getElementById('setting_autoGuessEmpty');
if (autoGuessCb) {
autoGuessCb.onchange = function() {
GM_setValue('auto_guess_empty', this.checked ? true : false);
log('🎲 AI全失败自动排除+盲选: ' + (this.checked ? '开' : '关'), 'blue');
};
}
var codeReviewCb = targetDoc.getElementById('setting_codeReview');
if (codeReviewCb) {
codeReviewCb.onchange = function() {
GM_setValue('code_review', this.checked ? true : false);
log('🧩 程序题自动审查: ' + (this.checked ? '开' : '关'), 'blue');
};
}
var gqScanBtn = targetDoc.getElementById('gqScanBtn');
if (gqScanBtn) {
gqScanBtn.onclick = function() {
var $r = $('#gqResult', targetDoc);
var items = gqScan();
if ($r.length) { $r.html('已发现 ' + items.length + ' 道题(详见下方日志)').css('color', items.length ? '#2e7d32' : '#999'); }
};
}
var gqRunBtn = targetDoc.getElementById('gqRunBtn');
if (gqRunBtn) {
gqRunBtn.onclick = function() {
var $r = $('#gqResult', targetDoc);
if ($r.length) { $r.html('⏳ 正在作答…').css('color', '#666'); }
gqChainSetHops(0);
gqRun().then(function(n) {
if ($r.length) { $r.html('✅ 已作答 ' + n + ' 题').css('color', '#2e7d32'); }
}).catch(function(err) {
if ($r.length) { $r.html('❌ 出错: ' + err).css('color', '#c62828'); }
});
};
}
var gqAutoCb = targetDoc.getElementById('setting_genericAuto');
if (gqAutoCb) {
gqAutoCb.onchange = function() {
GM_setValue('generic_auto', this.checked ? true : false);
log('♻️ 通用自动模式: ' + (this.checked ? '开' : '关'), 'blue');
if (this.checked && !window.__gqAutoTimer) { startGqAuto(); }
};
}
var gqModeCb = targetDoc.getElementById('setting_genericMode');
if (gqModeCb) {
gqModeCb.onchange = function() {
GM_setValue('generic_mode', this.checked ? true : false);
log('🧩 通用模式: ' + (this.checked ? '开' : '关'), 'blue');
};
}
var gqNextCb = targetDoc.getElementById('setting_gqAutoNext');
if (gqNextCb) {
gqNextCb.onchange = function() {
GM_setValue('gq_auto_next', this.checked ? true : false);
log('➡️ 答完自动下一题: ' + (this.checked ? '开' : '关'), 'blue');
};
}
var gqSubmitCb = targetDoc.getElementById('setting_gqAutoSubmit');
if (gqSubmitCb) {
gqSubmitCb.onchange = function() {
GM_setValue('gq_auto_submit', this.checked ? true : false);
log('📤 自动提交(复查后才提交): ' + (this.checked ? '开' : '关'), this.checked ? 'red' : 'blue');
};
}
var answerIntervalInput = targetDoc.getElementById('answerIntervalInput');
if (answerIntervalInput) {
answerIntervalInput.addEventListener('change', function(e) {
var newTime = parseInt(e.target.value);
if (newTime >= 1000 && newTime <= 10000) {
updateConfig('answerInterval', newTime);
log('⚙️ 答题间隔已实时更新为: ' + newTime + 'ms (实际随机 ±20%)', 'blue');
} else {
e.target.value = CONFIG.answerInterval;
log('⚠️ 答题间隔需在 1000~10000ms 之间,已恢复原值', 'orange');
}
});
}
$('input[name="videoMode"]', targetDoc).off('change').on('change', function() {
var newMode = this.value;
var changed = CONFIG.videoMode !== newMode;
updateConfig('videoMode', newMode);
SettingsManager.saveVideoMode(newMode);
log('🎬 视频模式已切换为: ' + (newMode === 'simulate' ? '模拟上报' : '正常播放'), 'green');
if (changed && currentVideoInterval) {
log('🔄 当前视频任务将按新模式重跑', 'orange');
clearInterval(currentVideoInterval);
currentVideoInterval = null;
if (currentVideoQuizObserver) {
try { currentVideoQuizObserver.disconnect(); } catch(e) {}
currentVideoQuizObserver = null;
}
stopQuizPoll();
stopQuizObserverGuard();
isProcessing = false;
setTimeout(function() { startMission(); }, 1000);
}
});
var checkboxes = ['handleVideoQuiz', 'autoSubmit', 'forceSubmit', 'autoNextExam', 'insertAnswer', 'autoSearch'];
checkboxes.forEach(function(id) {
var $cb = $('#setting_' + id, targetDoc);
if (!$cb.length) return;
$cb.off('change').on('change', function() {
var checked = this.checked;
updateConfig(id, checked);
if (id === 'handleVideoQuiz') {
if (checked) {
try {
document.querySelectorAll('iframe').forEach(function(f) {
var d = f.contentDocument || (f.contentWindow && f.contentWindow.document);
if (d && d.body && d.querySelector('video')) {
observeVideoQuiz(d);
startQuizPoll(d);
startQuizObserverGuard();
}
});
log('👀 视频弹题监听已开启', 'green');
} catch(e) {}
} else {
if (currentVideoQuizObserver) {
try { currentVideoQuizObserver.disconnect(); } catch(e) {}
currentVideoQuizObserver = null;
}
stopQuizPoll();
stopQuizObserverGuard();
log('👀 视频弹题监听已关闭', 'blue');
}
}
if (id === 'autoSubmit' && checked && CONFIG.forceSubmit) {
CONFIG.forceSubmit = false;
SettingsManager.set('forceSubmit', false);
$('#setting_forceSubmit', targetDoc).prop('checked', false);
log('⚙️ 自动提交与强制提交互斥,已关闭强制提交', 'blue');
}
if (id === 'forceSubmit' && checked && CONFIG.autoSubmit) {
CONFIG.autoSubmit = false;
SettingsManager.set('autoSubmit', false);
$('#setting_autoSubmit', targetDoc).prop('checked', false);
log('⚙️ 强制提交与自动提交互斥,已关闭自动提交', 'blue');
}
if (id === 'autoNextExam') {
log('⏭️ 考试自动跳转: ' + (checked ? '开' : '关'), 'blue');
}
if (id === 'insertAnswer') {
log('📖 答案插入题目: ' + (checked ? '开' : '关'), 'blue');
}
});
});
}
function showBox(force) {
if (!CONFIG.showBox && !force) return;
try {
var existingDoc = panelDoc();
if (existingDoc.querySelector('#ne-21box')) {
flushLogs();
if (pendingAnswerRequest) renderPendingQuestionUI();
return;
}
} catch(e) {}
setTimeout(function() {
try {
var targetDoc = panelDoc();
if (!targetDoc.body) { return; }
if (targetDoc.querySelector('#ne-21box')) { flushLogs(); return; }
var boxHtml = getSettingsPanelHTML();
$(targetDoc.body).append(boxHtml);
bindSettingUI(targetDoc);
$('#ne-21notice', targetDoc).html('💡 v1.2.1 | 学习通刷课+做题;其他网站也能做题(面板「通用做题」)| 先在面板填接口/密钥 | F9隐藏/显示
');
if (pendingAnswerRequest) renderPendingQuestionUI();
flushLogs();
showPikaqiu();
} catch(e) { console.error('[学习通助手] 显示悬浮窗失败:', e); }
}, 100);
}
// SPA / 重渲染守护:面板被页面刷掉后自动补回
function startPanelWatchdog() {
if (window.__panelWatchdog) { return; }
window.__panelWatchdog = setInterval(function() {
if (isBoxHidden) { return; }
try {
var doc = panelDoc();
if (!doc || !doc.body) { return; }
if (!doc.querySelector('#ne-21box')) { showBox(); }
if (!doc.getElementById('ne-21fac')) { pikaqiuAdded = false; showPikaqiu(); }
} catch(e) {}
}, 3000);
}
// ==================== 通用做题引擎(任意网站) ====================
function gqIsChaoxing() { return /(^|\.)chaoxing\.com$/i.test(location.hostname); }
function getGenericMode() { return GM_getValue('generic_mode', true) !== false; }
function getGenericAuto() { return GM_getValue('generic_auto', false) === true; }
function gqCleanText(s) { return String(s || '').replace(/\s+/g, ' ').trim(); }
var gqRowKeys = (typeof WeakMap === 'function') ? new WeakMap() : null;
var gqRowSeq = 0;
function gqRowKey(row) {
if (!row) { return 'row:anon'; }
if (!gqRowKeys) { return 'row:' + (Array.prototype.indexOf.call(row.ownerDocument.querySelectorAll('*'), row)); }
if (!gqRowKeys.has(row)) { gqRowKeys.set(row, 'row:' + (++gqRowSeq)); }
return gqRowKeys.get(row);
}
function gqVisible(doc, sel) {
var out = [];
var list = [];
try { list = doc.querySelectorAll(sel); } catch(e) { return out; }
for (var i = 0; i < list.length; i++) {
var el = list[i];
if (el.disabled || el.type === 'hidden') { continue; }
var r = el.getBoundingClientRect();
if (r.width > 0 || r.height > 0) { out.push(el); }
}
return out;
}
function gqLabelText(input) {
var doc = input.ownerDocument;
var lab = null;
if (input.id) {
try { lab = doc.querySelector('label[for="' + input.id.replace(/["\\]/g, '\\$&') + '"]'); } catch(e) {}
}
if (!lab) { try { lab = input.closest('label'); } catch(e) {} }
if (!lab && input.parentElement) { lab = input.parentElement; }
var t = lab ? gqCleanText(lab.innerText || lab.textContent || '') : '';
t = t.replace(/^[A-HA-H][.、,,))::]\s*/, '').replace(/^[①-⑩]\s*/, '');
t = t.replace(/^[((]\s*[A-HA-H]\s*[))]\s*/, '');
return gqCleanText(t);
}
function gqCommonAncestor(nodes) {
if (!nodes || !nodes.length) { return null; }
var anc = nodes[0];
for (var i = 1; i < nodes.length; i++) {
while (anc && !anc.contains(nodes[i])) { anc = anc.parentElement; }
if (!anc) { return null; }
}
return anc;
}
function gqQuestionText(container, optionTexts) {
if (!container) { return ''; }
var clone = container.cloneNode(true);
var junk = clone.querySelectorAll('input, textarea, select, button, script, style, svg, img');
for (var i = 0; i < junk.length; i++) { junk[i].remove(); }
var text = gqCleanText(clone.textContent || '');
(optionTexts || []).forEach(function(ot) {
if (!ot) { return; }
var idx = text.indexOf(ot);
if (idx !== -1) { text = text.slice(0, idx) + ' ' + text.slice(idx + ot.length); }
});
// 去掉残留的选项字母标记(如 A. B. C. D.)
text = text.replace(/(^|[\s((])[A-HA-H]\s*[.、,,))::]/g, ' ');
return gqCleanText(text).replace(/\s{2,}/g, ' ');
}
// 选项容器常常与题干是兄弟节点;向上找同时含题干和本组选项、且不混入其他题的容器
function gqWidenContainer(container, nodes) {
var cur = container;
for (var up = 0; up < 4 && cur && cur.parentElement; up++) {
var parent = cur.parentElement;
if (!parent || parent === document.body || parent === document.documentElement) { break; }
var others = 0;
var inputs = [];
try { inputs = parent.querySelectorAll('input[type="radio"], input[type="checkbox"]'); } catch(e) {}
for (var i = 0; i < inputs.length; i++) {
if (nodes.indexOf(inputs[i]) === -1) { others++; }
}
if (others > 0) { break; }
if (gqCleanText(parent.textContent || '').length > gqCleanText(cur.textContent || '').length) { cur = parent; }
else { break; }
}
return cur;
}
function gqCollectInDoc(doc, items) {
var inputs = gqVisible(doc, 'input[type="radio"], input[type="checkbox"]');
var groups = [];
var map = {};
inputs.forEach(function(inp) {
var key = inp.name ? ('name:' + inp.name) : '';
if (!key) {
var row = inp.parentElement, depth = 0;
while (row && depth < 4) {
var same = 0;
try { same = row.querySelectorAll('input[type="' + inp.type + '"]').length; } catch(e) {}
if (same >= 2) { break; }
row = row.parentElement; depth++;
}
key = gqRowKey(row);
}
if (!map[key]) { map[key] = { type: inp.type === 'radio' ? 0 : 1, inputs: [] }; groups.push(map[key]); }
map[key].inputs.push(inp);
});
var choiceContainers = [];
groups.forEach(function(g) {
var nodes = g.inputs;
if (nodes.length < 2) { return; }
var container = gqCommonAncestor(nodes);
if (!container) { return; }
container = gqWidenContainer(container, nodes);
var options = nodes.map(gqLabelText);
if (options.join('').length < 2) { return; }
var question = gqQuestionText(container, options);
if (!question || question.length < 4) { return; }
choiceContainers.push(container);
items.push({ kind: 'choice', type: g.type, container: container, inputs: nodes, options: options, question: question });
});
var texts = gqVisible(doc, 'textarea, input[type="text"], input[type="search"], input:not([type])');
var buckets = [];
texts.forEach(function(inp) {
var inChoice = false;
for (var i = 0; i < choiceContainers.length; i++) {
if (choiceContainers[i].contains(inp)) { inChoice = true; break; }
}
if (inChoice) { return; }
var container = gqTextContainer(inp);
if (!container) { return; }
var b = null;
for (var j = 0; j < buckets.length; j++) { if (buckets[j].container === container) { b = buckets[j]; break; } }
if (!b) { b = { container: container, inputs: [] }; buckets.push(b); }
b.inputs.push(inp);
});
buckets.forEach(function(b) {
var question = gqQuestionText(b.container, []);
if (!question || question.length < 4) { return; }
var t = getQuestionTypeFromText(question);
if (t === 0 || t === 1 || t === undefined) { t = 2; }
items.push({ kind: 'blank', type: t, container: b.container, inputs: b.inputs, options: [], question: question });
});
}
function gqTextContainer(inp) {
try {
var hint = inp.closest('[class*="question"],[class*="problem"],[class*="item"],[class*="ques"],[class*="exam"],[class*="quiz"],[class*="subject"],[class*="stem"],[class*="ti-"]');
if (hint) { return hint; }
var lab = inp.closest('label');
if (lab) { return lab; }
} catch(e) {}
var node = inp.parentElement, depth = 0;
while (node && depth < 8) {
if (gqCleanText(node.textContent || '').length >= 6) { return node; }
node = node.parentElement; depth++;
}
return inp.parentElement;
}
function gqCollectAll() {
var items = [];
gqCollectInDoc(document, items);
var frames = document.querySelectorAll('iframe');
for (var i = 0; i < frames.length; i++) {
try {
var d = frames[i].contentDocument;
if (d) { gqCollectInDoc(d, items); }
} catch(e) {}
}
return items;
}
function gqIsAnswered(item) {
if (item.kind === 'choice') {
return item.inputs.some(function(i) { return i.checked; });
}
return item.inputs.some(function(i) { return String(i.value || '').trim() !== ''; });
}
function gqClickInput(inp) {
try { inp.scrollIntoView({ block: 'center' }); } catch(e) {}
try {
inp.click();
if (!inp.checked) {
inp.checked = true;
inp.dispatchEvent(new Event('click', { bubbles: true }));
inp.dispatchEvent(new Event('change', { bubbles: true }));
}
} catch(e) {
inp.checked = true;
try { inp.dispatchEvent(new Event('change', { bubbles: true })); } catch(e2) {}
}
}
function gqSetValue(inp, value) {
var proto = (inp.tagName === 'TEXTAREA') ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
try {
var setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
setter.call(inp, value);
} catch(e) { inp.value = value; }
['input', 'change', 'blur'].forEach(function(evt) {
try { inp.dispatchEvent(new Event(evt, { bubbles: true })); } catch(e) {}
});
}
function gqApplyChoice(item, answer) {
var letters = String(answer || '').toUpperCase().replace(/[\s,,、;;]+/g, '');
var idxs = [];
if (/^[A-H]+$/.test(letters)) {
for (var i = 0; i < letters.length; i++) { idxs.push(letters.charCodeAt(i) - 65); }
} else {
idxs = matchMultiChoiceIndices(item.options, answer);
}
idxs = idxs.filter(function(n) { return n >= 0 && n < item.inputs.length; });
if (item.type === 0 && idxs.length > 1) { idxs = idxs.slice(0, 1); }
idxs.forEach(function(n) { gqClickInput(item.inputs[n]); });
return idxs;
}
function gqApplyBlank(item, answer) {
var parts = splitAnswer(answer);
item.inputs.forEach(function(inp, i) {
var v = parts[i] != null ? parts[i] : (parts.length === 1 ? parts[0] : '');
gqSetValue(inp, v);
});
}
// 填完后校验是否真的生效,没生效再试一次;返回是否成功
function gqApplyAndVerify(item, answer) {
if (item.kind === 'choice') { gqApplyChoice(item, answer); }
else { gqApplyBlank(item, answer); }
if (gqIsAnswered(item)) { return true; }
if (item.kind === 'choice') { gqApplyChoice(item, answer); }
else { gqApplyBlank(item, answer); }
return gqIsAnswered(item);
}
// 逐题作答(已答过的跳过,不做时间间隔)
function gqAnswerList(items) {
var idx = 0, done = 0, failed = 0, skipped = 0;
function step() {
if (idx >= items.length) {
return Promise.resolve({ done: done, failed: failed, skipped: skipped });
}
var item = items[idx++];
var no = idx;
if (gqIsAnswered(item)) {
skipped++;
log('⏭️ 第' + no + '题已答过,跳过', 'blue');
return step();
}
return getAnswer(item.type, item.question, item.options).then(function(ans) {
if (gqApplyAndVerify(item, ans)) {
done++;
log('✅ 第' + no + '题:' + String(ans).slice(0, 60), 'green');
} else {
failed++;
log('⚠️ 第' + no + '题填写未生效:' + String(ans).slice(0, 40), 'orange');
}
}, function(err) {
failed++;
log('⚠️ 第' + no + '题未作答:' + err, 'orange');
}).then(step);
}
return step();
}
function gqRun() {
if (window.__gqRunning) { return Promise.resolve(0); }
window.__gqRunning = true;
var items = gqCollectAll();
if (!items.length) {
log('🔍 通用模式:本页未发现可作答的题目', 'orange');
window.__gqRunning = false;
return Promise.resolve(0);
}
log('🧩 通用模式:发现 ' + items.length + ' 道题,开始作答…', 'blue');
return gqAnswerList(items).then(function(r) {
log('✅ 通用模式完成:作答 ' + r.done + ' 题' +
(r.skipped ? ',已答过跳过 ' + r.skipped + ' 题' : '') +
(r.failed ? ',填写未生效 ' + r.failed + ' 题' : ''), r.failed ? 'orange' : 'green');
window.__gqRunning = false;
// 答完立即进入下一题(含“本页题目都已答过”的情况)
setTimeout(function() { gqTryNextQuestion(); }, 30);
return r.done;
});
}
function startGqAuto() {
if (window.__gqAutoTimer) { return; }
window.__gqAutoTimer = setInterval(function() {
if (!getGenericAuto() || window.__gqRunning) { return; }
if (typeof isProcessing !== 'undefined' && isProcessing) { return; }
if (typeof pendingAnswerRequest !== 'undefined' && pendingAnswerRequest) { return; }
var items = gqCollectAll();
var todo = items.filter(function(it) { return !gqIsAnswered(it); });
if (todo.length) { gqRun(); }
}, 15000);
log('♻️ 通用自动模式已启动(每15秒扫描一次)', 'blue');
}
function getGqAutoNext() { return GM_getValue('gq_auto_next', true) !== false; }
function gqChainTouch() { GM_setValue('gq_chain', Date.now()); }
function gqChainClear() { GM_setValue('gq_chain', 0); GM_setValue('gq_chain_hops', 0); }
function gqChainHops() { return parseInt(GM_getValue('gq_chain_hops', 0), 10) || 0; }
function gqChainSetHops(n) { GM_setValue('gq_chain_hops', n); }
function gqChainFresh() {
var t = GM_getValue('gq_chain', 0);
return !!t && (Date.now() - t) < 120000;
}
function gqSignature() {
return gqCollectAll().map(function(it) { return it.question; }).join('||').slice(0, 400);
}
function gqBtnText(el) {
if (!el) { return ''; }
var t = el.value || el.innerText || el.textContent || el.getAttribute('aria-label') || el.title || '';
return String(t).replace(/\s+/g, ' ').trim().slice(0, 20);
}
function gqFindNextButton() {
var docs = [document];
var frames = document.querySelectorAll('iframe');
for (var i = 0; i < frames.length; i++) {
try { var d = frames[i].contentDocument; if (d) { docs.push(d); } } catch(e) {}
}
var NEXT = /(下一题|下一道|下一个|下一步|下题|next)/i;
var STOP = /(提交|交卷|完成|结束|保存|submit|finish|上一题|上一步|返回|previous|back|重做)/i;
for (var k = 0; k < docs.length; k++) {
var doc = docs[k];
var cands = [];
try {
cands = doc.querySelectorAll('button, a, input[type="button"], input[type="submit"], [role="button"], [class*="next"], [id*="next"]');
} catch(e) { continue; }
for (var j = 0; j < cands.length; j++) {
var el = cands[j];
try { if (el.closest && el.closest('#ne-21box')) { continue; } } catch(e) {}
if (el.disabled) { continue; }
var r = el.getBoundingClientRect();
if (r.width <= 0 && r.height <= 0) { continue; }
var text = gqBtnText(el);
if (!text || text.length > 16) { continue; }
if (STOP.test(text)) { continue; }
if (NEXT.test(text)) { return el; }
}
}
return null;
}
function gqScanButtons(re, notRe, hintRe, exclude) {
var docs = [document];
var frames = document.querySelectorAll('iframe');
for (var i = 0; i < frames.length; i++) {
try { var d = frames[i].contentDocument; if (d) { docs.push(d); } } catch(e) {}
}
for (var k = 0; k < docs.length; k++) {
var doc = docs[k];
var cands = [];
try {
cands = doc.querySelectorAll('button, a, input[type="button"], input[type="submit"], [role="button"], [class*="submit"], [id*="submit"], [class*="next"], [id*="next"], [class*="prev"], [id*="prev"]');
} catch(e) { continue; }
for (var j = 0; j < cands.length; j++) {
var el = cands[j];
try { if (el.closest && el.closest('#ne-21box')) { continue; } } catch(e) {}
if (exclude && exclude.indexOf(el) !== -1) { continue; }
if (el.disabled) { continue; }
var r = el.getBoundingClientRect();
if (r.width <= 0 && r.height <= 0) { continue; }
var text = gqBtnText(el);
if (!text || text.length > 16) { continue; }
if (notRe && notRe.test(text)) { continue; }
if (re.test(text) || (hintRe && hintRe.test(text))) { return el; }
}
}
return null;
}
function gqFindPrevButton() {
return gqScanButtons(/(上一题|上一道|上一步|前一步|prev)/i, null, null);
}
function gqFindSubmitButton() {
var nextBtn = gqFindNextButton();
var prevBtn = gqFindPrevButton();
var exclude = [nextBtn, prevBtn].filter(Boolean);
// 先找明确的提交按钮
var strong = gqScanButtons(
/(提交|交卷|submit|上传答案|提交答案|试卷)/i,
/(上一题|下一题|下一道|上一步|返回|重做|重置|取消|清空|保存)/i,
null, exclude
);
if (strong) { return strong; }
// 其次才接受「完成 / 结束答题」
return gqScanButtons(
/(完成|结束答题|交卷|提交)/i,
/(上一题|下一题|下一道|上一步|返回|重做|重置|取消|清空)/i,
null, exclude
);
}
// 等页面内容变化(SPA 翻页),变化了 resolve(true),超时 resolve(false)
function gqWaitChange(sig, timeoutMs) {
return new Promise(function(resolve) {
var deadline = Date.now() + (timeoutMs || 6000);
(function poll() {
if (gqSignature() !== sig) { resolve(true); return; }
if (Date.now() > deadline) { resolve(false); return; }
setTimeout(poll, 250);
})();
});
}
function getGqAutoSubmit() { return GM_getValue('gq_auto_submit', false) === true; }
// 自动提交:从头到尾复查每一题,确认全部作答才提交
async function gqVerifyAndSubmit() {
if (window.__gqSubmitting) { return; }
window.__gqSubmitting = true;
try {
log('🔎 自动提交:开始从头到尾复查…', 'blue');
// 1) 先退回第一题
var backSteps = 0;
while (backSteps < 60) {
var prev = gqFindPrevButton();
if (!prev) { break; }
var s0 = gqSignature();
try { prev.click(); } catch(e) { break; }
backSteps++;
var movedBack = await gqWaitChange(s0, 6000);
if (!movedBack) { break; }
}
if (backSteps) { log('↩️ 已回退 ' + backSteps + ' 次,回到第 1 题开始复查', 'blue'); }
// 2) 逐页向后:检查 + 补答
var total = 0, unanswered = 0, failedTotal = 0, page = 0;
while (page < 80) {
var items = gqCollectAll();
var r = await gqAnswerList(items);
total += items.length;
failedTotal += r.failed;
var remain = gqCollectAll().filter(function(it) { return !gqIsAnswered(it); });
unanswered += remain.length;
var next = gqFindNextButton();
if (!next) { break; }
var s1 = gqSignature();
try { next.click(); } catch(e) { break; }
page++;
var movedOn = await gqWaitChange(s1, 8000);
if (!movedOn) { break; }
}
if (total === 0) {
log('⚠️ 未检测到任何题目,取消自动提交', 'orange');
return;
}
log('📋 复查结果:共 ' + total + ' 题,未答 ' + unanswered + ' 题' +
(failedTotal ? ',填写失败 ' + failedTotal + ' 题' : ''), unanswered ? 'orange' : 'green');
if (unanswered > 0) {
log('⛔ 仍有题目未作答,已取消自动提交,请手动处理', 'red');
return;
}
// 3) 确认全部答完,才提交
var submitBtn = gqFindSubmitButton();
if (!submitBtn) {
log('⚠️ 未找到「提交」按钮,请手动提交', 'orange');
return;
}
await new Promise(function(r) { setTimeout(r, 400); });
log('✅ 全部 ' + total + ' 题均已作答,点击「' + gqBtnText(submitBtn) + '」提交', 'green');
gqChainClear();
try { submitBtn.click(); } catch(e) { log('⚠️ 提交点击失败: ' + e, 'red'); }
} finally {
window.__gqSubmitting = false;
}
}
// 作答完成后尝试进入下一题;返回 true 表示已触发跳转
function gqTryNextQuestion() {
if (!getGqAutoNext()) { gqChainClear(); return false; }
var hops = gqChainHops();
if (hops >= 80) {
log('⚠️ 自动下一题已达上限(80),停止,避免死循环', 'orange');
gqChainClear();
if (getGqAutoSubmit()) { gqVerifyAndSubmit(); }
return false;
}
var btn = gqFindNextButton();
if (!btn) {
log('🏁 未找到「下一题」按钮,本次自动做题结束', 'blue');
gqChainClear();
if (getGqAutoSubmit()) { gqVerifyAndSubmit(); }
return false;
}
gqChainSetHops(hops + 1);
var label = gqBtnText(btn);
var sig = gqSignature();
if (window.__gqLastNextSig === sig) {
log('⚠️ 本页已点过「下一题」且内容未变,停止', 'orange');
gqChainClear();
return false;
}
window.__gqLastNextSig = sig;
log('➡️ 点击「' + label + '」进入下一题(第 ' + (hops + 1) + ' 次跳转)', 'blue');
gqChainTouch();
try { btn.click(); } catch(e) {}
// 页面若不刷新(SPA):轮询等待内容变化,一变就立刻继续作答(无固定间隔)
gqWaitForChange(sig, Date.now() + 8000);
return true;
}
function gqWaitForChange(sig, deadline) {
setTimeout(function() {
if (window.__gqRunning) { return; }
if (gqSignature() !== sig) { gqRun(); return; }
if (Date.now() < deadline) { gqWaitForChange(sig, deadline); }
}, 250);
}
function gqScan() {
var items = gqCollectAll();
var choice = items.filter(function(i) { return i.kind === 'choice'; }).length;
var blank = items.length - choice;
log('🔍 扫描完成:共 ' + items.length + ' 道题(选择 ' + choice + ' / 填空简答 ' + blank + ')', items.length ? 'green' : 'orange');
items.slice(0, 8).forEach(function(it, n) {
log(' ' + (n + 1) + '. [' + typeNameById(it.type) + '] ' + it.question.slice(0, 40), 'blue');
});
return items;
}
// ==================== 初始化入口 ====================
$(function() {
console.log('[学习通助手] v1.2.1 已在 ' + location.hostname + ' 运行;本页判定为' + (gqIsChaoxing() ? '学习通' : '其他网站(通用模式)'));
CONFIG.videoMode = GM_getValue('videoMode', CONFIG.videoMode);
CONFIG.videoRate = GM_getValue('videoRate', CONFIG.videoRate);
CONFIG.showProgressBar = GM_getValue('showProgressBar', CONFIG.showProgressBar);
var settingsMap = { 'autoSubmit': 'autoSubmit', 'forceSubmit': 'forceSubmit', 'autoNextExam': 'autoNextExam', 'insertAnswer': 'insertAnswer', 'answerInterval': 'answerInterval', 'handleVideoQuiz': 'handleVideoQuiz' };
for (var key in settingsMap) {
var val = GM_getValue('setting_' + key, null);
if (val === null) val = localStorage.getItem('setting_' + key);
if (val !== null && val !== undefined) {
if (key === 'answerInterval') { CONFIG[settingsMap[key]] = parseInt(val); }
else { CONFIG[settingsMap[key]] = (val === 'true' || val === true); }
}
}
$('.navshow').find('a:contains(体验新版)')[0] && $('.navshow').find('a:contains(体验新版)')[0].click();
if (CONFIG.decryptFont) {
setTimeout(function() { decryptFont(); }, 1000);
setTimeout(function() { if ($('.font-cxsecret').length > 0) decryptFont(); }, 8000);
}
if (LOCATION.pathname == '/login' && CONFIG.autoLogin) {
showBox();
waitForElement('#phone').then(function() {
$('#phone').val(CONFIG.loginPhone);
$('#pwd').val(CONFIG.loginPassword);
$('#loginBtn').click();
});
} else if (LOCATION.pathname.includes('/mycourse/studentstudy')) {
showBox();
log('✅ 初始化完毕!', 'green');
} else if (LOCATION.pathname.includes('/knowledge/cards')) {
showBox();
var params = getTaskParams();
if (!params || params == '$mArg') {
log('⚠️ 无任务点可处理', 'red');
if (!hasTriggeredNoTaskJump) {
hasTriggeredNoTaskJump = true;
log('🔄 检测到无任务点,尝试跳转到下一章节...', 'blue');
setTimeout(function() {
var nextBtn = top.document.querySelector('#mainid > .prev_next.next:not(.disabled)') || top.document.querySelector('#prevNextFocusNext:not(.disabled)') || top.document.querySelector('.prev_next.next:not(.disabled)') || $('.prev_next.next:not(.disabled)')[0];
if (nextBtn && !nextBtn.disabled && !nextBtn.classList.contains('disabled')) { log('✅ 找到下一节按钮,即将跳转', 'green'); nextBtn.click(); }
else { log('📚 已是最后一章,无更多章节', 'green'); }
}, 2000);
}
return;
}
try {
var allTasks = $.parseJSON(params)['attachments'];
if (!allTasks || allTasks.length <= 0) {
log('⚠️ 无任务点可处理', 'red');
if (!hasTriggeredNoTaskJump) {
hasTriggeredNoTaskJump = true;
setTimeout(function() {
var nextBtn = top.document.querySelector('#mainid > .prev_next.next:not(.disabled)') || top.document.querySelector('#prevNextFocusNext:not(.disabled)') || top.document.querySelector('.prev_next.next:not(.disabled)') || $('.prev_next.next:not(.disabled)')[0];
if (nextBtn && !nextBtn.disabled && !nextBtn.classList.contains('disabled')) { nextBtn.click(); }
}, 2000);
}
return;
}
} catch(e) { log('⚠️ 解析任务参数失败', 'red'); return; }
waitForElement('.wrap .ans-cc .ans-attach-ct').then(function() {
if (top.checkJob) top.checkJob = function() { return false; };
var allTasks = $.parseJSON(params)['attachments'];
defaults = $.parseJSON(params)['defaults'];
domList = [];
var pendingTasks = [];
for (var i = 0; i < allTasks.length; i++) {
var task = allTasks[i];
if (!isTaskCompleted(task)) { pendingTasks.push(task); }
else { var taskName = task.property ? (task.property.name || task.property.title || '未知') : '未知'; log('✅ 任务点 ' + taskName + ' 已完成,跳过', 'green'); }
}
totalMissionCount = allTasks.length;
pendingMissionCount = pendingTasks.length;
completedMissionCount = 0;
if (pendingMissionCount === 0) { log('✅ 所有任务点已完成', 'green'); setTimeout(function() { goToNext(); }, 2000); return; }
log('📋 发现 ' + totalMissionCount + ' 个任务点,其中 ' + pendingMissionCount + ' 个待处理', 'green');
taskList = [];
var newDomList = [];
$('.wrap .ans-cc .ans-attach-ct').each(function(i, t) {
if (i < allTasks.length && !isTaskCompleted(allTasks[i])) { taskList.push(allTasks[i]); newDomList.push($(t).find('iframe')); }
});
domList = newDomList;
if (taskList.length > 0) {
log('🚀 开始处理 ' + taskList.length + ' 个待完成任务点', 'green');
startMission();
} else { log('✅ 所有任务点已完成', 'green'); setTimeout(function() { goToNext(); }, 2000); }
}).catch(function() {
log('❌ 等待元素超时', 'red');
if (!hasTriggeredNoTaskJump) { hasTriggeredNoTaskJump = true; setTimeout(function() { goToNext(); }, 2000); }
});
} else if (LOCATION.pathname.includes('/exam/test/reVersionTestStartNew')) {
showBox();
waitForElement('.mark_table .whiteDiv').then(function() { processExam(); });
} else if (LOCATION.pathname.includes('/mooc2/work/dowork')) {
showBox();
waitForElement('.mark_table form').then(function() { processHomework(); });
} else if (LOCATION.pathname.includes('/work/phone/doHomeWork')) {
var oldAlert = UNSAFE_WIN.alert;
UNSAFE_WIN.alert = function(msg) { if (msg == '保存成功') return; return oldAlert(msg); };
var oldConfirm = UNSAFE_WIN.confirm;
UNSAFE_WIN.confirm = function(msg) { if (msg.includes('确认提交') || msg.includes('未做完')) return true; return oldConfirm(msg); };
} else if (!gqIsChaoxing()) {
// 通用模式:任意网站
if (getGenericMode()) {
showBox(true);
startPanelWatchdog();
log('🧩 通用模式已就绪:点面板里的「扫描题目」或「自动作答」', 'green');
if (getGenericAuto()) { setTimeout(startGqAuto, 2000); }
if (gqChainFresh()) {
log('🔗 检测到上一题的自动做题链,继续作答…', 'blue');
setTimeout(function() { gqRun(); }, 1800);
}
}
}
});